"tests/models/roberta/test_modeling_flax_roberta.py" did not exist on "31616b8d613dcb7ac69b562d51b42d0db379f72f"
test_feature_extraction_speech_to_text.py 11.7 KB
Newer Older
Suraj Patil's avatar
Suraj Patil committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# coding=utf-8
# Copyright 2021 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import itertools
import random
import unittest

import numpy as np

23
from transformers import is_speech_available
Suraj Patil's avatar
Suraj Patil committed
24
25
26
27
28
from transformers.testing_utils import require_torch, require_torchaudio

from .test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


29
30
31
if is_speech_available():
    from transformers import Speech2TextFeatureExtractor

Suraj Patil's avatar
Suraj Patil committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
global_rng = random.Random()


def floats_list(shape, scale=1.0, rng=None, name=None):
    """Creates a random float32 tensor"""
    if rng is None:
        rng = global_rng

    values = []
    for batch_idx in range(shape[0]):
        values.append([])
        for _ in range(shape[1]):
            values[-1].append(rng.random() * scale)

    return values


@require_torch
@require_torchaudio
class Speech2TextFeatureExtractionTester(unittest.TestCase):
    def __init__(
        self,
        parent,
        batch_size=7,
        min_seq_length=400,
        max_seq_length=2000,
        feature_size=24,
        num_mel_bins=24,
        padding_value=0.0,
        sampling_rate=16_000,
        return_attention_mask=True,
        do_normalize=True,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.min_seq_length = min_seq_length
        self.max_seq_length = max_seq_length
        self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        self.feature_size = feature_size
        self.num_mel_bins = num_mel_bins
        self.padding_value = padding_value
        self.sampling_rate = sampling_rate
        self.return_attention_mask = return_attention_mask
        self.do_normalize = do_normalize

    def prepare_feat_extract_dict(self):
        return {
            "feature_size": self.feature_size,
            "num_mel_bins": self.num_mel_bins,
            "padding_value": self.padding_value,
            "sampling_rate": self.sampling_rate,
            "return_attention_mask": self.return_attention_mask,
            "do_normalize": self.do_normalize,
        }

    def prepare_inputs_for_common(self, equal_length=False, numpify=False):
        def _flatten(list_of_lists):
            return list(itertools.chain(*list_of_lists))

        if equal_length:
            speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
        else:
94
            # make sure that inputs increase in size
Suraj Patil's avatar
Suraj Patil committed
95
96
97
98
99
100
101
102
103
104
105
106
107
            speech_inputs = [
                floats_list((x, self.feature_size))
                for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)
            ]
        if numpify:
            speech_inputs = [np.asarray(x) for x in speech_inputs]
        return speech_inputs


@require_torch
@require_torchaudio
class Speech2TextFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):

108
    feature_extraction_class = Speech2TextFeatureExtractor if is_speech_available() else None
Suraj Patil's avatar
Suraj Patil committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    def setUp(self):
        self.feat_extract_tester = Speech2TextFeatureExtractionTester(self)

    def test_call(self):
        # Tests that all call wrap to encode_plus and batch_encode_plus
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        # create three inputs of length 800, 1000, and 1200
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs]

        # Test feature size
        input_features = feature_extractor(np_speech_inputs, padding=True, return_tensors="np").input_features
        self.assertTrue(input_features.ndim == 3)
        self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size)

        # Test not batched input
        encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features
        encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features
        self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3))

        # Test batched
        encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features
        encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features
        for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):
            self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))

    def test_cepstral_mean_and_variance_normalization(self):
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
139

Patrick von Platen's avatar
Patrick von Platen committed
140
141
        # TODO(Patrick, Suraj, Anton) - It's surprising that "non-padded/non-numpified" padding
        # results in quite inaccurate variance computation after (see 5e-1 tolerance)
Patrick von Platen's avatar
Patrick von Platen committed
142
143
144
145
146
147
148
        # Issue is filed and PR is underway: https://github.com/huggingface/transformers/issues/13539
        #        paddings = ["longest", "max_length", "do_not_pad"]
        #        max_lengths = [None, 16, None]
        #        var_tolerances = [1e-3, 1e-3, 5e-1]
        paddings = ["longest", "max_length"]
        max_lengths = [None, 16]
        var_tolerances = [1e-3, 1e-3]
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        for max_length, padding, var_tol in zip(max_lengths, paddings, var_tolerances):

            inputs = feature_extractor(
                speech_inputs, padding=padding, max_length=max_length, return_attention_mask=True
            )
            input_features = inputs.input_features
            attention_mask = inputs.attention_mask
            fbank_feat_lengths = [np.sum(x) for x in attention_mask]

            def _check_zero_mean_unit_variance(input_vector, var_tol=1e-3):
                self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3))
                self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < var_tol))

            _check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]], var_tol)
            _check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]], var_tol)
            _check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]], var_tol)

    def test_cepstral_mean_and_variance_normalization_np(self):
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]

Patrick von Platen's avatar
Patrick von Platen committed
170
171
        # TODO(Patrick, Suraj, Anton) - It's surprising that "non-padded/non-numpified" padding
        # results in quite inaccurate variance computation after (see 5e-1 tolerance)
Patrick von Platen's avatar
Patrick von Platen committed
172
173
174
175
176
177
178
        # Issue is filed and PR is underway: https://github.com/huggingface/transformers/issues/13539
        #        paddings = ["longest", "max_length", "do_not_pad"]
        #        max_lengths = [None, 16, None]
        #        var_tolerances = [1e-3, 1e-3, 5e-1]
        paddings = ["longest", "max_length"]
        max_lengths = [None, 16]
        var_tolerances = [1e-3, 1e-3]
179
180
181
182
183
184
185
186
187
188
189
190
191
        for max_length, padding, var_tol in zip(max_lengths, paddings, var_tolerances):
            inputs = feature_extractor(
                speech_inputs, max_length=max_length, padding=padding, return_tensors="np", return_attention_mask=True
            )
            input_features = inputs.input_features
            attention_mask = inputs.attention_mask
            fbank_feat_lengths = [np.sum(x) for x in attention_mask]

            def _check_zero_mean_unit_variance(input_vector, var_tol=1e-3):
                self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3))
                self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < var_tol))

            _check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]], var_tol)
192
            self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6)
193
            _check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]], var_tol)
194
            self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6)
195
            _check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]], var_tol)
196

197
    def test_cepstral_mean_and_variance_normalization_trunc_max_length(self):
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        inputs = feature_extractor(
            speech_inputs,
            padding="max_length",
            max_length=4,
            truncation=True,
            return_tensors="np",
            return_attention_mask=True,
        )
        input_features = inputs.input_features
        attention_mask = inputs.attention_mask
        fbank_feat_lengths = np.sum(attention_mask == 1, axis=1)

        def _check_zero_mean_unit_variance(input_vector):
            self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3))
            self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3))

        _check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
        _check_zero_mean_unit_variance(input_features[1])
        _check_zero_mean_unit_variance(input_features[2])
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264

    def test_cepstral_mean_and_variance_normalization_trunc_longest(self):
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        inputs = feature_extractor(
            speech_inputs,
            padding="longest",
            max_length=4,
            truncation=True,
            return_tensors="np",
            return_attention_mask=True,
        )
        input_features = inputs.input_features
        attention_mask = inputs.attention_mask
        fbank_feat_lengths = np.sum(attention_mask == 1, axis=1)

        def _check_zero_mean_unit_variance(input_vector):
            self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3))
            self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3))

        _check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
        _check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
        _check_zero_mean_unit_variance(input_features[2])

        # make sure that if max_length < longest -> then pad to max_length
        self.assertEqual(input_features.shape, (3, 4, 24))

        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        inputs = feature_extractor(
            speech_inputs,
            padding="longest",
            max_length=16,
            truncation=True,
            return_tensors="np",
            return_attention_mask=True,
        )
        input_features = inputs.input_features
        attention_mask = inputs.attention_mask
        fbank_feat_lengths = np.sum(attention_mask == 1, axis=1)

        _check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
        _check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
        _check_zero_mean_unit_variance(input_features[2])

        # make sure that if max_length < longest -> then pad to max_length
        self.assertEqual(input_features.shape, (3, 6, 24))