Archive experiment updates 2026-10-08 (16/119)
Browse filesFile-level snapshot; code revision eb6fa2872daec8b3cea3832ee9dfec9e63cf2176. Weights and Docker images remain local.
This view is limited to 50 files because it contains too many changes. See raw diff
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_feature_extraction_pop2piano.py +291 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_modeling_pop2piano.py +782 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_processor_pop2piano.py +264 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_tokenization_pop2piano.py +415 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_modeling_prophetnet.py +1332 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_tokenization_prophetnet.py +205 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_image_processing_pvt.py +106 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_modeling_pvt.py +325 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/test_modeling_qdqbert.py +575 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_rag.py +1189 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_tf_rag.py +1080 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_retrieval_rag.py +320 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_tokenization_rag.py +168 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_modeling_realm.py +554 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_retrieval_realm.py +187 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_tokenization_realm.py +321 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_modeling_reformer.py +1305 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_tokenization_reformer.py +370 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_flax_regnet.py +237 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_regnet.py +263 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_tf_regnet.py +294 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_rembert.py +512 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_tf_rembert.py +728 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_tokenization_rembert.py +243 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_flax_resnet.py +228 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_resnet.py +326 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_tf_resnet.py +256 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_flax_roberta.py +159 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_roberta.py +581 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_tf_roberta.py +702 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_tokenization_roberta.py +303 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_flax_roberta_prelayernorm.py +192 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py +565 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_tf_roberta_prelayernorm.py +693 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_modeling_roc_bert.py +745 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_tokenization_roc_bert.py +320 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/__init__.py +0 -0
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_flax_roformer.py +163 -0
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_feature_extraction_pop2piano.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from datasets import load_dataset
|
| 22 |
+
|
| 23 |
+
from transformers.testing_utils import (
|
| 24 |
+
check_json_file_has_correct_format,
|
| 25 |
+
require_essentia,
|
| 26 |
+
require_librosa,
|
| 27 |
+
require_scipy,
|
| 28 |
+
require_tf,
|
| 29 |
+
require_torch,
|
| 30 |
+
)
|
| 31 |
+
from transformers.utils.import_utils import (
|
| 32 |
+
is_essentia_available,
|
| 33 |
+
is_librosa_available,
|
| 34 |
+
is_scipy_available,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
requirements_available = (
|
| 42 |
+
is_torch_available() and is_essentia_available() and is_scipy_available() and is_librosa_available()
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if requirements_available:
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
from transformers import Pop2PianoFeatureExtractor
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Pop2PianoFeatureExtractionTester(unittest.TestCase):
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
parent,
|
| 55 |
+
n_bars=2,
|
| 56 |
+
sample_rate=22050,
|
| 57 |
+
use_mel=True,
|
| 58 |
+
padding_value=0,
|
| 59 |
+
vocab_size_special=4,
|
| 60 |
+
vocab_size_note=128,
|
| 61 |
+
vocab_size_velocity=2,
|
| 62 |
+
vocab_size_time=100,
|
| 63 |
+
):
|
| 64 |
+
self.parent = parent
|
| 65 |
+
self.n_bars = n_bars
|
| 66 |
+
self.sample_rate = sample_rate
|
| 67 |
+
self.use_mel = use_mel
|
| 68 |
+
self.padding_value = padding_value
|
| 69 |
+
self.vocab_size_special = vocab_size_special
|
| 70 |
+
self.vocab_size_note = vocab_size_note
|
| 71 |
+
self.vocab_size_velocity = vocab_size_velocity
|
| 72 |
+
self.vocab_size_time = vocab_size_time
|
| 73 |
+
|
| 74 |
+
def prepare_feat_extract_dict(self):
|
| 75 |
+
return {
|
| 76 |
+
"n_bars": self.n_bars,
|
| 77 |
+
"sample_rate": self.sample_rate,
|
| 78 |
+
"use_mel": self.use_mel,
|
| 79 |
+
"padding_value": self.padding_value,
|
| 80 |
+
"vocab_size_special": self.vocab_size_special,
|
| 81 |
+
"vocab_size_note": self.vocab_size_note,
|
| 82 |
+
"vocab_size_velocity": self.vocab_size_velocity,
|
| 83 |
+
"vocab_size_time": self.vocab_size_time,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@require_torch
|
| 88 |
+
@require_essentia
|
| 89 |
+
@require_librosa
|
| 90 |
+
@require_scipy
|
| 91 |
+
class Pop2PianoFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):
|
| 92 |
+
feature_extraction_class = Pop2PianoFeatureExtractor if requirements_available else None
|
| 93 |
+
|
| 94 |
+
def setUp(self):
|
| 95 |
+
self.feat_extract_tester = Pop2PianoFeatureExtractionTester(self)
|
| 96 |
+
|
| 97 |
+
def test_feat_extract_from_and_save_pretrained(self):
|
| 98 |
+
feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)
|
| 99 |
+
|
| 100 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 101 |
+
saved_file = feat_extract_first.save_pretrained(tmpdirname)[0]
|
| 102 |
+
check_json_file_has_correct_format(saved_file)
|
| 103 |
+
feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname)
|
| 104 |
+
|
| 105 |
+
dict_first = feat_extract_first.to_dict()
|
| 106 |
+
dict_second = feat_extract_second.to_dict()
|
| 107 |
+
mel_1 = feat_extract_first.use_mel
|
| 108 |
+
mel_2 = feat_extract_second.use_mel
|
| 109 |
+
self.assertTrue(np.allclose(mel_1, mel_2))
|
| 110 |
+
self.assertEqual(dict_first, dict_second)
|
| 111 |
+
|
| 112 |
+
def test_feat_extract_to_json_file(self):
|
| 113 |
+
feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)
|
| 114 |
+
|
| 115 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 116 |
+
json_file_path = os.path.join(tmpdirname, "feat_extract.json")
|
| 117 |
+
feat_extract_first.to_json_file(json_file_path)
|
| 118 |
+
feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path)
|
| 119 |
+
|
| 120 |
+
dict_first = feat_extract_first.to_dict()
|
| 121 |
+
dict_second = feat_extract_second.to_dict()
|
| 122 |
+
mel_1 = feat_extract_first.use_mel
|
| 123 |
+
mel_2 = feat_extract_second.use_mel
|
| 124 |
+
self.assertTrue(np.allclose(mel_1, mel_2))
|
| 125 |
+
self.assertEqual(dict_first, dict_second)
|
| 126 |
+
|
| 127 |
+
def test_call(self):
|
| 128 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 129 |
+
speech_input = np.zeros([1000000], dtype=np.float32)
|
| 130 |
+
|
| 131 |
+
input_features = feature_extractor(speech_input, sampling_rate=16_000, return_tensors="np")
|
| 132 |
+
self.assertTrue(input_features.input_features.ndim == 3)
|
| 133 |
+
self.assertEqual(input_features.input_features.shape[-1], 512)
|
| 134 |
+
|
| 135 |
+
self.assertTrue(input_features.beatsteps.ndim == 2)
|
| 136 |
+
self.assertTrue(input_features.extrapolated_beatstep.ndim == 2)
|
| 137 |
+
|
| 138 |
+
def test_integration(self):
|
| 139 |
+
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 140 |
+
speech_samples = ds.sort("id").select([0])["audio"]
|
| 141 |
+
input_speech = [x["array"] for x in speech_samples][0]
|
| 142 |
+
sampling_rate = [x["sampling_rate"] for x in speech_samples][0]
|
| 143 |
+
feaure_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano")
|
| 144 |
+
input_features = feaure_extractor(
|
| 145 |
+
input_speech, sampling_rate=sampling_rate, return_tensors="pt"
|
| 146 |
+
).input_features
|
| 147 |
+
|
| 148 |
+
EXPECTED_INPUT_FEATURES = torch.tensor(
|
| 149 |
+
[[-7.1493, -6.8701, -4.3214], [-5.9473, -5.7548, -3.8438], [-6.1324, -5.9018, -4.3778]]
|
| 150 |
+
)
|
| 151 |
+
self.assertTrue(torch.allclose(input_features[0, :3, :3], EXPECTED_INPUT_FEATURES, atol=1e-4))
|
| 152 |
+
|
| 153 |
+
def test_attention_mask(self):
|
| 154 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 155 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 156 |
+
speech_input2 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32)
|
| 157 |
+
input_features = feature_extractor(
|
| 158 |
+
[speech_input1, speech_input2],
|
| 159 |
+
sampling_rate=[44_100, 16_000],
|
| 160 |
+
return_tensors="np",
|
| 161 |
+
return_attention_mask=True,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
self.assertTrue(hasattr(input_features, "attention_mask"))
|
| 165 |
+
|
| 166 |
+
# check shapes
|
| 167 |
+
self.assertTrue(input_features["attention_mask"].ndim == 2)
|
| 168 |
+
self.assertEqual(input_features["attention_mask_beatsteps"].shape[0], 2)
|
| 169 |
+
self.assertEqual(input_features["attention_mask_extrapolated_beatstep"].shape[0], 2)
|
| 170 |
+
|
| 171 |
+
# check if they are any values except 0 and 1
|
| 172 |
+
self.assertTrue(np.max(input_features["attention_mask"]) == 1)
|
| 173 |
+
self.assertTrue(np.max(input_features["attention_mask_beatsteps"]) == 1)
|
| 174 |
+
self.assertTrue(np.max(input_features["attention_mask_extrapolated_beatstep"]) == 1)
|
| 175 |
+
|
| 176 |
+
self.assertTrue(np.min(input_features["attention_mask"]) == 0)
|
| 177 |
+
self.assertTrue(np.min(input_features["attention_mask_beatsteps"]) == 0)
|
| 178 |
+
self.assertTrue(np.min(input_features["attention_mask_extrapolated_beatstep"]) == 0)
|
| 179 |
+
|
| 180 |
+
def test_batch_feature(self):
|
| 181 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 182 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 183 |
+
speech_input2 = np.ones([2_000_000], dtype=np.float32)
|
| 184 |
+
speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32)
|
| 185 |
+
|
| 186 |
+
input_features = feature_extractor(
|
| 187 |
+
[speech_input1, speech_input2, speech_input3],
|
| 188 |
+
sampling_rate=[44_100, 16_000, 48_000],
|
| 189 |
+
return_attention_mask=True,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
self.assertEqual(len(input_features["input_features"].shape), 3)
|
| 193 |
+
# check shape
|
| 194 |
+
self.assertEqual(input_features["beatsteps"].shape[0], 3)
|
| 195 |
+
self.assertEqual(input_features["extrapolated_beatstep"].shape[0], 3)
|
| 196 |
+
|
| 197 |
+
def test_batch_feature_np(self):
|
| 198 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 199 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 200 |
+
speech_input2 = np.ones([2_000_000], dtype=np.float32)
|
| 201 |
+
speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32)
|
| 202 |
+
|
| 203 |
+
input_features = feature_extractor(
|
| 204 |
+
[speech_input1, speech_input2, speech_input3],
|
| 205 |
+
sampling_rate=[44_100, 16_000, 48_000],
|
| 206 |
+
return_tensors="np",
|
| 207 |
+
return_attention_mask=True,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# check np array or not
|
| 211 |
+
self.assertEqual(type(input_features["input_features"]), np.ndarray)
|
| 212 |
+
|
| 213 |
+
# check shape
|
| 214 |
+
self.assertEqual(len(input_features["input_features"].shape), 3)
|
| 215 |
+
|
| 216 |
+
def test_batch_feature_pt(self):
|
| 217 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 218 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 219 |
+
speech_input2 = np.ones([2_000_000], dtype=np.float32)
|
| 220 |
+
speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32)
|
| 221 |
+
|
| 222 |
+
input_features = feature_extractor(
|
| 223 |
+
[speech_input1, speech_input2, speech_input3],
|
| 224 |
+
sampling_rate=[44_100, 16_000, 48_000],
|
| 225 |
+
return_tensors="pt",
|
| 226 |
+
return_attention_mask=True,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# check pt tensor or not
|
| 230 |
+
self.assertEqual(type(input_features["input_features"]), torch.Tensor)
|
| 231 |
+
|
| 232 |
+
# check shape
|
| 233 |
+
self.assertEqual(len(input_features["input_features"].shape), 3)
|
| 234 |
+
|
| 235 |
+
@require_tf
|
| 236 |
+
def test_batch_feature_tf(self):
|
| 237 |
+
import tensorflow as tf
|
| 238 |
+
|
| 239 |
+
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
|
| 240 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 241 |
+
speech_input2 = np.ones([2_000_000], dtype=np.float32)
|
| 242 |
+
speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32)
|
| 243 |
+
|
| 244 |
+
input_features = feature_extractor(
|
| 245 |
+
[speech_input1, speech_input2, speech_input3],
|
| 246 |
+
sampling_rate=[44_100, 16_000, 48_000],
|
| 247 |
+
return_tensors="tf",
|
| 248 |
+
return_attention_mask=True,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# check tf tensor or not
|
| 252 |
+
self.assertTrue(tf.is_tensor(input_features["input_features"]))
|
| 253 |
+
|
| 254 |
+
# check shape
|
| 255 |
+
self.assertEqual(len(input_features["input_features"].shape), 3)
|
| 256 |
+
|
| 257 |
+
@unittest.skip(
|
| 258 |
+
"Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)"
|
| 259 |
+
)
|
| 260 |
+
def test_padding_accepts_tensors_pt(self):
|
| 261 |
+
pass
|
| 262 |
+
|
| 263 |
+
@unittest.skip(
|
| 264 |
+
"Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)"
|
| 265 |
+
)
|
| 266 |
+
def test_padding_accepts_tensors_tf(self):
|
| 267 |
+
pass
|
| 268 |
+
|
| 269 |
+
@unittest.skip(
|
| 270 |
+
"Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)"
|
| 271 |
+
)
|
| 272 |
+
def test_padding_from_list(self):
|
| 273 |
+
pass
|
| 274 |
+
|
| 275 |
+
@unittest.skip(
|
| 276 |
+
"Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)"
|
| 277 |
+
)
|
| 278 |
+
def test_padding_from_array(self):
|
| 279 |
+
pass
|
| 280 |
+
|
| 281 |
+
@unittest.skip("Pop2PianoFeatureExtractor does not support truncation")
|
| 282 |
+
def test_attention_mask_with_truncation(self):
|
| 283 |
+
pass
|
| 284 |
+
|
| 285 |
+
@unittest.skip("Pop2PianoFeatureExtractor does not supports truncation")
|
| 286 |
+
def test_truncation_from_array(self):
|
| 287 |
+
pass
|
| 288 |
+
|
| 289 |
+
@unittest.skip("Pop2PianoFeatureExtractor does not supports truncation")
|
| 290 |
+
def test_truncation_from_list(self):
|
| 291 |
+
pass
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_modeling_pop2piano.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch Pop2Piano model. """
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
from datasets import load_dataset
|
| 23 |
+
|
| 24 |
+
from transformers import Pop2PianoConfig
|
| 25 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 26 |
+
from transformers.testing_utils import (
|
| 27 |
+
require_essentia,
|
| 28 |
+
require_librosa,
|
| 29 |
+
require_onnx,
|
| 30 |
+
require_scipy,
|
| 31 |
+
require_torch,
|
| 32 |
+
slow,
|
| 33 |
+
torch_device,
|
| 34 |
+
)
|
| 35 |
+
from transformers.utils import is_essentia_available, is_librosa_available, is_scipy_available, is_torch_available
|
| 36 |
+
|
| 37 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 38 |
+
from ...test_configuration_common import ConfigTester
|
| 39 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor
|
| 40 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if is_torch_available():
|
| 44 |
+
import torch
|
| 45 |
+
|
| 46 |
+
from transformers import Pop2PianoForConditionalGeneration
|
| 47 |
+
from transformers.models.pop2piano.modeling_pop2piano import POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 48 |
+
from transformers.pytorch_utils import is_torch_1_8_0
|
| 49 |
+
|
| 50 |
+
else:
|
| 51 |
+
is_torch_1_8_0 = False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@require_torch
|
| 55 |
+
class Pop2PianoModelTester:
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
parent,
|
| 59 |
+
vocab_size=99,
|
| 60 |
+
batch_size=13,
|
| 61 |
+
encoder_seq_length=7,
|
| 62 |
+
decoder_seq_length=9,
|
| 63 |
+
# For common tests
|
| 64 |
+
is_training=False,
|
| 65 |
+
use_attention_mask=True,
|
| 66 |
+
use_labels=True,
|
| 67 |
+
hidden_size=64,
|
| 68 |
+
num_hidden_layers=5,
|
| 69 |
+
num_attention_heads=4,
|
| 70 |
+
d_ff=37,
|
| 71 |
+
relative_attention_num_buckets=8,
|
| 72 |
+
dropout_rate=0.1,
|
| 73 |
+
initializer_factor=0.002,
|
| 74 |
+
eos_token_id=1,
|
| 75 |
+
pad_token_id=0,
|
| 76 |
+
decoder_start_token_id=0,
|
| 77 |
+
scope=None,
|
| 78 |
+
decoder_layers=None,
|
| 79 |
+
):
|
| 80 |
+
self.parent = parent
|
| 81 |
+
self.batch_size = batch_size
|
| 82 |
+
self.encoder_seq_length = encoder_seq_length
|
| 83 |
+
self.decoder_seq_length = decoder_seq_length
|
| 84 |
+
# For common tests
|
| 85 |
+
self.seq_length = self.decoder_seq_length
|
| 86 |
+
self.is_training = is_training
|
| 87 |
+
self.use_attention_mask = use_attention_mask
|
| 88 |
+
self.use_labels = use_labels
|
| 89 |
+
self.vocab_size = vocab_size
|
| 90 |
+
self.hidden_size = hidden_size
|
| 91 |
+
self.num_hidden_layers = num_hidden_layers
|
| 92 |
+
self.num_attention_heads = num_attention_heads
|
| 93 |
+
self.d_ff = d_ff
|
| 94 |
+
self.relative_attention_num_buckets = relative_attention_num_buckets
|
| 95 |
+
self.dropout_rate = dropout_rate
|
| 96 |
+
self.initializer_factor = initializer_factor
|
| 97 |
+
self.eos_token_id = eos_token_id
|
| 98 |
+
self.pad_token_id = pad_token_id
|
| 99 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 100 |
+
self.scope = None
|
| 101 |
+
self.decoder_layers = decoder_layers
|
| 102 |
+
|
| 103 |
+
def prepare_config_and_inputs(self):
|
| 104 |
+
input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
|
| 105 |
+
decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
|
| 106 |
+
|
| 107 |
+
attention_mask = None
|
| 108 |
+
decoder_attention_mask = None
|
| 109 |
+
if self.use_attention_mask:
|
| 110 |
+
attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 111 |
+
decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
|
| 112 |
+
|
| 113 |
+
lm_labels = (
|
| 114 |
+
ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) if self.use_labels else None
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return self.get_config(), input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels
|
| 118 |
+
|
| 119 |
+
def get_pipeline_config(self):
|
| 120 |
+
return Pop2PianoConfig(
|
| 121 |
+
vocab_size=166, # Pop2Piano forces 100 extra tokens
|
| 122 |
+
d_model=self.hidden_size,
|
| 123 |
+
d_ff=self.d_ff,
|
| 124 |
+
d_kv=self.hidden_size // self.num_attention_heads,
|
| 125 |
+
num_layers=self.num_hidden_layers,
|
| 126 |
+
num_decoder_layers=self.decoder_layers,
|
| 127 |
+
num_heads=self.num_attention_heads,
|
| 128 |
+
relative_attention_num_buckets=self.relative_attention_num_buckets,
|
| 129 |
+
dropout_rate=self.dropout_rate,
|
| 130 |
+
initializer_factor=self.initializer_factor,
|
| 131 |
+
eos_token_id=self.eos_token_id,
|
| 132 |
+
bos_token_id=self.pad_token_id,
|
| 133 |
+
pad_token_id=self.pad_token_id,
|
| 134 |
+
decoder_start_token_id=self.decoder_start_token_id,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def get_config(self):
|
| 138 |
+
return Pop2PianoConfig(
|
| 139 |
+
vocab_size=self.vocab_size,
|
| 140 |
+
d_model=self.hidden_size,
|
| 141 |
+
d_ff=self.d_ff,
|
| 142 |
+
d_kv=self.hidden_size // self.num_attention_heads,
|
| 143 |
+
num_layers=self.num_hidden_layers,
|
| 144 |
+
num_decoder_layers=self.decoder_layers,
|
| 145 |
+
num_heads=self.num_attention_heads,
|
| 146 |
+
relative_attention_num_buckets=self.relative_attention_num_buckets,
|
| 147 |
+
dropout_rate=self.dropout_rate,
|
| 148 |
+
initializer_factor=self.initializer_factor,
|
| 149 |
+
eos_token_id=self.eos_token_id,
|
| 150 |
+
bos_token_id=self.pad_token_id,
|
| 151 |
+
pad_token_id=self.pad_token_id,
|
| 152 |
+
decoder_start_token_id=self.decoder_start_token_id,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def check_prepare_lm_labels_via_shift_left(
|
| 156 |
+
self,
|
| 157 |
+
config,
|
| 158 |
+
input_ids,
|
| 159 |
+
decoder_input_ids,
|
| 160 |
+
attention_mask,
|
| 161 |
+
decoder_attention_mask,
|
| 162 |
+
lm_labels,
|
| 163 |
+
):
|
| 164 |
+
model = Pop2PianoForConditionalGeneration(config=config)
|
| 165 |
+
model.to(torch_device)
|
| 166 |
+
model.eval()
|
| 167 |
+
|
| 168 |
+
# make sure that lm_labels are correctly padded from the right
|
| 169 |
+
lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id)
|
| 170 |
+
|
| 171 |
+
# add causal pad token mask
|
| 172 |
+
triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not()
|
| 173 |
+
lm_labels.masked_fill_(triangular_mask, self.pad_token_id)
|
| 174 |
+
decoder_input_ids = model._shift_right(lm_labels)
|
| 175 |
+
|
| 176 |
+
for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)):
|
| 177 |
+
# first item
|
| 178 |
+
self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id)
|
| 179 |
+
if i < decoder_input_ids_slice.shape[-1]:
|
| 180 |
+
if i < decoder_input_ids.shape[-1] - 1:
|
| 181 |
+
# items before diagonal
|
| 182 |
+
self.parent.assertListEqual(
|
| 183 |
+
decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist()
|
| 184 |
+
)
|
| 185 |
+
# pad items after diagonal
|
| 186 |
+
if i < decoder_input_ids.shape[-1] - 2:
|
| 187 |
+
self.parent.assertListEqual(
|
| 188 |
+
decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist()
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
# all items after square
|
| 192 |
+
self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist())
|
| 193 |
+
|
| 194 |
+
def create_and_check_model(
|
| 195 |
+
self,
|
| 196 |
+
config,
|
| 197 |
+
input_ids,
|
| 198 |
+
decoder_input_ids,
|
| 199 |
+
attention_mask,
|
| 200 |
+
decoder_attention_mask,
|
| 201 |
+
lm_labels,
|
| 202 |
+
):
|
| 203 |
+
model = Pop2PianoForConditionalGeneration(config=config)
|
| 204 |
+
model.to(torch_device)
|
| 205 |
+
model.eval()
|
| 206 |
+
result = model(
|
| 207 |
+
input_ids=input_ids,
|
| 208 |
+
decoder_input_ids=decoder_input_ids,
|
| 209 |
+
attention_mask=attention_mask,
|
| 210 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 211 |
+
)
|
| 212 |
+
result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
|
| 213 |
+
decoder_past = result.past_key_values
|
| 214 |
+
encoder_output = result.encoder_last_hidden_state
|
| 215 |
+
|
| 216 |
+
self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
|
| 217 |
+
# There should be `num_layers` key value embeddings stored in decoder_past
|
| 218 |
+
self.parent.assertEqual(len(decoder_past), config.num_layers)
|
| 219 |
+
# 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
|
| 220 |
+
self.parent.assertEqual(len(decoder_past[0]), 4)
|
| 221 |
+
|
| 222 |
+
def create_and_check_with_lm_head(
|
| 223 |
+
self,
|
| 224 |
+
config,
|
| 225 |
+
input_ids,
|
| 226 |
+
decoder_input_ids,
|
| 227 |
+
attention_mask,
|
| 228 |
+
decoder_attention_mask,
|
| 229 |
+
lm_labels,
|
| 230 |
+
):
|
| 231 |
+
model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval()
|
| 232 |
+
outputs = model(
|
| 233 |
+
input_ids=input_ids,
|
| 234 |
+
decoder_input_ids=decoder_input_ids,
|
| 235 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 236 |
+
labels=lm_labels,
|
| 237 |
+
)
|
| 238 |
+
self.parent.assertEqual(len(outputs), 4)
|
| 239 |
+
self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))
|
| 240 |
+
self.parent.assertEqual(outputs["loss"].size(), ())
|
| 241 |
+
|
| 242 |
+
def create_and_check_decoder_model_past(
|
| 243 |
+
self,
|
| 244 |
+
config,
|
| 245 |
+
input_ids,
|
| 246 |
+
decoder_input_ids,
|
| 247 |
+
attention_mask,
|
| 248 |
+
decoder_attention_mask,
|
| 249 |
+
lm_labels,
|
| 250 |
+
):
|
| 251 |
+
model = Pop2PianoForConditionalGeneration(config=config).get_decoder().to(torch_device).eval()
|
| 252 |
+
# first forward pass
|
| 253 |
+
outputs = model(input_ids, use_cache=True)
|
| 254 |
+
outputs_use_cache_conf = model(input_ids)
|
| 255 |
+
outputs_no_past = model(input_ids, use_cache=False)
|
| 256 |
+
|
| 257 |
+
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
|
| 258 |
+
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
|
| 259 |
+
|
| 260 |
+
output, past_key_values = outputs.to_tuple()
|
| 261 |
+
|
| 262 |
+
# create hypothetical next token and extent to next_input_ids
|
| 263 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 264 |
+
|
| 265 |
+
# append to next input_ids and
|
| 266 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 267 |
+
|
| 268 |
+
output_from_no_past = model(next_input_ids)["last_hidden_state"]
|
| 269 |
+
output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
|
| 270 |
+
|
| 271 |
+
# select random slice
|
| 272 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 273 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
|
| 274 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
|
| 275 |
+
|
| 276 |
+
# test that outputs are equal for slice
|
| 277 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 278 |
+
|
| 279 |
+
def create_and_check_decoder_model_attention_mask_past(
|
| 280 |
+
self,
|
| 281 |
+
config,
|
| 282 |
+
input_ids,
|
| 283 |
+
decoder_input_ids,
|
| 284 |
+
attention_mask,
|
| 285 |
+
decoder_attention_mask,
|
| 286 |
+
lm_labels,
|
| 287 |
+
):
|
| 288 |
+
model = Pop2PianoForConditionalGeneration(config=config).get_decoder()
|
| 289 |
+
model.to(torch_device)
|
| 290 |
+
model.eval()
|
| 291 |
+
|
| 292 |
+
# create attention mask
|
| 293 |
+
attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
|
| 294 |
+
|
| 295 |
+
half_seq_length = input_ids.shape[-1] // 2
|
| 296 |
+
attn_mask[:, half_seq_length:] = 0
|
| 297 |
+
|
| 298 |
+
# first forward pass
|
| 299 |
+
output, past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True).to_tuple()
|
| 300 |
+
|
| 301 |
+
# create hypothetical next token and extent to next_input_ids
|
| 302 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 303 |
+
|
| 304 |
+
# change a random masked slice from input_ids
|
| 305 |
+
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
|
| 306 |
+
random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
|
| 307 |
+
input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
|
| 308 |
+
|
| 309 |
+
# append to next input_ids and attn_mask
|
| 310 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 311 |
+
attn_mask = torch.cat(
|
| 312 |
+
[attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
|
| 313 |
+
dim=1,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# get two different outputs
|
| 317 |
+
output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
|
| 318 |
+
output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[
|
| 319 |
+
"last_hidden_state"
|
| 320 |
+
]
|
| 321 |
+
|
| 322 |
+
# select random slice
|
| 323 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 324 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
|
| 325 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
|
| 326 |
+
|
| 327 |
+
# test that outputs are equal for slice
|
| 328 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 329 |
+
|
| 330 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 331 |
+
self,
|
| 332 |
+
config,
|
| 333 |
+
input_ids,
|
| 334 |
+
decoder_input_ids,
|
| 335 |
+
attention_mask,
|
| 336 |
+
decoder_attention_mask,
|
| 337 |
+
lm_labels,
|
| 338 |
+
):
|
| 339 |
+
model = Pop2PianoForConditionalGeneration(config=config).get_decoder().to(torch_device).eval()
|
| 340 |
+
# first forward pass
|
| 341 |
+
outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
|
| 342 |
+
|
| 343 |
+
output, past_key_values = outputs.to_tuple()
|
| 344 |
+
|
| 345 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 346 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 347 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 348 |
+
|
| 349 |
+
# append to next input_ids and
|
| 350 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 351 |
+
next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1)
|
| 352 |
+
|
| 353 |
+
output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
|
| 354 |
+
output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
|
| 355 |
+
"last_hidden_state"
|
| 356 |
+
]
|
| 357 |
+
|
| 358 |
+
# select random slice
|
| 359 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 360 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 361 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 362 |
+
|
| 363 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 364 |
+
|
| 365 |
+
# test that outputs are equal for slice
|
| 366 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 367 |
+
|
| 368 |
+
def create_and_check_generate_with_past_key_values(
|
| 369 |
+
self,
|
| 370 |
+
config,
|
| 371 |
+
input_ids,
|
| 372 |
+
decoder_input_ids,
|
| 373 |
+
attention_mask,
|
| 374 |
+
decoder_attention_mask,
|
| 375 |
+
lm_labels,
|
| 376 |
+
):
|
| 377 |
+
model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval()
|
| 378 |
+
torch.manual_seed(0)
|
| 379 |
+
output_without_past_cache = model.generate(
|
| 380 |
+
input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False
|
| 381 |
+
)
|
| 382 |
+
torch.manual_seed(0)
|
| 383 |
+
output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)
|
| 384 |
+
self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
|
| 385 |
+
|
| 386 |
+
def create_and_check_model_fp16_forward(
|
| 387 |
+
self,
|
| 388 |
+
config,
|
| 389 |
+
input_ids,
|
| 390 |
+
decoder_input_ids,
|
| 391 |
+
attention_mask,
|
| 392 |
+
decoder_attention_mask,
|
| 393 |
+
lm_labels,
|
| 394 |
+
):
|
| 395 |
+
model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).half().eval()
|
| 396 |
+
output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)[
|
| 397 |
+
"encoder_last_hidden_state"
|
| 398 |
+
]
|
| 399 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 400 |
+
|
| 401 |
+
def create_and_check_encoder_decoder_shared_weights(
|
| 402 |
+
self,
|
| 403 |
+
config,
|
| 404 |
+
input_ids,
|
| 405 |
+
decoder_input_ids,
|
| 406 |
+
attention_mask,
|
| 407 |
+
decoder_attention_mask,
|
| 408 |
+
lm_labels,
|
| 409 |
+
):
|
| 410 |
+
for model_class in [Pop2PianoForConditionalGeneration]:
|
| 411 |
+
torch.manual_seed(0)
|
| 412 |
+
model = model_class(config=config).to(torch_device).eval()
|
| 413 |
+
# load state dict copies weights but does not tie them
|
| 414 |
+
model.encoder.load_state_dict(model.decoder.state_dict(), strict=False)
|
| 415 |
+
|
| 416 |
+
torch.manual_seed(0)
|
| 417 |
+
tied_config = copy.deepcopy(config)
|
| 418 |
+
tied_config.tie_encoder_decoder = True
|
| 419 |
+
tied_model = model_class(config=tied_config).to(torch_device).eval()
|
| 420 |
+
|
| 421 |
+
model_result = model(
|
| 422 |
+
input_ids=input_ids,
|
| 423 |
+
decoder_input_ids=decoder_input_ids,
|
| 424 |
+
attention_mask=attention_mask,
|
| 425 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
tied_model_result = tied_model(
|
| 429 |
+
input_ids=input_ids,
|
| 430 |
+
decoder_input_ids=decoder_input_ids,
|
| 431 |
+
attention_mask=attention_mask,
|
| 432 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# check that models has less parameters
|
| 436 |
+
self.parent.assertLess(
|
| 437 |
+
sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
|
| 438 |
+
)
|
| 439 |
+
random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
|
| 440 |
+
|
| 441 |
+
# check that outputs are equal
|
| 442 |
+
self.parent.assertTrue(
|
| 443 |
+
torch.allclose(
|
| 444 |
+
model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4
|
| 445 |
+
)
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# check that outputs after saving and loading are equal
|
| 449 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 450 |
+
tied_model.save_pretrained(tmpdirname)
|
| 451 |
+
tied_model = model_class.from_pretrained(tmpdirname)
|
| 452 |
+
tied_model.to(torch_device)
|
| 453 |
+
tied_model.eval()
|
| 454 |
+
|
| 455 |
+
# check that models has less parameters
|
| 456 |
+
self.parent.assertLess(
|
| 457 |
+
sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
|
| 458 |
+
)
|
| 459 |
+
random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
|
| 460 |
+
|
| 461 |
+
tied_model_result = tied_model(
|
| 462 |
+
input_ids=input_ids,
|
| 463 |
+
decoder_input_ids=decoder_input_ids,
|
| 464 |
+
attention_mask=attention_mask,
|
| 465 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
# check that outputs are equal
|
| 469 |
+
self.parent.assertTrue(
|
| 470 |
+
torch.allclose(
|
| 471 |
+
model_result[0][0, :, random_slice_idx],
|
| 472 |
+
tied_model_result[0][0, :, random_slice_idx],
|
| 473 |
+
atol=1e-4,
|
| 474 |
+
)
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
def check_resize_embeddings_pop2piano_v1_1(
|
| 478 |
+
self,
|
| 479 |
+
config,
|
| 480 |
+
):
|
| 481 |
+
prev_vocab_size = config.vocab_size
|
| 482 |
+
|
| 483 |
+
config.tie_word_embeddings = False
|
| 484 |
+
model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval()
|
| 485 |
+
model.resize_token_embeddings(prev_vocab_size - 10)
|
| 486 |
+
|
| 487 |
+
self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10)
|
| 488 |
+
self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10)
|
| 489 |
+
self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10)
|
| 490 |
+
|
| 491 |
+
def prepare_config_and_inputs_for_common(self):
|
| 492 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 493 |
+
(
|
| 494 |
+
config,
|
| 495 |
+
input_ids,
|
| 496 |
+
decoder_input_ids,
|
| 497 |
+
attention_mask,
|
| 498 |
+
decoder_attention_mask,
|
| 499 |
+
lm_labels,
|
| 500 |
+
) = config_and_inputs
|
| 501 |
+
|
| 502 |
+
inputs_dict = {
|
| 503 |
+
"input_ids": input_ids,
|
| 504 |
+
"attention_mask": attention_mask,
|
| 505 |
+
"decoder_input_ids": decoder_input_ids,
|
| 506 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 507 |
+
"use_cache": False,
|
| 508 |
+
}
|
| 509 |
+
return config, inputs_dict
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@require_torch
|
| 513 |
+
class Pop2PianoModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 514 |
+
all_model_classes = (Pop2PianoForConditionalGeneration,) if is_torch_available() else ()
|
| 515 |
+
all_generative_model_classes = ()
|
| 516 |
+
pipeline_model_mapping = (
|
| 517 |
+
{"automatic-speech-recognition": Pop2PianoForConditionalGeneration} if is_torch_available() else {}
|
| 518 |
+
)
|
| 519 |
+
all_parallelizable_model_classes = ()
|
| 520 |
+
fx_compatible = False
|
| 521 |
+
test_pruning = False
|
| 522 |
+
test_resize_embeddings = True
|
| 523 |
+
test_model_parallel = False
|
| 524 |
+
is_encoder_decoder = True
|
| 525 |
+
|
| 526 |
+
def setUp(self):
|
| 527 |
+
self.model_tester = Pop2PianoModelTester(self)
|
| 528 |
+
self.config_tester = ConfigTester(self, config_class=Pop2PianoConfig, d_model=37)
|
| 529 |
+
|
| 530 |
+
def test_config(self):
|
| 531 |
+
self.config_tester.run_common_tests()
|
| 532 |
+
|
| 533 |
+
def test_shift_right(self):
|
| 534 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 535 |
+
self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs)
|
| 536 |
+
|
| 537 |
+
def test_model(self):
|
| 538 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 539 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 540 |
+
|
| 541 |
+
def test_model_v1_1(self):
|
| 542 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 543 |
+
# check that gated gelu feed forward and different word embeddings work
|
| 544 |
+
config = config_and_inputs[0]
|
| 545 |
+
config.tie_word_embeddings = False
|
| 546 |
+
config.feed_forward_proj = "gated-gelu"
|
| 547 |
+
self.model_tester.create_and_check_model(config, *config_and_inputs[1:])
|
| 548 |
+
|
| 549 |
+
def test_config_and_model_silu_gated(self):
|
| 550 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 551 |
+
config = config_and_inputs[0]
|
| 552 |
+
config.feed_forward_proj = "gated-silu"
|
| 553 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 554 |
+
|
| 555 |
+
def test_with_lm_head(self):
|
| 556 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 557 |
+
self.model_tester.create_and_check_with_lm_head(*config_and_inputs)
|
| 558 |
+
|
| 559 |
+
def test_decoder_model_past(self):
|
| 560 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 561 |
+
self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
|
| 562 |
+
|
| 563 |
+
def test_decoder_model_past_with_attn_mask(self):
|
| 564 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 565 |
+
self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
|
| 566 |
+
|
| 567 |
+
def test_decoder_model_past_with_3d_attn_mask(self):
|
| 568 |
+
(
|
| 569 |
+
config,
|
| 570 |
+
input_ids,
|
| 571 |
+
decoder_input_ids,
|
| 572 |
+
attention_mask,
|
| 573 |
+
decoder_attention_mask,
|
| 574 |
+
lm_labels,
|
| 575 |
+
) = self.model_tester.prepare_config_and_inputs()
|
| 576 |
+
|
| 577 |
+
attention_mask = ids_tensor(
|
| 578 |
+
[self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length],
|
| 579 |
+
vocab_size=2,
|
| 580 |
+
)
|
| 581 |
+
decoder_attention_mask = ids_tensor(
|
| 582 |
+
[self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length],
|
| 583 |
+
vocab_size=2,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
self.model_tester.create_and_check_decoder_model_attention_mask_past(
|
| 587 |
+
config,
|
| 588 |
+
input_ids,
|
| 589 |
+
decoder_input_ids,
|
| 590 |
+
attention_mask,
|
| 591 |
+
decoder_attention_mask,
|
| 592 |
+
lm_labels,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 596 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 597 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 598 |
+
|
| 599 |
+
def test_encoder_decoder_shared_weights(self):
|
| 600 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 601 |
+
self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs)
|
| 602 |
+
|
| 603 |
+
@unittest.skipIf(torch_device == "cpu", "Cant do half precision")
|
| 604 |
+
def test_model_fp16_forward(self):
|
| 605 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 606 |
+
self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
|
| 607 |
+
|
| 608 |
+
def test_v1_1_resize_embeddings(self):
|
| 609 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 610 |
+
self.model_tester.check_resize_embeddings_pop2piano_v1_1(config)
|
| 611 |
+
|
| 612 |
+
@slow
|
| 613 |
+
def test_model_from_pretrained(self):
|
| 614 |
+
for model_name in POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 615 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained(model_name)
|
| 616 |
+
self.assertIsNotNone(model)
|
| 617 |
+
|
| 618 |
+
@require_onnx
|
| 619 |
+
@unittest.skipIf(
|
| 620 |
+
is_torch_1_8_0,
|
| 621 |
+
reason="Test has a segmentation fault on torch 1.8.0",
|
| 622 |
+
)
|
| 623 |
+
def test_export_to_onnx(self):
|
| 624 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 625 |
+
model = Pop2PianoForConditionalGeneration(config_and_inputs[0]).to(torch_device)
|
| 626 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 627 |
+
torch.onnx.export(
|
| 628 |
+
model,
|
| 629 |
+
(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]),
|
| 630 |
+
f"{tmpdirname}/Pop2Piano_test.onnx",
|
| 631 |
+
export_params=True,
|
| 632 |
+
opset_version=9,
|
| 633 |
+
input_names=["input_ids", "decoder_input_ids"],
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
def test_pass_with_input_features(self):
|
| 637 |
+
input_features = BatchFeature(
|
| 638 |
+
{
|
| 639 |
+
"input_features": torch.rand((75, 100, 512)).type(torch.float32),
|
| 640 |
+
"beatsteps": torch.randint(size=(1, 955), low=0, high=100).type(torch.float32),
|
| 641 |
+
"extrapolated_beatstep": torch.randint(size=(1, 900), low=0, high=100).type(torch.float32),
|
| 642 |
+
}
|
| 643 |
+
)
|
| 644 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 645 |
+
model_opts = model.generate(input_features=input_features["input_features"], return_dict_in_generate=True)
|
| 646 |
+
|
| 647 |
+
self.assertEqual(model_opts.sequences.ndim, 2)
|
| 648 |
+
|
| 649 |
+
def test_pass_with_batched_input_features(self):
|
| 650 |
+
input_features = BatchFeature(
|
| 651 |
+
{
|
| 652 |
+
"input_features": torch.rand((220, 70, 512)).type(torch.float32),
|
| 653 |
+
"beatsteps": torch.randint(size=(5, 955), low=0, high=100).type(torch.float32),
|
| 654 |
+
"extrapolated_beatstep": torch.randint(size=(5, 900), low=0, high=100).type(torch.float32),
|
| 655 |
+
"attention_mask": torch.concatenate(
|
| 656 |
+
[
|
| 657 |
+
torch.ones([120, 70], dtype=torch.int32),
|
| 658 |
+
torch.zeros([1, 70], dtype=torch.int32),
|
| 659 |
+
torch.ones([50, 70], dtype=torch.int32),
|
| 660 |
+
torch.zeros([1, 70], dtype=torch.int32),
|
| 661 |
+
torch.ones([47, 70], dtype=torch.int32),
|
| 662 |
+
torch.zeros([1, 70], dtype=torch.int32),
|
| 663 |
+
],
|
| 664 |
+
axis=0,
|
| 665 |
+
),
|
| 666 |
+
"attention_mask_beatsteps": torch.ones((5, 955)).type(torch.int32),
|
| 667 |
+
"attention_mask_extrapolated_beatstep": torch.ones((5, 900)).type(torch.int32),
|
| 668 |
+
}
|
| 669 |
+
)
|
| 670 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 671 |
+
model_opts = model.generate(
|
| 672 |
+
input_features=input_features["input_features"],
|
| 673 |
+
attention_mask=input_features["attention_mask"],
|
| 674 |
+
return_dict_in_generate=True,
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
self.assertEqual(model_opts.sequences.ndim, 2)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@require_torch
|
| 681 |
+
class Pop2PianoModelIntegrationTests(unittest.TestCase):
|
| 682 |
+
@slow
|
| 683 |
+
def test_mel_conditioner_integration(self):
|
| 684 |
+
composer = "composer1"
|
| 685 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 686 |
+
input_embeds = torch.ones([10, 100, 512])
|
| 687 |
+
|
| 688 |
+
composer_value = model.generation_config.composer_to_feature_token[composer]
|
| 689 |
+
composer_value = torch.tensor(composer_value)
|
| 690 |
+
composer_value = composer_value.repeat(input_embeds.size(0))
|
| 691 |
+
outputs = model.mel_conditioner(
|
| 692 |
+
input_embeds, composer_value, min(model.generation_config.composer_to_feature_token.values())
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
# check shape
|
| 696 |
+
self.assertEqual(outputs.size(), torch.Size([10, 101, 512]))
|
| 697 |
+
|
| 698 |
+
# check values
|
| 699 |
+
EXPECTED_OUTPUTS = torch.tensor(
|
| 700 |
+
[[1.0475305318832397, 0.29052114486694336, -0.47778210043907166], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
self.assertTrue(torch.allclose(outputs[0, :3, :3], EXPECTED_OUTPUTS, atol=1e-4))
|
| 704 |
+
|
| 705 |
+
@slow
|
| 706 |
+
@require_essentia
|
| 707 |
+
@require_librosa
|
| 708 |
+
@require_scipy
|
| 709 |
+
def test_full_model_integration(self):
|
| 710 |
+
if is_librosa_available() and is_scipy_available() and is_essentia_available() and is_torch_available():
|
| 711 |
+
from transformers import Pop2PianoProcessor
|
| 712 |
+
|
| 713 |
+
speech_input1 = np.zeros([1_000_000], dtype=np.float32)
|
| 714 |
+
sampling_rate = 44_100
|
| 715 |
+
|
| 716 |
+
processor = Pop2PianoProcessor.from_pretrained("sweetcocoa/pop2piano")
|
| 717 |
+
input_features = processor.feature_extractor(
|
| 718 |
+
speech_input1, sampling_rate=sampling_rate, return_tensors="pt"
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 722 |
+
outputs = model.generate(
|
| 723 |
+
input_features=input_features["input_features"], return_dict_in_generate=True
|
| 724 |
+
).sequences
|
| 725 |
+
|
| 726 |
+
# check for shapes
|
| 727 |
+
self.assertEqual(outputs.size(0), 70)
|
| 728 |
+
|
| 729 |
+
# check for values
|
| 730 |
+
self.assertEqual(outputs[0, :2].detach().cpu().numpy().tolist(), [0, 1])
|
| 731 |
+
|
| 732 |
+
# This is the test for a real music from K-Pop genre.
|
| 733 |
+
@slow
|
| 734 |
+
@require_essentia
|
| 735 |
+
@require_librosa
|
| 736 |
+
@require_scipy
|
| 737 |
+
def test_real_music(self):
|
| 738 |
+
if is_librosa_available() and is_scipy_available() and is_essentia_available() and is_torch_available():
|
| 739 |
+
from transformers import Pop2PianoFeatureExtractor, Pop2PianoTokenizer
|
| 740 |
+
|
| 741 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 742 |
+
model.eval()
|
| 743 |
+
feature_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano")
|
| 744 |
+
tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano")
|
| 745 |
+
ds = load_dataset("sweetcocoa/pop2piano_ci", split="test")
|
| 746 |
+
|
| 747 |
+
output_fe = feature_extractor(
|
| 748 |
+
ds["audio"][0]["array"], sampling_rate=ds["audio"][0]["sampling_rate"], return_tensors="pt"
|
| 749 |
+
)
|
| 750 |
+
output_model = model.generate(input_features=output_fe["input_features"], composer="composer1")
|
| 751 |
+
output_tokenizer = tokenizer.batch_decode(token_ids=output_model, feature_extractor_output=output_fe)
|
| 752 |
+
pretty_midi_object = output_tokenizer["pretty_midi_objects"][0]
|
| 753 |
+
|
| 754 |
+
# Checking if no of notes are same
|
| 755 |
+
self.assertEqual(len(pretty_midi_object.instruments[0].notes), 59)
|
| 756 |
+
predicted_timings = []
|
| 757 |
+
for i in pretty_midi_object.instruments[0].notes:
|
| 758 |
+
predicted_timings.append(i.start)
|
| 759 |
+
|
| 760 |
+
# Checking note start timings(first 6)
|
| 761 |
+
EXPECTED_START_TIMINGS = [
|
| 762 |
+
0.4876190423965454,
|
| 763 |
+
0.7314285635948181,
|
| 764 |
+
0.9752380847930908,
|
| 765 |
+
1.4396371841430664,
|
| 766 |
+
1.6718367338180542,
|
| 767 |
+
1.904036283493042,
|
| 768 |
+
]
|
| 769 |
+
|
| 770 |
+
np.allclose(EXPECTED_START_TIMINGS, predicted_timings[:6])
|
| 771 |
+
|
| 772 |
+
# Checking note end timings(last 6)
|
| 773 |
+
EXPECTED_END_TIMINGS = [
|
| 774 |
+
12.341403007507324,
|
| 775 |
+
12.567797183990479,
|
| 776 |
+
12.567797183990479,
|
| 777 |
+
12.567797183990479,
|
| 778 |
+
12.794191360473633,
|
| 779 |
+
12.794191360473633,
|
| 780 |
+
]
|
| 781 |
+
|
| 782 |
+
np.allclose(EXPECTED_END_TIMINGS, predicted_timings[-6:])
|
docs/development-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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import shutil
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pytest
|
| 21 |
+
from datasets import load_dataset
|
| 22 |
+
|
| 23 |
+
from transformers.testing_utils import (
|
| 24 |
+
require_essentia,
|
| 25 |
+
require_librosa,
|
| 26 |
+
require_pretty_midi,
|
| 27 |
+
require_scipy,
|
| 28 |
+
require_torch,
|
| 29 |
+
)
|
| 30 |
+
from transformers.tokenization_utils import BatchEncoding
|
| 31 |
+
from transformers.utils.import_utils import (
|
| 32 |
+
is_essentia_available,
|
| 33 |
+
is_librosa_available,
|
| 34 |
+
is_pretty_midi_available,
|
| 35 |
+
is_scipy_available,
|
| 36 |
+
is_torch_available,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
requirements_available = (
|
| 41 |
+
is_torch_available()
|
| 42 |
+
and is_essentia_available()
|
| 43 |
+
and is_scipy_available()
|
| 44 |
+
and is_librosa_available()
|
| 45 |
+
and is_pretty_midi_available()
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
if requirements_available:
|
| 49 |
+
import pretty_midi
|
| 50 |
+
|
| 51 |
+
from transformers import (
|
| 52 |
+
Pop2PianoFeatureExtractor,
|
| 53 |
+
Pop2PianoForConditionalGeneration,
|
| 54 |
+
Pop2PianoProcessor,
|
| 55 |
+
Pop2PianoTokenizer,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@require_scipy
|
| 60 |
+
@require_torch
|
| 61 |
+
@require_librosa
|
| 62 |
+
@require_essentia
|
| 63 |
+
@require_pretty_midi
|
| 64 |
+
class Pop2PianoProcessorTest(unittest.TestCase):
|
| 65 |
+
def setUp(self):
|
| 66 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 67 |
+
|
| 68 |
+
feature_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano")
|
| 69 |
+
tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano")
|
| 70 |
+
processor = Pop2PianoProcessor(feature_extractor, tokenizer)
|
| 71 |
+
|
| 72 |
+
processor.save_pretrained(self.tmpdirname)
|
| 73 |
+
|
| 74 |
+
def get_tokenizer(self, **kwargs):
|
| 75 |
+
return Pop2PianoTokenizer.from_pretrained(self.tmpdirname, **kwargs)
|
| 76 |
+
|
| 77 |
+
def get_feature_extractor(self, **kwargs):
|
| 78 |
+
return Pop2PianoFeatureExtractor.from_pretrained(self.tmpdirname, **kwargs)
|
| 79 |
+
|
| 80 |
+
def tearDown(self):
|
| 81 |
+
shutil.rmtree(self.tmpdirname)
|
| 82 |
+
|
| 83 |
+
def test_save_load_pretrained_additional_features(self):
|
| 84 |
+
processor = Pop2PianoProcessor(
|
| 85 |
+
tokenizer=self.get_tokenizer(),
|
| 86 |
+
feature_extractor=self.get_feature_extractor(),
|
| 87 |
+
)
|
| 88 |
+
processor.save_pretrained(self.tmpdirname)
|
| 89 |
+
|
| 90 |
+
tokenizer_add_kwargs = self.get_tokenizer(
|
| 91 |
+
unk_token="-1",
|
| 92 |
+
eos_token="1",
|
| 93 |
+
pad_token="0",
|
| 94 |
+
bos_token="2",
|
| 95 |
+
)
|
| 96 |
+
feature_extractor_add_kwargs = self.get_feature_extractor()
|
| 97 |
+
|
| 98 |
+
processor = Pop2PianoProcessor.from_pretrained(
|
| 99 |
+
self.tmpdirname,
|
| 100 |
+
unk_token="-1",
|
| 101 |
+
eos_token="1",
|
| 102 |
+
pad_token="0",
|
| 103 |
+
bos_token="2",
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
|
| 107 |
+
self.assertIsInstance(processor.tokenizer, Pop2PianoTokenizer)
|
| 108 |
+
|
| 109 |
+
self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string())
|
| 110 |
+
self.assertIsInstance(processor.feature_extractor, Pop2PianoFeatureExtractor)
|
| 111 |
+
|
| 112 |
+
def get_inputs(self):
|
| 113 |
+
"""get inputs for both feature extractor and tokenizer"""
|
| 114 |
+
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 115 |
+
speech_samples = ds.sort("id").select([0])["audio"]
|
| 116 |
+
input_speech = [x["array"] for x in speech_samples][0]
|
| 117 |
+
sampling_rate = [x["sampling_rate"] for x in speech_samples][0]
|
| 118 |
+
|
| 119 |
+
feature_extractor_outputs = self.get_feature_extractor()(
|
| 120 |
+
audio=input_speech, sampling_rate=sampling_rate, return_tensors="pt"
|
| 121 |
+
)
|
| 122 |
+
model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano")
|
| 123 |
+
token_ids = model.generate(input_features=feature_extractor_outputs["input_features"], composer="composer1")
|
| 124 |
+
dummy_notes = [
|
| 125 |
+
[
|
| 126 |
+
pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77),
|
| 127 |
+
pretty_midi.Note(start=0.673379, end=0.905578, pitch=73, velocity=77),
|
| 128 |
+
pretty_midi.Note(start=0.905578, end=2.159456, pitch=73, velocity=77),
|
| 129 |
+
pretty_midi.Note(start=1.114558, end=2.159456, pitch=78, velocity=77),
|
| 130 |
+
pretty_midi.Note(start=1.323537, end=1.532517, pitch=80, velocity=77),
|
| 131 |
+
],
|
| 132 |
+
[
|
| 133 |
+
pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77),
|
| 134 |
+
],
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
return input_speech, sampling_rate, token_ids, dummy_notes
|
| 138 |
+
|
| 139 |
+
def test_feature_extractor(self):
|
| 140 |
+
feature_extractor = self.get_feature_extractor()
|
| 141 |
+
tokenizer = self.get_tokenizer()
|
| 142 |
+
|
| 143 |
+
processor = Pop2PianoProcessor(
|
| 144 |
+
tokenizer=tokenizer,
|
| 145 |
+
feature_extractor=feature_extractor,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
input_speech, sampling_rate, _, _ = self.get_inputs()
|
| 149 |
+
|
| 150 |
+
feature_extractor_outputs = feature_extractor(
|
| 151 |
+
audio=input_speech, sampling_rate=sampling_rate, return_tensors="np"
|
| 152 |
+
)
|
| 153 |
+
processor_outputs = processor(audio=input_speech, sampling_rate=sampling_rate, return_tensors="np")
|
| 154 |
+
|
| 155 |
+
for key in feature_extractor_outputs.keys():
|
| 156 |
+
self.assertTrue(np.allclose(feature_extractor_outputs[key], processor_outputs[key], atol=1e-4))
|
| 157 |
+
|
| 158 |
+
def test_processor_batch_decode(self):
|
| 159 |
+
feature_extractor = self.get_feature_extractor()
|
| 160 |
+
tokenizer = self.get_tokenizer()
|
| 161 |
+
|
| 162 |
+
processor = Pop2PianoProcessor(
|
| 163 |
+
tokenizer=tokenizer,
|
| 164 |
+
feature_extractor=feature_extractor,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
audio, sampling_rate, token_ids, _ = self.get_inputs()
|
| 168 |
+
feature_extractor_output = feature_extractor(audio=audio, sampling_rate=sampling_rate, return_tensors="pt")
|
| 169 |
+
|
| 170 |
+
encoded_processor = processor.batch_decode(
|
| 171 |
+
token_ids=token_ids,
|
| 172 |
+
feature_extractor_output=feature_extractor_output,
|
| 173 |
+
return_midi=True,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
encoded_tokenizer = tokenizer.batch_decode(
|
| 177 |
+
token_ids=token_ids,
|
| 178 |
+
feature_extractor_output=feature_extractor_output,
|
| 179 |
+
return_midi=True,
|
| 180 |
+
)
|
| 181 |
+
# check start timings
|
| 182 |
+
encoded_processor_start_timings = [token.start for token in encoded_processor["notes"]]
|
| 183 |
+
encoded_tokenizer_start_timings = [token.start for token in encoded_tokenizer["notes"]]
|
| 184 |
+
self.assertListEqual(encoded_processor_start_timings, encoded_tokenizer_start_timings)
|
| 185 |
+
|
| 186 |
+
# check end timings
|
| 187 |
+
encoded_processor_end_timings = [token.end for token in encoded_processor["notes"]]
|
| 188 |
+
encoded_tokenizer_end_timings = [token.end for token in encoded_tokenizer["notes"]]
|
| 189 |
+
self.assertListEqual(encoded_processor_end_timings, encoded_tokenizer_end_timings)
|
| 190 |
+
|
| 191 |
+
# check pitch
|
| 192 |
+
encoded_processor_pitch = [token.pitch for token in encoded_processor["notes"]]
|
| 193 |
+
encoded_tokenizer_pitch = [token.pitch for token in encoded_tokenizer["notes"]]
|
| 194 |
+
self.assertListEqual(encoded_processor_pitch, encoded_tokenizer_pitch)
|
| 195 |
+
|
| 196 |
+
# check velocity
|
| 197 |
+
encoded_processor_velocity = [token.velocity for token in encoded_processor["notes"]]
|
| 198 |
+
encoded_tokenizer_velocity = [token.velocity for token in encoded_tokenizer["notes"]]
|
| 199 |
+
self.assertListEqual(encoded_processor_velocity, encoded_tokenizer_velocity)
|
| 200 |
+
|
| 201 |
+
def test_tokenizer_call(self):
|
| 202 |
+
feature_extractor = self.get_feature_extractor()
|
| 203 |
+
tokenizer = self.get_tokenizer()
|
| 204 |
+
|
| 205 |
+
processor = Pop2PianoProcessor(
|
| 206 |
+
tokenizer=tokenizer,
|
| 207 |
+
feature_extractor=feature_extractor,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
_, _, _, notes = self.get_inputs()
|
| 211 |
+
|
| 212 |
+
encoded_processor = processor(
|
| 213 |
+
notes=notes,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
self.assertTrue(isinstance(encoded_processor, BatchEncoding))
|
| 217 |
+
|
| 218 |
+
def test_processor(self):
|
| 219 |
+
feature_extractor = self.get_feature_extractor()
|
| 220 |
+
tokenizer = self.get_tokenizer()
|
| 221 |
+
|
| 222 |
+
processor = Pop2PianoProcessor(
|
| 223 |
+
tokenizer=tokenizer,
|
| 224 |
+
feature_extractor=feature_extractor,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
audio, sampling_rate, _, notes = self.get_inputs()
|
| 228 |
+
|
| 229 |
+
inputs = processor(
|
| 230 |
+
audio=audio,
|
| 231 |
+
sampling_rate=sampling_rate,
|
| 232 |
+
notes=notes,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
self.assertListEqual(
|
| 236 |
+
list(inputs.keys()),
|
| 237 |
+
["input_features", "beatsteps", "extrapolated_beatstep", "token_ids"],
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
# test if it raises when no input is passed
|
| 241 |
+
with pytest.raises(ValueError):
|
| 242 |
+
processor()
|
| 243 |
+
|
| 244 |
+
def test_model_input_names(self):
|
| 245 |
+
feature_extractor = self.get_feature_extractor()
|
| 246 |
+
tokenizer = self.get_tokenizer()
|
| 247 |
+
|
| 248 |
+
processor = Pop2PianoProcessor(
|
| 249 |
+
tokenizer=tokenizer,
|
| 250 |
+
feature_extractor=feature_extractor,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
audio, sampling_rate, _, notes = self.get_inputs()
|
| 254 |
+
feature_extractor(audio, sampling_rate, return_tensors="pt")
|
| 255 |
+
|
| 256 |
+
inputs = processor(
|
| 257 |
+
audio=audio,
|
| 258 |
+
sampling_rate=sampling_rate,
|
| 259 |
+
notes=notes,
|
| 260 |
+
)
|
| 261 |
+
self.assertListEqual(
|
| 262 |
+
list(inputs.keys()),
|
| 263 |
+
["input_features", "beatsteps", "extrapolated_beatstep", "token_ids"],
|
| 264 |
+
)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_tokenization_pop2piano.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Please note that Pop2PianoTokenizer is too far from our usual tokenizers and thus cannot use the TokenizerTesterMixin class.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import pickle
|
| 21 |
+
import shutil
|
| 22 |
+
import tempfile
|
| 23 |
+
import unittest
|
| 24 |
+
|
| 25 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 26 |
+
from transformers.testing_utils import (
|
| 27 |
+
is_pretty_midi_available,
|
| 28 |
+
is_torch_available,
|
| 29 |
+
require_pretty_midi,
|
| 30 |
+
require_torch,
|
| 31 |
+
)
|
| 32 |
+
from transformers.tokenization_utils import BatchEncoding
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
requirements_available = is_torch_available() and is_pretty_midi_available()
|
| 40 |
+
if requirements_available:
|
| 41 |
+
import pretty_midi
|
| 42 |
+
|
| 43 |
+
from transformers import Pop2PianoTokenizer
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@require_torch
|
| 47 |
+
@require_pretty_midi
|
| 48 |
+
class Pop2PianoTokenizerTest(unittest.TestCase):
|
| 49 |
+
def setUp(self):
|
| 50 |
+
super().setUp()
|
| 51 |
+
self.tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano")
|
| 52 |
+
|
| 53 |
+
def get_input_notes(self):
|
| 54 |
+
notes = [
|
| 55 |
+
[
|
| 56 |
+
pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77),
|
| 57 |
+
pretty_midi.Note(start=0.673379, end=0.905578, pitch=73, velocity=77),
|
| 58 |
+
pretty_midi.Note(start=0.905578, end=2.159456, pitch=73, velocity=77),
|
| 59 |
+
pretty_midi.Note(start=1.114558, end=2.159456, pitch=78, velocity=77),
|
| 60 |
+
pretty_midi.Note(start=1.323537, end=1.532517, pitch=80, velocity=77),
|
| 61 |
+
],
|
| 62 |
+
[
|
| 63 |
+
pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77),
|
| 64 |
+
],
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
return notes
|
| 68 |
+
|
| 69 |
+
def test_call(self):
|
| 70 |
+
notes = self.get_input_notes()
|
| 71 |
+
|
| 72 |
+
output = self.tokenizer(
|
| 73 |
+
notes,
|
| 74 |
+
return_tensors="pt",
|
| 75 |
+
padding="max_length",
|
| 76 |
+
truncation=True,
|
| 77 |
+
max_length=10,
|
| 78 |
+
return_attention_mask=True,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# check the output type
|
| 82 |
+
self.assertTrue(isinstance(output, BatchEncoding))
|
| 83 |
+
|
| 84 |
+
# check the values
|
| 85 |
+
expected_output_token_ids = torch.tensor(
|
| 86 |
+
[[134, 133, 74, 135, 77, 132, 77, 133, 77, 82], [134, 133, 74, 136, 132, 74, 134, 134, 134, 134]]
|
| 87 |
+
)
|
| 88 |
+
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]])
|
| 89 |
+
|
| 90 |
+
self.assertTrue(torch.allclose(output["token_ids"], expected_output_token_ids, atol=1e-4))
|
| 91 |
+
self.assertTrue(torch.allclose(output["attention_mask"], expected_output_attention_mask, atol=1e-4))
|
| 92 |
+
|
| 93 |
+
def test_batch_decode(self):
|
| 94 |
+
# test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep)
|
| 95 |
+
|
| 96 |
+
# Please note that this test does not test the accuracy of the outputs, instead it is designed to make sure that
|
| 97 |
+
# the tokenizer's batch_decode can deal with attention_mask in feature-extractor outputs. For the accuracy check
|
| 98 |
+
# please see the `test_batch_decode_outputs` test.
|
| 99 |
+
|
| 100 |
+
model_output = torch.concatenate(
|
| 101 |
+
[
|
| 102 |
+
torch.randint(size=[120, 96], low=0, high=70, dtype=torch.long),
|
| 103 |
+
torch.zeros(size=[1, 96], dtype=torch.long),
|
| 104 |
+
torch.randint(size=[50, 96], low=0, high=40, dtype=torch.long),
|
| 105 |
+
torch.zeros(size=[1, 96], dtype=torch.long),
|
| 106 |
+
],
|
| 107 |
+
axis=0,
|
| 108 |
+
)
|
| 109 |
+
input_features = BatchFeature(
|
| 110 |
+
{
|
| 111 |
+
"beatsteps": torch.ones([2, 955]),
|
| 112 |
+
"extrapolated_beatstep": torch.ones([2, 1000]),
|
| 113 |
+
"attention_mask": torch.concatenate(
|
| 114 |
+
[
|
| 115 |
+
torch.ones([120, 96], dtype=torch.long),
|
| 116 |
+
torch.zeros([1, 96], dtype=torch.long),
|
| 117 |
+
torch.ones([50, 96], dtype=torch.long),
|
| 118 |
+
torch.zeros([1, 96], dtype=torch.long),
|
| 119 |
+
],
|
| 120 |
+
axis=0,
|
| 121 |
+
),
|
| 122 |
+
"attention_mask_beatsteps": torch.ones([2, 955]),
|
| 123 |
+
"attention_mask_extrapolated_beatstep": torch.ones([2, 1000]),
|
| 124 |
+
}
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features)[
|
| 128 |
+
"pretty_midi_objects"
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
# check length
|
| 132 |
+
self.assertTrue(len(output) == 2)
|
| 133 |
+
|
| 134 |
+
# check object type
|
| 135 |
+
self.assertTrue(isinstance(output[0], pretty_midi.pretty_midi.PrettyMIDI))
|
| 136 |
+
self.assertTrue(isinstance(output[1], pretty_midi.pretty_midi.PrettyMIDI))
|
| 137 |
+
|
| 138 |
+
def test_batch_decode_outputs(self):
|
| 139 |
+
# test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep)
|
| 140 |
+
|
| 141 |
+
# Please note that this test tests the accuracy of the outputs of the tokenizer's `batch_decode` method.
|
| 142 |
+
|
| 143 |
+
model_output = torch.tensor(
|
| 144 |
+
[
|
| 145 |
+
[134, 133, 74, 135, 77, 82, 84, 136, 132, 74, 77, 82, 84],
|
| 146 |
+
[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],
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
input_features = BatchEncoding(
|
| 150 |
+
{
|
| 151 |
+
"beatsteps": torch.tensor([[0.0697, 0.1103, 0.1509, 0.1916]]),
|
| 152 |
+
"extrapolated_beatstep": torch.tensor([[0.0000, 0.0406, 0.0813, 0.1219]]),
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features)
|
| 157 |
+
|
| 158 |
+
# check outputs
|
| 159 |
+
self.assertEqual(len(output["notes"]), 4)
|
| 160 |
+
|
| 161 |
+
predicted_start_timings, predicted_end_timings = [], []
|
| 162 |
+
for i in output["notes"]:
|
| 163 |
+
predicted_start_timings.append(i.start)
|
| 164 |
+
predicted_end_timings.append(i.end)
|
| 165 |
+
|
| 166 |
+
# Checking note start timings
|
| 167 |
+
expected_start_timings = torch.tensor(
|
| 168 |
+
[
|
| 169 |
+
0.069700,
|
| 170 |
+
0.110300,
|
| 171 |
+
0.110300,
|
| 172 |
+
0.110300,
|
| 173 |
+
]
|
| 174 |
+
)
|
| 175 |
+
predicted_start_timings = torch.tensor(predicted_start_timings)
|
| 176 |
+
|
| 177 |
+
self.assertTrue(torch.allclose(expected_start_timings, predicted_start_timings, atol=1e-4))
|
| 178 |
+
|
| 179 |
+
# Checking note end timings
|
| 180 |
+
expected_end_timings = torch.tensor(
|
| 181 |
+
[
|
| 182 |
+
0.191600,
|
| 183 |
+
0.191600,
|
| 184 |
+
0.191600,
|
| 185 |
+
0.191600,
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
predicted_end_timings = torch.tensor(predicted_end_timings)
|
| 189 |
+
|
| 190 |
+
self.assertTrue(torch.allclose(expected_end_timings, predicted_end_timings, atol=1e-4))
|
| 191 |
+
|
| 192 |
+
def test_get_vocab(self):
|
| 193 |
+
vocab_dict = self.tokenizer.get_vocab()
|
| 194 |
+
self.assertIsInstance(vocab_dict, dict)
|
| 195 |
+
self.assertGreaterEqual(len(self.tokenizer), len(vocab_dict))
|
| 196 |
+
|
| 197 |
+
vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))]
|
| 198 |
+
self.assertEqual(len(vocab), len(self.tokenizer))
|
| 199 |
+
|
| 200 |
+
self.tokenizer.add_tokens(["asdfasdfasdfasdf"])
|
| 201 |
+
vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))]
|
| 202 |
+
self.assertEqual(len(vocab), len(self.tokenizer))
|
| 203 |
+
|
| 204 |
+
def test_save_and_load_tokenizer(self):
|
| 205 |
+
tmpdirname = tempfile.mkdtemp()
|
| 206 |
+
|
| 207 |
+
sample_notes = self.get_input_notes()
|
| 208 |
+
|
| 209 |
+
self.tokenizer.add_tokens(["bim", "bambam"])
|
| 210 |
+
additional_special_tokens = self.tokenizer.additional_special_tokens
|
| 211 |
+
additional_special_tokens.append("new_additional_special_token")
|
| 212 |
+
self.tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens})
|
| 213 |
+
before_token_ids = self.tokenizer(sample_notes)["token_ids"]
|
| 214 |
+
before_vocab = self.tokenizer.get_vocab()
|
| 215 |
+
self.tokenizer.save_pretrained(tmpdirname)
|
| 216 |
+
|
| 217 |
+
after_tokenizer = self.tokenizer.__class__.from_pretrained(tmpdirname)
|
| 218 |
+
after_token_ids = after_tokenizer(sample_notes)["token_ids"]
|
| 219 |
+
after_vocab = after_tokenizer.get_vocab()
|
| 220 |
+
self.assertDictEqual(before_vocab, after_vocab)
|
| 221 |
+
self.assertListEqual(before_token_ids, after_token_ids)
|
| 222 |
+
self.assertIn("bim", after_vocab)
|
| 223 |
+
self.assertIn("bambam", after_vocab)
|
| 224 |
+
self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens)
|
| 225 |
+
|
| 226 |
+
shutil.rmtree(tmpdirname)
|
| 227 |
+
|
| 228 |
+
def test_pickle_tokenizer(self):
|
| 229 |
+
tmpdirname = tempfile.mkdtemp()
|
| 230 |
+
|
| 231 |
+
notes = self.get_input_notes()
|
| 232 |
+
subwords = self.tokenizer(notes)["token_ids"]
|
| 233 |
+
|
| 234 |
+
filename = os.path.join(tmpdirname, "tokenizer.bin")
|
| 235 |
+
with open(filename, "wb") as handle:
|
| 236 |
+
pickle.dump(self.tokenizer, handle)
|
| 237 |
+
|
| 238 |
+
with open(filename, "rb") as handle:
|
| 239 |
+
tokenizer_new = pickle.load(handle)
|
| 240 |
+
|
| 241 |
+
subwords_loaded = tokenizer_new(notes)["token_ids"]
|
| 242 |
+
|
| 243 |
+
self.assertListEqual(subwords, subwords_loaded)
|
| 244 |
+
|
| 245 |
+
def test_padding_side_in_kwargs(self):
|
| 246 |
+
tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="left")
|
| 247 |
+
self.assertEqual(tokenizer_p.padding_side, "left")
|
| 248 |
+
|
| 249 |
+
tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="right")
|
| 250 |
+
self.assertEqual(tokenizer_p.padding_side, "right")
|
| 251 |
+
|
| 252 |
+
self.assertRaises(
|
| 253 |
+
ValueError,
|
| 254 |
+
Pop2PianoTokenizer.from_pretrained,
|
| 255 |
+
"sweetcocoa/pop2piano",
|
| 256 |
+
padding_side="unauthorized",
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
def test_truncation_side_in_kwargs(self):
|
| 260 |
+
tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="left")
|
| 261 |
+
self.assertEqual(tokenizer_p.truncation_side, "left")
|
| 262 |
+
|
| 263 |
+
tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="right")
|
| 264 |
+
self.assertEqual(tokenizer_p.truncation_side, "right")
|
| 265 |
+
|
| 266 |
+
self.assertRaises(
|
| 267 |
+
ValueError,
|
| 268 |
+
Pop2PianoTokenizer.from_pretrained,
|
| 269 |
+
"sweetcocoa/pop2piano",
|
| 270 |
+
truncation_side="unauthorized",
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
def test_right_and_left_padding(self):
|
| 274 |
+
tokenizer = self.tokenizer
|
| 275 |
+
notes = self.get_input_notes()
|
| 276 |
+
notes = notes[0]
|
| 277 |
+
max_length = 20
|
| 278 |
+
|
| 279 |
+
padding_idx = tokenizer.pad_token_id
|
| 280 |
+
|
| 281 |
+
# RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True
|
| 282 |
+
tokenizer.padding_side = "right"
|
| 283 |
+
padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"]
|
| 284 |
+
padded_notes_length = len(padded_notes)
|
| 285 |
+
notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"]
|
| 286 |
+
padding_size = max_length - len(notes_without_padding)
|
| 287 |
+
|
| 288 |
+
self.assertEqual(padded_notes_length, max_length)
|
| 289 |
+
self.assertEqual(notes_without_padding + [padding_idx] * padding_size, padded_notes)
|
| 290 |
+
|
| 291 |
+
# LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True
|
| 292 |
+
tokenizer.padding_side = "left"
|
| 293 |
+
padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"]
|
| 294 |
+
padded_notes_length = len(padded_notes)
|
| 295 |
+
notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"]
|
| 296 |
+
padding_size = max_length - len(notes_without_padding)
|
| 297 |
+
|
| 298 |
+
self.assertEqual(padded_notes_length, max_length)
|
| 299 |
+
self.assertEqual([padding_idx] * padding_size + notes_without_padding, padded_notes)
|
| 300 |
+
|
| 301 |
+
# RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding'
|
| 302 |
+
notes_without_padding = tokenizer(notes)["token_ids"]
|
| 303 |
+
|
| 304 |
+
tokenizer.padding_side = "right"
|
| 305 |
+
padded_notes_right = tokenizer(notes, padding=False)["token_ids"]
|
| 306 |
+
self.assertEqual(len(padded_notes_right), len(notes_without_padding))
|
| 307 |
+
self.assertEqual(padded_notes_right, notes_without_padding)
|
| 308 |
+
|
| 309 |
+
tokenizer.padding_side = "left"
|
| 310 |
+
padded_notes_left = tokenizer(notes, padding="longest")["token_ids"]
|
| 311 |
+
self.assertEqual(len(padded_notes_left), len(notes_without_padding))
|
| 312 |
+
self.assertEqual(padded_notes_left, notes_without_padding)
|
| 313 |
+
|
| 314 |
+
tokenizer.padding_side = "right"
|
| 315 |
+
padded_notes_right = tokenizer(notes, padding="longest")["token_ids"]
|
| 316 |
+
self.assertEqual(len(padded_notes_right), len(notes_without_padding))
|
| 317 |
+
self.assertEqual(padded_notes_right, notes_without_padding)
|
| 318 |
+
|
| 319 |
+
tokenizer.padding_side = "left"
|
| 320 |
+
padded_notes_left = tokenizer(notes, padding=False)["token_ids"]
|
| 321 |
+
self.assertEqual(len(padded_notes_left), len(notes_without_padding))
|
| 322 |
+
self.assertEqual(padded_notes_left, notes_without_padding)
|
| 323 |
+
|
| 324 |
+
def test_right_and_left_truncation(self):
|
| 325 |
+
tokenizer = self.tokenizer
|
| 326 |
+
notes = self.get_input_notes()
|
| 327 |
+
notes = notes[0]
|
| 328 |
+
truncation_size = 3
|
| 329 |
+
|
| 330 |
+
# RIGHT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True
|
| 331 |
+
tokenizer.truncation_side = "right"
|
| 332 |
+
full_encoded_notes = tokenizer(notes)["token_ids"]
|
| 333 |
+
full_encoded_notes_length = len(full_encoded_notes)
|
| 334 |
+
truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[
|
| 335 |
+
"token_ids"
|
| 336 |
+
]
|
| 337 |
+
self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size)
|
| 338 |
+
self.assertEqual(full_encoded_notes[:-truncation_size], truncated_notes)
|
| 339 |
+
|
| 340 |
+
# LEFT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True
|
| 341 |
+
tokenizer.truncation_side = "left"
|
| 342 |
+
full_encoded_notes = tokenizer(notes)["token_ids"]
|
| 343 |
+
full_encoded_notes_length = len(full_encoded_notes)
|
| 344 |
+
truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[
|
| 345 |
+
"token_ids"
|
| 346 |
+
]
|
| 347 |
+
self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size)
|
| 348 |
+
self.assertEqual(full_encoded_notes[truncation_size:], truncated_notes)
|
| 349 |
+
|
| 350 |
+
# RIGHT & LEFT TRUNCATION - Check that nothing is done for 'longest' and 'no_truncation'
|
| 351 |
+
tokenizer.truncation_side = "right"
|
| 352 |
+
truncated_notes_right = tokenizer(notes, truncation=True)["token_ids"]
|
| 353 |
+
self.assertEqual(full_encoded_notes_length, len(truncated_notes_right))
|
| 354 |
+
self.assertEqual(full_encoded_notes, truncated_notes_right)
|
| 355 |
+
|
| 356 |
+
tokenizer.truncation_side = "left"
|
| 357 |
+
truncated_notes_left = tokenizer(notes, truncation="longest_first")["token_ids"]
|
| 358 |
+
self.assertEqual(len(truncated_notes_left), full_encoded_notes_length)
|
| 359 |
+
self.assertEqual(truncated_notes_left, full_encoded_notes)
|
| 360 |
+
|
| 361 |
+
tokenizer.truncation_side = "right"
|
| 362 |
+
truncated_notes_right = tokenizer(notes, truncation="longest_first")["token_ids"]
|
| 363 |
+
self.assertEqual(len(truncated_notes_right), full_encoded_notes_length)
|
| 364 |
+
self.assertEqual(truncated_notes_right, full_encoded_notes)
|
| 365 |
+
|
| 366 |
+
tokenizer.truncation_side = "left"
|
| 367 |
+
truncated_notes_left = tokenizer(notes, truncation=True)["token_ids"]
|
| 368 |
+
self.assertEqual(len(truncated_notes_left), full_encoded_notes_length)
|
| 369 |
+
self.assertEqual(truncated_notes_left, full_encoded_notes)
|
| 370 |
+
|
| 371 |
+
def test_padding_to_multiple_of(self):
|
| 372 |
+
notes = self.get_input_notes()
|
| 373 |
+
|
| 374 |
+
if self.tokenizer.pad_token is None:
|
| 375 |
+
self.skipTest("No padding token.")
|
| 376 |
+
else:
|
| 377 |
+
normal_tokens = self.tokenizer(notes[0], padding=True, pad_to_multiple_of=8)
|
| 378 |
+
for key, value in normal_tokens.items():
|
| 379 |
+
self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
|
| 380 |
+
|
| 381 |
+
normal_tokens = self.tokenizer(notes[0], pad_to_multiple_of=8)
|
| 382 |
+
for key, value in normal_tokens.items():
|
| 383 |
+
self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
|
| 384 |
+
|
| 385 |
+
# Should also work with truncation
|
| 386 |
+
normal_tokens = self.tokenizer(notes[0], padding=True, truncation=True, pad_to_multiple_of=8)
|
| 387 |
+
for key, value in normal_tokens.items():
|
| 388 |
+
self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
|
| 389 |
+
|
| 390 |
+
# truncation to something which is not a multiple of pad_to_multiple_of raises an error
|
| 391 |
+
self.assertRaises(
|
| 392 |
+
ValueError,
|
| 393 |
+
self.tokenizer.__call__,
|
| 394 |
+
notes[0],
|
| 395 |
+
padding=True,
|
| 396 |
+
truncation=True,
|
| 397 |
+
max_length=12,
|
| 398 |
+
pad_to_multiple_of=8,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
def test_padding_with_attention_mask(self):
|
| 402 |
+
if self.tokenizer.pad_token is None:
|
| 403 |
+
self.skipTest("No padding token.")
|
| 404 |
+
if "attention_mask" not in self.tokenizer.model_input_names:
|
| 405 |
+
self.skipTest("This model does not use attention mask.")
|
| 406 |
+
|
| 407 |
+
features = [
|
| 408 |
+
{"token_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]},
|
| 409 |
+
{"token_ids": [1, 2, 3], "attention_mask": [1, 1, 0]},
|
| 410 |
+
]
|
| 411 |
+
padded_features = self.tokenizer.pad(features)
|
| 412 |
+
if self.tokenizer.padding_side == "right":
|
| 413 |
+
self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]])
|
| 414 |
+
else:
|
| 415 |
+
self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]])
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_modeling_prophetnet.py
ADDED
|
@@ -0,0 +1,1332 @@
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import ProphetNetConfig, is_torch_available
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
|
| 23 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
ProphetNetDecoder,
|
| 34 |
+
ProphetNetEncoder,
|
| 35 |
+
ProphetNetForCausalLM,
|
| 36 |
+
ProphetNetForConditionalGeneration,
|
| 37 |
+
ProphetNetModel,
|
| 38 |
+
ProphetNetTokenizer,
|
| 39 |
+
)
|
| 40 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ProphetNetModelTester:
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
parent,
|
| 47 |
+
vocab_size=99,
|
| 48 |
+
batch_size=13,
|
| 49 |
+
hidden_size=16,
|
| 50 |
+
encoder_seq_length=7,
|
| 51 |
+
decoder_seq_length=9,
|
| 52 |
+
# For common tests
|
| 53 |
+
is_training=True,
|
| 54 |
+
use_attention_mask=True,
|
| 55 |
+
use_labels=True,
|
| 56 |
+
decoder_start_token_id=0,
|
| 57 |
+
encoder_ffn_dim=32,
|
| 58 |
+
num_encoder_layers=2,
|
| 59 |
+
num_encoder_attention_heads=4,
|
| 60 |
+
decoder_ffn_dim=32,
|
| 61 |
+
num_decoder_layers=2,
|
| 62 |
+
num_decoder_attention_heads=4,
|
| 63 |
+
max_position_embeddings=30,
|
| 64 |
+
is_encoder_decoder=True,
|
| 65 |
+
pad_token_id=0,
|
| 66 |
+
bos_token_id=1,
|
| 67 |
+
eos_token_id=2,
|
| 68 |
+
ngram=2,
|
| 69 |
+
num_buckets=32,
|
| 70 |
+
relative_max_distance=128,
|
| 71 |
+
disable_ngram_loss=False,
|
| 72 |
+
scope=None,
|
| 73 |
+
):
|
| 74 |
+
self.parent = parent
|
| 75 |
+
self.batch_size = batch_size
|
| 76 |
+
self.encoder_seq_length = encoder_seq_length
|
| 77 |
+
self.decoder_seq_length = decoder_seq_length
|
| 78 |
+
# For common tests
|
| 79 |
+
self.seq_length = self.decoder_seq_length
|
| 80 |
+
self.is_training = is_training
|
| 81 |
+
self.use_attention_mask = use_attention_mask
|
| 82 |
+
self.use_labels = use_labels
|
| 83 |
+
|
| 84 |
+
self.vocab_size = vocab_size
|
| 85 |
+
self.hidden_size = hidden_size
|
| 86 |
+
self.num_hidden_layers = num_decoder_layers
|
| 87 |
+
self.num_encoder_layers = num_encoder_layers
|
| 88 |
+
self.num_decoder_layers = num_decoder_layers
|
| 89 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 90 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 91 |
+
self.num_attention_heads = num_decoder_attention_heads
|
| 92 |
+
self.num_encoder_attention_heads = num_encoder_attention_heads
|
| 93 |
+
self.num_decoder_attention_heads = num_decoder_attention_heads
|
| 94 |
+
self.eos_token_id = eos_token_id
|
| 95 |
+
self.bos_token_id = bos_token_id
|
| 96 |
+
self.pad_token_id = pad_token_id
|
| 97 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 98 |
+
self.ngram = ngram
|
| 99 |
+
self.num_buckets = num_buckets
|
| 100 |
+
self.relative_max_distance = relative_max_distance
|
| 101 |
+
self.disable_ngram_loss = disable_ngram_loss
|
| 102 |
+
self.max_position_embeddings = max_position_embeddings
|
| 103 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 104 |
+
|
| 105 |
+
self.scope = None
|
| 106 |
+
self.decoder_key_length = decoder_seq_length
|
| 107 |
+
self.base_model_out_len = 7
|
| 108 |
+
self.num_hidden_states_types = 3 # encoder, decoder_main, decoder_ngram
|
| 109 |
+
self.decoder_attention_idx = 2
|
| 110 |
+
|
| 111 |
+
def prepare_config_and_inputs(self):
|
| 112 |
+
input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
|
| 113 |
+
decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
|
| 114 |
+
|
| 115 |
+
attention_mask = None
|
| 116 |
+
decoder_attention_mask = None
|
| 117 |
+
if self.use_attention_mask:
|
| 118 |
+
attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 119 |
+
decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
|
| 120 |
+
|
| 121 |
+
lm_labels = None
|
| 122 |
+
if self.use_labels:
|
| 123 |
+
lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
|
| 124 |
+
|
| 125 |
+
config = self.get_config()
|
| 126 |
+
|
| 127 |
+
return (
|
| 128 |
+
config,
|
| 129 |
+
input_ids,
|
| 130 |
+
decoder_input_ids,
|
| 131 |
+
attention_mask,
|
| 132 |
+
decoder_attention_mask,
|
| 133 |
+
lm_labels,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def get_config(self):
|
| 137 |
+
return ProphetNetConfig(
|
| 138 |
+
vocab_size=self.vocab_size,
|
| 139 |
+
hidden_size=self.hidden_size,
|
| 140 |
+
num_encoder_layers=self.num_encoder_layers,
|
| 141 |
+
num_decoder_layers=self.num_decoder_layers,
|
| 142 |
+
decoder_ffn_dim=self.decoder_ffn_dim,
|
| 143 |
+
encoder_ffn_dim=self.encoder_ffn_dim,
|
| 144 |
+
num_encoder_attention_heads=self.num_encoder_attention_heads,
|
| 145 |
+
num_decoder_attention_heads=self.num_decoder_attention_heads,
|
| 146 |
+
eos_token_id=self.eos_token_id,
|
| 147 |
+
bos_token_id=self.bos_token_id,
|
| 148 |
+
pad_token_id=self.pad_token_id,
|
| 149 |
+
decoder_start_token_id=self.decoder_start_token_id,
|
| 150 |
+
ngram=self.ngram,
|
| 151 |
+
num_buckets=self.num_buckets,
|
| 152 |
+
relative_max_distance=self.relative_max_distance,
|
| 153 |
+
disable_ngram_loss=self.disable_ngram_loss,
|
| 154 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 155 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 159 |
+
(
|
| 160 |
+
config,
|
| 161 |
+
input_ids,
|
| 162 |
+
decoder_input_ids,
|
| 163 |
+
attention_mask,
|
| 164 |
+
decoder_attention_mask,
|
| 165 |
+
lm_labels,
|
| 166 |
+
) = self.prepare_config_and_inputs()
|
| 167 |
+
|
| 168 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size])
|
| 169 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 170 |
+
|
| 171 |
+
return (
|
| 172 |
+
config,
|
| 173 |
+
decoder_input_ids,
|
| 174 |
+
decoder_attention_mask,
|
| 175 |
+
encoder_hidden_states,
|
| 176 |
+
encoder_attention_mask,
|
| 177 |
+
lm_labels,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def check_prepare_lm_labels_via_shift_left(
|
| 181 |
+
self,
|
| 182 |
+
config,
|
| 183 |
+
input_ids,
|
| 184 |
+
decoder_input_ids,
|
| 185 |
+
attention_mask,
|
| 186 |
+
decoder_attention_mask,
|
| 187 |
+
lm_labels,
|
| 188 |
+
):
|
| 189 |
+
model = ProphetNetModel(config=config)
|
| 190 |
+
model.to(torch_device)
|
| 191 |
+
model.eval()
|
| 192 |
+
|
| 193 |
+
# make sure that lm_labels are correctly padded from the right
|
| 194 |
+
lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id)
|
| 195 |
+
|
| 196 |
+
# add casaul pad token mask
|
| 197 |
+
triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not()
|
| 198 |
+
lm_labels.masked_fill_(triangular_mask, self.pad_token_id)
|
| 199 |
+
decoder_input_ids = model._shift_right(lm_labels)
|
| 200 |
+
|
| 201 |
+
for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)):
|
| 202 |
+
# first item
|
| 203 |
+
self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id)
|
| 204 |
+
if i < decoder_input_ids_slice.shape[-1]:
|
| 205 |
+
if i < decoder_input_ids.shape[-1] - 1:
|
| 206 |
+
# items before diagonal
|
| 207 |
+
self.parent.assertListEqual(
|
| 208 |
+
decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist()
|
| 209 |
+
)
|
| 210 |
+
# pad items after diagonal
|
| 211 |
+
if i < decoder_input_ids.shape[-1] - 2:
|
| 212 |
+
self.parent.assertListEqual(
|
| 213 |
+
decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist()
|
| 214 |
+
)
|
| 215 |
+
else:
|
| 216 |
+
# all items after square
|
| 217 |
+
self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist())
|
| 218 |
+
|
| 219 |
+
def create_and_check_model(
|
| 220 |
+
self,
|
| 221 |
+
config,
|
| 222 |
+
input_ids,
|
| 223 |
+
decoder_input_ids,
|
| 224 |
+
attention_mask,
|
| 225 |
+
decoder_attention_mask,
|
| 226 |
+
lm_labels,
|
| 227 |
+
):
|
| 228 |
+
model = ProphetNetModel(config=config)
|
| 229 |
+
model.to(torch_device)
|
| 230 |
+
model.eval()
|
| 231 |
+
result = model(
|
| 232 |
+
input_ids=input_ids,
|
| 233 |
+
decoder_input_ids=decoder_input_ids,
|
| 234 |
+
attention_mask=attention_mask,
|
| 235 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 236 |
+
)
|
| 237 |
+
result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
|
| 238 |
+
decoder_output = result.last_hidden_state
|
| 239 |
+
decoder_past = result.past_key_values
|
| 240 |
+
encoder_output = result.encoder_last_hidden_state
|
| 241 |
+
|
| 242 |
+
self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
|
| 243 |
+
self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size))
|
| 244 |
+
# There should be `num_layers` key value embeddings stored in decoder_past
|
| 245 |
+
self.parent.assertEqual(len(decoder_past), config.num_decoder_layers)
|
| 246 |
+
# 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
|
| 247 |
+
self.parent.assertEqual(len(decoder_past[0]), 4) # cross-attention + uni-directional self-attention
|
| 248 |
+
|
| 249 |
+
def create_and_check_with_lm_head(
|
| 250 |
+
self,
|
| 251 |
+
config,
|
| 252 |
+
input_ids,
|
| 253 |
+
decoder_input_ids,
|
| 254 |
+
attention_mask,
|
| 255 |
+
decoder_attention_mask,
|
| 256 |
+
lm_labels,
|
| 257 |
+
):
|
| 258 |
+
model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval()
|
| 259 |
+
outputs = model(
|
| 260 |
+
input_ids=input_ids,
|
| 261 |
+
decoder_input_ids=decoder_input_ids,
|
| 262 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 263 |
+
labels=lm_labels,
|
| 264 |
+
)
|
| 265 |
+
self.parent.assertEqual(len(outputs), 5)
|
| 266 |
+
self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))
|
| 267 |
+
self.parent.assertEqual(outputs["loss"].size(), ())
|
| 268 |
+
|
| 269 |
+
def create_and_check_causal_lm_decoder(
|
| 270 |
+
self,
|
| 271 |
+
config,
|
| 272 |
+
input_ids,
|
| 273 |
+
decoder_input_ids,
|
| 274 |
+
attention_mask,
|
| 275 |
+
decoder_attention_mask,
|
| 276 |
+
lm_labels,
|
| 277 |
+
):
|
| 278 |
+
model = ProphetNetForCausalLM(config=config).to(torch_device).eval()
|
| 279 |
+
outputs = model(
|
| 280 |
+
input_ids=decoder_input_ids,
|
| 281 |
+
attention_mask=decoder_attention_mask,
|
| 282 |
+
labels=lm_labels,
|
| 283 |
+
)
|
| 284 |
+
self.parent.assertEqual(len(outputs), 4)
|
| 285 |
+
self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))
|
| 286 |
+
self.parent.assertEqual(outputs["loss"].size(), ())
|
| 287 |
+
|
| 288 |
+
def create_and_check_generate_with_past_key_value_states(
|
| 289 |
+
self,
|
| 290 |
+
config,
|
| 291 |
+
input_ids,
|
| 292 |
+
decoder_input_ids,
|
| 293 |
+
attention_mask,
|
| 294 |
+
decoder_attention_mask,
|
| 295 |
+
lm_labels,
|
| 296 |
+
):
|
| 297 |
+
model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval()
|
| 298 |
+
torch.manual_seed(0)
|
| 299 |
+
output_without_past_cache = model.generate(
|
| 300 |
+
input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False
|
| 301 |
+
)
|
| 302 |
+
torch.manual_seed(0)
|
| 303 |
+
output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)
|
| 304 |
+
self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
|
| 305 |
+
|
| 306 |
+
def create_and_check_decoder_generate_with_past_key_value_states(
|
| 307 |
+
self,
|
| 308 |
+
config,
|
| 309 |
+
input_ids,
|
| 310 |
+
decoder_input_ids,
|
| 311 |
+
attention_mask,
|
| 312 |
+
decoder_attention_mask,
|
| 313 |
+
lm_labels,
|
| 314 |
+
):
|
| 315 |
+
model = ProphetNetForCausalLM(config=config).to(torch_device).eval()
|
| 316 |
+
torch.manual_seed(0)
|
| 317 |
+
output_without_past_cache = model.generate(
|
| 318 |
+
input_ids[:1], num_beams=2, max_length=10, do_sample=True, use_cache=False
|
| 319 |
+
)
|
| 320 |
+
torch.manual_seed(0)
|
| 321 |
+
output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=10, do_sample=True)
|
| 322 |
+
self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
|
| 323 |
+
|
| 324 |
+
def create_and_check_model_fp16_forward(
|
| 325 |
+
self,
|
| 326 |
+
config,
|
| 327 |
+
input_ids,
|
| 328 |
+
decoder_input_ids,
|
| 329 |
+
attention_mask,
|
| 330 |
+
decoder_attention_mask,
|
| 331 |
+
lm_labels,
|
| 332 |
+
):
|
| 333 |
+
model = ProphetNetModel(config=config).to(torch_device).half().eval()
|
| 334 |
+
output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"]
|
| 335 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 336 |
+
|
| 337 |
+
def create_and_check_encoder_decoder_shared_weights(
|
| 338 |
+
self,
|
| 339 |
+
config,
|
| 340 |
+
input_ids,
|
| 341 |
+
decoder_input_ids,
|
| 342 |
+
attention_mask,
|
| 343 |
+
decoder_attention_mask,
|
| 344 |
+
lm_labels,
|
| 345 |
+
):
|
| 346 |
+
for model_class in [ProphetNetModel, ProphetNetForConditionalGeneration]:
|
| 347 |
+
torch.manual_seed(0)
|
| 348 |
+
model = model_class(config=config).to(torch_device).eval()
|
| 349 |
+
# load state dict copies weights but does not tie them
|
| 350 |
+
|
| 351 |
+
if model_class == ProphetNetForConditionalGeneration:
|
| 352 |
+
model.prophetnet.encoder.load_state_dict(model.prophetnet.decoder.state_dict(), strict=False)
|
| 353 |
+
else:
|
| 354 |
+
model.encoder.load_state_dict(model.decoder.state_dict(), strict=False)
|
| 355 |
+
|
| 356 |
+
torch.manual_seed(0)
|
| 357 |
+
tied_config = copy.deepcopy(config)
|
| 358 |
+
tied_config.tie_encoder_decoder = True
|
| 359 |
+
tied_model = model_class(config=tied_config).to(torch_device).eval()
|
| 360 |
+
|
| 361 |
+
model_result = model(
|
| 362 |
+
input_ids=input_ids,
|
| 363 |
+
decoder_input_ids=decoder_input_ids,
|
| 364 |
+
attention_mask=attention_mask,
|
| 365 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
tied_model_result = tied_model(
|
| 369 |
+
input_ids=input_ids,
|
| 370 |
+
decoder_input_ids=decoder_input_ids,
|
| 371 |
+
attention_mask=attention_mask,
|
| 372 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# check that models has less parameters
|
| 376 |
+
self.parent.assertLess(
|
| 377 |
+
sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
|
| 378 |
+
)
|
| 379 |
+
random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
|
| 380 |
+
|
| 381 |
+
# check that outputs are equal
|
| 382 |
+
self.parent.assertTrue(
|
| 383 |
+
torch.allclose(
|
| 384 |
+
model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4
|
| 385 |
+
)
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# check that outputs after saving and loading are equal
|
| 389 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 390 |
+
tied_model.save_pretrained(tmpdirname)
|
| 391 |
+
tied_model = model_class.from_pretrained(tmpdirname)
|
| 392 |
+
tied_model.to(torch_device)
|
| 393 |
+
tied_model.eval()
|
| 394 |
+
|
| 395 |
+
# check that models has less parameters
|
| 396 |
+
self.parent.assertLess(
|
| 397 |
+
sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
|
| 398 |
+
)
|
| 399 |
+
random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
|
| 400 |
+
|
| 401 |
+
tied_model_result = tied_model(
|
| 402 |
+
input_ids=input_ids,
|
| 403 |
+
decoder_input_ids=decoder_input_ids,
|
| 404 |
+
attention_mask=attention_mask,
|
| 405 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
# check that outputs are equal
|
| 409 |
+
self.parent.assertTrue(
|
| 410 |
+
torch.allclose(
|
| 411 |
+
model_result[0][0, :, random_slice_idx],
|
| 412 |
+
tied_model_result[0][0, :, random_slice_idx],
|
| 413 |
+
atol=1e-4,
|
| 414 |
+
)
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
def check_fast_integration(
|
| 418 |
+
self,
|
| 419 |
+
config,
|
| 420 |
+
*args,
|
| 421 |
+
):
|
| 422 |
+
input_ids = torch.tensor([[7, 4, 78, 0, 24, 52, 43]], device=torch_device, dtype=torch.long)
|
| 423 |
+
decoder_input_ids = torch.tensor([[12, 62, 25, 11, 47, 15, 14]], device=torch_device, dtype=torch.long)
|
| 424 |
+
attention_mask = torch.tensor([[1, 1, 1, 0, 1, 0, 0]], device=torch_device, dtype=torch.long)
|
| 425 |
+
decoder_attention_mask = torch.tensor([[1, 1, 1, 0, 0, 1, 0]], device=torch_device, dtype=torch.long)
|
| 426 |
+
lm_labels = torch.tensor([[62, 25, 11, 47, 15, 14, 24]], device=torch_device, dtype=torch.long)
|
| 427 |
+
torch.manual_seed(0)
|
| 428 |
+
config.ngram = 4
|
| 429 |
+
model = ProphetNetForConditionalGeneration(config=config)
|
| 430 |
+
model.to(torch_device)
|
| 431 |
+
model.eval()
|
| 432 |
+
with torch.no_grad():
|
| 433 |
+
result = model(
|
| 434 |
+
input_ids=input_ids,
|
| 435 |
+
decoder_input_ids=decoder_input_ids,
|
| 436 |
+
attention_mask=attention_mask,
|
| 437 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 438 |
+
labels=lm_labels,
|
| 439 |
+
)
|
| 440 |
+
self.parent.assertTrue(torch.allclose(result.loss, torch.tensor(4.5892, device=torch_device), atol=1e-3))
|
| 441 |
+
|
| 442 |
+
expected_logit_slice = torch.tensor(
|
| 443 |
+
[-0.0184, 0.0758, -0.0543, -0.0093, 0.0050, -0.0660, -0.1453], device=torch_device
|
| 444 |
+
)
|
| 445 |
+
self.parent.assertTrue(torch.allclose(result.logits[0, :, 1], expected_logit_slice, atol=1e-3))
|
| 446 |
+
|
| 447 |
+
def check_model_with_attn_mask(self, config, input_ids, decoder_input_ids, *args):
|
| 448 |
+
model = ProphetNetModel(config=config)
|
| 449 |
+
model.to(torch_device)
|
| 450 |
+
model.eval()
|
| 451 |
+
|
| 452 |
+
outputs_no_mask = model(input_ids=input_ids[:, :5], decoder_input_ids=decoder_input_ids[:, :5])
|
| 453 |
+
attention_mask = torch.ones_like(input_ids)
|
| 454 |
+
decoder_attention_mask = torch.ones_like(decoder_input_ids)
|
| 455 |
+
|
| 456 |
+
attention_mask[:, 5:] = 0
|
| 457 |
+
|
| 458 |
+
outputs_with_mask = model(
|
| 459 |
+
input_ids=input_ids,
|
| 460 |
+
attention_mask=attention_mask,
|
| 461 |
+
decoder_input_ids=decoder_input_ids,
|
| 462 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# check encoder
|
| 466 |
+
self.parent.assertTrue(
|
| 467 |
+
torch.allclose(
|
| 468 |
+
outputs_no_mask.encoder_last_hidden_state[0, :, 0],
|
| 469 |
+
outputs_with_mask.encoder_last_hidden_state[0, :5, 0],
|
| 470 |
+
atol=1e-3,
|
| 471 |
+
)
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
# check decoder
|
| 475 |
+
# main stream
|
| 476 |
+
self.parent.assertTrue(
|
| 477 |
+
torch.allclose(
|
| 478 |
+
outputs_no_mask.last_hidden_state[0, :, 0], outputs_with_mask.last_hidden_state[0, :5, 0], atol=1e-3
|
| 479 |
+
)
|
| 480 |
+
)
|
| 481 |
+
# predict stream
|
| 482 |
+
self.parent.assertTrue(
|
| 483 |
+
torch.allclose(
|
| 484 |
+
outputs_no_mask.last_hidden_state_ngram[0, :5, 0],
|
| 485 |
+
outputs_with_mask.last_hidden_state_ngram[0, :5, 0],
|
| 486 |
+
atol=1e-2,
|
| 487 |
+
)
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
def check_causal_lm_from_pretrained(
|
| 491 |
+
self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, *args
|
| 492 |
+
):
|
| 493 |
+
model = ProphetNetForConditionalGeneration(config).to(torch_device).eval()
|
| 494 |
+
|
| 495 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 496 |
+
model.save_pretrained(tmp_dirname)
|
| 497 |
+
decoder = ProphetNetForCausalLM.from_pretrained(tmp_dirname).to(torch_device)
|
| 498 |
+
|
| 499 |
+
encoder_hidden_states = model.prophetnet.encoder(input_ids).last_hidden_state
|
| 500 |
+
|
| 501 |
+
model_outputs = model(
|
| 502 |
+
encoder_outputs=BaseModelOutput(last_hidden_state=encoder_hidden_states),
|
| 503 |
+
decoder_input_ids=decoder_input_ids,
|
| 504 |
+
)
|
| 505 |
+
dec_outputs = decoder(encoder_hidden_states=encoder_hidden_states, input_ids=decoder_input_ids)
|
| 506 |
+
|
| 507 |
+
self.parent.assertTrue(
|
| 508 |
+
torch.allclose(
|
| 509 |
+
model_outputs.logits[0, :5],
|
| 510 |
+
dec_outputs.logits[0, :5],
|
| 511 |
+
atol=1e-3,
|
| 512 |
+
)
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
def prepare_config_and_inputs_for_common(self):
|
| 516 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 517 |
+
(
|
| 518 |
+
config,
|
| 519 |
+
input_ids,
|
| 520 |
+
decoder_input_ids,
|
| 521 |
+
attention_mask,
|
| 522 |
+
decoder_attention_mask,
|
| 523 |
+
lm_labels,
|
| 524 |
+
) = config_and_inputs
|
| 525 |
+
|
| 526 |
+
inputs_dict = {
|
| 527 |
+
"input_ids": input_ids,
|
| 528 |
+
"attention_mask": attention_mask,
|
| 529 |
+
"decoder_input_ids": decoder_input_ids,
|
| 530 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 531 |
+
"use_cache": False,
|
| 532 |
+
}
|
| 533 |
+
return config, inputs_dict
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
class ProphetNetStandaloneDecoderModelTester:
|
| 537 |
+
def __init__(
|
| 538 |
+
self,
|
| 539 |
+
parent,
|
| 540 |
+
vocab_size=99,
|
| 541 |
+
batch_size=13,
|
| 542 |
+
hidden_size=16,
|
| 543 |
+
encoder_seq_length=7,
|
| 544 |
+
decoder_seq_length=7,
|
| 545 |
+
# For common tests
|
| 546 |
+
is_training=True,
|
| 547 |
+
is_decoder=True,
|
| 548 |
+
use_attention_mask=True,
|
| 549 |
+
add_cross_attention=False,
|
| 550 |
+
use_cache=False,
|
| 551 |
+
use_labels=True,
|
| 552 |
+
decoder_start_token_id=0,
|
| 553 |
+
encoder_ffn_dim=32,
|
| 554 |
+
num_encoder_layers=2,
|
| 555 |
+
num_encoder_attention_heads=4,
|
| 556 |
+
decoder_ffn_dim=32,
|
| 557 |
+
num_decoder_layers=2,
|
| 558 |
+
num_decoder_attention_heads=4,
|
| 559 |
+
max_position_embeddings=30,
|
| 560 |
+
is_encoder_decoder=False,
|
| 561 |
+
pad_token_id=0,
|
| 562 |
+
bos_token_id=1,
|
| 563 |
+
eos_token_id=2,
|
| 564 |
+
ngram=2,
|
| 565 |
+
num_buckets=32,
|
| 566 |
+
relative_max_distance=128,
|
| 567 |
+
disable_ngram_loss=False,
|
| 568 |
+
scope=None,
|
| 569 |
+
):
|
| 570 |
+
self.parent = parent
|
| 571 |
+
self.batch_size = batch_size
|
| 572 |
+
self.encoder_seq_length = encoder_seq_length
|
| 573 |
+
self.decoder_seq_length = decoder_seq_length
|
| 574 |
+
# For common tests
|
| 575 |
+
self.seq_length = self.decoder_seq_length
|
| 576 |
+
self.is_training = is_training
|
| 577 |
+
self.use_attention_mask = use_attention_mask
|
| 578 |
+
self.use_labels = use_labels
|
| 579 |
+
|
| 580 |
+
self.vocab_size = vocab_size
|
| 581 |
+
self.hidden_size = hidden_size
|
| 582 |
+
self.num_hidden_layers = num_decoder_layers
|
| 583 |
+
self.num_encoder_layers = num_encoder_layers
|
| 584 |
+
self.num_decoder_layers = num_decoder_layers
|
| 585 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 586 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 587 |
+
self.num_attention_heads = num_decoder_attention_heads
|
| 588 |
+
self.num_encoder_attention_heads = num_encoder_attention_heads
|
| 589 |
+
self.num_decoder_attention_heads = num_decoder_attention_heads
|
| 590 |
+
self.eos_token_id = eos_token_id
|
| 591 |
+
self.bos_token_id = bos_token_id
|
| 592 |
+
self.pad_token_id = pad_token_id
|
| 593 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 594 |
+
self.ngram = ngram
|
| 595 |
+
self.num_buckets = num_buckets
|
| 596 |
+
self.relative_max_distance = relative_max_distance
|
| 597 |
+
self.use_cache = use_cache
|
| 598 |
+
self.disable_ngram_loss = disable_ngram_loss
|
| 599 |
+
self.max_position_embeddings = max_position_embeddings
|
| 600 |
+
self.add_cross_attention = add_cross_attention
|
| 601 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 602 |
+
|
| 603 |
+
self.scope = None
|
| 604 |
+
self.decoder_key_length = decoder_seq_length
|
| 605 |
+
self.base_model_out_len = 2
|
| 606 |
+
self.num_hidden_states_types = 2 # decoder_main, decoder_ngram
|
| 607 |
+
self.decoder_attention_idx = 1
|
| 608 |
+
|
| 609 |
+
def prepare_config_and_inputs(self):
|
| 610 |
+
input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
|
| 611 |
+
|
| 612 |
+
attention_mask = None
|
| 613 |
+
if self.use_attention_mask:
|
| 614 |
+
attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 615 |
+
|
| 616 |
+
lm_labels = None
|
| 617 |
+
if self.use_labels:
|
| 618 |
+
lm_labels = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
|
| 619 |
+
|
| 620 |
+
config = ProphetNetConfig(
|
| 621 |
+
vocab_size=self.vocab_size,
|
| 622 |
+
hidden_size=self.hidden_size,
|
| 623 |
+
num_encoder_layers=self.num_encoder_layers,
|
| 624 |
+
num_decoder_layers=self.num_decoder_layers,
|
| 625 |
+
decoder_ffn_dim=self.decoder_ffn_dim,
|
| 626 |
+
encoder_ffn_dim=self.encoder_ffn_dim,
|
| 627 |
+
num_encoder_attention_heads=self.num_encoder_attention_heads,
|
| 628 |
+
num_decoder_attention_heads=self.num_decoder_attention_heads,
|
| 629 |
+
eos_token_id=self.eos_token_id,
|
| 630 |
+
bos_token_id=self.bos_token_id,
|
| 631 |
+
use_cache=self.use_cache,
|
| 632 |
+
pad_token_id=self.pad_token_id,
|
| 633 |
+
decoder_start_token_id=self.decoder_start_token_id,
|
| 634 |
+
ngram=self.ngram,
|
| 635 |
+
num_buckets=self.num_buckets,
|
| 636 |
+
relative_max_distance=self.relative_max_distance,
|
| 637 |
+
disable_ngram_loss=self.disable_ngram_loss,
|
| 638 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 639 |
+
add_cross_attention=self.add_cross_attention,
|
| 640 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
return (
|
| 644 |
+
config,
|
| 645 |
+
input_ids,
|
| 646 |
+
attention_mask,
|
| 647 |
+
lm_labels,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 651 |
+
(
|
| 652 |
+
config,
|
| 653 |
+
input_ids,
|
| 654 |
+
attention_mask,
|
| 655 |
+
lm_labels,
|
| 656 |
+
) = self.prepare_config_and_inputs()
|
| 657 |
+
|
| 658 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size])
|
| 659 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 660 |
+
|
| 661 |
+
return (
|
| 662 |
+
config,
|
| 663 |
+
input_ids,
|
| 664 |
+
attention_mask,
|
| 665 |
+
encoder_hidden_states,
|
| 666 |
+
encoder_attention_mask,
|
| 667 |
+
lm_labels,
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
def create_and_check_decoder_model_past(
|
| 671 |
+
self,
|
| 672 |
+
config,
|
| 673 |
+
input_ids,
|
| 674 |
+
attention_mask,
|
| 675 |
+
lm_labels,
|
| 676 |
+
):
|
| 677 |
+
config.use_cache = True
|
| 678 |
+
model = ProphetNetDecoder(config=config).to(torch_device).eval()
|
| 679 |
+
# first forward pass
|
| 680 |
+
outputs = model(input_ids, use_cache=True)
|
| 681 |
+
outputs_use_cache_conf = model(input_ids)
|
| 682 |
+
outputs_no_past = model(input_ids, use_cache=False)
|
| 683 |
+
|
| 684 |
+
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
|
| 685 |
+
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
|
| 686 |
+
|
| 687 |
+
past_key_values = outputs["past_key_values"]
|
| 688 |
+
|
| 689 |
+
# create hypothetical next token and extent to next_input_ids
|
| 690 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 691 |
+
|
| 692 |
+
# append to next input_ids and
|
| 693 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 694 |
+
|
| 695 |
+
output_from_no_past = model(next_input_ids)["last_hidden_state"]
|
| 696 |
+
output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
|
| 697 |
+
|
| 698 |
+
# select random slice
|
| 699 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 700 |
+
output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
|
| 701 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
|
| 702 |
+
|
| 703 |
+
# test that outputs are equal for slice
|
| 704 |
+
assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
|
| 705 |
+
|
| 706 |
+
def create_and_check_decoder_model_attention_mask_past(
|
| 707 |
+
self,
|
| 708 |
+
config,
|
| 709 |
+
input_ids,
|
| 710 |
+
attention_mask,
|
| 711 |
+
lm_labels,
|
| 712 |
+
):
|
| 713 |
+
model = ProphetNetDecoder(config=config).to(torch_device).eval()
|
| 714 |
+
|
| 715 |
+
# create attention mask
|
| 716 |
+
attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
|
| 717 |
+
|
| 718 |
+
half_seq_length = input_ids.shape[-1] // 2
|
| 719 |
+
attn_mask[:, half_seq_length:] = 0
|
| 720 |
+
|
| 721 |
+
# first forward pass
|
| 722 |
+
past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
|
| 723 |
+
|
| 724 |
+
# create hypothetical next token and extent to next_input_ids
|
| 725 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 726 |
+
|
| 727 |
+
# change a random masked slice from input_ids
|
| 728 |
+
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
|
| 729 |
+
random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
|
| 730 |
+
input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
|
| 731 |
+
|
| 732 |
+
# append to next input_ids and attn_mask
|
| 733 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 734 |
+
attn_mask = torch.cat(
|
| 735 |
+
[attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
|
| 736 |
+
dim=1,
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
# get two different outputs
|
| 740 |
+
output_from_no_past = model(next_input_ids)["last_hidden_state"]
|
| 741 |
+
output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
|
| 742 |
+
|
| 743 |
+
# select random slice
|
| 744 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 745 |
+
output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
|
| 746 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
|
| 747 |
+
|
| 748 |
+
# test that outputs are equal for slice
|
| 749 |
+
assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2)
|
| 750 |
+
|
| 751 |
+
def prepare_config_and_inputs_for_common(self):
|
| 752 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 753 |
+
(
|
| 754 |
+
config,
|
| 755 |
+
input_ids,
|
| 756 |
+
attention_mask,
|
| 757 |
+
lm_labels,
|
| 758 |
+
) = config_and_inputs
|
| 759 |
+
|
| 760 |
+
inputs_dict = {
|
| 761 |
+
"input_ids": input_ids,
|
| 762 |
+
"attention_mask": attention_mask,
|
| 763 |
+
}
|
| 764 |
+
return config, inputs_dict
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
class ProphetNetStandaloneEncoderModelTester:
|
| 768 |
+
def __init__(
|
| 769 |
+
self,
|
| 770 |
+
parent,
|
| 771 |
+
vocab_size=99,
|
| 772 |
+
batch_size=13,
|
| 773 |
+
hidden_size=16,
|
| 774 |
+
encoder_seq_length=7,
|
| 775 |
+
decoder_seq_length=7,
|
| 776 |
+
# For common tests
|
| 777 |
+
is_training=True,
|
| 778 |
+
is_decoder=False,
|
| 779 |
+
use_attention_mask=True,
|
| 780 |
+
add_cross_attention=False,
|
| 781 |
+
use_cache=False,
|
| 782 |
+
use_labels=True,
|
| 783 |
+
decoder_start_token_id=0,
|
| 784 |
+
encoder_ffn_dim=32,
|
| 785 |
+
num_encoder_layers=2,
|
| 786 |
+
num_encoder_attention_heads=4,
|
| 787 |
+
decoder_ffn_dim=32,
|
| 788 |
+
num_decoder_layers=2,
|
| 789 |
+
num_decoder_attention_heads=4,
|
| 790 |
+
max_position_embeddings=30,
|
| 791 |
+
is_encoder_decoder=False,
|
| 792 |
+
pad_token_id=0,
|
| 793 |
+
bos_token_id=1,
|
| 794 |
+
eos_token_id=2,
|
| 795 |
+
num_buckets=32,
|
| 796 |
+
relative_max_distance=128,
|
| 797 |
+
disable_ngram_loss=False,
|
| 798 |
+
scope=None,
|
| 799 |
+
):
|
| 800 |
+
self.parent = parent
|
| 801 |
+
self.batch_size = batch_size
|
| 802 |
+
self.encoder_seq_length = encoder_seq_length
|
| 803 |
+
self.decoder_seq_length = decoder_seq_length
|
| 804 |
+
# For common tests
|
| 805 |
+
self.seq_length = self.decoder_seq_length
|
| 806 |
+
self.is_training = is_training
|
| 807 |
+
self.use_attention_mask = use_attention_mask
|
| 808 |
+
self.use_labels = use_labels
|
| 809 |
+
|
| 810 |
+
self.vocab_size = vocab_size
|
| 811 |
+
self.hidden_size = hidden_size
|
| 812 |
+
self.num_hidden_layers = num_decoder_layers
|
| 813 |
+
self.num_encoder_layers = num_encoder_layers
|
| 814 |
+
self.num_decoder_layers = num_decoder_layers
|
| 815 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 816 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 817 |
+
self.num_attention_heads = num_decoder_attention_heads
|
| 818 |
+
self.num_encoder_attention_heads = num_encoder_attention_heads
|
| 819 |
+
self.num_decoder_attention_heads = num_decoder_attention_heads
|
| 820 |
+
self.eos_token_id = eos_token_id
|
| 821 |
+
self.bos_token_id = bos_token_id
|
| 822 |
+
self.pad_token_id = pad_token_id
|
| 823 |
+
self.decoder_start_token_id = decoder_start_token_id
|
| 824 |
+
self.num_buckets = num_buckets
|
| 825 |
+
self.relative_max_distance = relative_max_distance
|
| 826 |
+
self.use_cache = use_cache
|
| 827 |
+
self.disable_ngram_loss = disable_ngram_loss
|
| 828 |
+
self.max_position_embeddings = max_position_embeddings
|
| 829 |
+
self.add_cross_attention = add_cross_attention
|
| 830 |
+
self.is_encoder_decoder = is_encoder_decoder
|
| 831 |
+
|
| 832 |
+
self.scope = None
|
| 833 |
+
self.decoder_key_length = decoder_seq_length
|
| 834 |
+
self.base_model_out_len = 1
|
| 835 |
+
self.num_hidden_states_types = 1
|
| 836 |
+
self.decoder_attention_idx = 1
|
| 837 |
+
|
| 838 |
+
def prepare_config_and_inputs(self):
|
| 839 |
+
input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
|
| 840 |
+
|
| 841 |
+
attention_mask = None
|
| 842 |
+
if self.use_attention_mask:
|
| 843 |
+
attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
|
| 844 |
+
|
| 845 |
+
config = ProphetNetConfig(
|
| 846 |
+
vocab_size=self.vocab_size,
|
| 847 |
+
hidden_size=self.hidden_size,
|
| 848 |
+
num_encoder_layers=self.num_encoder_layers,
|
| 849 |
+
num_decoder_layers=self.num_decoder_layers,
|
| 850 |
+
decoder_ffn_dim=self.decoder_ffn_dim,
|
| 851 |
+
encoder_ffn_dim=self.encoder_ffn_dim,
|
| 852 |
+
num_encoder_attention_heads=self.num_encoder_attention_heads,
|
| 853 |
+
num_decoder_attention_heads=self.num_decoder_attention_heads,
|
| 854 |
+
eos_token_id=self.eos_token_id,
|
| 855 |
+
bos_token_id=self.bos_token_id,
|
| 856 |
+
use_cache=self.use_cache,
|
| 857 |
+
pad_token_id=self.pad_token_id,
|
| 858 |
+
decoder_start_token_id=self.decoder_start_token_id,
|
| 859 |
+
num_buckets=self.num_buckets,
|
| 860 |
+
relative_max_distance=self.relative_max_distance,
|
| 861 |
+
disable_ngram_loss=self.disable_ngram_loss,
|
| 862 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 863 |
+
add_cross_attention=self.add_cross_attention,
|
| 864 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
return (
|
| 868 |
+
config,
|
| 869 |
+
input_ids,
|
| 870 |
+
attention_mask,
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
def prepare_config_and_inputs_for_common(self):
|
| 874 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 875 |
+
(
|
| 876 |
+
config,
|
| 877 |
+
input_ids,
|
| 878 |
+
attention_mask,
|
| 879 |
+
) = config_and_inputs
|
| 880 |
+
|
| 881 |
+
inputs_dict = {
|
| 882 |
+
"input_ids": input_ids,
|
| 883 |
+
"attention_mask": attention_mask,
|
| 884 |
+
}
|
| 885 |
+
return config, inputs_dict
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@require_torch
|
| 889 |
+
class ProphetNetModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 890 |
+
all_model_classes = (ProphetNetModel, ProphetNetForConditionalGeneration) if is_torch_available() else ()
|
| 891 |
+
all_generative_model_classes = (ProphetNetForConditionalGeneration,) if is_torch_available() else ()
|
| 892 |
+
pipeline_model_mapping = (
|
| 893 |
+
{
|
| 894 |
+
"conversational": ProphetNetForConditionalGeneration,
|
| 895 |
+
"feature-extraction": ProphetNetModel,
|
| 896 |
+
"summarization": ProphetNetForConditionalGeneration,
|
| 897 |
+
"text-generation": ProphetNetForCausalLM,
|
| 898 |
+
"text2text-generation": ProphetNetForConditionalGeneration,
|
| 899 |
+
"translation": ProphetNetForConditionalGeneration,
|
| 900 |
+
}
|
| 901 |
+
if is_torch_available()
|
| 902 |
+
else {}
|
| 903 |
+
)
|
| 904 |
+
test_pruning = False
|
| 905 |
+
test_resize_embeddings = False
|
| 906 |
+
is_encoder_decoder = True
|
| 907 |
+
|
| 908 |
+
# TODO: Fix the failed tests
|
| 909 |
+
def is_pipeline_test_to_skip(
|
| 910 |
+
self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
|
| 911 |
+
):
|
| 912 |
+
if pipeline_test_casse_name == "TextGenerationPipelineTests":
|
| 913 |
+
# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
|
| 914 |
+
# `ProphetNetConfig` was never used in pipeline tests: cannot create a simple
|
| 915 |
+
# tokenizer.
|
| 916 |
+
return True
|
| 917 |
+
|
| 918 |
+
return False
|
| 919 |
+
|
| 920 |
+
def setUp(self):
|
| 921 |
+
self.model_tester = ProphetNetModelTester(self)
|
| 922 |
+
self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)
|
| 923 |
+
|
| 924 |
+
def test_config(self):
|
| 925 |
+
self.config_tester.run_common_tests()
|
| 926 |
+
|
| 927 |
+
def test_model(self):
|
| 928 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 929 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 930 |
+
|
| 931 |
+
def test_lm_model(self):
|
| 932 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 933 |
+
self.model_tester.create_and_check_with_lm_head(*config_and_inputs)
|
| 934 |
+
|
| 935 |
+
def test_only_decoder_causal_model(self):
|
| 936 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 937 |
+
self.model_tester.create_and_check_causal_lm_decoder(*config_and_inputs)
|
| 938 |
+
|
| 939 |
+
def test_fast_integration(self):
|
| 940 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 941 |
+
self.model_tester.check_fast_integration(*config_and_inputs)
|
| 942 |
+
|
| 943 |
+
def test_shared_weights(self):
|
| 944 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 945 |
+
self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs)
|
| 946 |
+
|
| 947 |
+
def test_shift_labels_via_shift_left(self):
|
| 948 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 949 |
+
self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs)
|
| 950 |
+
|
| 951 |
+
@unittest.skip("Flaky test with no simple resolution. TODO Fix me @patrickvonplaten")
|
| 952 |
+
def test_decoder_model_generate(self):
|
| 953 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 954 |
+
self.model_tester.create_and_check_generate_with_past_key_value_states(*config_and_inputs)
|
| 955 |
+
|
| 956 |
+
def test_encoder_decoder_model_generate(self):
|
| 957 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 958 |
+
self.model_tester.create_and_check_decoder_generate_with_past_key_value_states(*config_and_inputs)
|
| 959 |
+
|
| 960 |
+
def test_attn_mask_model(self):
|
| 961 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 962 |
+
self.model_tester.check_model_with_attn_mask(*config_and_inputs)
|
| 963 |
+
|
| 964 |
+
def test_config_save(self):
|
| 965 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 966 |
+
config.add_cross_attention = False
|
| 967 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 968 |
+
config.save_pretrained(tmp_dirname)
|
| 969 |
+
config = ProphetNetConfig.from_pretrained(tmp_dirname)
|
| 970 |
+
|
| 971 |
+
self.assertFalse(config.add_cross_attention)
|
| 972 |
+
|
| 973 |
+
def test_causal_lm_from_pretrained(self):
|
| 974 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 975 |
+
self.model_tester.check_causal_lm_from_pretrained(*config_and_inputs)
|
| 976 |
+
|
| 977 |
+
@unittest.skipIf(torch_device == "cpu", "Cant do half precision")
|
| 978 |
+
def test_fp16_forward(self):
|
| 979 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 980 |
+
self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
|
| 981 |
+
|
| 982 |
+
# methods overwrite method in `test_modeling_common.py`
|
| 983 |
+
def test_attention_outputs(self):
|
| 984 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 985 |
+
|
| 986 |
+
seq_len = getattr(self.model_tester, "seq_length", None)
|
| 987 |
+
decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
|
| 988 |
+
encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
|
| 989 |
+
decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length)
|
| 990 |
+
encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
|
| 991 |
+
chunk_length = getattr(self.model_tester, "chunk_length", None)
|
| 992 |
+
if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
|
| 993 |
+
encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
|
| 994 |
+
|
| 995 |
+
for model_class in self.all_model_classes:
|
| 996 |
+
inputs_dict["output_attentions"] = True
|
| 997 |
+
inputs_dict["output_hidden_states"] = False
|
| 998 |
+
model = model_class(config)
|
| 999 |
+
model.to(torch_device)
|
| 1000 |
+
model.eval()
|
| 1001 |
+
with torch.no_grad():
|
| 1002 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 1003 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 1004 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 1005 |
+
|
| 1006 |
+
# check that output_attentions also work using config
|
| 1007 |
+
del inputs_dict["output_attentions"]
|
| 1008 |
+
config.output_attentions = True
|
| 1009 |
+
model = model_class(config)
|
| 1010 |
+
model.to(torch_device)
|
| 1011 |
+
model.eval()
|
| 1012 |
+
with torch.no_grad():
|
| 1013 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 1014 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 1015 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 1016 |
+
|
| 1017 |
+
if chunk_length is not None:
|
| 1018 |
+
self.assertListEqual(
|
| 1019 |
+
list(attentions[0].shape[-4:]),
|
| 1020 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
|
| 1021 |
+
)
|
| 1022 |
+
else:
|
| 1023 |
+
self.assertListEqual(
|
| 1024 |
+
list(attentions[0].shape[-3:]),
|
| 1025 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 1026 |
+
)
|
| 1027 |
+
out_len = len(outputs)
|
| 1028 |
+
|
| 1029 |
+
correct_outlen = 7
|
| 1030 |
+
|
| 1031 |
+
# loss is at first position
|
| 1032 |
+
if "labels" in inputs_dict:
|
| 1033 |
+
correct_outlen += 1 # loss is added to beginning
|
| 1034 |
+
|
| 1035 |
+
self.assertEqual(out_len, correct_outlen)
|
| 1036 |
+
|
| 1037 |
+
# decoder attentions
|
| 1038 |
+
decoder_attentions = outputs.decoder_attentions
|
| 1039 |
+
self.assertIsInstance(decoder_attentions, (list, tuple))
|
| 1040 |
+
self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
|
| 1041 |
+
self.assertListEqual(
|
| 1042 |
+
list(decoder_attentions[0].shape[-3:]),
|
| 1043 |
+
[self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length],
|
| 1044 |
+
)
|
| 1045 |
+
|
| 1046 |
+
# cross attentions
|
| 1047 |
+
cross_attentions = outputs.cross_attentions
|
| 1048 |
+
self.assertIsInstance(cross_attentions, (list, tuple))
|
| 1049 |
+
self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
|
| 1050 |
+
self.assertListEqual(
|
| 1051 |
+
list(cross_attentions[0].shape[-3:]),
|
| 1052 |
+
[
|
| 1053 |
+
self.model_tester.num_attention_heads,
|
| 1054 |
+
(self.model_tester.ngram + 1) * decoder_seq_length,
|
| 1055 |
+
encoder_key_length,
|
| 1056 |
+
],
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
# Check attention is always last and order is fine
|
| 1060 |
+
inputs_dict["output_attentions"] = True
|
| 1061 |
+
inputs_dict["output_hidden_states"] = True
|
| 1062 |
+
model = model_class(config)
|
| 1063 |
+
model.to(torch_device)
|
| 1064 |
+
model.eval()
|
| 1065 |
+
with torch.no_grad():
|
| 1066 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 1067 |
+
|
| 1068 |
+
if hasattr(self.model_tester, "num_hidden_states_types"):
|
| 1069 |
+
added_hidden_states = self.model_tester.num_hidden_states_types
|
| 1070 |
+
elif self.is_encoder_decoder:
|
| 1071 |
+
added_hidden_states = 2
|
| 1072 |
+
else:
|
| 1073 |
+
added_hidden_states = 1
|
| 1074 |
+
self.assertEqual(out_len + added_hidden_states, len(outputs))
|
| 1075 |
+
|
| 1076 |
+
self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 1077 |
+
|
| 1078 |
+
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
|
| 1079 |
+
if chunk_length is not None:
|
| 1080 |
+
self.assertListEqual(
|
| 1081 |
+
list(self_attentions[0].shape[-4:]),
|
| 1082 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length],
|
| 1083 |
+
)
|
| 1084 |
+
else:
|
| 1085 |
+
self.assertListEqual(
|
| 1086 |
+
list(self_attentions[0].shape[-3:]),
|
| 1087 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
def test_retain_grad_hidden_states_attentions(self):
|
| 1091 |
+
# decoder cannot keep gradients
|
| 1092 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 1093 |
+
config.output_hidden_states = True
|
| 1094 |
+
config.output_attentions = True
|
| 1095 |
+
|
| 1096 |
+
# no need to test all models as different heads yield the same functionality
|
| 1097 |
+
model_class = self.all_model_classes[0]
|
| 1098 |
+
model = model_class(config)
|
| 1099 |
+
model.to(torch_device)
|
| 1100 |
+
|
| 1101 |
+
inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 1102 |
+
|
| 1103 |
+
outputs = model(**inputs)
|
| 1104 |
+
output = outputs[0]
|
| 1105 |
+
|
| 1106 |
+
encoder_hidden_states = outputs.encoder_hidden_states[0]
|
| 1107 |
+
encoder_attentions = outputs.encoder_attentions[0]
|
| 1108 |
+
encoder_hidden_states.retain_grad()
|
| 1109 |
+
encoder_attentions.retain_grad()
|
| 1110 |
+
|
| 1111 |
+
output.flatten()[0].backward(retain_graph=True)
|
| 1112 |
+
|
| 1113 |
+
self.assertIsNotNone(encoder_hidden_states.grad)
|
| 1114 |
+
self.assertIsNotNone(encoder_attentions.grad)
|
| 1115 |
+
|
| 1116 |
+
def test_generate_with_head_masking(self):
|
| 1117 |
+
"""Generating with head_masking has not been implemented for ProphetNet models yet."""
|
| 1118 |
+
pass
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
@require_torch
|
| 1122 |
+
class ProphetNetStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
|
| 1123 |
+
all_model_classes = (ProphetNetDecoder, ProphetNetForCausalLM) if is_torch_available() else ()
|
| 1124 |
+
all_generative_model_classes = (ProphetNetForCausalLM,) if is_torch_available() else ()
|
| 1125 |
+
test_pruning = False
|
| 1126 |
+
|
| 1127 |
+
test_resize_embeddings = False
|
| 1128 |
+
is_encoder_decoder = False
|
| 1129 |
+
|
| 1130 |
+
def setUp(self):
|
| 1131 |
+
self.model_tester = ProphetNetStandaloneDecoderModelTester(self, is_training=False)
|
| 1132 |
+
self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)
|
| 1133 |
+
|
| 1134 |
+
def test_config(self):
|
| 1135 |
+
self.config_tester.run_common_tests()
|
| 1136 |
+
|
| 1137 |
+
def test_decoder_model_past(self):
|
| 1138 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 1139 |
+
self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
|
| 1140 |
+
|
| 1141 |
+
def test_decoder_model_attn_mask_past(self):
|
| 1142 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 1143 |
+
self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
|
| 1144 |
+
|
| 1145 |
+
def test_retain_grad_hidden_states_attentions(self):
|
| 1146 |
+
# decoder cannot keep gradients
|
| 1147 |
+
return
|
| 1148 |
+
|
| 1149 |
+
@unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :)
|
| 1150 |
+
def test_left_padding_compatibility(self):
|
| 1151 |
+
pass
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
@require_torch
|
| 1155 |
+
class ProphetNetStandaloneEncoderModelTest(ModelTesterMixin, unittest.TestCase):
|
| 1156 |
+
all_model_classes = (ProphetNetEncoder,) if is_torch_available() else ()
|
| 1157 |
+
test_pruning = False
|
| 1158 |
+
|
| 1159 |
+
test_resize_embeddings = False
|
| 1160 |
+
is_encoder_decoder = False
|
| 1161 |
+
|
| 1162 |
+
def setUp(self):
|
| 1163 |
+
self.model_tester = ProphetNetStandaloneEncoderModelTester(self, is_training=False)
|
| 1164 |
+
self.config_tester = ConfigTester(self, config_class=ProphetNetConfig)
|
| 1165 |
+
|
| 1166 |
+
def test_config(self):
|
| 1167 |
+
self.config_tester.run_common_tests()
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
@require_torch
|
| 1171 |
+
class ProphetNetModelIntegrationTest(unittest.TestCase):
|
| 1172 |
+
@slow
|
| 1173 |
+
def test_pretrained_checkpoint_hidden_states(self):
|
| 1174 |
+
model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased")
|
| 1175 |
+
model.to(torch_device)
|
| 1176 |
+
|
| 1177 |
+
# encoder-decoder outputs
|
| 1178 |
+
encoder_ids = torch.tensor(
|
| 1179 |
+
[
|
| 1180 |
+
[
|
| 1181 |
+
2871,
|
| 1182 |
+
102,
|
| 1183 |
+
2048,
|
| 1184 |
+
3176,
|
| 1185 |
+
2780,
|
| 1186 |
+
1997,
|
| 1187 |
+
2871,
|
| 1188 |
+
26727,
|
| 1189 |
+
2169,
|
| 1190 |
+
2097,
|
| 1191 |
+
12673,
|
| 1192 |
+
1996,
|
| 1193 |
+
8457,
|
| 1194 |
+
2006,
|
| 1195 |
+
2049,
|
| 1196 |
+
8240,
|
| 1197 |
+
2859,
|
| 1198 |
+
2799,
|
| 1199 |
+
1012,
|
| 1200 |
+
2023,
|
| 1201 |
+
6512,
|
| 1202 |
+
2038,
|
| 1203 |
+
2174,
|
| 1204 |
+
13977,
|
| 1205 |
+
2195,
|
| 1206 |
+
25962,
|
| 1207 |
+
1012,
|
| 1208 |
+
102,
|
| 1209 |
+
]
|
| 1210 |
+
]
|
| 1211 |
+
).to(torch_device)
|
| 1212 |
+
|
| 1213 |
+
decoder_prev_ids = torch.tensor([[102, 2129, 2116, 2372, 2024, 2006, 2169, 1997, 2122, 2048, 2780, 1029]]).to(
|
| 1214 |
+
torch_device
|
| 1215 |
+
)
|
| 1216 |
+
output = model(
|
| 1217 |
+
input_ids=encoder_ids,
|
| 1218 |
+
attention_mask=None,
|
| 1219 |
+
encoder_outputs=None,
|
| 1220 |
+
decoder_input_ids=decoder_prev_ids,
|
| 1221 |
+
)
|
| 1222 |
+
output_predited_logits = output[0]
|
| 1223 |
+
expected_shape = torch.Size((1, 12, 30522))
|
| 1224 |
+
self.assertEqual(output_predited_logits.shape, expected_shape)
|
| 1225 |
+
expected_slice = torch.tensor(
|
| 1226 |
+
[[[-7.7729, -8.0343, -8.26001], [-7.74213, -7.8629, -8.6000], [-7.7328, -7.8269, -8.5264]]]
|
| 1227 |
+
).to(torch_device)
|
| 1228 |
+
# self.assertTrue(torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4))
|
| 1229 |
+
assert torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4)
|
| 1230 |
+
|
| 1231 |
+
# encoder outputs
|
| 1232 |
+
encoder_outputs = model.prophetnet.encoder(encoder_ids)[0]
|
| 1233 |
+
expected_encoder_outputs_slice = torch.tensor(
|
| 1234 |
+
[[[-0.2526, -0.1951, -0.2185], [-0.8923, 0.2992, -0.4623], [-0.4585, 0.0165, -0.6652]]]
|
| 1235 |
+
).to(torch_device)
|
| 1236 |
+
expected_shape_encoder = torch.Size((1, 28, 1024))
|
| 1237 |
+
self.assertEqual(encoder_outputs.shape, expected_shape_encoder)
|
| 1238 |
+
# self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4))
|
| 1239 |
+
assert torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4)
|
| 1240 |
+
|
| 1241 |
+
# decoder outputs
|
| 1242 |
+
decoder_outputs = model.prophetnet.decoder(decoder_prev_ids, encoder_hidden_states=encoder_outputs)
|
| 1243 |
+
predicting_streams = decoder_outputs[1].view(1, model.config.ngram, 12, -1)
|
| 1244 |
+
predicting_streams_logits = model.lm_head(predicting_streams)
|
| 1245 |
+
next_first_stream_logits = predicting_streams_logits[:, 0]
|
| 1246 |
+
# self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4))
|
| 1247 |
+
assert torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4)
|
| 1248 |
+
|
| 1249 |
+
@slow
|
| 1250 |
+
def test_cnndm_inference(self):
|
| 1251 |
+
model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased-cnndm")
|
| 1252 |
+
model.config.max_length = 512
|
| 1253 |
+
model.to(torch_device)
|
| 1254 |
+
|
| 1255 |
+
tokenizer = ProphetNetTokenizer.from_pretrained("microsoft/prophetnet-large-uncased-cnndm")
|
| 1256 |
+
|
| 1257 |
+
ARTICLE_TO_SUMMARIZE = (
|
| 1258 |
+
"USTC was founded in Beijing by the Chinese Academy of Sciences (CAS) in September 1958. The Director of"
|
| 1259 |
+
" CAS, Mr. Guo Moruo was appointed the first president of USTC. USTC's founding mission was to develop a"
|
| 1260 |
+
" high-level science and technology workforce, as deemed critical for development of China's economy,"
|
| 1261 |
+
' defense, and science and technology education. The establishment was hailed as "A Major Event in the'
|
| 1262 |
+
' History of Chinese Education and Science." CAS has supported USTC by combining most of its institutes'
|
| 1263 |
+
" with the departments of the university. USTC is listed in the top 16 national key universities, becoming"
|
| 1264 |
+
" the youngest national key university.".lower()
|
| 1265 |
+
)
|
| 1266 |
+
input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=511, return_tensors="pt").input_ids
|
| 1267 |
+
|
| 1268 |
+
input_ids = input_ids.to(torch_device)
|
| 1269 |
+
|
| 1270 |
+
summary_ids = model.generate(
|
| 1271 |
+
input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True
|
| 1272 |
+
)
|
| 1273 |
+
EXPECTED_SUMMARIZE_512 = (
|
| 1274 |
+
"us ##tc was founded by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc is listed in the"
|
| 1275 |
+
" top 16 national key universities ."
|
| 1276 |
+
)
|
| 1277 |
+
generated_titles = [
|
| 1278 |
+
" ".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids
|
| 1279 |
+
]
|
| 1280 |
+
self.assertListEqual(
|
| 1281 |
+
[EXPECTED_SUMMARIZE_512],
|
| 1282 |
+
generated_titles,
|
| 1283 |
+
)
|
| 1284 |
+
input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=99, return_tensors="pt").input_ids
|
| 1285 |
+
input_ids = input_ids.to(torch_device)
|
| 1286 |
+
# actually 98 tokens are used. max_length=100 contains bos and eos.
|
| 1287 |
+
summary_ids = model.generate(
|
| 1288 |
+
input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True
|
| 1289 |
+
)
|
| 1290 |
+
EXPECTED_SUMMARIZE_100 = (
|
| 1291 |
+
r"us ##tc was founded in beijing by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc "
|
| 1292 |
+
"'"
|
| 1293 |
+
" s founding mission was to develop a high - level science and technology workforce . [X_SEP]"
|
| 1294 |
+
' establishment hailed as " a major event in the history of chinese education and science "'
|
| 1295 |
+
)
|
| 1296 |
+
generated_titles = [
|
| 1297 |
+
" ".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids
|
| 1298 |
+
]
|
| 1299 |
+
self.assertListEqual(
|
| 1300 |
+
[EXPECTED_SUMMARIZE_100],
|
| 1301 |
+
generated_titles,
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
@slow
|
| 1305 |
+
def test_question_gen_inference(self):
|
| 1306 |
+
model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased-squad-qg")
|
| 1307 |
+
model.to(torch_device)
|
| 1308 |
+
|
| 1309 |
+
tokenizer = ProphetNetTokenizer.from_pretrained("microsoft/prophetnet-large-uncased-squad-qg")
|
| 1310 |
+
|
| 1311 |
+
INPUTS = [
|
| 1312 |
+
"Bill Gates [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.",
|
| 1313 |
+
"1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.",
|
| 1314 |
+
"April 4, 1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.",
|
| 1315 |
+
]
|
| 1316 |
+
|
| 1317 |
+
input_ids = tokenizer(INPUTS, truncation=True, padding=True, return_tensors="pt").input_ids
|
| 1318 |
+
input_ids = input_ids.to(torch_device)
|
| 1319 |
+
|
| 1320 |
+
gen_output = model.generate(input_ids, num_beams=5, early_stopping=True)
|
| 1321 |
+
generated_questions = tokenizer.batch_decode(gen_output, skip_special_tokens=True)
|
| 1322 |
+
|
| 1323 |
+
EXPECTED_QUESTIONS = [
|
| 1324 |
+
"along with paul allen, who founded microsoft?",
|
| 1325 |
+
"what year was microsoft founded?",
|
| 1326 |
+
"when was microsoft founded?",
|
| 1327 |
+
]
|
| 1328 |
+
|
| 1329 |
+
self.assertListEqual(
|
| 1330 |
+
EXPECTED_QUESTIONS,
|
| 1331 |
+
generated_questions,
|
| 1332 |
+
)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_tokenization_prophetnet.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import BatchEncoding
|
| 21 |
+
from transformers.models.bert.tokenization_bert import (
|
| 22 |
+
BasicTokenizer,
|
| 23 |
+
WordpieceTokenizer,
|
| 24 |
+
_is_control,
|
| 25 |
+
_is_punctuation,
|
| 26 |
+
_is_whitespace,
|
| 27 |
+
)
|
| 28 |
+
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
|
| 29 |
+
from transformers.testing_utils import require_torch, slow
|
| 30 |
+
|
| 31 |
+
from ...test_tokenization_common import TokenizerTesterMixin
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ProphetNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 35 |
+
tokenizer_class = ProphetNetTokenizer
|
| 36 |
+
test_rust_tokenizer = False
|
| 37 |
+
|
| 38 |
+
def setUp(self):
|
| 39 |
+
super().setUp()
|
| 40 |
+
|
| 41 |
+
vocab_tokens = [
|
| 42 |
+
"[UNK]",
|
| 43 |
+
"[CLS]",
|
| 44 |
+
"[SEP]",
|
| 45 |
+
"[PAD]",
|
| 46 |
+
"[MASK]",
|
| 47 |
+
"want",
|
| 48 |
+
"##want",
|
| 49 |
+
"##ed",
|
| 50 |
+
"wa",
|
| 51 |
+
"un",
|
| 52 |
+
"runn",
|
| 53 |
+
"##ing",
|
| 54 |
+
",",
|
| 55 |
+
"low",
|
| 56 |
+
"lowest",
|
| 57 |
+
]
|
| 58 |
+
self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
|
| 59 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 60 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 61 |
+
|
| 62 |
+
def get_input_output_texts(self, tokenizer):
|
| 63 |
+
input_text = "UNwant\u00E9d,running"
|
| 64 |
+
output_text = "unwanted, running"
|
| 65 |
+
return input_text, output_text
|
| 66 |
+
|
| 67 |
+
def test_full_tokenizer(self):
|
| 68 |
+
tokenizer = self.tokenizer_class(self.vocab_file)
|
| 69 |
+
|
| 70 |
+
tokens = tokenizer.tokenize("UNwant\u00E9d,running")
|
| 71 |
+
self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
|
| 72 |
+
self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [9, 6, 7, 12, 10, 11])
|
| 73 |
+
|
| 74 |
+
def test_chinese(self):
|
| 75 |
+
tokenizer = BasicTokenizer()
|
| 76 |
+
|
| 77 |
+
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"])
|
| 78 |
+
|
| 79 |
+
def test_basic_tokenizer_lower(self):
|
| 80 |
+
tokenizer = BasicTokenizer(do_lower_case=True)
|
| 81 |
+
|
| 82 |
+
self.assertListEqual(
|
| 83 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"]
|
| 84 |
+
)
|
| 85 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 86 |
+
|
| 87 |
+
def test_basic_tokenizer_lower_strip_accents_false(self):
|
| 88 |
+
tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False)
|
| 89 |
+
|
| 90 |
+
self.assertListEqual(
|
| 91 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"]
|
| 92 |
+
)
|
| 93 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"])
|
| 94 |
+
|
| 95 |
+
def test_basic_tokenizer_lower_strip_accents_true(self):
|
| 96 |
+
tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True)
|
| 97 |
+
|
| 98 |
+
self.assertListEqual(
|
| 99 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 100 |
+
)
|
| 101 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 102 |
+
|
| 103 |
+
def test_basic_tokenizer_lower_strip_accents_default(self):
|
| 104 |
+
tokenizer = BasicTokenizer(do_lower_case=True)
|
| 105 |
+
|
| 106 |
+
self.assertListEqual(
|
| 107 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 108 |
+
)
|
| 109 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 110 |
+
|
| 111 |
+
def test_basic_tokenizer_no_lower(self):
|
| 112 |
+
tokenizer = BasicTokenizer(do_lower_case=False)
|
| 113 |
+
|
| 114 |
+
self.assertListEqual(
|
| 115 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"]
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
def test_basic_tokenizer_no_lower_strip_accents_false(self):
|
| 119 |
+
tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False)
|
| 120 |
+
|
| 121 |
+
self.assertListEqual(
|
| 122 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"]
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def test_basic_tokenizer_no_lower_strip_accents_true(self):
|
| 126 |
+
tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True)
|
| 127 |
+
|
| 128 |
+
self.assertListEqual(
|
| 129 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"]
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def test_basic_tokenizer_respects_never_split_tokens(self):
|
| 133 |
+
tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"])
|
| 134 |
+
|
| 135 |
+
self.assertListEqual(
|
| 136 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def test_wordpiece_tokenizer(self):
|
| 140 |
+
vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
|
| 141 |
+
|
| 142 |
+
vocab = {}
|
| 143 |
+
for i, token in enumerate(vocab_tokens):
|
| 144 |
+
vocab[token] = i
|
| 145 |
+
tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]")
|
| 146 |
+
|
| 147 |
+
self.assertListEqual(tokenizer.tokenize(""), [])
|
| 148 |
+
|
| 149 |
+
self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"])
|
| 150 |
+
|
| 151 |
+
self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
|
| 152 |
+
|
| 153 |
+
@require_torch
|
| 154 |
+
def test_prepare_batch(self):
|
| 155 |
+
tokenizer = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased")
|
| 156 |
+
|
| 157 |
+
src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."]
|
| 158 |
+
expected_src_tokens = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102]
|
| 159 |
+
batch = tokenizer(src_text, padding=True, return_tensors="pt")
|
| 160 |
+
self.assertIsInstance(batch, BatchEncoding)
|
| 161 |
+
result = list(batch.input_ids.numpy()[0])
|
| 162 |
+
self.assertListEqual(expected_src_tokens, result)
|
| 163 |
+
|
| 164 |
+
self.assertEqual((2, 9), batch.input_ids.shape)
|
| 165 |
+
self.assertEqual((2, 9), batch.attention_mask.shape)
|
| 166 |
+
|
| 167 |
+
def test_is_whitespace(self):
|
| 168 |
+
self.assertTrue(_is_whitespace(" "))
|
| 169 |
+
self.assertTrue(_is_whitespace("\t"))
|
| 170 |
+
self.assertTrue(_is_whitespace("\r"))
|
| 171 |
+
self.assertTrue(_is_whitespace("\n"))
|
| 172 |
+
self.assertTrue(_is_whitespace("\u00A0"))
|
| 173 |
+
|
| 174 |
+
self.assertFalse(_is_whitespace("A"))
|
| 175 |
+
self.assertFalse(_is_whitespace("-"))
|
| 176 |
+
|
| 177 |
+
def test_is_control(self):
|
| 178 |
+
self.assertTrue(_is_control("\u0005"))
|
| 179 |
+
|
| 180 |
+
self.assertFalse(_is_control("A"))
|
| 181 |
+
self.assertFalse(_is_control(" "))
|
| 182 |
+
self.assertFalse(_is_control("\t"))
|
| 183 |
+
self.assertFalse(_is_control("\r"))
|
| 184 |
+
|
| 185 |
+
def test_is_punctuation(self):
|
| 186 |
+
self.assertTrue(_is_punctuation("-"))
|
| 187 |
+
self.assertTrue(_is_punctuation("$"))
|
| 188 |
+
self.assertTrue(_is_punctuation("`"))
|
| 189 |
+
self.assertTrue(_is_punctuation("."))
|
| 190 |
+
|
| 191 |
+
self.assertFalse(_is_punctuation("A"))
|
| 192 |
+
self.assertFalse(_is_punctuation(" "))
|
| 193 |
+
|
| 194 |
+
@slow
|
| 195 |
+
def test_sequence_builders(self):
|
| 196 |
+
tokenizer = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased")
|
| 197 |
+
|
| 198 |
+
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
| 199 |
+
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
| 200 |
+
|
| 201 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 202 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 203 |
+
|
| 204 |
+
assert encoded_sentence == text + [102]
|
| 205 |
+
assert encoded_pair == text + [102] + text_2 + [102]
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_image_processing_pvt.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers.testing_utils import require_torch, require_vision
|
| 20 |
+
from transformers.utils import is_vision_available
|
| 21 |
+
|
| 22 |
+
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_vision_available():
|
| 26 |
+
from transformers import PvtImageProcessor
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class PvtImageProcessingTester(unittest.TestCase):
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
parent,
|
| 33 |
+
batch_size=7,
|
| 34 |
+
num_channels=3,
|
| 35 |
+
image_size=18,
|
| 36 |
+
min_resolution=30,
|
| 37 |
+
max_resolution=400,
|
| 38 |
+
do_resize=True,
|
| 39 |
+
size=None,
|
| 40 |
+
do_normalize=True,
|
| 41 |
+
image_mean=[0.485, 0.456, 0.406],
|
| 42 |
+
image_std=[0.229, 0.224, 0.225],
|
| 43 |
+
):
|
| 44 |
+
size = size if size is not None else {"height": 18, "width": 18}
|
| 45 |
+
self.parent = parent
|
| 46 |
+
self.batch_size = batch_size
|
| 47 |
+
self.num_channels = num_channels
|
| 48 |
+
self.image_size = image_size
|
| 49 |
+
self.min_resolution = min_resolution
|
| 50 |
+
self.max_resolution = max_resolution
|
| 51 |
+
self.do_resize = do_resize
|
| 52 |
+
self.size = size
|
| 53 |
+
self.do_normalize = do_normalize
|
| 54 |
+
self.image_mean = image_mean
|
| 55 |
+
self.image_std = image_std
|
| 56 |
+
|
| 57 |
+
def prepare_image_processor_dict(self):
|
| 58 |
+
return {
|
| 59 |
+
"image_mean": self.image_mean,
|
| 60 |
+
"image_std": self.image_std,
|
| 61 |
+
"do_normalize": self.do_normalize,
|
| 62 |
+
"do_resize": self.do_resize,
|
| 63 |
+
"size": self.size,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
def expected_output_image_shape(self, images):
|
| 67 |
+
return self.num_channels, self.size["height"], self.size["width"]
|
| 68 |
+
|
| 69 |
+
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
| 70 |
+
return prepare_image_inputs(
|
| 71 |
+
batch_size=self.batch_size,
|
| 72 |
+
num_channels=self.num_channels,
|
| 73 |
+
min_resolution=self.min_resolution,
|
| 74 |
+
max_resolution=self.max_resolution,
|
| 75 |
+
equal_resolution=equal_resolution,
|
| 76 |
+
numpify=numpify,
|
| 77 |
+
torchify=torchify,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@require_torch
|
| 82 |
+
@require_vision
|
| 83 |
+
class PvtImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
|
| 84 |
+
image_processing_class = PvtImageProcessor if is_vision_available() else None
|
| 85 |
+
|
| 86 |
+
def setUp(self):
|
| 87 |
+
self.image_processor_tester = PvtImageProcessingTester(self)
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def image_processor_dict(self):
|
| 91 |
+
return self.image_processor_tester.prepare_image_processor_dict()
|
| 92 |
+
|
| 93 |
+
def test_image_processor_properties(self):
|
| 94 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 95 |
+
self.assertTrue(hasattr(image_processing, "image_mean"))
|
| 96 |
+
self.assertTrue(hasattr(image_processing, "image_std"))
|
| 97 |
+
self.assertTrue(hasattr(image_processing, "do_normalize"))
|
| 98 |
+
self.assertTrue(hasattr(image_processing, "do_resize"))
|
| 99 |
+
self.assertTrue(hasattr(image_processing, "size"))
|
| 100 |
+
|
| 101 |
+
def test_image_processor_from_dict_with_kwargs(self):
|
| 102 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
|
| 103 |
+
self.assertEqual(image_processor.size, {"height": 18, "width": 18})
|
| 104 |
+
|
| 105 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42)
|
| 106 |
+
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_modeling_pvt.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch Pvt model. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import is_torch_available, is_vision_available
|
| 21 |
+
from transformers.models.auto import get_values
|
| 22 |
+
from transformers.testing_utils import (
|
| 23 |
+
require_accelerate,
|
| 24 |
+
require_torch,
|
| 25 |
+
require_torch_accelerator,
|
| 26 |
+
require_torch_fp16,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
from ...test_configuration_common import ConfigTester
|
| 32 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 33 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_torch_available():
|
| 37 |
+
import torch
|
| 38 |
+
|
| 39 |
+
from transformers import MODEL_MAPPING, PvtConfig, PvtForImageClassification, PvtImageProcessor, PvtModel
|
| 40 |
+
from transformers.models.pvt.modeling_pvt import PVT_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if is_vision_available():
|
| 44 |
+
from PIL import Image
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class PvtConfigTester(ConfigTester):
|
| 48 |
+
def run_common_tests(self):
|
| 49 |
+
config = self.config_class(**self.inputs_dict)
|
| 50 |
+
self.parent.assertTrue(hasattr(config, "hidden_sizes"))
|
| 51 |
+
self.parent.assertTrue(hasattr(config, "num_encoder_blocks"))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PvtModelTester:
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
parent,
|
| 58 |
+
batch_size=13,
|
| 59 |
+
image_size=64,
|
| 60 |
+
num_channels=3,
|
| 61 |
+
num_encoder_blocks=4,
|
| 62 |
+
depths=[2, 2, 2, 2],
|
| 63 |
+
sr_ratios=[8, 4, 2, 1],
|
| 64 |
+
hidden_sizes=[16, 32, 64, 128],
|
| 65 |
+
downsampling_rates=[1, 4, 8, 16],
|
| 66 |
+
num_attention_heads=[1, 2, 4, 8],
|
| 67 |
+
is_training=True,
|
| 68 |
+
use_labels=True,
|
| 69 |
+
hidden_act="gelu",
|
| 70 |
+
hidden_dropout_prob=0.1,
|
| 71 |
+
attention_probs_dropout_prob=0.1,
|
| 72 |
+
initializer_range=0.02,
|
| 73 |
+
num_labels=3,
|
| 74 |
+
scope=None,
|
| 75 |
+
):
|
| 76 |
+
self.parent = parent
|
| 77 |
+
self.batch_size = batch_size
|
| 78 |
+
self.image_size = image_size
|
| 79 |
+
self.num_channels = num_channels
|
| 80 |
+
self.num_encoder_blocks = num_encoder_blocks
|
| 81 |
+
self.sr_ratios = sr_ratios
|
| 82 |
+
self.depths = depths
|
| 83 |
+
self.hidden_sizes = hidden_sizes
|
| 84 |
+
self.downsampling_rates = downsampling_rates
|
| 85 |
+
self.num_attention_heads = num_attention_heads
|
| 86 |
+
self.is_training = is_training
|
| 87 |
+
self.use_labels = use_labels
|
| 88 |
+
self.hidden_act = hidden_act
|
| 89 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 90 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 91 |
+
self.initializer_range = initializer_range
|
| 92 |
+
self.num_labels = num_labels
|
| 93 |
+
self.scope = scope
|
| 94 |
+
|
| 95 |
+
def prepare_config_and_inputs(self):
|
| 96 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 97 |
+
|
| 98 |
+
labels = None
|
| 99 |
+
if self.use_labels:
|
| 100 |
+
labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
|
| 101 |
+
|
| 102 |
+
config = self.get_config()
|
| 103 |
+
return config, pixel_values, labels
|
| 104 |
+
|
| 105 |
+
def get_config(self):
|
| 106 |
+
return PvtConfig(
|
| 107 |
+
image_size=self.image_size,
|
| 108 |
+
num_channels=self.num_channels,
|
| 109 |
+
num_encoder_blocks=self.num_encoder_blocks,
|
| 110 |
+
depths=self.depths,
|
| 111 |
+
hidden_sizes=self.hidden_sizes,
|
| 112 |
+
num_attention_heads=self.num_attention_heads,
|
| 113 |
+
hidden_act=self.hidden_act,
|
| 114 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 115 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 116 |
+
initializer_range=self.initializer_range,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 120 |
+
model = PvtModel(config=config)
|
| 121 |
+
model.to(torch_device)
|
| 122 |
+
model.eval()
|
| 123 |
+
result = model(pixel_values)
|
| 124 |
+
self.parent.assertIsNotNone(result.last_hidden_state)
|
| 125 |
+
|
| 126 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 127 |
+
config.num_labels = self.type_sequence_label_size
|
| 128 |
+
model = PvtForImageClassification(config)
|
| 129 |
+
model.to(torch_device)
|
| 130 |
+
model.eval()
|
| 131 |
+
result = model(pixel_values, labels=labels)
|
| 132 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 133 |
+
|
| 134 |
+
# test greyscale images
|
| 135 |
+
config.num_channels = 1
|
| 136 |
+
model = PvtForImageClassification(config)
|
| 137 |
+
model.to(torch_device)
|
| 138 |
+
model.eval()
|
| 139 |
+
|
| 140 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 141 |
+
result = model(pixel_values)
|
| 142 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 143 |
+
|
| 144 |
+
def prepare_config_and_inputs_for_common(self):
|
| 145 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 146 |
+
config, pixel_values, labels = config_and_inputs
|
| 147 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 148 |
+
return config, inputs_dict
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# We will verify our results on an image of cute cats
|
| 152 |
+
def prepare_img():
|
| 153 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 154 |
+
return image
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@require_torch
|
| 158 |
+
class PvtModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 159 |
+
all_model_classes = (PvtModel, PvtForImageClassification) if is_torch_available() else ()
|
| 160 |
+
pipeline_model_mapping = (
|
| 161 |
+
{"feature-extraction": PvtModel, "image-classification": PvtForImageClassification}
|
| 162 |
+
if is_torch_available()
|
| 163 |
+
else {}
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
test_head_masking = False
|
| 167 |
+
test_pruning = False
|
| 168 |
+
test_resize_embeddings = False
|
| 169 |
+
test_torchscript = False
|
| 170 |
+
has_attentions = False
|
| 171 |
+
|
| 172 |
+
def setUp(self):
|
| 173 |
+
self.model_tester = PvtModelTester(self)
|
| 174 |
+
self.config_tester = PvtConfigTester(self, config_class=PvtConfig)
|
| 175 |
+
|
| 176 |
+
def test_config(self):
|
| 177 |
+
self.config_tester.run_common_tests()
|
| 178 |
+
|
| 179 |
+
def test_model(self):
|
| 180 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 181 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 182 |
+
|
| 183 |
+
@unittest.skip("Pvt does not use inputs_embeds")
|
| 184 |
+
def test_inputs_embeds(self):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
@unittest.skip("Pvt does not have get_input_embeddings method and get_output_embeddings methods")
|
| 188 |
+
def test_model_common_attributes(self):
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
def test_initialization(self):
|
| 192 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 193 |
+
|
| 194 |
+
for model_class in self.all_model_classes:
|
| 195 |
+
model = model_class(config=config)
|
| 196 |
+
for name, param in model.named_parameters():
|
| 197 |
+
self.assertTrue(
|
| 198 |
+
-1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0,
|
| 199 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
def test_hidden_states_output(self):
|
| 203 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 204 |
+
model = model_class(config)
|
| 205 |
+
model.to(torch_device)
|
| 206 |
+
model.eval()
|
| 207 |
+
|
| 208 |
+
with torch.no_grad():
|
| 209 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 210 |
+
|
| 211 |
+
hidden_states = outputs.hidden_states
|
| 212 |
+
|
| 213 |
+
expected_num_layers = sum(self.model_tester.depths) + 1
|
| 214 |
+
self.assertEqual(len(hidden_states), expected_num_layers)
|
| 215 |
+
|
| 216 |
+
# verify the first hidden states (first block)
|
| 217 |
+
self.assertListEqual(
|
| 218 |
+
list(hidden_states[0].shape[-3:]),
|
| 219 |
+
[
|
| 220 |
+
self.model_tester.batch_size,
|
| 221 |
+
(self.model_tester.image_size // 4) ** 2,
|
| 222 |
+
self.model_tester.image_size // 4,
|
| 223 |
+
],
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 227 |
+
|
| 228 |
+
for model_class in self.all_model_classes:
|
| 229 |
+
inputs_dict["output_hidden_states"] = True
|
| 230 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 231 |
+
|
| 232 |
+
# check that output_hidden_states also work using config
|
| 233 |
+
del inputs_dict["output_hidden_states"]
|
| 234 |
+
config.output_hidden_states = True
|
| 235 |
+
|
| 236 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 237 |
+
|
| 238 |
+
def test_training(self):
|
| 239 |
+
if not self.model_tester.is_training:
|
| 240 |
+
return
|
| 241 |
+
|
| 242 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 243 |
+
config.return_dict = True
|
| 244 |
+
|
| 245 |
+
for model_class in self.all_model_classes:
|
| 246 |
+
if model_class in get_values(MODEL_MAPPING):
|
| 247 |
+
continue
|
| 248 |
+
model = model_class(config)
|
| 249 |
+
model.to(torch_device)
|
| 250 |
+
model.train()
|
| 251 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 252 |
+
loss = model(**inputs).loss
|
| 253 |
+
loss.backward()
|
| 254 |
+
|
| 255 |
+
@slow
|
| 256 |
+
def test_model_from_pretrained(self):
|
| 257 |
+
for model_name in PVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 258 |
+
model = PvtModel.from_pretrained(model_name)
|
| 259 |
+
self.assertIsNotNone(model)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@require_torch
|
| 263 |
+
class PvtModelIntegrationTest(unittest.TestCase):
|
| 264 |
+
@slow
|
| 265 |
+
def test_inference_image_classification(self):
|
| 266 |
+
# only resize + normalize
|
| 267 |
+
image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224")
|
| 268 |
+
model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval()
|
| 269 |
+
|
| 270 |
+
image = prepare_img()
|
| 271 |
+
encoded_inputs = image_processor(images=image, return_tensors="pt")
|
| 272 |
+
pixel_values = encoded_inputs.pixel_values.to(torch_device)
|
| 273 |
+
|
| 274 |
+
with torch.no_grad():
|
| 275 |
+
outputs = model(pixel_values)
|
| 276 |
+
|
| 277 |
+
expected_shape = torch.Size((1, model.config.num_labels))
|
| 278 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 279 |
+
|
| 280 |
+
expected_slice = torch.tensor([-1.4192, -1.9158, -0.9702]).to(torch_device)
|
| 281 |
+
|
| 282 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
| 283 |
+
|
| 284 |
+
@slow
|
| 285 |
+
def test_inference_model(self):
|
| 286 |
+
model = PvtModel.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval()
|
| 287 |
+
|
| 288 |
+
image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224")
|
| 289 |
+
image = prepare_img()
|
| 290 |
+
inputs = image_processor(images=image, return_tensors="pt")
|
| 291 |
+
pixel_values = inputs.pixel_values.to(torch_device)
|
| 292 |
+
|
| 293 |
+
# forward pass
|
| 294 |
+
with torch.no_grad():
|
| 295 |
+
outputs = model(pixel_values)
|
| 296 |
+
|
| 297 |
+
# verify the logits
|
| 298 |
+
expected_shape = torch.Size((1, 50, 512))
|
| 299 |
+
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
| 300 |
+
|
| 301 |
+
expected_slice = torch.tensor(
|
| 302 |
+
[[-0.3086, 1.0402, 1.1816], [-0.2880, 0.5781, 0.6124], [0.1480, 0.6129, -0.0590]]
|
| 303 |
+
).to(torch_device)
|
| 304 |
+
|
| 305 |
+
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
| 306 |
+
|
| 307 |
+
@slow
|
| 308 |
+
@require_accelerate
|
| 309 |
+
@require_torch_accelerator
|
| 310 |
+
@require_torch_fp16
|
| 311 |
+
def test_inference_fp16(self):
|
| 312 |
+
r"""
|
| 313 |
+
A small test to make sure that inference work in half precision without any problem.
|
| 314 |
+
"""
|
| 315 |
+
model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224", torch_dtype=torch.float16)
|
| 316 |
+
model.to(torch_device)
|
| 317 |
+
image_processor = PvtImageProcessor(size=224)
|
| 318 |
+
|
| 319 |
+
image = prepare_img()
|
| 320 |
+
inputs = image_processor(images=image, return_tensors="pt")
|
| 321 |
+
pixel_values = inputs.pixel_values.to(torch_device, dtype=torch.float16)
|
| 322 |
+
|
| 323 |
+
# forward pass to make sure inference works in fp16
|
| 324 |
+
with torch.no_grad():
|
| 325 |
+
_ = model(pixel_values)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/test_modeling_qdqbert.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
# Copyright 2021 NVIDIA Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" Testing suite for the PyTorch QDQBERT model. """
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import QDQBertConfig, is_torch_available
|
| 22 |
+
from transformers.testing_utils import require_pytorch_quantization, require_torch, slow, torch_device
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
QDQBertForMaskedLM,
|
| 34 |
+
QDQBertForMultipleChoice,
|
| 35 |
+
QDQBertForNextSentencePrediction,
|
| 36 |
+
QDQBertForQuestionAnswering,
|
| 37 |
+
QDQBertForSequenceClassification,
|
| 38 |
+
QDQBertForTokenClassification,
|
| 39 |
+
QDQBertLMHeadModel,
|
| 40 |
+
QDQBertModel,
|
| 41 |
+
)
|
| 42 |
+
from transformers.models.qdqbert.modeling_qdqbert import QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class QDQBertModelTester:
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
parent,
|
| 49 |
+
batch_size=13,
|
| 50 |
+
seq_length=7,
|
| 51 |
+
is_training=True,
|
| 52 |
+
use_input_mask=True,
|
| 53 |
+
use_token_type_ids=True,
|
| 54 |
+
use_labels=True,
|
| 55 |
+
vocab_size=99,
|
| 56 |
+
hidden_size=32,
|
| 57 |
+
num_hidden_layers=2,
|
| 58 |
+
num_attention_heads=4,
|
| 59 |
+
intermediate_size=37,
|
| 60 |
+
hidden_act="gelu",
|
| 61 |
+
hidden_dropout_prob=0.1,
|
| 62 |
+
attention_probs_dropout_prob=0.1,
|
| 63 |
+
max_position_embeddings=512,
|
| 64 |
+
type_vocab_size=16,
|
| 65 |
+
type_sequence_label_size=2,
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
num_labels=3,
|
| 68 |
+
num_choices=4,
|
| 69 |
+
scope=None,
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = batch_size
|
| 73 |
+
self.seq_length = seq_length
|
| 74 |
+
self.is_training = is_training
|
| 75 |
+
self.use_input_mask = use_input_mask
|
| 76 |
+
self.use_token_type_ids = use_token_type_ids
|
| 77 |
+
self.use_labels = use_labels
|
| 78 |
+
self.vocab_size = vocab_size
|
| 79 |
+
self.hidden_size = hidden_size
|
| 80 |
+
self.num_hidden_layers = num_hidden_layers
|
| 81 |
+
self.num_attention_heads = num_attention_heads
|
| 82 |
+
self.intermediate_size = intermediate_size
|
| 83 |
+
self.hidden_act = hidden_act
|
| 84 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 85 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 86 |
+
self.max_position_embeddings = max_position_embeddings
|
| 87 |
+
self.type_vocab_size = type_vocab_size
|
| 88 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.num_labels = num_labels
|
| 91 |
+
self.num_choices = num_choices
|
| 92 |
+
self.scope = scope
|
| 93 |
+
|
| 94 |
+
def prepare_config_and_inputs(self):
|
| 95 |
+
# Set default quantizers before creating the model.
|
| 96 |
+
import pytorch_quantization.nn as quant_nn
|
| 97 |
+
from pytorch_quantization.tensor_quant import QuantDescriptor
|
| 98 |
+
|
| 99 |
+
# The default tensor quantizer is set to use Max calibration method
|
| 100 |
+
input_desc = QuantDescriptor(num_bits=8, calib_method="max")
|
| 101 |
+
# The default tensor quantizer is set to be per-channel quantization for weights
|
| 102 |
+
weight_desc = QuantDescriptor(num_bits=8, axis=((0,)))
|
| 103 |
+
quant_nn.QuantLinear.set_default_quant_desc_input(input_desc)
|
| 104 |
+
quant_nn.QuantLinear.set_default_quant_desc_weight(weight_desc)
|
| 105 |
+
# 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.
|
| 106 |
+
quant_nn.TensorQuantizer.use_fb_fake_quant = True
|
| 107 |
+
|
| 108 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 109 |
+
|
| 110 |
+
input_mask = None
|
| 111 |
+
if self.use_input_mask:
|
| 112 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 113 |
+
|
| 114 |
+
token_type_ids = None
|
| 115 |
+
if self.use_token_type_ids:
|
| 116 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 117 |
+
|
| 118 |
+
sequence_labels = None
|
| 119 |
+
token_labels = None
|
| 120 |
+
choice_labels = None
|
| 121 |
+
if self.use_labels:
|
| 122 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 123 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 124 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 125 |
+
|
| 126 |
+
config = self.get_config()
|
| 127 |
+
|
| 128 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 129 |
+
|
| 130 |
+
def get_config(self):
|
| 131 |
+
return QDQBertConfig(
|
| 132 |
+
vocab_size=self.vocab_size,
|
| 133 |
+
hidden_size=self.hidden_size,
|
| 134 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 135 |
+
num_attention_heads=self.num_attention_heads,
|
| 136 |
+
intermediate_size=self.intermediate_size,
|
| 137 |
+
hidden_act=self.hidden_act,
|
| 138 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 139 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 140 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 141 |
+
type_vocab_size=self.type_vocab_size,
|
| 142 |
+
is_decoder=False,
|
| 143 |
+
initializer_range=self.initializer_range,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 147 |
+
(
|
| 148 |
+
config,
|
| 149 |
+
input_ids,
|
| 150 |
+
token_type_ids,
|
| 151 |
+
input_mask,
|
| 152 |
+
sequence_labels,
|
| 153 |
+
token_labels,
|
| 154 |
+
choice_labels,
|
| 155 |
+
) = self.prepare_config_and_inputs()
|
| 156 |
+
|
| 157 |
+
config.is_decoder = True
|
| 158 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 159 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 160 |
+
|
| 161 |
+
return (
|
| 162 |
+
config,
|
| 163 |
+
input_ids,
|
| 164 |
+
token_type_ids,
|
| 165 |
+
input_mask,
|
| 166 |
+
sequence_labels,
|
| 167 |
+
token_labels,
|
| 168 |
+
choice_labels,
|
| 169 |
+
encoder_hidden_states,
|
| 170 |
+
encoder_attention_mask,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def create_and_check_model(
|
| 174 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 175 |
+
):
|
| 176 |
+
model = QDQBertModel(config=config)
|
| 177 |
+
model.to(torch_device)
|
| 178 |
+
model.eval()
|
| 179 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 180 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 181 |
+
result = model(input_ids)
|
| 182 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 183 |
+
|
| 184 |
+
def create_and_check_model_as_decoder(
|
| 185 |
+
self,
|
| 186 |
+
config,
|
| 187 |
+
input_ids,
|
| 188 |
+
token_type_ids,
|
| 189 |
+
input_mask,
|
| 190 |
+
sequence_labels,
|
| 191 |
+
token_labels,
|
| 192 |
+
choice_labels,
|
| 193 |
+
encoder_hidden_states,
|
| 194 |
+
encoder_attention_mask,
|
| 195 |
+
):
|
| 196 |
+
config.add_cross_attention = True
|
| 197 |
+
model = QDQBertModel(config)
|
| 198 |
+
model.to(torch_device)
|
| 199 |
+
model.eval()
|
| 200 |
+
result = model(
|
| 201 |
+
input_ids,
|
| 202 |
+
attention_mask=input_mask,
|
| 203 |
+
token_type_ids=token_type_ids,
|
| 204 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 205 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 206 |
+
)
|
| 207 |
+
result = model(
|
| 208 |
+
input_ids,
|
| 209 |
+
attention_mask=input_mask,
|
| 210 |
+
token_type_ids=token_type_ids,
|
| 211 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 212 |
+
)
|
| 213 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 214 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 215 |
+
|
| 216 |
+
def create_and_check_for_causal_lm(
|
| 217 |
+
self,
|
| 218 |
+
config,
|
| 219 |
+
input_ids,
|
| 220 |
+
token_type_ids,
|
| 221 |
+
input_mask,
|
| 222 |
+
sequence_labels,
|
| 223 |
+
token_labels,
|
| 224 |
+
choice_labels,
|
| 225 |
+
encoder_hidden_states,
|
| 226 |
+
encoder_attention_mask,
|
| 227 |
+
):
|
| 228 |
+
model = QDQBertLMHeadModel(config=config)
|
| 229 |
+
model.to(torch_device)
|
| 230 |
+
model.eval()
|
| 231 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 232 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 233 |
+
|
| 234 |
+
def create_and_check_for_masked_lm(
|
| 235 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 236 |
+
):
|
| 237 |
+
model = QDQBertForMaskedLM(config=config)
|
| 238 |
+
model.to(torch_device)
|
| 239 |
+
model.eval()
|
| 240 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 241 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 242 |
+
|
| 243 |
+
def create_and_check_model_for_causal_lm_as_decoder(
|
| 244 |
+
self,
|
| 245 |
+
config,
|
| 246 |
+
input_ids,
|
| 247 |
+
token_type_ids,
|
| 248 |
+
input_mask,
|
| 249 |
+
sequence_labels,
|
| 250 |
+
token_labels,
|
| 251 |
+
choice_labels,
|
| 252 |
+
encoder_hidden_states,
|
| 253 |
+
encoder_attention_mask,
|
| 254 |
+
):
|
| 255 |
+
config.add_cross_attention = True
|
| 256 |
+
model = QDQBertLMHeadModel(config=config)
|
| 257 |
+
model.to(torch_device)
|
| 258 |
+
model.eval()
|
| 259 |
+
result = model(
|
| 260 |
+
input_ids,
|
| 261 |
+
attention_mask=input_mask,
|
| 262 |
+
token_type_ids=token_type_ids,
|
| 263 |
+
labels=token_labels,
|
| 264 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 265 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 266 |
+
)
|
| 267 |
+
result = model(
|
| 268 |
+
input_ids,
|
| 269 |
+
attention_mask=input_mask,
|
| 270 |
+
token_type_ids=token_type_ids,
|
| 271 |
+
labels=token_labels,
|
| 272 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 273 |
+
)
|
| 274 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 275 |
+
|
| 276 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 277 |
+
self,
|
| 278 |
+
config,
|
| 279 |
+
input_ids,
|
| 280 |
+
token_type_ids,
|
| 281 |
+
input_mask,
|
| 282 |
+
sequence_labels,
|
| 283 |
+
token_labels,
|
| 284 |
+
choice_labels,
|
| 285 |
+
encoder_hidden_states,
|
| 286 |
+
encoder_attention_mask,
|
| 287 |
+
):
|
| 288 |
+
config.is_decoder = True
|
| 289 |
+
config.add_cross_attention = True
|
| 290 |
+
model = QDQBertLMHeadModel(config=config)
|
| 291 |
+
model.to(torch_device)
|
| 292 |
+
model.eval()
|
| 293 |
+
|
| 294 |
+
# first forward pass
|
| 295 |
+
outputs = model(
|
| 296 |
+
input_ids,
|
| 297 |
+
attention_mask=input_mask,
|
| 298 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 299 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 300 |
+
use_cache=True,
|
| 301 |
+
)
|
| 302 |
+
past_key_values = outputs.past_key_values
|
| 303 |
+
|
| 304 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 305 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 306 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 307 |
+
|
| 308 |
+
# append to next input_ids and
|
| 309 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 310 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 311 |
+
|
| 312 |
+
output_from_no_past = model(
|
| 313 |
+
next_input_ids,
|
| 314 |
+
attention_mask=next_attention_mask,
|
| 315 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 316 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 317 |
+
output_hidden_states=True,
|
| 318 |
+
)["hidden_states"][0]
|
| 319 |
+
output_from_past = model(
|
| 320 |
+
next_tokens,
|
| 321 |
+
attention_mask=next_attention_mask,
|
| 322 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 323 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 324 |
+
past_key_values=past_key_values,
|
| 325 |
+
output_hidden_states=True,
|
| 326 |
+
)["hidden_states"][0]
|
| 327 |
+
|
| 328 |
+
# select random slice
|
| 329 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 330 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 331 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 332 |
+
|
| 333 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 334 |
+
|
| 335 |
+
# test that outputs are equal for slice
|
| 336 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 337 |
+
|
| 338 |
+
def create_and_check_for_next_sequence_prediction(
|
| 339 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 340 |
+
):
|
| 341 |
+
model = QDQBertForNextSentencePrediction(config=config)
|
| 342 |
+
model.to(torch_device)
|
| 343 |
+
model.eval()
|
| 344 |
+
result = model(
|
| 345 |
+
input_ids,
|
| 346 |
+
attention_mask=input_mask,
|
| 347 |
+
token_type_ids=token_type_ids,
|
| 348 |
+
labels=sequence_labels,
|
| 349 |
+
)
|
| 350 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, 2))
|
| 351 |
+
|
| 352 |
+
def create_and_check_for_question_answering(
|
| 353 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 354 |
+
):
|
| 355 |
+
model = QDQBertForQuestionAnswering(config=config)
|
| 356 |
+
model.to(torch_device)
|
| 357 |
+
model.eval()
|
| 358 |
+
result = model(
|
| 359 |
+
input_ids,
|
| 360 |
+
attention_mask=input_mask,
|
| 361 |
+
token_type_ids=token_type_ids,
|
| 362 |
+
start_positions=sequence_labels,
|
| 363 |
+
end_positions=sequence_labels,
|
| 364 |
+
)
|
| 365 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 366 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 367 |
+
|
| 368 |
+
def create_and_check_for_sequence_classification(
|
| 369 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 370 |
+
):
|
| 371 |
+
config.num_labels = self.num_labels
|
| 372 |
+
model = QDQBertForSequenceClassification(config)
|
| 373 |
+
model.to(torch_device)
|
| 374 |
+
model.eval()
|
| 375 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
|
| 376 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 377 |
+
|
| 378 |
+
def create_and_check_for_token_classification(
|
| 379 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 380 |
+
):
|
| 381 |
+
config.num_labels = self.num_labels
|
| 382 |
+
model = QDQBertForTokenClassification(config=config)
|
| 383 |
+
model.to(torch_device)
|
| 384 |
+
model.eval()
|
| 385 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 386 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 387 |
+
|
| 388 |
+
def create_and_check_for_multiple_choice(
|
| 389 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 390 |
+
):
|
| 391 |
+
config.num_choices = self.num_choices
|
| 392 |
+
model = QDQBertForMultipleChoice(config=config)
|
| 393 |
+
model.to(torch_device)
|
| 394 |
+
model.eval()
|
| 395 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 396 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 397 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 398 |
+
result = model(
|
| 399 |
+
multiple_choice_inputs_ids,
|
| 400 |
+
attention_mask=multiple_choice_input_mask,
|
| 401 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 402 |
+
labels=choice_labels,
|
| 403 |
+
)
|
| 404 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 405 |
+
|
| 406 |
+
def prepare_config_and_inputs_for_common(self):
|
| 407 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 408 |
+
(
|
| 409 |
+
config,
|
| 410 |
+
input_ids,
|
| 411 |
+
token_type_ids,
|
| 412 |
+
input_mask,
|
| 413 |
+
sequence_labels,
|
| 414 |
+
token_labels,
|
| 415 |
+
choice_labels,
|
| 416 |
+
) = config_and_inputs
|
| 417 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 418 |
+
return config, inputs_dict
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@require_torch
|
| 422 |
+
@require_pytorch_quantization
|
| 423 |
+
class QDQBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 424 |
+
all_model_classes = (
|
| 425 |
+
(
|
| 426 |
+
QDQBertModel,
|
| 427 |
+
QDQBertForMaskedLM,
|
| 428 |
+
QDQBertForMultipleChoice,
|
| 429 |
+
QDQBertForNextSentencePrediction,
|
| 430 |
+
QDQBertForQuestionAnswering,
|
| 431 |
+
QDQBertForSequenceClassification,
|
| 432 |
+
QDQBertForTokenClassification,
|
| 433 |
+
QDQBertLMHeadModel,
|
| 434 |
+
)
|
| 435 |
+
if is_torch_available()
|
| 436 |
+
else ()
|
| 437 |
+
)
|
| 438 |
+
all_generative_model_classes = (QDQBertLMHeadModel,) if is_torch_available() else ()
|
| 439 |
+
pipeline_model_mapping = (
|
| 440 |
+
{
|
| 441 |
+
"feature-extraction": QDQBertModel,
|
| 442 |
+
"fill-mask": QDQBertForMaskedLM,
|
| 443 |
+
"question-answering": QDQBertForQuestionAnswering,
|
| 444 |
+
"text-classification": QDQBertForSequenceClassification,
|
| 445 |
+
"text-generation": QDQBertLMHeadModel,
|
| 446 |
+
"token-classification": QDQBertForTokenClassification,
|
| 447 |
+
"zero-shot": QDQBertForSequenceClassification,
|
| 448 |
+
}
|
| 449 |
+
if is_torch_available()
|
| 450 |
+
else {}
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
def setUp(self):
|
| 454 |
+
self.model_tester = QDQBertModelTester(self)
|
| 455 |
+
self.config_tester = ConfigTester(self, config_class=QDQBertConfig, hidden_size=37)
|
| 456 |
+
|
| 457 |
+
def test_config(self):
|
| 458 |
+
self.config_tester.run_common_tests()
|
| 459 |
+
|
| 460 |
+
def test_model(self):
|
| 461 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 462 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 463 |
+
|
| 464 |
+
def test_model_various_embeddings(self):
|
| 465 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 466 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 467 |
+
config_and_inputs[0].position_embedding_type = type
|
| 468 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 469 |
+
|
| 470 |
+
def test_model_as_decoder(self):
|
| 471 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 472 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 473 |
+
|
| 474 |
+
def test_model_as_decoder_with_default_input_mask(self):
|
| 475 |
+
# This regression test was failing with PyTorch < 1.3
|
| 476 |
+
(
|
| 477 |
+
config,
|
| 478 |
+
input_ids,
|
| 479 |
+
token_type_ids,
|
| 480 |
+
input_mask,
|
| 481 |
+
sequence_labels,
|
| 482 |
+
token_labels,
|
| 483 |
+
choice_labels,
|
| 484 |
+
encoder_hidden_states,
|
| 485 |
+
encoder_attention_mask,
|
| 486 |
+
) = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 487 |
+
|
| 488 |
+
input_mask = None
|
| 489 |
+
|
| 490 |
+
self.model_tester.create_and_check_model_as_decoder(
|
| 491 |
+
config,
|
| 492 |
+
input_ids,
|
| 493 |
+
token_type_ids,
|
| 494 |
+
input_mask,
|
| 495 |
+
sequence_labels,
|
| 496 |
+
token_labels,
|
| 497 |
+
choice_labels,
|
| 498 |
+
encoder_hidden_states,
|
| 499 |
+
encoder_attention_mask,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
def test_for_causal_lm(self):
|
| 503 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 504 |
+
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
|
| 505 |
+
|
| 506 |
+
def test_for_masked_lm(self):
|
| 507 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 508 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 509 |
+
|
| 510 |
+
def test_for_causal_lm_decoder(self):
|
| 511 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 512 |
+
self.model_tester.create_and_check_model_for_causal_lm_as_decoder(*config_and_inputs)
|
| 513 |
+
|
| 514 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 515 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 516 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 517 |
+
|
| 518 |
+
def test_for_multiple_choice(self):
|
| 519 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 520 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 521 |
+
|
| 522 |
+
def test_for_next_sequence_prediction(self):
|
| 523 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 524 |
+
self.model_tester.create_and_check_for_next_sequence_prediction(*config_and_inputs)
|
| 525 |
+
|
| 526 |
+
def test_for_question_answering(self):
|
| 527 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 528 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 529 |
+
|
| 530 |
+
def test_for_sequence_classification(self):
|
| 531 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 532 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 533 |
+
|
| 534 |
+
def test_for_token_classification(self):
|
| 535 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 536 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 537 |
+
|
| 538 |
+
@slow
|
| 539 |
+
def test_model_from_pretrained(self):
|
| 540 |
+
for model_name in QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 541 |
+
model = QDQBertModel.from_pretrained(model_name)
|
| 542 |
+
self.assertIsNotNone(model)
|
| 543 |
+
|
| 544 |
+
# Override
|
| 545 |
+
def test_feed_forward_chunking(self):
|
| 546 |
+
# feed forward chunking is not supported in QDQBert
|
| 547 |
+
pass
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@require_torch
|
| 551 |
+
@require_pytorch_quantization
|
| 552 |
+
class QDQBertModelIntegrationTest(unittest.TestCase):
|
| 553 |
+
@slow
|
| 554 |
+
def test_inference_no_head_absolute_embedding(self):
|
| 555 |
+
# Set default quantizers before creating the model.
|
| 556 |
+
import pytorch_quantization.nn as quant_nn
|
| 557 |
+
from pytorch_quantization.tensor_quant import QuantDescriptor
|
| 558 |
+
|
| 559 |
+
# The default tensor quantizer is set to use Max calibration method
|
| 560 |
+
input_desc = QuantDescriptor(num_bits=8, calib_method="max")
|
| 561 |
+
# The default tensor quantizer is set to be per-channel quantization for weights
|
| 562 |
+
weight_desc = QuantDescriptor(num_bits=8, axis=((0,)))
|
| 563 |
+
quant_nn.QuantLinear.set_default_quant_desc_input(input_desc)
|
| 564 |
+
quant_nn.QuantLinear.set_default_quant_desc_weight(weight_desc)
|
| 565 |
+
|
| 566 |
+
model = QDQBertModel.from_pretrained("bert-base-uncased")
|
| 567 |
+
input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
|
| 568 |
+
attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 569 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 570 |
+
expected_shape = torch.Size((1, 11, 768))
|
| 571 |
+
self.assertEqual(output.shape, expected_shape)
|
| 572 |
+
expected_slice = torch.tensor(
|
| 573 |
+
[[[0.4571, -0.0735, 0.8594], [0.2774, -0.0278, 0.8794], [0.3548, -0.0473, 0.7593]]]
|
| 574 |
+
)
|
| 575 |
+
self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_rag.py
ADDED
|
@@ -0,0 +1,1189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020, The RAG Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import gc
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import shutil
|
| 21 |
+
import tempfile
|
| 22 |
+
import unittest
|
| 23 |
+
from unittest.mock import patch
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from transformers import BartTokenizer, T5Tokenizer
|
| 28 |
+
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
|
| 29 |
+
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
|
| 30 |
+
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
|
| 31 |
+
from transformers.testing_utils import (
|
| 32 |
+
get_tests_dir,
|
| 33 |
+
require_sentencepiece,
|
| 34 |
+
require_tokenizers,
|
| 35 |
+
require_torch,
|
| 36 |
+
require_torch_non_multi_gpu,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
from transformers.utils import cached_property, is_datasets_available, is_faiss_available, is_torch_available
|
| 41 |
+
|
| 42 |
+
from ..bart.test_modeling_bart import BartModelTester
|
| 43 |
+
from ..dpr.test_modeling_dpr import DPRModelTester
|
| 44 |
+
from ..t5.test_modeling_t5 import T5ModelTester
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
TOLERANCE = 1e-3
|
| 48 |
+
|
| 49 |
+
T5_SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
|
| 50 |
+
if is_torch_available() and is_datasets_available() and is_faiss_available():
|
| 51 |
+
import faiss
|
| 52 |
+
import torch
|
| 53 |
+
from datasets import Dataset
|
| 54 |
+
|
| 55 |
+
from transformers import (
|
| 56 |
+
AutoConfig,
|
| 57 |
+
AutoModel,
|
| 58 |
+
AutoModelForSeq2SeqLM,
|
| 59 |
+
DPRContextEncoder,
|
| 60 |
+
RagConfig,
|
| 61 |
+
RagModel,
|
| 62 |
+
RagRetriever,
|
| 63 |
+
RagSequenceForGeneration,
|
| 64 |
+
RagTokenForGeneration,
|
| 65 |
+
RagTokenizer,
|
| 66 |
+
)
|
| 67 |
+
from transformers.modeling_outputs import BaseModelOutput
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
|
| 71 |
+
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
|
| 72 |
+
if a is None and b is None:
|
| 73 |
+
return True
|
| 74 |
+
try:
|
| 75 |
+
if torch.allclose(a, b, atol=atol):
|
| 76 |
+
return True
|
| 77 |
+
raise
|
| 78 |
+
except Exception:
|
| 79 |
+
msg = f"{a} != {b}"
|
| 80 |
+
if prefix:
|
| 81 |
+
msg = prefix + ": " + msg
|
| 82 |
+
raise AssertionError(msg)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def require_retrieval(test_case):
|
| 86 |
+
"""
|
| 87 |
+
Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with
|
| 88 |
+
[`RagRetriever`].
|
| 89 |
+
|
| 90 |
+
These tests are skipped when respective libraries are not installed.
|
| 91 |
+
|
| 92 |
+
"""
|
| 93 |
+
if not (is_torch_available() and is_datasets_available() and is_faiss_available()):
|
| 94 |
+
test_case = unittest.skip("test requires PyTorch, datasets and faiss")(test_case)
|
| 95 |
+
return test_case
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@require_torch
|
| 99 |
+
@require_retrieval
|
| 100 |
+
@require_sentencepiece
|
| 101 |
+
class RagTestMixin:
|
| 102 |
+
all_model_classes = (
|
| 103 |
+
(RagModel, RagTokenForGeneration, RagSequenceForGeneration)
|
| 104 |
+
if is_torch_available() and is_datasets_available() and is_faiss_available()
|
| 105 |
+
else ()
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
retrieval_vector_size = 32
|
| 109 |
+
n_docs = 3
|
| 110 |
+
max_combined_length = 16
|
| 111 |
+
|
| 112 |
+
def setUp(self):
|
| 113 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 114 |
+
|
| 115 |
+
# DPR tok
|
| 116 |
+
vocab_tokens = [
|
| 117 |
+
"[UNK]",
|
| 118 |
+
"[CLS]",
|
| 119 |
+
"[SEP]",
|
| 120 |
+
"[PAD]",
|
| 121 |
+
"[MASK]",
|
| 122 |
+
"want",
|
| 123 |
+
"##want",
|
| 124 |
+
"##ed",
|
| 125 |
+
"wa",
|
| 126 |
+
"un",
|
| 127 |
+
"runn",
|
| 128 |
+
"##ing",
|
| 129 |
+
",",
|
| 130 |
+
"low",
|
| 131 |
+
"lowest",
|
| 132 |
+
]
|
| 133 |
+
dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer")
|
| 134 |
+
os.makedirs(dpr_tokenizer_path, exist_ok=True)
|
| 135 |
+
self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"])
|
| 136 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 137 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 138 |
+
|
| 139 |
+
# BART tok
|
| 140 |
+
vocab = [
|
| 141 |
+
"l",
|
| 142 |
+
"o",
|
| 143 |
+
"w",
|
| 144 |
+
"e",
|
| 145 |
+
"r",
|
| 146 |
+
"s",
|
| 147 |
+
"t",
|
| 148 |
+
"i",
|
| 149 |
+
"d",
|
| 150 |
+
"n",
|
| 151 |
+
"\u0120",
|
| 152 |
+
"\u0120l",
|
| 153 |
+
"\u0120n",
|
| 154 |
+
"\u0120lo",
|
| 155 |
+
"\u0120low",
|
| 156 |
+
"er",
|
| 157 |
+
"\u0120lowest",
|
| 158 |
+
"\u0120newer",
|
| 159 |
+
"\u0120wider",
|
| 160 |
+
"<unk>",
|
| 161 |
+
]
|
| 162 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 163 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 164 |
+
self.special_tokens_map = {"unk_token": "<unk>"}
|
| 165 |
+
|
| 166 |
+
bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer")
|
| 167 |
+
os.makedirs(bart_tokenizer_path, exist_ok=True)
|
| 168 |
+
self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"])
|
| 169 |
+
self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"])
|
| 170 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 171 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 172 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 173 |
+
fp.write("\n".join(merges))
|
| 174 |
+
|
| 175 |
+
t5_tokenizer = T5Tokenizer(T5_SAMPLE_VOCAB)
|
| 176 |
+
t5_tokenizer_path = os.path.join(self.tmpdirname, "t5_tokenizer")
|
| 177 |
+
t5_tokenizer.save_pretrained(t5_tokenizer_path)
|
| 178 |
+
|
| 179 |
+
@cached_property
|
| 180 |
+
def dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer:
|
| 181 |
+
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 182 |
+
|
| 183 |
+
@cached_property
|
| 184 |
+
def dpr_ctx_encoder_tokenizer(self) -> DPRContextEncoderTokenizer:
|
| 185 |
+
return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 186 |
+
|
| 187 |
+
@cached_property
|
| 188 |
+
def bart_tokenizer(self) -> BartTokenizer:
|
| 189 |
+
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer"))
|
| 190 |
+
|
| 191 |
+
@cached_property
|
| 192 |
+
def t5_tokenizer(self) -> BartTokenizer:
|
| 193 |
+
return T5Tokenizer.from_pretrained(os.path.join(self.tmpdirname, "t5_tokenizer"))
|
| 194 |
+
|
| 195 |
+
def tearDown(self):
|
| 196 |
+
shutil.rmtree(self.tmpdirname)
|
| 197 |
+
|
| 198 |
+
# clean-up as much as possible GPU memory occupied by PyTorch
|
| 199 |
+
gc.collect()
|
| 200 |
+
torch.cuda.empty_cache()
|
| 201 |
+
|
| 202 |
+
def get_retriever(self, config):
|
| 203 |
+
dataset = Dataset.from_dict(
|
| 204 |
+
{
|
| 205 |
+
"id": ["0", "1", "3"],
|
| 206 |
+
"text": ["foo", "bar", "qux"],
|
| 207 |
+
"title": ["Foo", "Bar", "Qux"],
|
| 208 |
+
"embeddings": [
|
| 209 |
+
np.ones(self.retrieval_vector_size),
|
| 210 |
+
2 * np.ones(self.retrieval_vector_size),
|
| 211 |
+
3 * np.ones(self.retrieval_vector_size),
|
| 212 |
+
],
|
| 213 |
+
}
|
| 214 |
+
)
|
| 215 |
+
dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
|
| 216 |
+
tokenizer = self.bart_tokenizer if config.generator.model_type == "bart" else self.t5_tokenizer
|
| 217 |
+
with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
|
| 218 |
+
mock_load_dataset.return_value = dataset
|
| 219 |
+
retriever = RagRetriever(
|
| 220 |
+
config,
|
| 221 |
+
question_encoder_tokenizer=self.dpr_tokenizer,
|
| 222 |
+
generator_tokenizer=tokenizer,
|
| 223 |
+
)
|
| 224 |
+
return retriever
|
| 225 |
+
|
| 226 |
+
def check_model_with_retriever(
|
| 227 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 228 |
+
):
|
| 229 |
+
self.assertIsNotNone(config.question_encoder)
|
| 230 |
+
self.assertIsNotNone(config.generator)
|
| 231 |
+
|
| 232 |
+
for model_class in self.all_model_classes:
|
| 233 |
+
model = model_class(config, retriever=self.get_retriever(config)).to(torch_device)
|
| 234 |
+
model.eval()
|
| 235 |
+
|
| 236 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 237 |
+
|
| 238 |
+
outputs = model(
|
| 239 |
+
input_ids=input_ids,
|
| 240 |
+
attention_mask=attention_mask,
|
| 241 |
+
decoder_input_ids=decoder_input_ids,
|
| 242 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# logits
|
| 246 |
+
self.assertEqual(
|
| 247 |
+
outputs.logits.shape,
|
| 248 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 249 |
+
)
|
| 250 |
+
# generator encoder last hidden states
|
| 251 |
+
self.assertEqual(
|
| 252 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 253 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 254 |
+
)
|
| 255 |
+
# doc scores
|
| 256 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 257 |
+
|
| 258 |
+
def check_model_with_end2end_retriever(
|
| 259 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 260 |
+
):
|
| 261 |
+
self.assertIsNotNone(config.question_encoder)
|
| 262 |
+
self.assertIsNotNone(config.generator)
|
| 263 |
+
|
| 264 |
+
context_encoder_tokenizer = self.dpr_ctx_encoder_tokenizer
|
| 265 |
+
dpr_context_encoder = DPRContextEncoder(config.question_encoder) # dpr is a twin tower
|
| 266 |
+
|
| 267 |
+
retriever = self.get_retriever(config)
|
| 268 |
+
retriever.set_ctx_encoder_tokenizer(context_encoder_tokenizer) # setting the ctx_encoder_tokenizer.
|
| 269 |
+
|
| 270 |
+
for model_class in [RagTokenForGeneration, RagSequenceForGeneration]:
|
| 271 |
+
model = model_class(config, retriever=retriever)
|
| 272 |
+
model.set_context_encoder_for_training(dpr_context_encoder) # set the context_encoder for training
|
| 273 |
+
model.to(torch_device)
|
| 274 |
+
model.eval()
|
| 275 |
+
|
| 276 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 277 |
+
|
| 278 |
+
outputs = model(
|
| 279 |
+
input_ids=input_ids,
|
| 280 |
+
attention_mask=attention_mask,
|
| 281 |
+
decoder_input_ids=decoder_input_ids,
|
| 282 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# logits
|
| 286 |
+
self.assertEqual(
|
| 287 |
+
outputs.logits.shape,
|
| 288 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 289 |
+
)
|
| 290 |
+
# generator encoder last hidden states
|
| 291 |
+
self.assertEqual(
|
| 292 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 293 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 294 |
+
)
|
| 295 |
+
# doc scores
|
| 296 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 297 |
+
|
| 298 |
+
def check_model_generate_from_context_input_ids(
|
| 299 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 300 |
+
):
|
| 301 |
+
self.assertIsNotNone(config.question_encoder)
|
| 302 |
+
self.assertIsNotNone(config.generator)
|
| 303 |
+
|
| 304 |
+
retriever = self.get_retriever(config)
|
| 305 |
+
|
| 306 |
+
for model_class in self.all_model_classes:
|
| 307 |
+
model = model_class(config).to(torch_device)
|
| 308 |
+
model.eval()
|
| 309 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 310 |
+
|
| 311 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 312 |
+
|
| 313 |
+
out = retriever(
|
| 314 |
+
input_ids,
|
| 315 |
+
question_hidden_states.cpu().detach().to(torch.float32).numpy(),
|
| 316 |
+
prefix=config.generator.prefix,
|
| 317 |
+
return_tensors="pt",
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 321 |
+
out["context_input_ids"],
|
| 322 |
+
out["context_attention_mask"],
|
| 323 |
+
out["retrieved_doc_embeds"],
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# cast
|
| 327 |
+
retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
|
| 328 |
+
context_input_ids = context_input_ids.to(input_ids)
|
| 329 |
+
context_attention_mask = context_attention_mask.to(input_ids)
|
| 330 |
+
|
| 331 |
+
# compute doc_scores
|
| 332 |
+
doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
|
| 333 |
+
1
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
outputs = model.generate(
|
| 337 |
+
context_input_ids=context_input_ids,
|
| 338 |
+
context_attention_mask=context_attention_mask,
|
| 339 |
+
doc_scores=doc_scores,
|
| 340 |
+
do_deduplication=True,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
self.assertIsNotNone(outputs)
|
| 344 |
+
|
| 345 |
+
def check_model_generate(
|
| 346 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 347 |
+
):
|
| 348 |
+
self.assertIsNotNone(config.question_encoder)
|
| 349 |
+
self.assertIsNotNone(config.generator)
|
| 350 |
+
|
| 351 |
+
for model_class in self.all_model_classes[1:]:
|
| 352 |
+
model = model_class(config, retriever=self.get_retriever(config)).to(torch_device)
|
| 353 |
+
model.eval()
|
| 354 |
+
|
| 355 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 356 |
+
|
| 357 |
+
outputs = model.generate(
|
| 358 |
+
input_ids=input_ids,
|
| 359 |
+
num_beams=2,
|
| 360 |
+
num_return_sequences=2,
|
| 361 |
+
decoder_start_token_id=config.generator.eos_token_id,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
self.assertIsNotNone(outputs)
|
| 365 |
+
|
| 366 |
+
def check_model_without_retriever(
|
| 367 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 368 |
+
):
|
| 369 |
+
self.assertIsNotNone(config.question_encoder)
|
| 370 |
+
self.assertIsNotNone(config.generator)
|
| 371 |
+
|
| 372 |
+
retriever = self.get_retriever(config)
|
| 373 |
+
|
| 374 |
+
for model_class in self.all_model_classes:
|
| 375 |
+
model = model_class(config).to(torch_device)
|
| 376 |
+
model.eval()
|
| 377 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 378 |
+
|
| 379 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 380 |
+
|
| 381 |
+
out = retriever(
|
| 382 |
+
input_ids,
|
| 383 |
+
question_hidden_states.cpu().detach().to(torch.float32).numpy(),
|
| 384 |
+
prefix=config.generator.prefix,
|
| 385 |
+
return_tensors="pt",
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 389 |
+
out["context_input_ids"],
|
| 390 |
+
out["context_attention_mask"],
|
| 391 |
+
out["retrieved_doc_embeds"],
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# cast
|
| 395 |
+
retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
|
| 396 |
+
context_input_ids = context_input_ids.to(input_ids)
|
| 397 |
+
context_attention_mask = context_attention_mask.to(input_ids)
|
| 398 |
+
|
| 399 |
+
# compute doc_scores
|
| 400 |
+
doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
|
| 401 |
+
1
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
outputs = model(
|
| 405 |
+
context_input_ids=context_input_ids,
|
| 406 |
+
context_attention_mask=context_attention_mask,
|
| 407 |
+
doc_scores=doc_scores,
|
| 408 |
+
decoder_input_ids=decoder_input_ids,
|
| 409 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# logits
|
| 413 |
+
self.assertEqual(
|
| 414 |
+
outputs.logits.shape,
|
| 415 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 416 |
+
)
|
| 417 |
+
# generator encoder last hidden states
|
| 418 |
+
self.assertEqual(
|
| 419 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 420 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 421 |
+
)
|
| 422 |
+
# doc scores
|
| 423 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 424 |
+
|
| 425 |
+
def check_model_custom_n_docs(
|
| 426 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, n_docs, **kwargs
|
| 427 |
+
):
|
| 428 |
+
self.assertIsNotNone(config.question_encoder)
|
| 429 |
+
self.assertIsNotNone(config.generator)
|
| 430 |
+
|
| 431 |
+
retriever = self.get_retriever(config)
|
| 432 |
+
|
| 433 |
+
for model_class in self.all_model_classes:
|
| 434 |
+
model = model_class(config).to(torch_device)
|
| 435 |
+
model.eval()
|
| 436 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 437 |
+
|
| 438 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 439 |
+
|
| 440 |
+
out = retriever(
|
| 441 |
+
input_ids,
|
| 442 |
+
question_hidden_states.cpu().detach().to(torch.float32).numpy(),
|
| 443 |
+
prefix=config.generator.prefix,
|
| 444 |
+
return_tensors="pt",
|
| 445 |
+
n_docs=n_docs,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 449 |
+
out["context_input_ids"],
|
| 450 |
+
out["context_attention_mask"],
|
| 451 |
+
out["retrieved_doc_embeds"],
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# cast
|
| 455 |
+
retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
|
| 456 |
+
context_input_ids = context_input_ids.to(input_ids)
|
| 457 |
+
context_attention_mask = context_attention_mask.to(input_ids)
|
| 458 |
+
|
| 459 |
+
# compute doc_scores
|
| 460 |
+
doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
|
| 461 |
+
1
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
outputs = model(
|
| 465 |
+
context_input_ids=context_input_ids,
|
| 466 |
+
context_attention_mask=context_attention_mask,
|
| 467 |
+
doc_scores=doc_scores,
|
| 468 |
+
decoder_input_ids=decoder_input_ids,
|
| 469 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 470 |
+
n_docs=n_docs,
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
# logits
|
| 474 |
+
self.assertEqual(
|
| 475 |
+
outputs.logits.shape,
|
| 476 |
+
(n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 477 |
+
)
|
| 478 |
+
# generator encoder last hidden states
|
| 479 |
+
self.assertEqual(
|
| 480 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 481 |
+
(n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 482 |
+
)
|
| 483 |
+
# doc scores
|
| 484 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], n_docs))
|
| 485 |
+
|
| 486 |
+
def check_model_with_mismatch_n_docs_value(
|
| 487 |
+
self,
|
| 488 |
+
config,
|
| 489 |
+
input_ids,
|
| 490 |
+
attention_mask,
|
| 491 |
+
decoder_input_ids,
|
| 492 |
+
decoder_attention_mask,
|
| 493 |
+
retriever_n_docs,
|
| 494 |
+
generator_n_docs,
|
| 495 |
+
**kwargs,
|
| 496 |
+
):
|
| 497 |
+
self.assertIsNotNone(config.question_encoder)
|
| 498 |
+
self.assertIsNotNone(config.generator)
|
| 499 |
+
|
| 500 |
+
retriever = self.get_retriever(config)
|
| 501 |
+
|
| 502 |
+
for model_class in self.all_model_classes:
|
| 503 |
+
model = model_class(config).to(torch_device)
|
| 504 |
+
model.eval()
|
| 505 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 506 |
+
|
| 507 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 508 |
+
|
| 509 |
+
out = retriever(
|
| 510 |
+
input_ids,
|
| 511 |
+
question_hidden_states.cpu().detach().to(torch.float32).numpy(),
|
| 512 |
+
prefix=config.generator.prefix,
|
| 513 |
+
return_tensors="pt",
|
| 514 |
+
n_docs=retriever_n_docs,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 518 |
+
out["context_input_ids"],
|
| 519 |
+
out["context_attention_mask"],
|
| 520 |
+
out["retrieved_doc_embeds"],
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
# cast
|
| 524 |
+
retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states)
|
| 525 |
+
context_input_ids = context_input_ids.to(input_ids)
|
| 526 |
+
context_attention_mask = context_attention_mask.to(input_ids)
|
| 527 |
+
|
| 528 |
+
# compute doc_scores
|
| 529 |
+
doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze(
|
| 530 |
+
1
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
self.assertRaises(
|
| 534 |
+
AssertionError,
|
| 535 |
+
model.__call__,
|
| 536 |
+
context_input_ids=context_input_ids,
|
| 537 |
+
context_attention_mask=context_attention_mask,
|
| 538 |
+
doc_scores=doc_scores,
|
| 539 |
+
decoder_input_ids=decoder_input_ids,
|
| 540 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 541 |
+
n_docs=generator_n_docs,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
def check_model_with_encoder_outputs(
|
| 545 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 546 |
+
):
|
| 547 |
+
self.assertIsNotNone(config.question_encoder)
|
| 548 |
+
self.assertIsNotNone(config.generator)
|
| 549 |
+
|
| 550 |
+
for model_class in self.all_model_classes:
|
| 551 |
+
model = model_class(config, retriever=self.get_retriever(config)).to(torch_device)
|
| 552 |
+
model.eval()
|
| 553 |
+
|
| 554 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 555 |
+
|
| 556 |
+
outputs = model(
|
| 557 |
+
input_ids=input_ids,
|
| 558 |
+
attention_mask=attention_mask,
|
| 559 |
+
decoder_input_ids=decoder_input_ids,
|
| 560 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
encoder_outputs = BaseModelOutput(outputs.generator_enc_last_hidden_state)
|
| 564 |
+
|
| 565 |
+
# run only generator
|
| 566 |
+
outputs = model(
|
| 567 |
+
encoder_outputs=encoder_outputs,
|
| 568 |
+
doc_scores=outputs.doc_scores,
|
| 569 |
+
decoder_input_ids=decoder_input_ids,
|
| 570 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
# logits
|
| 574 |
+
self.assertEqual(
|
| 575 |
+
outputs.logits.shape,
|
| 576 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 577 |
+
)
|
| 578 |
+
# generator encoder last hidden states
|
| 579 |
+
self.assertEqual(
|
| 580 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 581 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 582 |
+
)
|
| 583 |
+
# doc scores
|
| 584 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 585 |
+
|
| 586 |
+
def test_model_with_retriever(self):
|
| 587 |
+
inputs_dict = self.config_and_inputs
|
| 588 |
+
self.check_model_with_retriever(**inputs_dict)
|
| 589 |
+
|
| 590 |
+
def test_model_with_end2end_retriever(self):
|
| 591 |
+
inputs_dict = self.config_and_inputs
|
| 592 |
+
self.check_model_with_end2end_retriever(**inputs_dict)
|
| 593 |
+
|
| 594 |
+
def test_model_without_retriever(self):
|
| 595 |
+
inputs_dict = self.config_and_inputs
|
| 596 |
+
self.check_model_without_retriever(**inputs_dict)
|
| 597 |
+
|
| 598 |
+
def test_model_with_encoder_outputs(self):
|
| 599 |
+
inputs_dict = self.config_and_inputs
|
| 600 |
+
self.check_model_with_encoder_outputs(**inputs_dict)
|
| 601 |
+
|
| 602 |
+
def test_model_generate(self):
|
| 603 |
+
inputs_dict = self.config_and_inputs
|
| 604 |
+
self.check_model_generate(**inputs_dict)
|
| 605 |
+
|
| 606 |
+
def test_model_with_custom_n_docs(self):
|
| 607 |
+
inputs_dict = self.config_and_inputs
|
| 608 |
+
inputs_dict["n_docs"] = 1
|
| 609 |
+
self.check_model_custom_n_docs(**inputs_dict)
|
| 610 |
+
|
| 611 |
+
def test_model_with_mismatch_n_docs_value(self):
|
| 612 |
+
inputs_dict = self.config_and_inputs
|
| 613 |
+
inputs_dict["retriever_n_docs"] = 3
|
| 614 |
+
inputs_dict["generator_n_docs"] = 2
|
| 615 |
+
self.check_model_with_mismatch_n_docs_value(**inputs_dict)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
@require_torch
|
| 619 |
+
@require_retrieval
|
| 620 |
+
class RagDPRBartTest(RagTestMixin, unittest.TestCase):
|
| 621 |
+
@cached_property
|
| 622 |
+
def config_and_inputs(self):
|
| 623 |
+
question_encoder_tester = DPRModelTester(self)
|
| 624 |
+
dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs()
|
| 625 |
+
generator_tester = BartModelTester(self)
|
| 626 |
+
bart_config_and_inputs = generator_tester.prepare_config_and_inputs_for_common()
|
| 627 |
+
|
| 628 |
+
(question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs
|
| 629 |
+
(generator_config, bart_inputs_dict) = bart_config_and_inputs
|
| 630 |
+
decoder_input_ids, decoder_attention_mask = bart_inputs_dict["input_ids"], bart_inputs_dict["attention_mask"]
|
| 631 |
+
|
| 632 |
+
config = RagConfig.from_question_encoder_generator_configs(
|
| 633 |
+
question_encoder_config,
|
| 634 |
+
generator_config,
|
| 635 |
+
n_docs=self.n_docs,
|
| 636 |
+
retrieval_vector_size=self.retrieval_vector_size,
|
| 637 |
+
max_combined_length=self.max_combined_length,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
return {
|
| 641 |
+
"config": config,
|
| 642 |
+
"input_ids": input_ids,
|
| 643 |
+
"attention_mask": input_mask,
|
| 644 |
+
"decoder_input_ids": decoder_input_ids,
|
| 645 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
@require_torch
|
| 650 |
+
@require_retrieval
|
| 651 |
+
class RagDPRT5Test(RagTestMixin, unittest.TestCase):
|
| 652 |
+
@cached_property
|
| 653 |
+
def config_and_inputs(self):
|
| 654 |
+
question_encoder_tester = DPRModelTester(self)
|
| 655 |
+
dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs()
|
| 656 |
+
generator_tester = T5ModelTester(self, vocab_size=1100)
|
| 657 |
+
t5_config_and_inputs = generator_tester.prepare_config_and_inputs()
|
| 658 |
+
|
| 659 |
+
(question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs
|
| 660 |
+
(generator_config, _, decoder_input_ids, _, decoder_attention_mask, _) = t5_config_and_inputs
|
| 661 |
+
config = RagConfig.from_question_encoder_generator_configs(
|
| 662 |
+
question_encoder_config,
|
| 663 |
+
generator_config,
|
| 664 |
+
n_docs=self.n_docs,
|
| 665 |
+
retrieval_vector_size=self.retrieval_vector_size,
|
| 666 |
+
max_combined_length=self.max_combined_length,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
return {
|
| 670 |
+
"config": config,
|
| 671 |
+
"input_ids": input_ids,
|
| 672 |
+
"attention_mask": input_mask,
|
| 673 |
+
"decoder_input_ids": decoder_input_ids,
|
| 674 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
@require_torch
|
| 679 |
+
@require_retrieval
|
| 680 |
+
@require_sentencepiece
|
| 681 |
+
@require_tokenizers
|
| 682 |
+
@require_torch_non_multi_gpu
|
| 683 |
+
class RagModelIntegrationTests(unittest.TestCase):
|
| 684 |
+
def tearDown(self):
|
| 685 |
+
super().tearDown()
|
| 686 |
+
# clean-up as much as possible GPU memory occupied by PyTorch
|
| 687 |
+
gc.collect()
|
| 688 |
+
torch.cuda.empty_cache()
|
| 689 |
+
|
| 690 |
+
@cached_property
|
| 691 |
+
def sequence_model(self):
|
| 692 |
+
return (
|
| 693 |
+
RagSequenceForGeneration.from_pretrained_question_encoder_generator(
|
| 694 |
+
"facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn"
|
| 695 |
+
)
|
| 696 |
+
.to(torch_device)
|
| 697 |
+
.eval()
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
@cached_property
|
| 701 |
+
def token_model(self):
|
| 702 |
+
return (
|
| 703 |
+
RagTokenForGeneration.from_pretrained_question_encoder_generator(
|
| 704 |
+
"facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn"
|
| 705 |
+
)
|
| 706 |
+
.to(torch_device)
|
| 707 |
+
.eval()
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
def get_rag_config(self):
|
| 711 |
+
question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 712 |
+
generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn")
|
| 713 |
+
return RagConfig.from_question_encoder_generator_configs(
|
| 714 |
+
question_encoder_config,
|
| 715 |
+
generator_config,
|
| 716 |
+
bos_token_id=0,
|
| 717 |
+
decoder_start_token_id=2,
|
| 718 |
+
eos_token_id=2,
|
| 719 |
+
is_encoder_decoder=True,
|
| 720 |
+
pad_token_id=1,
|
| 721 |
+
vocab_size=50264,
|
| 722 |
+
title_sep=" / ",
|
| 723 |
+
doc_sep=" // ",
|
| 724 |
+
n_docs=5,
|
| 725 |
+
max_combined_length=300,
|
| 726 |
+
dataset="wiki_dpr",
|
| 727 |
+
dataset_split="train",
|
| 728 |
+
index_name="exact",
|
| 729 |
+
index_path=None,
|
| 730 |
+
use_dummy_dataset=True,
|
| 731 |
+
retrieval_vector_size=768,
|
| 732 |
+
retrieval_batch_size=8,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
@slow
|
| 736 |
+
def test_rag_sequence_inference(self):
|
| 737 |
+
rag_config = self.get_rag_config()
|
| 738 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 739 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 740 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 741 |
+
)
|
| 742 |
+
rag_retriever = RagRetriever(
|
| 743 |
+
rag_config,
|
| 744 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 745 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
rag_sequence = self.sequence_model
|
| 749 |
+
rag_sequence.set_retriever(rag_retriever)
|
| 750 |
+
|
| 751 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 752 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 753 |
+
).input_ids
|
| 754 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids
|
| 755 |
+
|
| 756 |
+
input_ids = input_ids.to(torch_device)
|
| 757 |
+
decoder_input_ids = decoder_input_ids.to(torch_device)
|
| 758 |
+
|
| 759 |
+
with torch.no_grad():
|
| 760 |
+
output = rag_sequence(
|
| 761 |
+
input_ids,
|
| 762 |
+
labels=decoder_input_ids,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
expected_shape = torch.Size([5, 5, 50264])
|
| 766 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 767 |
+
|
| 768 |
+
expected_doc_scores = torch.tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]).to(torch_device)
|
| 769 |
+
_assert_tensors_equal(expected_doc_scores, output.doc_scores, atol=TOLERANCE)
|
| 770 |
+
|
| 771 |
+
expected_loss = torch.tensor([36.7368]).to(torch_device)
|
| 772 |
+
_assert_tensors_equal(expected_loss, output.loss, atol=TOLERANCE)
|
| 773 |
+
|
| 774 |
+
@slow
|
| 775 |
+
def test_rag_token_inference(self):
|
| 776 |
+
rag_config = self.get_rag_config()
|
| 777 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 778 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 779 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 780 |
+
)
|
| 781 |
+
rag_retriever = RagRetriever(
|
| 782 |
+
rag_config,
|
| 783 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 784 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
rag_token = self.token_model
|
| 788 |
+
rag_token.set_retriever(rag_retriever)
|
| 789 |
+
|
| 790 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 791 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 792 |
+
).input_ids
|
| 793 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids
|
| 794 |
+
|
| 795 |
+
input_ids = input_ids.to(torch_device)
|
| 796 |
+
decoder_input_ids = decoder_input_ids.to(torch_device)
|
| 797 |
+
|
| 798 |
+
with torch.no_grad():
|
| 799 |
+
output = rag_token(
|
| 800 |
+
input_ids,
|
| 801 |
+
labels=decoder_input_ids,
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
expected_shape = torch.Size([5, 5, 50264])
|
| 805 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 806 |
+
|
| 807 |
+
expected_doc_scores = torch.tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]).to(torch_device)
|
| 808 |
+
_assert_tensors_equal(expected_doc_scores, output.doc_scores, atol=TOLERANCE)
|
| 809 |
+
|
| 810 |
+
expected_loss = torch.tensor([36.3557]).to(torch_device)
|
| 811 |
+
_assert_tensors_equal(expected_loss, output.loss, atol=TOLERANCE)
|
| 812 |
+
|
| 813 |
+
@slow
|
| 814 |
+
def test_rag_token_generate_beam(self):
|
| 815 |
+
rag_config = self.get_rag_config()
|
| 816 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 817 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 818 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 819 |
+
)
|
| 820 |
+
rag_retriever = RagRetriever(
|
| 821 |
+
rag_config,
|
| 822 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 823 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
rag_token = self.token_model
|
| 827 |
+
rag_token.set_retriever(rag_retriever)
|
| 828 |
+
|
| 829 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 830 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 831 |
+
).input_ids
|
| 832 |
+
|
| 833 |
+
input_ids = input_ids.to(torch_device)
|
| 834 |
+
|
| 835 |
+
output_ids = rag_token.generate(
|
| 836 |
+
input_ids,
|
| 837 |
+
decoder_start_token_id=rag_token.generator.config.decoder_start_token_id,
|
| 838 |
+
num_beams=2,
|
| 839 |
+
num_return_sequences=2,
|
| 840 |
+
)
|
| 841 |
+
# sequence generate test
|
| 842 |
+
output_text_1 = rag_decoder_tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 843 |
+
output_text_2 = rag_decoder_tokenizer.decode(output_ids[1], skip_special_tokens=True)
|
| 844 |
+
|
| 845 |
+
# Expected outputs as given by model at integration time.
|
| 846 |
+
EXPECTED_OUTPUT_TEXT_1 = "\"She's My Kind of Girl"
|
| 847 |
+
EXPECTED_OUTPUT_TEXT_2 = "\"She's My Kind of Love"
|
| 848 |
+
|
| 849 |
+
self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1)
|
| 850 |
+
self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2)
|
| 851 |
+
|
| 852 |
+
@slow
|
| 853 |
+
def test_rag_sequence_generate_beam(self):
|
| 854 |
+
rag_config = self.get_rag_config()
|
| 855 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 856 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 857 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 858 |
+
)
|
| 859 |
+
rag_retriever = RagRetriever(
|
| 860 |
+
rag_config,
|
| 861 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 862 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
rag_sequence = self.sequence_model
|
| 866 |
+
rag_sequence.set_retriever(rag_retriever)
|
| 867 |
+
|
| 868 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 869 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 870 |
+
).input_ids
|
| 871 |
+
|
| 872 |
+
input_ids = input_ids.to(torch_device)
|
| 873 |
+
|
| 874 |
+
output_ids = rag_sequence.generate(
|
| 875 |
+
input_ids,
|
| 876 |
+
decoder_start_token_id=rag_sequence.generator.config.decoder_start_token_id,
|
| 877 |
+
num_beams=2,
|
| 878 |
+
num_return_sequences=2,
|
| 879 |
+
)
|
| 880 |
+
# sequence generate test
|
| 881 |
+
output_text_1 = rag_decoder_tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 882 |
+
output_text_2 = rag_decoder_tokenizer.decode(output_ids[1], skip_special_tokens=True)
|
| 883 |
+
|
| 884 |
+
# Expected outputs as given by model at integration time.
|
| 885 |
+
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."""
|
| 886 |
+
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."""
|
| 887 |
+
|
| 888 |
+
self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1)
|
| 889 |
+
self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2)
|
| 890 |
+
|
| 891 |
+
@property
|
| 892 |
+
def test_data_questions(self):
|
| 893 |
+
return [
|
| 894 |
+
"who got the first nobel prize in physics",
|
| 895 |
+
"when is the next deadpool movie being released",
|
| 896 |
+
"which mode is used for short wave broadcast service",
|
| 897 |
+
"who is the owner of reading football club",
|
| 898 |
+
"when is the next scandal episode coming out",
|
| 899 |
+
"when is the last time the philadelphia won the superbowl",
|
| 900 |
+
"what is the most current adobe flash player version",
|
| 901 |
+
"how many episodes are there in dragon ball z",
|
| 902 |
+
]
|
| 903 |
+
|
| 904 |
+
@slow
|
| 905 |
+
def test_rag_sequence_generate_batch(self):
|
| 906 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
|
| 907 |
+
retriever = RagRetriever.from_pretrained(
|
| 908 |
+
"facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
|
| 909 |
+
)
|
| 910 |
+
rag_sequence = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever).to(
|
| 911 |
+
torch_device
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
input_dict = tokenizer(
|
| 915 |
+
self.test_data_questions,
|
| 916 |
+
return_tensors="pt",
|
| 917 |
+
padding=True,
|
| 918 |
+
truncation=True,
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
input_ids = input_dict.input_ids.to(torch_device)
|
| 922 |
+
attention_mask = input_dict.attention_mask.to(torch_device)
|
| 923 |
+
|
| 924 |
+
output_ids = rag_sequence.generate(
|
| 925 |
+
input_ids,
|
| 926 |
+
attention_mask=attention_mask,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 930 |
+
|
| 931 |
+
EXPECTED_OUTPUTS = [
|
| 932 |
+
" albert einstein",
|
| 933 |
+
" june 22, 2018",
|
| 934 |
+
" amplitude modulation",
|
| 935 |
+
" tim besley ( chairman )",
|
| 936 |
+
" june 20, 2018",
|
| 937 |
+
" 1980",
|
| 938 |
+
" 7.0",
|
| 939 |
+
" 8",
|
| 940 |
+
]
|
| 941 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 942 |
+
|
| 943 |
+
@slow
|
| 944 |
+
def test_rag_sequence_generate_batch_from_context_input_ids(self):
|
| 945 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
|
| 946 |
+
retriever = RagRetriever.from_pretrained(
|
| 947 |
+
"facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
|
| 948 |
+
)
|
| 949 |
+
rag_sequence = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever).to(
|
| 950 |
+
torch_device
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
input_dict = tokenizer(
|
| 954 |
+
self.test_data_questions,
|
| 955 |
+
return_tensors="pt",
|
| 956 |
+
padding=True,
|
| 957 |
+
truncation=True,
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
input_ids = input_dict.input_ids.to(torch_device)
|
| 961 |
+
attention_mask = input_dict.attention_mask.to(torch_device)
|
| 962 |
+
|
| 963 |
+
question_hidden_states = rag_sequence.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 964 |
+
docs_dict = retriever(
|
| 965 |
+
input_ids.cpu().detach().numpy(), question_hidden_states.cpu().detach().numpy(), return_tensors="pt"
|
| 966 |
+
)
|
| 967 |
+
doc_scores = torch.bmm(
|
| 968 |
+
question_hidden_states.unsqueeze(1),
|
| 969 |
+
docs_dict["retrieved_doc_embeds"].to(torch_device).float().transpose(1, 2),
|
| 970 |
+
).squeeze(1)
|
| 971 |
+
|
| 972 |
+
output_ids = rag_sequence.generate(
|
| 973 |
+
context_input_ids=docs_dict["context_input_ids"].to(torch_device),
|
| 974 |
+
context_attention_mask=docs_dict["context_attention_mask"].to(torch_device),
|
| 975 |
+
doc_scores=doc_scores.to(torch_device),
|
| 976 |
+
do_deduplication=True,
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 980 |
+
|
| 981 |
+
EXPECTED_OUTPUTS = [
|
| 982 |
+
" albert einstein",
|
| 983 |
+
" june 22, 2018",
|
| 984 |
+
" amplitude modulation",
|
| 985 |
+
" tim besley ( chairman )",
|
| 986 |
+
" june 20, 2018",
|
| 987 |
+
" 1980",
|
| 988 |
+
" 7.0",
|
| 989 |
+
" 8",
|
| 990 |
+
]
|
| 991 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 992 |
+
|
| 993 |
+
@slow
|
| 994 |
+
def test_rag_token_generate_batch(self):
|
| 995 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
|
| 996 |
+
retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True)
|
| 997 |
+
rag_token = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever).to(
|
| 998 |
+
torch_device
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
if torch_device == "cuda":
|
| 1002 |
+
rag_token.half()
|
| 1003 |
+
|
| 1004 |
+
input_dict = tokenizer(
|
| 1005 |
+
self.test_data_questions,
|
| 1006 |
+
return_tensors="pt",
|
| 1007 |
+
padding=True,
|
| 1008 |
+
truncation=True,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
input_ids = input_dict.input_ids.to(torch_device)
|
| 1012 |
+
attention_mask = input_dict.attention_mask.to(torch_device)
|
| 1013 |
+
|
| 1014 |
+
output_ids = rag_token.generate(
|
| 1015 |
+
input_ids,
|
| 1016 |
+
attention_mask=attention_mask,
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 1020 |
+
|
| 1021 |
+
EXPECTED_OUTPUTS = [
|
| 1022 |
+
" albert einstein",
|
| 1023 |
+
" september 22, 2017",
|
| 1024 |
+
" amplitude modulation",
|
| 1025 |
+
" stefan persson",
|
| 1026 |
+
" april 20, 2018",
|
| 1027 |
+
" the 1970s",
|
| 1028 |
+
" 7.1. 2",
|
| 1029 |
+
" 13",
|
| 1030 |
+
]
|
| 1031 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
@require_torch
|
| 1035 |
+
@require_retrieval
|
| 1036 |
+
class RagModelSaveLoadTests(unittest.TestCase):
|
| 1037 |
+
def tearDown(self):
|
| 1038 |
+
super().tearDown()
|
| 1039 |
+
# clean-up as much as possible GPU memory occupied by PyTorch
|
| 1040 |
+
gc.collect()
|
| 1041 |
+
torch.cuda.empty_cache()
|
| 1042 |
+
|
| 1043 |
+
def get_rag_config(self):
|
| 1044 |
+
question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 1045 |
+
generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn")
|
| 1046 |
+
return RagConfig.from_question_encoder_generator_configs(
|
| 1047 |
+
question_encoder_config,
|
| 1048 |
+
generator_config,
|
| 1049 |
+
bos_token_id=0,
|
| 1050 |
+
decoder_start_token_id=2,
|
| 1051 |
+
eos_token_id=2,
|
| 1052 |
+
is_encoder_decoder=True,
|
| 1053 |
+
pad_token_id=1,
|
| 1054 |
+
vocab_size=50264,
|
| 1055 |
+
title_sep=" / ",
|
| 1056 |
+
doc_sep=" // ",
|
| 1057 |
+
n_docs=5,
|
| 1058 |
+
max_combined_length=300,
|
| 1059 |
+
dataset="wiki_dpr",
|
| 1060 |
+
dataset_split="train",
|
| 1061 |
+
index_name="exact",
|
| 1062 |
+
index_path=None,
|
| 1063 |
+
use_dummy_dataset=True,
|
| 1064 |
+
retrieval_vector_size=768,
|
| 1065 |
+
retrieval_batch_size=8,
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
@slow
|
| 1069 |
+
def test_rag_sequence_from_pretrained(self):
|
| 1070 |
+
rag_config = self.get_rag_config()
|
| 1071 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 1072 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 1073 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 1074 |
+
)
|
| 1075 |
+
rag_retriever = RagRetriever(
|
| 1076 |
+
rag_config,
|
| 1077 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 1078 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 1082 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 1083 |
+
).input_ids
|
| 1084 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids
|
| 1085 |
+
|
| 1086 |
+
input_ids = input_ids.to(torch_device)
|
| 1087 |
+
decoder_input_ids = decoder_input_ids.to(torch_device)
|
| 1088 |
+
|
| 1089 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1090 |
+
rag_sequence = RagSequenceForGeneration.from_pretrained_question_encoder_generator(
|
| 1091 |
+
"facebook/dpr-question_encoder-single-nq-base",
|
| 1092 |
+
"facebook/bart-large-cnn",
|
| 1093 |
+
retriever=rag_retriever,
|
| 1094 |
+
config=rag_config,
|
| 1095 |
+
).to(torch_device)
|
| 1096 |
+
# check that the from pretrained methods work
|
| 1097 |
+
rag_sequence.save_pretrained(tmp_dirname)
|
| 1098 |
+
rag_sequence.from_pretrained(tmp_dirname, retriever=rag_retriever)
|
| 1099 |
+
rag_sequence.to(torch_device)
|
| 1100 |
+
|
| 1101 |
+
with torch.no_grad():
|
| 1102 |
+
output = rag_sequence(
|
| 1103 |
+
input_ids,
|
| 1104 |
+
labels=decoder_input_ids,
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
loss_pretrained = output.loss
|
| 1108 |
+
del rag_sequence
|
| 1109 |
+
|
| 1110 |
+
question_encoder = AutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 1111 |
+
generator = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn")
|
| 1112 |
+
rag_sequence = RagSequenceForGeneration(
|
| 1113 |
+
config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever
|
| 1114 |
+
)
|
| 1115 |
+
rag_sequence.to(torch_device)
|
| 1116 |
+
|
| 1117 |
+
with torch.no_grad():
|
| 1118 |
+
output = rag_sequence(
|
| 1119 |
+
input_ids,
|
| 1120 |
+
labels=decoder_input_ids,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
loss_init = output.loss
|
| 1124 |
+
|
| 1125 |
+
self.assertAlmostEqual(loss_pretrained.item(), loss_init.item(), places=4)
|
| 1126 |
+
|
| 1127 |
+
@slow
|
| 1128 |
+
def test_rag_token_from_pretrained(self):
|
| 1129 |
+
rag_config = self.get_rag_config()
|
| 1130 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 1131 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 1132 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 1133 |
+
)
|
| 1134 |
+
rag_retriever = RagRetriever(
|
| 1135 |
+
rag_config,
|
| 1136 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 1137 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 1138 |
+
)
|
| 1139 |
+
|
| 1140 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 1141 |
+
"who sings does he love me with reba", return_tensors="pt"
|
| 1142 |
+
).input_ids
|
| 1143 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids
|
| 1144 |
+
|
| 1145 |
+
input_ids = input_ids.to(torch_device)
|
| 1146 |
+
decoder_input_ids = decoder_input_ids.to(torch_device)
|
| 1147 |
+
|
| 1148 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1149 |
+
rag_token = RagTokenForGeneration.from_pretrained_question_encoder_generator(
|
| 1150 |
+
"facebook/dpr-question_encoder-single-nq-base",
|
| 1151 |
+
"facebook/bart-large-cnn",
|
| 1152 |
+
retriever=rag_retriever,
|
| 1153 |
+
config=rag_config,
|
| 1154 |
+
question_encoder_max_length=200,
|
| 1155 |
+
generator_max_length=200,
|
| 1156 |
+
).to(torch_device)
|
| 1157 |
+
# check that the from pretrained methods work
|
| 1158 |
+
rag_token.save_pretrained(tmp_dirname)
|
| 1159 |
+
rag_token.from_pretrained(tmp_dirname, retriever=rag_retriever)
|
| 1160 |
+
rag_token.to(torch_device)
|
| 1161 |
+
|
| 1162 |
+
self.assertTrue(rag_token.question_encoder.config.max_length == 200)
|
| 1163 |
+
self.assertTrue(rag_token.generator.config.max_length == 200)
|
| 1164 |
+
|
| 1165 |
+
with torch.no_grad():
|
| 1166 |
+
output = rag_token(
|
| 1167 |
+
input_ids,
|
| 1168 |
+
labels=decoder_input_ids,
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
loss_pretrained = output.loss
|
| 1172 |
+
del rag_token
|
| 1173 |
+
|
| 1174 |
+
question_encoder = AutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 1175 |
+
generator = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn")
|
| 1176 |
+
rag_token = RagTokenForGeneration(
|
| 1177 |
+
config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever
|
| 1178 |
+
)
|
| 1179 |
+
rag_token.to(torch_device)
|
| 1180 |
+
|
| 1181 |
+
with torch.no_grad():
|
| 1182 |
+
output = rag_token(
|
| 1183 |
+
input_ids,
|
| 1184 |
+
labels=decoder_input_ids,
|
| 1185 |
+
)
|
| 1186 |
+
|
| 1187 |
+
loss_init = output.loss
|
| 1188 |
+
|
| 1189 |
+
self.assertAlmostEqual(loss_pretrained.item(), loss_init.item(), places=4)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_tf_rag.py
ADDED
|
@@ -0,0 +1,1080 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import tempfile
|
| 7 |
+
import unittest
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from transformers import BartTokenizer
|
| 13 |
+
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
|
| 14 |
+
from transformers.models.dpr.tokenization_dpr import DPRQuestionEncoderTokenizer
|
| 15 |
+
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
|
| 16 |
+
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
|
| 17 |
+
from transformers.utils import cached_property, is_datasets_available, is_faiss_available, is_tf_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if is_tf_available() and is_datasets_available() and is_faiss_available():
|
| 21 |
+
import faiss
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
|
| 25 |
+
from transformers import (
|
| 26 |
+
AutoConfig,
|
| 27 |
+
RagConfig,
|
| 28 |
+
RagRetriever,
|
| 29 |
+
RagTokenizer,
|
| 30 |
+
TFAutoModel,
|
| 31 |
+
TFAutoModelForSeq2SeqLM,
|
| 32 |
+
TFRagModel,
|
| 33 |
+
TFRagSequenceForGeneration,
|
| 34 |
+
TFRagTokenForGeneration,
|
| 35 |
+
)
|
| 36 |
+
from transformers.modeling_tf_outputs import TFBaseModelOutput
|
| 37 |
+
|
| 38 |
+
from ..bart.test_modeling_tf_bart import TFBartModelTester
|
| 39 |
+
from ..dpr.test_modeling_tf_dpr import TFDPRModelTester
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
TOLERANCE = 1e-3
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def require_retrieval(test_case):
|
| 46 |
+
"""
|
| 47 |
+
Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with
|
| 48 |
+
[`RagRetriever`].
|
| 49 |
+
|
| 50 |
+
These tests are skipped when respective libraries are not installed.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
if not (is_tf_available() and is_datasets_available() and is_faiss_available()):
|
| 54 |
+
test_case = unittest.skip("test requires tensorflow, datasets and faiss")(test_case)
|
| 55 |
+
return test_case
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@require_tf
|
| 59 |
+
@require_retrieval
|
| 60 |
+
@require_sentencepiece
|
| 61 |
+
class TFRagTestMixin:
|
| 62 |
+
all_model_classes = (
|
| 63 |
+
(TFRagModel, TFRagTokenForGeneration, TFRagSequenceForGeneration)
|
| 64 |
+
if is_tf_available() and is_datasets_available() and is_faiss_available()
|
| 65 |
+
else ()
|
| 66 |
+
)
|
| 67 |
+
all_generative_model_classes = (
|
| 68 |
+
(TFRagTokenForGeneration, TFRagSequenceForGeneration)
|
| 69 |
+
if is_tf_available() and is_datasets_available() and is_faiss_available()
|
| 70 |
+
else ()
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
retrieval_vector_size = 32
|
| 74 |
+
n_docs = 3
|
| 75 |
+
max_combined_length = 16
|
| 76 |
+
|
| 77 |
+
def setUp(self):
|
| 78 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 79 |
+
|
| 80 |
+
# DPR tok
|
| 81 |
+
vocab_tokens = [
|
| 82 |
+
"[UNK]",
|
| 83 |
+
"[CLS]",
|
| 84 |
+
"[SEP]",
|
| 85 |
+
"[PAD]",
|
| 86 |
+
"[MASK]",
|
| 87 |
+
"want",
|
| 88 |
+
"##want",
|
| 89 |
+
"##ed",
|
| 90 |
+
"wa",
|
| 91 |
+
"un",
|
| 92 |
+
"runn",
|
| 93 |
+
"##ing",
|
| 94 |
+
",",
|
| 95 |
+
"low",
|
| 96 |
+
"lowest",
|
| 97 |
+
]
|
| 98 |
+
dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer")
|
| 99 |
+
os.makedirs(dpr_tokenizer_path, exist_ok=True)
|
| 100 |
+
self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"])
|
| 101 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 102 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 103 |
+
|
| 104 |
+
# BART tok
|
| 105 |
+
vocab = [
|
| 106 |
+
"l",
|
| 107 |
+
"o",
|
| 108 |
+
"w",
|
| 109 |
+
"e",
|
| 110 |
+
"r",
|
| 111 |
+
"s",
|
| 112 |
+
"t",
|
| 113 |
+
"i",
|
| 114 |
+
"d",
|
| 115 |
+
"n",
|
| 116 |
+
"\u0120",
|
| 117 |
+
"\u0120l",
|
| 118 |
+
"\u0120n",
|
| 119 |
+
"\u0120lo",
|
| 120 |
+
"\u0120low",
|
| 121 |
+
"er",
|
| 122 |
+
"\u0120lowest",
|
| 123 |
+
"\u0120newer",
|
| 124 |
+
"\u0120wider",
|
| 125 |
+
"<unk>",
|
| 126 |
+
]
|
| 127 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 128 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 129 |
+
self.special_tokens_map = {"unk_token": "<unk>"}
|
| 130 |
+
|
| 131 |
+
bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer")
|
| 132 |
+
os.makedirs(bart_tokenizer_path, exist_ok=True)
|
| 133 |
+
self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"])
|
| 134 |
+
self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"])
|
| 135 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 136 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 137 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 138 |
+
fp.write("\n".join(merges))
|
| 139 |
+
|
| 140 |
+
@cached_property
|
| 141 |
+
def dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer:
|
| 142 |
+
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 143 |
+
|
| 144 |
+
@cached_property
|
| 145 |
+
def bart_tokenizer(self) -> BartTokenizer:
|
| 146 |
+
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer"))
|
| 147 |
+
|
| 148 |
+
def tearDown(self):
|
| 149 |
+
shutil.rmtree(self.tmpdirname)
|
| 150 |
+
|
| 151 |
+
def get_retriever(self, config):
|
| 152 |
+
dataset = Dataset.from_dict(
|
| 153 |
+
{
|
| 154 |
+
"id": ["0", "1", "3"],
|
| 155 |
+
"text": ["foo", "bar", "qux"],
|
| 156 |
+
"title": ["Foo", "Bar", "Qux"],
|
| 157 |
+
"embeddings": [
|
| 158 |
+
np.ones(self.retrieval_vector_size),
|
| 159 |
+
2 * np.ones(self.retrieval_vector_size),
|
| 160 |
+
3 * np.ones(self.retrieval_vector_size),
|
| 161 |
+
],
|
| 162 |
+
}
|
| 163 |
+
)
|
| 164 |
+
dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
|
| 165 |
+
tokenizer = self.bart_tokenizer
|
| 166 |
+
with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
|
| 167 |
+
mock_load_dataset.return_value = dataset
|
| 168 |
+
retriever = RagRetriever(
|
| 169 |
+
config,
|
| 170 |
+
question_encoder_tokenizer=self.dpr_tokenizer,
|
| 171 |
+
generator_tokenizer=tokenizer,
|
| 172 |
+
)
|
| 173 |
+
return retriever
|
| 174 |
+
|
| 175 |
+
def check_model_with_retriever(
|
| 176 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 177 |
+
):
|
| 178 |
+
self.assertIsNotNone(config.question_encoder)
|
| 179 |
+
self.assertIsNotNone(config.generator)
|
| 180 |
+
|
| 181 |
+
for model_class in self.all_model_classes:
|
| 182 |
+
model = model_class(config, retriever=self.get_retriever(config))
|
| 183 |
+
|
| 184 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 185 |
+
|
| 186 |
+
outputs = model(
|
| 187 |
+
input_ids=input_ids,
|
| 188 |
+
attention_mask=attention_mask,
|
| 189 |
+
decoder_input_ids=decoder_input_ids,
|
| 190 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# logits
|
| 194 |
+
self.assertEqual(
|
| 195 |
+
outputs.logits.shape,
|
| 196 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 197 |
+
)
|
| 198 |
+
# generator encoder last hidden states
|
| 199 |
+
self.assertEqual(
|
| 200 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 201 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 202 |
+
)
|
| 203 |
+
# doc scores
|
| 204 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 205 |
+
|
| 206 |
+
def check_model_generate_from_context_input_ids(
|
| 207 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 208 |
+
):
|
| 209 |
+
self.assertIsNotNone(config.question_encoder)
|
| 210 |
+
self.assertIsNotNone(config.generator)
|
| 211 |
+
|
| 212 |
+
retriever = self.get_retriever(config)
|
| 213 |
+
|
| 214 |
+
for i, model_class in enumerate(self.all_generative_model_classes):
|
| 215 |
+
model = model_class(config)
|
| 216 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 217 |
+
|
| 218 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 219 |
+
|
| 220 |
+
out = retriever(
|
| 221 |
+
input_ids,
|
| 222 |
+
question_hidden_states.numpy(),
|
| 223 |
+
prefix=config.generator.prefix,
|
| 224 |
+
return_tensors="tf",
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 228 |
+
out["context_input_ids"],
|
| 229 |
+
out["context_attention_mask"],
|
| 230 |
+
out["retrieved_doc_embeds"],
|
| 231 |
+
)
|
| 232 |
+
retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
|
| 233 |
+
|
| 234 |
+
# compute doc_scores
|
| 235 |
+
doc_scores = tf.squeeze(
|
| 236 |
+
tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True),
|
| 237 |
+
axis=[1],
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
outputs = model.generate(
|
| 241 |
+
context_input_ids=context_input_ids,
|
| 242 |
+
context_attention_mask=context_attention_mask,
|
| 243 |
+
doc_scores=doc_scores,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
self.assertIsNotNone(outputs)
|
| 247 |
+
|
| 248 |
+
def check_model_generate(
|
| 249 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 250 |
+
):
|
| 251 |
+
self.assertIsNotNone(config.question_encoder)
|
| 252 |
+
self.assertIsNotNone(config.generator)
|
| 253 |
+
|
| 254 |
+
for model_class in self.all_generative_model_classes:
|
| 255 |
+
model = model_class(config, retriever=self.get_retriever(config))
|
| 256 |
+
|
| 257 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 258 |
+
|
| 259 |
+
input_ids = tf.cast(input_ids, tf.int32)
|
| 260 |
+
outputs = model.generate(
|
| 261 |
+
input_ids=input_ids,
|
| 262 |
+
num_beams=2,
|
| 263 |
+
num_return_sequences=2,
|
| 264 |
+
decoder_start_token_id=config.generator.eos_token_id,
|
| 265 |
+
max_new_tokens=5,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
self.assertIsNotNone(outputs)
|
| 269 |
+
|
| 270 |
+
def check_model_without_retriever(
|
| 271 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 272 |
+
):
|
| 273 |
+
self.assertIsNotNone(config.question_encoder)
|
| 274 |
+
self.assertIsNotNone(config.generator)
|
| 275 |
+
|
| 276 |
+
retriever = self.get_retriever(config)
|
| 277 |
+
|
| 278 |
+
for model_class in self.all_model_classes:
|
| 279 |
+
model = model_class(config)
|
| 280 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 281 |
+
|
| 282 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 283 |
+
|
| 284 |
+
out = retriever(
|
| 285 |
+
input_ids,
|
| 286 |
+
question_hidden_states.numpy(),
|
| 287 |
+
prefix=config.generator.prefix,
|
| 288 |
+
return_tensors="tf",
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 292 |
+
out["context_input_ids"],
|
| 293 |
+
out["context_attention_mask"],
|
| 294 |
+
out["retrieved_doc_embeds"],
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
|
| 298 |
+
|
| 299 |
+
# compute doc_scores
|
| 300 |
+
doc_scores = tf.squeeze(
|
| 301 |
+
tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True),
|
| 302 |
+
axis=[1],
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
outputs = model(
|
| 306 |
+
input_ids=None,
|
| 307 |
+
context_input_ids=context_input_ids,
|
| 308 |
+
context_attention_mask=context_attention_mask,
|
| 309 |
+
doc_scores=doc_scores,
|
| 310 |
+
decoder_input_ids=decoder_input_ids,
|
| 311 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
# logits
|
| 315 |
+
self.assertEqual(
|
| 316 |
+
outputs.logits.shape,
|
| 317 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
# generator encoder last hidden states
|
| 321 |
+
self.assertEqual(
|
| 322 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 323 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 324 |
+
)
|
| 325 |
+
# doc scores
|
| 326 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 327 |
+
|
| 328 |
+
def check_model_custom_n_docs(
|
| 329 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, n_docs, **kwargs
|
| 330 |
+
):
|
| 331 |
+
self.assertIsNotNone(config.question_encoder)
|
| 332 |
+
self.assertIsNotNone(config.generator)
|
| 333 |
+
|
| 334 |
+
retriever = self.get_retriever(config)
|
| 335 |
+
|
| 336 |
+
for model_class in self.all_model_classes:
|
| 337 |
+
model = model_class(config)
|
| 338 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 339 |
+
|
| 340 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 341 |
+
|
| 342 |
+
out = retriever(
|
| 343 |
+
input_ids,
|
| 344 |
+
question_hidden_states.numpy(),
|
| 345 |
+
prefix=config.generator.prefix,
|
| 346 |
+
return_tensors="tf",
|
| 347 |
+
n_docs=n_docs,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 351 |
+
out["context_input_ids"],
|
| 352 |
+
out["context_attention_mask"],
|
| 353 |
+
out["retrieved_doc_embeds"],
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
|
| 357 |
+
|
| 358 |
+
# compute doc_scores
|
| 359 |
+
doc_scores = tf.squeeze(
|
| 360 |
+
tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True),
|
| 361 |
+
axis=[1],
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
outputs = model(
|
| 365 |
+
input_ids=None,
|
| 366 |
+
context_input_ids=context_input_ids,
|
| 367 |
+
context_attention_mask=context_attention_mask,
|
| 368 |
+
doc_scores=doc_scores,
|
| 369 |
+
decoder_input_ids=decoder_input_ids,
|
| 370 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 371 |
+
n_docs=n_docs,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
# logits
|
| 375 |
+
self.assertEqual(
|
| 376 |
+
outputs.logits.shape,
|
| 377 |
+
(n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 378 |
+
)
|
| 379 |
+
# generator encoder last hidden states
|
| 380 |
+
self.assertEqual(
|
| 381 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 382 |
+
(n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 383 |
+
)
|
| 384 |
+
# doc scores
|
| 385 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], n_docs))
|
| 386 |
+
|
| 387 |
+
def check_model_with_mismatch_n_docs_value(
|
| 388 |
+
self,
|
| 389 |
+
config,
|
| 390 |
+
input_ids,
|
| 391 |
+
attention_mask,
|
| 392 |
+
decoder_input_ids,
|
| 393 |
+
decoder_attention_mask,
|
| 394 |
+
retriever_n_docs,
|
| 395 |
+
generator_n_docs,
|
| 396 |
+
**kwargs,
|
| 397 |
+
):
|
| 398 |
+
self.assertIsNotNone(config.question_encoder)
|
| 399 |
+
self.assertIsNotNone(config.generator)
|
| 400 |
+
|
| 401 |
+
retriever = self.get_retriever(config)
|
| 402 |
+
|
| 403 |
+
for model_class in self.all_model_classes:
|
| 404 |
+
model = model_class(config)
|
| 405 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 406 |
+
|
| 407 |
+
question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0]
|
| 408 |
+
|
| 409 |
+
out = retriever(
|
| 410 |
+
input_ids,
|
| 411 |
+
question_hidden_states.numpy(),
|
| 412 |
+
prefix=config.generator.prefix,
|
| 413 |
+
return_tensors="tf",
|
| 414 |
+
n_docs=retriever_n_docs,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 418 |
+
out["context_input_ids"],
|
| 419 |
+
out["context_attention_mask"],
|
| 420 |
+
out["retrieved_doc_embeds"],
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32)
|
| 424 |
+
|
| 425 |
+
# compute doc_scores
|
| 426 |
+
doc_scores = tf.squeeze(
|
| 427 |
+
tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True),
|
| 428 |
+
axis=[1],
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
self.assertRaises(
|
| 432 |
+
AssertionError,
|
| 433 |
+
model.__call__,
|
| 434 |
+
input_ids=None,
|
| 435 |
+
context_input_ids=context_input_ids,
|
| 436 |
+
context_attention_mask=context_attention_mask,
|
| 437 |
+
doc_scores=doc_scores,
|
| 438 |
+
decoder_input_ids=decoder_input_ids,
|
| 439 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 440 |
+
n_docs=generator_n_docs,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
def check_model_with_encoder_outputs(
|
| 444 |
+
self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs
|
| 445 |
+
):
|
| 446 |
+
self.assertIsNotNone(config.question_encoder)
|
| 447 |
+
self.assertIsNotNone(config.generator)
|
| 448 |
+
|
| 449 |
+
for model_class in self.all_model_classes:
|
| 450 |
+
model = model_class(config, retriever=self.get_retriever(config))
|
| 451 |
+
|
| 452 |
+
self.assertTrue(model.config.is_encoder_decoder)
|
| 453 |
+
|
| 454 |
+
outputs = model(
|
| 455 |
+
input_ids=input_ids,
|
| 456 |
+
attention_mask=attention_mask,
|
| 457 |
+
decoder_input_ids=decoder_input_ids,
|
| 458 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
encoder_outputs = TFBaseModelOutput(outputs.generator_enc_last_hidden_state)
|
| 462 |
+
|
| 463 |
+
# run only generator
|
| 464 |
+
outputs = model(
|
| 465 |
+
input_ids=None,
|
| 466 |
+
encoder_outputs=encoder_outputs,
|
| 467 |
+
doc_scores=outputs.doc_scores,
|
| 468 |
+
decoder_input_ids=decoder_input_ids,
|
| 469 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
# logits
|
| 473 |
+
self.assertEqual(
|
| 474 |
+
outputs.logits.shape,
|
| 475 |
+
(self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size),
|
| 476 |
+
)
|
| 477 |
+
# generator encoder last hidden states
|
| 478 |
+
self.assertEqual(
|
| 479 |
+
outputs.generator_enc_last_hidden_state.shape,
|
| 480 |
+
(self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size),
|
| 481 |
+
)
|
| 482 |
+
# doc scores
|
| 483 |
+
self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs))
|
| 484 |
+
|
| 485 |
+
def test_model_with_retriever(self):
|
| 486 |
+
inputs_dict = self.config_and_inputs
|
| 487 |
+
self.check_model_with_retriever(**inputs_dict)
|
| 488 |
+
|
| 489 |
+
def test_model_without_retriever(self):
|
| 490 |
+
inputs_dict = self.config_and_inputs
|
| 491 |
+
self.check_model_without_retriever(**inputs_dict)
|
| 492 |
+
|
| 493 |
+
@slow
|
| 494 |
+
def test_model_generate_from_context_input_ids(self):
|
| 495 |
+
inputs_dict = self.config_and_inputs
|
| 496 |
+
self.check_model_generate_from_context_input_ids(**inputs_dict)
|
| 497 |
+
|
| 498 |
+
def test_model_with_encoder_outputs(self):
|
| 499 |
+
inputs_dict = self.config_and_inputs
|
| 500 |
+
self.check_model_with_encoder_outputs(**inputs_dict)
|
| 501 |
+
|
| 502 |
+
@slow
|
| 503 |
+
def test_model_generate(self):
|
| 504 |
+
inputs_dict = self.config_and_inputs
|
| 505 |
+
self.check_model_generate(**inputs_dict)
|
| 506 |
+
|
| 507 |
+
def test_model_with_custom_n_docs(self):
|
| 508 |
+
inputs_dict = self.config_and_inputs
|
| 509 |
+
inputs_dict["n_docs"] = 1
|
| 510 |
+
self.check_model_custom_n_docs(**inputs_dict)
|
| 511 |
+
|
| 512 |
+
def test_model_with_mismatch_n_docs_value(self):
|
| 513 |
+
inputs_dict = self.config_and_inputs
|
| 514 |
+
inputs_dict["retriever_n_docs"] = 3
|
| 515 |
+
inputs_dict["generator_n_docs"] = 2
|
| 516 |
+
self.check_model_with_mismatch_n_docs_value(**inputs_dict)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@require_tf
|
| 520 |
+
@require_retrieval
|
| 521 |
+
class TFRagDPRBartTest(TFRagTestMixin, unittest.TestCase):
|
| 522 |
+
@cached_property
|
| 523 |
+
def config_and_inputs(self):
|
| 524 |
+
question_encoder_tester = TFDPRModelTester(self)
|
| 525 |
+
dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs()
|
| 526 |
+
generator_tester = TFBartModelTester(self)
|
| 527 |
+
bart_config_and_inputs = generator_tester.prepare_config_and_inputs_for_common()
|
| 528 |
+
|
| 529 |
+
(question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs
|
| 530 |
+
(generator_config, bart_inputs_dict) = bart_config_and_inputs
|
| 531 |
+
decoder_input_ids, decoder_attention_mask = bart_inputs_dict["input_ids"], bart_inputs_dict["attention_mask"]
|
| 532 |
+
|
| 533 |
+
config = RagConfig.from_question_encoder_generator_configs(
|
| 534 |
+
question_encoder_config,
|
| 535 |
+
generator_config,
|
| 536 |
+
n_docs=self.n_docs,
|
| 537 |
+
retrieval_vector_size=self.retrieval_vector_size,
|
| 538 |
+
max_combined_length=self.max_combined_length,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
return {
|
| 542 |
+
"config": config,
|
| 543 |
+
"input_ids": input_ids,
|
| 544 |
+
"attention_mask": input_mask,
|
| 545 |
+
"decoder_input_ids": decoder_input_ids,
|
| 546 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@require_tf
|
| 551 |
+
@require_retrieval
|
| 552 |
+
@require_sentencepiece
|
| 553 |
+
@require_tokenizers
|
| 554 |
+
class TFRagModelIntegrationTests(unittest.TestCase):
|
| 555 |
+
@cached_property
|
| 556 |
+
def token_model(self):
|
| 557 |
+
return TFRagTokenForGeneration.from_pretrained_question_encoder_generator(
|
| 558 |
+
"facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn"
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
@cached_property
|
| 562 |
+
def sequence_model(self):
|
| 563 |
+
return TFRagSequenceForGeneration.from_pretrained_question_encoder_generator(
|
| 564 |
+
"facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn"
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
def token_model_nq_checkpoint(self, retriever):
|
| 568 |
+
return TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
|
| 569 |
+
|
| 570 |
+
def get_rag_config(self):
|
| 571 |
+
question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 572 |
+
generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn")
|
| 573 |
+
return RagConfig.from_question_encoder_generator_configs(
|
| 574 |
+
question_encoder_config,
|
| 575 |
+
generator_config,
|
| 576 |
+
bos_token_id=0,
|
| 577 |
+
decoder_start_token_id=2,
|
| 578 |
+
eos_token_id=2,
|
| 579 |
+
is_encoder_decoder=True,
|
| 580 |
+
pad_token_id=1,
|
| 581 |
+
vocab_size=50264,
|
| 582 |
+
title_sep=" / ",
|
| 583 |
+
doc_sep=" // ",
|
| 584 |
+
n_docs=5,
|
| 585 |
+
max_combined_length=300,
|
| 586 |
+
dataset="wiki_dpr",
|
| 587 |
+
dataset_split="train",
|
| 588 |
+
index_name="exact",
|
| 589 |
+
index_path=None,
|
| 590 |
+
use_dummy_dataset=True,
|
| 591 |
+
retrieval_vector_size=768,
|
| 592 |
+
retrieval_batch_size=8,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
@slow
|
| 596 |
+
def test_rag_sequence_inference(self):
|
| 597 |
+
rag_config = self.get_rag_config()
|
| 598 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 599 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 600 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 601 |
+
)
|
| 602 |
+
rag_retriever = RagRetriever(
|
| 603 |
+
rag_config,
|
| 604 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 605 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
rag_sequence = self.sequence_model
|
| 609 |
+
rag_sequence.set_retriever(rag_retriever)
|
| 610 |
+
|
| 611 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 612 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 613 |
+
).input_ids
|
| 614 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 615 |
+
|
| 616 |
+
output = rag_sequence(
|
| 617 |
+
input_ids,
|
| 618 |
+
labels=decoder_input_ids,
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
expected_shape = tf.TensorShape([5, 5, 50264])
|
| 622 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 623 |
+
|
| 624 |
+
expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]])
|
| 625 |
+
expected_loss = tf.convert_to_tensor([36.7368])
|
| 626 |
+
|
| 627 |
+
tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
|
| 628 |
+
tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3)
|
| 629 |
+
|
| 630 |
+
@slow
|
| 631 |
+
def test_rag_token_inference(self):
|
| 632 |
+
rag_config = self.get_rag_config()
|
| 633 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 634 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 635 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 636 |
+
)
|
| 637 |
+
rag_retriever = RagRetriever(
|
| 638 |
+
rag_config,
|
| 639 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 640 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
rag_token = self.token_model
|
| 644 |
+
rag_token.set_retriever(rag_retriever)
|
| 645 |
+
|
| 646 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 647 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 648 |
+
).input_ids
|
| 649 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 650 |
+
|
| 651 |
+
output = rag_token(
|
| 652 |
+
input_ids,
|
| 653 |
+
labels=decoder_input_ids,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
expected_shape = tf.TensorShape([5, 5, 50264])
|
| 657 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 658 |
+
|
| 659 |
+
expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]])
|
| 660 |
+
expected_loss = tf.convert_to_tensor([36.3557])
|
| 661 |
+
|
| 662 |
+
tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
|
| 663 |
+
tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3)
|
| 664 |
+
|
| 665 |
+
@slow
|
| 666 |
+
def test_rag_token_inference_nq_checkpoint(self):
|
| 667 |
+
rag_config = self.get_rag_config()
|
| 668 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 669 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 670 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 671 |
+
)
|
| 672 |
+
rag_retriever = RagRetriever(
|
| 673 |
+
rag_config,
|
| 674 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 675 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
rag_token = self.token_model_nq_checkpoint(retriever=rag_retriever)
|
| 679 |
+
|
| 680 |
+
# check that outputs after saving and loading are equal
|
| 681 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 682 |
+
rag_token.save_pretrained(tmpdirname)
|
| 683 |
+
rag_token = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever)
|
| 684 |
+
|
| 685 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 686 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 687 |
+
).input_ids
|
| 688 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 689 |
+
|
| 690 |
+
output = rag_token(
|
| 691 |
+
input_ids,
|
| 692 |
+
labels=decoder_input_ids,
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
expected_shape = tf.TensorShape([5, 5, 50265])
|
| 696 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 697 |
+
|
| 698 |
+
expected_doc_scores = tf.convert_to_tensor([[62.9402, 62.7107, 62.2382, 62.1194, 61.8578]])
|
| 699 |
+
expected_loss = tf.convert_to_tensor([32.521812])
|
| 700 |
+
|
| 701 |
+
tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
|
| 702 |
+
tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3)
|
| 703 |
+
|
| 704 |
+
@slow
|
| 705 |
+
def test_rag_token_inference_save_pretrained(self):
|
| 706 |
+
rag_config = self.get_rag_config()
|
| 707 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 708 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 709 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 710 |
+
)
|
| 711 |
+
rag_retriever = RagRetriever(
|
| 712 |
+
rag_config,
|
| 713 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 714 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
rag_token = self.token_model
|
| 718 |
+
rag_token.set_retriever(rag_retriever)
|
| 719 |
+
|
| 720 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 721 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 722 |
+
).input_ids
|
| 723 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 724 |
+
|
| 725 |
+
# model must run once to be functional before loading/saving works
|
| 726 |
+
rag_token(
|
| 727 |
+
input_ids,
|
| 728 |
+
labels=decoder_input_ids,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
# check that outputs after saving and loading are equal
|
| 732 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 733 |
+
rag_token.save_pretrained(tmpdirname)
|
| 734 |
+
rag_token = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever)
|
| 735 |
+
|
| 736 |
+
output = rag_token(
|
| 737 |
+
input_ids,
|
| 738 |
+
labels=decoder_input_ids,
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
+
expected_shape = tf.TensorShape([5, 5, 50264])
|
| 742 |
+
self.assertEqual(output.logits.shape, expected_shape)
|
| 743 |
+
|
| 744 |
+
expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]])
|
| 745 |
+
expected_loss = tf.convert_to_tensor([36.3557])
|
| 746 |
+
|
| 747 |
+
tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
|
| 748 |
+
tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3)
|
| 749 |
+
|
| 750 |
+
@slow
|
| 751 |
+
def test_init_and_from_pretrained(self):
|
| 752 |
+
rag_config = self.get_rag_config()
|
| 753 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 754 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 755 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 756 |
+
)
|
| 757 |
+
rag_retriever = RagRetriever(
|
| 758 |
+
rag_config,
|
| 759 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 760 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
rag_config = RagConfig.from_pretrained("facebook/rag-sequence-base")
|
| 764 |
+
rag = TFRagTokenForGeneration(rag_config, retriever=rag_retriever)
|
| 765 |
+
|
| 766 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 767 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 768 |
+
).input_ids
|
| 769 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 770 |
+
|
| 771 |
+
rag(
|
| 772 |
+
input_ids,
|
| 773 |
+
decoder_input_ids=decoder_input_ids,
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
# this should not give any warnings
|
| 777 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 778 |
+
rag.save_pretrained(tmpdirname)
|
| 779 |
+
rag = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever)
|
| 780 |
+
|
| 781 |
+
@property
|
| 782 |
+
def test_data_questions(self):
|
| 783 |
+
return [
|
| 784 |
+
"who got the first nobel prize in physics",
|
| 785 |
+
"when is the next deadpool movie being released",
|
| 786 |
+
"which mode is used for short wave broadcast service",
|
| 787 |
+
"who is the owner of reading football club",
|
| 788 |
+
"when is the next scandal episode coming out",
|
| 789 |
+
"when is the last time the philadelphia won the superbowl",
|
| 790 |
+
"what is the most current adobe flash player version",
|
| 791 |
+
"how many episodes are there in dragon ball z",
|
| 792 |
+
]
|
| 793 |
+
|
| 794 |
+
@slow
|
| 795 |
+
def test_rag_token_greedy_search(self):
|
| 796 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
|
| 797 |
+
retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True)
|
| 798 |
+
rag_token = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
|
| 799 |
+
|
| 800 |
+
# check first two questions
|
| 801 |
+
input_dict = tokenizer(
|
| 802 |
+
self.test_data_questions[:2],
|
| 803 |
+
return_tensors="tf",
|
| 804 |
+
padding=True,
|
| 805 |
+
truncation=True,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
input_ids = input_dict.input_ids
|
| 809 |
+
attention_mask = input_dict.attention_mask
|
| 810 |
+
|
| 811 |
+
# make sure only 1 beam is used
|
| 812 |
+
rag_token.config.num_beams = 1
|
| 813 |
+
|
| 814 |
+
output_ids = rag_token.generate(
|
| 815 |
+
input_ids,
|
| 816 |
+
attention_mask=attention_mask,
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 820 |
+
|
| 821 |
+
EXPECTED_OUTPUTS = [
|
| 822 |
+
" albert einstein",
|
| 823 |
+
" september 22, 2017",
|
| 824 |
+
]
|
| 825 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 826 |
+
|
| 827 |
+
@slow
|
| 828 |
+
def test_rag_token_generate_batch(self):
|
| 829 |
+
# NOTE: gold labels comes from num_beam=4, so this is effectively beam-search test
|
| 830 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
|
| 831 |
+
retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True)
|
| 832 |
+
rag_token = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
|
| 833 |
+
|
| 834 |
+
input_dict = tokenizer(
|
| 835 |
+
self.test_data_questions,
|
| 836 |
+
return_tensors="tf",
|
| 837 |
+
padding=True,
|
| 838 |
+
truncation=True,
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
input_ids = input_dict.input_ids
|
| 842 |
+
attention_mask = input_dict.attention_mask
|
| 843 |
+
|
| 844 |
+
EXPECTED_OUTPUTS = [
|
| 845 |
+
" albert einstein",
|
| 846 |
+
" september 22, 2017",
|
| 847 |
+
" amplitude modulation",
|
| 848 |
+
" stefan persson",
|
| 849 |
+
" april 20, 2018",
|
| 850 |
+
" the 1970s",
|
| 851 |
+
" 7.1. 2",
|
| 852 |
+
" 13",
|
| 853 |
+
]
|
| 854 |
+
|
| 855 |
+
# Split into 2 batches of 4 examples to avoid GPU OOM.
|
| 856 |
+
output_ids = rag_token.generate(
|
| 857 |
+
input_ids[:4],
|
| 858 |
+
attention_mask=attention_mask[:4],
|
| 859 |
+
)
|
| 860 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 861 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS[:4])
|
| 862 |
+
|
| 863 |
+
output_ids = rag_token.generate(
|
| 864 |
+
input_ids[4:],
|
| 865 |
+
attention_mask=attention_mask[4:],
|
| 866 |
+
)
|
| 867 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 868 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS[4:])
|
| 869 |
+
|
| 870 |
+
@slow
|
| 871 |
+
def test_rag_sequence_generate_batch(self):
|
| 872 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
|
| 873 |
+
retriever = RagRetriever.from_pretrained(
|
| 874 |
+
"facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
|
| 875 |
+
)
|
| 876 |
+
rag_sequence = TFRagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever)
|
| 877 |
+
|
| 878 |
+
input_dict = tokenizer(
|
| 879 |
+
self.test_data_questions,
|
| 880 |
+
return_tensors="tf",
|
| 881 |
+
padding=True,
|
| 882 |
+
truncation=True,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
input_ids = input_dict.input_ids
|
| 886 |
+
attention_mask = input_dict.attention_mask
|
| 887 |
+
|
| 888 |
+
output_ids = rag_sequence.generate(
|
| 889 |
+
input_ids,
|
| 890 |
+
attention_mask=attention_mask,
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 894 |
+
|
| 895 |
+
EXPECTED_OUTPUTS = [
|
| 896 |
+
" albert einstein",
|
| 897 |
+
" june 22, 2018",
|
| 898 |
+
" amplitude modulation",
|
| 899 |
+
" tim besley ( chairman )",
|
| 900 |
+
" june 20, 2018",
|
| 901 |
+
" 1980",
|
| 902 |
+
" 7.0",
|
| 903 |
+
" 8",
|
| 904 |
+
]
|
| 905 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 906 |
+
|
| 907 |
+
@slow
|
| 908 |
+
def test_rag_sequence_generate_batch_from_context_input_ids(self):
|
| 909 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
|
| 910 |
+
retriever = RagRetriever.from_pretrained(
|
| 911 |
+
"facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
|
| 912 |
+
)
|
| 913 |
+
rag_sequence = TFRagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever)
|
| 914 |
+
input_dict = tokenizer(
|
| 915 |
+
self.test_data_questions,
|
| 916 |
+
return_tensors="tf",
|
| 917 |
+
padding=True,
|
| 918 |
+
truncation=True,
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
input_ids = input_dict.input_ids
|
| 922 |
+
|
| 923 |
+
question_hidden_states = rag_sequence.question_encoder(input_ids)[0]
|
| 924 |
+
docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
|
| 925 |
+
doc_scores = tf.squeeze(
|
| 926 |
+
tf.matmul(
|
| 927 |
+
tf.expand_dims(question_hidden_states, axis=[1]), docs_dict["retrieved_doc_embeds"], transpose_b=True
|
| 928 |
+
),
|
| 929 |
+
axis=[1],
|
| 930 |
+
)
|
| 931 |
+
output_ids = rag_sequence.generate(
|
| 932 |
+
context_input_ids=docs_dict["context_input_ids"],
|
| 933 |
+
context_attention_mask=docs_dict["context_attention_mask"],
|
| 934 |
+
doc_scores=doc_scores,
|
| 935 |
+
do_deduplication=True,
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 939 |
+
|
| 940 |
+
EXPECTED_OUTPUTS = [
|
| 941 |
+
" albert einstein",
|
| 942 |
+
" june 22, 2018",
|
| 943 |
+
" amplitude modulation",
|
| 944 |
+
" tim besley ( chairman )",
|
| 945 |
+
" june 20, 2018",
|
| 946 |
+
" 1980",
|
| 947 |
+
" 7.0",
|
| 948 |
+
" 8",
|
| 949 |
+
]
|
| 950 |
+
self.assertListEqual(outputs, EXPECTED_OUTPUTS)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
@require_tf
|
| 954 |
+
@require_retrieval
|
| 955 |
+
class TFRagModelSaveLoadTests(unittest.TestCase):
|
| 956 |
+
def get_rag_config(self):
|
| 957 |
+
question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 958 |
+
generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn")
|
| 959 |
+
return RagConfig.from_question_encoder_generator_configs(
|
| 960 |
+
question_encoder_config,
|
| 961 |
+
generator_config,
|
| 962 |
+
bos_token_id=0,
|
| 963 |
+
decoder_start_token_id=2,
|
| 964 |
+
eos_token_id=2,
|
| 965 |
+
is_encoder_decoder=True,
|
| 966 |
+
pad_token_id=1,
|
| 967 |
+
vocab_size=50264,
|
| 968 |
+
title_sep=" / ",
|
| 969 |
+
doc_sep=" // ",
|
| 970 |
+
n_docs=5,
|
| 971 |
+
max_combined_length=300,
|
| 972 |
+
dataset="wiki_dpr",
|
| 973 |
+
dataset_split="train",
|
| 974 |
+
index_name="exact",
|
| 975 |
+
index_path=None,
|
| 976 |
+
use_dummy_dataset=True,
|
| 977 |
+
retrieval_vector_size=768,
|
| 978 |
+
retrieval_batch_size=8,
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
@slow
|
| 982 |
+
def test_rag_sequence_from_pretrained(self):
|
| 983 |
+
load_weight_prefix = "tf_rag_model_1"
|
| 984 |
+
|
| 985 |
+
rag_config = self.get_rag_config()
|
| 986 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 987 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 988 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 989 |
+
)
|
| 990 |
+
rag_retriever = RagRetriever(
|
| 991 |
+
rag_config,
|
| 992 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 993 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 997 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 998 |
+
).input_ids
|
| 999 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 1000 |
+
|
| 1001 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1002 |
+
rag_sequence = TFRagSequenceForGeneration.from_pretrained_question_encoder_generator(
|
| 1003 |
+
"facebook/dpr-question_encoder-single-nq-base",
|
| 1004 |
+
"facebook/bart-large-cnn",
|
| 1005 |
+
retriever=rag_retriever,
|
| 1006 |
+
config=rag_config,
|
| 1007 |
+
)
|
| 1008 |
+
# check that the from pretrained methods work
|
| 1009 |
+
rag_sequence.save_pretrained(tmp_dirname)
|
| 1010 |
+
rag_sequence.from_pretrained(tmp_dirname, retriever=rag_retriever)
|
| 1011 |
+
|
| 1012 |
+
output = rag_sequence(input_ids, labels=decoder_input_ids)
|
| 1013 |
+
|
| 1014 |
+
loss_pretrained = output.loss
|
| 1015 |
+
del rag_sequence
|
| 1016 |
+
|
| 1017 |
+
question_encoder = TFAutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 1018 |
+
generator = TFAutoModelForSeq2SeqLM.from_pretrained(
|
| 1019 |
+
"facebook/bart-large-cnn", load_weight_prefix=load_weight_prefix, name="generator"
|
| 1020 |
+
)
|
| 1021 |
+
|
| 1022 |
+
rag_sequence = TFRagSequenceForGeneration(
|
| 1023 |
+
config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
output = rag_sequence(input_ids, labels=decoder_input_ids)
|
| 1027 |
+
|
| 1028 |
+
loss_init = output.loss
|
| 1029 |
+
|
| 1030 |
+
self.assertAlmostEqual(loss_pretrained, loss_init, places=4)
|
| 1031 |
+
|
| 1032 |
+
@slow
|
| 1033 |
+
def test_rag_token_from_pretrained(self):
|
| 1034 |
+
load_weight_prefix = "tf_rag_model_1"
|
| 1035 |
+
|
| 1036 |
+
rag_config = self.get_rag_config()
|
| 1037 |
+
rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 1038 |
+
rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
|
| 1039 |
+
"facebook/dpr-question_encoder-single-nq-base"
|
| 1040 |
+
)
|
| 1041 |
+
rag_retriever = RagRetriever(
|
| 1042 |
+
rag_config,
|
| 1043 |
+
question_encoder_tokenizer=rag_question_encoder_tokenizer,
|
| 1044 |
+
generator_tokenizer=rag_decoder_tokenizer,
|
| 1045 |
+
)
|
| 1046 |
+
|
| 1047 |
+
input_ids = rag_question_encoder_tokenizer(
|
| 1048 |
+
"who sings does he love me with reba", return_tensors="tf"
|
| 1049 |
+
).input_ids
|
| 1050 |
+
decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids
|
| 1051 |
+
|
| 1052 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1053 |
+
rag_token = TFRagTokenForGeneration.from_pretrained_question_encoder_generator(
|
| 1054 |
+
"facebook/dpr-question_encoder-single-nq-base",
|
| 1055 |
+
"facebook/bart-large-cnn",
|
| 1056 |
+
retriever=rag_retriever,
|
| 1057 |
+
config=rag_config,
|
| 1058 |
+
)
|
| 1059 |
+
# check that the from pretrained methods work
|
| 1060 |
+
rag_token.save_pretrained(tmp_dirname)
|
| 1061 |
+
rag_token.from_pretrained(tmp_dirname, retriever=rag_retriever)
|
| 1062 |
+
|
| 1063 |
+
output = rag_token(input_ids, labels=decoder_input_ids)
|
| 1064 |
+
|
| 1065 |
+
loss_pretrained = output.loss
|
| 1066 |
+
del rag_token
|
| 1067 |
+
|
| 1068 |
+
question_encoder = TFAutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 1069 |
+
generator = TFAutoModelForSeq2SeqLM.from_pretrained(
|
| 1070 |
+
"facebook/bart-large-cnn", load_weight_prefix=load_weight_prefix, name="generator"
|
| 1071 |
+
)
|
| 1072 |
+
rag_token = TFRagTokenForGeneration(
|
| 1073 |
+
config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
output = rag_token(input_ids, labels=decoder_input_ids)
|
| 1077 |
+
|
| 1078 |
+
loss_init = output.loss
|
| 1079 |
+
|
| 1080 |
+
self.assertAlmostEqual(loss_pretrained, loss_init, places=4)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_retrieval_rag.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import tempfile
|
| 19 |
+
from unittest import TestCase
|
| 20 |
+
from unittest.mock import patch
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
|
| 25 |
+
from transformers import is_faiss_available
|
| 26 |
+
from transformers.models.bart.configuration_bart import BartConfig
|
| 27 |
+
from transformers.models.bart.tokenization_bart import BartTokenizer
|
| 28 |
+
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
|
| 29 |
+
from transformers.models.dpr.configuration_dpr import DPRConfig
|
| 30 |
+
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
|
| 31 |
+
from transformers.models.rag.configuration_rag import RagConfig
|
| 32 |
+
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
|
| 33 |
+
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
|
| 34 |
+
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if is_faiss_available():
|
| 38 |
+
import faiss
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@require_faiss
|
| 42 |
+
class RagRetrieverTest(TestCase):
|
| 43 |
+
def setUp(self):
|
| 44 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 45 |
+
self.retrieval_vector_size = 8
|
| 46 |
+
|
| 47 |
+
# DPR tok
|
| 48 |
+
vocab_tokens = [
|
| 49 |
+
"[UNK]",
|
| 50 |
+
"[CLS]",
|
| 51 |
+
"[SEP]",
|
| 52 |
+
"[PAD]",
|
| 53 |
+
"[MASK]",
|
| 54 |
+
"want",
|
| 55 |
+
"##want",
|
| 56 |
+
"##ed",
|
| 57 |
+
"wa",
|
| 58 |
+
"un",
|
| 59 |
+
"runn",
|
| 60 |
+
"##ing",
|
| 61 |
+
",",
|
| 62 |
+
"low",
|
| 63 |
+
"lowest",
|
| 64 |
+
]
|
| 65 |
+
dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer")
|
| 66 |
+
os.makedirs(dpr_tokenizer_path, exist_ok=True)
|
| 67 |
+
self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"])
|
| 68 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 69 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 70 |
+
|
| 71 |
+
# BART tok
|
| 72 |
+
vocab = [
|
| 73 |
+
"l",
|
| 74 |
+
"o",
|
| 75 |
+
"w",
|
| 76 |
+
"e",
|
| 77 |
+
"r",
|
| 78 |
+
"s",
|
| 79 |
+
"t",
|
| 80 |
+
"i",
|
| 81 |
+
"d",
|
| 82 |
+
"n",
|
| 83 |
+
"\u0120",
|
| 84 |
+
"\u0120l",
|
| 85 |
+
"\u0120n",
|
| 86 |
+
"\u0120lo",
|
| 87 |
+
"\u0120low",
|
| 88 |
+
"er",
|
| 89 |
+
"\u0120lowest",
|
| 90 |
+
"\u0120newer",
|
| 91 |
+
"\u0120wider",
|
| 92 |
+
"<unk>",
|
| 93 |
+
]
|
| 94 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 95 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 96 |
+
self.special_tokens_map = {"unk_token": "<unk>"}
|
| 97 |
+
|
| 98 |
+
bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer")
|
| 99 |
+
os.makedirs(bart_tokenizer_path, exist_ok=True)
|
| 100 |
+
self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"])
|
| 101 |
+
self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"])
|
| 102 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 103 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 104 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 105 |
+
fp.write("\n".join(merges))
|
| 106 |
+
|
| 107 |
+
def get_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer:
|
| 108 |
+
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 109 |
+
|
| 110 |
+
def get_dpr_ctx_encoder_tokenizer(self) -> DPRContextEncoderTokenizer:
|
| 111 |
+
return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 112 |
+
|
| 113 |
+
def get_bart_tokenizer(self) -> BartTokenizer:
|
| 114 |
+
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer"))
|
| 115 |
+
|
| 116 |
+
def tearDown(self):
|
| 117 |
+
shutil.rmtree(self.tmpdirname)
|
| 118 |
+
|
| 119 |
+
def get_dummy_dataset(self):
|
| 120 |
+
dataset = Dataset.from_dict(
|
| 121 |
+
{
|
| 122 |
+
"id": ["0", "1"],
|
| 123 |
+
"text": ["foo", "bar"],
|
| 124 |
+
"title": ["Foo", "Bar"],
|
| 125 |
+
"embeddings": [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)],
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT)
|
| 129 |
+
return dataset
|
| 130 |
+
|
| 131 |
+
def get_dummy_canonical_hf_index_retriever(self):
|
| 132 |
+
dataset = self.get_dummy_dataset()
|
| 133 |
+
config = RagConfig(
|
| 134 |
+
retrieval_vector_size=self.retrieval_vector_size,
|
| 135 |
+
question_encoder=DPRConfig().to_dict(),
|
| 136 |
+
generator=BartConfig().to_dict(),
|
| 137 |
+
)
|
| 138 |
+
with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
|
| 139 |
+
mock_load_dataset.return_value = dataset
|
| 140 |
+
retriever = RagRetriever(
|
| 141 |
+
config,
|
| 142 |
+
question_encoder_tokenizer=self.get_dpr_tokenizer(),
|
| 143 |
+
generator_tokenizer=self.get_bart_tokenizer(),
|
| 144 |
+
)
|
| 145 |
+
return retriever
|
| 146 |
+
|
| 147 |
+
def get_dummy_custom_hf_index_retriever(self, from_disk: bool):
|
| 148 |
+
dataset = self.get_dummy_dataset()
|
| 149 |
+
config = RagConfig(
|
| 150 |
+
retrieval_vector_size=self.retrieval_vector_size,
|
| 151 |
+
question_encoder=DPRConfig().to_dict(),
|
| 152 |
+
generator=BartConfig().to_dict(),
|
| 153 |
+
index_name="custom",
|
| 154 |
+
)
|
| 155 |
+
if from_disk:
|
| 156 |
+
config.passages_path = os.path.join(self.tmpdirname, "dataset")
|
| 157 |
+
config.index_path = os.path.join(self.tmpdirname, "index.faiss")
|
| 158 |
+
dataset.get_index("embeddings").save(os.path.join(self.tmpdirname, "index.faiss"))
|
| 159 |
+
dataset.drop_index("embeddings")
|
| 160 |
+
dataset.save_to_disk(os.path.join(self.tmpdirname, "dataset"))
|
| 161 |
+
del dataset
|
| 162 |
+
retriever = RagRetriever(
|
| 163 |
+
config,
|
| 164 |
+
question_encoder_tokenizer=self.get_dpr_tokenizer(),
|
| 165 |
+
generator_tokenizer=self.get_bart_tokenizer(),
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
retriever = RagRetriever(
|
| 169 |
+
config,
|
| 170 |
+
question_encoder_tokenizer=self.get_dpr_tokenizer(),
|
| 171 |
+
generator_tokenizer=self.get_bart_tokenizer(),
|
| 172 |
+
index=CustomHFIndex(config.retrieval_vector_size, dataset),
|
| 173 |
+
)
|
| 174 |
+
return retriever
|
| 175 |
+
|
| 176 |
+
def test_canonical_hf_index_retriever_retrieve(self):
|
| 177 |
+
n_docs = 1
|
| 178 |
+
retriever = self.get_dummy_canonical_hf_index_retriever()
|
| 179 |
+
hidden_states = np.array(
|
| 180 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 181 |
+
)
|
| 182 |
+
retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
|
| 183 |
+
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
|
| 184 |
+
self.assertEqual(len(doc_dicts), 2)
|
| 185 |
+
self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
|
| 186 |
+
self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
|
| 187 |
+
self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc
|
| 188 |
+
self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc
|
| 189 |
+
self.assertListEqual(doc_ids.tolist(), [[1], [0]])
|
| 190 |
+
|
| 191 |
+
def test_canonical_hf_index_retriever_save_and_from_pretrained(self):
|
| 192 |
+
retriever = self.get_dummy_canonical_hf_index_retriever()
|
| 193 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 194 |
+
with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset:
|
| 195 |
+
mock_load_dataset.return_value = self.get_dummy_dataset()
|
| 196 |
+
retriever.save_pretrained(tmp_dirname)
|
| 197 |
+
retriever = RagRetriever.from_pretrained(tmp_dirname)
|
| 198 |
+
self.assertIsInstance(retriever, RagRetriever)
|
| 199 |
+
hidden_states = np.array(
|
| 200 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 201 |
+
)
|
| 202 |
+
out = retriever.retrieve(hidden_states, n_docs=1)
|
| 203 |
+
self.assertTrue(out is not None)
|
| 204 |
+
|
| 205 |
+
def test_custom_hf_index_retriever_retrieve(self):
|
| 206 |
+
n_docs = 1
|
| 207 |
+
retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False)
|
| 208 |
+
hidden_states = np.array(
|
| 209 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 210 |
+
)
|
| 211 |
+
retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
|
| 212 |
+
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
|
| 213 |
+
self.assertEqual(len(doc_dicts), 2)
|
| 214 |
+
self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
|
| 215 |
+
self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
|
| 216 |
+
self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc
|
| 217 |
+
self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc
|
| 218 |
+
self.assertListEqual(doc_ids.tolist(), [[1], [0]])
|
| 219 |
+
|
| 220 |
+
def test_custom_hf_index_retriever_save_and_from_pretrained(self):
|
| 221 |
+
retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False)
|
| 222 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 223 |
+
retriever.save_pretrained(tmp_dirname)
|
| 224 |
+
retriever = RagRetriever.from_pretrained(tmp_dirname)
|
| 225 |
+
self.assertIsInstance(retriever, RagRetriever)
|
| 226 |
+
hidden_states = np.array(
|
| 227 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 228 |
+
)
|
| 229 |
+
out = retriever.retrieve(hidden_states, n_docs=1)
|
| 230 |
+
self.assertTrue(out is not None)
|
| 231 |
+
|
| 232 |
+
def test_custom_hf_index_retriever_retrieve_from_disk(self):
|
| 233 |
+
n_docs = 1
|
| 234 |
+
retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True)
|
| 235 |
+
hidden_states = np.array(
|
| 236 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 237 |
+
)
|
| 238 |
+
retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs)
|
| 239 |
+
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
|
| 240 |
+
self.assertEqual(len(doc_dicts), 2)
|
| 241 |
+
self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"])
|
| 242 |
+
self.assertEqual(len(doc_dicts[0]["id"]), n_docs)
|
| 243 |
+
self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc
|
| 244 |
+
self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc
|
| 245 |
+
self.assertListEqual(doc_ids.tolist(), [[1], [0]])
|
| 246 |
+
|
| 247 |
+
def test_custom_hf_index_retriever_save_and_from_pretrained_from_disk(self):
|
| 248 |
+
retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True)
|
| 249 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 250 |
+
retriever.save_pretrained(tmp_dirname)
|
| 251 |
+
retriever = RagRetriever.from_pretrained(tmp_dirname)
|
| 252 |
+
self.assertIsInstance(retriever, RagRetriever)
|
| 253 |
+
hidden_states = np.array(
|
| 254 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 255 |
+
)
|
| 256 |
+
out = retriever.retrieve(hidden_states, n_docs=1)
|
| 257 |
+
self.assertTrue(out is not None)
|
| 258 |
+
|
| 259 |
+
@require_torch
|
| 260 |
+
@require_tokenizers
|
| 261 |
+
@require_sentencepiece
|
| 262 |
+
def test_hf_index_retriever_call(self):
|
| 263 |
+
import torch
|
| 264 |
+
|
| 265 |
+
n_docs = 1
|
| 266 |
+
retriever = self.get_dummy_canonical_hf_index_retriever()
|
| 267 |
+
question_input_ids = [[5, 7], [10, 11]]
|
| 268 |
+
hidden_states = np.array(
|
| 269 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 270 |
+
)
|
| 271 |
+
out = retriever(question_input_ids, hidden_states, prefix=retriever.config.generator.prefix, n_docs=n_docs)
|
| 272 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds = (
|
| 273 |
+
out["context_input_ids"],
|
| 274 |
+
out["context_attention_mask"],
|
| 275 |
+
out["retrieved_doc_embeds"],
|
| 276 |
+
)
|
| 277 |
+
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
|
| 278 |
+
self.assertIsInstance(context_input_ids, list)
|
| 279 |
+
self.assertIsInstance(context_attention_mask, list)
|
| 280 |
+
self.assertIsInstance(retrieved_doc_embeds, np.ndarray)
|
| 281 |
+
|
| 282 |
+
out = retriever(
|
| 283 |
+
question_input_ids,
|
| 284 |
+
hidden_states,
|
| 285 |
+
prefix=retriever.config.generator.prefix,
|
| 286 |
+
n_docs=n_docs,
|
| 287 |
+
return_tensors="pt",
|
| 288 |
+
)
|
| 289 |
+
context_input_ids, context_attention_mask, retrieved_doc_embeds, doc_ids = ( # noqa: F841
|
| 290 |
+
out["context_input_ids"],
|
| 291 |
+
out["context_attention_mask"],
|
| 292 |
+
out["retrieved_doc_embeds"],
|
| 293 |
+
out["doc_ids"],
|
| 294 |
+
)
|
| 295 |
+
self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size))
|
| 296 |
+
self.assertIsInstance(context_input_ids, torch.Tensor)
|
| 297 |
+
self.assertIsInstance(context_attention_mask, torch.Tensor)
|
| 298 |
+
self.assertIsInstance(retrieved_doc_embeds, torch.Tensor)
|
| 299 |
+
|
| 300 |
+
@require_torch
|
| 301 |
+
@require_tokenizers
|
| 302 |
+
@require_sentencepiece
|
| 303 |
+
def test_custom_hf_index_end2end_retriever_call(self):
|
| 304 |
+
context_encoder_tokenizer = self.get_dpr_ctx_encoder_tokenizer()
|
| 305 |
+
n_docs = 1
|
| 306 |
+
retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False)
|
| 307 |
+
retriever.set_ctx_encoder_tokenizer(context_encoder_tokenizer)
|
| 308 |
+
|
| 309 |
+
question_input_ids = [[5, 7], [10, 11]]
|
| 310 |
+
hidden_states = np.array(
|
| 311 |
+
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32
|
| 312 |
+
)
|
| 313 |
+
out = retriever(question_input_ids, hidden_states, prefix=retriever.config.generator.prefix, n_docs=n_docs)
|
| 314 |
+
|
| 315 |
+
self.assertEqual(
|
| 316 |
+
len(out), 6
|
| 317 |
+
) # check whether the retriever output consist of 6 attributes including tokenized docs
|
| 318 |
+
self.assertEqual(
|
| 319 |
+
all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask")), True
|
| 320 |
+
) # check for doc token related keys in dictionary.
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_tokenization_rag.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import tempfile
|
| 19 |
+
from unittest import TestCase
|
| 20 |
+
|
| 21 |
+
from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
|
| 22 |
+
from transformers.models.bart.configuration_bart import BartConfig
|
| 23 |
+
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
|
| 24 |
+
from transformers.models.dpr.configuration_dpr import DPRConfig
|
| 25 |
+
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
|
| 26 |
+
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
|
| 27 |
+
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available() and is_datasets_available() and is_faiss_available():
|
| 31 |
+
from transformers.models.rag.configuration_rag import RagConfig
|
| 32 |
+
from transformers.models.rag.tokenization_rag import RagTokenizer
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@require_faiss
|
| 36 |
+
@require_torch
|
| 37 |
+
class RagTokenizerTest(TestCase):
|
| 38 |
+
def setUp(self):
|
| 39 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 40 |
+
self.retrieval_vector_size = 8
|
| 41 |
+
|
| 42 |
+
# DPR tok
|
| 43 |
+
vocab_tokens = [
|
| 44 |
+
"[UNK]",
|
| 45 |
+
"[CLS]",
|
| 46 |
+
"[SEP]",
|
| 47 |
+
"[PAD]",
|
| 48 |
+
"[MASK]",
|
| 49 |
+
"want",
|
| 50 |
+
"##want",
|
| 51 |
+
"##ed",
|
| 52 |
+
"wa",
|
| 53 |
+
"un",
|
| 54 |
+
"runn",
|
| 55 |
+
"##ing",
|
| 56 |
+
",",
|
| 57 |
+
"low",
|
| 58 |
+
"lowest",
|
| 59 |
+
]
|
| 60 |
+
dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer")
|
| 61 |
+
os.makedirs(dpr_tokenizer_path, exist_ok=True)
|
| 62 |
+
self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"])
|
| 63 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 64 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 65 |
+
|
| 66 |
+
# BART tok
|
| 67 |
+
vocab = [
|
| 68 |
+
"l",
|
| 69 |
+
"o",
|
| 70 |
+
"w",
|
| 71 |
+
"e",
|
| 72 |
+
"r",
|
| 73 |
+
"s",
|
| 74 |
+
"t",
|
| 75 |
+
"i",
|
| 76 |
+
"d",
|
| 77 |
+
"n",
|
| 78 |
+
"\u0120",
|
| 79 |
+
"\u0120l",
|
| 80 |
+
"\u0120n",
|
| 81 |
+
"\u0120lo",
|
| 82 |
+
"\u0120low",
|
| 83 |
+
"er",
|
| 84 |
+
"\u0120lowest",
|
| 85 |
+
"\u0120newer",
|
| 86 |
+
"\u0120wider",
|
| 87 |
+
"<unk>",
|
| 88 |
+
]
|
| 89 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 90 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 91 |
+
self.special_tokens_map = {"unk_token": "<unk>"}
|
| 92 |
+
|
| 93 |
+
bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer")
|
| 94 |
+
os.makedirs(bart_tokenizer_path, exist_ok=True)
|
| 95 |
+
self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"])
|
| 96 |
+
self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"])
|
| 97 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 98 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 99 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 100 |
+
fp.write("\n".join(merges))
|
| 101 |
+
|
| 102 |
+
def get_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer:
|
| 103 |
+
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer"))
|
| 104 |
+
|
| 105 |
+
def get_bart_tokenizer(self) -> BartTokenizer:
|
| 106 |
+
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer"))
|
| 107 |
+
|
| 108 |
+
def tearDown(self):
|
| 109 |
+
shutil.rmtree(self.tmpdirname)
|
| 110 |
+
|
| 111 |
+
@require_tokenizers
|
| 112 |
+
def test_save_load_pretrained_with_saved_config(self):
|
| 113 |
+
save_dir = os.path.join(self.tmpdirname, "rag_tokenizer")
|
| 114 |
+
rag_config = RagConfig(question_encoder=DPRConfig().to_dict(), generator=BartConfig().to_dict())
|
| 115 |
+
rag_tokenizer = RagTokenizer(question_encoder=self.get_dpr_tokenizer(), generator=self.get_bart_tokenizer())
|
| 116 |
+
rag_config.save_pretrained(save_dir)
|
| 117 |
+
rag_tokenizer.save_pretrained(save_dir)
|
| 118 |
+
new_rag_tokenizer = RagTokenizer.from_pretrained(save_dir, config=rag_config)
|
| 119 |
+
self.assertIsInstance(new_rag_tokenizer.question_encoder, DPRQuestionEncoderTokenizerFast)
|
| 120 |
+
self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab(), rag_tokenizer.question_encoder.get_vocab())
|
| 121 |
+
self.assertIsInstance(new_rag_tokenizer.generator, BartTokenizerFast)
|
| 122 |
+
self.assertEqual(new_rag_tokenizer.generator.get_vocab(), rag_tokenizer.generator.get_vocab())
|
| 123 |
+
|
| 124 |
+
@slow
|
| 125 |
+
def test_pretrained_token_nq_tokenizer(self):
|
| 126 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
|
| 127 |
+
input_strings = [
|
| 128 |
+
"who got the first nobel prize in physics",
|
| 129 |
+
"when is the next deadpool movie being released",
|
| 130 |
+
"which mode is used for short wave broadcast service",
|
| 131 |
+
"who is the owner of reading football club",
|
| 132 |
+
"when is the next scandal episode coming out",
|
| 133 |
+
"when is the last time the philadelphia won the superbowl",
|
| 134 |
+
"what is the most current adobe flash player version",
|
| 135 |
+
"how many episodes are there in dragon ball z",
|
| 136 |
+
"what is the first step in the evolution of the eye",
|
| 137 |
+
"where is gall bladder situated in human body",
|
| 138 |
+
"what is the main mineral in lithium batteries",
|
| 139 |
+
"who is the president of usa right now",
|
| 140 |
+
"where do the greasers live in the outsiders",
|
| 141 |
+
"panda is a national animal of which country",
|
| 142 |
+
"what is the name of manchester united stadium",
|
| 143 |
+
]
|
| 144 |
+
input_dict = tokenizer(input_strings)
|
| 145 |
+
self.assertIsNotNone(input_dict)
|
| 146 |
+
|
| 147 |
+
@slow
|
| 148 |
+
def test_pretrained_sequence_nq_tokenizer(self):
|
| 149 |
+
tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
|
| 150 |
+
input_strings = [
|
| 151 |
+
"who got the first nobel prize in physics",
|
| 152 |
+
"when is the next deadpool movie being released",
|
| 153 |
+
"which mode is used for short wave broadcast service",
|
| 154 |
+
"who is the owner of reading football club",
|
| 155 |
+
"when is the next scandal episode coming out",
|
| 156 |
+
"when is the last time the philadelphia won the superbowl",
|
| 157 |
+
"what is the most current adobe flash player version",
|
| 158 |
+
"how many episodes are there in dragon ball z",
|
| 159 |
+
"what is the first step in the evolution of the eye",
|
| 160 |
+
"where is gall bladder situated in human body",
|
| 161 |
+
"what is the main mineral in lithium batteries",
|
| 162 |
+
"who is the president of usa right now",
|
| 163 |
+
"where do the greasers live in the outsiders",
|
| 164 |
+
"panda is a national animal of which country",
|
| 165 |
+
"what is the name of manchester united stadium",
|
| 166 |
+
]
|
| 167 |
+
input_dict = tokenizer(input_strings)
|
| 168 |
+
self.assertIsNotNone(input_dict)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_modeling_realm.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch REALM model. """
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from transformers import RealmConfig, is_torch_available
|
| 23 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 24 |
+
|
| 25 |
+
from ...test_configuration_common import ConfigTester
|
| 26 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 27 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
|
| 33 |
+
from transformers import (
|
| 34 |
+
RealmEmbedder,
|
| 35 |
+
RealmForOpenQA,
|
| 36 |
+
RealmKnowledgeAugEncoder,
|
| 37 |
+
RealmReader,
|
| 38 |
+
RealmRetriever,
|
| 39 |
+
RealmScorer,
|
| 40 |
+
RealmTokenizer,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class RealmModelTester:
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
parent,
|
| 48 |
+
batch_size=13,
|
| 49 |
+
retriever_proj_size=128,
|
| 50 |
+
seq_length=7,
|
| 51 |
+
is_training=True,
|
| 52 |
+
use_input_mask=True,
|
| 53 |
+
use_token_type_ids=True,
|
| 54 |
+
use_labels=True,
|
| 55 |
+
vocab_size=99,
|
| 56 |
+
hidden_size=32,
|
| 57 |
+
num_hidden_layers=2,
|
| 58 |
+
num_attention_heads=4,
|
| 59 |
+
intermediate_size=37,
|
| 60 |
+
hidden_act="gelu",
|
| 61 |
+
hidden_dropout_prob=0.1,
|
| 62 |
+
attention_probs_dropout_prob=0.1,
|
| 63 |
+
max_position_embeddings=512,
|
| 64 |
+
type_vocab_size=16,
|
| 65 |
+
type_sequence_label_size=2,
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
layer_norm_eps=1e-12,
|
| 68 |
+
span_hidden_size=50,
|
| 69 |
+
max_span_width=10,
|
| 70 |
+
reader_layer_norm_eps=1e-3,
|
| 71 |
+
reader_beam_size=4,
|
| 72 |
+
reader_seq_len=288 + 32,
|
| 73 |
+
num_block_records=13353718,
|
| 74 |
+
searcher_beam_size=8,
|
| 75 |
+
searcher_seq_len=64,
|
| 76 |
+
num_labels=3,
|
| 77 |
+
num_choices=4,
|
| 78 |
+
num_candidates=10,
|
| 79 |
+
scope=None,
|
| 80 |
+
):
|
| 81 |
+
# General config
|
| 82 |
+
self.parent = parent
|
| 83 |
+
self.batch_size = batch_size
|
| 84 |
+
self.retriever_proj_size = retriever_proj_size
|
| 85 |
+
self.seq_length = seq_length
|
| 86 |
+
self.is_training = is_training
|
| 87 |
+
self.use_input_mask = use_input_mask
|
| 88 |
+
self.use_token_type_ids = use_token_type_ids
|
| 89 |
+
self.use_labels = use_labels
|
| 90 |
+
self.vocab_size = vocab_size
|
| 91 |
+
self.hidden_size = hidden_size
|
| 92 |
+
self.num_hidden_layers = num_hidden_layers
|
| 93 |
+
self.num_attention_heads = num_attention_heads
|
| 94 |
+
self.intermediate_size = intermediate_size
|
| 95 |
+
self.hidden_act = hidden_act
|
| 96 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 97 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 98 |
+
self.max_position_embeddings = max_position_embeddings
|
| 99 |
+
self.type_vocab_size = type_vocab_size
|
| 100 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 101 |
+
self.initializer_range = initializer_range
|
| 102 |
+
self.layer_norm_eps = layer_norm_eps
|
| 103 |
+
|
| 104 |
+
# Reader config
|
| 105 |
+
self.span_hidden_size = span_hidden_size
|
| 106 |
+
self.max_span_width = max_span_width
|
| 107 |
+
self.reader_layer_norm_eps = reader_layer_norm_eps
|
| 108 |
+
self.reader_beam_size = reader_beam_size
|
| 109 |
+
self.reader_seq_len = reader_seq_len
|
| 110 |
+
|
| 111 |
+
# Searcher config
|
| 112 |
+
self.num_block_records = num_block_records
|
| 113 |
+
self.searcher_beam_size = searcher_beam_size
|
| 114 |
+
self.searcher_seq_len = searcher_seq_len
|
| 115 |
+
|
| 116 |
+
self.num_labels = num_labels
|
| 117 |
+
self.num_choices = num_choices
|
| 118 |
+
self.num_candidates = num_candidates
|
| 119 |
+
self.scope = scope
|
| 120 |
+
|
| 121 |
+
def prepare_config_and_inputs(self):
|
| 122 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 123 |
+
candiate_input_ids = ids_tensor([self.batch_size, self.num_candidates, self.seq_length], self.vocab_size)
|
| 124 |
+
reader_input_ids = ids_tensor([self.reader_beam_size, self.reader_seq_len], self.vocab_size)
|
| 125 |
+
|
| 126 |
+
input_mask = None
|
| 127 |
+
candiate_input_mask = None
|
| 128 |
+
reader_input_mask = None
|
| 129 |
+
if self.use_input_mask:
|
| 130 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 131 |
+
candiate_input_mask = random_attention_mask([self.batch_size, self.num_candidates, self.seq_length])
|
| 132 |
+
reader_input_mask = random_attention_mask([self.reader_beam_size, self.reader_seq_len])
|
| 133 |
+
|
| 134 |
+
token_type_ids = None
|
| 135 |
+
candidate_token_type_ids = None
|
| 136 |
+
reader_token_type_ids = None
|
| 137 |
+
if self.use_token_type_ids:
|
| 138 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 139 |
+
candidate_token_type_ids = ids_tensor(
|
| 140 |
+
[self.batch_size, self.num_candidates, self.seq_length], self.type_vocab_size
|
| 141 |
+
)
|
| 142 |
+
reader_token_type_ids = ids_tensor([self.reader_beam_size, self.reader_seq_len], self.type_vocab_size)
|
| 143 |
+
|
| 144 |
+
sequence_labels = None
|
| 145 |
+
token_labels = None
|
| 146 |
+
choice_labels = None
|
| 147 |
+
if self.use_labels:
|
| 148 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 149 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 150 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 151 |
+
|
| 152 |
+
config = self.get_config()
|
| 153 |
+
|
| 154 |
+
# inputs with additional num_candidates axis.
|
| 155 |
+
scorer_encoder_inputs = (candiate_input_ids, candiate_input_mask, candidate_token_type_ids)
|
| 156 |
+
# reader inputs
|
| 157 |
+
reader_inputs = (reader_input_ids, reader_input_mask, reader_token_type_ids)
|
| 158 |
+
|
| 159 |
+
return (
|
| 160 |
+
config,
|
| 161 |
+
input_ids,
|
| 162 |
+
token_type_ids,
|
| 163 |
+
input_mask,
|
| 164 |
+
scorer_encoder_inputs,
|
| 165 |
+
reader_inputs,
|
| 166 |
+
sequence_labels,
|
| 167 |
+
token_labels,
|
| 168 |
+
choice_labels,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def get_config(self):
|
| 172 |
+
return RealmConfig(
|
| 173 |
+
vocab_size=self.vocab_size,
|
| 174 |
+
hidden_size=self.hidden_size,
|
| 175 |
+
retriever_proj_size=self.retriever_proj_size,
|
| 176 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 177 |
+
num_attention_heads=self.num_attention_heads,
|
| 178 |
+
num_candidates=self.num_candidates,
|
| 179 |
+
intermediate_size=self.intermediate_size,
|
| 180 |
+
hidden_act=self.hidden_act,
|
| 181 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 182 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 183 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 184 |
+
type_vocab_size=self.type_vocab_size,
|
| 185 |
+
initializer_range=self.initializer_range,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def create_and_check_embedder(
|
| 189 |
+
self,
|
| 190 |
+
config,
|
| 191 |
+
input_ids,
|
| 192 |
+
token_type_ids,
|
| 193 |
+
input_mask,
|
| 194 |
+
scorer_encoder_inputs,
|
| 195 |
+
reader_inputs,
|
| 196 |
+
sequence_labels,
|
| 197 |
+
token_labels,
|
| 198 |
+
choice_labels,
|
| 199 |
+
):
|
| 200 |
+
model = RealmEmbedder(config=config)
|
| 201 |
+
model.to(torch_device)
|
| 202 |
+
model.eval()
|
| 203 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 204 |
+
self.parent.assertEqual(result.projected_score.shape, (self.batch_size, self.retriever_proj_size))
|
| 205 |
+
|
| 206 |
+
def create_and_check_encoder(
|
| 207 |
+
self,
|
| 208 |
+
config,
|
| 209 |
+
input_ids,
|
| 210 |
+
token_type_ids,
|
| 211 |
+
input_mask,
|
| 212 |
+
scorer_encoder_inputs,
|
| 213 |
+
reader_inputs,
|
| 214 |
+
sequence_labels,
|
| 215 |
+
token_labels,
|
| 216 |
+
choice_labels,
|
| 217 |
+
):
|
| 218 |
+
model = RealmKnowledgeAugEncoder(config=config)
|
| 219 |
+
model.to(torch_device)
|
| 220 |
+
model.eval()
|
| 221 |
+
relevance_score = floats_tensor([self.batch_size, self.num_candidates])
|
| 222 |
+
result = model(
|
| 223 |
+
scorer_encoder_inputs[0],
|
| 224 |
+
attention_mask=scorer_encoder_inputs[1],
|
| 225 |
+
token_type_ids=scorer_encoder_inputs[2],
|
| 226 |
+
relevance_score=relevance_score,
|
| 227 |
+
labels=token_labels,
|
| 228 |
+
)
|
| 229 |
+
self.parent.assertEqual(
|
| 230 |
+
result.logits.shape, (self.batch_size * self.num_candidates, self.seq_length, self.vocab_size)
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
def create_and_check_reader(
|
| 234 |
+
self,
|
| 235 |
+
config,
|
| 236 |
+
input_ids,
|
| 237 |
+
token_type_ids,
|
| 238 |
+
input_mask,
|
| 239 |
+
scorer_encoder_inputs,
|
| 240 |
+
reader_inputs,
|
| 241 |
+
sequence_labels,
|
| 242 |
+
token_labels,
|
| 243 |
+
choice_labels,
|
| 244 |
+
):
|
| 245 |
+
model = RealmReader(config=config)
|
| 246 |
+
model.to(torch_device)
|
| 247 |
+
model.eval()
|
| 248 |
+
relevance_score = floats_tensor([self.reader_beam_size])
|
| 249 |
+
result = model(
|
| 250 |
+
reader_inputs[0],
|
| 251 |
+
attention_mask=reader_inputs[1],
|
| 252 |
+
token_type_ids=reader_inputs[2],
|
| 253 |
+
relevance_score=relevance_score,
|
| 254 |
+
)
|
| 255 |
+
self.parent.assertEqual(result.block_idx.shape, ())
|
| 256 |
+
self.parent.assertEqual(result.candidate.shape, ())
|
| 257 |
+
self.parent.assertEqual(result.start_pos.shape, ())
|
| 258 |
+
self.parent.assertEqual(result.end_pos.shape, ())
|
| 259 |
+
|
| 260 |
+
def create_and_check_scorer(
|
| 261 |
+
self,
|
| 262 |
+
config,
|
| 263 |
+
input_ids,
|
| 264 |
+
token_type_ids,
|
| 265 |
+
input_mask,
|
| 266 |
+
scorer_encoder_inputs,
|
| 267 |
+
reader_inputs,
|
| 268 |
+
sequence_labels,
|
| 269 |
+
token_labels,
|
| 270 |
+
choice_labels,
|
| 271 |
+
):
|
| 272 |
+
model = RealmScorer(config=config)
|
| 273 |
+
model.to(torch_device)
|
| 274 |
+
model.eval()
|
| 275 |
+
result = model(
|
| 276 |
+
input_ids,
|
| 277 |
+
attention_mask=input_mask,
|
| 278 |
+
token_type_ids=token_type_ids,
|
| 279 |
+
candidate_input_ids=scorer_encoder_inputs[0],
|
| 280 |
+
candidate_attention_mask=scorer_encoder_inputs[1],
|
| 281 |
+
candidate_token_type_ids=scorer_encoder_inputs[2],
|
| 282 |
+
)
|
| 283 |
+
self.parent.assertEqual(result.relevance_score.shape, (self.batch_size, self.num_candidates))
|
| 284 |
+
self.parent.assertEqual(result.query_score.shape, (self.batch_size, self.retriever_proj_size))
|
| 285 |
+
self.parent.assertEqual(
|
| 286 |
+
result.candidate_score.shape, (self.batch_size, self.num_candidates, self.retriever_proj_size)
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
def prepare_config_and_inputs_for_common(self):
|
| 290 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 291 |
+
(
|
| 292 |
+
config,
|
| 293 |
+
input_ids,
|
| 294 |
+
token_type_ids,
|
| 295 |
+
input_mask,
|
| 296 |
+
scorer_encoder_inputs,
|
| 297 |
+
reader_inputs,
|
| 298 |
+
sequence_labels,
|
| 299 |
+
token_labels,
|
| 300 |
+
choice_labels,
|
| 301 |
+
) = config_and_inputs
|
| 302 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 303 |
+
return config, inputs_dict
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@require_torch
|
| 307 |
+
class RealmModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 308 |
+
all_model_classes = (
|
| 309 |
+
(
|
| 310 |
+
RealmEmbedder,
|
| 311 |
+
RealmKnowledgeAugEncoder,
|
| 312 |
+
# RealmScorer is excluded from common tests as it is a container model
|
| 313 |
+
# consisting of two RealmEmbedders & a simple inner product calculation.
|
| 314 |
+
# RealmScorer
|
| 315 |
+
)
|
| 316 |
+
if is_torch_available()
|
| 317 |
+
else ()
|
| 318 |
+
)
|
| 319 |
+
all_generative_model_classes = ()
|
| 320 |
+
pipeline_model_mapping = {} if is_torch_available() else {}
|
| 321 |
+
|
| 322 |
+
# disable these tests because there is no base_model in Realm
|
| 323 |
+
test_save_load_fast_init_from_base = False
|
| 324 |
+
test_save_load_fast_init_to_base = False
|
| 325 |
+
|
| 326 |
+
def setUp(self):
|
| 327 |
+
self.test_pruning = False
|
| 328 |
+
self.model_tester = RealmModelTester(self)
|
| 329 |
+
self.config_tester = ConfigTester(self, config_class=RealmConfig)
|
| 330 |
+
|
| 331 |
+
def test_config(self):
|
| 332 |
+
self.config_tester.run_common_tests()
|
| 333 |
+
|
| 334 |
+
def test_embedder(self):
|
| 335 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 336 |
+
self.model_tester.create_and_check_embedder(*config_and_inputs)
|
| 337 |
+
|
| 338 |
+
def test_encoder(self):
|
| 339 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 340 |
+
self.model_tester.create_and_check_encoder(*config_and_inputs)
|
| 341 |
+
|
| 342 |
+
def test_model_various_embeddings(self):
|
| 343 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 344 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 345 |
+
config_and_inputs[0].position_embedding_type = type
|
| 346 |
+
self.model_tester.create_and_check_embedder(*config_and_inputs)
|
| 347 |
+
self.model_tester.create_and_check_encoder(*config_and_inputs)
|
| 348 |
+
|
| 349 |
+
def test_scorer(self):
|
| 350 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 351 |
+
self.model_tester.create_and_check_scorer(*config_and_inputs)
|
| 352 |
+
|
| 353 |
+
def test_training(self):
|
| 354 |
+
if not self.model_tester.is_training:
|
| 355 |
+
return
|
| 356 |
+
|
| 357 |
+
config, *inputs = self.model_tester.prepare_config_and_inputs()
|
| 358 |
+
input_ids, token_type_ids, input_mask, scorer_encoder_inputs = inputs[0:4]
|
| 359 |
+
config.return_dict = True
|
| 360 |
+
|
| 361 |
+
tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa")
|
| 362 |
+
|
| 363 |
+
# RealmKnowledgeAugEncoder training
|
| 364 |
+
model = RealmKnowledgeAugEncoder(config)
|
| 365 |
+
model.to(torch_device)
|
| 366 |
+
model.train()
|
| 367 |
+
|
| 368 |
+
inputs_dict = {
|
| 369 |
+
"input_ids": scorer_encoder_inputs[0].to(torch_device),
|
| 370 |
+
"attention_mask": scorer_encoder_inputs[1].to(torch_device),
|
| 371 |
+
"token_type_ids": scorer_encoder_inputs[2].to(torch_device),
|
| 372 |
+
"relevance_score": floats_tensor([self.model_tester.batch_size, self.model_tester.num_candidates]),
|
| 373 |
+
}
|
| 374 |
+
inputs_dict["labels"] = torch.zeros(
|
| 375 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 376 |
+
)
|
| 377 |
+
inputs = inputs_dict
|
| 378 |
+
loss = model(**inputs).loss
|
| 379 |
+
loss.backward()
|
| 380 |
+
|
| 381 |
+
# RealmForOpenQA training
|
| 382 |
+
openqa_config = copy.deepcopy(config)
|
| 383 |
+
openqa_config.vocab_size = 30522 # the retrieved texts will inevitably have more than 99 vocabs.
|
| 384 |
+
openqa_config.num_block_records = 5
|
| 385 |
+
openqa_config.searcher_beam_size = 2
|
| 386 |
+
|
| 387 |
+
block_records = np.array(
|
| 388 |
+
[
|
| 389 |
+
b"This is the first record.",
|
| 390 |
+
b"This is the second record.",
|
| 391 |
+
b"This is the third record.",
|
| 392 |
+
b"This is the fourth record.",
|
| 393 |
+
b"This is the fifth record.",
|
| 394 |
+
],
|
| 395 |
+
dtype=object,
|
| 396 |
+
)
|
| 397 |
+
retriever = RealmRetriever(block_records, tokenizer)
|
| 398 |
+
model = RealmForOpenQA(openqa_config, retriever)
|
| 399 |
+
model.to(torch_device)
|
| 400 |
+
model.train()
|
| 401 |
+
|
| 402 |
+
inputs_dict = {
|
| 403 |
+
"input_ids": input_ids[:1].to(torch_device),
|
| 404 |
+
"attention_mask": input_mask[:1].to(torch_device),
|
| 405 |
+
"token_type_ids": token_type_ids[:1].to(torch_device),
|
| 406 |
+
"answer_ids": input_ids[:1].tolist(),
|
| 407 |
+
}
|
| 408 |
+
inputs = self._prepare_for_class(inputs_dict, RealmForOpenQA)
|
| 409 |
+
loss = model(**inputs).reader_output.loss
|
| 410 |
+
loss.backward()
|
| 411 |
+
|
| 412 |
+
# Test model.block_embedding_to
|
| 413 |
+
device = torch.device("cpu")
|
| 414 |
+
model.block_embedding_to(device)
|
| 415 |
+
loss = model(**inputs).reader_output.loss
|
| 416 |
+
loss.backward()
|
| 417 |
+
self.assertEqual(model.block_emb.device.type, device.type)
|
| 418 |
+
|
| 419 |
+
@slow
|
| 420 |
+
def test_embedder_from_pretrained(self):
|
| 421 |
+
model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder")
|
| 422 |
+
self.assertIsNotNone(model)
|
| 423 |
+
|
| 424 |
+
@slow
|
| 425 |
+
def test_encoder_from_pretrained(self):
|
| 426 |
+
model = RealmKnowledgeAugEncoder.from_pretrained("google/realm-cc-news-pretrained-encoder")
|
| 427 |
+
self.assertIsNotNone(model)
|
| 428 |
+
|
| 429 |
+
@slow
|
| 430 |
+
def test_open_qa_from_pretrained(self):
|
| 431 |
+
model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa")
|
| 432 |
+
self.assertIsNotNone(model)
|
| 433 |
+
|
| 434 |
+
@slow
|
| 435 |
+
def test_reader_from_pretrained(self):
|
| 436 |
+
model = RealmReader.from_pretrained("google/realm-orqa-nq-reader")
|
| 437 |
+
self.assertIsNotNone(model)
|
| 438 |
+
|
| 439 |
+
@slow
|
| 440 |
+
def test_scorer_from_pretrained(self):
|
| 441 |
+
model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer")
|
| 442 |
+
self.assertIsNotNone(model)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
@require_torch
|
| 446 |
+
class RealmModelIntegrationTest(unittest.TestCase):
|
| 447 |
+
@slow
|
| 448 |
+
def test_inference_embedder(self):
|
| 449 |
+
retriever_projected_size = 128
|
| 450 |
+
|
| 451 |
+
model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder")
|
| 452 |
+
input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
|
| 453 |
+
output = model(input_ids)[0]
|
| 454 |
+
|
| 455 |
+
expected_shape = torch.Size((1, retriever_projected_size))
|
| 456 |
+
self.assertEqual(output.shape, expected_shape)
|
| 457 |
+
|
| 458 |
+
expected_slice = torch.tensor([[-0.0714, -0.0837, -0.1314]])
|
| 459 |
+
self.assertTrue(torch.allclose(output[:, :3], expected_slice, atol=1e-4))
|
| 460 |
+
|
| 461 |
+
@slow
|
| 462 |
+
def test_inference_encoder(self):
|
| 463 |
+
num_candidates = 2
|
| 464 |
+
vocab_size = 30522
|
| 465 |
+
|
| 466 |
+
model = RealmKnowledgeAugEncoder.from_pretrained(
|
| 467 |
+
"google/realm-cc-news-pretrained-encoder", num_candidates=num_candidates
|
| 468 |
+
)
|
| 469 |
+
input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
|
| 470 |
+
relevance_score = torch.tensor([[0.3, 0.7]], dtype=torch.float32)
|
| 471 |
+
output = model(input_ids, relevance_score=relevance_score)[0]
|
| 472 |
+
|
| 473 |
+
expected_shape = torch.Size((2, 6, vocab_size))
|
| 474 |
+
self.assertEqual(output.shape, expected_shape)
|
| 475 |
+
|
| 476 |
+
expected_slice = torch.tensor([[[-11.0888, -11.2544], [-10.2170, -10.3874]]])
|
| 477 |
+
|
| 478 |
+
self.assertTrue(torch.allclose(output[1, :2, :2], expected_slice, atol=1e-4))
|
| 479 |
+
|
| 480 |
+
@slow
|
| 481 |
+
def test_inference_open_qa(self):
|
| 482 |
+
from transformers.models.realm.retrieval_realm import RealmRetriever
|
| 483 |
+
|
| 484 |
+
tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa")
|
| 485 |
+
retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa")
|
| 486 |
+
|
| 487 |
+
model = RealmForOpenQA.from_pretrained(
|
| 488 |
+
"google/realm-orqa-nq-openqa",
|
| 489 |
+
retriever=retriever,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
question = "Who is the pioneer in modern computer science?"
|
| 493 |
+
|
| 494 |
+
question = tokenizer(
|
| 495 |
+
[question],
|
| 496 |
+
padding=True,
|
| 497 |
+
truncation=True,
|
| 498 |
+
max_length=model.config.searcher_seq_len,
|
| 499 |
+
return_tensors="pt",
|
| 500 |
+
).to(model.device)
|
| 501 |
+
|
| 502 |
+
predicted_answer_ids = model(**question).predicted_answer_ids
|
| 503 |
+
|
| 504 |
+
predicted_answer = tokenizer.decode(predicted_answer_ids)
|
| 505 |
+
self.assertEqual(predicted_answer, "alan mathison turing")
|
| 506 |
+
|
| 507 |
+
@slow
|
| 508 |
+
def test_inference_reader(self):
|
| 509 |
+
config = RealmConfig(reader_beam_size=2, max_span_width=3)
|
| 510 |
+
model = RealmReader.from_pretrained("google/realm-orqa-nq-reader", config=config)
|
| 511 |
+
|
| 512 |
+
concat_input_ids = torch.arange(10).view((2, 5))
|
| 513 |
+
concat_token_type_ids = torch.tensor([[0, 0, 1, 1, 1], [0, 0, 1, 1, 1]], dtype=torch.int64)
|
| 514 |
+
concat_block_mask = torch.tensor([[0, 0, 1, 1, 0], [0, 0, 1, 1, 0]], dtype=torch.int64)
|
| 515 |
+
relevance_score = torch.tensor([0.3, 0.7], dtype=torch.float32)
|
| 516 |
+
|
| 517 |
+
output = model(
|
| 518 |
+
concat_input_ids,
|
| 519 |
+
token_type_ids=concat_token_type_ids,
|
| 520 |
+
relevance_score=relevance_score,
|
| 521 |
+
block_mask=concat_block_mask,
|
| 522 |
+
return_dict=True,
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
block_idx_expected_shape = torch.Size(())
|
| 526 |
+
start_pos_expected_shape = torch.Size((1,))
|
| 527 |
+
end_pos_expected_shape = torch.Size((1,))
|
| 528 |
+
self.assertEqual(output.block_idx.shape, block_idx_expected_shape)
|
| 529 |
+
self.assertEqual(output.start_pos.shape, start_pos_expected_shape)
|
| 530 |
+
self.assertEqual(output.end_pos.shape, end_pos_expected_shape)
|
| 531 |
+
|
| 532 |
+
expected_block_idx = torch.tensor(1)
|
| 533 |
+
expected_start_pos = torch.tensor(3)
|
| 534 |
+
expected_end_pos = torch.tensor(3)
|
| 535 |
+
|
| 536 |
+
self.assertTrue(torch.allclose(output.block_idx, expected_block_idx, atol=1e-4))
|
| 537 |
+
self.assertTrue(torch.allclose(output.start_pos, expected_start_pos, atol=1e-4))
|
| 538 |
+
self.assertTrue(torch.allclose(output.end_pos, expected_end_pos, atol=1e-4))
|
| 539 |
+
|
| 540 |
+
@slow
|
| 541 |
+
def test_inference_scorer(self):
|
| 542 |
+
num_candidates = 2
|
| 543 |
+
|
| 544 |
+
model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=num_candidates)
|
| 545 |
+
|
| 546 |
+
input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
|
| 547 |
+
candidate_input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
|
| 548 |
+
output = model(input_ids, candidate_input_ids=candidate_input_ids)[0]
|
| 549 |
+
|
| 550 |
+
expected_shape = torch.Size((1, 2))
|
| 551 |
+
self.assertEqual(output.shape, expected_shape)
|
| 552 |
+
|
| 553 |
+
expected_slice = torch.tensor([[0.7410, 0.7170]])
|
| 554 |
+
self.assertTrue(torch.allclose(output, expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_retrieval_realm.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import tempfile
|
| 19 |
+
from unittest import TestCase
|
| 20 |
+
from unittest.mock import patch
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
|
| 25 |
+
from transformers.models.realm.configuration_realm import RealmConfig
|
| 26 |
+
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
|
| 27 |
+
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class RealmRetrieverTest(TestCase):
|
| 31 |
+
def setUp(self):
|
| 32 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 33 |
+
self.num_block_records = 5
|
| 34 |
+
|
| 35 |
+
# Realm tok
|
| 36 |
+
vocab_tokens = [
|
| 37 |
+
"[UNK]",
|
| 38 |
+
"[CLS]",
|
| 39 |
+
"[SEP]",
|
| 40 |
+
"[PAD]",
|
| 41 |
+
"[MASK]",
|
| 42 |
+
"test",
|
| 43 |
+
"question",
|
| 44 |
+
"this",
|
| 45 |
+
"is",
|
| 46 |
+
"the",
|
| 47 |
+
"first",
|
| 48 |
+
"second",
|
| 49 |
+
"third",
|
| 50 |
+
"fourth",
|
| 51 |
+
"fifth",
|
| 52 |
+
"record",
|
| 53 |
+
"want",
|
| 54 |
+
"##want",
|
| 55 |
+
"##ed",
|
| 56 |
+
"wa",
|
| 57 |
+
"un",
|
| 58 |
+
"runn",
|
| 59 |
+
"##ing",
|
| 60 |
+
",",
|
| 61 |
+
"low",
|
| 62 |
+
"lowest",
|
| 63 |
+
]
|
| 64 |
+
realm_tokenizer_path = os.path.join(self.tmpdirname, "realm_tokenizer")
|
| 65 |
+
os.makedirs(realm_tokenizer_path, exist_ok=True)
|
| 66 |
+
self.vocab_file = os.path.join(realm_tokenizer_path, VOCAB_FILES_NAMES["vocab_file"])
|
| 67 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 68 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 69 |
+
|
| 70 |
+
realm_block_records_path = os.path.join(self.tmpdirname, "realm_block_records")
|
| 71 |
+
os.makedirs(realm_block_records_path, exist_ok=True)
|
| 72 |
+
|
| 73 |
+
def get_tokenizer(self) -> RealmTokenizer:
|
| 74 |
+
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname, "realm_tokenizer"))
|
| 75 |
+
|
| 76 |
+
def tearDown(self):
|
| 77 |
+
shutil.rmtree(self.tmpdirname)
|
| 78 |
+
|
| 79 |
+
def get_config(self):
|
| 80 |
+
config = RealmConfig(num_block_records=self.num_block_records)
|
| 81 |
+
return config
|
| 82 |
+
|
| 83 |
+
def get_dummy_dataset(self):
|
| 84 |
+
dataset = Dataset.from_dict(
|
| 85 |
+
{
|
| 86 |
+
"id": ["0", "1"],
|
| 87 |
+
"question": ["foo", "bar"],
|
| 88 |
+
"answers": [["Foo", "Bar"], ["Bar"]],
|
| 89 |
+
}
|
| 90 |
+
)
|
| 91 |
+
return dataset
|
| 92 |
+
|
| 93 |
+
def get_dummy_block_records(self):
|
| 94 |
+
block_records = np.array(
|
| 95 |
+
[
|
| 96 |
+
b"This is the first record",
|
| 97 |
+
b"This is the second record",
|
| 98 |
+
b"This is the third record",
|
| 99 |
+
b"This is the fourth record",
|
| 100 |
+
b"This is the fifth record",
|
| 101 |
+
b"This is a longer longer longer record",
|
| 102 |
+
],
|
| 103 |
+
dtype=object,
|
| 104 |
+
)
|
| 105 |
+
return block_records
|
| 106 |
+
|
| 107 |
+
def get_dummy_retriever(self):
|
| 108 |
+
retriever = RealmRetriever(
|
| 109 |
+
block_records=self.get_dummy_block_records(),
|
| 110 |
+
tokenizer=self.get_tokenizer(),
|
| 111 |
+
)
|
| 112 |
+
return retriever
|
| 113 |
+
|
| 114 |
+
def test_retrieve(self):
|
| 115 |
+
config = self.get_config()
|
| 116 |
+
retriever = self.get_dummy_retriever()
|
| 117 |
+
tokenizer = retriever.tokenizer
|
| 118 |
+
|
| 119 |
+
retrieved_block_ids = np.array([0, 3], dtype="long")
|
| 120 |
+
question_input_ids = tokenizer(["Test question"]).input_ids
|
| 121 |
+
answer_ids = tokenizer(
|
| 122 |
+
["the fourth"],
|
| 123 |
+
add_special_tokens=False,
|
| 124 |
+
return_token_type_ids=False,
|
| 125 |
+
return_attention_mask=False,
|
| 126 |
+
).input_ids
|
| 127 |
+
max_length = config.reader_seq_len
|
| 128 |
+
|
| 129 |
+
has_answers, start_pos, end_pos, concat_inputs = retriever(
|
| 130 |
+
retrieved_block_ids, question_input_ids, answer_ids=answer_ids, max_length=max_length, return_tensors="np"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
self.assertEqual(len(has_answers), 2)
|
| 134 |
+
self.assertEqual(len(start_pos), 2)
|
| 135 |
+
self.assertEqual(len(end_pos), 2)
|
| 136 |
+
self.assertEqual(concat_inputs.input_ids.shape, (2, 10))
|
| 137 |
+
self.assertEqual(concat_inputs.attention_mask.shape, (2, 10))
|
| 138 |
+
self.assertEqual(concat_inputs.token_type_ids.shape, (2, 10))
|
| 139 |
+
self.assertEqual(concat_inputs.special_tokens_mask.shape, (2, 10))
|
| 140 |
+
self.assertEqual(
|
| 141 |
+
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]),
|
| 142 |
+
["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"],
|
| 143 |
+
)
|
| 144 |
+
self.assertEqual(
|
| 145 |
+
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]),
|
| 146 |
+
["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"],
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def test_block_has_answer(self):
|
| 150 |
+
config = self.get_config()
|
| 151 |
+
retriever = self.get_dummy_retriever()
|
| 152 |
+
tokenizer = retriever.tokenizer
|
| 153 |
+
|
| 154 |
+
retrieved_block_ids = np.array([0, 3, 5], dtype="long")
|
| 155 |
+
question_input_ids = tokenizer(["Test question"]).input_ids
|
| 156 |
+
answer_ids = tokenizer(
|
| 157 |
+
["the fourth", "longer longer"],
|
| 158 |
+
add_special_tokens=False,
|
| 159 |
+
return_token_type_ids=False,
|
| 160 |
+
return_attention_mask=False,
|
| 161 |
+
).input_ids
|
| 162 |
+
max_length = config.reader_seq_len
|
| 163 |
+
|
| 164 |
+
has_answers, start_pos, end_pos, _ = retriever(
|
| 165 |
+
retrieved_block_ids, question_input_ids, answer_ids=answer_ids, max_length=max_length, return_tensors="np"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
self.assertEqual([False, True, True], has_answers)
|
| 169 |
+
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]], start_pos)
|
| 170 |
+
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]], end_pos)
|
| 171 |
+
|
| 172 |
+
def test_save_load_pretrained(self):
|
| 173 |
+
retriever = self.get_dummy_retriever()
|
| 174 |
+
retriever.save_pretrained(os.path.join(self.tmpdirname, "realm_block_records"))
|
| 175 |
+
|
| 176 |
+
# Test local path
|
| 177 |
+
retriever = retriever.from_pretrained(os.path.join(self.tmpdirname, "realm_block_records"))
|
| 178 |
+
self.assertEqual(retriever.block_records[0], b"This is the first record")
|
| 179 |
+
|
| 180 |
+
# Test mocked remote path
|
| 181 |
+
with patch("transformers.models.realm.retrieval_realm.hf_hub_download") as mock_hf_hub_download:
|
| 182 |
+
mock_hf_hub_download.return_value = os.path.join(
|
| 183 |
+
os.path.join(self.tmpdirname, "realm_block_records"), _REALM_BLOCK_RECORDS_FILENAME
|
| 184 |
+
)
|
| 185 |
+
retriever = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa")
|
| 186 |
+
|
| 187 |
+
self.assertEqual(retriever.block_records[0], b"This is the first record")
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_tokenization_realm.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import RealmTokenizerFast
|
| 20 |
+
from transformers.models.bert.tokenization_bert import (
|
| 21 |
+
VOCAB_FILES_NAMES,
|
| 22 |
+
BasicTokenizer,
|
| 23 |
+
WordpieceTokenizer,
|
| 24 |
+
_is_control,
|
| 25 |
+
_is_punctuation,
|
| 26 |
+
_is_whitespace,
|
| 27 |
+
)
|
| 28 |
+
from transformers.models.realm.tokenization_realm import RealmTokenizer
|
| 29 |
+
from transformers.testing_utils import require_tokenizers, slow
|
| 30 |
+
|
| 31 |
+
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@require_tokenizers
|
| 35 |
+
class RealmTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 36 |
+
tokenizer_class = RealmTokenizer
|
| 37 |
+
rust_tokenizer_class = RealmTokenizerFast
|
| 38 |
+
test_rust_tokenizer = True
|
| 39 |
+
space_between_special_tokens = True
|
| 40 |
+
from_pretrained_filter = filter_non_english
|
| 41 |
+
|
| 42 |
+
def setUp(self):
|
| 43 |
+
super().setUp()
|
| 44 |
+
|
| 45 |
+
vocab_tokens = [
|
| 46 |
+
"[UNK]",
|
| 47 |
+
"[CLS]",
|
| 48 |
+
"[SEP]",
|
| 49 |
+
"[PAD]",
|
| 50 |
+
"[MASK]",
|
| 51 |
+
"want",
|
| 52 |
+
"##want",
|
| 53 |
+
"##ed",
|
| 54 |
+
"wa",
|
| 55 |
+
"un",
|
| 56 |
+
"runn",
|
| 57 |
+
"##ing",
|
| 58 |
+
",",
|
| 59 |
+
"low",
|
| 60 |
+
"lowest",
|
| 61 |
+
]
|
| 62 |
+
self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
|
| 63 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 64 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 65 |
+
|
| 66 |
+
def get_input_output_texts(self, tokenizer):
|
| 67 |
+
input_text = "UNwant\u00E9d,running"
|
| 68 |
+
output_text = "unwanted, running"
|
| 69 |
+
return input_text, output_text
|
| 70 |
+
|
| 71 |
+
def test_full_tokenizer(self):
|
| 72 |
+
tokenizer = self.tokenizer_class(self.vocab_file)
|
| 73 |
+
|
| 74 |
+
tokens = tokenizer.tokenize("UNwant\u00E9d,running")
|
| 75 |
+
self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
|
| 76 |
+
self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [9, 6, 7, 12, 10, 11])
|
| 77 |
+
|
| 78 |
+
def test_rust_and_python_full_tokenizers(self):
|
| 79 |
+
if not self.test_rust_tokenizer:
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
tokenizer = self.get_tokenizer()
|
| 83 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 84 |
+
|
| 85 |
+
sequence = "UNwant\u00E9d,running"
|
| 86 |
+
|
| 87 |
+
tokens = tokenizer.tokenize(sequence)
|
| 88 |
+
rust_tokens = rust_tokenizer.tokenize(sequence)
|
| 89 |
+
self.assertListEqual(tokens, rust_tokens)
|
| 90 |
+
|
| 91 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 92 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 93 |
+
self.assertListEqual(ids, rust_ids)
|
| 94 |
+
|
| 95 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 96 |
+
ids = tokenizer.encode(sequence)
|
| 97 |
+
rust_ids = rust_tokenizer.encode(sequence)
|
| 98 |
+
self.assertListEqual(ids, rust_ids)
|
| 99 |
+
|
| 100 |
+
# With lower casing
|
| 101 |
+
tokenizer = self.get_tokenizer(do_lower_case=True)
|
| 102 |
+
rust_tokenizer = self.get_rust_tokenizer(do_lower_case=True)
|
| 103 |
+
|
| 104 |
+
sequence = "UNwant\u00E9d,running"
|
| 105 |
+
|
| 106 |
+
tokens = tokenizer.tokenize(sequence)
|
| 107 |
+
rust_tokens = rust_tokenizer.tokenize(sequence)
|
| 108 |
+
self.assertListEqual(tokens, rust_tokens)
|
| 109 |
+
|
| 110 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 111 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 112 |
+
self.assertListEqual(ids, rust_ids)
|
| 113 |
+
|
| 114 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 115 |
+
ids = tokenizer.encode(sequence)
|
| 116 |
+
rust_ids = rust_tokenizer.encode(sequence)
|
| 117 |
+
self.assertListEqual(ids, rust_ids)
|
| 118 |
+
|
| 119 |
+
def test_chinese(self):
|
| 120 |
+
tokenizer = BasicTokenizer()
|
| 121 |
+
|
| 122 |
+
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"])
|
| 123 |
+
|
| 124 |
+
def test_basic_tokenizer_lower(self):
|
| 125 |
+
tokenizer = BasicTokenizer(do_lower_case=True)
|
| 126 |
+
|
| 127 |
+
self.assertListEqual(
|
| 128 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"]
|
| 129 |
+
)
|
| 130 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 131 |
+
|
| 132 |
+
def test_basic_tokenizer_lower_strip_accents_false(self):
|
| 133 |
+
tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False)
|
| 134 |
+
|
| 135 |
+
self.assertListEqual(
|
| 136 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"]
|
| 137 |
+
)
|
| 138 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"])
|
| 139 |
+
|
| 140 |
+
def test_basic_tokenizer_lower_strip_accents_true(self):
|
| 141 |
+
tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True)
|
| 142 |
+
|
| 143 |
+
self.assertListEqual(
|
| 144 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 145 |
+
)
|
| 146 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 147 |
+
|
| 148 |
+
def test_basic_tokenizer_lower_strip_accents_default(self):
|
| 149 |
+
tokenizer = BasicTokenizer(do_lower_case=True)
|
| 150 |
+
|
| 151 |
+
self.assertListEqual(
|
| 152 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 153 |
+
)
|
| 154 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 155 |
+
|
| 156 |
+
def test_basic_tokenizer_no_lower(self):
|
| 157 |
+
tokenizer = BasicTokenizer(do_lower_case=False)
|
| 158 |
+
|
| 159 |
+
self.assertListEqual(
|
| 160 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def test_basic_tokenizer_no_lower_strip_accents_false(self):
|
| 164 |
+
tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False)
|
| 165 |
+
|
| 166 |
+
self.assertListEqual(
|
| 167 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def test_basic_tokenizer_no_lower_strip_accents_true(self):
|
| 171 |
+
tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True)
|
| 172 |
+
|
| 173 |
+
self.assertListEqual(
|
| 174 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"]
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def test_basic_tokenizer_respects_never_split_tokens(self):
|
| 178 |
+
tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"])
|
| 179 |
+
|
| 180 |
+
self.assertListEqual(
|
| 181 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def test_wordpiece_tokenizer(self):
|
| 185 |
+
vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
|
| 186 |
+
|
| 187 |
+
vocab = {}
|
| 188 |
+
for i, token in enumerate(vocab_tokens):
|
| 189 |
+
vocab[token] = i
|
| 190 |
+
tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]")
|
| 191 |
+
|
| 192 |
+
self.assertListEqual(tokenizer.tokenize(""), [])
|
| 193 |
+
|
| 194 |
+
self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"])
|
| 195 |
+
|
| 196 |
+
self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
|
| 197 |
+
|
| 198 |
+
def test_is_whitespace(self):
|
| 199 |
+
self.assertTrue(_is_whitespace(" "))
|
| 200 |
+
self.assertTrue(_is_whitespace("\t"))
|
| 201 |
+
self.assertTrue(_is_whitespace("\r"))
|
| 202 |
+
self.assertTrue(_is_whitespace("\n"))
|
| 203 |
+
self.assertTrue(_is_whitespace("\u00A0"))
|
| 204 |
+
|
| 205 |
+
self.assertFalse(_is_whitespace("A"))
|
| 206 |
+
self.assertFalse(_is_whitespace("-"))
|
| 207 |
+
|
| 208 |
+
def test_is_control(self):
|
| 209 |
+
self.assertTrue(_is_control("\u0005"))
|
| 210 |
+
|
| 211 |
+
self.assertFalse(_is_control("A"))
|
| 212 |
+
self.assertFalse(_is_control(" "))
|
| 213 |
+
self.assertFalse(_is_control("\t"))
|
| 214 |
+
self.assertFalse(_is_control("\r"))
|
| 215 |
+
|
| 216 |
+
def test_is_punctuation(self):
|
| 217 |
+
self.assertTrue(_is_punctuation("-"))
|
| 218 |
+
self.assertTrue(_is_punctuation("$"))
|
| 219 |
+
self.assertTrue(_is_punctuation("`"))
|
| 220 |
+
self.assertTrue(_is_punctuation("."))
|
| 221 |
+
|
| 222 |
+
self.assertFalse(_is_punctuation("A"))
|
| 223 |
+
self.assertFalse(_is_punctuation(" "))
|
| 224 |
+
|
| 225 |
+
def test_clean_text(self):
|
| 226 |
+
tokenizer = self.get_tokenizer()
|
| 227 |
+
|
| 228 |
+
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
|
| 229 |
+
self.assertListEqual([tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]])
|
| 230 |
+
|
| 231 |
+
if self.test_rust_tokenizer:
|
| 232 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 233 |
+
self.assertListEqual(
|
| 234 |
+
[rust_tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]]
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
@slow
|
| 238 |
+
def test_sequence_builders(self):
|
| 239 |
+
tokenizer = self.tokenizer_class.from_pretrained("bert-base-uncased")
|
| 240 |
+
|
| 241 |
+
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
| 242 |
+
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
| 243 |
+
|
| 244 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 245 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 246 |
+
|
| 247 |
+
assert encoded_sentence == [101] + text + [102]
|
| 248 |
+
assert encoded_pair == [101] + text + [102] + text_2 + [102]
|
| 249 |
+
|
| 250 |
+
def test_offsets_with_special_characters(self):
|
| 251 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 252 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 253 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 254 |
+
|
| 255 |
+
sentence = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence."
|
| 256 |
+
tokens = tokenizer_r.encode_plus(
|
| 257 |
+
sentence,
|
| 258 |
+
return_attention_mask=False,
|
| 259 |
+
return_token_type_ids=False,
|
| 260 |
+
return_offsets_mapping=True,
|
| 261 |
+
add_special_tokens=True,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, "do_lower_case") else False
|
| 265 |
+
expected_results = (
|
| 266 |
+
[
|
| 267 |
+
((0, 0), tokenizer_r.cls_token),
|
| 268 |
+
((0, 1), "A"),
|
| 269 |
+
((1, 2), ","),
|
| 270 |
+
((3, 5), "na"),
|
| 271 |
+
((5, 6), "##ï"),
|
| 272 |
+
((6, 8), "##ve"),
|
| 273 |
+
((9, 15), tokenizer_r.mask_token),
|
| 274 |
+
((16, 21), "Allen"),
|
| 275 |
+
((21, 23), "##NL"),
|
| 276 |
+
((23, 24), "##P"),
|
| 277 |
+
((25, 33), "sentence"),
|
| 278 |
+
((33, 34), "."),
|
| 279 |
+
((0, 0), tokenizer_r.sep_token),
|
| 280 |
+
]
|
| 281 |
+
if not do_lower_case
|
| 282 |
+
else [
|
| 283 |
+
((0, 0), tokenizer_r.cls_token),
|
| 284 |
+
((0, 1), "a"),
|
| 285 |
+
((1, 2), ","),
|
| 286 |
+
((3, 8), "naive"),
|
| 287 |
+
((9, 15), tokenizer_r.mask_token),
|
| 288 |
+
((16, 21), "allen"),
|
| 289 |
+
((21, 23), "##nl"),
|
| 290 |
+
((23, 24), "##p"),
|
| 291 |
+
((25, 33), "sentence"),
|
| 292 |
+
((33, 34), "."),
|
| 293 |
+
((0, 0), tokenizer_r.sep_token),
|
| 294 |
+
]
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
self.assertEqual(
|
| 298 |
+
[e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["input_ids"])
|
| 299 |
+
)
|
| 300 |
+
self.assertEqual([e[0] for e in expected_results], tokens["offset_mapping"])
|
| 301 |
+
|
| 302 |
+
@slow
|
| 303 |
+
def test_batch_encode_candidates(self):
|
| 304 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 305 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 306 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 307 |
+
tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 308 |
+
text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
|
| 309 |
+
|
| 310 |
+
encoded_sentence_r = tokenizer_r.batch_encode_candidates(text, max_length=10, return_tensors="np")
|
| 311 |
+
encoded_sentence_p = tokenizer_p.batch_encode_candidates(text, max_length=10, return_tensors="np")
|
| 312 |
+
|
| 313 |
+
expected_shape = (2, 2, 10)
|
| 314 |
+
|
| 315 |
+
self.assertEqual(encoded_sentence_r["input_ids"].shape, expected_shape)
|
| 316 |
+
self.assertEqual(encoded_sentence_r["attention_mask"].shape, expected_shape)
|
| 317 |
+
self.assertEqual(encoded_sentence_r["token_type_ids"].shape, expected_shape)
|
| 318 |
+
|
| 319 |
+
self.assertEqual(encoded_sentence_p["input_ids"].shape, expected_shape)
|
| 320 |
+
self.assertEqual(encoded_sentence_p["attention_mask"].shape, expected_shape)
|
| 321 |
+
self.assertEqual(encoded_sentence_p["token_type_ids"].shape, expected_shape)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_modeling_reformer.py
ADDED
|
@@ -0,0 +1,1305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8 # Copyright 2020 Huggingface
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
from transformers import ReformerConfig, is_torch_available
|
| 19 |
+
from transformers.testing_utils import (
|
| 20 |
+
require_sentencepiece,
|
| 21 |
+
require_tokenizers,
|
| 22 |
+
require_torch,
|
| 23 |
+
require_torch_fp16,
|
| 24 |
+
require_torch_multi_gpu,
|
| 25 |
+
slow,
|
| 26 |
+
torch_device,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 30 |
+
from ...test_configuration_common import ConfigTester
|
| 31 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 32 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
from torch import nn
|
| 38 |
+
|
| 39 |
+
from transformers import (
|
| 40 |
+
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 41 |
+
ReformerForMaskedLM,
|
| 42 |
+
ReformerForQuestionAnswering,
|
| 43 |
+
ReformerForSequenceClassification,
|
| 44 |
+
ReformerLayer,
|
| 45 |
+
ReformerModel,
|
| 46 |
+
ReformerModelWithLMHead,
|
| 47 |
+
ReformerTokenizer,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ReformerModelTester:
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
parent,
|
| 55 |
+
batch_size=13,
|
| 56 |
+
seq_length=32,
|
| 57 |
+
is_training=True,
|
| 58 |
+
is_decoder=True,
|
| 59 |
+
use_input_mask=True,
|
| 60 |
+
use_labels=True,
|
| 61 |
+
vocab_size=32,
|
| 62 |
+
attention_head_size=16,
|
| 63 |
+
hidden_size=32,
|
| 64 |
+
num_attention_heads=2,
|
| 65 |
+
local_attn_chunk_length=4,
|
| 66 |
+
local_num_chunks_before=1,
|
| 67 |
+
local_num_chunks_after=0,
|
| 68 |
+
num_buckets=None,
|
| 69 |
+
num_hashes=1,
|
| 70 |
+
lsh_attn_chunk_length=None,
|
| 71 |
+
lsh_num_chunks_before=None,
|
| 72 |
+
lsh_num_chunks_after=None,
|
| 73 |
+
chunk_size_lm_head=0,
|
| 74 |
+
chunk_size_feed_forward=0,
|
| 75 |
+
feed_forward_size=32,
|
| 76 |
+
hidden_act="gelu",
|
| 77 |
+
hidden_dropout_prob=0.1,
|
| 78 |
+
local_attention_probs_dropout_prob=0.1,
|
| 79 |
+
lsh_attention_probs_dropout_prob=None,
|
| 80 |
+
max_position_embeddings=512,
|
| 81 |
+
initializer_range=0.02,
|
| 82 |
+
axial_norm_std=1.0,
|
| 83 |
+
layer_norm_eps=1e-12,
|
| 84 |
+
axial_pos_embds=True,
|
| 85 |
+
axial_pos_shape=[4, 8],
|
| 86 |
+
axial_pos_embds_dim=[16, 16],
|
| 87 |
+
attn_layers=["local", "local", "local", "local"],
|
| 88 |
+
pad_token_id=0,
|
| 89 |
+
eos_token_id=2,
|
| 90 |
+
scope=None,
|
| 91 |
+
hash_seed=0,
|
| 92 |
+
num_labels=2,
|
| 93 |
+
):
|
| 94 |
+
self.parent = parent
|
| 95 |
+
self.batch_size = batch_size
|
| 96 |
+
self.seq_length = seq_length
|
| 97 |
+
self.is_training = is_training
|
| 98 |
+
self.is_decoder = is_decoder
|
| 99 |
+
self.use_input_mask = use_input_mask
|
| 100 |
+
self.use_labels = use_labels
|
| 101 |
+
self.vocab_size = vocab_size
|
| 102 |
+
self.attention_head_size = attention_head_size
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_attention_heads = num_attention_heads
|
| 105 |
+
self.num_hidden_layers = len(attn_layers) if attn_layers is not None else 0
|
| 106 |
+
self.local_attn_chunk_length = local_attn_chunk_length
|
| 107 |
+
self.local_num_chunks_after = local_num_chunks_after
|
| 108 |
+
self.local_num_chunks_before = local_num_chunks_before
|
| 109 |
+
self.num_hashes = num_hashes
|
| 110 |
+
self.num_buckets = tuple(num_buckets) if isinstance(num_buckets, list) else num_buckets
|
| 111 |
+
self.lsh_attn_chunk_length = lsh_attn_chunk_length
|
| 112 |
+
self.lsh_num_chunks_after = lsh_num_chunks_after
|
| 113 |
+
self.lsh_num_chunks_before = lsh_num_chunks_before
|
| 114 |
+
self.hidden_act = hidden_act
|
| 115 |
+
self.feed_forward_size = feed_forward_size
|
| 116 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 117 |
+
self.local_attention_probs_dropout_prob = local_attention_probs_dropout_prob
|
| 118 |
+
self.lsh_attention_probs_dropout_prob = lsh_attention_probs_dropout_prob
|
| 119 |
+
self.max_position_embeddings = max_position_embeddings
|
| 120 |
+
self.initializer_range = initializer_range
|
| 121 |
+
self.layer_norm_eps = layer_norm_eps
|
| 122 |
+
self.axial_pos_embds = axial_pos_embds
|
| 123 |
+
self.axial_pos_shape = tuple(axial_pos_shape)
|
| 124 |
+
self.axial_pos_embds_dim = tuple(axial_pos_embds_dim)
|
| 125 |
+
self.axial_norm_std = axial_norm_std
|
| 126 |
+
self.chunk_size_lm_head = chunk_size_lm_head
|
| 127 |
+
self.chunk_size_feed_forward = chunk_size_feed_forward
|
| 128 |
+
self.scope = scope
|
| 129 |
+
self.attn_layers = attn_layers
|
| 130 |
+
self.pad_token_id = pad_token_id
|
| 131 |
+
self.hash_seed = hash_seed
|
| 132 |
+
|
| 133 |
+
attn_chunk_length = local_attn_chunk_length if local_attn_chunk_length is not None else lsh_attn_chunk_length
|
| 134 |
+
num_chunks_after = local_num_chunks_after if local_num_chunks_after is not None else lsh_num_chunks_after
|
| 135 |
+
num_chunks_before = local_num_chunks_before if local_num_chunks_before is not None else lsh_num_chunks_before
|
| 136 |
+
|
| 137 |
+
self.encoder_seq_length = seq_length // attn_chunk_length + (self.seq_length % attn_chunk_length != 0)
|
| 138 |
+
self.key_length = (num_chunks_before + num_chunks_after + 1) * attn_chunk_length
|
| 139 |
+
self.chunk_length = attn_chunk_length
|
| 140 |
+
self.num_labels = num_labels
|
| 141 |
+
|
| 142 |
+
def prepare_config_and_inputs(self):
|
| 143 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 144 |
+
|
| 145 |
+
input_mask = None
|
| 146 |
+
if self.use_input_mask:
|
| 147 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 148 |
+
|
| 149 |
+
choice_labels = None
|
| 150 |
+
if self.use_labels:
|
| 151 |
+
choice_labels = ids_tensor([self.batch_size], 2)
|
| 152 |
+
|
| 153 |
+
config = self.get_config()
|
| 154 |
+
|
| 155 |
+
return (
|
| 156 |
+
config,
|
| 157 |
+
input_ids,
|
| 158 |
+
input_mask,
|
| 159 |
+
choice_labels,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def get_config(self):
|
| 163 |
+
return ReformerConfig(
|
| 164 |
+
vocab_size=self.vocab_size,
|
| 165 |
+
hidden_size=self.hidden_size,
|
| 166 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 167 |
+
num_attention_heads=self.num_attention_heads,
|
| 168 |
+
feed_forward_size=self.feed_forward_size,
|
| 169 |
+
hidden_act=self.hidden_act,
|
| 170 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 171 |
+
local_attention_probs_dropout_prob=self.local_attention_probs_dropout_prob,
|
| 172 |
+
lsh_attention_probs_dropout_prob=self.lsh_attention_probs_dropout_prob,
|
| 173 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 174 |
+
is_decoder=self.is_decoder,
|
| 175 |
+
axial_pos_embds=self.axial_pos_embds,
|
| 176 |
+
axial_pos_shape=self.axial_pos_shape,
|
| 177 |
+
axial_pos_embds_dim=self.axial_pos_embds_dim,
|
| 178 |
+
local_attn_chunk_length=self.local_attn_chunk_length,
|
| 179 |
+
local_num_chunks_after=self.local_num_chunks_after,
|
| 180 |
+
local_num_chunks_before=self.local_num_chunks_before,
|
| 181 |
+
num_hashes=self.num_hashes,
|
| 182 |
+
num_buckets=self.num_buckets,
|
| 183 |
+
lsh_attn_chunk_length=self.lsh_attn_chunk_length,
|
| 184 |
+
lsh_num_chunks_after=self.lsh_num_chunks_after,
|
| 185 |
+
lsh_num_chunks_before=self.lsh_num_chunks_before,
|
| 186 |
+
attn_layers=self.attn_layers,
|
| 187 |
+
pad_token_id=self.pad_token_id,
|
| 188 |
+
hash_seed=self.hash_seed,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
def get_pipeline_config(self):
|
| 192 |
+
config = self.get_config()
|
| 193 |
+
config.vocab_size = 100
|
| 194 |
+
config.max_position_embeddings = 100
|
| 195 |
+
config.axial_pos_shape = (4, 25)
|
| 196 |
+
config.is_decoder = False
|
| 197 |
+
return config
|
| 198 |
+
|
| 199 |
+
def create_and_check_reformer_model(self, config, input_ids, input_mask, choice_labels):
|
| 200 |
+
model = ReformerModel(config=config)
|
| 201 |
+
model.to(torch_device)
|
| 202 |
+
model.eval()
|
| 203 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 204 |
+
result = model(input_ids)
|
| 205 |
+
|
| 206 |
+
# 2 * hidden_size because we use reversible resnet layers
|
| 207 |
+
self.parent.assertEqual(
|
| 208 |
+
result.last_hidden_state.shape, (self.batch_size, self.seq_length, 2 * self.hidden_size)
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def create_and_check_reformer_model_with_lm_backward(self, config, input_ids, input_mask, choice_labels):
|
| 212 |
+
if not self.is_training:
|
| 213 |
+
return
|
| 214 |
+
|
| 215 |
+
config.is_decoder = False
|
| 216 |
+
config.lsh_num_chunks_after = 1
|
| 217 |
+
model = ReformerForMaskedLM(config=config)
|
| 218 |
+
model.to(torch_device)
|
| 219 |
+
model.train()
|
| 220 |
+
loss = model(input_ids, attention_mask=input_mask, labels=input_ids)["loss"]
|
| 221 |
+
loss.backward()
|
| 222 |
+
|
| 223 |
+
def create_and_check_reformer_with_lm(self, config, input_ids, input_mask, choice_labels):
|
| 224 |
+
config.lsh_num_chunks_after = 0
|
| 225 |
+
config.is_decoder = True
|
| 226 |
+
model = ReformerModelWithLMHead(config=config)
|
| 227 |
+
model.to(torch_device)
|
| 228 |
+
model.eval()
|
| 229 |
+
result = model(input_ids, attention_mask=input_mask, labels=input_ids)
|
| 230 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 231 |
+
|
| 232 |
+
def create_and_check_reformer_with_mlm(self, config, input_ids, input_mask, choice_labels):
|
| 233 |
+
config.is_decoder = False
|
| 234 |
+
model = ReformerForMaskedLM(config=config)
|
| 235 |
+
model.to(torch_device)
|
| 236 |
+
model.eval()
|
| 237 |
+
result = model(input_ids, attention_mask=input_mask, labels=input_ids)
|
| 238 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 239 |
+
|
| 240 |
+
def create_and_check_reformer_model_with_attn_mask(
|
| 241 |
+
self, config, input_ids, input_mask, choice_labels, is_decoder=False
|
| 242 |
+
):
|
| 243 |
+
# no special position embeddings
|
| 244 |
+
config.axial_pos_embds = False
|
| 245 |
+
config.is_decoder = is_decoder
|
| 246 |
+
|
| 247 |
+
if self.lsh_attn_chunk_length is not None:
|
| 248 |
+
# need to set chunk length equal sequence length to be certain that chunking works
|
| 249 |
+
config.lsh_attn_chunk_length = self.seq_length
|
| 250 |
+
|
| 251 |
+
model = ReformerModel(config=config)
|
| 252 |
+
model.to(torch_device)
|
| 253 |
+
model.eval()
|
| 254 |
+
# set all position encodings to zero so that postions don't matter
|
| 255 |
+
with torch.no_grad():
|
| 256 |
+
embedding = model.embeddings.position_embeddings.embedding
|
| 257 |
+
embedding.weight = nn.Parameter(torch.zeros(embedding.weight.shape).to(torch_device))
|
| 258 |
+
embedding.weight.requires_grad = False
|
| 259 |
+
|
| 260 |
+
half_seq_len = self.seq_length // 2
|
| 261 |
+
roll = self.chunk_length
|
| 262 |
+
|
| 263 |
+
half_input_ids = input_ids[:, :half_seq_len]
|
| 264 |
+
|
| 265 |
+
# normal padded
|
| 266 |
+
attn_mask = torch.cat(
|
| 267 |
+
[torch.ones_like(half_input_ids), torch.zeros_like(half_input_ids)],
|
| 268 |
+
dim=-1,
|
| 269 |
+
)
|
| 270 |
+
input_ids_padded = torch.cat(
|
| 271 |
+
[half_input_ids, ids_tensor((self.batch_size, half_seq_len), self.vocab_size)],
|
| 272 |
+
dim=-1,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
# shifted padded
|
| 276 |
+
input_ids_roll = torch.cat(
|
| 277 |
+
[half_input_ids, ids_tensor((self.batch_size, half_seq_len), self.vocab_size)],
|
| 278 |
+
dim=-1,
|
| 279 |
+
)
|
| 280 |
+
input_ids_roll = torch.roll(input_ids_roll, roll, dims=-1)
|
| 281 |
+
attn_mask_roll = torch.roll(attn_mask, roll, dims=-1)
|
| 282 |
+
|
| 283 |
+
output_padded = model(input_ids_padded, attention_mask=attn_mask)[0][:, :half_seq_len]
|
| 284 |
+
output_padded_rolled = model(input_ids_roll, attention_mask=attn_mask_roll)[0][:, roll : half_seq_len + roll]
|
| 285 |
+
|
| 286 |
+
self.parent.assertTrue(torch.allclose(output_padded, output_padded_rolled, atol=1e-3))
|
| 287 |
+
|
| 288 |
+
def create_and_check_reformer_layer_dropout_seed(
|
| 289 |
+
self, config, input_ids, input_mask, choice_labels, is_decoder=False
|
| 290 |
+
):
|
| 291 |
+
config.is_decoder = is_decoder
|
| 292 |
+
layer = ReformerLayer(config).to(torch_device)
|
| 293 |
+
layer.train()
|
| 294 |
+
shape = (
|
| 295 |
+
self.batch_size,
|
| 296 |
+
self.seq_length,
|
| 297 |
+
config.hidden_size,
|
| 298 |
+
) # Batch x SeqLen x hiddenSize
|
| 299 |
+
|
| 300 |
+
# get random tensors
|
| 301 |
+
hidden_states = floats_tensor(shape)
|
| 302 |
+
prev_attn_output = floats_tensor(shape)
|
| 303 |
+
|
| 304 |
+
# now the random seeds for attention and feed forward is initialized
|
| 305 |
+
# forward tensors with dropout
|
| 306 |
+
layer_outputs = layer(prev_attn_output, hidden_states, attention_mask=input_mask)
|
| 307 |
+
|
| 308 |
+
next_attn_output = layer_outputs.attn_output
|
| 309 |
+
next_hidden_states = layer_outputs.hidden_states
|
| 310 |
+
|
| 311 |
+
torch.manual_seed(layer.attention_seed)
|
| 312 |
+
attn_outputs = layer.attention(hidden_states, attention_mask=input_mask)
|
| 313 |
+
self.parent.assertTrue(
|
| 314 |
+
torch.allclose(
|
| 315 |
+
prev_attn_output + attn_outputs.hidden_states,
|
| 316 |
+
next_attn_output,
|
| 317 |
+
atol=1e-3,
|
| 318 |
+
)
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
torch.manual_seed(layer.feed_forward_seed)
|
| 322 |
+
feed_forward_hidden_states = layer.feed_forward(next_attn_output)
|
| 323 |
+
self.parent.assertTrue(
|
| 324 |
+
torch.allclose(
|
| 325 |
+
next_hidden_states,
|
| 326 |
+
hidden_states + feed_forward_hidden_states,
|
| 327 |
+
atol=1e-3,
|
| 328 |
+
)
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
def create_and_check_reformer_feed_backward_chunking(self, config, input_ids, input_mask, choice_labels):
|
| 332 |
+
if not self.is_training:
|
| 333 |
+
return
|
| 334 |
+
|
| 335 |
+
# disable dropout
|
| 336 |
+
config.hidden_dropout_prob = 0
|
| 337 |
+
config.local_attention_probs_dropout_prob = 0
|
| 338 |
+
config.lsh_attention_probs_dropout_prob = 0
|
| 339 |
+
config.lsh_num_chunks_after = 1
|
| 340 |
+
config.is_decoder = False
|
| 341 |
+
|
| 342 |
+
torch.manual_seed(0)
|
| 343 |
+
model = ReformerForMaskedLM(config=config)
|
| 344 |
+
model.to(torch_device)
|
| 345 |
+
model.train()
|
| 346 |
+
model.zero_grad()
|
| 347 |
+
loss_no_chunk, output_no_chunk = model(input_ids, labels=input_ids, attention_mask=input_mask)[:2]
|
| 348 |
+
loss_no_chunk.backward()
|
| 349 |
+
grad_slice_word_no_chunk = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
|
| 350 |
+
grad_slice_position_factor_1_no_chunk = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
|
| 351 |
+
grad_slice_position_factor_2_no_chunk = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
|
| 352 |
+
|
| 353 |
+
config.chunk_size_lm_head = 1
|
| 354 |
+
config.chunk_size_feed_forward = 1
|
| 355 |
+
|
| 356 |
+
torch.manual_seed(0)
|
| 357 |
+
model = ReformerForMaskedLM(config=config)
|
| 358 |
+
model.to(torch_device)
|
| 359 |
+
model.train()
|
| 360 |
+
model.zero_grad()
|
| 361 |
+
loss_chunk, output_chunk = model(input_ids, labels=input_ids, attention_mask=input_mask)[:2]
|
| 362 |
+
loss_chunk.backward()
|
| 363 |
+
grad_slice_word_chunk = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
|
| 364 |
+
grad_slice_position_factor_1_chunk = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
|
| 365 |
+
grad_slice_position_factor_2_chunk = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
|
| 366 |
+
self.parent.assertTrue(torch.allclose(loss_chunk, loss_no_chunk, atol=1e-3))
|
| 367 |
+
self.parent.assertTrue(torch.allclose(grad_slice_word_no_chunk, grad_slice_word_chunk, atol=1e-3))
|
| 368 |
+
self.parent.assertTrue(
|
| 369 |
+
torch.allclose(grad_slice_position_factor_1_chunk, grad_slice_position_factor_1_no_chunk, atol=1e-3)
|
| 370 |
+
)
|
| 371 |
+
self.parent.assertTrue(
|
| 372 |
+
torch.allclose(grad_slice_position_factor_2_chunk, grad_slice_position_factor_2_no_chunk, atol=1e-3)
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
def create_and_check_reformer_random_seed(self, config, input_ids, input_mask, choice_labels):
|
| 376 |
+
layer = ReformerLayer(config).to(torch_device)
|
| 377 |
+
layer.train()
|
| 378 |
+
|
| 379 |
+
shape = (
|
| 380 |
+
self.batch_size,
|
| 381 |
+
self.seq_length,
|
| 382 |
+
config.hidden_size,
|
| 383 |
+
) # Batch x SeqLen x hiddenSize
|
| 384 |
+
|
| 385 |
+
hidden_states = floats_tensor(shape)
|
| 386 |
+
attn_output = floats_tensor(shape)
|
| 387 |
+
|
| 388 |
+
seeds = []
|
| 389 |
+
for _ in range(100):
|
| 390 |
+
layer_outputs = layer(attn_output, hidden_states, attention_mask=input_mask)
|
| 391 |
+
attn_output = layer_outputs.attn_output
|
| 392 |
+
hidden_states = layer_outputs.hidden_states
|
| 393 |
+
torch.manual_seed(layer.attention_seed)
|
| 394 |
+
seeds.append(layer.attention_seed)
|
| 395 |
+
self.parent.assertGreater(len(set(seeds)), 70)
|
| 396 |
+
|
| 397 |
+
seeds = []
|
| 398 |
+
for _ in range(100):
|
| 399 |
+
layer_outputs = layer(attn_output, hidden_states, attention_mask=input_mask)
|
| 400 |
+
attn_output = layer_outputs.attn_output
|
| 401 |
+
hidden_states = layer_outputs.hidden_states
|
| 402 |
+
torch.manual_seed(layer.feed_forward_seed)
|
| 403 |
+
seeds.append(layer.feed_forward_seed)
|
| 404 |
+
self.parent.assertGreater(len(set(seeds)), 70)
|
| 405 |
+
|
| 406 |
+
def create_and_check_reformer_model_fp16_forward(self, config, input_ids, input_mask, choice_labels):
|
| 407 |
+
model = ReformerModel(config=config)
|
| 408 |
+
model.to(torch_device)
|
| 409 |
+
model.half()
|
| 410 |
+
model.eval()
|
| 411 |
+
output = model(input_ids, attention_mask=input_mask)["last_hidden_state"]
|
| 412 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 413 |
+
|
| 414 |
+
def create_and_check_reformer_model_generate(self, config, input_ids, input_mask, choice_labels):
|
| 415 |
+
config.is_decoder = True
|
| 416 |
+
config.lsh_num_chunks_after = 0
|
| 417 |
+
config.bos_token_id = 0
|
| 418 |
+
config.eos_token_id = None
|
| 419 |
+
config.max_length = 20
|
| 420 |
+
|
| 421 |
+
model = ReformerModelWithLMHead(config=config)
|
| 422 |
+
model.to(torch_device)
|
| 423 |
+
model.eval()
|
| 424 |
+
output = model.generate()
|
| 425 |
+
self.parent.assertIsNotNone(output)
|
| 426 |
+
|
| 427 |
+
def create_and_check_reformer_model_fp16_generate(self, config, input_ids, input_mask, choice_labels):
|
| 428 |
+
config.is_decoder = True
|
| 429 |
+
config.lsh_num_chunks_after = 0
|
| 430 |
+
model = ReformerModelWithLMHead(config=config)
|
| 431 |
+
model.to(torch_device)
|
| 432 |
+
model.half()
|
| 433 |
+
model.eval()
|
| 434 |
+
# only use last 10 inputs for generation
|
| 435 |
+
output = model.generate(input_ids[:, -10:], attention_mask=input_mask, do_sample=False)
|
| 436 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 437 |
+
|
| 438 |
+
def create_and_check_reformer_no_chunking(self, config, input_ids, input_mask, choice_labels):
|
| 439 |
+
# force chunk length to be bigger than input_ids
|
| 440 |
+
config.lsh_attn_chunk_length = 2 * input_ids.shape[-1]
|
| 441 |
+
config.local_attn_chunk_length = 2 * input_ids.shape[-1]
|
| 442 |
+
config.lsh_num_chunks_after = 1
|
| 443 |
+
config.is_decoder = False
|
| 444 |
+
model = ReformerForMaskedLM(config=config)
|
| 445 |
+
model.to(torch_device)
|
| 446 |
+
model.eval()
|
| 447 |
+
output_logits = model(input_ids, attention_mask=input_mask)["logits"]
|
| 448 |
+
self.parent.assertTrue(output_logits.shape[1] == input_ids.shape[-1])
|
| 449 |
+
|
| 450 |
+
def create_and_check_reformer_for_question_answering(self, config, input_ids, input_mask, choice_labels):
|
| 451 |
+
model = ReformerForQuestionAnswering(config=config)
|
| 452 |
+
model.to(torch_device)
|
| 453 |
+
model.eval()
|
| 454 |
+
result = model(
|
| 455 |
+
input_ids,
|
| 456 |
+
attention_mask=input_mask,
|
| 457 |
+
start_positions=choice_labels,
|
| 458 |
+
end_positions=choice_labels,
|
| 459 |
+
)
|
| 460 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 461 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 462 |
+
|
| 463 |
+
def create_and_check_past_buckets_states(self, config, input_ids, input_mask, choice_labels):
|
| 464 |
+
config.is_decoder = True
|
| 465 |
+
config.lsh_num_chunks_before = 1
|
| 466 |
+
config.lsh_num_chunks_after = 0
|
| 467 |
+
model = ReformerModelWithLMHead(config=config)
|
| 468 |
+
model.to(torch_device)
|
| 469 |
+
model.eval()
|
| 470 |
+
input_ids_first = input_ids[:, :-1]
|
| 471 |
+
input_ids_second = input_ids[:, -1:]
|
| 472 |
+
|
| 473 |
+
# return saved cache
|
| 474 |
+
past_buckets_states = model(input_ids_first, use_cache=True)["past_buckets_states"]
|
| 475 |
+
|
| 476 |
+
# calculate last output with and without cache
|
| 477 |
+
outputs_with_cache = model(input_ids_second, past_buckets_states=past_buckets_states, use_cache=True)["logits"]
|
| 478 |
+
outputs_without_cache = model(input_ids)["logits"][:, -1]
|
| 479 |
+
|
| 480 |
+
# select random slice idx
|
| 481 |
+
random_slice_idx = torch.randint(outputs_without_cache.shape[-1], (1, 1), device=torch_device).item()
|
| 482 |
+
|
| 483 |
+
# outputs should be similar within range
|
| 484 |
+
self.parent.assertTrue(
|
| 485 |
+
torch.allclose(
|
| 486 |
+
outputs_with_cache[:, 0, random_slice_idx], outputs_without_cache[:, random_slice_idx], atol=1e-2
|
| 487 |
+
)
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
def prepare_config_and_inputs_for_common(self):
|
| 491 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 492 |
+
(config, input_ids, input_mask, choice_labels) = config_and_inputs
|
| 493 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 494 |
+
return config, inputs_dict
|
| 495 |
+
|
| 496 |
+
def create_and_check_reformer_for_sequence_classification(
|
| 497 |
+
self, config, input_ids, input_mask, choice_labels, is_decoder
|
| 498 |
+
):
|
| 499 |
+
config.is_decoder = is_decoder
|
| 500 |
+
sequence_labels = ids_tensor([self.batch_size], config.num_labels)
|
| 501 |
+
model = ReformerForSequenceClassification(config)
|
| 502 |
+
model.to(torch_device)
|
| 503 |
+
model.eval()
|
| 504 |
+
result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
|
| 505 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class ReformerTesterMixin:
|
| 509 |
+
"""
|
| 510 |
+
Reformer Local and Reformer LSH run essentially the same tests
|
| 511 |
+
"""
|
| 512 |
+
|
| 513 |
+
def test_config(self):
|
| 514 |
+
self.config_tester.run_common_tests()
|
| 515 |
+
|
| 516 |
+
def test_reformer_model(self):
|
| 517 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 518 |
+
self.model_tester.create_and_check_reformer_model(*config_and_inputs)
|
| 519 |
+
|
| 520 |
+
def test_reformer_lm_model_backward(self):
|
| 521 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 522 |
+
self.model_tester.create_and_check_reformer_model_with_lm_backward(*config_and_inputs)
|
| 523 |
+
|
| 524 |
+
def test_reformer_model_attn_masking(self):
|
| 525 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 526 |
+
self.model_tester.create_and_check_reformer_model_with_attn_mask(*config_and_inputs, is_decoder=True)
|
| 527 |
+
self.model_tester.create_and_check_reformer_model_with_attn_mask(*config_and_inputs, is_decoder=False)
|
| 528 |
+
|
| 529 |
+
def test_reformer_with_lm(self):
|
| 530 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 531 |
+
self.model_tester.create_and_check_reformer_with_lm(*config_and_inputs)
|
| 532 |
+
|
| 533 |
+
def test_reformer_with_mlm(self):
|
| 534 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 535 |
+
self.model_tester.create_and_check_reformer_with_mlm(*config_and_inputs)
|
| 536 |
+
|
| 537 |
+
def test_reformer_layer_training_dropout(self):
|
| 538 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 539 |
+
self.model_tester.create_and_check_reformer_layer_dropout_seed(*config_and_inputs, is_decoder=True)
|
| 540 |
+
self.model_tester.create_and_check_reformer_layer_dropout_seed(*config_and_inputs, is_decoder=False)
|
| 541 |
+
|
| 542 |
+
def test_reformer_chunking_backward_equality(self):
|
| 543 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 544 |
+
self.model_tester.create_and_check_reformer_feed_backward_chunking(*config_and_inputs)
|
| 545 |
+
|
| 546 |
+
def test_reformer_no_chunking(self):
|
| 547 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 548 |
+
self.model_tester.create_and_check_reformer_no_chunking(*config_and_inputs)
|
| 549 |
+
|
| 550 |
+
def test_reformer_qa_answering(self):
|
| 551 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 552 |
+
self.model_tester.create_and_check_reformer_for_question_answering(*config_and_inputs)
|
| 553 |
+
|
| 554 |
+
def test_reformer_cached_inference(self):
|
| 555 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 556 |
+
self.model_tester.create_and_check_past_buckets_states(*config_and_inputs)
|
| 557 |
+
|
| 558 |
+
def test_reformer_cached_generate(self):
|
| 559 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 560 |
+
self.model_tester.create_and_check_reformer_model_generate(*config_and_inputs)
|
| 561 |
+
|
| 562 |
+
@slow
|
| 563 |
+
def test_dropout_random_seed_is_changing(self):
|
| 564 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 565 |
+
self.model_tester.create_and_check_reformer_random_seed(*config_and_inputs)
|
| 566 |
+
|
| 567 |
+
@require_torch_fp16
|
| 568 |
+
def test_reformer_model_fp16_forward(self):
|
| 569 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 570 |
+
self.model_tester.create_and_check_reformer_model_fp16_forward(*config_and_inputs)
|
| 571 |
+
|
| 572 |
+
@require_torch_fp16
|
| 573 |
+
def test_reformer_model_fp16_generate(self):
|
| 574 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 575 |
+
self.model_tester.create_and_check_reformer_model_fp16_generate(*config_and_inputs)
|
| 576 |
+
|
| 577 |
+
@require_torch_multi_gpu
|
| 578 |
+
@unittest.skip(
|
| 579 |
+
reason=(
|
| 580 |
+
"Reformer does not work with data parallel (DP) because of a bug in PyTorch:"
|
| 581 |
+
" https://github.com/pytorch/pytorch/issues/36035"
|
| 582 |
+
)
|
| 583 |
+
)
|
| 584 |
+
def test_multi_gpu_data_parallel_forward(self):
|
| 585 |
+
pass
|
| 586 |
+
|
| 587 |
+
def test_for_sequence_classification(self):
|
| 588 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 589 |
+
self.model_tester.create_and_check_reformer_for_sequence_classification(*config_and_inputs, is_decoder=False)
|
| 590 |
+
|
| 591 |
+
def test_retain_grad_hidden_states_attentions(self):
|
| 592 |
+
# reformer cannot keep gradients in attentions or hidden states
|
| 593 |
+
return
|
| 594 |
+
|
| 595 |
+
def test_resize_embeddings_untied(self):
|
| 596 |
+
# reformer cannot resize embeddings that easily
|
| 597 |
+
return
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
@require_torch
|
| 601 |
+
class ReformerLocalAttnModelTest(ReformerTesterMixin, GenerationTesterMixin, ModelTesterMixin, unittest.TestCase):
|
| 602 |
+
all_model_classes = (
|
| 603 |
+
(ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering)
|
| 604 |
+
if is_torch_available()
|
| 605 |
+
else ()
|
| 606 |
+
)
|
| 607 |
+
all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else ()
|
| 608 |
+
test_pruning = False
|
| 609 |
+
test_headmasking = False
|
| 610 |
+
test_torchscript = False
|
| 611 |
+
test_sequence_classification_problem_types = True
|
| 612 |
+
|
| 613 |
+
def setUp(self):
|
| 614 |
+
self.model_tester = ReformerModelTester(self)
|
| 615 |
+
self.config_tester = ConfigTester(self, config_class=ReformerConfig, hidden_size=37)
|
| 616 |
+
|
| 617 |
+
@slow
|
| 618 |
+
def test_model_from_pretrained(self):
|
| 619 |
+
for model_name in REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 620 |
+
model = ReformerModelWithLMHead.from_pretrained(model_name)
|
| 621 |
+
self.assertIsNotNone(model)
|
| 622 |
+
|
| 623 |
+
def _check_attentions_for_generate(
|
| 624 |
+
self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1
|
| 625 |
+
):
|
| 626 |
+
self.assertIsInstance(attentions, tuple)
|
| 627 |
+
self.assertListEqual(
|
| 628 |
+
[isinstance(iter_attentions, list) for iter_attentions in attentions], [True] * len(attentions)
|
| 629 |
+
)
|
| 630 |
+
self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups)
|
| 631 |
+
|
| 632 |
+
for idx, iter_attentions in enumerate(attentions):
|
| 633 |
+
tgt_len = min_length + idx if not use_cache else 1
|
| 634 |
+
num_chunks = tgt_len // config.local_attn_chunk_length + (tgt_len % config.local_attn_chunk_length != 0)
|
| 635 |
+
tgt_chunk_len = config.local_attn_chunk_length
|
| 636 |
+
src_chunk_len = config.local_attn_chunk_length * (
|
| 637 |
+
1 + config.local_num_chunks_after + config.local_num_chunks_before
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
if use_cache:
|
| 641 |
+
expected_shape = (
|
| 642 |
+
batch_size * num_beam_groups,
|
| 643 |
+
config.num_attention_heads,
|
| 644 |
+
tgt_len,
|
| 645 |
+
min_length // config.local_attn_chunk_length + 1 + idx,
|
| 646 |
+
)
|
| 647 |
+
else:
|
| 648 |
+
expected_shape = (
|
| 649 |
+
batch_size * num_beam_groups,
|
| 650 |
+
config.num_attention_heads,
|
| 651 |
+
num_chunks,
|
| 652 |
+
tgt_chunk_len,
|
| 653 |
+
src_chunk_len,
|
| 654 |
+
)
|
| 655 |
+
# check attn size
|
| 656 |
+
self.assertListEqual(
|
| 657 |
+
[layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions)
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
def _check_hidden_states_for_generate(
|
| 661 |
+
self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1
|
| 662 |
+
):
|
| 663 |
+
self.assertIsInstance(hidden_states, tuple)
|
| 664 |
+
self.assertListEqual(
|
| 665 |
+
[isinstance(iter_hidden_states, list) for iter_hidden_states in hidden_states],
|
| 666 |
+
[True] * len(hidden_states),
|
| 667 |
+
)
|
| 668 |
+
self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups)
|
| 669 |
+
|
| 670 |
+
for idx, iter_hidden_states in enumerate(hidden_states):
|
| 671 |
+
seq_len = min_length + idx
|
| 672 |
+
seq_len = config.local_attn_chunk_length * (
|
| 673 |
+
seq_len // config.local_attn_chunk_length + (seq_len % config.local_attn_chunk_length != 0)
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
if use_cache:
|
| 677 |
+
seq_len = 1
|
| 678 |
+
|
| 679 |
+
expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size)
|
| 680 |
+
# check hidden size
|
| 681 |
+
self.assertListEqual(
|
| 682 |
+
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states],
|
| 683 |
+
[expected_shape] * len(iter_hidden_states),
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
@unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :)
|
| 687 |
+
def test_left_padding_compatibility(self):
|
| 688 |
+
pass
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
@require_torch
|
| 692 |
+
class ReformerLSHAttnModelTest(
|
| 693 |
+
ReformerTesterMixin, ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase
|
| 694 |
+
):
|
| 695 |
+
all_model_classes = (
|
| 696 |
+
(ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering)
|
| 697 |
+
if is_torch_available()
|
| 698 |
+
else ()
|
| 699 |
+
)
|
| 700 |
+
all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else ()
|
| 701 |
+
pipeline_model_mapping = (
|
| 702 |
+
{
|
| 703 |
+
"feature-extraction": ReformerModel,
|
| 704 |
+
"fill-mask": ReformerForMaskedLM,
|
| 705 |
+
"question-answering": ReformerForQuestionAnswering,
|
| 706 |
+
"text-classification": ReformerForSequenceClassification,
|
| 707 |
+
"text-generation": ReformerModelWithLMHead,
|
| 708 |
+
"zero-shot": ReformerForSequenceClassification,
|
| 709 |
+
}
|
| 710 |
+
if is_torch_available()
|
| 711 |
+
else {}
|
| 712 |
+
)
|
| 713 |
+
test_pruning = False
|
| 714 |
+
test_headmasking = False
|
| 715 |
+
test_torchscript = False
|
| 716 |
+
|
| 717 |
+
# TODO: Fix the failed tests
|
| 718 |
+
def is_pipeline_test_to_skip(
|
| 719 |
+
self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
|
| 720 |
+
):
|
| 721 |
+
if (
|
| 722 |
+
pipeline_test_casse_name == "QAPipelineTests"
|
| 723 |
+
and tokenizer_name is not None
|
| 724 |
+
and not tokenizer_name.endswith("Fast")
|
| 725 |
+
):
|
| 726 |
+
# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
|
| 727 |
+
# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
|
| 728 |
+
# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
|
| 729 |
+
return True
|
| 730 |
+
|
| 731 |
+
return False
|
| 732 |
+
|
| 733 |
+
def setUp(self):
|
| 734 |
+
self.model_tester = ReformerModelTester(
|
| 735 |
+
self,
|
| 736 |
+
batch_size=13,
|
| 737 |
+
seq_length=13,
|
| 738 |
+
use_input_mask=True,
|
| 739 |
+
use_labels=True,
|
| 740 |
+
is_training=False,
|
| 741 |
+
is_decoder=True,
|
| 742 |
+
vocab_size=32,
|
| 743 |
+
attention_head_size=16,
|
| 744 |
+
hidden_size=64,
|
| 745 |
+
num_attention_heads=2,
|
| 746 |
+
num_buckets=2,
|
| 747 |
+
num_hashes=4,
|
| 748 |
+
lsh_attn_chunk_length=4,
|
| 749 |
+
lsh_num_chunks_before=1,
|
| 750 |
+
lsh_num_chunks_after=0,
|
| 751 |
+
chunk_size_lm_head=5,
|
| 752 |
+
chunk_size_feed_forward=6,
|
| 753 |
+
feed_forward_size=32,
|
| 754 |
+
hidden_act="relu",
|
| 755 |
+
hidden_dropout_prob=0.1,
|
| 756 |
+
lsh_attention_probs_dropout_prob=0.1,
|
| 757 |
+
max_position_embeddings=512,
|
| 758 |
+
initializer_range=0.02,
|
| 759 |
+
axial_norm_std=1.0,
|
| 760 |
+
layer_norm_eps=1e-12,
|
| 761 |
+
axial_pos_embds=True,
|
| 762 |
+
axial_pos_shape=[4, 8],
|
| 763 |
+
axial_pos_embds_dim=[16, 48],
|
| 764 |
+
# sanotheu
|
| 765 |
+
# attn_layers=[lsh,lsh,lsh,lsh],
|
| 766 |
+
attn_layers=["lsh"],
|
| 767 |
+
pad_token_id=0,
|
| 768 |
+
eos_token_id=2,
|
| 769 |
+
scope=None,
|
| 770 |
+
hash_seed=0,
|
| 771 |
+
num_labels=2,
|
| 772 |
+
)
|
| 773 |
+
self.config_tester = ConfigTester(self, config_class=ReformerConfig, hidden_size=37)
|
| 774 |
+
|
| 775 |
+
def _check_attentions_for_generate(
|
| 776 |
+
self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1
|
| 777 |
+
):
|
| 778 |
+
self.assertIsInstance(attentions, tuple)
|
| 779 |
+
self.assertListEqual(
|
| 780 |
+
[isinstance(iter_attentions, list) for iter_attentions in attentions], [True] * len(attentions)
|
| 781 |
+
)
|
| 782 |
+
self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups)
|
| 783 |
+
|
| 784 |
+
for idx, iter_attentions in enumerate(attentions):
|
| 785 |
+
tgt_len = min_length + idx if not use_cache else 1
|
| 786 |
+
num_chunks = tgt_len // config.lsh_attn_chunk_length + (tgt_len % config.lsh_attn_chunk_length != 0)
|
| 787 |
+
tgt_chunk_len = config.lsh_attn_chunk_length
|
| 788 |
+
src_chunk_len = config.lsh_attn_chunk_length * (
|
| 789 |
+
1 + config.lsh_num_chunks_after + config.lsh_num_chunks_before
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
if use_cache:
|
| 793 |
+
expected_shape = (
|
| 794 |
+
batch_size * num_beam_groups,
|
| 795 |
+
config.num_attention_heads,
|
| 796 |
+
config.num_hashes,
|
| 797 |
+
tgt_len,
|
| 798 |
+
config.num_hashes * (1 + config.lsh_num_chunks_after + config.lsh_num_chunks_before),
|
| 799 |
+
)
|
| 800 |
+
else:
|
| 801 |
+
expected_shape = (
|
| 802 |
+
batch_size * num_beam_groups,
|
| 803 |
+
config.num_attention_heads,
|
| 804 |
+
num_chunks * config.num_hashes,
|
| 805 |
+
tgt_chunk_len,
|
| 806 |
+
src_chunk_len,
|
| 807 |
+
)
|
| 808 |
+
# check attn size
|
| 809 |
+
self.assertListEqual(
|
| 810 |
+
[layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions)
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
def _check_hidden_states_for_generate(
|
| 814 |
+
self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1
|
| 815 |
+
):
|
| 816 |
+
self.assertIsInstance(hidden_states, tuple)
|
| 817 |
+
self.assertListEqual(
|
| 818 |
+
[isinstance(iter_hidden_states, list) for iter_hidden_states in hidden_states],
|
| 819 |
+
[True] * len(hidden_states),
|
| 820 |
+
)
|
| 821 |
+
self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups)
|
| 822 |
+
|
| 823 |
+
for idx, iter_hidden_states in enumerate(hidden_states):
|
| 824 |
+
seq_len = min_length + idx if not use_cache else 1
|
| 825 |
+
seq_len = config.lsh_attn_chunk_length * (
|
| 826 |
+
seq_len // config.lsh_attn_chunk_length + (seq_len % config.lsh_attn_chunk_length != 0)
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
if use_cache:
|
| 830 |
+
seq_len = 1
|
| 831 |
+
|
| 832 |
+
expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size)
|
| 833 |
+
# check hidden size
|
| 834 |
+
self.assertListEqual(
|
| 835 |
+
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states],
|
| 836 |
+
[expected_shape] * len(iter_hidden_states),
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
@unittest.skip("Fails because the sequence length is not a multiple of 4")
|
| 840 |
+
def test_problem_types(self):
|
| 841 |
+
pass
|
| 842 |
+
|
| 843 |
+
@unittest.skip("Fails because the sequence length is not a multiple of 4")
|
| 844 |
+
def test_past_key_values_format(self):
|
| 845 |
+
pass
|
| 846 |
+
|
| 847 |
+
@unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :)
|
| 848 |
+
def test_left_padding_compatibility(self):
|
| 849 |
+
pass
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
@require_torch
|
| 853 |
+
@require_sentencepiece
|
| 854 |
+
@require_tokenizers
|
| 855 |
+
class ReformerIntegrationTests(unittest.TestCase):
|
| 856 |
+
"""
|
| 857 |
+
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`.
|
| 858 |
+
"""
|
| 859 |
+
|
| 860 |
+
def _get_basic_config_and_input(self):
|
| 861 |
+
config = {
|
| 862 |
+
"vocab_size": 320,
|
| 863 |
+
"attention_head_size": 8,
|
| 864 |
+
"hidden_size": 16,
|
| 865 |
+
"num_attention_heads": 2,
|
| 866 |
+
"num_buckets": 2,
|
| 867 |
+
"num_hashes": 4,
|
| 868 |
+
"lsh_attn_chunk_length": 4,
|
| 869 |
+
"local_attn_chunk_length": 4,
|
| 870 |
+
"lsh_num_chunks_before": 1,
|
| 871 |
+
"lsh_num_chunks_after": 0,
|
| 872 |
+
"local_num_chunks_before": 1,
|
| 873 |
+
"local_num_chunks_after": 0,
|
| 874 |
+
"chunk_size_lm_head": 0,
|
| 875 |
+
"chunk_size_feed_forward": 0,
|
| 876 |
+
"feed_forward_size": 32,
|
| 877 |
+
"hidden_act": "gelu",
|
| 878 |
+
"hidden_dropout_prob": 0.0,
|
| 879 |
+
"lsh_attention_probs_dropout_prob": 0.0,
|
| 880 |
+
"local_attention_probs_dropout_prob": 0.0,
|
| 881 |
+
"max_position_embeddings": 32,
|
| 882 |
+
"initializer_range": 0.02,
|
| 883 |
+
"axial_norm_std": 1.0,
|
| 884 |
+
"layer_norm_eps": 1e-12,
|
| 885 |
+
"sinusoidal_pos_embds": False,
|
| 886 |
+
"axial_pos_embds": True,
|
| 887 |
+
"axial_pos_shape": [4, 8],
|
| 888 |
+
"axial_pos_embds_dim": [8, 8],
|
| 889 |
+
"hash_seed": 0,
|
| 890 |
+
"is_decoder": True,
|
| 891 |
+
}
|
| 892 |
+
return config
|
| 893 |
+
|
| 894 |
+
def _get_hidden_states(self):
|
| 895 |
+
return torch.tensor(
|
| 896 |
+
[
|
| 897 |
+
[
|
| 898 |
+
[
|
| 899 |
+
1.90826353e00,
|
| 900 |
+
-1.45999730e00,
|
| 901 |
+
-6.20405462e-01,
|
| 902 |
+
1.52503433e00,
|
| 903 |
+
-3.64464232e-01,
|
| 904 |
+
-8.27359235e-01,
|
| 905 |
+
8.39670803e-01,
|
| 906 |
+
2.44492178e-01,
|
| 907 |
+
4.98332758e-01,
|
| 908 |
+
2.69175139e00,
|
| 909 |
+
-7.08081422e-03,
|
| 910 |
+
1.04915401e00,
|
| 911 |
+
-1.83476661e00,
|
| 912 |
+
7.67220476e-01,
|
| 913 |
+
2.98580543e-01,
|
| 914 |
+
2.84803992e-02,
|
| 915 |
+
],
|
| 916 |
+
[
|
| 917 |
+
-2.66374286e-02,
|
| 918 |
+
4.33497576e-01,
|
| 919 |
+
3.10386309e-01,
|
| 920 |
+
5.46039944e-01,
|
| 921 |
+
-2.47292666e-04,
|
| 922 |
+
-7.52305019e-01,
|
| 923 |
+
2.39162103e-01,
|
| 924 |
+
7.25216186e-01,
|
| 925 |
+
-7.58357372e-01,
|
| 926 |
+
4.20635998e-01,
|
| 927 |
+
-4.04739919e-02,
|
| 928 |
+
1.59924145e-01,
|
| 929 |
+
2.05135748e00,
|
| 930 |
+
-1.15997978e00,
|
| 931 |
+
5.37166397e-01,
|
| 932 |
+
2.62873606e-01,
|
| 933 |
+
],
|
| 934 |
+
[
|
| 935 |
+
1.85247482e-01,
|
| 936 |
+
7.07046037e-01,
|
| 937 |
+
-6.77089715e-01,
|
| 938 |
+
-2.24209655e00,
|
| 939 |
+
-3.75307980e-02,
|
| 940 |
+
-8.59380874e-01,
|
| 941 |
+
-2.81027884e00,
|
| 942 |
+
1.01276376e00,
|
| 943 |
+
-1.69438001e00,
|
| 944 |
+
4.17574660e-01,
|
| 945 |
+
-1.49196962e00,
|
| 946 |
+
-1.76483717e00,
|
| 947 |
+
-1.94566312e-01,
|
| 948 |
+
-1.71183858e00,
|
| 949 |
+
7.72903565e-01,
|
| 950 |
+
-1.11557056e00,
|
| 951 |
+
],
|
| 952 |
+
[
|
| 953 |
+
9.46069193e-01,
|
| 954 |
+
1.53417623e-01,
|
| 955 |
+
-9.58686996e-01,
|
| 956 |
+
1.18126669e-01,
|
| 957 |
+
1.75967724e00,
|
| 958 |
+
1.62194590e00,
|
| 959 |
+
-5.74108159e-01,
|
| 960 |
+
6.79920443e-01,
|
| 961 |
+
5.44028163e-01,
|
| 962 |
+
2.05466114e-01,
|
| 963 |
+
-3.63045868e-01,
|
| 964 |
+
2.41865062e-01,
|
| 965 |
+
3.20348382e-01,
|
| 966 |
+
-9.05611176e-01,
|
| 967 |
+
-1.92690727e-01,
|
| 968 |
+
-1.19917547e00,
|
| 969 |
+
],
|
| 970 |
+
]
|
| 971 |
+
],
|
| 972 |
+
dtype=torch.float32,
|
| 973 |
+
device=torch_device,
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
def _get_attn_mask(self):
|
| 977 |
+
return torch.tensor([[0, 1, 0, 0]], dtype=torch.long, device=torch_device)
|
| 978 |
+
|
| 979 |
+
def _get_input_ids_and_mask(self):
|
| 980 |
+
mask = torch.tensor(
|
| 981 |
+
[
|
| 982 |
+
[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],
|
| 983 |
+
[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],
|
| 984 |
+
],
|
| 985 |
+
dtype=torch.long,
|
| 986 |
+
device=torch_device,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
input_ids = torch.tensor(
|
| 990 |
+
[
|
| 991 |
+
[
|
| 992 |
+
89,
|
| 993 |
+
279,
|
| 994 |
+
286,
|
| 995 |
+
84,
|
| 996 |
+
194,
|
| 997 |
+
316,
|
| 998 |
+
182,
|
| 999 |
+
28,
|
| 1000 |
+
283,
|
| 1001 |
+
37,
|
| 1002 |
+
169,
|
| 1003 |
+
7,
|
| 1004 |
+
253,
|
| 1005 |
+
267,
|
| 1006 |
+
107,
|
| 1007 |
+
250,
|
| 1008 |
+
44,
|
| 1009 |
+
7,
|
| 1010 |
+
102,
|
| 1011 |
+
62,
|
| 1012 |
+
3,
|
| 1013 |
+
243,
|
| 1014 |
+
171,
|
| 1015 |
+
265,
|
| 1016 |
+
302,
|
| 1017 |
+
48,
|
| 1018 |
+
164,
|
| 1019 |
+
264,
|
| 1020 |
+
148,
|
| 1021 |
+
229,
|
| 1022 |
+
280,
|
| 1023 |
+
150,
|
| 1024 |
+
],
|
| 1025 |
+
[
|
| 1026 |
+
9,
|
| 1027 |
+
192,
|
| 1028 |
+
66,
|
| 1029 |
+
112,
|
| 1030 |
+
163,
|
| 1031 |
+
83,
|
| 1032 |
+
135,
|
| 1033 |
+
70,
|
| 1034 |
+
224,
|
| 1035 |
+
96,
|
| 1036 |
+
31,
|
| 1037 |
+
80,
|
| 1038 |
+
196,
|
| 1039 |
+
80,
|
| 1040 |
+
63,
|
| 1041 |
+
22,
|
| 1042 |
+
85,
|
| 1043 |
+
100,
|
| 1044 |
+
47,
|
| 1045 |
+
283,
|
| 1046 |
+
0,
|
| 1047 |
+
163,
|
| 1048 |
+
126,
|
| 1049 |
+
143,
|
| 1050 |
+
195,
|
| 1051 |
+
82,
|
| 1052 |
+
53,
|
| 1053 |
+
82,
|
| 1054 |
+
18,
|
| 1055 |
+
27,
|
| 1056 |
+
182,
|
| 1057 |
+
52,
|
| 1058 |
+
],
|
| 1059 |
+
],
|
| 1060 |
+
dtype=torch.long,
|
| 1061 |
+
device=torch_device,
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
return input_ids, mask
|
| 1065 |
+
|
| 1066 |
+
def test_lsh_layer_forward(self):
|
| 1067 |
+
config = self._get_basic_config_and_input()
|
| 1068 |
+
config["lsh_num_chunks_before"] = 0
|
| 1069 |
+
config["attn_layers"] = ["lsh"]
|
| 1070 |
+
config["is_decoder"] = False
|
| 1071 |
+
hidden_states = self._get_hidden_states()
|
| 1072 |
+
torch.manual_seed(0)
|
| 1073 |
+
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
|
| 1074 |
+
layer.eval()
|
| 1075 |
+
reformer_output = layer(prev_attn_output=hidden_states.clone(), hidden_states=hidden_states)
|
| 1076 |
+
output_slice = reformer_output.hidden_states[0, 0, :5]
|
| 1077 |
+
expected_output_slice = torch.tensor(
|
| 1078 |
+
[1.6879, -1.3083, -0.4708, 1.3555, -0.6292],
|
| 1079 |
+
dtype=torch.float,
|
| 1080 |
+
device=torch_device,
|
| 1081 |
+
)
|
| 1082 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1083 |
+
|
| 1084 |
+
def test_lsh_layer_forward_complex(self):
|
| 1085 |
+
config = self._get_basic_config_and_input()
|
| 1086 |
+
config["lsh_num_chunks_before"] = 0
|
| 1087 |
+
config["attn_layers"] = ["lsh"]
|
| 1088 |
+
config["num_buckets"] = [2, 4]
|
| 1089 |
+
attn_mask = self._get_attn_mask()
|
| 1090 |
+
hidden_states = self._get_hidden_states()
|
| 1091 |
+
torch.manual_seed(0)
|
| 1092 |
+
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
|
| 1093 |
+
layer.eval()
|
| 1094 |
+
reformer_output = layer(
|
| 1095 |
+
prev_attn_output=hidden_states.clone(),
|
| 1096 |
+
hidden_states=hidden_states,
|
| 1097 |
+
attention_mask=attn_mask,
|
| 1098 |
+
)
|
| 1099 |
+
output_slice = reformer_output.hidden_states[0, 0, :5]
|
| 1100 |
+
expected_output_slice = torch.tensor(
|
| 1101 |
+
[1.6439, -1.2306, -0.5108, 1.3006, -0.6537],
|
| 1102 |
+
dtype=torch.float,
|
| 1103 |
+
device=torch_device,
|
| 1104 |
+
)
|
| 1105 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1106 |
+
|
| 1107 |
+
def test_local_layer_forward(self):
|
| 1108 |
+
config = self._get_basic_config_and_input()
|
| 1109 |
+
config["local_num_chunks_before"] = 0
|
| 1110 |
+
config["attn_layers"] = ["local"]
|
| 1111 |
+
config["is_decoder"] = False
|
| 1112 |
+
hidden_states = self._get_hidden_states()
|
| 1113 |
+
torch.manual_seed(0)
|
| 1114 |
+
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
|
| 1115 |
+
layer.eval()
|
| 1116 |
+
reformer_output = layer(prev_attn_output=hidden_states, hidden_states=hidden_states)
|
| 1117 |
+
output_slice = reformer_output.hidden_states[0, 0, :5]
|
| 1118 |
+
expected_output_slice = torch.tensor(
|
| 1119 |
+
[1.4212, -2.0576, -0.9688, 1.4599, -0.1344],
|
| 1120 |
+
dtype=torch.float,
|
| 1121 |
+
device=torch_device,
|
| 1122 |
+
)
|
| 1123 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1124 |
+
|
| 1125 |
+
def test_local_layer_forward_complex(self):
|
| 1126 |
+
config = self._get_basic_config_and_input()
|
| 1127 |
+
config["local_num_chunks_before"] = 0
|
| 1128 |
+
config["attn_layers"] = ["local"]
|
| 1129 |
+
attn_mask = self._get_attn_mask()
|
| 1130 |
+
hidden_states = self._get_hidden_states()
|
| 1131 |
+
torch.manual_seed(0)
|
| 1132 |
+
layer = ReformerLayer(ReformerConfig(**config)).to(torch_device)
|
| 1133 |
+
layer.eval()
|
| 1134 |
+
reformer_output = layer(
|
| 1135 |
+
prev_attn_output=hidden_states,
|
| 1136 |
+
hidden_states=hidden_states,
|
| 1137 |
+
attention_mask=attn_mask,
|
| 1138 |
+
)
|
| 1139 |
+
output_slice = reformer_output.hidden_states[0, 0, :5]
|
| 1140 |
+
expected_output_slice = torch.tensor(
|
| 1141 |
+
[1.4750, -2.0235, -0.9743, 1.4463, -0.1269],
|
| 1142 |
+
dtype=torch.float,
|
| 1143 |
+
device=torch_device,
|
| 1144 |
+
)
|
| 1145 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1146 |
+
|
| 1147 |
+
def test_lsh_model_forward(self):
|
| 1148 |
+
config = self._get_basic_config_and_input()
|
| 1149 |
+
config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"]
|
| 1150 |
+
config["num_buckets"] = [2, 4]
|
| 1151 |
+
torch.manual_seed(0)
|
| 1152 |
+
model = ReformerModel(ReformerConfig(**config)).to(torch_device)
|
| 1153 |
+
model.eval()
|
| 1154 |
+
input_ids, attn_mask = self._get_input_ids_and_mask()
|
| 1155 |
+
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
|
| 1156 |
+
output_slice = hidden_states[0, 0, :5]
|
| 1157 |
+
expected_output_slice = torch.tensor(
|
| 1158 |
+
[-0.9896, -0.9396, -1.0831, -0.0597, 0.2456],
|
| 1159 |
+
dtype=torch.float,
|
| 1160 |
+
device=torch_device,
|
| 1161 |
+
)
|
| 1162 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1163 |
+
|
| 1164 |
+
def test_local_model_forward(self):
|
| 1165 |
+
config = self._get_basic_config_and_input()
|
| 1166 |
+
config["attn_layers"] = ["local", "local", "local", "local"]
|
| 1167 |
+
torch.manual_seed(0)
|
| 1168 |
+
model = ReformerModel(ReformerConfig(**config)).to(torch_device)
|
| 1169 |
+
model.eval()
|
| 1170 |
+
input_ids, attn_mask = self._get_input_ids_and_mask()
|
| 1171 |
+
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
|
| 1172 |
+
output_slice = hidden_states[0, 0, :5]
|
| 1173 |
+
expected_output_slice = torch.tensor(
|
| 1174 |
+
[-1.6791, 0.7171, 0.1594, 0.4063, 1.2584],
|
| 1175 |
+
dtype=torch.float,
|
| 1176 |
+
device=torch_device,
|
| 1177 |
+
)
|
| 1178 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1179 |
+
|
| 1180 |
+
def test_lm_model_forward(self):
|
| 1181 |
+
config = self._get_basic_config_and_input()
|
| 1182 |
+
config["attn_layers"] = ["local", "lsh", "local", "lsh", "local", "lsh"]
|
| 1183 |
+
config["num_buckets"] = [2, 4]
|
| 1184 |
+
config["is_decoder"] = False
|
| 1185 |
+
torch.manual_seed(0)
|
| 1186 |
+
model = ReformerForMaskedLM(ReformerConfig(**config)).to(torch_device)
|
| 1187 |
+
model.eval()
|
| 1188 |
+
input_ids, attn_mask = self._get_input_ids_and_mask()
|
| 1189 |
+
hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0]
|
| 1190 |
+
output_slice = hidden_states[1, -1, :5]
|
| 1191 |
+
expected_output_slice = torch.tensor(
|
| 1192 |
+
[0.1018, -0.2026, 0.2116, 0.0270, -0.1233],
|
| 1193 |
+
dtype=torch.float,
|
| 1194 |
+
device=torch_device,
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
| 1198 |
+
|
| 1199 |
+
def test_local_lm_model_grad(self):
|
| 1200 |
+
config = self._get_basic_config_and_input()
|
| 1201 |
+
config["attn_layers"] = ["local", "local", "local", "local"]
|
| 1202 |
+
config["hidden_dropout_prob"] = 0.0
|
| 1203 |
+
config["local_attention_probs_dropout_prob"] = 0.0
|
| 1204 |
+
torch.manual_seed(0)
|
| 1205 |
+
model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device)
|
| 1206 |
+
model.train()
|
| 1207 |
+
model.zero_grad()
|
| 1208 |
+
input_ids, _ = self._get_input_ids_and_mask()
|
| 1209 |
+
loss = model(input_ids=input_ids, labels=input_ids)[0]
|
| 1210 |
+
|
| 1211 |
+
self.assertTrue(torch.allclose(loss, torch.tensor(5.8019, dtype=torch.float, device=torch_device), atol=1e-3))
|
| 1212 |
+
loss.backward()
|
| 1213 |
+
|
| 1214 |
+
# check last grads to cover all proable errors
|
| 1215 |
+
grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
|
| 1216 |
+
expected_grad_slice_word = torch.tensor(
|
| 1217 |
+
[-0.0005, -0.0001, -0.0002, -0.0006, -0.0006],
|
| 1218 |
+
dtype=torch.float,
|
| 1219 |
+
device=torch_device,
|
| 1220 |
+
)
|
| 1221 |
+
grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
|
| 1222 |
+
expected_grad_slice_pos_fac_1 = torch.tensor(
|
| 1223 |
+
[-0.5235, 0.5704, 0.0922, -0.3140, 0.9928],
|
| 1224 |
+
dtype=torch.float,
|
| 1225 |
+
device=torch_device,
|
| 1226 |
+
)
|
| 1227 |
+
grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
|
| 1228 |
+
expected_grad_slice_pos_fac_2 = torch.tensor(
|
| 1229 |
+
[1.7960, 1.7668, 0.5593, 0.0907, 1.8342],
|
| 1230 |
+
dtype=torch.float,
|
| 1231 |
+
device=torch_device,
|
| 1232 |
+
)
|
| 1233 |
+
self.assertTrue(torch.allclose(grad_slice_word, expected_grad_slice_word, atol=1e-3))
|
| 1234 |
+
self.assertTrue(torch.allclose(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, atol=1e-3))
|
| 1235 |
+
self.assertTrue(torch.allclose(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, atol=1e-3))
|
| 1236 |
+
|
| 1237 |
+
def test_lsh_lm_model_grad(self):
|
| 1238 |
+
config = self._get_basic_config_and_input()
|
| 1239 |
+
config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"]
|
| 1240 |
+
config["hidden_dropout_prob"] = 0.0
|
| 1241 |
+
config["lsh_attention_probs_dropout_prob"] = 0.0
|
| 1242 |
+
config["num_buckets"] = [2, 4]
|
| 1243 |
+
config["num_hashes"] = 6
|
| 1244 |
+
torch.manual_seed(0)
|
| 1245 |
+
model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device)
|
| 1246 |
+
model.train()
|
| 1247 |
+
model.zero_grad()
|
| 1248 |
+
input_ids, _ = self._get_input_ids_and_mask()
|
| 1249 |
+
loss = model(input_ids=input_ids, labels=input_ids)[0]
|
| 1250 |
+
|
| 1251 |
+
self.assertTrue(torch.allclose(loss, torch.tensor(5.7854, dtype=torch.float, device=torch_device), atol=1e-3))
|
| 1252 |
+
loss.backward()
|
| 1253 |
+
# check last grads to cover all proable errors
|
| 1254 |
+
grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5]
|
| 1255 |
+
expected_grad_slice_word = torch.tensor(
|
| 1256 |
+
[0.0004, 0.0003, 0.0006, -0.0004, 0.0002],
|
| 1257 |
+
dtype=torch.float,
|
| 1258 |
+
device=torch_device,
|
| 1259 |
+
)
|
| 1260 |
+
grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:]
|
| 1261 |
+
expected_grad_slice_pos_fac_1 = torch.tensor(
|
| 1262 |
+
[-0.3792, 0.5593, -1.6993, 0.2033, 0.4131],
|
| 1263 |
+
dtype=torch.float,
|
| 1264 |
+
device=torch_device,
|
| 1265 |
+
)
|
| 1266 |
+
grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5]
|
| 1267 |
+
expected_grad_slice_pos_fac_2 = torch.tensor(
|
| 1268 |
+
[-1.4212, -0.3201, -1.1944, 0.1258, 0.2856],
|
| 1269 |
+
dtype=torch.float,
|
| 1270 |
+
device=torch_device,
|
| 1271 |
+
)
|
| 1272 |
+
self.assertTrue(torch.allclose(grad_slice_word, expected_grad_slice_word, atol=1e-3))
|
| 1273 |
+
self.assertTrue(torch.allclose(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, atol=1e-3))
|
| 1274 |
+
self.assertTrue(torch.allclose(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, atol=1e-3))
|
| 1275 |
+
|
| 1276 |
+
@slow
|
| 1277 |
+
def test_pretrained_generate_crime_and_punish(self):
|
| 1278 |
+
model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device)
|
| 1279 |
+
tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
|
| 1280 |
+
model.eval()
|
| 1281 |
+
|
| 1282 |
+
input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device)
|
| 1283 |
+
output_ids = model.generate(
|
| 1284 |
+
input_ids, max_length=50, num_beams=4, early_stopping=True, do_sample=False, num_hashes=8
|
| 1285 |
+
)
|
| 1286 |
+
output = tokenizer.decode(output_ids[0])
|
| 1287 |
+
|
| 1288 |
+
self.assertEqual(
|
| 1289 |
+
output,
|
| 1290 |
+
"A few months later state expression in his ideas, at the first entrance. He was positively for an inst",
|
| 1291 |
+
)
|
| 1292 |
+
|
| 1293 |
+
@slow
|
| 1294 |
+
def test_pretrained_generate_use_cache_equality(self):
|
| 1295 |
+
model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device)
|
| 1296 |
+
tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
|
| 1297 |
+
model.eval()
|
| 1298 |
+
input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device)
|
| 1299 |
+
output_ids_with_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=False)
|
| 1300 |
+
output_ids_without_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=True)
|
| 1301 |
+
|
| 1302 |
+
output_with_cache = tokenizer.decode(output_ids_with_cache[0])
|
| 1303 |
+
output_without_cache = tokenizer.decode(output_ids_without_cache[0])
|
| 1304 |
+
|
| 1305 |
+
self.assertEqual(output_with_cache, output_without_cache)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_tokenization_reformer.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
|
| 18 |
+
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
|
| 19 |
+
from transformers.utils import cached_property
|
| 20 |
+
|
| 21 |
+
from ...test_tokenization_common import TokenizerTesterMixin
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@require_sentencepiece
|
| 28 |
+
@require_tokenizers
|
| 29 |
+
class ReformerTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 30 |
+
tokenizer_class = ReformerTokenizer
|
| 31 |
+
rust_tokenizer_class = ReformerTokenizerFast
|
| 32 |
+
test_rust_tokenizer = True
|
| 33 |
+
test_seq2seq = False
|
| 34 |
+
test_sentencepiece = True
|
| 35 |
+
|
| 36 |
+
def setUp(self):
|
| 37 |
+
super().setUp()
|
| 38 |
+
|
| 39 |
+
tokenizer = ReformerTokenizer(SAMPLE_VOCAB, keep_accents=True)
|
| 40 |
+
tokenizer.save_pretrained(self.tmpdirname)
|
| 41 |
+
|
| 42 |
+
def test_convert_token_and_id(self):
|
| 43 |
+
"""Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
|
| 44 |
+
token = "<s>"
|
| 45 |
+
token_id = 1
|
| 46 |
+
|
| 47 |
+
self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id)
|
| 48 |
+
self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
|
| 49 |
+
|
| 50 |
+
def test_get_vocab(self):
|
| 51 |
+
vocab_keys = list(self.get_tokenizer().get_vocab().keys())
|
| 52 |
+
|
| 53 |
+
self.assertEqual(vocab_keys[0], "<unk>")
|
| 54 |
+
self.assertEqual(vocab_keys[1], "<s>")
|
| 55 |
+
self.assertEqual(vocab_keys[-1], "j")
|
| 56 |
+
self.assertEqual(len(vocab_keys), 1_000)
|
| 57 |
+
|
| 58 |
+
def test_vocab_size(self):
|
| 59 |
+
self.assertEqual(self.get_tokenizer().vocab_size, 1_000)
|
| 60 |
+
|
| 61 |
+
def test_rust_and_python_full_tokenizers(self):
|
| 62 |
+
if not self.test_rust_tokenizer:
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
tokenizer = self.get_tokenizer()
|
| 66 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 67 |
+
|
| 68 |
+
sequence = "I was born in 92000, and this is falsé."
|
| 69 |
+
|
| 70 |
+
tokens = tokenizer.tokenize(sequence)
|
| 71 |
+
rust_tokens = rust_tokenizer.tokenize(sequence)
|
| 72 |
+
self.assertListEqual(tokens, rust_tokens)
|
| 73 |
+
|
| 74 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 75 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 76 |
+
self.assertListEqual(ids, rust_ids)
|
| 77 |
+
|
| 78 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 79 |
+
ids = tokenizer.encode(sequence)
|
| 80 |
+
rust_ids = rust_tokenizer.encode(sequence)
|
| 81 |
+
self.assertListEqual(ids, rust_ids)
|
| 82 |
+
|
| 83 |
+
def test_padding(self, max_length=15):
|
| 84 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 85 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 86 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 87 |
+
|
| 88 |
+
# Simple input
|
| 89 |
+
s = "This is a simple input"
|
| 90 |
+
s2 = ["This is a simple input 1", "This is a simple input 2"]
|
| 91 |
+
p = ("This is a simple input", "This is a pair")
|
| 92 |
+
p2 = [
|
| 93 |
+
("This is a simple input 1", "This is a simple input 2"),
|
| 94 |
+
("This is a simple pair 1", "This is a simple pair 2"),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
# Simple input tests
|
| 98 |
+
self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
|
| 99 |
+
|
| 100 |
+
# Simple input
|
| 101 |
+
self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
|
| 102 |
+
|
| 103 |
+
# Simple input
|
| 104 |
+
self.assertRaises(
|
| 105 |
+
ValueError,
|
| 106 |
+
tokenizer_r.batch_encode_plus,
|
| 107 |
+
s2,
|
| 108 |
+
max_length=max_length,
|
| 109 |
+
padding="max_length",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Pair input
|
| 113 |
+
self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
|
| 114 |
+
|
| 115 |
+
# Pair input
|
| 116 |
+
self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
|
| 117 |
+
|
| 118 |
+
# Pair input
|
| 119 |
+
self.assertRaises(
|
| 120 |
+
ValueError,
|
| 121 |
+
tokenizer_r.batch_encode_plus,
|
| 122 |
+
p2,
|
| 123 |
+
max_length=max_length,
|
| 124 |
+
padding="max_length",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# tokenizer has no padding token
|
| 128 |
+
def test_padding_different_model_input_name(self):
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
def test_full_tokenizer(self):
|
| 132 |
+
tokenizer = ReformerTokenizer(SAMPLE_VOCAB, keep_accents=True)
|
| 133 |
+
|
| 134 |
+
tokens = tokenizer.tokenize("This is a test")
|
| 135 |
+
self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
|
| 136 |
+
|
| 137 |
+
self.assertListEqual(
|
| 138 |
+
tokenizer.convert_tokens_to_ids(tokens),
|
| 139 |
+
[285, 46, 10, 170, 382],
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
|
| 143 |
+
self.assertListEqual(
|
| 144 |
+
tokens,
|
| 145 |
+
[
|
| 146 |
+
SPIECE_UNDERLINE + "I",
|
| 147 |
+
SPIECE_UNDERLINE + "was",
|
| 148 |
+
SPIECE_UNDERLINE + "b",
|
| 149 |
+
"or",
|
| 150 |
+
"n",
|
| 151 |
+
SPIECE_UNDERLINE + "in",
|
| 152 |
+
SPIECE_UNDERLINE + "",
|
| 153 |
+
"9",
|
| 154 |
+
"2",
|
| 155 |
+
"0",
|
| 156 |
+
"0",
|
| 157 |
+
"0",
|
| 158 |
+
",",
|
| 159 |
+
SPIECE_UNDERLINE + "and",
|
| 160 |
+
SPIECE_UNDERLINE + "this",
|
| 161 |
+
SPIECE_UNDERLINE + "is",
|
| 162 |
+
SPIECE_UNDERLINE + "f",
|
| 163 |
+
"al",
|
| 164 |
+
"s",
|
| 165 |
+
"é",
|
| 166 |
+
".",
|
| 167 |
+
],
|
| 168 |
+
)
|
| 169 |
+
ids = tokenizer.convert_tokens_to_ids(tokens)
|
| 170 |
+
self.assertListEqual(
|
| 171 |
+
ids,
|
| 172 |
+
[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4],
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
back_tokens = tokenizer.convert_ids_to_tokens(ids)
|
| 176 |
+
self.assertListEqual(
|
| 177 |
+
back_tokens,
|
| 178 |
+
[
|
| 179 |
+
SPIECE_UNDERLINE + "I",
|
| 180 |
+
SPIECE_UNDERLINE + "was",
|
| 181 |
+
SPIECE_UNDERLINE + "b",
|
| 182 |
+
"or",
|
| 183 |
+
"n",
|
| 184 |
+
SPIECE_UNDERLINE + "in",
|
| 185 |
+
SPIECE_UNDERLINE + "",
|
| 186 |
+
"<unk>",
|
| 187 |
+
"2",
|
| 188 |
+
"0",
|
| 189 |
+
"0",
|
| 190 |
+
"0",
|
| 191 |
+
",",
|
| 192 |
+
SPIECE_UNDERLINE + "and",
|
| 193 |
+
SPIECE_UNDERLINE + "this",
|
| 194 |
+
SPIECE_UNDERLINE + "is",
|
| 195 |
+
SPIECE_UNDERLINE + "f",
|
| 196 |
+
"al",
|
| 197 |
+
"s",
|
| 198 |
+
"<unk>",
|
| 199 |
+
".",
|
| 200 |
+
],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
@cached_property
|
| 204 |
+
def big_tokenizer(self):
|
| 205 |
+
return ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
|
| 206 |
+
|
| 207 |
+
@slow
|
| 208 |
+
def test_tokenization_base_easy_symbols(self):
|
| 209 |
+
symbols = "Hello World!"
|
| 210 |
+
original_tokenizer_encodings = [126, 32, 262, 152, 38, 72, 287]
|
| 211 |
+
|
| 212 |
+
self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))
|
| 213 |
+
|
| 214 |
+
@slow
|
| 215 |
+
def test_tokenization_base_hard_symbols(self):
|
| 216 |
+
symbols = (
|
| 217 |
+
'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
|
| 218 |
+
" add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"
|
| 219 |
+
)
|
| 220 |
+
original_tokenizer_encodings = [
|
| 221 |
+
108,
|
| 222 |
+
265,
|
| 223 |
+
24,
|
| 224 |
+
111,
|
| 225 |
+
4,
|
| 226 |
+
258,
|
| 227 |
+
156,
|
| 228 |
+
35,
|
| 229 |
+
28,
|
| 230 |
+
275,
|
| 231 |
+
3,
|
| 232 |
+
259,
|
| 233 |
+
297,
|
| 234 |
+
260,
|
| 235 |
+
84,
|
| 236 |
+
4,
|
| 237 |
+
35,
|
| 238 |
+
110,
|
| 239 |
+
44,
|
| 240 |
+
8,
|
| 241 |
+
259,
|
| 242 |
+
91,
|
| 243 |
+
268,
|
| 244 |
+
21,
|
| 245 |
+
11,
|
| 246 |
+
209,
|
| 247 |
+
274,
|
| 248 |
+
109,
|
| 249 |
+
266,
|
| 250 |
+
277,
|
| 251 |
+
117,
|
| 252 |
+
86,
|
| 253 |
+
93,
|
| 254 |
+
315,
|
| 255 |
+
258,
|
| 256 |
+
278,
|
| 257 |
+
258,
|
| 258 |
+
277,
|
| 259 |
+
258,
|
| 260 |
+
0,
|
| 261 |
+
258,
|
| 262 |
+
288,
|
| 263 |
+
258,
|
| 264 |
+
319,
|
| 265 |
+
258,
|
| 266 |
+
0,
|
| 267 |
+
258,
|
| 268 |
+
0,
|
| 269 |
+
258,
|
| 270 |
+
0,
|
| 271 |
+
258,
|
| 272 |
+
0,
|
| 273 |
+
258,
|
| 274 |
+
287,
|
| 275 |
+
258,
|
| 276 |
+
315,
|
| 277 |
+
258,
|
| 278 |
+
289,
|
| 279 |
+
258,
|
| 280 |
+
278,
|
| 281 |
+
99,
|
| 282 |
+
269,
|
| 283 |
+
266,
|
| 284 |
+
262,
|
| 285 |
+
8,
|
| 286 |
+
259,
|
| 287 |
+
241,
|
| 288 |
+
4,
|
| 289 |
+
217,
|
| 290 |
+
230,
|
| 291 |
+
268,
|
| 292 |
+
266,
|
| 293 |
+
55,
|
| 294 |
+
168,
|
| 295 |
+
106,
|
| 296 |
+
75,
|
| 297 |
+
193,
|
| 298 |
+
266,
|
| 299 |
+
223,
|
| 300 |
+
27,
|
| 301 |
+
49,
|
| 302 |
+
26,
|
| 303 |
+
282,
|
| 304 |
+
25,
|
| 305 |
+
264,
|
| 306 |
+
299,
|
| 307 |
+
19,
|
| 308 |
+
26,
|
| 309 |
+
0,
|
| 310 |
+
258,
|
| 311 |
+
277,
|
| 312 |
+
117,
|
| 313 |
+
86,
|
| 314 |
+
93,
|
| 315 |
+
176,
|
| 316 |
+
183,
|
| 317 |
+
270,
|
| 318 |
+
11,
|
| 319 |
+
262,
|
| 320 |
+
42,
|
| 321 |
+
61,
|
| 322 |
+
265,
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))
|
| 326 |
+
|
| 327 |
+
@require_torch
|
| 328 |
+
@slow
|
| 329 |
+
def test_torch_encode_plus_sent_to_model(self):
|
| 330 |
+
import torch
|
| 331 |
+
|
| 332 |
+
from transformers import ReformerConfig, ReformerModel
|
| 333 |
+
|
| 334 |
+
# Build sequence
|
| 335 |
+
first_ten_tokens = list(self.big_tokenizer.get_vocab().keys())[:10]
|
| 336 |
+
sequence = " ".join(first_ten_tokens)
|
| 337 |
+
encoded_sequence = self.big_tokenizer.encode_plus(sequence, return_tensors="pt")
|
| 338 |
+
batch_encoded_sequence = self.big_tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt")
|
| 339 |
+
|
| 340 |
+
config = ReformerConfig()
|
| 341 |
+
# The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
|
| 342 |
+
config.axial_pos_shape = encoded_sequence["input_ids"].shape
|
| 343 |
+
model = ReformerModel(config)
|
| 344 |
+
|
| 345 |
+
# Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
|
| 346 |
+
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
|
| 347 |
+
|
| 348 |
+
with torch.no_grad():
|
| 349 |
+
model(**encoded_sequence)
|
| 350 |
+
model(**batch_encoded_sequence)
|
| 351 |
+
|
| 352 |
+
@slow
|
| 353 |
+
def test_tokenizer_integration(self):
|
| 354 |
+
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
|
| 355 |
+
|
| 356 |
+
# This tokenizer does not know some characters like ")".
|
| 357 |
+
# That is the reason why we use very simple texts here.
|
| 358 |
+
# Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
|
| 359 |
+
sequences = [
|
| 360 |
+
"This is a very simple sentence.",
|
| 361 |
+
"The quick brown fox jumps over the lazy dog.",
|
| 362 |
+
]
|
| 363 |
+
|
| 364 |
+
self.tokenizer_integration_test_util(
|
| 365 |
+
expected_encoding=expected_encoding,
|
| 366 |
+
model_name="google/reformer-crime-and-punishment",
|
| 367 |
+
revision="0e6c3decb8211d49bf881013425dc8b0448b3f5a",
|
| 368 |
+
padding=False,
|
| 369 |
+
sequences=sequences,
|
| 370 |
+
)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_flax_regnet.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import RegNetConfig, is_flax_available
|
| 20 |
+
from transformers.testing_utils import require_flax, slow
|
| 21 |
+
from transformers.utils import cached_property, is_vision_available
|
| 22 |
+
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_flax_available():
|
| 28 |
+
import jax
|
| 29 |
+
import jax.numpy as jnp
|
| 30 |
+
|
| 31 |
+
from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel
|
| 32 |
+
|
| 33 |
+
if is_vision_available():
|
| 34 |
+
from PIL import Image
|
| 35 |
+
|
| 36 |
+
from transformers import AutoImageProcessor
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class FlaxRegNetModelTester(unittest.TestCase):
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
parent,
|
| 43 |
+
batch_size=3,
|
| 44 |
+
image_size=32,
|
| 45 |
+
num_channels=3,
|
| 46 |
+
embeddings_size=10,
|
| 47 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 48 |
+
depths=[1, 1, 2, 1],
|
| 49 |
+
is_training=True,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
hidden_act="relu",
|
| 52 |
+
num_labels=3,
|
| 53 |
+
scope=None,
|
| 54 |
+
):
|
| 55 |
+
self.parent = parent
|
| 56 |
+
self.batch_size = batch_size
|
| 57 |
+
self.image_size = image_size
|
| 58 |
+
self.num_channels = num_channels
|
| 59 |
+
self.embeddings_size = embeddings_size
|
| 60 |
+
self.hidden_sizes = hidden_sizes
|
| 61 |
+
self.depths = depths
|
| 62 |
+
self.is_training = is_training
|
| 63 |
+
self.use_labels = use_labels
|
| 64 |
+
self.hidden_act = hidden_act
|
| 65 |
+
self.num_labels = num_labels
|
| 66 |
+
self.scope = scope
|
| 67 |
+
self.num_stages = len(hidden_sizes)
|
| 68 |
+
|
| 69 |
+
def prepare_config_and_inputs(self):
|
| 70 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 71 |
+
|
| 72 |
+
config = self.get_config()
|
| 73 |
+
|
| 74 |
+
return config, pixel_values
|
| 75 |
+
|
| 76 |
+
def get_config(self):
|
| 77 |
+
return RegNetConfig(
|
| 78 |
+
num_channels=self.num_channels,
|
| 79 |
+
embeddings_size=self.embeddings_size,
|
| 80 |
+
hidden_sizes=self.hidden_sizes,
|
| 81 |
+
depths=self.depths,
|
| 82 |
+
hidden_act=self.hidden_act,
|
| 83 |
+
num_labels=self.num_labels,
|
| 84 |
+
image_size=self.image_size,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def create_and_check_model(self, config, pixel_values):
|
| 88 |
+
model = FlaxRegNetModel(config=config)
|
| 89 |
+
result = model(pixel_values)
|
| 90 |
+
|
| 91 |
+
# Output shape (b, c, h, w)
|
| 92 |
+
self.parent.assertEqual(
|
| 93 |
+
result.last_hidden_state.shape,
|
| 94 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def create_and_check_for_image_classification(self, config, pixel_values):
|
| 98 |
+
config.num_labels = self.num_labels
|
| 99 |
+
model = FlaxRegNetForImageClassification(config=config)
|
| 100 |
+
result = model(pixel_values)
|
| 101 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 102 |
+
|
| 103 |
+
def prepare_config_and_inputs_for_common(self):
|
| 104 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 105 |
+
config, pixel_values = config_and_inputs
|
| 106 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 107 |
+
return config, inputs_dict
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@require_flax
|
| 111 |
+
class FlaxResNetModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 112 |
+
all_model_classes = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()
|
| 113 |
+
|
| 114 |
+
is_encoder_decoder = False
|
| 115 |
+
test_head_masking = False
|
| 116 |
+
has_attentions = False
|
| 117 |
+
|
| 118 |
+
def setUp(self) -> None:
|
| 119 |
+
self.model_tester = FlaxRegNetModelTester(self)
|
| 120 |
+
self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False)
|
| 121 |
+
|
| 122 |
+
def test_config(self):
|
| 123 |
+
self.create_and_test_config_common_properties()
|
| 124 |
+
self.config_tester.create_and_test_config_to_json_string()
|
| 125 |
+
self.config_tester.create_and_test_config_to_json_file()
|
| 126 |
+
self.config_tester.create_and_test_config_from_and_save_pretrained()
|
| 127 |
+
self.config_tester.create_and_test_config_with_num_labels()
|
| 128 |
+
self.config_tester.check_config_can_be_init_without_params()
|
| 129 |
+
self.config_tester.check_config_arguments_init()
|
| 130 |
+
|
| 131 |
+
def create_and_test_config_common_properties(self):
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
def test_model(self):
|
| 135 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 136 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 137 |
+
|
| 138 |
+
def test_for_image_classification(self):
|
| 139 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 140 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 141 |
+
|
| 142 |
+
@unittest.skip(reason="RegNet does not use inputs_embeds")
|
| 143 |
+
def test_inputs_embeds(self):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
@unittest.skip(reason="RegNet does not support input and output embeddings")
|
| 147 |
+
def test_model_common_attributes(self):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
def test_forward_signature(self):
|
| 151 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 152 |
+
|
| 153 |
+
for model_class in self.all_model_classes:
|
| 154 |
+
model = model_class(config)
|
| 155 |
+
signature = inspect.signature(model.__call__)
|
| 156 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 157 |
+
arg_names = [*signature.parameters.keys()]
|
| 158 |
+
|
| 159 |
+
expected_arg_names = ["pixel_values"]
|
| 160 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 161 |
+
|
| 162 |
+
def test_hidden_states_output(self):
|
| 163 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 164 |
+
model = model_class(config)
|
| 165 |
+
|
| 166 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 167 |
+
|
| 168 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 169 |
+
|
| 170 |
+
expected_num_stages = self.model_tester.num_stages
|
| 171 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 172 |
+
|
| 173 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 174 |
+
|
| 175 |
+
for model_class in self.all_model_classes:
|
| 176 |
+
inputs_dict["output_hidden_states"] = True
|
| 177 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 178 |
+
|
| 179 |
+
# check that output_hidden_states also work using config
|
| 180 |
+
del inputs_dict["output_hidden_states"]
|
| 181 |
+
config.output_hidden_states = True
|
| 182 |
+
|
| 183 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 184 |
+
|
| 185 |
+
def test_jit_compilation(self):
|
| 186 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 187 |
+
|
| 188 |
+
for model_class in self.all_model_classes:
|
| 189 |
+
with self.subTest(model_class.__name__):
|
| 190 |
+
prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
|
| 191 |
+
model = model_class(config)
|
| 192 |
+
|
| 193 |
+
@jax.jit
|
| 194 |
+
def model_jitted(pixel_values, **kwargs):
|
| 195 |
+
return model(pixel_values=pixel_values, **kwargs)
|
| 196 |
+
|
| 197 |
+
with self.subTest("JIT Enabled"):
|
| 198 |
+
jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 199 |
+
|
| 200 |
+
with self.subTest("JIT Disabled"):
|
| 201 |
+
with jax.disable_jit():
|
| 202 |
+
outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 203 |
+
|
| 204 |
+
self.assertEqual(len(outputs), len(jitted_outputs))
|
| 205 |
+
for jitted_output, output in zip(jitted_outputs, outputs):
|
| 206 |
+
self.assertEqual(jitted_output.shape, output.shape)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# We will verify our results on an image of cute cats
|
| 210 |
+
def prepare_img():
|
| 211 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 212 |
+
return image
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@require_flax
|
| 216 |
+
class FlaxRegNetModelIntegrationTest(unittest.TestCase):
|
| 217 |
+
@cached_property
|
| 218 |
+
def default_image_processor(self):
|
| 219 |
+
return AutoImageProcessor.from_pretrained("facebook/regnet-y-040") if is_vision_available() else None
|
| 220 |
+
|
| 221 |
+
@slow
|
| 222 |
+
def test_inference_image_classification_head(self):
|
| 223 |
+
model = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040")
|
| 224 |
+
|
| 225 |
+
image_processor = self.default_image_processor
|
| 226 |
+
image = prepare_img()
|
| 227 |
+
inputs = image_processor(images=image, return_tensors="np")
|
| 228 |
+
|
| 229 |
+
outputs = model(**inputs)
|
| 230 |
+
|
| 231 |
+
# verify the logits
|
| 232 |
+
expected_shape = (1, 1000)
|
| 233 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 234 |
+
|
| 235 |
+
expected_slice = jnp.array([-0.4180, -1.5051, -3.4836])
|
| 236 |
+
|
| 237 |
+
self.assertTrue(jnp.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_regnet.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch RegNet model. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import RegNetConfig
|
| 21 |
+
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
|
| 22 |
+
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
from torch import nn
|
| 32 |
+
|
| 33 |
+
from transformers import RegNetForImageClassification, RegNetModel
|
| 34 |
+
from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if is_vision_available():
|
| 38 |
+
from PIL import Image
|
| 39 |
+
|
| 40 |
+
from transformers import AutoImageProcessor
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class RegNetModelTester:
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
parent,
|
| 47 |
+
batch_size=3,
|
| 48 |
+
image_size=32,
|
| 49 |
+
num_channels=3,
|
| 50 |
+
embeddings_size=10,
|
| 51 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 52 |
+
depths=[1, 1, 2, 1],
|
| 53 |
+
is_training=True,
|
| 54 |
+
use_labels=True,
|
| 55 |
+
hidden_act="relu",
|
| 56 |
+
num_labels=3,
|
| 57 |
+
scope=None,
|
| 58 |
+
):
|
| 59 |
+
self.parent = parent
|
| 60 |
+
self.batch_size = batch_size
|
| 61 |
+
self.image_size = image_size
|
| 62 |
+
self.num_channels = num_channels
|
| 63 |
+
self.embeddings_size = embeddings_size
|
| 64 |
+
self.hidden_sizes = hidden_sizes
|
| 65 |
+
self.depths = depths
|
| 66 |
+
self.is_training = is_training
|
| 67 |
+
self.use_labels = use_labels
|
| 68 |
+
self.hidden_act = hidden_act
|
| 69 |
+
self.num_labels = num_labels
|
| 70 |
+
self.scope = scope
|
| 71 |
+
self.num_stages = len(hidden_sizes)
|
| 72 |
+
|
| 73 |
+
def prepare_config_and_inputs(self):
|
| 74 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 75 |
+
|
| 76 |
+
labels = None
|
| 77 |
+
if self.use_labels:
|
| 78 |
+
labels = ids_tensor([self.batch_size], self.num_labels)
|
| 79 |
+
|
| 80 |
+
config = self.get_config()
|
| 81 |
+
|
| 82 |
+
return config, pixel_values, labels
|
| 83 |
+
|
| 84 |
+
def get_config(self):
|
| 85 |
+
return RegNetConfig(
|
| 86 |
+
num_channels=self.num_channels,
|
| 87 |
+
embeddings_size=self.embeddings_size,
|
| 88 |
+
hidden_sizes=self.hidden_sizes,
|
| 89 |
+
depths=self.depths,
|
| 90 |
+
hidden_act=self.hidden_act,
|
| 91 |
+
num_labels=self.num_labels,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 95 |
+
model = RegNetModel(config=config)
|
| 96 |
+
model.to(torch_device)
|
| 97 |
+
model.eval()
|
| 98 |
+
result = model(pixel_values)
|
| 99 |
+
# expected last hidden states: B, C, H // 32, W // 32
|
| 100 |
+
self.parent.assertEqual(
|
| 101 |
+
result.last_hidden_state.shape,
|
| 102 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 106 |
+
config.num_labels = self.num_labels
|
| 107 |
+
model = RegNetForImageClassification(config)
|
| 108 |
+
model.to(torch_device)
|
| 109 |
+
model.eval()
|
| 110 |
+
result = model(pixel_values, labels=labels)
|
| 111 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 112 |
+
|
| 113 |
+
def prepare_config_and_inputs_for_common(self):
|
| 114 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 115 |
+
config, pixel_values, labels = config_and_inputs
|
| 116 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 117 |
+
return config, inputs_dict
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@require_torch
|
| 121 |
+
class RegNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 122 |
+
"""
|
| 123 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as RegNet does not use input_ids, inputs_embeds,
|
| 124 |
+
attention_mask and seq_length.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
all_model_classes = (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
|
| 128 |
+
pipeline_model_mapping = (
|
| 129 |
+
{"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
|
| 130 |
+
if is_torch_available()
|
| 131 |
+
else {}
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
test_pruning = False
|
| 135 |
+
test_resize_embeddings = False
|
| 136 |
+
test_head_masking = False
|
| 137 |
+
has_attentions = False
|
| 138 |
+
|
| 139 |
+
def setUp(self):
|
| 140 |
+
self.model_tester = RegNetModelTester(self)
|
| 141 |
+
self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False)
|
| 142 |
+
|
| 143 |
+
def test_config(self):
|
| 144 |
+
self.create_and_test_config_common_properties()
|
| 145 |
+
self.config_tester.create_and_test_config_to_json_string()
|
| 146 |
+
self.config_tester.create_and_test_config_to_json_file()
|
| 147 |
+
self.config_tester.create_and_test_config_from_and_save_pretrained()
|
| 148 |
+
self.config_tester.create_and_test_config_with_num_labels()
|
| 149 |
+
self.config_tester.check_config_can_be_init_without_params()
|
| 150 |
+
self.config_tester.check_config_arguments_init()
|
| 151 |
+
|
| 152 |
+
def create_and_test_config_common_properties(self):
|
| 153 |
+
return
|
| 154 |
+
|
| 155 |
+
@unittest.skip(reason="RegNet does not use inputs_embeds")
|
| 156 |
+
def test_inputs_embeds(self):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
@unittest.skip(reason="RegNet does not support input and output embeddings")
|
| 160 |
+
def test_model_common_attributes(self):
|
| 161 |
+
pass
|
| 162 |
+
|
| 163 |
+
def test_model(self):
|
| 164 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 165 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 166 |
+
|
| 167 |
+
def test_initialization(self):
|
| 168 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 169 |
+
|
| 170 |
+
for model_class in self.all_model_classes:
|
| 171 |
+
model = model_class(config=config)
|
| 172 |
+
for name, module in model.named_modules():
|
| 173 |
+
if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 174 |
+
self.assertTrue(
|
| 175 |
+
torch.all(module.weight == 1),
|
| 176 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 177 |
+
)
|
| 178 |
+
self.assertTrue(
|
| 179 |
+
torch.all(module.bias == 0),
|
| 180 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
def test_hidden_states_output(self):
|
| 184 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 185 |
+
model = model_class(config)
|
| 186 |
+
model.to(torch_device)
|
| 187 |
+
model.eval()
|
| 188 |
+
|
| 189 |
+
with torch.no_grad():
|
| 190 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 191 |
+
|
| 192 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 193 |
+
|
| 194 |
+
expected_num_stages = self.model_tester.num_stages
|
| 195 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 196 |
+
|
| 197 |
+
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
|
| 198 |
+
self.assertListEqual(
|
| 199 |
+
list(hidden_states[0].shape[-2:]),
|
| 200 |
+
[self.model_tester.image_size // 2, self.model_tester.image_size // 2],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 204 |
+
layers_type = ["basic", "bottleneck"]
|
| 205 |
+
for model_class in self.all_model_classes:
|
| 206 |
+
for layer_type in layers_type:
|
| 207 |
+
config.layer_type = layer_type
|
| 208 |
+
inputs_dict["output_hidden_states"] = True
|
| 209 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 210 |
+
|
| 211 |
+
# check that output_hidden_states also work using config
|
| 212 |
+
del inputs_dict["output_hidden_states"]
|
| 213 |
+
config.output_hidden_states = True
|
| 214 |
+
|
| 215 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 216 |
+
|
| 217 |
+
def test_for_image_classification(self):
|
| 218 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 219 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 220 |
+
|
| 221 |
+
@slow
|
| 222 |
+
def test_model_from_pretrained(self):
|
| 223 |
+
for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 224 |
+
model = RegNetModel.from_pretrained(model_name)
|
| 225 |
+
self.assertIsNotNone(model)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# We will verify our results on an image of cute cats
|
| 229 |
+
def prepare_img():
|
| 230 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 231 |
+
return image
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@require_torch
|
| 235 |
+
@require_vision
|
| 236 |
+
class RegNetModelIntegrationTest(unittest.TestCase):
|
| 237 |
+
@cached_property
|
| 238 |
+
def default_image_processor(self):
|
| 239 |
+
return (
|
| 240 |
+
AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 241 |
+
if is_vision_available()
|
| 242 |
+
else None
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
@slow
|
| 246 |
+
def test_inference_image_classification_head(self):
|
| 247 |
+
model = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(torch_device)
|
| 248 |
+
|
| 249 |
+
image_processor = self.default_image_processor
|
| 250 |
+
image = prepare_img()
|
| 251 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 252 |
+
|
| 253 |
+
# forward pass
|
| 254 |
+
with torch.no_grad():
|
| 255 |
+
outputs = model(**inputs)
|
| 256 |
+
|
| 257 |
+
# verify the logits
|
| 258 |
+
expected_shape = torch.Size((1, 1000))
|
| 259 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 260 |
+
|
| 261 |
+
expected_slice = torch.tensor([-0.4180, -1.5051, -3.4836]).to(torch_device)
|
| 262 |
+
|
| 263 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_tf_regnet.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the TensorFlow RegNet model. """
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import inspect
|
| 20 |
+
import unittest
|
| 21 |
+
from typing import List, Tuple
|
| 22 |
+
|
| 23 |
+
from transformers import RegNetConfig
|
| 24 |
+
from transformers.testing_utils import require_tf, require_vision, slow
|
| 25 |
+
from transformers.utils import cached_property, is_tf_available, is_vision_available
|
| 26 |
+
|
| 27 |
+
from ...test_configuration_common import ConfigTester
|
| 28 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
|
| 29 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_tf_available():
|
| 33 |
+
import tensorflow as tf
|
| 34 |
+
|
| 35 |
+
from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if is_vision_available():
|
| 39 |
+
from PIL import Image
|
| 40 |
+
|
| 41 |
+
from transformers import AutoImageProcessor
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class TFRegNetModelTester:
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
parent,
|
| 48 |
+
batch_size=3,
|
| 49 |
+
image_size=32,
|
| 50 |
+
num_channels=3,
|
| 51 |
+
embeddings_size=10,
|
| 52 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 53 |
+
depths=[1, 1, 2, 1],
|
| 54 |
+
is_training=True,
|
| 55 |
+
use_labels=True,
|
| 56 |
+
hidden_act="relu",
|
| 57 |
+
num_labels=3,
|
| 58 |
+
scope=None,
|
| 59 |
+
):
|
| 60 |
+
self.parent = parent
|
| 61 |
+
self.batch_size = batch_size
|
| 62 |
+
self.image_size = image_size
|
| 63 |
+
self.num_channels = num_channels
|
| 64 |
+
self.embeddings_size = embeddings_size
|
| 65 |
+
self.hidden_sizes = hidden_sizes
|
| 66 |
+
self.depths = depths
|
| 67 |
+
self.is_training = is_training
|
| 68 |
+
self.use_labels = use_labels
|
| 69 |
+
self.hidden_act = hidden_act
|
| 70 |
+
self.num_labels = num_labels
|
| 71 |
+
self.scope = scope
|
| 72 |
+
self.num_stages = len(hidden_sizes)
|
| 73 |
+
|
| 74 |
+
def prepare_config_and_inputs(self):
|
| 75 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 76 |
+
|
| 77 |
+
labels = None
|
| 78 |
+
if self.use_labels:
|
| 79 |
+
labels = ids_tensor([self.batch_size], self.num_labels)
|
| 80 |
+
|
| 81 |
+
config = self.get_config()
|
| 82 |
+
return config, pixel_values, labels
|
| 83 |
+
|
| 84 |
+
def get_config(self):
|
| 85 |
+
return RegNetConfig(
|
| 86 |
+
num_channels=self.num_channels,
|
| 87 |
+
embeddings_size=self.embeddings_size,
|
| 88 |
+
hidden_sizes=self.hidden_sizes,
|
| 89 |
+
depths=self.depths,
|
| 90 |
+
hidden_act=self.hidden_act,
|
| 91 |
+
num_labels=self.num_labels,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 95 |
+
model = TFRegNetModel(config=config)
|
| 96 |
+
result = model(pixel_values, training=False)
|
| 97 |
+
# expected last hidden states: B, C, H // 32, W // 32
|
| 98 |
+
self.parent.assertEqual(
|
| 99 |
+
result.last_hidden_state.shape,
|
| 100 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 104 |
+
config.num_labels = self.num_labels
|
| 105 |
+
model = TFRegNetForImageClassification(config)
|
| 106 |
+
result = model(pixel_values, labels=labels, training=False)
|
| 107 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 108 |
+
|
| 109 |
+
def prepare_config_and_inputs_for_common(self):
|
| 110 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 111 |
+
config, pixel_values, labels = config_and_inputs
|
| 112 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 113 |
+
return config, inputs_dict
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@require_tf
|
| 117 |
+
class TFRegNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 118 |
+
"""
|
| 119 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as RegNet does not use input_ids, inputs_embeds,
|
| 120 |
+
attention_mask and seq_length.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
all_model_classes = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
|
| 124 |
+
pipeline_model_mapping = (
|
| 125 |
+
{"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
|
| 126 |
+
if is_tf_available()
|
| 127 |
+
else {}
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
test_pruning = False
|
| 131 |
+
test_onnx = False
|
| 132 |
+
test_resize_embeddings = False
|
| 133 |
+
test_head_masking = False
|
| 134 |
+
has_attentions = False
|
| 135 |
+
|
| 136 |
+
def setUp(self):
|
| 137 |
+
self.model_tester = TFRegNetModelTester(self)
|
| 138 |
+
self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False)
|
| 139 |
+
|
| 140 |
+
def create_and_test_config_common_properties(self):
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
@unittest.skip(reason="RegNet does not use inputs_embeds")
|
| 144 |
+
def test_inputs_embeds(self):
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
@unittest.skipIf(
|
| 148 |
+
not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0,
|
| 149 |
+
reason="TF does not support backprop for grouped convolutions on CPU.",
|
| 150 |
+
)
|
| 151 |
+
@slow
|
| 152 |
+
def test_keras_fit(self):
|
| 153 |
+
super().test_keras_fit()
|
| 154 |
+
|
| 155 |
+
@unittest.skip(reason="RegNet does not support input and output embeddings")
|
| 156 |
+
def test_model_common_attributes(self):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
def test_forward_signature(self):
|
| 160 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 161 |
+
|
| 162 |
+
for model_class in self.all_model_classes:
|
| 163 |
+
model = model_class(config)
|
| 164 |
+
signature = inspect.signature(model.call)
|
| 165 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 166 |
+
arg_names = [*signature.parameters.keys()]
|
| 167 |
+
|
| 168 |
+
expected_arg_names = ["pixel_values"]
|
| 169 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 170 |
+
|
| 171 |
+
def test_model(self):
|
| 172 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 173 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 174 |
+
|
| 175 |
+
def test_hidden_states_output(self):
|
| 176 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 177 |
+
model = model_class(config)
|
| 178 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
|
| 179 |
+
|
| 180 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 181 |
+
|
| 182 |
+
expected_num_stages = self.model_tester.num_stages
|
| 183 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 184 |
+
|
| 185 |
+
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
|
| 186 |
+
self.assertListEqual(
|
| 187 |
+
list(hidden_states[0].shape[-2:]),
|
| 188 |
+
[self.model_tester.image_size // 2, self.model_tester.image_size // 2],
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 192 |
+
layers_type = ["basic", "bottleneck"]
|
| 193 |
+
for model_class in self.all_model_classes:
|
| 194 |
+
for layer_type in layers_type:
|
| 195 |
+
config.layer_type = layer_type
|
| 196 |
+
inputs_dict["output_hidden_states"] = True
|
| 197 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 198 |
+
|
| 199 |
+
# check that output_hidden_states also work using config
|
| 200 |
+
del inputs_dict["output_hidden_states"]
|
| 201 |
+
config.output_hidden_states = True
|
| 202 |
+
|
| 203 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 204 |
+
|
| 205 |
+
# Since RegNet does not have any attention we need to rewrite this test.
|
| 206 |
+
def test_model_outputs_equivalence(self):
|
| 207 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 208 |
+
|
| 209 |
+
def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
|
| 210 |
+
tuple_output = model(tuple_inputs, return_dict=False, **additional_kwargs)
|
| 211 |
+
dict_output = model(dict_inputs, return_dict=True, **additional_kwargs).to_tuple()
|
| 212 |
+
|
| 213 |
+
def recursive_check(tuple_object, dict_object):
|
| 214 |
+
if isinstance(tuple_object, (List, Tuple)):
|
| 215 |
+
for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
|
| 216 |
+
recursive_check(tuple_iterable_value, dict_iterable_value)
|
| 217 |
+
elif tuple_object is None:
|
| 218 |
+
return
|
| 219 |
+
else:
|
| 220 |
+
self.assertTrue(
|
| 221 |
+
all(tf.equal(tuple_object, dict_object)),
|
| 222 |
+
msg=(
|
| 223 |
+
"Tuple and dict output are not equal. Difference:"
|
| 224 |
+
f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"
|
| 225 |
+
),
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
recursive_check(tuple_output, dict_output)
|
| 229 |
+
|
| 230 |
+
for model_class in self.all_model_classes:
|
| 231 |
+
model = model_class(config)
|
| 232 |
+
|
| 233 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 234 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 235 |
+
check_equivalence(model, tuple_inputs, dict_inputs)
|
| 236 |
+
|
| 237 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 238 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 239 |
+
check_equivalence(model, tuple_inputs, dict_inputs)
|
| 240 |
+
|
| 241 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 242 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 243 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
|
| 244 |
+
|
| 245 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 246 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 247 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
|
| 248 |
+
|
| 249 |
+
def test_for_image_classification(self):
|
| 250 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 251 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 252 |
+
|
| 253 |
+
@slow
|
| 254 |
+
def test_model_from_pretrained(self):
|
| 255 |
+
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 256 |
+
model = TFRegNetModel.from_pretrained(model_name)
|
| 257 |
+
self.assertIsNotNone(model)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# We will verify our results on an image of cute cats
|
| 261 |
+
def prepare_img():
|
| 262 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 263 |
+
return image
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@require_tf
|
| 267 |
+
@require_vision
|
| 268 |
+
class RegNetModelIntegrationTest(unittest.TestCase):
|
| 269 |
+
@cached_property
|
| 270 |
+
def default_image_processor(self):
|
| 271 |
+
return (
|
| 272 |
+
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 273 |
+
if is_vision_available()
|
| 274 |
+
else None
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
@slow
|
| 278 |
+
def test_inference_image_classification_head(self):
|
| 279 |
+
model = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 280 |
+
|
| 281 |
+
image_processor = self.default_image_processor
|
| 282 |
+
image = prepare_img()
|
| 283 |
+
inputs = image_processor(images=image, return_tensors="tf")
|
| 284 |
+
|
| 285 |
+
# forward pass
|
| 286 |
+
outputs = model(**inputs, training=False)
|
| 287 |
+
|
| 288 |
+
# verify the logits
|
| 289 |
+
expected_shape = tf.TensorShape((1, 1000))
|
| 290 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 291 |
+
|
| 292 |
+
expected_slice = tf.constant([-0.4180, -1.5051, -3.4836])
|
| 293 |
+
|
| 294 |
+
tf.debugging.assert_near(outputs.logits[0, :3], expected_slice, atol=1e-4)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_rembert.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch RemBERT model. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import is_torch_available
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
RemBertConfig,
|
| 33 |
+
RemBertForCausalLM,
|
| 34 |
+
RemBertForMaskedLM,
|
| 35 |
+
RemBertForMultipleChoice,
|
| 36 |
+
RemBertForQuestionAnswering,
|
| 37 |
+
RemBertForSequenceClassification,
|
| 38 |
+
RemBertForTokenClassification,
|
| 39 |
+
RemBertModel,
|
| 40 |
+
)
|
| 41 |
+
from transformers.models.rembert.modeling_rembert import REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class RemBertModelTester:
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
parent,
|
| 48 |
+
batch_size=13,
|
| 49 |
+
seq_length=7,
|
| 50 |
+
is_training=True,
|
| 51 |
+
use_input_mask=True,
|
| 52 |
+
use_token_type_ids=True,
|
| 53 |
+
use_labels=True,
|
| 54 |
+
vocab_size=99,
|
| 55 |
+
hidden_size=32,
|
| 56 |
+
input_embedding_size=18,
|
| 57 |
+
output_embedding_size=43,
|
| 58 |
+
num_hidden_layers=2,
|
| 59 |
+
num_attention_heads=4,
|
| 60 |
+
intermediate_size=37,
|
| 61 |
+
hidden_act="gelu",
|
| 62 |
+
hidden_dropout_prob=0.1,
|
| 63 |
+
attention_probs_dropout_prob=0.1,
|
| 64 |
+
max_position_embeddings=512,
|
| 65 |
+
type_vocab_size=16,
|
| 66 |
+
type_sequence_label_size=2,
|
| 67 |
+
initializer_range=0.02,
|
| 68 |
+
num_labels=3,
|
| 69 |
+
num_choices=4,
|
| 70 |
+
scope=None,
|
| 71 |
+
):
|
| 72 |
+
self.parent = parent
|
| 73 |
+
self.batch_size = batch_size
|
| 74 |
+
self.seq_length = seq_length
|
| 75 |
+
self.is_training = is_training
|
| 76 |
+
self.use_input_mask = use_input_mask
|
| 77 |
+
self.use_token_type_ids = use_token_type_ids
|
| 78 |
+
self.use_labels = use_labels
|
| 79 |
+
self.vocab_size = vocab_size
|
| 80 |
+
self.hidden_size = hidden_size
|
| 81 |
+
self.input_embedding_size = input_embedding_size
|
| 82 |
+
self.output_embedding_size = output_embedding_size
|
| 83 |
+
self.num_hidden_layers = num_hidden_layers
|
| 84 |
+
self.num_attention_heads = num_attention_heads
|
| 85 |
+
self.intermediate_size = intermediate_size
|
| 86 |
+
self.hidden_act = hidden_act
|
| 87 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 88 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 89 |
+
self.max_position_embeddings = max_position_embeddings
|
| 90 |
+
self.type_vocab_size = type_vocab_size
|
| 91 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 92 |
+
self.initializer_range = initializer_range
|
| 93 |
+
self.num_labels = num_labels
|
| 94 |
+
self.num_choices = num_choices
|
| 95 |
+
self.scope = scope
|
| 96 |
+
|
| 97 |
+
def prepare_config_and_inputs(self):
|
| 98 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 99 |
+
|
| 100 |
+
input_mask = None
|
| 101 |
+
if self.use_input_mask:
|
| 102 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 103 |
+
|
| 104 |
+
token_type_ids = None
|
| 105 |
+
if self.use_token_type_ids:
|
| 106 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 107 |
+
|
| 108 |
+
sequence_labels = None
|
| 109 |
+
token_labels = None
|
| 110 |
+
choice_labels = None
|
| 111 |
+
if self.use_labels:
|
| 112 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 113 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 114 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 115 |
+
|
| 116 |
+
config = RemBertConfig(
|
| 117 |
+
vocab_size=self.vocab_size,
|
| 118 |
+
hidden_size=self.hidden_size,
|
| 119 |
+
input_embedding_size=self.input_embedding_size,
|
| 120 |
+
output_embedding_size=self.output_embedding_size,
|
| 121 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 122 |
+
num_attention_heads=self.num_attention_heads,
|
| 123 |
+
intermediate_size=self.intermediate_size,
|
| 124 |
+
hidden_act=self.hidden_act,
|
| 125 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 126 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 127 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 128 |
+
type_vocab_size=self.type_vocab_size,
|
| 129 |
+
is_decoder=False,
|
| 130 |
+
initializer_range=self.initializer_range,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 134 |
+
|
| 135 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 136 |
+
(
|
| 137 |
+
config,
|
| 138 |
+
input_ids,
|
| 139 |
+
token_type_ids,
|
| 140 |
+
input_mask,
|
| 141 |
+
sequence_labels,
|
| 142 |
+
token_labels,
|
| 143 |
+
choice_labels,
|
| 144 |
+
) = self.prepare_config_and_inputs()
|
| 145 |
+
|
| 146 |
+
config.is_decoder = True
|
| 147 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 148 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 149 |
+
|
| 150 |
+
return (
|
| 151 |
+
config,
|
| 152 |
+
input_ids,
|
| 153 |
+
token_type_ids,
|
| 154 |
+
input_mask,
|
| 155 |
+
sequence_labels,
|
| 156 |
+
token_labels,
|
| 157 |
+
choice_labels,
|
| 158 |
+
encoder_hidden_states,
|
| 159 |
+
encoder_attention_mask,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def create_and_check_model(
|
| 163 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 164 |
+
):
|
| 165 |
+
model = RemBertModel(config=config)
|
| 166 |
+
model.to(torch_device)
|
| 167 |
+
model.eval()
|
| 168 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 169 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 170 |
+
result = model(input_ids)
|
| 171 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 172 |
+
|
| 173 |
+
def create_and_check_model_as_decoder(
|
| 174 |
+
self,
|
| 175 |
+
config,
|
| 176 |
+
input_ids,
|
| 177 |
+
token_type_ids,
|
| 178 |
+
input_mask,
|
| 179 |
+
sequence_labels,
|
| 180 |
+
token_labels,
|
| 181 |
+
choice_labels,
|
| 182 |
+
encoder_hidden_states,
|
| 183 |
+
encoder_attention_mask,
|
| 184 |
+
):
|
| 185 |
+
config.add_cross_attention = True
|
| 186 |
+
model = RemBertModel(config)
|
| 187 |
+
model.to(torch_device)
|
| 188 |
+
model.eval()
|
| 189 |
+
result = model(
|
| 190 |
+
input_ids,
|
| 191 |
+
attention_mask=input_mask,
|
| 192 |
+
token_type_ids=token_type_ids,
|
| 193 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 194 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 195 |
+
)
|
| 196 |
+
result = model(
|
| 197 |
+
input_ids,
|
| 198 |
+
attention_mask=input_mask,
|
| 199 |
+
token_type_ids=token_type_ids,
|
| 200 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 201 |
+
)
|
| 202 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 203 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 204 |
+
|
| 205 |
+
def create_and_check_for_causal_lm(
|
| 206 |
+
self,
|
| 207 |
+
config,
|
| 208 |
+
input_ids,
|
| 209 |
+
token_type_ids,
|
| 210 |
+
input_mask,
|
| 211 |
+
sequence_labels,
|
| 212 |
+
token_labels,
|
| 213 |
+
choice_labels,
|
| 214 |
+
encoder_hidden_states,
|
| 215 |
+
encoder_attention_mask,
|
| 216 |
+
):
|
| 217 |
+
model = RemBertForCausalLM(config=config)
|
| 218 |
+
model.to(torch_device)
|
| 219 |
+
model.eval()
|
| 220 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 221 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 222 |
+
|
| 223 |
+
def create_and_check_for_masked_lm(
|
| 224 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 225 |
+
):
|
| 226 |
+
model = RemBertForMaskedLM(config=config)
|
| 227 |
+
model.to(torch_device)
|
| 228 |
+
model.eval()
|
| 229 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 230 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 231 |
+
|
| 232 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 233 |
+
self,
|
| 234 |
+
config,
|
| 235 |
+
input_ids,
|
| 236 |
+
token_type_ids,
|
| 237 |
+
input_mask,
|
| 238 |
+
sequence_labels,
|
| 239 |
+
token_labels,
|
| 240 |
+
choice_labels,
|
| 241 |
+
encoder_hidden_states,
|
| 242 |
+
encoder_attention_mask,
|
| 243 |
+
):
|
| 244 |
+
config.is_decoder = True
|
| 245 |
+
config.add_cross_attention = True
|
| 246 |
+
model = RemBertForCausalLM(config=config)
|
| 247 |
+
model.to(torch_device)
|
| 248 |
+
model.eval()
|
| 249 |
+
|
| 250 |
+
# first forward pass
|
| 251 |
+
outputs = model(
|
| 252 |
+
input_ids,
|
| 253 |
+
attention_mask=input_mask,
|
| 254 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 255 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 256 |
+
use_cache=True,
|
| 257 |
+
)
|
| 258 |
+
past_key_values = outputs.past_key_values
|
| 259 |
+
|
| 260 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 261 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 262 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 263 |
+
|
| 264 |
+
# append to next input_ids and
|
| 265 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 266 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 267 |
+
|
| 268 |
+
output_from_no_past = model(
|
| 269 |
+
next_input_ids,
|
| 270 |
+
attention_mask=next_attention_mask,
|
| 271 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 272 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 273 |
+
output_hidden_states=True,
|
| 274 |
+
)["hidden_states"][0]
|
| 275 |
+
output_from_past = model(
|
| 276 |
+
next_tokens,
|
| 277 |
+
attention_mask=next_attention_mask,
|
| 278 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 279 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 280 |
+
past_key_values=past_key_values,
|
| 281 |
+
output_hidden_states=True,
|
| 282 |
+
)["hidden_states"][0]
|
| 283 |
+
|
| 284 |
+
# select random slice
|
| 285 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 286 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 287 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 288 |
+
|
| 289 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 290 |
+
|
| 291 |
+
# test that outputs are equal for slice
|
| 292 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 293 |
+
|
| 294 |
+
def create_and_check_for_question_answering(
|
| 295 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 296 |
+
):
|
| 297 |
+
model = RemBertForQuestionAnswering(config=config)
|
| 298 |
+
model.to(torch_device)
|
| 299 |
+
model.eval()
|
| 300 |
+
result = model(
|
| 301 |
+
input_ids,
|
| 302 |
+
attention_mask=input_mask,
|
| 303 |
+
token_type_ids=token_type_ids,
|
| 304 |
+
start_positions=sequence_labels,
|
| 305 |
+
end_positions=sequence_labels,
|
| 306 |
+
)
|
| 307 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 308 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 309 |
+
|
| 310 |
+
def create_and_check_for_sequence_classification(
|
| 311 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 312 |
+
):
|
| 313 |
+
config.num_labels = self.num_labels
|
| 314 |
+
model = RemBertForSequenceClassification(config)
|
| 315 |
+
model.to(torch_device)
|
| 316 |
+
model.eval()
|
| 317 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
|
| 318 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 319 |
+
|
| 320 |
+
def create_and_check_for_token_classification(
|
| 321 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 322 |
+
):
|
| 323 |
+
config.num_labels = self.num_labels
|
| 324 |
+
model = RemBertForTokenClassification(config=config)
|
| 325 |
+
model.to(torch_device)
|
| 326 |
+
model.eval()
|
| 327 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 328 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 329 |
+
|
| 330 |
+
def create_and_check_for_multiple_choice(
|
| 331 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 332 |
+
):
|
| 333 |
+
config.num_choices = self.num_choices
|
| 334 |
+
model = RemBertForMultipleChoice(config=config)
|
| 335 |
+
model.to(torch_device)
|
| 336 |
+
model.eval()
|
| 337 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 338 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 339 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 340 |
+
result = model(
|
| 341 |
+
multiple_choice_inputs_ids,
|
| 342 |
+
attention_mask=multiple_choice_input_mask,
|
| 343 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 344 |
+
labels=choice_labels,
|
| 345 |
+
)
|
| 346 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 347 |
+
|
| 348 |
+
def prepare_config_and_inputs_for_common(self):
|
| 349 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 350 |
+
(
|
| 351 |
+
config,
|
| 352 |
+
input_ids,
|
| 353 |
+
token_type_ids,
|
| 354 |
+
input_mask,
|
| 355 |
+
sequence_labels,
|
| 356 |
+
token_labels,
|
| 357 |
+
choice_labels,
|
| 358 |
+
) = config_and_inputs
|
| 359 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 360 |
+
return config, inputs_dict
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
@require_torch
|
| 364 |
+
class RemBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 365 |
+
all_model_classes = (
|
| 366 |
+
(
|
| 367 |
+
RemBertModel,
|
| 368 |
+
RemBertForMaskedLM,
|
| 369 |
+
RemBertForCausalLM,
|
| 370 |
+
RemBertForMultipleChoice,
|
| 371 |
+
RemBertForQuestionAnswering,
|
| 372 |
+
RemBertForSequenceClassification,
|
| 373 |
+
RemBertForTokenClassification,
|
| 374 |
+
)
|
| 375 |
+
if is_torch_available()
|
| 376 |
+
else ()
|
| 377 |
+
)
|
| 378 |
+
all_generative_model_classes = (RemBertForCausalLM,) if is_torch_available() else ()
|
| 379 |
+
pipeline_model_mapping = (
|
| 380 |
+
{
|
| 381 |
+
"feature-extraction": RemBertModel,
|
| 382 |
+
"fill-mask": RemBertForMaskedLM,
|
| 383 |
+
"question-answering": RemBertForQuestionAnswering,
|
| 384 |
+
"text-classification": RemBertForSequenceClassification,
|
| 385 |
+
"text-generation": RemBertForCausalLM,
|
| 386 |
+
"token-classification": RemBertForTokenClassification,
|
| 387 |
+
"zero-shot": RemBertForSequenceClassification,
|
| 388 |
+
}
|
| 389 |
+
if is_torch_available()
|
| 390 |
+
else {}
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
def setUp(self):
|
| 394 |
+
self.model_tester = RemBertModelTester(self)
|
| 395 |
+
self.config_tester = ConfigTester(self, config_class=RemBertConfig, hidden_size=37)
|
| 396 |
+
|
| 397 |
+
def test_config(self):
|
| 398 |
+
self.config_tester.run_common_tests()
|
| 399 |
+
|
| 400 |
+
def test_model(self):
|
| 401 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 402 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 403 |
+
|
| 404 |
+
def test_model_various_embeddings(self):
|
| 405 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 406 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 407 |
+
config_and_inputs[0].position_embedding_type = type
|
| 408 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 409 |
+
|
| 410 |
+
def test_for_masked_lm(self):
|
| 411 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 412 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 413 |
+
|
| 414 |
+
def test_for_multiple_choice(self):
|
| 415 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 416 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 417 |
+
|
| 418 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 419 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 420 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 421 |
+
|
| 422 |
+
def test_for_question_answering(self):
|
| 423 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 424 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 425 |
+
|
| 426 |
+
def test_for_sequence_classification(self):
|
| 427 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 428 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 429 |
+
|
| 430 |
+
def test_for_token_classification(self):
|
| 431 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 432 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 433 |
+
|
| 434 |
+
def test_model_as_decoder(self):
|
| 435 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 436 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 437 |
+
|
| 438 |
+
def test_model_as_decoder_with_default_input_mask(self):
|
| 439 |
+
# This regression test was failing with PyTorch < 1.3
|
| 440 |
+
(
|
| 441 |
+
config,
|
| 442 |
+
input_ids,
|
| 443 |
+
token_type_ids,
|
| 444 |
+
input_mask,
|
| 445 |
+
sequence_labels,
|
| 446 |
+
token_labels,
|
| 447 |
+
choice_labels,
|
| 448 |
+
encoder_hidden_states,
|
| 449 |
+
encoder_attention_mask,
|
| 450 |
+
) = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 451 |
+
|
| 452 |
+
input_mask = None
|
| 453 |
+
|
| 454 |
+
self.model_tester.create_and_check_model_as_decoder(
|
| 455 |
+
config,
|
| 456 |
+
input_ids,
|
| 457 |
+
token_type_ids,
|
| 458 |
+
input_mask,
|
| 459 |
+
sequence_labels,
|
| 460 |
+
token_labels,
|
| 461 |
+
choice_labels,
|
| 462 |
+
encoder_hidden_states,
|
| 463 |
+
encoder_attention_mask,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
@slow
|
| 467 |
+
def test_model_from_pretrained(self):
|
| 468 |
+
for model_name in REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 469 |
+
model = RemBertModel.from_pretrained(model_name)
|
| 470 |
+
self.assertIsNotNone(model)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@require_torch
|
| 474 |
+
class RemBertModelIntegrationTest(unittest.TestCase):
|
| 475 |
+
@slow
|
| 476 |
+
def test_inference_model(self):
|
| 477 |
+
# Test exact values at the last hidden layer
|
| 478 |
+
model = RemBertModel.from_pretrained("google/rembert")
|
| 479 |
+
input_ids = torch.tensor([[312, 56498, 313, 2125, 313]])
|
| 480 |
+
segment_ids = torch.tensor([[0, 0, 0, 1, 1]])
|
| 481 |
+
with torch.no_grad():
|
| 482 |
+
output = model(input_ids, token_type_ids=segment_ids, output_hidden_states=True)
|
| 483 |
+
|
| 484 |
+
hidden_size = 1152
|
| 485 |
+
|
| 486 |
+
expected_shape = torch.Size((1, 5, hidden_size))
|
| 487 |
+
self.assertEqual(output["last_hidden_state"].shape, expected_shape)
|
| 488 |
+
|
| 489 |
+
expected_implementation = torch.tensor(
|
| 490 |
+
[
|
| 491 |
+
[
|
| 492 |
+
[0.0754, -0.2022, 0.1904],
|
| 493 |
+
[-0.3354, -0.3692, -0.4791],
|
| 494 |
+
[-0.2314, -0.6729, -0.0749],
|
| 495 |
+
[-0.0396, -0.3105, -0.4234],
|
| 496 |
+
[-0.1571, -0.0525, 0.5353],
|
| 497 |
+
]
|
| 498 |
+
]
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
# Running on the original tf implementation gives slightly different results here.
|
| 502 |
+
# Not clear why this variations is present
|
| 503 |
+
# TODO: Find reason for discrepancy
|
| 504 |
+
# expected_original_implementation = [[
|
| 505 |
+
# [0.07630594074726105, -0.20146065950393677, 0.19107051193714142],
|
| 506 |
+
# [-0.3405614495277405, -0.36971670389175415, -0.4808273911476135],
|
| 507 |
+
# [-0.22587086260318756, -0.6656315922737122, -0.07844287157058716],
|
| 508 |
+
# [-0.04145475849509239, -0.3077218234539032, -0.42316967248916626],
|
| 509 |
+
# [-0.15887849032878876, -0.054529931396245956, 0.5356100797653198]
|
| 510 |
+
# ]]
|
| 511 |
+
|
| 512 |
+
self.assertTrue(torch.allclose(output["last_hidden_state"][:, :, :3], expected_implementation, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_tf_rembert.py
ADDED
|
@@ -0,0 +1,728 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import RemBertConfig, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_tf, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
TFRemBertForCausalLM,
|
| 34 |
+
TFRemBertForMaskedLM,
|
| 35 |
+
TFRemBertForMultipleChoice,
|
| 36 |
+
TFRemBertForQuestionAnswering,
|
| 37 |
+
TFRemBertForSequenceClassification,
|
| 38 |
+
TFRemBertForTokenClassification,
|
| 39 |
+
TFRemBertModel,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class TFRemBertModelTester:
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
parent,
|
| 47 |
+
batch_size=13,
|
| 48 |
+
seq_length=7,
|
| 49 |
+
is_training=True,
|
| 50 |
+
use_input_mask=True,
|
| 51 |
+
use_token_type_ids=True,
|
| 52 |
+
use_labels=True,
|
| 53 |
+
vocab_size=99,
|
| 54 |
+
hidden_size=32,
|
| 55 |
+
input_embedding_size=18,
|
| 56 |
+
output_embedding_size=43,
|
| 57 |
+
num_hidden_layers=2,
|
| 58 |
+
num_attention_heads=4,
|
| 59 |
+
intermediate_size=37,
|
| 60 |
+
hidden_act="gelu",
|
| 61 |
+
hidden_dropout_prob=0.1,
|
| 62 |
+
attention_probs_dropout_prob=0.1,
|
| 63 |
+
max_position_embeddings=512,
|
| 64 |
+
type_vocab_size=16,
|
| 65 |
+
type_sequence_label_size=2,
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
num_labels=3,
|
| 68 |
+
num_choices=4,
|
| 69 |
+
scope=None,
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = 13
|
| 73 |
+
self.seq_length = 7
|
| 74 |
+
self.is_training = True
|
| 75 |
+
self.use_input_mask = True
|
| 76 |
+
self.use_token_type_ids = True
|
| 77 |
+
self.use_labels = True
|
| 78 |
+
self.vocab_size = 99
|
| 79 |
+
self.hidden_size = 32
|
| 80 |
+
self.input_embedding_size = input_embedding_size
|
| 81 |
+
self.output_embedding_size = output_embedding_size
|
| 82 |
+
self.num_hidden_layers = 2
|
| 83 |
+
self.num_attention_heads = 4
|
| 84 |
+
self.intermediate_size = 37
|
| 85 |
+
self.hidden_act = "gelu"
|
| 86 |
+
self.hidden_dropout_prob = 0.1
|
| 87 |
+
self.attention_probs_dropout_prob = 0.1
|
| 88 |
+
self.max_position_embeddings = 512
|
| 89 |
+
self.type_vocab_size = 16
|
| 90 |
+
self.type_sequence_label_size = 2
|
| 91 |
+
self.initializer_range = 0.02
|
| 92 |
+
self.num_labels = 3
|
| 93 |
+
self.num_choices = 4
|
| 94 |
+
self.scope = None
|
| 95 |
+
|
| 96 |
+
def prepare_config_and_inputs(self):
|
| 97 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 98 |
+
|
| 99 |
+
input_mask = None
|
| 100 |
+
if self.use_input_mask:
|
| 101 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 102 |
+
|
| 103 |
+
token_type_ids = None
|
| 104 |
+
if self.use_token_type_ids:
|
| 105 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 106 |
+
|
| 107 |
+
sequence_labels = None
|
| 108 |
+
token_labels = None
|
| 109 |
+
choice_labels = None
|
| 110 |
+
if self.use_labels:
|
| 111 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 112 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 113 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 114 |
+
|
| 115 |
+
config = RemBertConfig(
|
| 116 |
+
vocab_size=self.vocab_size,
|
| 117 |
+
hidden_size=self.hidden_size,
|
| 118 |
+
input_embedding_size=self.input_embedding_size,
|
| 119 |
+
output_embedding_size=self.output_embedding_size,
|
| 120 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 121 |
+
num_attention_heads=self.num_attention_heads,
|
| 122 |
+
intermediate_size=self.intermediate_size,
|
| 123 |
+
hidden_act=self.hidden_act,
|
| 124 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 125 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 126 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 127 |
+
type_vocab_size=self.type_vocab_size,
|
| 128 |
+
initializer_range=self.initializer_range,
|
| 129 |
+
return_dict=True,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 133 |
+
|
| 134 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 135 |
+
(
|
| 136 |
+
config,
|
| 137 |
+
input_ids,
|
| 138 |
+
token_type_ids,
|
| 139 |
+
input_mask,
|
| 140 |
+
sequence_labels,
|
| 141 |
+
token_labels,
|
| 142 |
+
choice_labels,
|
| 143 |
+
) = self.prepare_config_and_inputs()
|
| 144 |
+
|
| 145 |
+
config.is_decoder = True
|
| 146 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 147 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 148 |
+
|
| 149 |
+
return (
|
| 150 |
+
config,
|
| 151 |
+
input_ids,
|
| 152 |
+
token_type_ids,
|
| 153 |
+
input_mask,
|
| 154 |
+
sequence_labels,
|
| 155 |
+
token_labels,
|
| 156 |
+
choice_labels,
|
| 157 |
+
encoder_hidden_states,
|
| 158 |
+
encoder_attention_mask,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def create_and_check_model(
|
| 162 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 163 |
+
):
|
| 164 |
+
model = TFRemBertModel(config=config)
|
| 165 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 166 |
+
|
| 167 |
+
inputs = [input_ids, input_mask]
|
| 168 |
+
result = model(inputs)
|
| 169 |
+
|
| 170 |
+
result = model(input_ids)
|
| 171 |
+
|
| 172 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 173 |
+
|
| 174 |
+
def create_and_check_causal_lm_base_model(
|
| 175 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 176 |
+
):
|
| 177 |
+
config.is_decoder = True
|
| 178 |
+
|
| 179 |
+
model = TFRemBertModel(config=config)
|
| 180 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 181 |
+
result = model(inputs)
|
| 182 |
+
|
| 183 |
+
inputs = [input_ids, input_mask]
|
| 184 |
+
result = model(inputs)
|
| 185 |
+
|
| 186 |
+
result = model(input_ids)
|
| 187 |
+
|
| 188 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 189 |
+
|
| 190 |
+
def create_and_check_model_as_decoder(
|
| 191 |
+
self,
|
| 192 |
+
config,
|
| 193 |
+
input_ids,
|
| 194 |
+
token_type_ids,
|
| 195 |
+
input_mask,
|
| 196 |
+
sequence_labels,
|
| 197 |
+
token_labels,
|
| 198 |
+
choice_labels,
|
| 199 |
+
encoder_hidden_states,
|
| 200 |
+
encoder_attention_mask,
|
| 201 |
+
):
|
| 202 |
+
config.add_cross_attention = True
|
| 203 |
+
|
| 204 |
+
model = TFRemBertModel(config=config)
|
| 205 |
+
inputs = {
|
| 206 |
+
"input_ids": input_ids,
|
| 207 |
+
"attention_mask": input_mask,
|
| 208 |
+
"token_type_ids": token_type_ids,
|
| 209 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 210 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 211 |
+
}
|
| 212 |
+
result = model(inputs)
|
| 213 |
+
|
| 214 |
+
inputs = [input_ids, input_mask]
|
| 215 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 216 |
+
|
| 217 |
+
# Also check the case where encoder outputs are not passed
|
| 218 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 219 |
+
|
| 220 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 221 |
+
|
| 222 |
+
def create_and_check_causal_lm_model(
|
| 223 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 224 |
+
):
|
| 225 |
+
config.is_decoder = True
|
| 226 |
+
model = TFRemBertForCausalLM(config=config)
|
| 227 |
+
inputs = {
|
| 228 |
+
"input_ids": input_ids,
|
| 229 |
+
"attention_mask": input_mask,
|
| 230 |
+
"token_type_ids": token_type_ids,
|
| 231 |
+
}
|
| 232 |
+
prediction_scores = model(inputs)["logits"]
|
| 233 |
+
self.parent.assertListEqual(
|
| 234 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def create_and_check_causal_lm_model_as_decoder(
|
| 238 |
+
self,
|
| 239 |
+
config,
|
| 240 |
+
input_ids,
|
| 241 |
+
token_type_ids,
|
| 242 |
+
input_mask,
|
| 243 |
+
sequence_labels,
|
| 244 |
+
token_labels,
|
| 245 |
+
choice_labels,
|
| 246 |
+
encoder_hidden_states,
|
| 247 |
+
encoder_attention_mask,
|
| 248 |
+
):
|
| 249 |
+
config.add_cross_attention = True
|
| 250 |
+
|
| 251 |
+
model = TFRemBertForCausalLM(config=config)
|
| 252 |
+
inputs = {
|
| 253 |
+
"input_ids": input_ids,
|
| 254 |
+
"attention_mask": input_mask,
|
| 255 |
+
"token_type_ids": token_type_ids,
|
| 256 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 257 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 258 |
+
}
|
| 259 |
+
result = model(inputs)
|
| 260 |
+
|
| 261 |
+
inputs = [input_ids, input_mask]
|
| 262 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 263 |
+
|
| 264 |
+
prediction_scores = result["logits"]
|
| 265 |
+
self.parent.assertListEqual(
|
| 266 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
def create_and_check_causal_lm_model_past(
|
| 270 |
+
self,
|
| 271 |
+
config,
|
| 272 |
+
input_ids,
|
| 273 |
+
token_type_ids,
|
| 274 |
+
input_mask,
|
| 275 |
+
sequence_labels,
|
| 276 |
+
token_labels,
|
| 277 |
+
choice_labels,
|
| 278 |
+
):
|
| 279 |
+
config.is_decoder = True
|
| 280 |
+
|
| 281 |
+
model = TFRemBertForCausalLM(config=config)
|
| 282 |
+
|
| 283 |
+
# first forward pass
|
| 284 |
+
outputs = model(input_ids, use_cache=True)
|
| 285 |
+
outputs_use_cache_conf = model(input_ids)
|
| 286 |
+
outputs_no_past = model(input_ids, use_cache=False)
|
| 287 |
+
|
| 288 |
+
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
|
| 289 |
+
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
|
| 290 |
+
|
| 291 |
+
past_key_values = outputs.past_key_values
|
| 292 |
+
|
| 293 |
+
# create hypothetical next token and extent to next_input_ids
|
| 294 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 295 |
+
|
| 296 |
+
# append to next input_ids and attn_mask
|
| 297 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 298 |
+
|
| 299 |
+
output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0]
|
| 300 |
+
output_from_past = model(
|
| 301 |
+
next_tokens, past_key_values=past_key_values, output_hidden_states=True
|
| 302 |
+
).hidden_states[0]
|
| 303 |
+
|
| 304 |
+
# select random slice
|
| 305 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 306 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 307 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 308 |
+
|
| 309 |
+
# test that outputs are equal for slice
|
| 310 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 311 |
+
|
| 312 |
+
def create_and_check_causal_lm_model_past_with_attn_mask(
|
| 313 |
+
self,
|
| 314 |
+
config,
|
| 315 |
+
input_ids,
|
| 316 |
+
token_type_ids,
|
| 317 |
+
input_mask,
|
| 318 |
+
sequence_labels,
|
| 319 |
+
token_labels,
|
| 320 |
+
choice_labels,
|
| 321 |
+
):
|
| 322 |
+
config.is_decoder = True
|
| 323 |
+
|
| 324 |
+
model = TFRemBertForCausalLM(config=config)
|
| 325 |
+
|
| 326 |
+
# create attention mask
|
| 327 |
+
half_seq_length = self.seq_length // 2
|
| 328 |
+
attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32)
|
| 329 |
+
attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32)
|
| 330 |
+
attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1)
|
| 331 |
+
|
| 332 |
+
# first forward pass
|
| 333 |
+
outputs = model(input_ids, attention_mask=attn_mask, use_cache=True)
|
| 334 |
+
|
| 335 |
+
# create hypothetical next token and extent to next_input_ids
|
| 336 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 337 |
+
|
| 338 |
+
past_key_values = outputs.past_key_values
|
| 339 |
+
|
| 340 |
+
# change a random masked slice from input_ids
|
| 341 |
+
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1
|
| 342 |
+
random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size)
|
| 343 |
+
vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change)
|
| 344 |
+
condition = tf.transpose(
|
| 345 |
+
tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size))
|
| 346 |
+
)
|
| 347 |
+
input_ids = tf.where(condition, random_other_next_tokens, input_ids)
|
| 348 |
+
|
| 349 |
+
# append to next input_ids and
|
| 350 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 351 |
+
attn_mask = tf.concat(
|
| 352 |
+
[attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)],
|
| 353 |
+
axis=1,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
output_from_no_past = model(
|
| 357 |
+
next_input_ids,
|
| 358 |
+
attention_mask=attn_mask,
|
| 359 |
+
output_hidden_states=True,
|
| 360 |
+
).hidden_states[0]
|
| 361 |
+
output_from_past = model(
|
| 362 |
+
next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True
|
| 363 |
+
).hidden_states[0]
|
| 364 |
+
|
| 365 |
+
# select random slice
|
| 366 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 367 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 368 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 369 |
+
|
| 370 |
+
# test that outputs are equal for slice
|
| 371 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 372 |
+
|
| 373 |
+
def create_and_check_causal_lm_model_past_large_inputs(
|
| 374 |
+
self,
|
| 375 |
+
config,
|
| 376 |
+
input_ids,
|
| 377 |
+
token_type_ids,
|
| 378 |
+
input_mask,
|
| 379 |
+
sequence_labels,
|
| 380 |
+
token_labels,
|
| 381 |
+
choice_labels,
|
| 382 |
+
):
|
| 383 |
+
config.is_decoder = True
|
| 384 |
+
|
| 385 |
+
model = TFRemBertForCausalLM(config=config)
|
| 386 |
+
|
| 387 |
+
input_ids = input_ids[:1, :]
|
| 388 |
+
input_mask = input_mask[:1, :]
|
| 389 |
+
self.batch_size = 1
|
| 390 |
+
|
| 391 |
+
# first forward pass
|
| 392 |
+
outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
|
| 393 |
+
past_key_values = outputs.past_key_values
|
| 394 |
+
|
| 395 |
+
# create hypothetical next token and extent to next_input_ids
|
| 396 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 397 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 398 |
+
|
| 399 |
+
# append to next input_ids and
|
| 400 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 401 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 402 |
+
|
| 403 |
+
output_from_no_past = model(
|
| 404 |
+
next_input_ids,
|
| 405 |
+
attention_mask=next_attention_mask,
|
| 406 |
+
output_hidden_states=True,
|
| 407 |
+
).hidden_states[0]
|
| 408 |
+
output_from_past = model(
|
| 409 |
+
next_tokens,
|
| 410 |
+
attention_mask=next_attention_mask,
|
| 411 |
+
past_key_values=past_key_values,
|
| 412 |
+
output_hidden_states=True,
|
| 413 |
+
).hidden_states[0]
|
| 414 |
+
|
| 415 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 416 |
+
|
| 417 |
+
# select random slice
|
| 418 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 419 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 420 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 421 |
+
|
| 422 |
+
# test that outputs are equal for slice
|
| 423 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 424 |
+
|
| 425 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 426 |
+
self,
|
| 427 |
+
config,
|
| 428 |
+
input_ids,
|
| 429 |
+
token_type_ids,
|
| 430 |
+
input_mask,
|
| 431 |
+
sequence_labels,
|
| 432 |
+
token_labels,
|
| 433 |
+
choice_labels,
|
| 434 |
+
encoder_hidden_states,
|
| 435 |
+
encoder_attention_mask,
|
| 436 |
+
):
|
| 437 |
+
config.add_cross_attention = True
|
| 438 |
+
|
| 439 |
+
model = TFRemBertForCausalLM(config=config)
|
| 440 |
+
|
| 441 |
+
input_ids = input_ids[:1, :]
|
| 442 |
+
input_mask = input_mask[:1, :]
|
| 443 |
+
encoder_hidden_states = encoder_hidden_states[:1, :, :]
|
| 444 |
+
encoder_attention_mask = encoder_attention_mask[:1, :]
|
| 445 |
+
self.batch_size = 1
|
| 446 |
+
|
| 447 |
+
# first forward pass
|
| 448 |
+
outputs = model(
|
| 449 |
+
input_ids,
|
| 450 |
+
attention_mask=input_mask,
|
| 451 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 452 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 453 |
+
use_cache=True,
|
| 454 |
+
)
|
| 455 |
+
past_key_values = outputs.past_key_values
|
| 456 |
+
|
| 457 |
+
# create hypothetical next token and extent to next_input_ids
|
| 458 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 459 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 460 |
+
|
| 461 |
+
# append to next input_ids and
|
| 462 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 463 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 464 |
+
|
| 465 |
+
output_from_no_past = model(
|
| 466 |
+
next_input_ids,
|
| 467 |
+
attention_mask=next_attention_mask,
|
| 468 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 469 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 470 |
+
output_hidden_states=True,
|
| 471 |
+
).hidden_states[0]
|
| 472 |
+
output_from_past = model(
|
| 473 |
+
next_tokens,
|
| 474 |
+
attention_mask=next_attention_mask,
|
| 475 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 476 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 477 |
+
past_key_values=past_key_values,
|
| 478 |
+
output_hidden_states=True,
|
| 479 |
+
).hidden_states[0]
|
| 480 |
+
|
| 481 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 482 |
+
|
| 483 |
+
# select random slice
|
| 484 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 485 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 486 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 487 |
+
|
| 488 |
+
# test that outputs are equal for slice
|
| 489 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 490 |
+
|
| 491 |
+
def create_and_check_for_masked_lm(
|
| 492 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 493 |
+
):
|
| 494 |
+
model = TFRemBertForMaskedLM(config=config)
|
| 495 |
+
inputs = {
|
| 496 |
+
"input_ids": input_ids,
|
| 497 |
+
"attention_mask": input_mask,
|
| 498 |
+
"token_type_ids": token_type_ids,
|
| 499 |
+
}
|
| 500 |
+
result = model(inputs)
|
| 501 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 502 |
+
|
| 503 |
+
def create_and_check_for_sequence_classification(
|
| 504 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 505 |
+
):
|
| 506 |
+
config.num_labels = self.num_labels
|
| 507 |
+
model = TFRemBertForSequenceClassification(config=config)
|
| 508 |
+
inputs = {
|
| 509 |
+
"input_ids": input_ids,
|
| 510 |
+
"attention_mask": input_mask,
|
| 511 |
+
"token_type_ids": token_type_ids,
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
result = model(inputs)
|
| 515 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 516 |
+
|
| 517 |
+
def create_and_check_for_multiple_choice(
|
| 518 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 519 |
+
):
|
| 520 |
+
config.num_choices = self.num_choices
|
| 521 |
+
model = TFRemBertForMultipleChoice(config=config)
|
| 522 |
+
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
|
| 523 |
+
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
|
| 524 |
+
multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
|
| 525 |
+
inputs = {
|
| 526 |
+
"input_ids": multiple_choice_inputs_ids,
|
| 527 |
+
"attention_mask": multiple_choice_input_mask,
|
| 528 |
+
"token_type_ids": multiple_choice_token_type_ids,
|
| 529 |
+
}
|
| 530 |
+
result = model(inputs)
|
| 531 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 532 |
+
|
| 533 |
+
def create_and_check_for_token_classification(
|
| 534 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 535 |
+
):
|
| 536 |
+
config.num_labels = self.num_labels
|
| 537 |
+
model = TFRemBertForTokenClassification(config=config)
|
| 538 |
+
inputs = {
|
| 539 |
+
"input_ids": input_ids,
|
| 540 |
+
"attention_mask": input_mask,
|
| 541 |
+
"token_type_ids": token_type_ids,
|
| 542 |
+
}
|
| 543 |
+
result = model(inputs)
|
| 544 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 545 |
+
|
| 546 |
+
def create_and_check_for_question_answering(
|
| 547 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 548 |
+
):
|
| 549 |
+
model = TFRemBertForQuestionAnswering(config=config)
|
| 550 |
+
inputs = {
|
| 551 |
+
"input_ids": input_ids,
|
| 552 |
+
"attention_mask": input_mask,
|
| 553 |
+
"token_type_ids": token_type_ids,
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
result = model(inputs)
|
| 557 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 558 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 559 |
+
|
| 560 |
+
def prepare_config_and_inputs_for_common(self):
|
| 561 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 562 |
+
(
|
| 563 |
+
config,
|
| 564 |
+
input_ids,
|
| 565 |
+
token_type_ids,
|
| 566 |
+
input_mask,
|
| 567 |
+
sequence_labels,
|
| 568 |
+
token_labels,
|
| 569 |
+
choice_labels,
|
| 570 |
+
) = config_and_inputs
|
| 571 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 572 |
+
return config, inputs_dict
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@require_tf
|
| 576 |
+
class TFRemBertModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 577 |
+
all_model_classes = (
|
| 578 |
+
(
|
| 579 |
+
TFRemBertModel,
|
| 580 |
+
TFRemBertForCausalLM,
|
| 581 |
+
TFRemBertForMaskedLM,
|
| 582 |
+
TFRemBertForQuestionAnswering,
|
| 583 |
+
TFRemBertForSequenceClassification,
|
| 584 |
+
TFRemBertForTokenClassification,
|
| 585 |
+
TFRemBertForMultipleChoice,
|
| 586 |
+
)
|
| 587 |
+
if is_tf_available()
|
| 588 |
+
else ()
|
| 589 |
+
)
|
| 590 |
+
pipeline_model_mapping = (
|
| 591 |
+
{
|
| 592 |
+
"feature-extraction": TFRemBertModel,
|
| 593 |
+
"fill-mask": TFRemBertForMaskedLM,
|
| 594 |
+
"question-answering": TFRemBertForQuestionAnswering,
|
| 595 |
+
"text-classification": TFRemBertForSequenceClassification,
|
| 596 |
+
"text-generation": TFRemBertForCausalLM,
|
| 597 |
+
"token-classification": TFRemBertForTokenClassification,
|
| 598 |
+
"zero-shot": TFRemBertForSequenceClassification,
|
| 599 |
+
}
|
| 600 |
+
if is_tf_available()
|
| 601 |
+
else {}
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
test_head_masking = False
|
| 605 |
+
test_onnx = False
|
| 606 |
+
|
| 607 |
+
def setUp(self):
|
| 608 |
+
self.model_tester = TFRemBertModelTester(self)
|
| 609 |
+
self.config_tester = ConfigTester(self, config_class=RemBertConfig, hidden_size=37)
|
| 610 |
+
|
| 611 |
+
def test_config(self):
|
| 612 |
+
self.config_tester.run_common_tests()
|
| 613 |
+
|
| 614 |
+
def test_model(self):
|
| 615 |
+
"""Test the base model"""
|
| 616 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 617 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 618 |
+
|
| 619 |
+
def test_causal_lm_base_model(self):
|
| 620 |
+
"""Test the base model of the causal LM model
|
| 621 |
+
|
| 622 |
+
is_deocder=True, no cross_attention, no encoder outputs
|
| 623 |
+
"""
|
| 624 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 625 |
+
self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs)
|
| 626 |
+
|
| 627 |
+
def test_model_as_decoder(self):
|
| 628 |
+
"""Test the base model as a decoder (of an encoder-decoder architecture)
|
| 629 |
+
|
| 630 |
+
is_deocder=True + cross_attention + pass encoder outputs
|
| 631 |
+
"""
|
| 632 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 633 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 634 |
+
|
| 635 |
+
def test_for_masked_lm(self):
|
| 636 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 637 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 638 |
+
|
| 639 |
+
def test_for_causal_lm(self):
|
| 640 |
+
"""Test the causal LM model"""
|
| 641 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 642 |
+
self.model_tester.create_and_check_causal_lm_model(*config_and_inputs)
|
| 643 |
+
|
| 644 |
+
def test_causal_lm_model_as_decoder(self):
|
| 645 |
+
"""Test the causal LM model as a decoder"""
|
| 646 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 647 |
+
self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs)
|
| 648 |
+
|
| 649 |
+
def test_causal_lm_model_past(self):
|
| 650 |
+
"""Test causal LM model with `past_key_values`"""
|
| 651 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 652 |
+
self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs)
|
| 653 |
+
|
| 654 |
+
def test_causal_lm_model_past_with_attn_mask(self):
|
| 655 |
+
"""Test the causal LM model with `past_key_values` and `attention_mask`"""
|
| 656 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 657 |
+
self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs)
|
| 658 |
+
|
| 659 |
+
def test_causal_lm_model_past_with_large_inputs(self):
|
| 660 |
+
"""Test the causal LM model with `past_key_values` and a longer decoder sequence length"""
|
| 661 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 662 |
+
self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs)
|
| 663 |
+
|
| 664 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 665 |
+
"""Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention"""
|
| 666 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 667 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 668 |
+
|
| 669 |
+
def test_for_multiple_choice(self):
|
| 670 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 671 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 672 |
+
|
| 673 |
+
def test_for_question_answering(self):
|
| 674 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 675 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 676 |
+
|
| 677 |
+
def test_for_sequence_classification(self):
|
| 678 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 679 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 680 |
+
|
| 681 |
+
def test_for_token_classification(self):
|
| 682 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 683 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 684 |
+
|
| 685 |
+
@slow
|
| 686 |
+
def test_model_from_pretrained(self):
|
| 687 |
+
model = TFRemBertModel.from_pretrained("google/rembert")
|
| 688 |
+
self.assertIsNotNone(model)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
@require_tf
|
| 692 |
+
class TFRemBertModelIntegrationTest(unittest.TestCase):
|
| 693 |
+
@slow
|
| 694 |
+
def test_inference_model(self):
|
| 695 |
+
model = TFRemBertModel.from_pretrained("google/rembert")
|
| 696 |
+
|
| 697 |
+
input_ids = tf.constant([[312, 56498, 313, 2125, 313]])
|
| 698 |
+
segment_ids = tf.constant([[0, 0, 0, 1, 1]])
|
| 699 |
+
output = model(input_ids, token_type_ids=segment_ids, output_hidden_states=True)
|
| 700 |
+
|
| 701 |
+
hidden_size = 1152
|
| 702 |
+
|
| 703 |
+
expected_shape = [1, 5, hidden_size]
|
| 704 |
+
self.assertEqual(output["last_hidden_state"].shape, expected_shape)
|
| 705 |
+
|
| 706 |
+
expected_implementation = tf.constant(
|
| 707 |
+
[
|
| 708 |
+
[
|
| 709 |
+
[0.0754, -0.2022, 0.1904],
|
| 710 |
+
[-0.3354, -0.3692, -0.4791],
|
| 711 |
+
[-0.2314, -0.6729, -0.0749],
|
| 712 |
+
[-0.0396, -0.3105, -0.4234],
|
| 713 |
+
[-0.1571, -0.0525, 0.5353],
|
| 714 |
+
]
|
| 715 |
+
]
|
| 716 |
+
)
|
| 717 |
+
tf.debugging.assert_near(output["last_hidden_state"][:, :, :3], expected_implementation, atol=1e-4)
|
| 718 |
+
|
| 719 |
+
# Running on the original tf implementation gives slightly different results here.
|
| 720 |
+
# Not clear why this variations is present
|
| 721 |
+
# TODO: Find reason for discrepancy
|
| 722 |
+
# expected_original_implementation = [[
|
| 723 |
+
# [0.07630594074726105, -0.20146065950393677, 0.19107051193714142],
|
| 724 |
+
# [-0.3405614495277405, -0.36971670389175415, -0.4808273911476135],
|
| 725 |
+
# [-0.22587086260318756, -0.6656315922737122, -0.07844287157058716],
|
| 726 |
+
# [-0.04145475849509239, -0.3077218234539032, -0.42316967248916626],
|
| 727 |
+
# [-0.15887849032878876, -0.054529931396245956, 0.5356100797653198]
|
| 728 |
+
# ]]
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_tokenization_rembert.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the RemBert tokenizer. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from tests.test_tokenization_common import AddedToken, TokenizerTesterMixin
|
| 22 |
+
from transformers import RemBertTokenizer, RemBertTokenizerFast
|
| 23 |
+
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
SENTENCEPIECE_UNDERLINE = "▁"
|
| 27 |
+
SPIECE_UNDERLINE = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
|
| 28 |
+
|
| 29 |
+
SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@require_sentencepiece
|
| 33 |
+
@require_tokenizers
|
| 34 |
+
class RemBertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 35 |
+
tokenizer_class = RemBertTokenizer
|
| 36 |
+
rust_tokenizer_class = RemBertTokenizerFast
|
| 37 |
+
space_between_special_tokens = True
|
| 38 |
+
test_rust_tokenizer = True
|
| 39 |
+
test_sentencepiece_ignore_case = True
|
| 40 |
+
pre_trained_model_path = "google/rembert"
|
| 41 |
+
|
| 42 |
+
def setUp(self):
|
| 43 |
+
super().setUp()
|
| 44 |
+
|
| 45 |
+
tokenizer = RemBertTokenizer(SAMPLE_VOCAB)
|
| 46 |
+
tokenizer.save_pretrained(self.tmpdirname)
|
| 47 |
+
|
| 48 |
+
# Copied from ReformerTokenizationTest.get_input_output_texts
|
| 49 |
+
def get_input_output_texts(self, tokenizer):
|
| 50 |
+
input_text = "this is a test"
|
| 51 |
+
output_text = "this is a test"
|
| 52 |
+
return input_text, output_text
|
| 53 |
+
|
| 54 |
+
def test_get_vocab(self):
|
| 55 |
+
vocab_keys = list(self.get_tokenizer().get_vocab().keys())
|
| 56 |
+
self.assertEqual(vocab_keys[0], "<unk>")
|
| 57 |
+
self.assertEqual(vocab_keys[1], "<s>")
|
| 58 |
+
|
| 59 |
+
self.assertEqual(vocab_keys[5], "▁the")
|
| 60 |
+
self.assertEqual(vocab_keys[2], "</s>")
|
| 61 |
+
|
| 62 |
+
def test_vocab_size(self):
|
| 63 |
+
self.assertEqual(self.get_tokenizer().vocab_size, 1_000)
|
| 64 |
+
|
| 65 |
+
def test_full_tokenizer(self):
|
| 66 |
+
tokenizer = RemBertTokenizer(SAMPLE_VOCAB, keep_accents=True)
|
| 67 |
+
|
| 68 |
+
tokens = tokenizer.tokenize("This is a test")
|
| 69 |
+
self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
|
| 70 |
+
|
| 71 |
+
self.assertListEqual(
|
| 72 |
+
tokenizer.convert_tokens_to_ids(tokens),
|
| 73 |
+
[285, 46, 10, 170, 382],
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
|
| 77 |
+
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
|
| 78 |
+
ids = tokenizer.convert_tokens_to_ids(tokens)
|
| 79 |
+
self.assertListEqual(ids, [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4])
|
| 80 |
+
|
| 81 |
+
def test_encode_decode_round_trip(self):
|
| 82 |
+
tokenizer = RemBertTokenizer(SAMPLE_VOCAB, keep_accents=True)
|
| 83 |
+
|
| 84 |
+
text = "清水寺は京都にある。"
|
| 85 |
+
tokens = tokenizer.tokenize(text)
|
| 86 |
+
self.assertListEqual(tokens, ["▁", "清水寺は京都にある。"])
|
| 87 |
+
encoded_string = tokenizer.encode(text)
|
| 88 |
+
self.assertListEqual(encoded_string, [1000, 7, 0, 1001])
|
| 89 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 90 |
+
self.assertEquals(decode_text, text)
|
| 91 |
+
|
| 92 |
+
text = "That's awesome! 🤩 #HuggingFace, 🌟 Have a great day! 🌈"
|
| 93 |
+
tokens = tokenizer.tokenize(text)
|
| 94 |
+
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
|
| 95 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 96 |
+
self.assertEquals(decode_text, "That's awesome! 🤩 #HuggingFace, 🌟 Have a great day! 🌈")
|
| 97 |
+
|
| 98 |
+
text = "In the sky up above"
|
| 99 |
+
tokens = tokenizer._tokenize(text)
|
| 100 |
+
self.assertListEqual(tokens, ["▁In", "▁the", "▁s", "k", "y", "▁up", "▁a", "b", "o", "ve"]) # fmt: skip
|
| 101 |
+
encoded_string = tokenizer.encode(text)
|
| 102 |
+
self.assertListEqual(encoded_string, [1000, 388, 5, 47, 45, 30, 118, 10, 65, 20, 123, 1001])
|
| 103 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 104 |
+
self.assertEqual(text, decode_text)
|
| 105 |
+
|
| 106 |
+
text = "The cat. . Sat <s>.In a room"
|
| 107 |
+
tokens = tokenizer.tokenize(text)
|
| 108 |
+
self.assertListEqual(
|
| 109 |
+
tokens, ["▁The", "▁c", "at", ".", "▁", ".", "▁S", "at", "▁", "<", "s", ">", ".", "I", "n", "▁a", "▁room"]
|
| 110 |
+
)
|
| 111 |
+
encoded_string = tokenizer.encode(text)
|
| 112 |
+
self.assertListEqual(
|
| 113 |
+
encoded_string, [1000, 68, 69, 76, 4, 7, 4, 166, 76, 7, 0, 6, 0, 4, 100, 24, 10, 136, 1001]
|
| 114 |
+
)
|
| 115 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 116 |
+
self.assertEqual(text, decode_text)
|
| 117 |
+
|
| 118 |
+
text = "Invoice #12345, dated 2023-12-01, is due on 2024-01-15."
|
| 119 |
+
tokens = tokenizer.tokenize(text)
|
| 120 |
+
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
|
| 121 |
+
encoded_string = tokenizer.encode(text)
|
| 122 |
+
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
|
| 123 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 124 |
+
self.assertEqual(text, decode_text)
|
| 125 |
+
|
| 126 |
+
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit..."
|
| 127 |
+
tokens = tokenizer.tokenize(text)
|
| 128 |
+
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
|
| 129 |
+
encoded_string = tokenizer.encode(text)
|
| 130 |
+
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
|
| 131 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 132 |
+
self.assertEqual(text, decode_text)
|
| 133 |
+
|
| 134 |
+
# for multiple language in one sentence
|
| 135 |
+
text = "Bonjour! Hello! こんにちは!"
|
| 136 |
+
tokens = tokenizer.tokenize(text)
|
| 137 |
+
self.assertListEqual(tokens, ["▁B", "on", "j", "o", "ur", "!", "▁He", "ll", "o", "!", "▁", "こんにちは", "!"])
|
| 138 |
+
encoded_string = tokenizer.encode(text)
|
| 139 |
+
self.assertListEqual(encoded_string, [1000, 295, 109, 999, 20, 108, 146, 156, 86, 20, 146, 7, 0, 146, 1001])
|
| 140 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 141 |
+
self.assertEqual(text, decode_text)
|
| 142 |
+
|
| 143 |
+
text = "Extra spaces\tand\nline breaks\r\nshould be handled."
|
| 144 |
+
tokens = tokenizer.tokenize(text)
|
| 145 |
+
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
|
| 146 |
+
encoded_string = tokenizer.encode(text)
|
| 147 |
+
self.assertListEqual(
|
| 148 |
+
encoded_string,
|
| 149 |
+
[1000, 454, 297, 14, 35, 18, 277, 18, 133, 6, 12, 485, 84, 56, 18, 45, 6, 173, 36, 363, 338, 4, 1001],
|
| 150 |
+
)
|
| 151 |
+
decode_text = tokenizer.convert_tokens_to_string(tokens)
|
| 152 |
+
self.assertEqual("Extra spaces and line breaks should be handled.", decode_text)
|
| 153 |
+
|
| 154 |
+
def test_sequence_builders(self):
|
| 155 |
+
tokenizer = RemBertTokenizer(SAMPLE_VOCAB)
|
| 156 |
+
|
| 157 |
+
text = tokenizer.encode("sequence builders")
|
| 158 |
+
text_2 = tokenizer.encode("multi-sequence build")
|
| 159 |
+
|
| 160 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 161 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 162 |
+
|
| 163 |
+
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
|
| 164 |
+
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [
|
| 165 |
+
tokenizer.sep_token_id
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
def test_added_tokens_serialization(self):
|
| 169 |
+
# Utility to test the added vocab
|
| 170 |
+
def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir):
|
| 171 |
+
tokenizer = tokenizer_class.from_pretrained(temp_dir)
|
| 172 |
+
self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens)
|
| 173 |
+
self.assertIn(new_eos, tokenizer.added_tokens_decoder.values())
|
| 174 |
+
self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos)
|
| 175 |
+
self.assertDictEqual(expected, tokenizer.added_tokens_decoder)
|
| 176 |
+
return tokenizer
|
| 177 |
+
|
| 178 |
+
new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False, special=True)
|
| 179 |
+
new_masked_token = AddedToken("[MASK]", lstrip=True, rstrip=False, normalized=False)
|
| 180 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 181 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 182 |
+
# Load a slow tokenizer from the hub, init with the new token for fast to also include it
|
| 183 |
+
tokenizer = self.tokenizer_class.from_pretrained(
|
| 184 |
+
pretrained_name, eos_token=new_eos, mask_token=new_masked_token
|
| 185 |
+
)
|
| 186 |
+
EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder
|
| 187 |
+
with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"):
|
| 188 |
+
self.assertEqual(tokenizer._eos_token, new_eos)
|
| 189 |
+
self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values()))
|
| 190 |
+
|
| 191 |
+
with tempfile.TemporaryDirectory() as tmp_dir_2:
|
| 192 |
+
tokenizer.save_pretrained(tmp_dir_2)
|
| 193 |
+
with self.subTest(
|
| 194 |
+
"Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class"
|
| 195 |
+
):
|
| 196 |
+
_test_added_vocab_and_eos(
|
| 197 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
if self.rust_tokenizer_class is not None:
|
| 201 |
+
with self.subTest(
|
| 202 |
+
"Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class"
|
| 203 |
+
):
|
| 204 |
+
tokenizer_fast = _test_added_vocab_and_eos(
|
| 205 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2
|
| 206 |
+
)
|
| 207 |
+
with tempfile.TemporaryDirectory() as tmp_dir_3:
|
| 208 |
+
tokenizer_fast.save_pretrained(tmp_dir_3)
|
| 209 |
+
with self.subTest(
|
| 210 |
+
"Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class"
|
| 211 |
+
):
|
| 212 |
+
_test_added_vocab_and_eos(
|
| 213 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
with self.subTest(
|
| 217 |
+
"Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class"
|
| 218 |
+
):
|
| 219 |
+
_test_added_vocab_and_eos(
|
| 220 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"):
|
| 224 |
+
if self.rust_tokenizer_class is not None:
|
| 225 |
+
tokenizer_fast = self.rust_tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos)
|
| 226 |
+
self.assertEqual(tokenizer_fast._eos_token, new_eos)
|
| 227 |
+
self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values()))
|
| 228 |
+
# 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
|
| 229 |
+
with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"):
|
| 230 |
+
self.assertDictEqual(EXPECTED_ADDED_TOKENS_DECODER, tokenizer_fast.added_tokens_decoder)
|
| 231 |
+
|
| 232 |
+
EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder
|
| 233 |
+
with tempfile.TemporaryDirectory() as tmp_dir_4:
|
| 234 |
+
tokenizer_fast.save_pretrained(tmp_dir_4)
|
| 235 |
+
with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"):
|
| 236 |
+
_test_added_vocab_and_eos(
|
| 237 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"):
|
| 241 |
+
_test_added_vocab_and_eos(
|
| 242 |
+
EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4
|
| 243 |
+
)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_flax_resnet.py
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
from transformers import ResNetConfig, is_flax_available
|
| 19 |
+
from transformers.testing_utils import require_flax, slow
|
| 20 |
+
from transformers.utils import cached_property, is_vision_available
|
| 21 |
+
|
| 22 |
+
from ...test_configuration_common import ConfigTester
|
| 23 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_flax_available():
|
| 27 |
+
import jax
|
| 28 |
+
import jax.numpy as jnp
|
| 29 |
+
|
| 30 |
+
from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel
|
| 31 |
+
|
| 32 |
+
if is_vision_available():
|
| 33 |
+
from PIL import Image
|
| 34 |
+
|
| 35 |
+
from transformers import AutoImageProcessor
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FlaxResNetModelTester(unittest.TestCase):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parent,
|
| 42 |
+
batch_size=3,
|
| 43 |
+
image_size=32,
|
| 44 |
+
num_channels=3,
|
| 45 |
+
embeddings_size=10,
|
| 46 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 47 |
+
depths=[1, 1, 2, 1],
|
| 48 |
+
is_training=True,
|
| 49 |
+
use_labels=True,
|
| 50 |
+
hidden_act="relu",
|
| 51 |
+
num_labels=3,
|
| 52 |
+
scope=None,
|
| 53 |
+
):
|
| 54 |
+
self.parent = parent
|
| 55 |
+
self.batch_size = batch_size
|
| 56 |
+
self.image_size = image_size
|
| 57 |
+
self.num_channels = num_channels
|
| 58 |
+
self.embeddings_size = embeddings_size
|
| 59 |
+
self.hidden_sizes = hidden_sizes
|
| 60 |
+
self.depths = depths
|
| 61 |
+
self.is_training = is_training
|
| 62 |
+
self.use_labels = use_labels
|
| 63 |
+
self.hidden_act = hidden_act
|
| 64 |
+
self.num_labels = num_labels
|
| 65 |
+
self.scope = scope
|
| 66 |
+
self.num_stages = len(hidden_sizes)
|
| 67 |
+
|
| 68 |
+
def prepare_config_and_inputs(self):
|
| 69 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 70 |
+
|
| 71 |
+
config = self.get_config()
|
| 72 |
+
|
| 73 |
+
return config, pixel_values
|
| 74 |
+
|
| 75 |
+
def get_config(self):
|
| 76 |
+
return ResNetConfig(
|
| 77 |
+
num_channels=self.num_channels,
|
| 78 |
+
embeddings_size=self.embeddings_size,
|
| 79 |
+
hidden_sizes=self.hidden_sizes,
|
| 80 |
+
depths=self.depths,
|
| 81 |
+
hidden_act=self.hidden_act,
|
| 82 |
+
num_labels=self.num_labels,
|
| 83 |
+
image_size=self.image_size,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def create_and_check_model(self, config, pixel_values):
|
| 87 |
+
model = FlaxResNetModel(config=config)
|
| 88 |
+
result = model(pixel_values)
|
| 89 |
+
|
| 90 |
+
# Output shape (b, c, h, w)
|
| 91 |
+
self.parent.assertEqual(
|
| 92 |
+
result.last_hidden_state.shape,
|
| 93 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
def create_and_check_for_image_classification(self, config, pixel_values):
|
| 97 |
+
config.num_labels = self.num_labels
|
| 98 |
+
model = FlaxResNetForImageClassification(config=config)
|
| 99 |
+
result = model(pixel_values)
|
| 100 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 101 |
+
|
| 102 |
+
def prepare_config_and_inputs_for_common(self):
|
| 103 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 104 |
+
config, pixel_values = config_and_inputs
|
| 105 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 106 |
+
return config, inputs_dict
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@require_flax
|
| 110 |
+
class FlaxResNetModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 111 |
+
all_model_classes = (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()
|
| 112 |
+
|
| 113 |
+
is_encoder_decoder = False
|
| 114 |
+
test_head_masking = False
|
| 115 |
+
has_attentions = False
|
| 116 |
+
|
| 117 |
+
def setUp(self) -> None:
|
| 118 |
+
self.model_tester = FlaxResNetModelTester(self)
|
| 119 |
+
self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False)
|
| 120 |
+
|
| 121 |
+
def test_config(self):
|
| 122 |
+
self.create_and_test_config_common_properties()
|
| 123 |
+
self.config_tester.create_and_test_config_to_json_string()
|
| 124 |
+
self.config_tester.create_and_test_config_to_json_file()
|
| 125 |
+
self.config_tester.create_and_test_config_from_and_save_pretrained()
|
| 126 |
+
self.config_tester.create_and_test_config_with_num_labels()
|
| 127 |
+
self.config_tester.check_config_can_be_init_without_params()
|
| 128 |
+
self.config_tester.check_config_arguments_init()
|
| 129 |
+
|
| 130 |
+
def create_and_test_config_common_properties(self):
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
def test_model(self):
|
| 134 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 135 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 136 |
+
|
| 137 |
+
def test_for_image_classification(self):
|
| 138 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 139 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 140 |
+
|
| 141 |
+
@unittest.skip(reason="ResNet does not use inputs_embeds")
|
| 142 |
+
def test_inputs_embeds(self):
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
@unittest.skip(reason="ResNet does not support input and output embeddings")
|
| 146 |
+
def test_model_common_attributes(self):
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
def test_forward_signature(self):
|
| 150 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 151 |
+
|
| 152 |
+
for model_class in self.all_model_classes:
|
| 153 |
+
model = model_class(config)
|
| 154 |
+
signature = inspect.signature(model.__call__)
|
| 155 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 156 |
+
arg_names = [*signature.parameters.keys()]
|
| 157 |
+
|
| 158 |
+
expected_arg_names = ["pixel_values"]
|
| 159 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 160 |
+
|
| 161 |
+
def test_hidden_states_output(self):
|
| 162 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 163 |
+
model = model_class(config)
|
| 164 |
+
|
| 165 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 166 |
+
|
| 167 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 168 |
+
|
| 169 |
+
expected_num_stages = self.model_tester.num_stages
|
| 170 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 171 |
+
|
| 172 |
+
@unittest.skip(reason="ResNet does not use feedforward chunking")
|
| 173 |
+
def test_feed_forward_chunking(self):
|
| 174 |
+
pass
|
| 175 |
+
|
| 176 |
+
def test_jit_compilation(self):
|
| 177 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 178 |
+
|
| 179 |
+
for model_class in self.all_model_classes:
|
| 180 |
+
with self.subTest(model_class.__name__):
|
| 181 |
+
prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
|
| 182 |
+
model = model_class(config)
|
| 183 |
+
|
| 184 |
+
@jax.jit
|
| 185 |
+
def model_jitted(pixel_values, **kwargs):
|
| 186 |
+
return model(pixel_values=pixel_values, **kwargs)
|
| 187 |
+
|
| 188 |
+
with self.subTest("JIT Enabled"):
|
| 189 |
+
jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 190 |
+
|
| 191 |
+
with self.subTest("JIT Disabled"):
|
| 192 |
+
with jax.disable_jit():
|
| 193 |
+
outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 194 |
+
|
| 195 |
+
self.assertEqual(len(outputs), len(jitted_outputs))
|
| 196 |
+
for jitted_output, output in zip(jitted_outputs, outputs):
|
| 197 |
+
self.assertEqual(jitted_output.shape, output.shape)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# We will verify our results on an image of cute cats
|
| 201 |
+
def prepare_img():
|
| 202 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 203 |
+
return image
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@require_flax
|
| 207 |
+
class FlaxResNetModelIntegrationTest(unittest.TestCase):
|
| 208 |
+
@cached_property
|
| 209 |
+
def default_image_processor(self):
|
| 210 |
+
return AutoImageProcessor.from_pretrained("microsoft/resnet-50") if is_vision_available() else None
|
| 211 |
+
|
| 212 |
+
@slow
|
| 213 |
+
def test_inference_image_classification_head(self):
|
| 214 |
+
model = FlaxResNetForImageClassification.from_pretrained("microsoft/resnet-50")
|
| 215 |
+
|
| 216 |
+
image_processor = self.default_image_processor
|
| 217 |
+
image = prepare_img()
|
| 218 |
+
inputs = image_processor(images=image, return_tensors="np")
|
| 219 |
+
|
| 220 |
+
outputs = model(**inputs)
|
| 221 |
+
|
| 222 |
+
# verify the logits
|
| 223 |
+
expected_shape = (1, 1000)
|
| 224 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 225 |
+
|
| 226 |
+
expected_slice = jnp.array([-11.1069, -9.7877, -8.3777])
|
| 227 |
+
|
| 228 |
+
self.assertTrue(jnp.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_resnet.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch ResNet model. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import ResNetConfig
|
| 21 |
+
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
|
| 22 |
+
from transformers.utils import cached_property, is_torch_available, is_vision_available
|
| 23 |
+
|
| 24 |
+
from ...test_backbone_common import BackboneTesterMixin
|
| 25 |
+
from ...test_configuration_common import ConfigTester
|
| 26 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 27 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
from torch import nn
|
| 33 |
+
|
| 34 |
+
from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
|
| 35 |
+
from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if is_vision_available():
|
| 39 |
+
from PIL import Image
|
| 40 |
+
|
| 41 |
+
from transformers import AutoImageProcessor
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ResNetModelTester:
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
parent,
|
| 48 |
+
batch_size=3,
|
| 49 |
+
image_size=32,
|
| 50 |
+
num_channels=3,
|
| 51 |
+
embeddings_size=10,
|
| 52 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 53 |
+
depths=[1, 1, 2, 1],
|
| 54 |
+
is_training=True,
|
| 55 |
+
use_labels=True,
|
| 56 |
+
hidden_act="relu",
|
| 57 |
+
num_labels=3,
|
| 58 |
+
scope=None,
|
| 59 |
+
out_features=["stage2", "stage3", "stage4"],
|
| 60 |
+
out_indices=[2, 3, 4],
|
| 61 |
+
):
|
| 62 |
+
self.parent = parent
|
| 63 |
+
self.batch_size = batch_size
|
| 64 |
+
self.image_size = image_size
|
| 65 |
+
self.num_channels = num_channels
|
| 66 |
+
self.embeddings_size = embeddings_size
|
| 67 |
+
self.hidden_sizes = hidden_sizes
|
| 68 |
+
self.depths = depths
|
| 69 |
+
self.is_training = is_training
|
| 70 |
+
self.use_labels = use_labels
|
| 71 |
+
self.hidden_act = hidden_act
|
| 72 |
+
self.num_labels = num_labels
|
| 73 |
+
self.scope = scope
|
| 74 |
+
self.num_stages = len(hidden_sizes)
|
| 75 |
+
self.out_features = out_features
|
| 76 |
+
self.out_indices = out_indices
|
| 77 |
+
|
| 78 |
+
def prepare_config_and_inputs(self):
|
| 79 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 80 |
+
|
| 81 |
+
labels = None
|
| 82 |
+
if self.use_labels:
|
| 83 |
+
labels = ids_tensor([self.batch_size], self.num_labels)
|
| 84 |
+
|
| 85 |
+
config = self.get_config()
|
| 86 |
+
|
| 87 |
+
return config, pixel_values, labels
|
| 88 |
+
|
| 89 |
+
def get_config(self):
|
| 90 |
+
return ResNetConfig(
|
| 91 |
+
num_channels=self.num_channels,
|
| 92 |
+
embeddings_size=self.embeddings_size,
|
| 93 |
+
hidden_sizes=self.hidden_sizes,
|
| 94 |
+
depths=self.depths,
|
| 95 |
+
hidden_act=self.hidden_act,
|
| 96 |
+
num_labels=self.num_labels,
|
| 97 |
+
out_features=self.out_features,
|
| 98 |
+
out_indices=self.out_indices,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 102 |
+
model = ResNetModel(config=config)
|
| 103 |
+
model.to(torch_device)
|
| 104 |
+
model.eval()
|
| 105 |
+
result = model(pixel_values)
|
| 106 |
+
# expected last hidden states: B, C, H // 32, W // 32
|
| 107 |
+
self.parent.assertEqual(
|
| 108 |
+
result.last_hidden_state.shape,
|
| 109 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 113 |
+
config.num_labels = self.num_labels
|
| 114 |
+
model = ResNetForImageClassification(config)
|
| 115 |
+
model.to(torch_device)
|
| 116 |
+
model.eval()
|
| 117 |
+
result = model(pixel_values, labels=labels)
|
| 118 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 119 |
+
|
| 120 |
+
def create_and_check_backbone(self, config, pixel_values, labels):
|
| 121 |
+
model = ResNetBackbone(config=config)
|
| 122 |
+
model.to(torch_device)
|
| 123 |
+
model.eval()
|
| 124 |
+
result = model(pixel_values)
|
| 125 |
+
|
| 126 |
+
# verify feature maps
|
| 127 |
+
self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
|
| 128 |
+
self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[1], 4, 4])
|
| 129 |
+
|
| 130 |
+
# verify channels
|
| 131 |
+
self.parent.assertEqual(len(model.channels), len(config.out_features))
|
| 132 |
+
self.parent.assertListEqual(model.channels, config.hidden_sizes[1:])
|
| 133 |
+
|
| 134 |
+
# verify backbone works with out_features=None
|
| 135 |
+
config.out_features = None
|
| 136 |
+
model = ResNetBackbone(config=config)
|
| 137 |
+
model.to(torch_device)
|
| 138 |
+
model.eval()
|
| 139 |
+
result = model(pixel_values)
|
| 140 |
+
|
| 141 |
+
# verify feature maps
|
| 142 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 143 |
+
self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[-1], 1, 1])
|
| 144 |
+
|
| 145 |
+
# verify channels
|
| 146 |
+
self.parent.assertEqual(len(model.channels), 1)
|
| 147 |
+
self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]])
|
| 148 |
+
|
| 149 |
+
def prepare_config_and_inputs_for_common(self):
|
| 150 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 151 |
+
config, pixel_values, labels = config_and_inputs
|
| 152 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 153 |
+
return config, inputs_dict
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@require_torch
|
| 157 |
+
class ResNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 158 |
+
"""
|
| 159 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds,
|
| 160 |
+
attention_mask and seq_length.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
all_model_classes = (
|
| 164 |
+
(
|
| 165 |
+
ResNetModel,
|
| 166 |
+
ResNetForImageClassification,
|
| 167 |
+
ResNetBackbone,
|
| 168 |
+
)
|
| 169 |
+
if is_torch_available()
|
| 170 |
+
else ()
|
| 171 |
+
)
|
| 172 |
+
pipeline_model_mapping = (
|
| 173 |
+
{"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
|
| 174 |
+
if is_torch_available()
|
| 175 |
+
else {}
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
fx_compatible = True
|
| 179 |
+
test_pruning = False
|
| 180 |
+
test_resize_embeddings = False
|
| 181 |
+
test_head_masking = False
|
| 182 |
+
has_attentions = False
|
| 183 |
+
|
| 184 |
+
def setUp(self):
|
| 185 |
+
self.model_tester = ResNetModelTester(self)
|
| 186 |
+
self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False)
|
| 187 |
+
|
| 188 |
+
def test_config(self):
|
| 189 |
+
self.create_and_test_config_common_properties()
|
| 190 |
+
self.config_tester.create_and_test_config_to_json_string()
|
| 191 |
+
self.config_tester.create_and_test_config_to_json_file()
|
| 192 |
+
self.config_tester.create_and_test_config_from_and_save_pretrained()
|
| 193 |
+
self.config_tester.create_and_test_config_with_num_labels()
|
| 194 |
+
self.config_tester.check_config_can_be_init_without_params()
|
| 195 |
+
self.config_tester.check_config_arguments_init()
|
| 196 |
+
|
| 197 |
+
def create_and_test_config_common_properties(self):
|
| 198 |
+
return
|
| 199 |
+
|
| 200 |
+
@unittest.skip(reason="ResNet does not use inputs_embeds")
|
| 201 |
+
def test_inputs_embeds(self):
|
| 202 |
+
pass
|
| 203 |
+
|
| 204 |
+
@unittest.skip(reason="ResNet does not support input and output embeddings")
|
| 205 |
+
def test_model_common_attributes(self):
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
def test_model(self):
|
| 209 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 210 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 211 |
+
|
| 212 |
+
def test_backbone(self):
|
| 213 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 214 |
+
self.model_tester.create_and_check_backbone(*config_and_inputs)
|
| 215 |
+
|
| 216 |
+
def test_initialization(self):
|
| 217 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 218 |
+
|
| 219 |
+
for model_class in self.all_model_classes:
|
| 220 |
+
model = model_class(config=config)
|
| 221 |
+
for name, module in model.named_modules():
|
| 222 |
+
if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 223 |
+
self.assertTrue(
|
| 224 |
+
torch.all(module.weight == 1),
|
| 225 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 226 |
+
)
|
| 227 |
+
self.assertTrue(
|
| 228 |
+
torch.all(module.bias == 0),
|
| 229 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def test_hidden_states_output(self):
|
| 233 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 234 |
+
model = model_class(config)
|
| 235 |
+
model.to(torch_device)
|
| 236 |
+
model.eval()
|
| 237 |
+
|
| 238 |
+
with torch.no_grad():
|
| 239 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 240 |
+
|
| 241 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 242 |
+
|
| 243 |
+
expected_num_stages = self.model_tester.num_stages
|
| 244 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 245 |
+
|
| 246 |
+
# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
|
| 247 |
+
self.assertListEqual(
|
| 248 |
+
list(hidden_states[0].shape[-2:]),
|
| 249 |
+
[self.model_tester.image_size // 4, self.model_tester.image_size // 4],
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 253 |
+
layers_type = ["basic", "bottleneck"]
|
| 254 |
+
for model_class in self.all_model_classes:
|
| 255 |
+
for layer_type in layers_type:
|
| 256 |
+
config.layer_type = layer_type
|
| 257 |
+
inputs_dict["output_hidden_states"] = True
|
| 258 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 259 |
+
|
| 260 |
+
# check that output_hidden_states also work using config
|
| 261 |
+
del inputs_dict["output_hidden_states"]
|
| 262 |
+
config.output_hidden_states = True
|
| 263 |
+
|
| 264 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 265 |
+
|
| 266 |
+
@unittest.skip(reason="ResNet does not use feedforward chunking")
|
| 267 |
+
def test_feed_forward_chunking(self):
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
def test_for_image_classification(self):
|
| 271 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 272 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 273 |
+
|
| 274 |
+
@slow
|
| 275 |
+
def test_model_from_pretrained(self):
|
| 276 |
+
for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 277 |
+
model = ResNetModel.from_pretrained(model_name)
|
| 278 |
+
self.assertIsNotNone(model)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
# We will verify our results on an image of cute cats
|
| 282 |
+
def prepare_img():
|
| 283 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 284 |
+
return image
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@require_torch
|
| 288 |
+
@require_vision
|
| 289 |
+
class ResNetModelIntegrationTest(unittest.TestCase):
|
| 290 |
+
@cached_property
|
| 291 |
+
def default_image_processor(self):
|
| 292 |
+
return (
|
| 293 |
+
AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 294 |
+
if is_vision_available()
|
| 295 |
+
else None
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
@slow
|
| 299 |
+
def test_inference_image_classification_head(self):
|
| 300 |
+
model = ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(torch_device)
|
| 301 |
+
|
| 302 |
+
image_processor = self.default_image_processor
|
| 303 |
+
image = prepare_img()
|
| 304 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 305 |
+
|
| 306 |
+
# forward pass
|
| 307 |
+
with torch.no_grad():
|
| 308 |
+
outputs = model(**inputs)
|
| 309 |
+
|
| 310 |
+
# verify the logits
|
| 311 |
+
expected_shape = torch.Size((1, 1000))
|
| 312 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 313 |
+
|
| 314 |
+
expected_slice = torch.tensor([-11.1069, -9.7877, -8.3777]).to(torch_device)
|
| 315 |
+
|
| 316 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@require_torch
|
| 320 |
+
class ResNetBackboneTest(BackboneTesterMixin, unittest.TestCase):
|
| 321 |
+
all_model_classes = (ResNetBackbone,) if is_torch_available() else ()
|
| 322 |
+
has_attentions = False
|
| 323 |
+
config_class = ResNetConfig
|
| 324 |
+
|
| 325 |
+
def setUp(self):
|
| 326 |
+
self.model_tester = ResNetModelTester(self)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_tf_resnet.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the Tensorflow ResNet model. """
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import inspect
|
| 21 |
+
import unittest
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from transformers import ResNetConfig
|
| 26 |
+
from transformers.testing_utils import require_tf, require_vision, slow
|
| 27 |
+
from transformers.utils import cached_property, is_tf_available, is_vision_available
|
| 28 |
+
|
| 29 |
+
from ...test_configuration_common import ConfigTester
|
| 30 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
|
| 31 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_tf_available():
|
| 35 |
+
import tensorflow as tf
|
| 36 |
+
|
| 37 |
+
from transformers import TFResNetForImageClassification, TFResNetModel
|
| 38 |
+
from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if is_vision_available():
|
| 42 |
+
from PIL import Image
|
| 43 |
+
|
| 44 |
+
from transformers import AutoImageProcessor
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class TFResNetModelTester:
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
parent,
|
| 51 |
+
batch_size=3,
|
| 52 |
+
image_size=32,
|
| 53 |
+
num_channels=3,
|
| 54 |
+
embeddings_size=10,
|
| 55 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 56 |
+
depths=[1, 1, 2, 1],
|
| 57 |
+
is_training=True,
|
| 58 |
+
use_labels=True,
|
| 59 |
+
hidden_act="relu",
|
| 60 |
+
num_labels=3,
|
| 61 |
+
scope=None,
|
| 62 |
+
):
|
| 63 |
+
self.parent = parent
|
| 64 |
+
self.batch_size = batch_size
|
| 65 |
+
self.image_size = image_size
|
| 66 |
+
self.num_channels = num_channels
|
| 67 |
+
self.embeddings_size = embeddings_size
|
| 68 |
+
self.hidden_sizes = hidden_sizes
|
| 69 |
+
self.depths = depths
|
| 70 |
+
self.is_training = is_training
|
| 71 |
+
self.use_labels = use_labels
|
| 72 |
+
self.hidden_act = hidden_act
|
| 73 |
+
self.num_labels = num_labels
|
| 74 |
+
self.scope = scope
|
| 75 |
+
self.num_stages = len(hidden_sizes)
|
| 76 |
+
|
| 77 |
+
def prepare_config_and_inputs(self):
|
| 78 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 79 |
+
|
| 80 |
+
labels = None
|
| 81 |
+
if self.use_labels:
|
| 82 |
+
labels = ids_tensor([self.batch_size], self.num_labels)
|
| 83 |
+
|
| 84 |
+
config = self.get_config()
|
| 85 |
+
|
| 86 |
+
return config, pixel_values, labels
|
| 87 |
+
|
| 88 |
+
def get_config(self):
|
| 89 |
+
return ResNetConfig(
|
| 90 |
+
num_channels=self.num_channels,
|
| 91 |
+
embeddings_size=self.embeddings_size,
|
| 92 |
+
hidden_sizes=self.hidden_sizes,
|
| 93 |
+
depths=self.depths,
|
| 94 |
+
hidden_act=self.hidden_act,
|
| 95 |
+
num_labels=self.num_labels,
|
| 96 |
+
image_size=self.image_size,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 100 |
+
model = TFResNetModel(config=config)
|
| 101 |
+
result = model(pixel_values)
|
| 102 |
+
# expected last hidden states: B, C, H // 32, W // 32
|
| 103 |
+
self.parent.assertEqual(
|
| 104 |
+
result.last_hidden_state.shape,
|
| 105 |
+
(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 109 |
+
config.num_labels = self.num_labels
|
| 110 |
+
model = TFResNetForImageClassification(config)
|
| 111 |
+
result = model(pixel_values, labels=labels)
|
| 112 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 113 |
+
|
| 114 |
+
def prepare_config_and_inputs_for_common(self):
|
| 115 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 116 |
+
config, pixel_values, labels = config_and_inputs
|
| 117 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 118 |
+
return config, inputs_dict
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@require_tf
|
| 122 |
+
class TFResNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 123 |
+
"""
|
| 124 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds,
|
| 125 |
+
attention_mask and seq_length.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
all_model_classes = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
|
| 129 |
+
pipeline_model_mapping = (
|
| 130 |
+
{"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
|
| 131 |
+
if is_tf_available()
|
| 132 |
+
else {}
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
test_pruning = False
|
| 136 |
+
test_resize_embeddings = False
|
| 137 |
+
test_head_masking = False
|
| 138 |
+
test_onnx = False
|
| 139 |
+
has_attentions = False
|
| 140 |
+
|
| 141 |
+
def setUp(self):
|
| 142 |
+
self.model_tester = TFResNetModelTester(self)
|
| 143 |
+
self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False)
|
| 144 |
+
|
| 145 |
+
def test_config(self):
|
| 146 |
+
self.create_and_test_config_common_properties()
|
| 147 |
+
self.config_tester.create_and_test_config_to_json_string()
|
| 148 |
+
self.config_tester.create_and_test_config_to_json_file()
|
| 149 |
+
self.config_tester.create_and_test_config_from_and_save_pretrained()
|
| 150 |
+
self.config_tester.create_and_test_config_with_num_labels()
|
| 151 |
+
self.config_tester.check_config_can_be_init_without_params()
|
| 152 |
+
self.config_tester.check_config_arguments_init()
|
| 153 |
+
|
| 154 |
+
def create_and_test_config_common_properties(self):
|
| 155 |
+
return
|
| 156 |
+
|
| 157 |
+
@unittest.skip(reason="ResNet does not use inputs_embeds")
|
| 158 |
+
def test_inputs_embeds(self):
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
@unittest.skip(reason="ResNet does not support input and output embeddings")
|
| 162 |
+
def test_model_common_attributes(self):
|
| 163 |
+
pass
|
| 164 |
+
|
| 165 |
+
def test_forward_signature(self):
|
| 166 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 167 |
+
|
| 168 |
+
for model_class in self.all_model_classes:
|
| 169 |
+
model = model_class(config)
|
| 170 |
+
signature = inspect.signature(model.call)
|
| 171 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 172 |
+
arg_names = [*signature.parameters.keys()]
|
| 173 |
+
|
| 174 |
+
expected_arg_names = ["pixel_values"]
|
| 175 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 176 |
+
|
| 177 |
+
def test_model(self):
|
| 178 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 179 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 180 |
+
|
| 181 |
+
def test_hidden_states_output(self):
|
| 182 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 183 |
+
model = model_class(config)
|
| 184 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 185 |
+
|
| 186 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 187 |
+
|
| 188 |
+
expected_num_stages = self.model_tester.num_stages
|
| 189 |
+
self.assertEqual(len(hidden_states), expected_num_stages + 1)
|
| 190 |
+
|
| 191 |
+
# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
|
| 192 |
+
self.assertListEqual(
|
| 193 |
+
list(hidden_states[0].shape[-2:]),
|
| 194 |
+
[self.model_tester.image_size // 4, self.model_tester.image_size // 4],
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 198 |
+
layers_type = ["basic", "bottleneck"]
|
| 199 |
+
for model_class in self.all_model_classes:
|
| 200 |
+
for layer_type in layers_type:
|
| 201 |
+
config.layer_type = layer_type
|
| 202 |
+
inputs_dict["output_hidden_states"] = True
|
| 203 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 204 |
+
|
| 205 |
+
# check that output_hidden_states also work using config
|
| 206 |
+
del inputs_dict["output_hidden_states"]
|
| 207 |
+
config.output_hidden_states = True
|
| 208 |
+
|
| 209 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 210 |
+
|
| 211 |
+
def test_for_image_classification(self):
|
| 212 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 213 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 214 |
+
|
| 215 |
+
@slow
|
| 216 |
+
def test_model_from_pretrained(self):
|
| 217 |
+
for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 218 |
+
model = TFResNetModel.from_pretrained(model_name)
|
| 219 |
+
self.assertIsNotNone(model)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# We will verify our results on an image of cute cats
|
| 223 |
+
def prepare_img():
|
| 224 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 225 |
+
return image
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@require_tf
|
| 229 |
+
@require_vision
|
| 230 |
+
class TFResNetModelIntegrationTest(unittest.TestCase):
|
| 231 |
+
@cached_property
|
| 232 |
+
def default_image_processor(self):
|
| 233 |
+
return (
|
| 234 |
+
AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 235 |
+
if is_vision_available()
|
| 236 |
+
else None
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
@slow
|
| 240 |
+
def test_inference_image_classification_head(self):
|
| 241 |
+
model = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
|
| 242 |
+
|
| 243 |
+
image_processor = self.default_image_processor
|
| 244 |
+
image = prepare_img()
|
| 245 |
+
inputs = image_processor(images=image, return_tensors="tf")
|
| 246 |
+
|
| 247 |
+
# forward pass
|
| 248 |
+
outputs = model(**inputs)
|
| 249 |
+
|
| 250 |
+
# verify the logits
|
| 251 |
+
expected_shape = tf.TensorShape((1, 1000))
|
| 252 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 253 |
+
|
| 254 |
+
expected_slice = tf.constant([-11.1069, -9.7877, -8.3777])
|
| 255 |
+
|
| 256 |
+
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy(), expected_slice, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_flax_roberta.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from transformers import RobertaConfig, is_flax_available
|
| 20 |
+
from transformers.testing_utils import require_flax, slow
|
| 21 |
+
|
| 22 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_flax_available():
|
| 26 |
+
from transformers.models.roberta.modeling_flax_roberta import (
|
| 27 |
+
FlaxRobertaForCausalLM,
|
| 28 |
+
FlaxRobertaForMaskedLM,
|
| 29 |
+
FlaxRobertaForMultipleChoice,
|
| 30 |
+
FlaxRobertaForQuestionAnswering,
|
| 31 |
+
FlaxRobertaForSequenceClassification,
|
| 32 |
+
FlaxRobertaForTokenClassification,
|
| 33 |
+
FlaxRobertaModel,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class FlaxRobertaModelTester(unittest.TestCase):
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
parent,
|
| 41 |
+
batch_size=13,
|
| 42 |
+
seq_length=7,
|
| 43 |
+
is_training=True,
|
| 44 |
+
use_attention_mask=True,
|
| 45 |
+
use_token_type_ids=True,
|
| 46 |
+
use_labels=True,
|
| 47 |
+
vocab_size=99,
|
| 48 |
+
hidden_size=32,
|
| 49 |
+
num_hidden_layers=2,
|
| 50 |
+
num_attention_heads=4,
|
| 51 |
+
intermediate_size=37,
|
| 52 |
+
hidden_act="gelu",
|
| 53 |
+
hidden_dropout_prob=0.1,
|
| 54 |
+
attention_probs_dropout_prob=0.1,
|
| 55 |
+
max_position_embeddings=512,
|
| 56 |
+
type_vocab_size=16,
|
| 57 |
+
type_sequence_label_size=2,
|
| 58 |
+
initializer_range=0.02,
|
| 59 |
+
num_choices=4,
|
| 60 |
+
):
|
| 61 |
+
self.parent = parent
|
| 62 |
+
self.batch_size = batch_size
|
| 63 |
+
self.seq_length = seq_length
|
| 64 |
+
self.is_training = is_training
|
| 65 |
+
self.use_attention_mask = use_attention_mask
|
| 66 |
+
self.use_token_type_ids = use_token_type_ids
|
| 67 |
+
self.use_labels = use_labels
|
| 68 |
+
self.vocab_size = vocab_size
|
| 69 |
+
self.hidden_size = hidden_size
|
| 70 |
+
self.num_hidden_layers = num_hidden_layers
|
| 71 |
+
self.num_attention_heads = num_attention_heads
|
| 72 |
+
self.intermediate_size = intermediate_size
|
| 73 |
+
self.hidden_act = hidden_act
|
| 74 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 75 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 76 |
+
self.max_position_embeddings = max_position_embeddings
|
| 77 |
+
self.type_vocab_size = type_vocab_size
|
| 78 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 79 |
+
self.initializer_range = initializer_range
|
| 80 |
+
self.num_choices = num_choices
|
| 81 |
+
|
| 82 |
+
def prepare_config_and_inputs(self):
|
| 83 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 84 |
+
|
| 85 |
+
attention_mask = None
|
| 86 |
+
if self.use_attention_mask:
|
| 87 |
+
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 88 |
+
|
| 89 |
+
token_type_ids = None
|
| 90 |
+
if self.use_token_type_ids:
|
| 91 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 92 |
+
|
| 93 |
+
config = RobertaConfig(
|
| 94 |
+
vocab_size=self.vocab_size,
|
| 95 |
+
hidden_size=self.hidden_size,
|
| 96 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 97 |
+
num_attention_heads=self.num_attention_heads,
|
| 98 |
+
intermediate_size=self.intermediate_size,
|
| 99 |
+
hidden_act=self.hidden_act,
|
| 100 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 101 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 102 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 103 |
+
type_vocab_size=self.type_vocab_size,
|
| 104 |
+
is_decoder=False,
|
| 105 |
+
initializer_range=self.initializer_range,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return config, input_ids, token_type_ids, attention_mask
|
| 109 |
+
|
| 110 |
+
def prepare_config_and_inputs_for_common(self):
|
| 111 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 112 |
+
config, input_ids, token_type_ids, attention_mask = config_and_inputs
|
| 113 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
|
| 114 |
+
return config, inputs_dict
|
| 115 |
+
|
| 116 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 117 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 118 |
+
config, input_ids, token_type_ids, attention_mask = config_and_inputs
|
| 119 |
+
|
| 120 |
+
config.is_decoder = True
|
| 121 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 122 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 123 |
+
|
| 124 |
+
return (
|
| 125 |
+
config,
|
| 126 |
+
input_ids,
|
| 127 |
+
token_type_ids,
|
| 128 |
+
encoder_hidden_states,
|
| 129 |
+
encoder_attention_mask,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@require_flax
|
| 134 |
+
class FlaxRobertaModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 135 |
+
test_head_masking = True
|
| 136 |
+
|
| 137 |
+
all_model_classes = (
|
| 138 |
+
(
|
| 139 |
+
FlaxRobertaModel,
|
| 140 |
+
FlaxRobertaForCausalLM,
|
| 141 |
+
FlaxRobertaForMaskedLM,
|
| 142 |
+
FlaxRobertaForSequenceClassification,
|
| 143 |
+
FlaxRobertaForTokenClassification,
|
| 144 |
+
FlaxRobertaForMultipleChoice,
|
| 145 |
+
FlaxRobertaForQuestionAnswering,
|
| 146 |
+
)
|
| 147 |
+
if is_flax_available()
|
| 148 |
+
else ()
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def setUp(self):
|
| 152 |
+
self.model_tester = FlaxRobertaModelTester(self)
|
| 153 |
+
|
| 154 |
+
@slow
|
| 155 |
+
def test_model_from_pretrained(self):
|
| 156 |
+
for model_class_name in self.all_model_classes:
|
| 157 |
+
model = model_class_name.from_pretrained("roberta-base", from_pt=True)
|
| 158 |
+
outputs = model(np.ones((1, 1)))
|
| 159 |
+
self.assertIsNotNone(outputs)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_roberta.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import RobertaConfig, is_torch_available
|
| 20 |
+
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
|
| 21 |
+
|
| 22 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
RobertaForCausalLM,
|
| 33 |
+
RobertaForMaskedLM,
|
| 34 |
+
RobertaForMultipleChoice,
|
| 35 |
+
RobertaForQuestionAnswering,
|
| 36 |
+
RobertaForSequenceClassification,
|
| 37 |
+
RobertaForTokenClassification,
|
| 38 |
+
RobertaModel,
|
| 39 |
+
)
|
| 40 |
+
from transformers.models.roberta.modeling_roberta import (
|
| 41 |
+
ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 42 |
+
RobertaEmbeddings,
|
| 43 |
+
create_position_ids_from_input_ids,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
ROBERTA_TINY = "sshleifer/tiny-distilroberta-base"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class RobertaModelTester:
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
parent,
|
| 53 |
+
batch_size=13,
|
| 54 |
+
seq_length=7,
|
| 55 |
+
is_training=True,
|
| 56 |
+
use_input_mask=True,
|
| 57 |
+
use_token_type_ids=True,
|
| 58 |
+
use_labels=True,
|
| 59 |
+
vocab_size=99,
|
| 60 |
+
hidden_size=32,
|
| 61 |
+
num_hidden_layers=2,
|
| 62 |
+
num_attention_heads=4,
|
| 63 |
+
intermediate_size=37,
|
| 64 |
+
hidden_act="gelu",
|
| 65 |
+
hidden_dropout_prob=0.1,
|
| 66 |
+
attention_probs_dropout_prob=0.1,
|
| 67 |
+
max_position_embeddings=512,
|
| 68 |
+
type_vocab_size=16,
|
| 69 |
+
type_sequence_label_size=2,
|
| 70 |
+
initializer_range=0.02,
|
| 71 |
+
num_labels=3,
|
| 72 |
+
num_choices=4,
|
| 73 |
+
scope=None,
|
| 74 |
+
):
|
| 75 |
+
self.parent = parent
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.seq_length = seq_length
|
| 78 |
+
self.is_training = is_training
|
| 79 |
+
self.use_input_mask = use_input_mask
|
| 80 |
+
self.use_token_type_ids = use_token_type_ids
|
| 81 |
+
self.use_labels = use_labels
|
| 82 |
+
self.vocab_size = vocab_size
|
| 83 |
+
self.hidden_size = hidden_size
|
| 84 |
+
self.num_hidden_layers = num_hidden_layers
|
| 85 |
+
self.num_attention_heads = num_attention_heads
|
| 86 |
+
self.intermediate_size = intermediate_size
|
| 87 |
+
self.hidden_act = hidden_act
|
| 88 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 89 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 90 |
+
self.max_position_embeddings = max_position_embeddings
|
| 91 |
+
self.type_vocab_size = type_vocab_size
|
| 92 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 93 |
+
self.initializer_range = initializer_range
|
| 94 |
+
self.num_labels = num_labels
|
| 95 |
+
self.num_choices = num_choices
|
| 96 |
+
self.scope = scope
|
| 97 |
+
|
| 98 |
+
def prepare_config_and_inputs(self):
|
| 99 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 100 |
+
|
| 101 |
+
input_mask = None
|
| 102 |
+
if self.use_input_mask:
|
| 103 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 104 |
+
|
| 105 |
+
token_type_ids = None
|
| 106 |
+
if self.use_token_type_ids:
|
| 107 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 108 |
+
|
| 109 |
+
sequence_labels = None
|
| 110 |
+
token_labels = None
|
| 111 |
+
choice_labels = None
|
| 112 |
+
if self.use_labels:
|
| 113 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 114 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 115 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 116 |
+
|
| 117 |
+
config = self.get_config()
|
| 118 |
+
|
| 119 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 120 |
+
|
| 121 |
+
def get_config(self):
|
| 122 |
+
return RobertaConfig(
|
| 123 |
+
vocab_size=self.vocab_size,
|
| 124 |
+
hidden_size=self.hidden_size,
|
| 125 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 126 |
+
num_attention_heads=self.num_attention_heads,
|
| 127 |
+
intermediate_size=self.intermediate_size,
|
| 128 |
+
hidden_act=self.hidden_act,
|
| 129 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 130 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 131 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 132 |
+
type_vocab_size=self.type_vocab_size,
|
| 133 |
+
initializer_range=self.initializer_range,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def get_pipeline_config(self):
|
| 137 |
+
config = self.get_config()
|
| 138 |
+
config.vocab_size = 300
|
| 139 |
+
return config
|
| 140 |
+
|
| 141 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 142 |
+
(
|
| 143 |
+
config,
|
| 144 |
+
input_ids,
|
| 145 |
+
token_type_ids,
|
| 146 |
+
input_mask,
|
| 147 |
+
sequence_labels,
|
| 148 |
+
token_labels,
|
| 149 |
+
choice_labels,
|
| 150 |
+
) = self.prepare_config_and_inputs()
|
| 151 |
+
|
| 152 |
+
config.is_decoder = True
|
| 153 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 154 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 155 |
+
|
| 156 |
+
return (
|
| 157 |
+
config,
|
| 158 |
+
input_ids,
|
| 159 |
+
token_type_ids,
|
| 160 |
+
input_mask,
|
| 161 |
+
sequence_labels,
|
| 162 |
+
token_labels,
|
| 163 |
+
choice_labels,
|
| 164 |
+
encoder_hidden_states,
|
| 165 |
+
encoder_attention_mask,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def create_and_check_model(
|
| 169 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 170 |
+
):
|
| 171 |
+
model = RobertaModel(config=config)
|
| 172 |
+
model.to(torch_device)
|
| 173 |
+
model.eval()
|
| 174 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 175 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 176 |
+
result = model(input_ids)
|
| 177 |
+
|
| 178 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 179 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
|
| 180 |
+
|
| 181 |
+
def create_and_check_model_as_decoder(
|
| 182 |
+
self,
|
| 183 |
+
config,
|
| 184 |
+
input_ids,
|
| 185 |
+
token_type_ids,
|
| 186 |
+
input_mask,
|
| 187 |
+
sequence_labels,
|
| 188 |
+
token_labels,
|
| 189 |
+
choice_labels,
|
| 190 |
+
encoder_hidden_states,
|
| 191 |
+
encoder_attention_mask,
|
| 192 |
+
):
|
| 193 |
+
config.add_cross_attention = True
|
| 194 |
+
model = RobertaModel(config)
|
| 195 |
+
model.to(torch_device)
|
| 196 |
+
model.eval()
|
| 197 |
+
result = model(
|
| 198 |
+
input_ids,
|
| 199 |
+
attention_mask=input_mask,
|
| 200 |
+
token_type_ids=token_type_ids,
|
| 201 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 202 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 203 |
+
)
|
| 204 |
+
result = model(
|
| 205 |
+
input_ids,
|
| 206 |
+
attention_mask=input_mask,
|
| 207 |
+
token_type_ids=token_type_ids,
|
| 208 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 209 |
+
)
|
| 210 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 211 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 212 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
|
| 213 |
+
|
| 214 |
+
def create_and_check_for_causal_lm(
|
| 215 |
+
self,
|
| 216 |
+
config,
|
| 217 |
+
input_ids,
|
| 218 |
+
token_type_ids,
|
| 219 |
+
input_mask,
|
| 220 |
+
sequence_labels,
|
| 221 |
+
token_labels,
|
| 222 |
+
choice_labels,
|
| 223 |
+
encoder_hidden_states,
|
| 224 |
+
encoder_attention_mask,
|
| 225 |
+
):
|
| 226 |
+
model = RobertaForCausalLM(config=config)
|
| 227 |
+
model.to(torch_device)
|
| 228 |
+
model.eval()
|
| 229 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 230 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 231 |
+
|
| 232 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 233 |
+
self,
|
| 234 |
+
config,
|
| 235 |
+
input_ids,
|
| 236 |
+
token_type_ids,
|
| 237 |
+
input_mask,
|
| 238 |
+
sequence_labels,
|
| 239 |
+
token_labels,
|
| 240 |
+
choice_labels,
|
| 241 |
+
encoder_hidden_states,
|
| 242 |
+
encoder_attention_mask,
|
| 243 |
+
):
|
| 244 |
+
config.is_decoder = True
|
| 245 |
+
config.add_cross_attention = True
|
| 246 |
+
model = RobertaForCausalLM(config=config).to(torch_device).eval()
|
| 247 |
+
|
| 248 |
+
# make sure that ids don't start with pad token
|
| 249 |
+
mask = input_ids.ne(config.pad_token_id).long()
|
| 250 |
+
input_ids = input_ids * mask
|
| 251 |
+
|
| 252 |
+
# first forward pass
|
| 253 |
+
outputs = model(
|
| 254 |
+
input_ids,
|
| 255 |
+
attention_mask=input_mask,
|
| 256 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 257 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 258 |
+
use_cache=True,
|
| 259 |
+
)
|
| 260 |
+
past_key_values = outputs.past_key_values
|
| 261 |
+
|
| 262 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 263 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 264 |
+
|
| 265 |
+
# make sure that ids don't start with pad token
|
| 266 |
+
mask = next_tokens.ne(config.pad_token_id).long()
|
| 267 |
+
next_tokens = next_tokens * mask
|
| 268 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 269 |
+
|
| 270 |
+
# append to next input_ids and
|
| 271 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 272 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 273 |
+
|
| 274 |
+
output_from_no_past = model(
|
| 275 |
+
next_input_ids,
|
| 276 |
+
attention_mask=next_attention_mask,
|
| 277 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 278 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 279 |
+
output_hidden_states=True,
|
| 280 |
+
)["hidden_states"][0]
|
| 281 |
+
output_from_past = model(
|
| 282 |
+
next_tokens,
|
| 283 |
+
attention_mask=next_attention_mask,
|
| 284 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 285 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 286 |
+
past_key_values=past_key_values,
|
| 287 |
+
output_hidden_states=True,
|
| 288 |
+
)["hidden_states"][0]
|
| 289 |
+
|
| 290 |
+
# select random slice
|
| 291 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 292 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 293 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 294 |
+
|
| 295 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 296 |
+
|
| 297 |
+
# test that outputs are equal for slice
|
| 298 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 299 |
+
|
| 300 |
+
def create_and_check_for_masked_lm(
|
| 301 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 302 |
+
):
|
| 303 |
+
model = RobertaForMaskedLM(config=config)
|
| 304 |
+
model.to(torch_device)
|
| 305 |
+
model.eval()
|
| 306 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 307 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 308 |
+
|
| 309 |
+
def create_and_check_for_token_classification(
|
| 310 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 311 |
+
):
|
| 312 |
+
config.num_labels = self.num_labels
|
| 313 |
+
model = RobertaForTokenClassification(config=config)
|
| 314 |
+
model.to(torch_device)
|
| 315 |
+
model.eval()
|
| 316 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 317 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 318 |
+
|
| 319 |
+
def create_and_check_for_multiple_choice(
|
| 320 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 321 |
+
):
|
| 322 |
+
config.num_choices = self.num_choices
|
| 323 |
+
model = RobertaForMultipleChoice(config=config)
|
| 324 |
+
model.to(torch_device)
|
| 325 |
+
model.eval()
|
| 326 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 327 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 328 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 329 |
+
result = model(
|
| 330 |
+
multiple_choice_inputs_ids,
|
| 331 |
+
attention_mask=multiple_choice_input_mask,
|
| 332 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 333 |
+
labels=choice_labels,
|
| 334 |
+
)
|
| 335 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 336 |
+
|
| 337 |
+
def create_and_check_for_question_answering(
|
| 338 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 339 |
+
):
|
| 340 |
+
model = RobertaForQuestionAnswering(config=config)
|
| 341 |
+
model.to(torch_device)
|
| 342 |
+
model.eval()
|
| 343 |
+
result = model(
|
| 344 |
+
input_ids,
|
| 345 |
+
attention_mask=input_mask,
|
| 346 |
+
token_type_ids=token_type_ids,
|
| 347 |
+
start_positions=sequence_labels,
|
| 348 |
+
end_positions=sequence_labels,
|
| 349 |
+
)
|
| 350 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 351 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 352 |
+
|
| 353 |
+
def prepare_config_and_inputs_for_common(self):
|
| 354 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 355 |
+
(
|
| 356 |
+
config,
|
| 357 |
+
input_ids,
|
| 358 |
+
token_type_ids,
|
| 359 |
+
input_mask,
|
| 360 |
+
sequence_labels,
|
| 361 |
+
token_labels,
|
| 362 |
+
choice_labels,
|
| 363 |
+
) = config_and_inputs
|
| 364 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 365 |
+
return config, inputs_dict
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
@require_torch
|
| 369 |
+
class RobertaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 370 |
+
all_model_classes = (
|
| 371 |
+
(
|
| 372 |
+
RobertaForCausalLM,
|
| 373 |
+
RobertaForMaskedLM,
|
| 374 |
+
RobertaModel,
|
| 375 |
+
RobertaForSequenceClassification,
|
| 376 |
+
RobertaForTokenClassification,
|
| 377 |
+
RobertaForMultipleChoice,
|
| 378 |
+
RobertaForQuestionAnswering,
|
| 379 |
+
)
|
| 380 |
+
if is_torch_available()
|
| 381 |
+
else ()
|
| 382 |
+
)
|
| 383 |
+
all_generative_model_classes = (RobertaForCausalLM,) if is_torch_available() else ()
|
| 384 |
+
pipeline_model_mapping = (
|
| 385 |
+
{
|
| 386 |
+
"feature-extraction": RobertaModel,
|
| 387 |
+
"fill-mask": RobertaForMaskedLM,
|
| 388 |
+
"question-answering": RobertaForQuestionAnswering,
|
| 389 |
+
"text-classification": RobertaForSequenceClassification,
|
| 390 |
+
"text-generation": RobertaForCausalLM,
|
| 391 |
+
"token-classification": RobertaForTokenClassification,
|
| 392 |
+
"zero-shot": RobertaForSequenceClassification,
|
| 393 |
+
}
|
| 394 |
+
if is_torch_available()
|
| 395 |
+
else {}
|
| 396 |
+
)
|
| 397 |
+
fx_compatible = True
|
| 398 |
+
model_split_percents = [0.5, 0.8, 0.9]
|
| 399 |
+
|
| 400 |
+
def setUp(self):
|
| 401 |
+
self.model_tester = RobertaModelTester(self)
|
| 402 |
+
self.config_tester = ConfigTester(self, config_class=RobertaConfig, hidden_size=37)
|
| 403 |
+
|
| 404 |
+
def test_config(self):
|
| 405 |
+
self.config_tester.run_common_tests()
|
| 406 |
+
|
| 407 |
+
def test_model(self):
|
| 408 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 409 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 410 |
+
|
| 411 |
+
def test_model_various_embeddings(self):
|
| 412 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 413 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 414 |
+
config_and_inputs[0].position_embedding_type = type
|
| 415 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 416 |
+
|
| 417 |
+
def test_model_as_decoder(self):
|
| 418 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 419 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 420 |
+
|
| 421 |
+
def test_model_as_decoder_with_default_input_mask(self):
|
| 422 |
+
# This regression test was failing with PyTorch < 1.3
|
| 423 |
+
(
|
| 424 |
+
config,
|
| 425 |
+
input_ids,
|
| 426 |
+
token_type_ids,
|
| 427 |
+
input_mask,
|
| 428 |
+
sequence_labels,
|
| 429 |
+
token_labels,
|
| 430 |
+
choice_labels,
|
| 431 |
+
encoder_hidden_states,
|
| 432 |
+
encoder_attention_mask,
|
| 433 |
+
) = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 434 |
+
|
| 435 |
+
input_mask = None
|
| 436 |
+
|
| 437 |
+
self.model_tester.create_and_check_model_as_decoder(
|
| 438 |
+
config,
|
| 439 |
+
input_ids,
|
| 440 |
+
token_type_ids,
|
| 441 |
+
input_mask,
|
| 442 |
+
sequence_labels,
|
| 443 |
+
token_labels,
|
| 444 |
+
choice_labels,
|
| 445 |
+
encoder_hidden_states,
|
| 446 |
+
encoder_attention_mask,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
def test_for_causal_lm(self):
|
| 450 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 451 |
+
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
|
| 452 |
+
|
| 453 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 454 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 455 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 456 |
+
|
| 457 |
+
def test_decoder_model_past_with_large_inputs_relative_pos_emb(self):
|
| 458 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 459 |
+
config_and_inputs[0].position_embedding_type = "relative_key"
|
| 460 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 461 |
+
|
| 462 |
+
def test_for_masked_lm(self):
|
| 463 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 464 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 465 |
+
|
| 466 |
+
def test_for_token_classification(self):
|
| 467 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 468 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 469 |
+
|
| 470 |
+
def test_for_multiple_choice(self):
|
| 471 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 472 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 473 |
+
|
| 474 |
+
def test_for_question_answering(self):
|
| 475 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 476 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 477 |
+
|
| 478 |
+
@slow
|
| 479 |
+
def test_model_from_pretrained(self):
|
| 480 |
+
for model_name in ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 481 |
+
model = RobertaModel.from_pretrained(model_name)
|
| 482 |
+
self.assertIsNotNone(model)
|
| 483 |
+
|
| 484 |
+
def test_create_position_ids_respects_padding_index(self):
|
| 485 |
+
"""Ensure that the default position ids only assign a sequential . This is a regression
|
| 486 |
+
test for https://github.com/huggingface/transformers/issues/1761
|
| 487 |
+
|
| 488 |
+
The position ids should be masked with the embedding object's padding index. Therefore, the
|
| 489 |
+
first available non-padding position index is RobertaEmbeddings.padding_idx + 1
|
| 490 |
+
"""
|
| 491 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 492 |
+
model = RobertaEmbeddings(config=config)
|
| 493 |
+
|
| 494 |
+
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
|
| 495 |
+
expected_positions = torch.as_tensor(
|
| 496 |
+
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
|
| 500 |
+
self.assertEqual(position_ids.shape, expected_positions.shape)
|
| 501 |
+
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
|
| 502 |
+
|
| 503 |
+
def test_create_position_ids_from_inputs_embeds(self):
|
| 504 |
+
"""Ensure that the default position ids only assign a sequential . This is a regression
|
| 505 |
+
test for https://github.com/huggingface/transformers/issues/1761
|
| 506 |
+
|
| 507 |
+
The position ids should be masked with the embedding object's padding index. Therefore, the
|
| 508 |
+
first available non-padding position index is RobertaEmbeddings.padding_idx + 1
|
| 509 |
+
"""
|
| 510 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 511 |
+
embeddings = RobertaEmbeddings(config=config)
|
| 512 |
+
|
| 513 |
+
inputs_embeds = torch.empty(2, 4, 30)
|
| 514 |
+
expected_single_positions = [
|
| 515 |
+
0 + embeddings.padding_idx + 1,
|
| 516 |
+
1 + embeddings.padding_idx + 1,
|
| 517 |
+
2 + embeddings.padding_idx + 1,
|
| 518 |
+
3 + embeddings.padding_idx + 1,
|
| 519 |
+
]
|
| 520 |
+
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
|
| 521 |
+
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 522 |
+
self.assertEqual(position_ids.shape, expected_positions.shape)
|
| 523 |
+
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
@require_torch
|
| 527 |
+
class RobertaModelIntegrationTest(TestCasePlus):
|
| 528 |
+
@slow
|
| 529 |
+
def test_inference_masked_lm(self):
|
| 530 |
+
model = RobertaForMaskedLM.from_pretrained("roberta-base")
|
| 531 |
+
|
| 532 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 533 |
+
with torch.no_grad():
|
| 534 |
+
output = model(input_ids)[0]
|
| 535 |
+
expected_shape = torch.Size((1, 11, 50265))
|
| 536 |
+
self.assertEqual(output.shape, expected_shape)
|
| 537 |
+
# compare the actual values for a slice.
|
| 538 |
+
expected_slice = torch.tensor(
|
| 539 |
+
[[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]]
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.base')
|
| 543 |
+
# roberta.eval()
|
| 544 |
+
# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
|
| 545 |
+
|
| 546 |
+
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
|
| 547 |
+
|
| 548 |
+
@slow
|
| 549 |
+
def test_inference_no_head(self):
|
| 550 |
+
model = RobertaModel.from_pretrained("roberta-base")
|
| 551 |
+
|
| 552 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 553 |
+
with torch.no_grad():
|
| 554 |
+
output = model(input_ids)[0]
|
| 555 |
+
# compare the actual values for a slice.
|
| 556 |
+
expected_slice = torch.tensor(
|
| 557 |
+
[[[-0.0231, 0.0782, 0.0074], [-0.1854, 0.0540, -0.0175], [0.0548, 0.0799, 0.1687]]]
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.base')
|
| 561 |
+
# roberta.eval()
|
| 562 |
+
# expected_slice = roberta.extract_features(input_ids)[:, :3, :3].detach()
|
| 563 |
+
|
| 564 |
+
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
|
| 565 |
+
|
| 566 |
+
@slow
|
| 567 |
+
def test_inference_classification_head(self):
|
| 568 |
+
model = RobertaForSequenceClassification.from_pretrained("roberta-large-mnli")
|
| 569 |
+
|
| 570 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 571 |
+
with torch.no_grad():
|
| 572 |
+
output = model(input_ids)[0]
|
| 573 |
+
expected_shape = torch.Size((1, 3))
|
| 574 |
+
self.assertEqual(output.shape, expected_shape)
|
| 575 |
+
expected_tensor = torch.tensor([[-0.9469, 0.3913, 0.5118]])
|
| 576 |
+
|
| 577 |
+
# roberta = torch.hub.load('pytorch/fairseq', 'roberta.large.mnli')
|
| 578 |
+
# roberta.eval()
|
| 579 |
+
# expected_tensor = roberta.predict("mnli", input_ids, return_logits=True).detach()
|
| 580 |
+
|
| 581 |
+
self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_tf_roberta.py
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import RobertaConfig, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import numpy
|
| 31 |
+
import tensorflow as tf
|
| 32 |
+
|
| 33 |
+
from transformers.models.roberta.modeling_tf_roberta import (
|
| 34 |
+
TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 35 |
+
TFRobertaForCausalLM,
|
| 36 |
+
TFRobertaForMaskedLM,
|
| 37 |
+
TFRobertaForMultipleChoice,
|
| 38 |
+
TFRobertaForQuestionAnswering,
|
| 39 |
+
TFRobertaForSequenceClassification,
|
| 40 |
+
TFRobertaForTokenClassification,
|
| 41 |
+
TFRobertaModel,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TFRobertaModelTester:
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
parent,
|
| 49 |
+
):
|
| 50 |
+
self.parent = parent
|
| 51 |
+
self.batch_size = 13
|
| 52 |
+
self.seq_length = 7
|
| 53 |
+
self.is_training = True
|
| 54 |
+
self.use_input_mask = True
|
| 55 |
+
self.use_token_type_ids = True
|
| 56 |
+
self.use_labels = True
|
| 57 |
+
self.vocab_size = 99
|
| 58 |
+
self.hidden_size = 32
|
| 59 |
+
self.num_hidden_layers = 2
|
| 60 |
+
self.num_attention_heads = 4
|
| 61 |
+
self.intermediate_size = 37
|
| 62 |
+
self.hidden_act = "gelu"
|
| 63 |
+
self.hidden_dropout_prob = 0.1
|
| 64 |
+
self.attention_probs_dropout_prob = 0.1
|
| 65 |
+
self.max_position_embeddings = 512
|
| 66 |
+
self.type_vocab_size = 16
|
| 67 |
+
self.type_sequence_label_size = 2
|
| 68 |
+
self.initializer_range = 0.02
|
| 69 |
+
self.num_labels = 3
|
| 70 |
+
self.num_choices = 4
|
| 71 |
+
self.scope = None
|
| 72 |
+
|
| 73 |
+
def prepare_config_and_inputs(self):
|
| 74 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 75 |
+
|
| 76 |
+
input_mask = None
|
| 77 |
+
if self.use_input_mask:
|
| 78 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 79 |
+
|
| 80 |
+
token_type_ids = None
|
| 81 |
+
if self.use_token_type_ids:
|
| 82 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 83 |
+
|
| 84 |
+
sequence_labels = None
|
| 85 |
+
token_labels = None
|
| 86 |
+
choice_labels = None
|
| 87 |
+
if self.use_labels:
|
| 88 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 89 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 90 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 91 |
+
|
| 92 |
+
config = RobertaConfig(
|
| 93 |
+
vocab_size=self.vocab_size,
|
| 94 |
+
hidden_size=self.hidden_size,
|
| 95 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 96 |
+
num_attention_heads=self.num_attention_heads,
|
| 97 |
+
intermediate_size=self.intermediate_size,
|
| 98 |
+
hidden_act=self.hidden_act,
|
| 99 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 100 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 101 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 102 |
+
type_vocab_size=self.type_vocab_size,
|
| 103 |
+
initializer_range=self.initializer_range,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 107 |
+
|
| 108 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 109 |
+
(
|
| 110 |
+
config,
|
| 111 |
+
input_ids,
|
| 112 |
+
token_type_ids,
|
| 113 |
+
input_mask,
|
| 114 |
+
sequence_labels,
|
| 115 |
+
token_labels,
|
| 116 |
+
choice_labels,
|
| 117 |
+
) = self.prepare_config_and_inputs()
|
| 118 |
+
|
| 119 |
+
config.is_decoder = True
|
| 120 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 121 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 122 |
+
|
| 123 |
+
return (
|
| 124 |
+
config,
|
| 125 |
+
input_ids,
|
| 126 |
+
token_type_ids,
|
| 127 |
+
input_mask,
|
| 128 |
+
sequence_labels,
|
| 129 |
+
token_labels,
|
| 130 |
+
choice_labels,
|
| 131 |
+
encoder_hidden_states,
|
| 132 |
+
encoder_attention_mask,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def create_and_check_model(
|
| 136 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 137 |
+
):
|
| 138 |
+
model = TFRobertaModel(config=config)
|
| 139 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 140 |
+
result = model(inputs)
|
| 141 |
+
|
| 142 |
+
inputs = [input_ids, input_mask]
|
| 143 |
+
result = model(inputs)
|
| 144 |
+
|
| 145 |
+
result = model(input_ids)
|
| 146 |
+
|
| 147 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 148 |
+
|
| 149 |
+
def create_and_check_causal_lm_base_model(
|
| 150 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 151 |
+
):
|
| 152 |
+
config.is_decoder = True
|
| 153 |
+
|
| 154 |
+
model = TFRobertaModel(config=config)
|
| 155 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 156 |
+
result = model(inputs)
|
| 157 |
+
|
| 158 |
+
inputs = [input_ids, input_mask]
|
| 159 |
+
result = model(inputs)
|
| 160 |
+
|
| 161 |
+
result = model(input_ids)
|
| 162 |
+
|
| 163 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 164 |
+
|
| 165 |
+
def create_and_check_model_as_decoder(
|
| 166 |
+
self,
|
| 167 |
+
config,
|
| 168 |
+
input_ids,
|
| 169 |
+
token_type_ids,
|
| 170 |
+
input_mask,
|
| 171 |
+
sequence_labels,
|
| 172 |
+
token_labels,
|
| 173 |
+
choice_labels,
|
| 174 |
+
encoder_hidden_states,
|
| 175 |
+
encoder_attention_mask,
|
| 176 |
+
):
|
| 177 |
+
config.add_cross_attention = True
|
| 178 |
+
|
| 179 |
+
model = TFRobertaModel(config=config)
|
| 180 |
+
inputs = {
|
| 181 |
+
"input_ids": input_ids,
|
| 182 |
+
"attention_mask": input_mask,
|
| 183 |
+
"token_type_ids": token_type_ids,
|
| 184 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 185 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 186 |
+
}
|
| 187 |
+
result = model(inputs)
|
| 188 |
+
|
| 189 |
+
inputs = [input_ids, input_mask]
|
| 190 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 191 |
+
|
| 192 |
+
# Also check the case where encoder outputs are not passed
|
| 193 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 194 |
+
|
| 195 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 196 |
+
|
| 197 |
+
def create_and_check_causal_lm_model(
|
| 198 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 199 |
+
):
|
| 200 |
+
config.is_decoder = True
|
| 201 |
+
|
| 202 |
+
model = TFRobertaForCausalLM(config=config)
|
| 203 |
+
inputs = {
|
| 204 |
+
"input_ids": input_ids,
|
| 205 |
+
"attention_mask": input_mask,
|
| 206 |
+
"token_type_ids": token_type_ids,
|
| 207 |
+
}
|
| 208 |
+
prediction_scores = model(inputs)["logits"]
|
| 209 |
+
self.parent.assertListEqual(
|
| 210 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def create_and_check_causal_lm_model_as_decoder(
|
| 214 |
+
self,
|
| 215 |
+
config,
|
| 216 |
+
input_ids,
|
| 217 |
+
token_type_ids,
|
| 218 |
+
input_mask,
|
| 219 |
+
sequence_labels,
|
| 220 |
+
token_labels,
|
| 221 |
+
choice_labels,
|
| 222 |
+
encoder_hidden_states,
|
| 223 |
+
encoder_attention_mask,
|
| 224 |
+
):
|
| 225 |
+
config.add_cross_attention = True
|
| 226 |
+
|
| 227 |
+
model = TFRobertaForCausalLM(config=config)
|
| 228 |
+
inputs = {
|
| 229 |
+
"input_ids": input_ids,
|
| 230 |
+
"attention_mask": input_mask,
|
| 231 |
+
"token_type_ids": token_type_ids,
|
| 232 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 233 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 234 |
+
}
|
| 235 |
+
result = model(inputs)
|
| 236 |
+
|
| 237 |
+
inputs = [input_ids, input_mask]
|
| 238 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 239 |
+
|
| 240 |
+
prediction_scores = result["logits"]
|
| 241 |
+
self.parent.assertListEqual(
|
| 242 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
def create_and_check_causal_lm_model_past(
|
| 246 |
+
self,
|
| 247 |
+
config,
|
| 248 |
+
input_ids,
|
| 249 |
+
token_type_ids,
|
| 250 |
+
input_mask,
|
| 251 |
+
sequence_labels,
|
| 252 |
+
token_labels,
|
| 253 |
+
choice_labels,
|
| 254 |
+
):
|
| 255 |
+
config.is_decoder = True
|
| 256 |
+
|
| 257 |
+
model = TFRobertaForCausalLM(config=config)
|
| 258 |
+
|
| 259 |
+
# special to `RobertaEmbeddings` in `Roberta`:
|
| 260 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 261 |
+
# (TFRobertaEmbeddings.create_position_ids_from_input_ids)
|
| 262 |
+
# - `1` here is `TFRobertaEmbeddings.padding_idx`
|
| 263 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 264 |
+
|
| 265 |
+
# first forward pass
|
| 266 |
+
outputs = model(input_ids, use_cache=True)
|
| 267 |
+
outputs_use_cache_conf = model(input_ids)
|
| 268 |
+
outputs_no_past = model(input_ids, use_cache=False)
|
| 269 |
+
|
| 270 |
+
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
|
| 271 |
+
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
|
| 272 |
+
|
| 273 |
+
past_key_values = outputs.past_key_values
|
| 274 |
+
|
| 275 |
+
# create hypothetical next token and extent to next_input_ids
|
| 276 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 277 |
+
|
| 278 |
+
# append to next input_ids and attn_mask
|
| 279 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 280 |
+
|
| 281 |
+
output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0]
|
| 282 |
+
output_from_past = model(
|
| 283 |
+
next_tokens, past_key_values=past_key_values, output_hidden_states=True
|
| 284 |
+
).hidden_states[0]
|
| 285 |
+
|
| 286 |
+
# select random slice
|
| 287 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 288 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 289 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 290 |
+
|
| 291 |
+
# test that outputs are equal for slice
|
| 292 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 293 |
+
|
| 294 |
+
def create_and_check_causal_lm_model_past_with_attn_mask(
|
| 295 |
+
self,
|
| 296 |
+
config,
|
| 297 |
+
input_ids,
|
| 298 |
+
token_type_ids,
|
| 299 |
+
input_mask,
|
| 300 |
+
sequence_labels,
|
| 301 |
+
token_labels,
|
| 302 |
+
choice_labels,
|
| 303 |
+
):
|
| 304 |
+
config.is_decoder = True
|
| 305 |
+
|
| 306 |
+
model = TFRobertaForCausalLM(config=config)
|
| 307 |
+
|
| 308 |
+
# special to `RobertaEmbeddings` in `Roberta`:
|
| 309 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 310 |
+
# (TFRobertaEmbeddings.create_position_ids_from_input_ids)
|
| 311 |
+
# - `1` here is `TFRobertaEmbeddings.padding_idx`
|
| 312 |
+
# avoid `padding_idx` in the past
|
| 313 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 314 |
+
|
| 315 |
+
# create attention mask
|
| 316 |
+
half_seq_length = self.seq_length // 2
|
| 317 |
+
attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32)
|
| 318 |
+
attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32)
|
| 319 |
+
attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1)
|
| 320 |
+
|
| 321 |
+
# first forward pass
|
| 322 |
+
outputs = model(input_ids, attention_mask=attn_mask, use_cache=True)
|
| 323 |
+
|
| 324 |
+
# create hypothetical next token and extent to next_input_ids
|
| 325 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 326 |
+
|
| 327 |
+
past_key_values = outputs.past_key_values
|
| 328 |
+
|
| 329 |
+
# change a random masked slice from input_ids
|
| 330 |
+
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1
|
| 331 |
+
random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size)
|
| 332 |
+
vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change)
|
| 333 |
+
condition = tf.transpose(
|
| 334 |
+
tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size))
|
| 335 |
+
)
|
| 336 |
+
input_ids = tf.where(condition, random_other_next_tokens, input_ids)
|
| 337 |
+
# avoid `padding_idx` in the past
|
| 338 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 339 |
+
|
| 340 |
+
# append to next input_ids and
|
| 341 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 342 |
+
attn_mask = tf.concat(
|
| 343 |
+
[attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)],
|
| 344 |
+
axis=1,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
output_from_no_past = model(
|
| 348 |
+
next_input_ids,
|
| 349 |
+
attention_mask=attn_mask,
|
| 350 |
+
output_hidden_states=True,
|
| 351 |
+
).hidden_states[0]
|
| 352 |
+
output_from_past = model(
|
| 353 |
+
next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True
|
| 354 |
+
).hidden_states[0]
|
| 355 |
+
|
| 356 |
+
# select random slice
|
| 357 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 358 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 359 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 360 |
+
|
| 361 |
+
# test that outputs are equal for slice
|
| 362 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 363 |
+
|
| 364 |
+
def create_and_check_causal_lm_model_past_large_inputs(
|
| 365 |
+
self,
|
| 366 |
+
config,
|
| 367 |
+
input_ids,
|
| 368 |
+
token_type_ids,
|
| 369 |
+
input_mask,
|
| 370 |
+
sequence_labels,
|
| 371 |
+
token_labels,
|
| 372 |
+
choice_labels,
|
| 373 |
+
):
|
| 374 |
+
config.is_decoder = True
|
| 375 |
+
|
| 376 |
+
model = TFRobertaForCausalLM(config=config)
|
| 377 |
+
|
| 378 |
+
# special to `RobertaEmbeddings` in `Roberta`:
|
| 379 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 380 |
+
# (TFRobertaEmbeddings.create_position_ids_from_input_ids)
|
| 381 |
+
# - `1` here is `TFRobertaEmbeddings.padding_idx`
|
| 382 |
+
# avoid `padding_idx` in the past
|
| 383 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 384 |
+
|
| 385 |
+
input_ids = input_ids[:1, :]
|
| 386 |
+
input_mask = input_mask[:1, :]
|
| 387 |
+
self.batch_size = 1
|
| 388 |
+
|
| 389 |
+
# first forward pass
|
| 390 |
+
outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
|
| 391 |
+
past_key_values = outputs.past_key_values
|
| 392 |
+
|
| 393 |
+
# create hypothetical next token and extent to next_input_ids
|
| 394 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 395 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 396 |
+
|
| 397 |
+
# append to next input_ids and
|
| 398 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 399 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 400 |
+
|
| 401 |
+
output_from_no_past = model(
|
| 402 |
+
next_input_ids,
|
| 403 |
+
attention_mask=next_attention_mask,
|
| 404 |
+
output_hidden_states=True,
|
| 405 |
+
).hidden_states[0]
|
| 406 |
+
output_from_past = model(
|
| 407 |
+
next_tokens,
|
| 408 |
+
attention_mask=next_attention_mask,
|
| 409 |
+
past_key_values=past_key_values,
|
| 410 |
+
output_hidden_states=True,
|
| 411 |
+
).hidden_states[0]
|
| 412 |
+
|
| 413 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 414 |
+
|
| 415 |
+
# select random slice
|
| 416 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 417 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 418 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 419 |
+
|
| 420 |
+
# test that outputs are equal for slice
|
| 421 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 422 |
+
|
| 423 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 424 |
+
self,
|
| 425 |
+
config,
|
| 426 |
+
input_ids,
|
| 427 |
+
token_type_ids,
|
| 428 |
+
input_mask,
|
| 429 |
+
sequence_labels,
|
| 430 |
+
token_labels,
|
| 431 |
+
choice_labels,
|
| 432 |
+
encoder_hidden_states,
|
| 433 |
+
encoder_attention_mask,
|
| 434 |
+
):
|
| 435 |
+
config.add_cross_attention = True
|
| 436 |
+
|
| 437 |
+
model = TFRobertaForCausalLM(config=config)
|
| 438 |
+
|
| 439 |
+
# special to `RobertaEmbeddings` in `Roberta`:
|
| 440 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 441 |
+
# (TFRobertaEmbeddings.create_position_ids_from_input_ids)
|
| 442 |
+
# - `1` here is `TFRobertaEmbeddings.padding_idx`
|
| 443 |
+
# avoid `padding_idx` in the past
|
| 444 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 445 |
+
|
| 446 |
+
input_ids = input_ids[:1, :]
|
| 447 |
+
input_mask = input_mask[:1, :]
|
| 448 |
+
encoder_hidden_states = encoder_hidden_states[:1, :, :]
|
| 449 |
+
encoder_attention_mask = encoder_attention_mask[:1, :]
|
| 450 |
+
self.batch_size = 1
|
| 451 |
+
|
| 452 |
+
# first forward pass
|
| 453 |
+
outputs = model(
|
| 454 |
+
input_ids,
|
| 455 |
+
attention_mask=input_mask,
|
| 456 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 457 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 458 |
+
use_cache=True,
|
| 459 |
+
)
|
| 460 |
+
past_key_values = outputs.past_key_values
|
| 461 |
+
|
| 462 |
+
# create hypothetical next token and extent to next_input_ids
|
| 463 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 464 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 465 |
+
|
| 466 |
+
# append to next input_ids and
|
| 467 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 468 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 469 |
+
|
| 470 |
+
output_from_no_past = model(
|
| 471 |
+
next_input_ids,
|
| 472 |
+
attention_mask=next_attention_mask,
|
| 473 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 474 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 475 |
+
output_hidden_states=True,
|
| 476 |
+
).hidden_states[0]
|
| 477 |
+
output_from_past = model(
|
| 478 |
+
next_tokens,
|
| 479 |
+
attention_mask=next_attention_mask,
|
| 480 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 481 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 482 |
+
past_key_values=past_key_values,
|
| 483 |
+
output_hidden_states=True,
|
| 484 |
+
).hidden_states[0]
|
| 485 |
+
|
| 486 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 487 |
+
|
| 488 |
+
# select random slice
|
| 489 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 490 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 491 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 492 |
+
|
| 493 |
+
# test that outputs are equal for slice
|
| 494 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 495 |
+
|
| 496 |
+
def create_and_check_for_masked_lm(
|
| 497 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 498 |
+
):
|
| 499 |
+
model = TFRobertaForMaskedLM(config=config)
|
| 500 |
+
result = model([input_ids, input_mask, token_type_ids])
|
| 501 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 502 |
+
|
| 503 |
+
def create_and_check_for_token_classification(
|
| 504 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 505 |
+
):
|
| 506 |
+
config.num_labels = self.num_labels
|
| 507 |
+
model = TFRobertaForTokenClassification(config=config)
|
| 508 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 509 |
+
result = model(inputs)
|
| 510 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 511 |
+
|
| 512 |
+
def create_and_check_for_question_answering(
|
| 513 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 514 |
+
):
|
| 515 |
+
model = TFRobertaForQuestionAnswering(config=config)
|
| 516 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 517 |
+
result = model(inputs)
|
| 518 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 519 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 520 |
+
|
| 521 |
+
def create_and_check_for_multiple_choice(
|
| 522 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 523 |
+
):
|
| 524 |
+
config.num_choices = self.num_choices
|
| 525 |
+
model = TFRobertaForMultipleChoice(config=config)
|
| 526 |
+
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
|
| 527 |
+
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
|
| 528 |
+
multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
|
| 529 |
+
inputs = {
|
| 530 |
+
"input_ids": multiple_choice_inputs_ids,
|
| 531 |
+
"attention_mask": multiple_choice_input_mask,
|
| 532 |
+
"token_type_ids": multiple_choice_token_type_ids,
|
| 533 |
+
}
|
| 534 |
+
result = model(inputs)
|
| 535 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 536 |
+
|
| 537 |
+
def prepare_config_and_inputs_for_common(self):
|
| 538 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 539 |
+
(
|
| 540 |
+
config,
|
| 541 |
+
input_ids,
|
| 542 |
+
token_type_ids,
|
| 543 |
+
input_mask,
|
| 544 |
+
sequence_labels,
|
| 545 |
+
token_labels,
|
| 546 |
+
choice_labels,
|
| 547 |
+
) = config_and_inputs
|
| 548 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 549 |
+
return config, inputs_dict
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
@require_tf
|
| 553 |
+
class TFRobertaModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 554 |
+
all_model_classes = (
|
| 555 |
+
(
|
| 556 |
+
TFRobertaModel,
|
| 557 |
+
TFRobertaForCausalLM,
|
| 558 |
+
TFRobertaForMaskedLM,
|
| 559 |
+
TFRobertaForSequenceClassification,
|
| 560 |
+
TFRobertaForTokenClassification,
|
| 561 |
+
TFRobertaForQuestionAnswering,
|
| 562 |
+
)
|
| 563 |
+
if is_tf_available()
|
| 564 |
+
else ()
|
| 565 |
+
)
|
| 566 |
+
pipeline_model_mapping = (
|
| 567 |
+
{
|
| 568 |
+
"feature-extraction": TFRobertaModel,
|
| 569 |
+
"fill-mask": TFRobertaForMaskedLM,
|
| 570 |
+
"question-answering": TFRobertaForQuestionAnswering,
|
| 571 |
+
"text-classification": TFRobertaForSequenceClassification,
|
| 572 |
+
"text-generation": TFRobertaForCausalLM,
|
| 573 |
+
"token-classification": TFRobertaForTokenClassification,
|
| 574 |
+
"zero-shot": TFRobertaForSequenceClassification,
|
| 575 |
+
}
|
| 576 |
+
if is_tf_available()
|
| 577 |
+
else {}
|
| 578 |
+
)
|
| 579 |
+
test_head_masking = False
|
| 580 |
+
test_onnx = False
|
| 581 |
+
|
| 582 |
+
def setUp(self):
|
| 583 |
+
self.model_tester = TFRobertaModelTester(self)
|
| 584 |
+
self.config_tester = ConfigTester(self, config_class=RobertaConfig, hidden_size=37)
|
| 585 |
+
|
| 586 |
+
def test_config(self):
|
| 587 |
+
self.config_tester.run_common_tests()
|
| 588 |
+
|
| 589 |
+
def test_model(self):
|
| 590 |
+
"""Test the base model"""
|
| 591 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 592 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 593 |
+
|
| 594 |
+
def test_causal_lm_base_model(self):
|
| 595 |
+
"""Test the base model of the causal LM model
|
| 596 |
+
|
| 597 |
+
is_deocder=True, no cross_attention, no encoder outputs
|
| 598 |
+
"""
|
| 599 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 600 |
+
self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs)
|
| 601 |
+
|
| 602 |
+
def test_model_as_decoder(self):
|
| 603 |
+
"""Test the base model as a decoder (of an encoder-decoder architecture)
|
| 604 |
+
|
| 605 |
+
is_deocder=True + cross_attention + pass encoder outputs
|
| 606 |
+
"""
|
| 607 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 608 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 609 |
+
|
| 610 |
+
def test_for_masked_lm(self):
|
| 611 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 612 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 613 |
+
|
| 614 |
+
def test_for_causal_lm(self):
|
| 615 |
+
"""Test the causal LM model"""
|
| 616 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 617 |
+
self.model_tester.create_and_check_causal_lm_model(*config_and_inputs)
|
| 618 |
+
|
| 619 |
+
def test_causal_lm_model_as_decoder(self):
|
| 620 |
+
"""Test the causal LM model as a decoder"""
|
| 621 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 622 |
+
self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs)
|
| 623 |
+
|
| 624 |
+
def test_causal_lm_model_past(self):
|
| 625 |
+
"""Test causal LM model with `past_key_values`"""
|
| 626 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 627 |
+
self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs)
|
| 628 |
+
|
| 629 |
+
def test_causal_lm_model_past_with_attn_mask(self):
|
| 630 |
+
"""Test the causal LM model with `past_key_values` and `attention_mask`"""
|
| 631 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 632 |
+
self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs)
|
| 633 |
+
|
| 634 |
+
def test_causal_lm_model_past_with_large_inputs(self):
|
| 635 |
+
"""Test the causal LM model with `past_key_values` and a longer decoder sequence length"""
|
| 636 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 637 |
+
self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs)
|
| 638 |
+
|
| 639 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 640 |
+
"""Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention"""
|
| 641 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 642 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 643 |
+
|
| 644 |
+
def test_for_token_classification(self):
|
| 645 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 646 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 647 |
+
|
| 648 |
+
def test_for_question_answering(self):
|
| 649 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 650 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 651 |
+
|
| 652 |
+
def test_for_multiple_choice(self):
|
| 653 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 654 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 655 |
+
|
| 656 |
+
@slow
|
| 657 |
+
def test_model_from_pretrained(self):
|
| 658 |
+
for model_name in TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 659 |
+
model = TFRobertaModel.from_pretrained(model_name)
|
| 660 |
+
self.assertIsNotNone(model)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
@require_tf
|
| 664 |
+
@require_sentencepiece
|
| 665 |
+
@require_tokenizers
|
| 666 |
+
class TFRobertaModelIntegrationTest(unittest.TestCase):
|
| 667 |
+
@slow
|
| 668 |
+
def test_inference_masked_lm(self):
|
| 669 |
+
model = TFRobertaForMaskedLM.from_pretrained("roberta-base")
|
| 670 |
+
|
| 671 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 672 |
+
output = model(input_ids)[0]
|
| 673 |
+
expected_shape = [1, 11, 50265]
|
| 674 |
+
self.assertEqual(list(output.numpy().shape), expected_shape)
|
| 675 |
+
# compare the actual values for a slice.
|
| 676 |
+
expected_slice = tf.constant(
|
| 677 |
+
[[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]]
|
| 678 |
+
)
|
| 679 |
+
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4))
|
| 680 |
+
|
| 681 |
+
@slow
|
| 682 |
+
def test_inference_no_head(self):
|
| 683 |
+
model = TFRobertaModel.from_pretrained("roberta-base")
|
| 684 |
+
|
| 685 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 686 |
+
output = model(input_ids)[0]
|
| 687 |
+
# compare the actual values for a slice.
|
| 688 |
+
expected_slice = tf.constant(
|
| 689 |
+
[[[-0.0231, 0.0782, 0.0074], [-0.1854, 0.0540, -0.0175], [0.0548, 0.0799, 0.1687]]]
|
| 690 |
+
)
|
| 691 |
+
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4))
|
| 692 |
+
|
| 693 |
+
@slow
|
| 694 |
+
def test_inference_classification_head(self):
|
| 695 |
+
model = TFRobertaForSequenceClassification.from_pretrained("roberta-large-mnli")
|
| 696 |
+
|
| 697 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 698 |
+
output = model(input_ids)[0]
|
| 699 |
+
expected_shape = [1, 3]
|
| 700 |
+
self.assertEqual(list(output.numpy().shape), expected_shape)
|
| 701 |
+
expected_tensor = tf.constant([[-0.9469, 0.3913, 0.5118]])
|
| 702 |
+
self.assertTrue(numpy.allclose(output.numpy(), expected_tensor.numpy(), atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_tokenization_roberta.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import itertools
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import unittest
|
| 21 |
+
|
| 22 |
+
from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
|
| 23 |
+
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
|
| 24 |
+
from transformers.testing_utils import require_tokenizers, slow
|
| 25 |
+
|
| 26 |
+
from ...test_tokenization_common import TokenizerTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@require_tokenizers
|
| 30 |
+
class RobertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 31 |
+
tokenizer_class = RobertaTokenizer
|
| 32 |
+
rust_tokenizer_class = RobertaTokenizerFast
|
| 33 |
+
test_rust_tokenizer = True
|
| 34 |
+
from_pretrained_kwargs = {"cls_token": "<s>"}
|
| 35 |
+
|
| 36 |
+
def setUp(self):
|
| 37 |
+
super().setUp()
|
| 38 |
+
|
| 39 |
+
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
|
| 40 |
+
vocab = [
|
| 41 |
+
"l",
|
| 42 |
+
"o",
|
| 43 |
+
"w",
|
| 44 |
+
"e",
|
| 45 |
+
"r",
|
| 46 |
+
"s",
|
| 47 |
+
"t",
|
| 48 |
+
"i",
|
| 49 |
+
"d",
|
| 50 |
+
"n",
|
| 51 |
+
"\u0120",
|
| 52 |
+
"\u0120l",
|
| 53 |
+
"\u0120n",
|
| 54 |
+
"\u0120lo",
|
| 55 |
+
"\u0120low",
|
| 56 |
+
"er",
|
| 57 |
+
"\u0120lowest",
|
| 58 |
+
"\u0120newer",
|
| 59 |
+
"\u0120wider",
|
| 60 |
+
"<unk>",
|
| 61 |
+
]
|
| 62 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 63 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 64 |
+
self.special_tokens_map = {"unk_token": "<unk>"}
|
| 65 |
+
|
| 66 |
+
self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
|
| 67 |
+
self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
|
| 68 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 69 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 70 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 71 |
+
fp.write("\n".join(merges))
|
| 72 |
+
|
| 73 |
+
def get_tokenizer(self, **kwargs):
|
| 74 |
+
kwargs.update(self.special_tokens_map)
|
| 75 |
+
return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
|
| 76 |
+
|
| 77 |
+
def get_rust_tokenizer(self, **kwargs):
|
| 78 |
+
kwargs.update(self.special_tokens_map)
|
| 79 |
+
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
|
| 80 |
+
|
| 81 |
+
def get_input_output_texts(self, tokenizer):
|
| 82 |
+
input_text = "lower newer"
|
| 83 |
+
output_text = "lower newer"
|
| 84 |
+
return input_text, output_text
|
| 85 |
+
|
| 86 |
+
def test_full_tokenizer(self):
|
| 87 |
+
tokenizer = self.tokenizer_class(self.vocab_file, self.merges_file, **self.special_tokens_map)
|
| 88 |
+
text = "lower newer"
|
| 89 |
+
bpe_tokens = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
|
| 90 |
+
tokens = tokenizer.tokenize(text) # , add_prefix_space=True)
|
| 91 |
+
self.assertListEqual(tokens, bpe_tokens)
|
| 92 |
+
|
| 93 |
+
input_tokens = tokens + [tokenizer.unk_token]
|
| 94 |
+
input_bpe_tokens = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
|
| 95 |
+
self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
|
| 96 |
+
|
| 97 |
+
def roberta_dict_integration_testing(self):
|
| 98 |
+
tokenizer = self.get_tokenizer()
|
| 99 |
+
|
| 100 |
+
self.assertListEqual(tokenizer.encode("Hello world!", add_special_tokens=False), [0, 31414, 232, 328, 2])
|
| 101 |
+
self.assertListEqual(
|
| 102 |
+
tokenizer.encode("Hello world! cécé herlolip 418", add_special_tokens=False),
|
| 103 |
+
[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2],
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
@slow
|
| 107 |
+
def test_sequence_builders(self):
|
| 108 |
+
tokenizer = self.tokenizer_class.from_pretrained("roberta-base")
|
| 109 |
+
|
| 110 |
+
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
| 111 |
+
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
| 112 |
+
|
| 113 |
+
encoded_text_from_decode = tokenizer.encode(
|
| 114 |
+
"sequence builders", add_special_tokens=True, add_prefix_space=False
|
| 115 |
+
)
|
| 116 |
+
encoded_pair_from_decode = tokenizer.encode(
|
| 117 |
+
"sequence builders", "multi-sequence build", add_special_tokens=True, add_prefix_space=False
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 121 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 122 |
+
|
| 123 |
+
assert encoded_sentence == encoded_text_from_decode
|
| 124 |
+
assert encoded_pair == encoded_pair_from_decode
|
| 125 |
+
|
| 126 |
+
def test_space_encoding(self):
|
| 127 |
+
tokenizer = self.get_tokenizer()
|
| 128 |
+
|
| 129 |
+
sequence = "Encode this sequence."
|
| 130 |
+
space_encoding = tokenizer.byte_encoder[" ".encode("utf-8")[0]]
|
| 131 |
+
|
| 132 |
+
# Testing encoder arguments
|
| 133 |
+
encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=False)
|
| 134 |
+
first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
|
| 135 |
+
self.assertNotEqual(first_char, space_encoding)
|
| 136 |
+
|
| 137 |
+
encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True)
|
| 138 |
+
first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0]
|
| 139 |
+
self.assertEqual(first_char, space_encoding)
|
| 140 |
+
|
| 141 |
+
tokenizer.add_special_tokens({"bos_token": "<s>"})
|
| 142 |
+
encoded = tokenizer.encode(sequence, add_special_tokens=True)
|
| 143 |
+
first_char = tokenizer.convert_ids_to_tokens(encoded[1])[0]
|
| 144 |
+
self.assertNotEqual(first_char, space_encoding)
|
| 145 |
+
|
| 146 |
+
# Testing spaces after special tokens
|
| 147 |
+
mask = "<mask>"
|
| 148 |
+
tokenizer.add_special_tokens(
|
| 149 |
+
{"mask_token": AddedToken(mask, lstrip=True, rstrip=False)}
|
| 150 |
+
) # mask token has a left space
|
| 151 |
+
mask_ind = tokenizer.convert_tokens_to_ids(mask)
|
| 152 |
+
|
| 153 |
+
sequence = "Encode <mask> sequence"
|
| 154 |
+
sequence_nospace = "Encode <mask>sequence"
|
| 155 |
+
|
| 156 |
+
encoded = tokenizer.encode(sequence)
|
| 157 |
+
mask_loc = encoded.index(mask_ind)
|
| 158 |
+
first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
|
| 159 |
+
self.assertEqual(first_char, space_encoding)
|
| 160 |
+
|
| 161 |
+
encoded = tokenizer.encode(sequence_nospace)
|
| 162 |
+
mask_loc = encoded.index(mask_ind)
|
| 163 |
+
first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0]
|
| 164 |
+
self.assertNotEqual(first_char, space_encoding)
|
| 165 |
+
|
| 166 |
+
def test_pretokenized_inputs(self):
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
def test_embeded_special_tokens(self):
|
| 170 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 171 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 172 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 173 |
+
tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 174 |
+
sentence = "A, <mask> AllenNLP sentence."
|
| 175 |
+
tokens_r = tokenizer_r.encode_plus(sentence, add_special_tokens=True, return_token_type_ids=True)
|
| 176 |
+
tokens_p = tokenizer_p.encode_plus(sentence, add_special_tokens=True, return_token_type_ids=True)
|
| 177 |
+
|
| 178 |
+
# token_type_ids should put 0 everywhere
|
| 179 |
+
self.assertEqual(sum(tokens_r["token_type_ids"]), sum(tokens_p["token_type_ids"]))
|
| 180 |
+
|
| 181 |
+
# attention_mask should put 1 everywhere, so sum over length should be 1
|
| 182 |
+
self.assertEqual(
|
| 183 |
+
sum(tokens_r["attention_mask"]) / len(tokens_r["attention_mask"]),
|
| 184 |
+
sum(tokens_p["attention_mask"]) / len(tokens_p["attention_mask"]),
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
tokens_r_str = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"])
|
| 188 |
+
tokens_p_str = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"])
|
| 189 |
+
|
| 190 |
+
# Rust correctly handles the space before the mask while python doesnt
|
| 191 |
+
self.assertSequenceEqual(tokens_p["input_ids"], [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2])
|
| 192 |
+
self.assertSequenceEqual(tokens_r["input_ids"], [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2])
|
| 193 |
+
|
| 194 |
+
self.assertSequenceEqual(
|
| 195 |
+
tokens_p_str, ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]
|
| 196 |
+
)
|
| 197 |
+
self.assertSequenceEqual(
|
| 198 |
+
tokens_r_str, ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def test_change_add_prefix_space_and_trim_offsets_args(self):
|
| 202 |
+
for trim_offsets, add_prefix_space in itertools.product([True, False], repeat=2):
|
| 203 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 204 |
+
self.tmpdirname, use_fast=True, add_prefix_space=add_prefix_space, trim_offsets=trim_offsets
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
pre_tokenizer_state = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__())
|
| 208 |
+
post_processor_state = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__())
|
| 209 |
+
|
| 210 |
+
self.assertEqual(pre_tokenizer_state["add_prefix_space"], add_prefix_space)
|
| 211 |
+
|
| 212 |
+
self.assertEqual(post_processor_state["add_prefix_space"], add_prefix_space)
|
| 213 |
+
self.assertEqual(post_processor_state["trim_offsets"], trim_offsets)
|
| 214 |
+
|
| 215 |
+
def test_offsets_mapping_with_different_add_prefix_space_and_trim_space_arguments(self):
|
| 216 |
+
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
|
| 217 |
+
# `trim_offsets`
|
| 218 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 219 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 220 |
+
text_of_1_token = "hello" # `hello` is a token in the vocabulary of `pretrained_name`
|
| 221 |
+
text = f"{text_of_1_token} {text_of_1_token}"
|
| 222 |
+
|
| 223 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 224 |
+
pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
|
| 225 |
+
)
|
| 226 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 227 |
+
self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token)))
|
| 228 |
+
self.assertEqual(
|
| 229 |
+
encoding.offset_mapping[1],
|
| 230 |
+
(len(text_of_1_token) + 1, len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 234 |
+
pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=True
|
| 235 |
+
)
|
| 236 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 237 |
+
self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token)))
|
| 238 |
+
self.assertEqual(
|
| 239 |
+
encoding.offset_mapping[1],
|
| 240 |
+
(len(text_of_1_token) + 1, len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 244 |
+
pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=False
|
| 245 |
+
)
|
| 246 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 247 |
+
self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token)))
|
| 248 |
+
self.assertEqual(
|
| 249 |
+
encoding.offset_mapping[1],
|
| 250 |
+
(len(text_of_1_token), len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 254 |
+
pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=False
|
| 255 |
+
)
|
| 256 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 257 |
+
self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token)))
|
| 258 |
+
self.assertEqual(
|
| 259 |
+
encoding.offset_mapping[1],
|
| 260 |
+
(len(text_of_1_token), len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
text = f" {text}"
|
| 264 |
+
|
| 265 |
+
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 266 |
+
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
|
| 267 |
+
# )
|
| 268 |
+
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 269 |
+
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
|
| 270 |
+
# self.assertEqual(
|
| 271 |
+
# encoding.offset_mapping[1],
|
| 272 |
+
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 273 |
+
# )
|
| 274 |
+
|
| 275 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 276 |
+
pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=True
|
| 277 |
+
)
|
| 278 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 279 |
+
self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
|
| 280 |
+
self.assertEqual(
|
| 281 |
+
encoding.offset_mapping[1],
|
| 282 |
+
(1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 286 |
+
pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=False
|
| 287 |
+
)
|
| 288 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 289 |
+
self.assertEqual(encoding.offset_mapping[0], (0, 1 + len(text_of_1_token)))
|
| 290 |
+
self.assertEqual(
|
| 291 |
+
encoding.offset_mapping[1],
|
| 292 |
+
(1 + len(text_of_1_token), 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(
|
| 296 |
+
pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=False
|
| 297 |
+
)
|
| 298 |
+
encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
|
| 299 |
+
self.assertEqual(encoding.offset_mapping[0], (0, 1 + len(text_of_1_token)))
|
| 300 |
+
self.assertEqual(
|
| 301 |
+
encoding.offset_mapping[1],
|
| 302 |
+
(1 + len(text_of_1_token), 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
|
| 303 |
+
)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from transformers import RobertaPreLayerNormConfig, is_flax_available
|
| 20 |
+
from transformers.testing_utils import require_flax, slow
|
| 21 |
+
|
| 22 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_flax_available():
|
| 26 |
+
import jax.numpy as jnp
|
| 27 |
+
|
| 28 |
+
from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
|
| 29 |
+
FlaxRobertaPreLayerNormForCausalLM,
|
| 30 |
+
FlaxRobertaPreLayerNormForMaskedLM,
|
| 31 |
+
FlaxRobertaPreLayerNormForMultipleChoice,
|
| 32 |
+
FlaxRobertaPreLayerNormForQuestionAnswering,
|
| 33 |
+
FlaxRobertaPreLayerNormForSequenceClassification,
|
| 34 |
+
FlaxRobertaPreLayerNormForTokenClassification,
|
| 35 |
+
FlaxRobertaPreLayerNormModel,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Copied from tests.models.roberta.test_modeling_flax_roberta.FlaxRobertaModelTester with Roberta->RobertaPreLayerNorm
|
| 40 |
+
class FlaxRobertaPreLayerNormModelTester(unittest.TestCase):
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
parent,
|
| 44 |
+
batch_size=13,
|
| 45 |
+
seq_length=7,
|
| 46 |
+
is_training=True,
|
| 47 |
+
use_attention_mask=True,
|
| 48 |
+
use_token_type_ids=True,
|
| 49 |
+
use_labels=True,
|
| 50 |
+
vocab_size=99,
|
| 51 |
+
hidden_size=32,
|
| 52 |
+
num_hidden_layers=2,
|
| 53 |
+
num_attention_heads=4,
|
| 54 |
+
intermediate_size=37,
|
| 55 |
+
hidden_act="gelu",
|
| 56 |
+
hidden_dropout_prob=0.1,
|
| 57 |
+
attention_probs_dropout_prob=0.1,
|
| 58 |
+
max_position_embeddings=512,
|
| 59 |
+
type_vocab_size=16,
|
| 60 |
+
type_sequence_label_size=2,
|
| 61 |
+
initializer_range=0.02,
|
| 62 |
+
num_choices=4,
|
| 63 |
+
):
|
| 64 |
+
self.parent = parent
|
| 65 |
+
self.batch_size = batch_size
|
| 66 |
+
self.seq_length = seq_length
|
| 67 |
+
self.is_training = is_training
|
| 68 |
+
self.use_attention_mask = use_attention_mask
|
| 69 |
+
self.use_token_type_ids = use_token_type_ids
|
| 70 |
+
self.use_labels = use_labels
|
| 71 |
+
self.vocab_size = vocab_size
|
| 72 |
+
self.hidden_size = hidden_size
|
| 73 |
+
self.num_hidden_layers = num_hidden_layers
|
| 74 |
+
self.num_attention_heads = num_attention_heads
|
| 75 |
+
self.intermediate_size = intermediate_size
|
| 76 |
+
self.hidden_act = hidden_act
|
| 77 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 78 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 79 |
+
self.max_position_embeddings = max_position_embeddings
|
| 80 |
+
self.type_vocab_size = type_vocab_size
|
| 81 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 82 |
+
self.initializer_range = initializer_range
|
| 83 |
+
self.num_choices = num_choices
|
| 84 |
+
|
| 85 |
+
def prepare_config_and_inputs(self):
|
| 86 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 87 |
+
|
| 88 |
+
attention_mask = None
|
| 89 |
+
if self.use_attention_mask:
|
| 90 |
+
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 91 |
+
|
| 92 |
+
token_type_ids = None
|
| 93 |
+
if self.use_token_type_ids:
|
| 94 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 95 |
+
|
| 96 |
+
config = RobertaPreLayerNormConfig(
|
| 97 |
+
vocab_size=self.vocab_size,
|
| 98 |
+
hidden_size=self.hidden_size,
|
| 99 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 100 |
+
num_attention_heads=self.num_attention_heads,
|
| 101 |
+
intermediate_size=self.intermediate_size,
|
| 102 |
+
hidden_act=self.hidden_act,
|
| 103 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 104 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 105 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 106 |
+
type_vocab_size=self.type_vocab_size,
|
| 107 |
+
is_decoder=False,
|
| 108 |
+
initializer_range=self.initializer_range,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
return config, input_ids, token_type_ids, attention_mask
|
| 112 |
+
|
| 113 |
+
def prepare_config_and_inputs_for_common(self):
|
| 114 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 115 |
+
config, input_ids, token_type_ids, attention_mask = config_and_inputs
|
| 116 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
|
| 117 |
+
return config, inputs_dict
|
| 118 |
+
|
| 119 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 120 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 121 |
+
config, input_ids, token_type_ids, attention_mask = config_and_inputs
|
| 122 |
+
|
| 123 |
+
config.is_decoder = True
|
| 124 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 125 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 126 |
+
|
| 127 |
+
return (
|
| 128 |
+
config,
|
| 129 |
+
input_ids,
|
| 130 |
+
token_type_ids,
|
| 131 |
+
encoder_hidden_states,
|
| 132 |
+
encoder_attention_mask,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@require_flax
|
| 137 |
+
# Copied from tests.models.roberta.test_modeling_flax_roberta.FlaxRobertaModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
|
| 138 |
+
class FlaxRobertaPreLayerNormModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 139 |
+
test_head_masking = True
|
| 140 |
+
|
| 141 |
+
all_model_classes = (
|
| 142 |
+
(
|
| 143 |
+
FlaxRobertaPreLayerNormModel,
|
| 144 |
+
FlaxRobertaPreLayerNormForCausalLM,
|
| 145 |
+
FlaxRobertaPreLayerNormForMaskedLM,
|
| 146 |
+
FlaxRobertaPreLayerNormForSequenceClassification,
|
| 147 |
+
FlaxRobertaPreLayerNormForTokenClassification,
|
| 148 |
+
FlaxRobertaPreLayerNormForMultipleChoice,
|
| 149 |
+
FlaxRobertaPreLayerNormForQuestionAnswering,
|
| 150 |
+
)
|
| 151 |
+
if is_flax_available()
|
| 152 |
+
else ()
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def setUp(self):
|
| 156 |
+
self.model_tester = FlaxRobertaPreLayerNormModelTester(self)
|
| 157 |
+
|
| 158 |
+
@slow
|
| 159 |
+
def test_model_from_pretrained(self):
|
| 160 |
+
for model_class_name in self.all_model_classes:
|
| 161 |
+
model = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True)
|
| 162 |
+
outputs = model(np.ones((1, 1)))
|
| 163 |
+
self.assertIsNotNone(outputs)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@require_flax
|
| 167 |
+
class TFRobertaPreLayerNormModelIntegrationTest(unittest.TestCase):
|
| 168 |
+
@slow
|
| 169 |
+
def test_inference_masked_lm(self):
|
| 170 |
+
model = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True)
|
| 171 |
+
|
| 172 |
+
input_ids = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]], dtype=jnp.int32)
|
| 173 |
+
output = model(input_ids)[0]
|
| 174 |
+
expected_shape = [1, 11, 50265]
|
| 175 |
+
self.assertEqual(list(output.shape), expected_shape)
|
| 176 |
+
# compare the actual values for a slice.
|
| 177 |
+
EXPECTED_SLICE = np.array(
|
| 178 |
+
[[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]], dtype=np.float32
|
| 179 |
+
)
|
| 180 |
+
self.assertTrue(np.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4))
|
| 181 |
+
|
| 182 |
+
@slow
|
| 183 |
+
def test_inference_no_head(self):
|
| 184 |
+
model = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True)
|
| 185 |
+
|
| 186 |
+
input_ids = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]], dtype=jnp.int32)
|
| 187 |
+
output = model(input_ids)[0]
|
| 188 |
+
# compare the actual values for a slice.
|
| 189 |
+
EXPECTED_SLICE = np.array(
|
| 190 |
+
[[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]], dtype=np.float32
|
| 191 |
+
)
|
| 192 |
+
self.assertTrue(np.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import RobertaPreLayerNormConfig, is_torch_available
|
| 20 |
+
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
|
| 21 |
+
|
| 22 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
RobertaPreLayerNormForCausalLM,
|
| 33 |
+
RobertaPreLayerNormForMaskedLM,
|
| 34 |
+
RobertaPreLayerNormForMultipleChoice,
|
| 35 |
+
RobertaPreLayerNormForQuestionAnswering,
|
| 36 |
+
RobertaPreLayerNormForSequenceClassification,
|
| 37 |
+
RobertaPreLayerNormForTokenClassification,
|
| 38 |
+
RobertaPreLayerNormModel,
|
| 39 |
+
)
|
| 40 |
+
from transformers.models.roberta_prelayernorm.modeling_roberta_prelayernorm import (
|
| 41 |
+
ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 42 |
+
RobertaPreLayerNormEmbeddings,
|
| 43 |
+
create_position_ids_from_input_ids,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTester with Roberta->RobertaPreLayerNorm
|
| 48 |
+
class RobertaPreLayerNormModelTester:
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
parent,
|
| 52 |
+
batch_size=13,
|
| 53 |
+
seq_length=7,
|
| 54 |
+
is_training=True,
|
| 55 |
+
use_input_mask=True,
|
| 56 |
+
use_token_type_ids=True,
|
| 57 |
+
use_labels=True,
|
| 58 |
+
vocab_size=99,
|
| 59 |
+
hidden_size=32,
|
| 60 |
+
num_hidden_layers=2,
|
| 61 |
+
num_attention_heads=4,
|
| 62 |
+
intermediate_size=37,
|
| 63 |
+
hidden_act="gelu",
|
| 64 |
+
hidden_dropout_prob=0.1,
|
| 65 |
+
attention_probs_dropout_prob=0.1,
|
| 66 |
+
max_position_embeddings=512,
|
| 67 |
+
type_vocab_size=16,
|
| 68 |
+
type_sequence_label_size=2,
|
| 69 |
+
initializer_range=0.02,
|
| 70 |
+
num_labels=3,
|
| 71 |
+
num_choices=4,
|
| 72 |
+
scope=None,
|
| 73 |
+
):
|
| 74 |
+
self.parent = parent
|
| 75 |
+
self.batch_size = batch_size
|
| 76 |
+
self.seq_length = seq_length
|
| 77 |
+
self.is_training = is_training
|
| 78 |
+
self.use_input_mask = use_input_mask
|
| 79 |
+
self.use_token_type_ids = use_token_type_ids
|
| 80 |
+
self.use_labels = use_labels
|
| 81 |
+
self.vocab_size = vocab_size
|
| 82 |
+
self.hidden_size = hidden_size
|
| 83 |
+
self.num_hidden_layers = num_hidden_layers
|
| 84 |
+
self.num_attention_heads = num_attention_heads
|
| 85 |
+
self.intermediate_size = intermediate_size
|
| 86 |
+
self.hidden_act = hidden_act
|
| 87 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 88 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 89 |
+
self.max_position_embeddings = max_position_embeddings
|
| 90 |
+
self.type_vocab_size = type_vocab_size
|
| 91 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 92 |
+
self.initializer_range = initializer_range
|
| 93 |
+
self.num_labels = num_labels
|
| 94 |
+
self.num_choices = num_choices
|
| 95 |
+
self.scope = scope
|
| 96 |
+
|
| 97 |
+
def prepare_config_and_inputs(self):
|
| 98 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 99 |
+
|
| 100 |
+
input_mask = None
|
| 101 |
+
if self.use_input_mask:
|
| 102 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 103 |
+
|
| 104 |
+
token_type_ids = None
|
| 105 |
+
if self.use_token_type_ids:
|
| 106 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 107 |
+
|
| 108 |
+
sequence_labels = None
|
| 109 |
+
token_labels = None
|
| 110 |
+
choice_labels = None
|
| 111 |
+
if self.use_labels:
|
| 112 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 113 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 114 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 115 |
+
|
| 116 |
+
config = self.get_config()
|
| 117 |
+
|
| 118 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 119 |
+
|
| 120 |
+
def get_config(self):
|
| 121 |
+
return RobertaPreLayerNormConfig(
|
| 122 |
+
vocab_size=self.vocab_size,
|
| 123 |
+
hidden_size=self.hidden_size,
|
| 124 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 125 |
+
num_attention_heads=self.num_attention_heads,
|
| 126 |
+
intermediate_size=self.intermediate_size,
|
| 127 |
+
hidden_act=self.hidden_act,
|
| 128 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 129 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 130 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 131 |
+
type_vocab_size=self.type_vocab_size,
|
| 132 |
+
initializer_range=self.initializer_range,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def get_pipeline_config(self):
|
| 136 |
+
config = self.get_config()
|
| 137 |
+
config.vocab_size = 300
|
| 138 |
+
return config
|
| 139 |
+
|
| 140 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 141 |
+
(
|
| 142 |
+
config,
|
| 143 |
+
input_ids,
|
| 144 |
+
token_type_ids,
|
| 145 |
+
input_mask,
|
| 146 |
+
sequence_labels,
|
| 147 |
+
token_labels,
|
| 148 |
+
choice_labels,
|
| 149 |
+
) = self.prepare_config_and_inputs()
|
| 150 |
+
|
| 151 |
+
config.is_decoder = True
|
| 152 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 153 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 154 |
+
|
| 155 |
+
return (
|
| 156 |
+
config,
|
| 157 |
+
input_ids,
|
| 158 |
+
token_type_ids,
|
| 159 |
+
input_mask,
|
| 160 |
+
sequence_labels,
|
| 161 |
+
token_labels,
|
| 162 |
+
choice_labels,
|
| 163 |
+
encoder_hidden_states,
|
| 164 |
+
encoder_attention_mask,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def create_and_check_model(
|
| 168 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 169 |
+
):
|
| 170 |
+
model = RobertaPreLayerNormModel(config=config)
|
| 171 |
+
model.to(torch_device)
|
| 172 |
+
model.eval()
|
| 173 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 174 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 175 |
+
result = model(input_ids)
|
| 176 |
+
|
| 177 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 178 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
|
| 179 |
+
|
| 180 |
+
def create_and_check_model_as_decoder(
|
| 181 |
+
self,
|
| 182 |
+
config,
|
| 183 |
+
input_ids,
|
| 184 |
+
token_type_ids,
|
| 185 |
+
input_mask,
|
| 186 |
+
sequence_labels,
|
| 187 |
+
token_labels,
|
| 188 |
+
choice_labels,
|
| 189 |
+
encoder_hidden_states,
|
| 190 |
+
encoder_attention_mask,
|
| 191 |
+
):
|
| 192 |
+
config.add_cross_attention = True
|
| 193 |
+
model = RobertaPreLayerNormModel(config)
|
| 194 |
+
model.to(torch_device)
|
| 195 |
+
model.eval()
|
| 196 |
+
result = model(
|
| 197 |
+
input_ids,
|
| 198 |
+
attention_mask=input_mask,
|
| 199 |
+
token_type_ids=token_type_ids,
|
| 200 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 201 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 202 |
+
)
|
| 203 |
+
result = model(
|
| 204 |
+
input_ids,
|
| 205 |
+
attention_mask=input_mask,
|
| 206 |
+
token_type_ids=token_type_ids,
|
| 207 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 208 |
+
)
|
| 209 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 210 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 211 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
|
| 212 |
+
|
| 213 |
+
def create_and_check_for_causal_lm(
|
| 214 |
+
self,
|
| 215 |
+
config,
|
| 216 |
+
input_ids,
|
| 217 |
+
token_type_ids,
|
| 218 |
+
input_mask,
|
| 219 |
+
sequence_labels,
|
| 220 |
+
token_labels,
|
| 221 |
+
choice_labels,
|
| 222 |
+
encoder_hidden_states,
|
| 223 |
+
encoder_attention_mask,
|
| 224 |
+
):
|
| 225 |
+
model = RobertaPreLayerNormForCausalLM(config=config)
|
| 226 |
+
model.to(torch_device)
|
| 227 |
+
model.eval()
|
| 228 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 229 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 230 |
+
|
| 231 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 232 |
+
self,
|
| 233 |
+
config,
|
| 234 |
+
input_ids,
|
| 235 |
+
token_type_ids,
|
| 236 |
+
input_mask,
|
| 237 |
+
sequence_labels,
|
| 238 |
+
token_labels,
|
| 239 |
+
choice_labels,
|
| 240 |
+
encoder_hidden_states,
|
| 241 |
+
encoder_attention_mask,
|
| 242 |
+
):
|
| 243 |
+
config.is_decoder = True
|
| 244 |
+
config.add_cross_attention = True
|
| 245 |
+
model = RobertaPreLayerNormForCausalLM(config=config).to(torch_device).eval()
|
| 246 |
+
|
| 247 |
+
# make sure that ids don't start with pad token
|
| 248 |
+
mask = input_ids.ne(config.pad_token_id).long()
|
| 249 |
+
input_ids = input_ids * mask
|
| 250 |
+
|
| 251 |
+
# first forward pass
|
| 252 |
+
outputs = model(
|
| 253 |
+
input_ids,
|
| 254 |
+
attention_mask=input_mask,
|
| 255 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 256 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 257 |
+
use_cache=True,
|
| 258 |
+
)
|
| 259 |
+
past_key_values = outputs.past_key_values
|
| 260 |
+
|
| 261 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 262 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 263 |
+
|
| 264 |
+
# make sure that ids don't start with pad token
|
| 265 |
+
mask = next_tokens.ne(config.pad_token_id).long()
|
| 266 |
+
next_tokens = next_tokens * mask
|
| 267 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 268 |
+
|
| 269 |
+
# append to next input_ids and
|
| 270 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 271 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 272 |
+
|
| 273 |
+
output_from_no_past = model(
|
| 274 |
+
next_input_ids,
|
| 275 |
+
attention_mask=next_attention_mask,
|
| 276 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 277 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 278 |
+
output_hidden_states=True,
|
| 279 |
+
)["hidden_states"][0]
|
| 280 |
+
output_from_past = model(
|
| 281 |
+
next_tokens,
|
| 282 |
+
attention_mask=next_attention_mask,
|
| 283 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 284 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 285 |
+
past_key_values=past_key_values,
|
| 286 |
+
output_hidden_states=True,
|
| 287 |
+
)["hidden_states"][0]
|
| 288 |
+
|
| 289 |
+
# select random slice
|
| 290 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 291 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 292 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 293 |
+
|
| 294 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 295 |
+
|
| 296 |
+
# test that outputs are equal for slice
|
| 297 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 298 |
+
|
| 299 |
+
def create_and_check_for_masked_lm(
|
| 300 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 301 |
+
):
|
| 302 |
+
model = RobertaPreLayerNormForMaskedLM(config=config)
|
| 303 |
+
model.to(torch_device)
|
| 304 |
+
model.eval()
|
| 305 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 306 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 307 |
+
|
| 308 |
+
def create_and_check_for_token_classification(
|
| 309 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 310 |
+
):
|
| 311 |
+
config.num_labels = self.num_labels
|
| 312 |
+
model = RobertaPreLayerNormForTokenClassification(config=config)
|
| 313 |
+
model.to(torch_device)
|
| 314 |
+
model.eval()
|
| 315 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 316 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 317 |
+
|
| 318 |
+
def create_and_check_for_multiple_choice(
|
| 319 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 320 |
+
):
|
| 321 |
+
config.num_choices = self.num_choices
|
| 322 |
+
model = RobertaPreLayerNormForMultipleChoice(config=config)
|
| 323 |
+
model.to(torch_device)
|
| 324 |
+
model.eval()
|
| 325 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 326 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 327 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 328 |
+
result = model(
|
| 329 |
+
multiple_choice_inputs_ids,
|
| 330 |
+
attention_mask=multiple_choice_input_mask,
|
| 331 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 332 |
+
labels=choice_labels,
|
| 333 |
+
)
|
| 334 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 335 |
+
|
| 336 |
+
def create_and_check_for_question_answering(
|
| 337 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 338 |
+
):
|
| 339 |
+
model = RobertaPreLayerNormForQuestionAnswering(config=config)
|
| 340 |
+
model.to(torch_device)
|
| 341 |
+
model.eval()
|
| 342 |
+
result = model(
|
| 343 |
+
input_ids,
|
| 344 |
+
attention_mask=input_mask,
|
| 345 |
+
token_type_ids=token_type_ids,
|
| 346 |
+
start_positions=sequence_labels,
|
| 347 |
+
end_positions=sequence_labels,
|
| 348 |
+
)
|
| 349 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 350 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 351 |
+
|
| 352 |
+
def prepare_config_and_inputs_for_common(self):
|
| 353 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 354 |
+
(
|
| 355 |
+
config,
|
| 356 |
+
input_ids,
|
| 357 |
+
token_type_ids,
|
| 358 |
+
input_mask,
|
| 359 |
+
sequence_labels,
|
| 360 |
+
token_labels,
|
| 361 |
+
choice_labels,
|
| 362 |
+
) = config_and_inputs
|
| 363 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 364 |
+
return config, inputs_dict
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@require_torch
|
| 368 |
+
class RobertaPreLayerNormModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 369 |
+
all_model_classes = (
|
| 370 |
+
(
|
| 371 |
+
RobertaPreLayerNormForCausalLM,
|
| 372 |
+
RobertaPreLayerNormForMaskedLM,
|
| 373 |
+
RobertaPreLayerNormModel,
|
| 374 |
+
RobertaPreLayerNormForSequenceClassification,
|
| 375 |
+
RobertaPreLayerNormForTokenClassification,
|
| 376 |
+
RobertaPreLayerNormForMultipleChoice,
|
| 377 |
+
RobertaPreLayerNormForQuestionAnswering,
|
| 378 |
+
)
|
| 379 |
+
if is_torch_available()
|
| 380 |
+
else ()
|
| 381 |
+
)
|
| 382 |
+
all_generative_model_classes = (RobertaPreLayerNormForCausalLM,) if is_torch_available() else ()
|
| 383 |
+
pipeline_model_mapping = (
|
| 384 |
+
{
|
| 385 |
+
"feature-extraction": RobertaPreLayerNormModel,
|
| 386 |
+
"fill-mask": RobertaPreLayerNormForMaskedLM,
|
| 387 |
+
"question-answering": RobertaPreLayerNormForQuestionAnswering,
|
| 388 |
+
"text-classification": RobertaPreLayerNormForSequenceClassification,
|
| 389 |
+
"text-generation": RobertaPreLayerNormForCausalLM,
|
| 390 |
+
"token-classification": RobertaPreLayerNormForTokenClassification,
|
| 391 |
+
"zero-shot": RobertaPreLayerNormForSequenceClassification,
|
| 392 |
+
}
|
| 393 |
+
if is_torch_available()
|
| 394 |
+
else {}
|
| 395 |
+
)
|
| 396 |
+
fx_compatible = False
|
| 397 |
+
model_split_percents = [0.5, 0.8, 0.9]
|
| 398 |
+
|
| 399 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.setUp with Roberta->RobertaPreLayerNorm
|
| 400 |
+
def setUp(self):
|
| 401 |
+
self.model_tester = RobertaPreLayerNormModelTester(self)
|
| 402 |
+
self.config_tester = ConfigTester(self, config_class=RobertaPreLayerNormConfig, hidden_size=37)
|
| 403 |
+
|
| 404 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_config
|
| 405 |
+
def test_config(self):
|
| 406 |
+
self.config_tester.run_common_tests()
|
| 407 |
+
|
| 408 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model
|
| 409 |
+
def test_model(self):
|
| 410 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 411 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 412 |
+
|
| 413 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_various_embeddings
|
| 414 |
+
def test_model_various_embeddings(self):
|
| 415 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 416 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 417 |
+
config_and_inputs[0].position_embedding_type = type
|
| 418 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 419 |
+
|
| 420 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_as_decoder
|
| 421 |
+
def test_model_as_decoder(self):
|
| 422 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 423 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 424 |
+
|
| 425 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_as_decoder_with_default_input_mask
|
| 426 |
+
def test_model_as_decoder_with_default_input_mask(self):
|
| 427 |
+
# This regression test was failing with PyTorch < 1.3
|
| 428 |
+
(
|
| 429 |
+
config,
|
| 430 |
+
input_ids,
|
| 431 |
+
token_type_ids,
|
| 432 |
+
input_mask,
|
| 433 |
+
sequence_labels,
|
| 434 |
+
token_labels,
|
| 435 |
+
choice_labels,
|
| 436 |
+
encoder_hidden_states,
|
| 437 |
+
encoder_attention_mask,
|
| 438 |
+
) = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 439 |
+
|
| 440 |
+
input_mask = None
|
| 441 |
+
|
| 442 |
+
self.model_tester.create_and_check_model_as_decoder(
|
| 443 |
+
config,
|
| 444 |
+
input_ids,
|
| 445 |
+
token_type_ids,
|
| 446 |
+
input_mask,
|
| 447 |
+
sequence_labels,
|
| 448 |
+
token_labels,
|
| 449 |
+
choice_labels,
|
| 450 |
+
encoder_hidden_states,
|
| 451 |
+
encoder_attention_mask,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_causal_lm
|
| 455 |
+
def test_for_causal_lm(self):
|
| 456 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 457 |
+
self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
|
| 458 |
+
|
| 459 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_decoder_model_past_with_large_inputs
|
| 460 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 461 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 462 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 463 |
+
|
| 464 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_masked_lm
|
| 465 |
+
def test_for_masked_lm(self):
|
| 466 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 467 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 468 |
+
|
| 469 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_token_classification
|
| 470 |
+
def test_for_token_classification(self):
|
| 471 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 472 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 473 |
+
|
| 474 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_multiple_choice
|
| 475 |
+
def test_for_multiple_choice(self):
|
| 476 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 477 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 478 |
+
|
| 479 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_question_answering
|
| 480 |
+
def test_for_question_answering(self):
|
| 481 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 482 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 483 |
+
|
| 484 |
+
@slow
|
| 485 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_from_pretrained with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm
|
| 486 |
+
def test_model_from_pretrained(self):
|
| 487 |
+
for model_name in ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 488 |
+
model = RobertaPreLayerNormModel.from_pretrained(model_name)
|
| 489 |
+
self.assertIsNotNone(model)
|
| 490 |
+
|
| 491 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_create_position_ids_respects_padding_index with Roberta->RobertaPreLayerNorm
|
| 492 |
+
def test_create_position_ids_respects_padding_index(self):
|
| 493 |
+
"""Ensure that the default position ids only assign a sequential . This is a regression
|
| 494 |
+
test for https://github.com/huggingface/transformers/issues/1761
|
| 495 |
+
|
| 496 |
+
The position ids should be masked with the embedding object's padding index. Therefore, the
|
| 497 |
+
first available non-padding position index is RobertaPreLayerNormEmbeddings.padding_idx + 1
|
| 498 |
+
"""
|
| 499 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 500 |
+
model = RobertaPreLayerNormEmbeddings(config=config)
|
| 501 |
+
|
| 502 |
+
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
|
| 503 |
+
expected_positions = torch.as_tensor(
|
| 504 |
+
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
|
| 508 |
+
self.assertEqual(position_ids.shape, expected_positions.shape)
|
| 509 |
+
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
|
| 510 |
+
|
| 511 |
+
# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_create_position_ids_from_inputs_embeds with Roberta->RobertaPreLayerNorm
|
| 512 |
+
def test_create_position_ids_from_inputs_embeds(self):
|
| 513 |
+
"""Ensure that the default position ids only assign a sequential . This is a regression
|
| 514 |
+
test for https://github.com/huggingface/transformers/issues/1761
|
| 515 |
+
|
| 516 |
+
The position ids should be masked with the embedding object's padding index. Therefore, the
|
| 517 |
+
first available non-padding position index is RobertaPreLayerNormEmbeddings.padding_idx + 1
|
| 518 |
+
"""
|
| 519 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 520 |
+
embeddings = RobertaPreLayerNormEmbeddings(config=config)
|
| 521 |
+
|
| 522 |
+
inputs_embeds = torch.empty(2, 4, 30)
|
| 523 |
+
expected_single_positions = [
|
| 524 |
+
0 + embeddings.padding_idx + 1,
|
| 525 |
+
1 + embeddings.padding_idx + 1,
|
| 526 |
+
2 + embeddings.padding_idx + 1,
|
| 527 |
+
3 + embeddings.padding_idx + 1,
|
| 528 |
+
]
|
| 529 |
+
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
|
| 530 |
+
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 531 |
+
self.assertEqual(position_ids.shape, expected_positions.shape)
|
| 532 |
+
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
@require_torch
|
| 536 |
+
class RobertaPreLayerNormModelIntegrationTest(TestCasePlus):
|
| 537 |
+
@slow
|
| 538 |
+
def test_inference_masked_lm(self):
|
| 539 |
+
model = RobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40")
|
| 540 |
+
|
| 541 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 542 |
+
with torch.no_grad():
|
| 543 |
+
output = model(input_ids)[0]
|
| 544 |
+
expected_shape = torch.Size((1, 11, 50265))
|
| 545 |
+
self.assertEqual(output.shape, expected_shape)
|
| 546 |
+
# compare the actual values for a slice.
|
| 547 |
+
EXPECTED_SLICE = torch.tensor(
|
| 548 |
+
[[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]]
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
self.assertTrue(torch.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4))
|
| 552 |
+
|
| 553 |
+
@slow
|
| 554 |
+
def test_inference_no_head(self):
|
| 555 |
+
model = RobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40")
|
| 556 |
+
|
| 557 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 558 |
+
with torch.no_grad():
|
| 559 |
+
output = model(input_ids)[0]
|
| 560 |
+
# compare the actual values for a slice.
|
| 561 |
+
EXPECTED_SLICE = torch.tensor(
|
| 562 |
+
[[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]]
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
self.assertTrue(torch.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_tf_roberta_prelayernorm.py
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import RobertaPreLayerNormConfig, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import numpy
|
| 31 |
+
import tensorflow as tf
|
| 32 |
+
|
| 33 |
+
from transformers.models.roberta_prelayernorm.modeling_tf_roberta_prelayernorm import (
|
| 34 |
+
TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 35 |
+
TFRobertaPreLayerNormForCausalLM,
|
| 36 |
+
TFRobertaPreLayerNormForMaskedLM,
|
| 37 |
+
TFRobertaPreLayerNormForMultipleChoice,
|
| 38 |
+
TFRobertaPreLayerNormForQuestionAnswering,
|
| 39 |
+
TFRobertaPreLayerNormForSequenceClassification,
|
| 40 |
+
TFRobertaPreLayerNormForTokenClassification,
|
| 41 |
+
TFRobertaPreLayerNormModel,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Copied from tests.models.roberta.test_modeling_tf_roberta.TFRobertaModelTester with Roberta->RobertaPreLayerNorm
|
| 46 |
+
class TFRobertaPreLayerNormModelTester:
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
parent,
|
| 50 |
+
):
|
| 51 |
+
self.parent = parent
|
| 52 |
+
self.batch_size = 13
|
| 53 |
+
self.seq_length = 7
|
| 54 |
+
self.is_training = True
|
| 55 |
+
self.use_input_mask = True
|
| 56 |
+
self.use_token_type_ids = True
|
| 57 |
+
self.use_labels = True
|
| 58 |
+
self.vocab_size = 99
|
| 59 |
+
self.hidden_size = 32
|
| 60 |
+
self.num_hidden_layers = 2
|
| 61 |
+
self.num_attention_heads = 4
|
| 62 |
+
self.intermediate_size = 37
|
| 63 |
+
self.hidden_act = "gelu"
|
| 64 |
+
self.hidden_dropout_prob = 0.1
|
| 65 |
+
self.attention_probs_dropout_prob = 0.1
|
| 66 |
+
self.max_position_embeddings = 512
|
| 67 |
+
self.type_vocab_size = 16
|
| 68 |
+
self.type_sequence_label_size = 2
|
| 69 |
+
self.initializer_range = 0.02
|
| 70 |
+
self.num_labels = 3
|
| 71 |
+
self.num_choices = 4
|
| 72 |
+
self.scope = None
|
| 73 |
+
|
| 74 |
+
def prepare_config_and_inputs(self):
|
| 75 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 76 |
+
|
| 77 |
+
input_mask = None
|
| 78 |
+
if self.use_input_mask:
|
| 79 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 80 |
+
|
| 81 |
+
token_type_ids = None
|
| 82 |
+
if self.use_token_type_ids:
|
| 83 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 84 |
+
|
| 85 |
+
sequence_labels = None
|
| 86 |
+
token_labels = None
|
| 87 |
+
choice_labels = None
|
| 88 |
+
if self.use_labels:
|
| 89 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 90 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 91 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 92 |
+
|
| 93 |
+
config = RobertaPreLayerNormConfig(
|
| 94 |
+
vocab_size=self.vocab_size,
|
| 95 |
+
hidden_size=self.hidden_size,
|
| 96 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 97 |
+
num_attention_heads=self.num_attention_heads,
|
| 98 |
+
intermediate_size=self.intermediate_size,
|
| 99 |
+
hidden_act=self.hidden_act,
|
| 100 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 101 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 102 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 103 |
+
type_vocab_size=self.type_vocab_size,
|
| 104 |
+
initializer_range=self.initializer_range,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 108 |
+
|
| 109 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 110 |
+
(
|
| 111 |
+
config,
|
| 112 |
+
input_ids,
|
| 113 |
+
token_type_ids,
|
| 114 |
+
input_mask,
|
| 115 |
+
sequence_labels,
|
| 116 |
+
token_labels,
|
| 117 |
+
choice_labels,
|
| 118 |
+
) = self.prepare_config_and_inputs()
|
| 119 |
+
|
| 120 |
+
config.is_decoder = True
|
| 121 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 122 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 123 |
+
|
| 124 |
+
return (
|
| 125 |
+
config,
|
| 126 |
+
input_ids,
|
| 127 |
+
token_type_ids,
|
| 128 |
+
input_mask,
|
| 129 |
+
sequence_labels,
|
| 130 |
+
token_labels,
|
| 131 |
+
choice_labels,
|
| 132 |
+
encoder_hidden_states,
|
| 133 |
+
encoder_attention_mask,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def create_and_check_model(
|
| 137 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 138 |
+
):
|
| 139 |
+
model = TFRobertaPreLayerNormModel(config=config)
|
| 140 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 141 |
+
result = model(inputs)
|
| 142 |
+
|
| 143 |
+
inputs = [input_ids, input_mask]
|
| 144 |
+
result = model(inputs)
|
| 145 |
+
|
| 146 |
+
result = model(input_ids)
|
| 147 |
+
|
| 148 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 149 |
+
|
| 150 |
+
def create_and_check_causal_lm_base_model(
|
| 151 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 152 |
+
):
|
| 153 |
+
config.is_decoder = True
|
| 154 |
+
|
| 155 |
+
model = TFRobertaPreLayerNormModel(config=config)
|
| 156 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 157 |
+
result = model(inputs)
|
| 158 |
+
|
| 159 |
+
inputs = [input_ids, input_mask]
|
| 160 |
+
result = model(inputs)
|
| 161 |
+
|
| 162 |
+
result = model(input_ids)
|
| 163 |
+
|
| 164 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 165 |
+
|
| 166 |
+
def create_and_check_model_as_decoder(
|
| 167 |
+
self,
|
| 168 |
+
config,
|
| 169 |
+
input_ids,
|
| 170 |
+
token_type_ids,
|
| 171 |
+
input_mask,
|
| 172 |
+
sequence_labels,
|
| 173 |
+
token_labels,
|
| 174 |
+
choice_labels,
|
| 175 |
+
encoder_hidden_states,
|
| 176 |
+
encoder_attention_mask,
|
| 177 |
+
):
|
| 178 |
+
config.add_cross_attention = True
|
| 179 |
+
|
| 180 |
+
model = TFRobertaPreLayerNormModel(config=config)
|
| 181 |
+
inputs = {
|
| 182 |
+
"input_ids": input_ids,
|
| 183 |
+
"attention_mask": input_mask,
|
| 184 |
+
"token_type_ids": token_type_ids,
|
| 185 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 186 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 187 |
+
}
|
| 188 |
+
result = model(inputs)
|
| 189 |
+
|
| 190 |
+
inputs = [input_ids, input_mask]
|
| 191 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 192 |
+
|
| 193 |
+
# Also check the case where encoder outputs are not passed
|
| 194 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 195 |
+
|
| 196 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 197 |
+
|
| 198 |
+
def create_and_check_causal_lm_model(
|
| 199 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 200 |
+
):
|
| 201 |
+
config.is_decoder = True
|
| 202 |
+
|
| 203 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 204 |
+
inputs = {
|
| 205 |
+
"input_ids": input_ids,
|
| 206 |
+
"attention_mask": input_mask,
|
| 207 |
+
"token_type_ids": token_type_ids,
|
| 208 |
+
}
|
| 209 |
+
prediction_scores = model(inputs)["logits"]
|
| 210 |
+
self.parent.assertListEqual(
|
| 211 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def create_and_check_causal_lm_model_as_decoder(
|
| 215 |
+
self,
|
| 216 |
+
config,
|
| 217 |
+
input_ids,
|
| 218 |
+
token_type_ids,
|
| 219 |
+
input_mask,
|
| 220 |
+
sequence_labels,
|
| 221 |
+
token_labels,
|
| 222 |
+
choice_labels,
|
| 223 |
+
encoder_hidden_states,
|
| 224 |
+
encoder_attention_mask,
|
| 225 |
+
):
|
| 226 |
+
config.add_cross_attention = True
|
| 227 |
+
|
| 228 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 229 |
+
inputs = {
|
| 230 |
+
"input_ids": input_ids,
|
| 231 |
+
"attention_mask": input_mask,
|
| 232 |
+
"token_type_ids": token_type_ids,
|
| 233 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 234 |
+
"encoder_attention_mask": encoder_attention_mask,
|
| 235 |
+
}
|
| 236 |
+
result = model(inputs)
|
| 237 |
+
|
| 238 |
+
inputs = [input_ids, input_mask]
|
| 239 |
+
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
|
| 240 |
+
|
| 241 |
+
prediction_scores = result["logits"]
|
| 242 |
+
self.parent.assertListEqual(
|
| 243 |
+
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
def create_and_check_causal_lm_model_past(
|
| 247 |
+
self,
|
| 248 |
+
config,
|
| 249 |
+
input_ids,
|
| 250 |
+
token_type_ids,
|
| 251 |
+
input_mask,
|
| 252 |
+
sequence_labels,
|
| 253 |
+
token_labels,
|
| 254 |
+
choice_labels,
|
| 255 |
+
):
|
| 256 |
+
config.is_decoder = True
|
| 257 |
+
|
| 258 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 259 |
+
|
| 260 |
+
# special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`:
|
| 261 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 262 |
+
# (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids)
|
| 263 |
+
# - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx`
|
| 264 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 265 |
+
|
| 266 |
+
# first forward pass
|
| 267 |
+
outputs = model(input_ids, use_cache=True)
|
| 268 |
+
outputs_use_cache_conf = model(input_ids)
|
| 269 |
+
outputs_no_past = model(input_ids, use_cache=False)
|
| 270 |
+
|
| 271 |
+
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
|
| 272 |
+
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
|
| 273 |
+
|
| 274 |
+
past_key_values = outputs.past_key_values
|
| 275 |
+
|
| 276 |
+
# create hypothetical next token and extent to next_input_ids
|
| 277 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 278 |
+
|
| 279 |
+
# append to next input_ids and attn_mask
|
| 280 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 281 |
+
|
| 282 |
+
output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0]
|
| 283 |
+
output_from_past = model(
|
| 284 |
+
next_tokens, past_key_values=past_key_values, output_hidden_states=True
|
| 285 |
+
).hidden_states[0]
|
| 286 |
+
|
| 287 |
+
# select random slice
|
| 288 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 289 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 290 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 291 |
+
|
| 292 |
+
# test that outputs are equal for slice
|
| 293 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 294 |
+
|
| 295 |
+
def create_and_check_causal_lm_model_past_with_attn_mask(
|
| 296 |
+
self,
|
| 297 |
+
config,
|
| 298 |
+
input_ids,
|
| 299 |
+
token_type_ids,
|
| 300 |
+
input_mask,
|
| 301 |
+
sequence_labels,
|
| 302 |
+
token_labels,
|
| 303 |
+
choice_labels,
|
| 304 |
+
):
|
| 305 |
+
config.is_decoder = True
|
| 306 |
+
|
| 307 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 308 |
+
|
| 309 |
+
# special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`:
|
| 310 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 311 |
+
# (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids)
|
| 312 |
+
# - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx`
|
| 313 |
+
# avoid `padding_idx` in the past
|
| 314 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 315 |
+
|
| 316 |
+
# create attention mask
|
| 317 |
+
half_seq_length = self.seq_length // 2
|
| 318 |
+
attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32)
|
| 319 |
+
attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32)
|
| 320 |
+
attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1)
|
| 321 |
+
|
| 322 |
+
# first forward pass
|
| 323 |
+
outputs = model(input_ids, attention_mask=attn_mask, use_cache=True)
|
| 324 |
+
|
| 325 |
+
# create hypothetical next token and extent to next_input_ids
|
| 326 |
+
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
|
| 327 |
+
|
| 328 |
+
past_key_values = outputs.past_key_values
|
| 329 |
+
|
| 330 |
+
# change a random masked slice from input_ids
|
| 331 |
+
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1
|
| 332 |
+
random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size)
|
| 333 |
+
vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change)
|
| 334 |
+
condition = tf.transpose(
|
| 335 |
+
tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size))
|
| 336 |
+
)
|
| 337 |
+
input_ids = tf.where(condition, random_other_next_tokens, input_ids)
|
| 338 |
+
# avoid `padding_idx` in the past
|
| 339 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 340 |
+
|
| 341 |
+
# append to next input_ids and
|
| 342 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 343 |
+
attn_mask = tf.concat(
|
| 344 |
+
[attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)],
|
| 345 |
+
axis=1,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
output_from_no_past = model(
|
| 349 |
+
next_input_ids,
|
| 350 |
+
attention_mask=attn_mask,
|
| 351 |
+
output_hidden_states=True,
|
| 352 |
+
).hidden_states[0]
|
| 353 |
+
output_from_past = model(
|
| 354 |
+
next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True
|
| 355 |
+
).hidden_states[0]
|
| 356 |
+
|
| 357 |
+
# select random slice
|
| 358 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 359 |
+
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
|
| 360 |
+
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
|
| 361 |
+
|
| 362 |
+
# test that outputs are equal for slice
|
| 363 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
|
| 364 |
+
|
| 365 |
+
def create_and_check_causal_lm_model_past_large_inputs(
|
| 366 |
+
self,
|
| 367 |
+
config,
|
| 368 |
+
input_ids,
|
| 369 |
+
token_type_ids,
|
| 370 |
+
input_mask,
|
| 371 |
+
sequence_labels,
|
| 372 |
+
token_labels,
|
| 373 |
+
choice_labels,
|
| 374 |
+
):
|
| 375 |
+
config.is_decoder = True
|
| 376 |
+
|
| 377 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 378 |
+
|
| 379 |
+
# special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`:
|
| 380 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 381 |
+
# (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids)
|
| 382 |
+
# - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx`
|
| 383 |
+
# avoid `padding_idx` in the past
|
| 384 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 385 |
+
|
| 386 |
+
input_ids = input_ids[:1, :]
|
| 387 |
+
input_mask = input_mask[:1, :]
|
| 388 |
+
self.batch_size = 1
|
| 389 |
+
|
| 390 |
+
# first forward pass
|
| 391 |
+
outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
|
| 392 |
+
past_key_values = outputs.past_key_values
|
| 393 |
+
|
| 394 |
+
# create hypothetical next token and extent to next_input_ids
|
| 395 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 396 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 397 |
+
|
| 398 |
+
# append to next input_ids and
|
| 399 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 400 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 401 |
+
|
| 402 |
+
output_from_no_past = model(
|
| 403 |
+
next_input_ids,
|
| 404 |
+
attention_mask=next_attention_mask,
|
| 405 |
+
output_hidden_states=True,
|
| 406 |
+
).hidden_states[0]
|
| 407 |
+
output_from_past = model(
|
| 408 |
+
next_tokens,
|
| 409 |
+
attention_mask=next_attention_mask,
|
| 410 |
+
past_key_values=past_key_values,
|
| 411 |
+
output_hidden_states=True,
|
| 412 |
+
).hidden_states[0]
|
| 413 |
+
|
| 414 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 415 |
+
|
| 416 |
+
# select random slice
|
| 417 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 418 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 419 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 420 |
+
|
| 421 |
+
# test that outputs are equal for slice
|
| 422 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 423 |
+
|
| 424 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 425 |
+
self,
|
| 426 |
+
config,
|
| 427 |
+
input_ids,
|
| 428 |
+
token_type_ids,
|
| 429 |
+
input_mask,
|
| 430 |
+
sequence_labels,
|
| 431 |
+
token_labels,
|
| 432 |
+
choice_labels,
|
| 433 |
+
encoder_hidden_states,
|
| 434 |
+
encoder_attention_mask,
|
| 435 |
+
):
|
| 436 |
+
config.add_cross_attention = True
|
| 437 |
+
|
| 438 |
+
model = TFRobertaPreLayerNormForCausalLM(config=config)
|
| 439 |
+
|
| 440 |
+
# special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`:
|
| 441 |
+
# - its `padding_idx` and its effect on `position_ids`
|
| 442 |
+
# (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids)
|
| 443 |
+
# - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx`
|
| 444 |
+
# avoid `padding_idx` in the past
|
| 445 |
+
input_ids = tf.where(input_ids == 1, 2, input_ids)
|
| 446 |
+
|
| 447 |
+
input_ids = input_ids[:1, :]
|
| 448 |
+
input_mask = input_mask[:1, :]
|
| 449 |
+
encoder_hidden_states = encoder_hidden_states[:1, :, :]
|
| 450 |
+
encoder_attention_mask = encoder_attention_mask[:1, :]
|
| 451 |
+
self.batch_size = 1
|
| 452 |
+
|
| 453 |
+
# first forward pass
|
| 454 |
+
outputs = model(
|
| 455 |
+
input_ids,
|
| 456 |
+
attention_mask=input_mask,
|
| 457 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 458 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 459 |
+
use_cache=True,
|
| 460 |
+
)
|
| 461 |
+
past_key_values = outputs.past_key_values
|
| 462 |
+
|
| 463 |
+
# create hypothetical next token and extent to next_input_ids
|
| 464 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 465 |
+
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
|
| 466 |
+
|
| 467 |
+
# append to next input_ids and
|
| 468 |
+
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
|
| 469 |
+
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
|
| 470 |
+
|
| 471 |
+
output_from_no_past = model(
|
| 472 |
+
next_input_ids,
|
| 473 |
+
attention_mask=next_attention_mask,
|
| 474 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 475 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 476 |
+
output_hidden_states=True,
|
| 477 |
+
).hidden_states[0]
|
| 478 |
+
output_from_past = model(
|
| 479 |
+
next_tokens,
|
| 480 |
+
attention_mask=next_attention_mask,
|
| 481 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 482 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 483 |
+
past_key_values=past_key_values,
|
| 484 |
+
output_hidden_states=True,
|
| 485 |
+
).hidden_states[0]
|
| 486 |
+
|
| 487 |
+
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
|
| 488 |
+
|
| 489 |
+
# select random slice
|
| 490 |
+
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
|
| 491 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
|
| 492 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx]
|
| 493 |
+
|
| 494 |
+
# test that outputs are equal for slice
|
| 495 |
+
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
|
| 496 |
+
|
| 497 |
+
def create_and_check_for_masked_lm(
|
| 498 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 499 |
+
):
|
| 500 |
+
model = TFRobertaPreLayerNormForMaskedLM(config=config)
|
| 501 |
+
result = model([input_ids, input_mask, token_type_ids])
|
| 502 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 503 |
+
|
| 504 |
+
def create_and_check_for_token_classification(
|
| 505 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 506 |
+
):
|
| 507 |
+
config.num_labels = self.num_labels
|
| 508 |
+
model = TFRobertaPreLayerNormForTokenClassification(config=config)
|
| 509 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 510 |
+
result = model(inputs)
|
| 511 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 512 |
+
|
| 513 |
+
def create_and_check_for_question_answering(
|
| 514 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 515 |
+
):
|
| 516 |
+
model = TFRobertaPreLayerNormForQuestionAnswering(config=config)
|
| 517 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 518 |
+
result = model(inputs)
|
| 519 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 520 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 521 |
+
|
| 522 |
+
def create_and_check_for_multiple_choice(
|
| 523 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 524 |
+
):
|
| 525 |
+
config.num_choices = self.num_choices
|
| 526 |
+
model = TFRobertaPreLayerNormForMultipleChoice(config=config)
|
| 527 |
+
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
|
| 528 |
+
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
|
| 529 |
+
multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
|
| 530 |
+
inputs = {
|
| 531 |
+
"input_ids": multiple_choice_inputs_ids,
|
| 532 |
+
"attention_mask": multiple_choice_input_mask,
|
| 533 |
+
"token_type_ids": multiple_choice_token_type_ids,
|
| 534 |
+
}
|
| 535 |
+
result = model(inputs)
|
| 536 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 537 |
+
|
| 538 |
+
def prepare_config_and_inputs_for_common(self):
|
| 539 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 540 |
+
(
|
| 541 |
+
config,
|
| 542 |
+
input_ids,
|
| 543 |
+
token_type_ids,
|
| 544 |
+
input_mask,
|
| 545 |
+
sequence_labels,
|
| 546 |
+
token_labels,
|
| 547 |
+
choice_labels,
|
| 548 |
+
) = config_and_inputs
|
| 549 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 550 |
+
return config, inputs_dict
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@require_tf
|
| 554 |
+
# Copied from tests.models.roberta.test_modeling_tf_roberta.TFRobertaModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm
|
| 555 |
+
class TFRobertaPreLayerNormModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 556 |
+
all_model_classes = (
|
| 557 |
+
(
|
| 558 |
+
TFRobertaPreLayerNormModel,
|
| 559 |
+
TFRobertaPreLayerNormForCausalLM,
|
| 560 |
+
TFRobertaPreLayerNormForMaskedLM,
|
| 561 |
+
TFRobertaPreLayerNormForSequenceClassification,
|
| 562 |
+
TFRobertaPreLayerNormForTokenClassification,
|
| 563 |
+
TFRobertaPreLayerNormForQuestionAnswering,
|
| 564 |
+
)
|
| 565 |
+
if is_tf_available()
|
| 566 |
+
else ()
|
| 567 |
+
)
|
| 568 |
+
pipeline_model_mapping = (
|
| 569 |
+
{
|
| 570 |
+
"feature-extraction": TFRobertaPreLayerNormModel,
|
| 571 |
+
"fill-mask": TFRobertaPreLayerNormForMaskedLM,
|
| 572 |
+
"question-answering": TFRobertaPreLayerNormForQuestionAnswering,
|
| 573 |
+
"text-classification": TFRobertaPreLayerNormForSequenceClassification,
|
| 574 |
+
"text-generation": TFRobertaPreLayerNormForCausalLM,
|
| 575 |
+
"token-classification": TFRobertaPreLayerNormForTokenClassification,
|
| 576 |
+
"zero-shot": TFRobertaPreLayerNormForSequenceClassification,
|
| 577 |
+
}
|
| 578 |
+
if is_tf_available()
|
| 579 |
+
else {}
|
| 580 |
+
)
|
| 581 |
+
test_head_masking = False
|
| 582 |
+
test_onnx = False
|
| 583 |
+
|
| 584 |
+
def setUp(self):
|
| 585 |
+
self.model_tester = TFRobertaPreLayerNormModelTester(self)
|
| 586 |
+
self.config_tester = ConfigTester(self, config_class=RobertaPreLayerNormConfig, hidden_size=37)
|
| 587 |
+
|
| 588 |
+
def test_config(self):
|
| 589 |
+
self.config_tester.run_common_tests()
|
| 590 |
+
|
| 591 |
+
def test_model(self):
|
| 592 |
+
"""Test the base model"""
|
| 593 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 594 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 595 |
+
|
| 596 |
+
def test_causal_lm_base_model(self):
|
| 597 |
+
"""Test the base model of the causal LM model
|
| 598 |
+
|
| 599 |
+
is_deocder=True, no cross_attention, no encoder outputs
|
| 600 |
+
"""
|
| 601 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 602 |
+
self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs)
|
| 603 |
+
|
| 604 |
+
def test_model_as_decoder(self):
|
| 605 |
+
"""Test the base model as a decoder (of an encoder-decoder architecture)
|
| 606 |
+
|
| 607 |
+
is_deocder=True + cross_attention + pass encoder outputs
|
| 608 |
+
"""
|
| 609 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 610 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 611 |
+
|
| 612 |
+
def test_for_masked_lm(self):
|
| 613 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 614 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 615 |
+
|
| 616 |
+
def test_for_causal_lm(self):
|
| 617 |
+
"""Test the causal LM model"""
|
| 618 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 619 |
+
self.model_tester.create_and_check_causal_lm_model(*config_and_inputs)
|
| 620 |
+
|
| 621 |
+
def test_causal_lm_model_as_decoder(self):
|
| 622 |
+
"""Test the causal LM model as a decoder"""
|
| 623 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 624 |
+
self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs)
|
| 625 |
+
|
| 626 |
+
def test_causal_lm_model_past(self):
|
| 627 |
+
"""Test causal LM model with `past_key_values`"""
|
| 628 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 629 |
+
self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs)
|
| 630 |
+
|
| 631 |
+
def test_causal_lm_model_past_with_attn_mask(self):
|
| 632 |
+
"""Test the causal LM model with `past_key_values` and `attention_mask`"""
|
| 633 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 634 |
+
self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs)
|
| 635 |
+
|
| 636 |
+
def test_causal_lm_model_past_with_large_inputs(self):
|
| 637 |
+
"""Test the causal LM model with `past_key_values` and a longer decoder sequence length"""
|
| 638 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 639 |
+
self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs)
|
| 640 |
+
|
| 641 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 642 |
+
"""Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention"""
|
| 643 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 644 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 645 |
+
|
| 646 |
+
def test_for_token_classification(self):
|
| 647 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 648 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 649 |
+
|
| 650 |
+
def test_for_question_answering(self):
|
| 651 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 652 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 653 |
+
|
| 654 |
+
def test_for_multiple_choice(self):
|
| 655 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 656 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 657 |
+
|
| 658 |
+
@slow
|
| 659 |
+
def test_model_from_pretrained(self):
|
| 660 |
+
for model_name in TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 661 |
+
model = TFRobertaPreLayerNormModel.from_pretrained(model_name)
|
| 662 |
+
self.assertIsNotNone(model)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
@require_tf
|
| 666 |
+
@require_sentencepiece
|
| 667 |
+
@require_tokenizers
|
| 668 |
+
class TFRobertaPreLayerNormModelIntegrationTest(unittest.TestCase):
|
| 669 |
+
@slow
|
| 670 |
+
def test_inference_masked_lm(self):
|
| 671 |
+
model = TFRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40")
|
| 672 |
+
|
| 673 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 674 |
+
output = model(input_ids)[0]
|
| 675 |
+
expected_shape = [1, 11, 50265]
|
| 676 |
+
self.assertEqual(list(output.numpy().shape), expected_shape)
|
| 677 |
+
# compare the actual values for a slice.
|
| 678 |
+
EXPECTED_SLICE = tf.constant(
|
| 679 |
+
[[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]]
|
| 680 |
+
)
|
| 681 |
+
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), EXPECTED_SLICE.numpy(), atol=1e-4))
|
| 682 |
+
|
| 683 |
+
@slow
|
| 684 |
+
def test_inference_no_head(self):
|
| 685 |
+
model = TFRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40")
|
| 686 |
+
|
| 687 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 688 |
+
output = model(input_ids)[0]
|
| 689 |
+
# compare the actual values for a slice.
|
| 690 |
+
EXPECTED_SLICE = tf.constant(
|
| 691 |
+
[[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]]
|
| 692 |
+
)
|
| 693 |
+
self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), EXPECTED_SLICE.numpy(), atol=1e-4))
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_modeling_roc_bert.py
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Testing suite for the PyTorch RoCBert model. """
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import RoCBertConfig, is_torch_available
|
| 20 |
+
from transformers.models.auto import get_values
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
MODEL_FOR_PRETRAINING_MAPPING,
|
| 33 |
+
RoCBertForCausalLM,
|
| 34 |
+
RoCBertForMaskedLM,
|
| 35 |
+
RoCBertForMultipleChoice,
|
| 36 |
+
RoCBertForPreTraining,
|
| 37 |
+
RoCBertForQuestionAnswering,
|
| 38 |
+
RoCBertForSequenceClassification,
|
| 39 |
+
RoCBertForTokenClassification,
|
| 40 |
+
RoCBertModel,
|
| 41 |
+
)
|
| 42 |
+
from transformers.models.roc_bert.modeling_roc_bert import ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class RoCBertModelTester:
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
parent,
|
| 49 |
+
batch_size=13,
|
| 50 |
+
seq_length=7,
|
| 51 |
+
is_training=True,
|
| 52 |
+
use_input_mask=True,
|
| 53 |
+
use_token_type_ids=True,
|
| 54 |
+
use_labels=True,
|
| 55 |
+
vocab_size=99,
|
| 56 |
+
pronunciation_vocab_size=99,
|
| 57 |
+
shape_vocab_size=99,
|
| 58 |
+
pronunciation_embed_dim=32,
|
| 59 |
+
shape_embed_dim=32,
|
| 60 |
+
hidden_size=32,
|
| 61 |
+
num_hidden_layers=2,
|
| 62 |
+
num_attention_heads=4,
|
| 63 |
+
intermediate_size=37,
|
| 64 |
+
hidden_act="gelu",
|
| 65 |
+
hidden_dropout_prob=0.1,
|
| 66 |
+
attention_probs_dropout_prob=0.1,
|
| 67 |
+
max_position_embeddings=512,
|
| 68 |
+
type_vocab_size=16,
|
| 69 |
+
type_sequence_label_size=2,
|
| 70 |
+
initializer_range=0.02,
|
| 71 |
+
num_labels=3,
|
| 72 |
+
num_choices=4,
|
| 73 |
+
scope=None,
|
| 74 |
+
):
|
| 75 |
+
self.parent = parent
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.seq_length = seq_length
|
| 78 |
+
self.is_training = is_training
|
| 79 |
+
self.use_input_mask = use_input_mask
|
| 80 |
+
self.use_token_type_ids = use_token_type_ids
|
| 81 |
+
self.use_labels = use_labels
|
| 82 |
+
self.vocab_size = vocab_size
|
| 83 |
+
self.pronunciation_vocab_size = pronunciation_vocab_size
|
| 84 |
+
self.shape_vocab_size = shape_vocab_size
|
| 85 |
+
self.pronunciation_embed_dim = pronunciation_embed_dim
|
| 86 |
+
self.shape_embed_dim = shape_embed_dim
|
| 87 |
+
self.hidden_size = hidden_size
|
| 88 |
+
self.num_hidden_layers = num_hidden_layers
|
| 89 |
+
self.num_attention_heads = num_attention_heads
|
| 90 |
+
self.intermediate_size = intermediate_size
|
| 91 |
+
self.hidden_act = hidden_act
|
| 92 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 93 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 94 |
+
self.max_position_embeddings = max_position_embeddings
|
| 95 |
+
self.type_vocab_size = type_vocab_size
|
| 96 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 97 |
+
self.initializer_range = initializer_range
|
| 98 |
+
self.num_labels = num_labels
|
| 99 |
+
self.num_choices = num_choices
|
| 100 |
+
self.scope = scope
|
| 101 |
+
|
| 102 |
+
def prepare_config_and_inputs(self):
|
| 103 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 104 |
+
input_shape_ids = ids_tensor([self.batch_size, self.seq_length], self.shape_vocab_size)
|
| 105 |
+
input_pronunciation_ids = ids_tensor([self.batch_size, self.seq_length], self.pronunciation_vocab_size)
|
| 106 |
+
|
| 107 |
+
input_mask = None
|
| 108 |
+
if self.use_input_mask:
|
| 109 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 110 |
+
|
| 111 |
+
token_type_ids = None
|
| 112 |
+
if self.use_token_type_ids:
|
| 113 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 114 |
+
|
| 115 |
+
sequence_labels = None
|
| 116 |
+
token_labels = None
|
| 117 |
+
choice_labels = None
|
| 118 |
+
if self.use_labels:
|
| 119 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 120 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 121 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 122 |
+
|
| 123 |
+
config = self.get_config()
|
| 124 |
+
|
| 125 |
+
return (
|
| 126 |
+
config,
|
| 127 |
+
input_ids,
|
| 128 |
+
input_shape_ids,
|
| 129 |
+
input_pronunciation_ids,
|
| 130 |
+
token_type_ids,
|
| 131 |
+
input_mask,
|
| 132 |
+
sequence_labels,
|
| 133 |
+
token_labels,
|
| 134 |
+
choice_labels,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def get_config(self):
|
| 138 |
+
return RoCBertConfig(
|
| 139 |
+
vocab_size=self.vocab_size,
|
| 140 |
+
shape_vocab_size=self.shape_vocab_size,
|
| 141 |
+
pronunciation_vocab_size=self.pronunciation_vocab_size,
|
| 142 |
+
shape_embed_dim=self.shape_embed_dim,
|
| 143 |
+
pronunciation_embed_dim=self.pronunciation_embed_dim,
|
| 144 |
+
hidden_size=self.hidden_size,
|
| 145 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 146 |
+
num_attention_heads=self.num_attention_heads,
|
| 147 |
+
intermediate_size=self.intermediate_size,
|
| 148 |
+
hidden_act=self.hidden_act,
|
| 149 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 150 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 151 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 152 |
+
type_vocab_size=self.type_vocab_size,
|
| 153 |
+
is_decoder=False,
|
| 154 |
+
initializer_range=self.initializer_range,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
def prepare_config_and_inputs_for_decoder(self):
|
| 158 |
+
(
|
| 159 |
+
config,
|
| 160 |
+
input_ids,
|
| 161 |
+
input_shape_ids,
|
| 162 |
+
input_pronunciation_ids,
|
| 163 |
+
token_type_ids,
|
| 164 |
+
input_mask,
|
| 165 |
+
sequence_labels,
|
| 166 |
+
token_labels,
|
| 167 |
+
choice_labels,
|
| 168 |
+
) = self.prepare_config_and_inputs()
|
| 169 |
+
|
| 170 |
+
config.is_decoder = True
|
| 171 |
+
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
|
| 172 |
+
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 173 |
+
|
| 174 |
+
return (
|
| 175 |
+
config,
|
| 176 |
+
input_ids,
|
| 177 |
+
input_shape_ids,
|
| 178 |
+
input_pronunciation_ids,
|
| 179 |
+
token_type_ids,
|
| 180 |
+
input_mask,
|
| 181 |
+
sequence_labels,
|
| 182 |
+
token_labels,
|
| 183 |
+
choice_labels,
|
| 184 |
+
encoder_hidden_states,
|
| 185 |
+
encoder_attention_mask,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def create_and_check_model(
|
| 189 |
+
self,
|
| 190 |
+
config,
|
| 191 |
+
input_ids,
|
| 192 |
+
input_shape_ids,
|
| 193 |
+
input_pronunciation_ids,
|
| 194 |
+
token_type_ids,
|
| 195 |
+
input_mask,
|
| 196 |
+
sequence_labels,
|
| 197 |
+
token_labels,
|
| 198 |
+
choice_labels,
|
| 199 |
+
):
|
| 200 |
+
model = RoCBertModel(config=config)
|
| 201 |
+
model.to(torch_device)
|
| 202 |
+
model.eval()
|
| 203 |
+
result = model(
|
| 204 |
+
input_ids,
|
| 205 |
+
input_shape_ids=input_shape_ids,
|
| 206 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 207 |
+
attention_mask=input_mask,
|
| 208 |
+
token_type_ids=token_type_ids,
|
| 209 |
+
)
|
| 210 |
+
result = model(
|
| 211 |
+
input_ids,
|
| 212 |
+
input_shape_ids=input_shape_ids,
|
| 213 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 214 |
+
token_type_ids=token_type_ids,
|
| 215 |
+
)
|
| 216 |
+
result = model(input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids)
|
| 217 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 218 |
+
|
| 219 |
+
def create_and_check_model_as_decoder(
|
| 220 |
+
self,
|
| 221 |
+
config,
|
| 222 |
+
input_ids,
|
| 223 |
+
input_shape_ids,
|
| 224 |
+
input_pronunciation_ids,
|
| 225 |
+
token_type_ids,
|
| 226 |
+
input_mask,
|
| 227 |
+
sequence_labels,
|
| 228 |
+
token_labels,
|
| 229 |
+
choice_labels,
|
| 230 |
+
encoder_hidden_states,
|
| 231 |
+
encoder_attention_mask,
|
| 232 |
+
):
|
| 233 |
+
config.add_cross_attention = True
|
| 234 |
+
model = RoCBertModel(config)
|
| 235 |
+
model.to(torch_device)
|
| 236 |
+
model.eval()
|
| 237 |
+
result = model(
|
| 238 |
+
input_ids,
|
| 239 |
+
input_shape_ids=input_shape_ids,
|
| 240 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 241 |
+
attention_mask=input_mask,
|
| 242 |
+
token_type_ids=token_type_ids,
|
| 243 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 244 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 245 |
+
)
|
| 246 |
+
result = model(
|
| 247 |
+
input_ids,
|
| 248 |
+
input_shape_ids=input_shape_ids,
|
| 249 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 250 |
+
attention_mask=input_mask,
|
| 251 |
+
token_type_ids=token_type_ids,
|
| 252 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 253 |
+
)
|
| 254 |
+
result = model(
|
| 255 |
+
input_ids,
|
| 256 |
+
input_shape_ids=input_shape_ids,
|
| 257 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 258 |
+
attention_mask=input_mask,
|
| 259 |
+
token_type_ids=token_type_ids,
|
| 260 |
+
)
|
| 261 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 262 |
+
|
| 263 |
+
def create_and_check_for_causal_lm(
|
| 264 |
+
self,
|
| 265 |
+
config,
|
| 266 |
+
input_ids,
|
| 267 |
+
input_shape_ids,
|
| 268 |
+
input_pronunciation_ids,
|
| 269 |
+
token_type_ids,
|
| 270 |
+
input_mask,
|
| 271 |
+
sequence_labels,
|
| 272 |
+
token_labels,
|
| 273 |
+
choice_labels,
|
| 274 |
+
encoder_hidden_states,
|
| 275 |
+
encoder_attention_mask,
|
| 276 |
+
):
|
| 277 |
+
model = RoCBertForCausalLM(config=config)
|
| 278 |
+
model.to(torch_device)
|
| 279 |
+
model.eval()
|
| 280 |
+
result = model(
|
| 281 |
+
input_ids,
|
| 282 |
+
input_shape_ids=input_shape_ids,
|
| 283 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 284 |
+
attention_mask=input_mask,
|
| 285 |
+
token_type_ids=token_type_ids,
|
| 286 |
+
labels=token_labels,
|
| 287 |
+
)
|
| 288 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 289 |
+
|
| 290 |
+
def create_and_check_for_masked_lm(
|
| 291 |
+
self,
|
| 292 |
+
config,
|
| 293 |
+
input_ids,
|
| 294 |
+
input_shape_ids,
|
| 295 |
+
input_pronunciation_ids,
|
| 296 |
+
token_type_ids,
|
| 297 |
+
input_mask,
|
| 298 |
+
sequence_labels,
|
| 299 |
+
token_labels,
|
| 300 |
+
choice_labels,
|
| 301 |
+
):
|
| 302 |
+
model = RoCBertForMaskedLM(config=config)
|
| 303 |
+
model.to(torch_device)
|
| 304 |
+
model.eval()
|
| 305 |
+
result = model(
|
| 306 |
+
input_ids,
|
| 307 |
+
input_shape_ids=input_shape_ids,
|
| 308 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 309 |
+
attention_mask=input_mask,
|
| 310 |
+
token_type_ids=token_type_ids,
|
| 311 |
+
labels=token_labels,
|
| 312 |
+
)
|
| 313 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 314 |
+
|
| 315 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 316 |
+
self,
|
| 317 |
+
config,
|
| 318 |
+
input_ids,
|
| 319 |
+
input_shape_ids,
|
| 320 |
+
input_pronunciation_ids,
|
| 321 |
+
token_type_ids,
|
| 322 |
+
input_mask,
|
| 323 |
+
sequence_labels,
|
| 324 |
+
token_labels,
|
| 325 |
+
choice_labels,
|
| 326 |
+
encoder_hidden_states,
|
| 327 |
+
encoder_attention_mask,
|
| 328 |
+
):
|
| 329 |
+
config.is_decoder = True
|
| 330 |
+
config.add_cross_attention = True
|
| 331 |
+
model = RoCBertForCausalLM(config=config)
|
| 332 |
+
model.to(torch_device)
|
| 333 |
+
model.eval()
|
| 334 |
+
|
| 335 |
+
# first forward pass
|
| 336 |
+
outputs = model(
|
| 337 |
+
input_ids,
|
| 338 |
+
input_shape_ids=input_shape_ids,
|
| 339 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 340 |
+
attention_mask=input_mask,
|
| 341 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 342 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 343 |
+
use_cache=True,
|
| 344 |
+
)
|
| 345 |
+
past_key_values = outputs.past_key_values
|
| 346 |
+
|
| 347 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 348 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 349 |
+
next_shape_tokens = ids_tensor((self.batch_size, 3), config.shape_vocab_size)
|
| 350 |
+
next_pronunciation_tokens = ids_tensor((self.batch_size, 3), config.pronunciation_vocab_size)
|
| 351 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 352 |
+
|
| 353 |
+
# append to next input_ids and
|
| 354 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 355 |
+
next_input_shape_ids = torch.cat([input_shape_ids, next_shape_tokens], dim=-1)
|
| 356 |
+
next_input_pronunciation_ids = torch.cat([input_pronunciation_ids, next_pronunciation_tokens], dim=-1)
|
| 357 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 358 |
+
|
| 359 |
+
output_from_no_past = model(
|
| 360 |
+
next_input_ids,
|
| 361 |
+
input_shape_ids=next_input_shape_ids,
|
| 362 |
+
input_pronunciation_ids=next_input_pronunciation_ids,
|
| 363 |
+
attention_mask=next_attention_mask,
|
| 364 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 365 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 366 |
+
output_hidden_states=True,
|
| 367 |
+
)["hidden_states"][0]
|
| 368 |
+
output_from_past = model(
|
| 369 |
+
next_tokens,
|
| 370 |
+
input_shape_ids=next_shape_tokens,
|
| 371 |
+
input_pronunciation_ids=next_pronunciation_tokens,
|
| 372 |
+
attention_mask=next_attention_mask,
|
| 373 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 374 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 375 |
+
past_key_values=past_key_values,
|
| 376 |
+
output_hidden_states=True,
|
| 377 |
+
)["hidden_states"][0]
|
| 378 |
+
|
| 379 |
+
# select random slice
|
| 380 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 381 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 382 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 383 |
+
|
| 384 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 385 |
+
|
| 386 |
+
# test that outputs are equal for slice
|
| 387 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 388 |
+
|
| 389 |
+
def create_and_check_for_question_answering(
|
| 390 |
+
self,
|
| 391 |
+
config,
|
| 392 |
+
input_ids,
|
| 393 |
+
input_shape_ids,
|
| 394 |
+
input_pronunciation_ids,
|
| 395 |
+
token_type_ids,
|
| 396 |
+
input_mask,
|
| 397 |
+
sequence_labels,
|
| 398 |
+
token_labels,
|
| 399 |
+
choice_labels,
|
| 400 |
+
):
|
| 401 |
+
model = RoCBertForQuestionAnswering(config=config)
|
| 402 |
+
model.to(torch_device)
|
| 403 |
+
model.eval()
|
| 404 |
+
result = model(
|
| 405 |
+
input_ids,
|
| 406 |
+
input_shape_ids=input_shape_ids,
|
| 407 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 408 |
+
attention_mask=input_mask,
|
| 409 |
+
token_type_ids=token_type_ids,
|
| 410 |
+
start_positions=sequence_labels,
|
| 411 |
+
end_positions=sequence_labels,
|
| 412 |
+
)
|
| 413 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 414 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 415 |
+
|
| 416 |
+
def create_and_check_for_sequence_classification(
|
| 417 |
+
self,
|
| 418 |
+
config,
|
| 419 |
+
input_ids,
|
| 420 |
+
input_shape_ids,
|
| 421 |
+
input_pronunciation_ids,
|
| 422 |
+
token_type_ids,
|
| 423 |
+
input_mask,
|
| 424 |
+
sequence_labels,
|
| 425 |
+
token_labels,
|
| 426 |
+
choice_labels,
|
| 427 |
+
):
|
| 428 |
+
config.num_labels = self.num_labels
|
| 429 |
+
model = RoCBertForSequenceClassification(config)
|
| 430 |
+
model.to(torch_device)
|
| 431 |
+
model.eval()
|
| 432 |
+
result = model(
|
| 433 |
+
input_ids,
|
| 434 |
+
input_shape_ids=input_shape_ids,
|
| 435 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 436 |
+
attention_mask=input_mask,
|
| 437 |
+
token_type_ids=token_type_ids,
|
| 438 |
+
labels=sequence_labels,
|
| 439 |
+
)
|
| 440 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 441 |
+
|
| 442 |
+
def create_and_check_for_token_classification(
|
| 443 |
+
self,
|
| 444 |
+
config,
|
| 445 |
+
input_ids,
|
| 446 |
+
input_shape_ids,
|
| 447 |
+
input_pronunciation_ids,
|
| 448 |
+
token_type_ids,
|
| 449 |
+
input_mask,
|
| 450 |
+
sequence_labels,
|
| 451 |
+
token_labels,
|
| 452 |
+
choice_labels,
|
| 453 |
+
):
|
| 454 |
+
config.num_labels = self.num_labels
|
| 455 |
+
model = RoCBertForTokenClassification(config=config)
|
| 456 |
+
model.to(torch_device)
|
| 457 |
+
model.eval()
|
| 458 |
+
result = model(
|
| 459 |
+
input_ids,
|
| 460 |
+
input_shape_ids=input_shape_ids,
|
| 461 |
+
input_pronunciation_ids=input_pronunciation_ids,
|
| 462 |
+
attention_mask=input_mask,
|
| 463 |
+
token_type_ids=token_type_ids,
|
| 464 |
+
labels=token_labels,
|
| 465 |
+
)
|
| 466 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 467 |
+
|
| 468 |
+
def create_and_check_for_multiple_choice(
|
| 469 |
+
self,
|
| 470 |
+
config,
|
| 471 |
+
input_ids,
|
| 472 |
+
input_shape_ids,
|
| 473 |
+
input_pronunciation_ids,
|
| 474 |
+
token_type_ids,
|
| 475 |
+
input_mask,
|
| 476 |
+
sequence_labels,
|
| 477 |
+
token_labels,
|
| 478 |
+
choice_labels,
|
| 479 |
+
):
|
| 480 |
+
config.num_choices = self.num_choices
|
| 481 |
+
model = RoCBertForMultipleChoice(config=config)
|
| 482 |
+
model.to(torch_device)
|
| 483 |
+
model.eval()
|
| 484 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 485 |
+
multiple_choice_inputs_shape_ids = input_shape_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 486 |
+
multiple_choice_inputs_pronunciation_ids = (
|
| 487 |
+
input_pronunciation_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 488 |
+
)
|
| 489 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 490 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 491 |
+
result = model(
|
| 492 |
+
multiple_choice_inputs_ids,
|
| 493 |
+
input_shape_ids=multiple_choice_inputs_shape_ids,
|
| 494 |
+
input_pronunciation_ids=multiple_choice_inputs_pronunciation_ids,
|
| 495 |
+
attention_mask=multiple_choice_input_mask,
|
| 496 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 497 |
+
labels=choice_labels,
|
| 498 |
+
)
|
| 499 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 500 |
+
|
| 501 |
+
def prepare_config_and_inputs_for_common(self):
|
| 502 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 503 |
+
(
|
| 504 |
+
config,
|
| 505 |
+
input_ids,
|
| 506 |
+
input_shape_ids,
|
| 507 |
+
input_pronunciation_ids,
|
| 508 |
+
token_type_ids,
|
| 509 |
+
input_mask,
|
| 510 |
+
sequence_labels,
|
| 511 |
+
token_labels,
|
| 512 |
+
choice_labels,
|
| 513 |
+
) = config_and_inputs
|
| 514 |
+
inputs_dict = {
|
| 515 |
+
"input_ids": input_ids,
|
| 516 |
+
"input_shape_ids": input_shape_ids,
|
| 517 |
+
"input_pronunciation_ids": input_pronunciation_ids,
|
| 518 |
+
"token_type_ids": token_type_ids,
|
| 519 |
+
"attention_mask": input_mask,
|
| 520 |
+
}
|
| 521 |
+
return config, inputs_dict
|
| 522 |
+
|
| 523 |
+
def create_and_check_for_pretraining(
|
| 524 |
+
self,
|
| 525 |
+
config,
|
| 526 |
+
input_ids,
|
| 527 |
+
input_shape_ids,
|
| 528 |
+
input_pronunciation_ids,
|
| 529 |
+
token_type_ids,
|
| 530 |
+
input_mask,
|
| 531 |
+
sequence_labels,
|
| 532 |
+
token_labels,
|
| 533 |
+
choice_labels,
|
| 534 |
+
):
|
| 535 |
+
model = RoCBertForPreTraining(config=config)
|
| 536 |
+
model.to(torch_device)
|
| 537 |
+
model.eval()
|
| 538 |
+
result = model(
|
| 539 |
+
input_ids,
|
| 540 |
+
input_shape_ids,
|
| 541 |
+
input_pronunciation_ids,
|
| 542 |
+
attention_mask=input_mask,
|
| 543 |
+
token_type_ids=token_type_ids,
|
| 544 |
+
attack_input_ids=input_ids,
|
| 545 |
+
attack_input_shape_ids=input_shape_ids,
|
| 546 |
+
attack_input_pronunciation_ids=input_pronunciation_ids,
|
| 547 |
+
attack_attention_mask=input_mask,
|
| 548 |
+
attack_token_type_ids=token_type_ids,
|
| 549 |
+
labels_input_ids=token_labels,
|
| 550 |
+
labels_input_shape_ids=input_shape_ids,
|
| 551 |
+
labels_input_pronunciation_ids=input_pronunciation_ids,
|
| 552 |
+
labels_attention_mask=input_mask,
|
| 553 |
+
labels_token_type_ids=token_type_ids,
|
| 554 |
+
)
|
| 555 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
@require_torch
|
| 559 |
+
class RoCBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 560 |
+
all_model_classes = (
|
| 561 |
+
(
|
| 562 |
+
RoCBertModel,
|
| 563 |
+
RoCBertForMaskedLM,
|
| 564 |
+
RoCBertForCausalLM,
|
| 565 |
+
RoCBertForMultipleChoice,
|
| 566 |
+
RoCBertForQuestionAnswering,
|
| 567 |
+
RoCBertForSequenceClassification,
|
| 568 |
+
RoCBertForTokenClassification,
|
| 569 |
+
RoCBertForPreTraining,
|
| 570 |
+
)
|
| 571 |
+
if is_torch_available()
|
| 572 |
+
else ()
|
| 573 |
+
)
|
| 574 |
+
all_generative_model_classes = (RoCBertForCausalLM,) if is_torch_available() else ()
|
| 575 |
+
pipeline_model_mapping = (
|
| 576 |
+
{
|
| 577 |
+
"feature-extraction": RoCBertModel,
|
| 578 |
+
"fill-mask": RoCBertForMaskedLM,
|
| 579 |
+
"question-answering": RoCBertForQuestionAnswering,
|
| 580 |
+
"text-classification": RoCBertForSequenceClassification,
|
| 581 |
+
"text-generation": RoCBertForCausalLM,
|
| 582 |
+
"token-classification": RoCBertForTokenClassification,
|
| 583 |
+
"zero-shot": RoCBertForSequenceClassification,
|
| 584 |
+
}
|
| 585 |
+
if is_torch_available()
|
| 586 |
+
else {}
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
# TODO: Fix the failed tests when this model gets more usage
|
| 590 |
+
def is_pipeline_test_to_skip(
|
| 591 |
+
self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
|
| 592 |
+
):
|
| 593 |
+
if pipeline_test_casse_name in [
|
| 594 |
+
"FillMaskPipelineTests",
|
| 595 |
+
"FeatureExtractionPipelineTests",
|
| 596 |
+
"TextClassificationPipelineTests",
|
| 597 |
+
"TokenClassificationPipelineTests",
|
| 598 |
+
]:
|
| 599 |
+
# Get error: IndexError: index out of range in self.
|
| 600 |
+
# `word_shape_file` and `word_pronunciation_file` should be shrunk during tiny model creation,
|
| 601 |
+
# otherwise `IndexError` could occur in some embedding layers. Skip for now until this model has
|
| 602 |
+
# more usage.
|
| 603 |
+
return True
|
| 604 |
+
|
| 605 |
+
return False
|
| 606 |
+
|
| 607 |
+
# special case for ForPreTraining model
|
| 608 |
+
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
| 609 |
+
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
| 610 |
+
|
| 611 |
+
if return_labels:
|
| 612 |
+
if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
|
| 613 |
+
inputs_dict["labels_input_ids"] = torch.zeros(
|
| 614 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 615 |
+
)
|
| 616 |
+
inputs_dict["labels_input_shape_ids"] = torch.zeros(
|
| 617 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 618 |
+
)
|
| 619 |
+
inputs_dict["labels_input_pronunciation_ids"] = torch.zeros(
|
| 620 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 621 |
+
)
|
| 622 |
+
inputs_dict["attack_input_ids"] = torch.zeros(
|
| 623 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 624 |
+
)
|
| 625 |
+
inputs_dict["attack_input_shape_ids"] = torch.zeros(
|
| 626 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 627 |
+
)
|
| 628 |
+
inputs_dict["attack_input_pronunciation_ids"] = torch.zeros(
|
| 629 |
+
(self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
|
| 630 |
+
)
|
| 631 |
+
return inputs_dict
|
| 632 |
+
|
| 633 |
+
def setUp(self):
|
| 634 |
+
self.model_tester = RoCBertModelTester(self)
|
| 635 |
+
self.config_tester = ConfigTester(self, config_class=RoCBertConfig, hidden_size=37)
|
| 636 |
+
|
| 637 |
+
def test_config(self):
|
| 638 |
+
self.config_tester.run_common_tests()
|
| 639 |
+
|
| 640 |
+
def test_model(self):
|
| 641 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 642 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 643 |
+
|
| 644 |
+
def test_model_various_embeddings(self):
|
| 645 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 646 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 647 |
+
config_and_inputs[0].position_embedding_type = type
|
| 648 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 649 |
+
|
| 650 |
+
def test_for_masked_lm(self):
|
| 651 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 652 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 653 |
+
|
| 654 |
+
def test_for_multiple_choice(self):
|
| 655 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 656 |
+
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
|
| 657 |
+
|
| 658 |
+
def test_decoder_model_past_with_large_inputs(self):
|
| 659 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 660 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 661 |
+
|
| 662 |
+
def test_decoder_model_past_with_large_inputs_relative_pos_emb(self):
|
| 663 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 664 |
+
config_and_inputs[0].position_embedding_type = "relative_key"
|
| 665 |
+
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
|
| 666 |
+
|
| 667 |
+
def test_for_question_answering(self):
|
| 668 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 669 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 670 |
+
|
| 671 |
+
def test_for_sequence_classification(self):
|
| 672 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 673 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 674 |
+
|
| 675 |
+
def test_for_token_classification(self):
|
| 676 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 677 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 678 |
+
|
| 679 |
+
def test_for_pretraining(self):
|
| 680 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 681 |
+
self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
|
| 682 |
+
|
| 683 |
+
def test_model_as_decoder(self):
|
| 684 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 685 |
+
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
|
| 686 |
+
|
| 687 |
+
def test_model_as_decoder_with_default_input_mask(self):
|
| 688 |
+
# This regression test was failing with PyTorch < 1.3
|
| 689 |
+
(
|
| 690 |
+
config,
|
| 691 |
+
input_ids,
|
| 692 |
+
input_shape_ids,
|
| 693 |
+
input_pronunciation_ids,
|
| 694 |
+
token_type_ids,
|
| 695 |
+
input_mask,
|
| 696 |
+
sequence_labels,
|
| 697 |
+
token_labels,
|
| 698 |
+
choice_labels,
|
| 699 |
+
encoder_hidden_states,
|
| 700 |
+
encoder_attention_mask,
|
| 701 |
+
) = self.model_tester.prepare_config_and_inputs_for_decoder()
|
| 702 |
+
|
| 703 |
+
input_mask = None
|
| 704 |
+
|
| 705 |
+
self.model_tester.create_and_check_model_as_decoder(
|
| 706 |
+
config,
|
| 707 |
+
input_ids,
|
| 708 |
+
input_shape_ids,
|
| 709 |
+
input_pronunciation_ids,
|
| 710 |
+
token_type_ids,
|
| 711 |
+
input_mask,
|
| 712 |
+
sequence_labels,
|
| 713 |
+
token_labels,
|
| 714 |
+
choice_labels,
|
| 715 |
+
encoder_hidden_states,
|
| 716 |
+
encoder_attention_mask,
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
@slow
|
| 720 |
+
def test_model_from_pretrained(self):
|
| 721 |
+
for model_name in ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
| 722 |
+
model = RoCBertModel.from_pretrained(model_name)
|
| 723 |
+
self.assertIsNotNone(model)
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
@require_torch
|
| 727 |
+
class RoCBertModelIntegrationTest(unittest.TestCase):
|
| 728 |
+
@slow
|
| 729 |
+
def test_inference_masked_lm(self):
|
| 730 |
+
model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh")
|
| 731 |
+
|
| 732 |
+
# input_text: ['[CLS]', 'b', 'a', '里', '系', '[MASK]', '国', '的', '首', '都', '[SEP]'] is the adversarial text
|
| 733 |
+
# of ['[CLS]', '巴', '黎', '是', '[MASK]', '国', '的', '首', '都', '[SEP]'], means
|
| 734 |
+
# "Paris is the [MASK] of France" in English
|
| 735 |
+
input_ids = torch.tensor([[101, 144, 143, 7027, 5143, 103, 1744, 4638, 7674, 6963, 102]])
|
| 736 |
+
input_shape_ids = torch.tensor([[2, 20324, 23690, 8740, 706, 1, 10900, 23343, 20205, 5850, 2]])
|
| 737 |
+
input_pronunciation_ids = torch.tensor([[2, 718, 397, 52, 61, 1, 168, 273, 180, 243, 2]])
|
| 738 |
+
|
| 739 |
+
output = model(input_ids, input_shape_ids, input_pronunciation_ids)
|
| 740 |
+
output_ids = torch.argmax(output.logits, dim=2)
|
| 741 |
+
|
| 742 |
+
# convert to tokens is: ['[CLS]', '巴', '*', '黎', '是', '法', '国', '的', '首', '都', '[SEP]']
|
| 743 |
+
expected_output = torch.tensor([[101, 2349, 115, 7944, 3221, 3791, 1744, 4638, 7674, 6963, 102]])
|
| 744 |
+
|
| 745 |
+
assert torch.allclose(output_ids, expected_output)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_tokenization_roc_bert.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers.models.roc_bert.tokenization_roc_bert import (
|
| 22 |
+
VOCAB_FILES_NAMES,
|
| 23 |
+
RoCBertBasicTokenizer,
|
| 24 |
+
RoCBertTokenizer,
|
| 25 |
+
RoCBertWordpieceTokenizer,
|
| 26 |
+
_is_control,
|
| 27 |
+
_is_punctuation,
|
| 28 |
+
_is_whitespace,
|
| 29 |
+
)
|
| 30 |
+
from transformers.testing_utils import require_tokenizers, slow
|
| 31 |
+
|
| 32 |
+
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@require_tokenizers
|
| 36 |
+
class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 37 |
+
tokenizer_class = RoCBertTokenizer
|
| 38 |
+
rust_tokenizer_class = None
|
| 39 |
+
test_rust_tokenizer = False
|
| 40 |
+
space_between_special_tokens = True
|
| 41 |
+
from_pretrained_filter = filter_non_english
|
| 42 |
+
|
| 43 |
+
def setUp(self):
|
| 44 |
+
super().setUp()
|
| 45 |
+
|
| 46 |
+
vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"]
|
| 47 |
+
word_shape = {}
|
| 48 |
+
word_pronunciation = {}
|
| 49 |
+
for i, value in enumerate(vocab_tokens):
|
| 50 |
+
word_shape[value] = i
|
| 51 |
+
word_pronunciation[value] = i
|
| 52 |
+
self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
|
| 53 |
+
self.word_shape_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["word_shape_file"])
|
| 54 |
+
self.word_pronunciation_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["word_pronunciation_file"])
|
| 55 |
+
with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
|
| 56 |
+
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
|
| 57 |
+
with open(self.word_shape_file, "w", encoding="utf-8") as word_shape_writer:
|
| 58 |
+
json.dump(word_shape, word_shape_writer, ensure_ascii=False)
|
| 59 |
+
with open(self.word_pronunciation_file, "w", encoding="utf-8") as word_pronunciation_writer:
|
| 60 |
+
json.dump(word_pronunciation, word_pronunciation_writer, ensure_ascii=False)
|
| 61 |
+
|
| 62 |
+
def test_full_tokenizer(self):
|
| 63 |
+
tokenizer = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file)
|
| 64 |
+
|
| 65 |
+
tokens = tokenizer.tokenize("你好[SEP]你是谁")
|
| 66 |
+
self.assertListEqual(tokens, ["你", "好", "[SEP]", "你", "是", "谁"])
|
| 67 |
+
self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [5, 6, 2, 5, 7, 8])
|
| 68 |
+
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(tokens), [5, 6, 2, 5, 7, 8])
|
| 69 |
+
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(tokens), [5, 6, 2, 5, 7, 8])
|
| 70 |
+
|
| 71 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_chinese with BasicTokenizer->RoCBertBasicTokenizer
|
| 72 |
+
def test_chinese(self):
|
| 73 |
+
tokenizer = RoCBertBasicTokenizer()
|
| 74 |
+
|
| 75 |
+
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"])
|
| 76 |
+
|
| 77 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower with BasicTokenizer->RoCBertBasicTokenizer
|
| 78 |
+
def test_basic_tokenizer_lower(self):
|
| 79 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=True)
|
| 80 |
+
|
| 81 |
+
self.assertListEqual(
|
| 82 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"]
|
| 83 |
+
)
|
| 84 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 85 |
+
|
| 86 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_false with BasicTokenizer->RoCBertBasicTokenizer
|
| 87 |
+
def test_basic_tokenizer_lower_strip_accents_false(self):
|
| 88 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=True, strip_accents=False)
|
| 89 |
+
|
| 90 |
+
self.assertListEqual(
|
| 91 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"]
|
| 92 |
+
)
|
| 93 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"])
|
| 94 |
+
|
| 95 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_true with BasicTokenizer->RoCBertBasicTokenizer
|
| 96 |
+
def test_basic_tokenizer_lower_strip_accents_true(self):
|
| 97 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=True, strip_accents=True)
|
| 98 |
+
|
| 99 |
+
self.assertListEqual(
|
| 100 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 101 |
+
)
|
| 102 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 103 |
+
|
| 104 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_default with BasicTokenizer->RoCBertBasicTokenizer
|
| 105 |
+
def test_basic_tokenizer_lower_strip_accents_default(self):
|
| 106 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=True)
|
| 107 |
+
|
| 108 |
+
self.assertListEqual(
|
| 109 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"]
|
| 110 |
+
)
|
| 111 |
+
self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
|
| 112 |
+
|
| 113 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower with BasicTokenizer->RoCBertBasicTokenizer
|
| 114 |
+
def test_basic_tokenizer_no_lower(self):
|
| 115 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=False)
|
| 116 |
+
|
| 117 |
+
self.assertListEqual(
|
| 118 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"]
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower_strip_accents_false with BasicTokenizer->RoCBertBasicTokenizer
|
| 122 |
+
def test_basic_tokenizer_no_lower_strip_accents_false(self):
|
| 123 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=False, strip_accents=False)
|
| 124 |
+
|
| 125 |
+
self.assertListEqual(
|
| 126 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower_strip_accents_true with BasicTokenizer->RoCBertBasicTokenizer
|
| 130 |
+
def test_basic_tokenizer_no_lower_strip_accents_true(self):
|
| 131 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=False, strip_accents=True)
|
| 132 |
+
|
| 133 |
+
self.assertListEqual(
|
| 134 |
+
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"]
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_respects_never_split_tokens with BasicTokenizer->RoCBertBasicTokenizer
|
| 138 |
+
def test_basic_tokenizer_respects_never_split_tokens(self):
|
| 139 |
+
tokenizer = RoCBertBasicTokenizer(do_lower_case=False, never_split=["[UNK]"])
|
| 140 |
+
|
| 141 |
+
self.assertListEqual(
|
| 142 |
+
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_wordpiece_tokenizer with WordpieceTokenizer->RoCBertWordpieceTokenizer
|
| 146 |
+
def test_wordpiece_tokenizer(self):
|
| 147 |
+
vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
|
| 148 |
+
|
| 149 |
+
vocab = {}
|
| 150 |
+
for i, token in enumerate(vocab_tokens):
|
| 151 |
+
vocab[token] = i
|
| 152 |
+
tokenizer = RoCBertWordpieceTokenizer(vocab=vocab, unk_token="[UNK]")
|
| 153 |
+
|
| 154 |
+
self.assertListEqual(tokenizer.tokenize(""), [])
|
| 155 |
+
|
| 156 |
+
self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"])
|
| 157 |
+
|
| 158 |
+
self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
|
| 159 |
+
|
| 160 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_whitespace
|
| 161 |
+
def test_is_whitespace(self):
|
| 162 |
+
self.assertTrue(_is_whitespace(" "))
|
| 163 |
+
self.assertTrue(_is_whitespace("\t"))
|
| 164 |
+
self.assertTrue(_is_whitespace("\r"))
|
| 165 |
+
self.assertTrue(_is_whitespace("\n"))
|
| 166 |
+
self.assertTrue(_is_whitespace("\u00A0"))
|
| 167 |
+
|
| 168 |
+
self.assertFalse(_is_whitespace("A"))
|
| 169 |
+
self.assertFalse(_is_whitespace("-"))
|
| 170 |
+
|
| 171 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_control
|
| 172 |
+
def test_is_control(self):
|
| 173 |
+
self.assertTrue(_is_control("\u0005"))
|
| 174 |
+
|
| 175 |
+
self.assertFalse(_is_control("A"))
|
| 176 |
+
self.assertFalse(_is_control(" "))
|
| 177 |
+
self.assertFalse(_is_control("\t"))
|
| 178 |
+
self.assertFalse(_is_control("\r"))
|
| 179 |
+
|
| 180 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_punctuation
|
| 181 |
+
def test_is_punctuation(self):
|
| 182 |
+
self.assertTrue(_is_punctuation("-"))
|
| 183 |
+
self.assertTrue(_is_punctuation("$"))
|
| 184 |
+
self.assertTrue(_is_punctuation("`"))
|
| 185 |
+
self.assertTrue(_is_punctuation("."))
|
| 186 |
+
|
| 187 |
+
self.assertFalse(_is_punctuation("A"))
|
| 188 |
+
self.assertFalse(_is_punctuation(" "))
|
| 189 |
+
|
| 190 |
+
def test_clean_text(self):
|
| 191 |
+
tokenizer = self.get_tokenizer()
|
| 192 |
+
|
| 193 |
+
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
|
| 194 |
+
self.assertListEqual([tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]])
|
| 195 |
+
|
| 196 |
+
if self.test_rust_tokenizer:
|
| 197 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 198 |
+
self.assertListEqual(
|
| 199 |
+
[rust_tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]]
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_offsets_with_special_characters
|
| 203 |
+
def test_offsets_with_special_characters(self):
|
| 204 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 205 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 206 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 207 |
+
|
| 208 |
+
sentence = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence."
|
| 209 |
+
tokens = tokenizer_r.encode_plus(
|
| 210 |
+
sentence,
|
| 211 |
+
return_attention_mask=False,
|
| 212 |
+
return_token_type_ids=False,
|
| 213 |
+
return_offsets_mapping=True,
|
| 214 |
+
add_special_tokens=True,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, "do_lower_case") else False
|
| 218 |
+
expected_results = (
|
| 219 |
+
[
|
| 220 |
+
((0, 0), tokenizer_r.cls_token),
|
| 221 |
+
((0, 1), "A"),
|
| 222 |
+
((1, 2), ","),
|
| 223 |
+
((3, 5), "na"),
|
| 224 |
+
((5, 6), "##ï"),
|
| 225 |
+
((6, 8), "##ve"),
|
| 226 |
+
((9, 15), tokenizer_r.mask_token),
|
| 227 |
+
((16, 21), "Allen"),
|
| 228 |
+
((21, 23), "##NL"),
|
| 229 |
+
((23, 24), "##P"),
|
| 230 |
+
((25, 33), "sentence"),
|
| 231 |
+
((33, 34), "."),
|
| 232 |
+
((0, 0), tokenizer_r.sep_token),
|
| 233 |
+
]
|
| 234 |
+
if not do_lower_case
|
| 235 |
+
else [
|
| 236 |
+
((0, 0), tokenizer_r.cls_token),
|
| 237 |
+
((0, 1), "a"),
|
| 238 |
+
((1, 2), ","),
|
| 239 |
+
((3, 8), "naive"),
|
| 240 |
+
((9, 15), tokenizer_r.mask_token),
|
| 241 |
+
((16, 21), "allen"),
|
| 242 |
+
((21, 23), "##nl"),
|
| 243 |
+
((23, 24), "##p"),
|
| 244 |
+
((25, 33), "sentence"),
|
| 245 |
+
((33, 34), "."),
|
| 246 |
+
((0, 0), tokenizer_r.sep_token),
|
| 247 |
+
]
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
self.assertEqual(
|
| 251 |
+
[e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["input_ids"])
|
| 252 |
+
)
|
| 253 |
+
self.assertEqual([e[0] for e in expected_results], tokens["offset_mapping"])
|
| 254 |
+
|
| 255 |
+
# Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_change_tokenize_chinese_chars
|
| 256 |
+
def test_change_tokenize_chinese_chars(self):
|
| 257 |
+
list_of_commun_chinese_char = ["的", "人", "有"]
|
| 258 |
+
text_with_chinese_char = "".join(list_of_commun_chinese_char)
|
| 259 |
+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
|
| 260 |
+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
|
| 261 |
+
kwargs["tokenize_chinese_chars"] = True
|
| 262 |
+
tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 263 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 264 |
+
|
| 265 |
+
ids_without_spe_char_p = tokenizer_p.encode(text_with_chinese_char, add_special_tokens=False)
|
| 266 |
+
ids_without_spe_char_r = tokenizer_r.encode(text_with_chinese_char, add_special_tokens=False)
|
| 267 |
+
|
| 268 |
+
tokens_without_spe_char_r = tokenizer_r.convert_ids_to_tokens(ids_without_spe_char_r)
|
| 269 |
+
tokens_without_spe_char_p = tokenizer_p.convert_ids_to_tokens(ids_without_spe_char_p)
|
| 270 |
+
|
| 271 |
+
# it is expected that each Chinese character is not preceded by "##"
|
| 272 |
+
self.assertListEqual(tokens_without_spe_char_p, list_of_commun_chinese_char)
|
| 273 |
+
self.assertListEqual(tokens_without_spe_char_r, list_of_commun_chinese_char)
|
| 274 |
+
|
| 275 |
+
kwargs["tokenize_chinese_chars"] = False
|
| 276 |
+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 277 |
+
tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
|
| 278 |
+
|
| 279 |
+
ids_without_spe_char_r = tokenizer_r.encode(text_with_chinese_char, add_special_tokens=False)
|
| 280 |
+
ids_without_spe_char_p = tokenizer_p.encode(text_with_chinese_char, add_special_tokens=False)
|
| 281 |
+
|
| 282 |
+
tokens_without_spe_char_r = tokenizer_r.convert_ids_to_tokens(ids_without_spe_char_r)
|
| 283 |
+
tokens_without_spe_char_p = tokenizer_p.convert_ids_to_tokens(ids_without_spe_char_p)
|
| 284 |
+
|
| 285 |
+
# it is expected that only the first Chinese character is not preceded by "##".
|
| 286 |
+
expected_tokens = [
|
| 287 |
+
f"##{token}" if idx != 0 else token for idx, token in enumerate(list_of_commun_chinese_char)
|
| 288 |
+
]
|
| 289 |
+
self.assertListEqual(tokens_without_spe_char_p, expected_tokens)
|
| 290 |
+
self.assertListEqual(tokens_without_spe_char_r, expected_tokens)
|
| 291 |
+
|
| 292 |
+
@slow
|
| 293 |
+
def test_sequence_builders(self):
|
| 294 |
+
tokenizer = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file)
|
| 295 |
+
|
| 296 |
+
text = tokenizer.encode("你好", add_special_tokens=False)
|
| 297 |
+
text_2 = tokenizer.encode("你是谁", add_special_tokens=False)
|
| 298 |
+
|
| 299 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 300 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 301 |
+
|
| 302 |
+
assert encoded_sentence == [1] + text + [2]
|
| 303 |
+
assert encoded_pair == [1] + text + [2] + text_2 + [2]
|
| 304 |
+
|
| 305 |
+
def test_prepare_for_model(self):
|
| 306 |
+
tokenizers = self.get_tokenizers(do_lower_case=False)
|
| 307 |
+
for tokenizer in tokenizers:
|
| 308 |
+
with self.subTest(f"{tokenizer.__class__.__name__}"):
|
| 309 |
+
string_sequence = "你好,你是谁"
|
| 310 |
+
tokens = tokenizer.tokenize(string_sequence)
|
| 311 |
+
tokens_ids = tokenizer.convert_tokens_to_ids(tokens)
|
| 312 |
+
tokens_shape_ids = tokenizer.convert_tokens_to_shape_ids(tokens)
|
| 313 |
+
tokens_proun_ids = tokenizer.convert_tokens_to_pronunciation_ids(tokens)
|
| 314 |
+
prepared_input_dict = tokenizer.prepare_for_model(
|
| 315 |
+
tokens_ids, tokens_shape_ids, tokens_proun_ids, add_special_tokens=True
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
input_dict = tokenizer.encode_plus(string_sequence, add_special_tokens=True)
|
| 319 |
+
|
| 320 |
+
self.assertEqual(input_dict, prepared_input_dict)
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/__init__.py
ADDED
|
File without changes
|
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_flax_roformer.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from transformers import RoFormerConfig, is_flax_available
|
| 20 |
+
from transformers.testing_utils import require_flax, slow
|
| 21 |
+
|
| 22 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_flax_available():
|
| 26 |
+
import jax.numpy as jnp
|
| 27 |
+
|
| 28 |
+
from transformers.models.roformer.modeling_flax_roformer import (
|
| 29 |
+
FlaxRoFormerForMaskedLM,
|
| 30 |
+
FlaxRoFormerForMultipleChoice,
|
| 31 |
+
FlaxRoFormerForQuestionAnswering,
|
| 32 |
+
FlaxRoFormerForSequenceClassification,
|
| 33 |
+
FlaxRoFormerForTokenClassification,
|
| 34 |
+
FlaxRoFormerModel,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FlaxRoFormerModelTester(unittest.TestCase):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parent,
|
| 42 |
+
batch_size=13,
|
| 43 |
+
seq_length=7,
|
| 44 |
+
is_training=True,
|
| 45 |
+
use_attention_mask=True,
|
| 46 |
+
use_token_type_ids=True,
|
| 47 |
+
use_labels=True,
|
| 48 |
+
vocab_size=99,
|
| 49 |
+
hidden_size=32,
|
| 50 |
+
num_hidden_layers=2,
|
| 51 |
+
num_attention_heads=4,
|
| 52 |
+
intermediate_size=37,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
hidden_dropout_prob=0.1,
|
| 55 |
+
attention_probs_dropout_prob=0.1,
|
| 56 |
+
max_position_embeddings=512,
|
| 57 |
+
type_vocab_size=16,
|
| 58 |
+
type_sequence_label_size=2,
|
| 59 |
+
initializer_range=0.02,
|
| 60 |
+
num_choices=4,
|
| 61 |
+
):
|
| 62 |
+
self.parent = parent
|
| 63 |
+
self.batch_size = batch_size
|
| 64 |
+
self.seq_length = seq_length
|
| 65 |
+
self.is_training = is_training
|
| 66 |
+
self.use_attention_mask = use_attention_mask
|
| 67 |
+
self.use_token_type_ids = use_token_type_ids
|
| 68 |
+
self.use_labels = use_labels
|
| 69 |
+
self.vocab_size = vocab_size
|
| 70 |
+
self.hidden_size = hidden_size
|
| 71 |
+
self.num_hidden_layers = num_hidden_layers
|
| 72 |
+
self.num_attention_heads = num_attention_heads
|
| 73 |
+
self.intermediate_size = intermediate_size
|
| 74 |
+
self.hidden_act = hidden_act
|
| 75 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 76 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 77 |
+
self.max_position_embeddings = max_position_embeddings
|
| 78 |
+
self.type_vocab_size = type_vocab_size
|
| 79 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 80 |
+
self.initializer_range = initializer_range
|
| 81 |
+
self.num_choices = num_choices
|
| 82 |
+
|
| 83 |
+
def prepare_config_and_inputs(self):
|
| 84 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 85 |
+
|
| 86 |
+
attention_mask = None
|
| 87 |
+
if self.use_attention_mask:
|
| 88 |
+
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 89 |
+
|
| 90 |
+
token_type_ids = None
|
| 91 |
+
if self.use_token_type_ids:
|
| 92 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 93 |
+
|
| 94 |
+
config = RoFormerConfig(
|
| 95 |
+
vocab_size=self.vocab_size,
|
| 96 |
+
hidden_size=self.hidden_size,
|
| 97 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 98 |
+
num_attention_heads=self.num_attention_heads,
|
| 99 |
+
intermediate_size=self.intermediate_size,
|
| 100 |
+
hidden_act=self.hidden_act,
|
| 101 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 102 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 103 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 104 |
+
type_vocab_size=self.type_vocab_size,
|
| 105 |
+
is_decoder=False,
|
| 106 |
+
initializer_range=self.initializer_range,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
return config, input_ids, token_type_ids, attention_mask
|
| 110 |
+
|
| 111 |
+
def prepare_config_and_inputs_for_common(self):
|
| 112 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 113 |
+
config, input_ids, token_type_ids, attention_mask = config_and_inputs
|
| 114 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
|
| 115 |
+
return config, inputs_dict
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@require_flax
|
| 119 |
+
class FlaxRoFormerModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 120 |
+
test_head_masking = True
|
| 121 |
+
|
| 122 |
+
all_model_classes = (
|
| 123 |
+
(
|
| 124 |
+
FlaxRoFormerModel,
|
| 125 |
+
FlaxRoFormerForMaskedLM,
|
| 126 |
+
FlaxRoFormerForSequenceClassification,
|
| 127 |
+
FlaxRoFormerForTokenClassification,
|
| 128 |
+
FlaxRoFormerForMultipleChoice,
|
| 129 |
+
FlaxRoFormerForQuestionAnswering,
|
| 130 |
+
)
|
| 131 |
+
if is_flax_available()
|
| 132 |
+
else ()
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def setUp(self):
|
| 136 |
+
self.model_tester = FlaxRoFormerModelTester(self)
|
| 137 |
+
|
| 138 |
+
@slow
|
| 139 |
+
def test_model_from_pretrained(self):
|
| 140 |
+
for model_class_name in self.all_model_classes:
|
| 141 |
+
model = model_class_name.from_pretrained("junnyu/roformer_chinese_small", from_pt=True)
|
| 142 |
+
outputs = model(np.ones((1, 1)))
|
| 143 |
+
self.assertIsNotNone(outputs)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@require_flax
|
| 147 |
+
class FlaxRoFormerModelIntegrationTest(unittest.TestCase):
|
| 148 |
+
@slow
|
| 149 |
+
def test_inference_masked_lm(self):
|
| 150 |
+
model = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base")
|
| 151 |
+
input_ids = jnp.array([[0, 1, 2, 3, 4, 5]])
|
| 152 |
+
output = model(input_ids)[0]
|
| 153 |
+
|
| 154 |
+
vocab_size = 50000
|
| 155 |
+
|
| 156 |
+
expected_shape = (1, 6, vocab_size)
|
| 157 |
+
self.assertEqual(output.shape, expected_shape)
|
| 158 |
+
|
| 159 |
+
expected_slice = jnp.array(
|
| 160 |
+
[[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
self.assertTrue(jnp.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
|