transformers
255 строк · 11.2 Кб
1# coding=utf-8
2# Copyright 2022 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
17import itertools18import os19import random20import tempfile21import unittest22
23import numpy as np24from datasets import load_dataset25
26from transformers import WhisperFeatureExtractor27from transformers.testing_utils import check_json_file_has_correct_format, require_torch28from transformers.utils.import_utils import is_torch_available29
30from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin31
32
33if is_torch_available():34import torch35
36global_rng = random.Random()37
38
39def floats_list(shape, scale=1.0, rng=None, name=None):40"""Creates a random float32 tensor"""41if rng is None:42rng = global_rng43
44values = []45for batch_idx in range(shape[0]):46values.append([])47for _ in range(shape[1]):48values[-1].append(rng.random() * scale)49
50return values51
52
53class WhisperFeatureExtractionTester(unittest.TestCase):54def __init__(55self,56parent,57batch_size=7,58min_seq_length=400,59max_seq_length=2000,60feature_size=10,61hop_length=160,62chunk_length=8,63padding_value=0.0,64sampling_rate=4_000,65return_attention_mask=False,66do_normalize=True,67):68self.parent = parent69self.batch_size = batch_size70self.min_seq_length = min_seq_length71self.max_seq_length = max_seq_length72self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)73self.padding_value = padding_value74self.sampling_rate = sampling_rate75self.return_attention_mask = return_attention_mask76self.do_normalize = do_normalize77self.feature_size = feature_size78self.chunk_length = chunk_length79self.hop_length = hop_length80
81def prepare_feat_extract_dict(self):82return {83"feature_size": self.feature_size,84"hop_length": self.hop_length,85"chunk_length": self.chunk_length,86"padding_value": self.padding_value,87"sampling_rate": self.sampling_rate,88"return_attention_mask": self.return_attention_mask,89"do_normalize": self.do_normalize,90}91
92def prepare_inputs_for_common(self, equal_length=False, numpify=False):93def _flatten(list_of_lists):94return list(itertools.chain(*list_of_lists))95
96if equal_length:97speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]98else:99# make sure that inputs increase in size100speech_inputs = [101floats_list((x, self.feature_size))102for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)103]104if numpify:105speech_inputs = [np.asarray(x) for x in speech_inputs]106return speech_inputs107
108
109class WhisperFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):110feature_extraction_class = WhisperFeatureExtractor111
112def setUp(self):113self.feat_extract_tester = WhisperFeatureExtractionTester(self)114
115def test_feat_extract_from_and_save_pretrained(self):116feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)117
118with tempfile.TemporaryDirectory() as tmpdirname:119saved_file = feat_extract_first.save_pretrained(tmpdirname)[0]120check_json_file_has_correct_format(saved_file)121feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname)122
123dict_first = feat_extract_first.to_dict()124dict_second = feat_extract_second.to_dict()125mel_1 = feat_extract_first.mel_filters126mel_2 = feat_extract_second.mel_filters127self.assertTrue(np.allclose(mel_1, mel_2))128self.assertEqual(dict_first, dict_second)129
130def test_feat_extract_to_json_file(self):131feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)132
133with tempfile.TemporaryDirectory() as tmpdirname:134json_file_path = os.path.join(tmpdirname, "feat_extract.json")135feat_extract_first.to_json_file(json_file_path)136feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path)137
138dict_first = feat_extract_first.to_dict()139dict_second = feat_extract_second.to_dict()140mel_1 = feat_extract_first.mel_filters141mel_2 = feat_extract_second.mel_filters142self.assertTrue(np.allclose(mel_1, mel_2))143self.assertEqual(dict_first, dict_second)144
145def test_call(self):146# Tests that all call wrap to encode_plus and batch_encode_plus147feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())148# create three inputs of length 800, 1000, and 1200149speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]150np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs]151
152# Test feature size153input_features = feature_extractor(np_speech_inputs, padding="max_length", return_tensors="np").input_features154self.assertTrue(input_features.ndim == 3)155self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames)156self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size)157
158# Test not batched input159encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features160encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features161self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3))162
163# Test batched164encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features165encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features166for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):167self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))168
169# Test 2-D numpy arrays are batched.170speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)]171np_speech_inputs = np.asarray(speech_inputs)172encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features173encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features174for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):175self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))176
177# Test truncation required178speech_inputs = [floats_list((1, x))[0] for x in range(200, (feature_extractor.n_samples + 500), 200)]179np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs]180
181speech_inputs_truncated = [x[: feature_extractor.n_samples] for x in speech_inputs]182np_speech_inputs_truncated = [np.asarray(speech_input) for speech_input in speech_inputs_truncated]183
184encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features185encoded_sequences_2 = feature_extractor(np_speech_inputs_truncated, return_tensors="np").input_features186for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):187self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))188
189@require_torch190def test_double_precision_pad(self):191import torch192
193feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())194np_speech_inputs = np.random.rand(100, 32).astype(np.float64)195py_speech_inputs = np_speech_inputs.tolist()196
197for inputs in [py_speech_inputs, np_speech_inputs]:198np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np")199self.assertTrue(np_processed.input_features.dtype == np.float32)200pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt")201self.assertTrue(pt_processed.input_features.dtype == torch.float32)202
203def _load_datasamples(self, num_samples):204ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")205# automatic decoding with librispeech206speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"]207
208return [x["array"] for x in speech_samples]209
210@require_torch211def test_torch_integration(self):212# fmt: off213EXPECTED_INPUT_FEATURES = torch.tensor(214[2150.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951,2160.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678,2170.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554,218-0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854219]220)221# fmt: on222
223input_speech = self._load_datasamples(1)224feature_extractor = WhisperFeatureExtractor()225input_features = feature_extractor(input_speech, return_tensors="pt").input_features226self.assertEqual(input_features.shape, (1, 80, 3000))227self.assertTrue(torch.allclose(input_features[0, 0, :30], EXPECTED_INPUT_FEATURES, atol=1e-4))228
229@unittest.mock.patch("transformers.models.whisper.feature_extraction_whisper.is_torch_available", lambda: False)230def test_numpy_integration(self):231# fmt: off232EXPECTED_INPUT_FEATURES = np.array(233[2340.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951,2350.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678,2360.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554,237-0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854238]239)240# fmt: on241
242input_speech = self._load_datasamples(1)243feature_extractor = WhisperFeatureExtractor()244input_features = feature_extractor(input_speech, return_tensors="np").input_features245self.assertEqual(input_features.shape, (1, 80, 3000))246self.assertTrue(np.allclose(input_features[0, 0, :30], EXPECTED_INPUT_FEATURES, atol=1e-4))247
248def test_zero_mean_unit_variance_normalization_trunc_np_longest(self):249feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())250audio = self._load_datasamples(1)[0]251audio = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535 # Rescale to [0, 65535] to show issue252audio = feat_extract.zero_mean_unit_var_norm([audio], attention_mask=None)[0]253
254self.assertTrue(np.all(np.mean(audio) < 1e-3))255self.assertTrue(np.all(np.abs(np.var(audio) - 1) < 1e-3))256