sanchit-gandhi HF staff commited on
Commit
d7a48d8
1 Parent(s): e0695a7
config.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SpeechEncoderDecoderModel"
4
+ ],
5
+ "decoder": {
6
+ "_name_or_path": "decoder",
7
+ "activation_dropout": 0.1,
8
+ "activation_function": "gelu",
9
+ "add_bias_logits": false,
10
+ "add_cross_attention": true,
11
+ "add_final_layer_norm": false,
12
+ "architectures": [
13
+ "BartForCausalLM"
14
+ ],
15
+ "attention_dropout": 0.1,
16
+ "bad_words_ids": null,
17
+ "bos_token_id": 0,
18
+ "chunk_size_feed_forward": 0,
19
+ "classif_dropout": 0.1,
20
+ "classifier_dropout": 0.0,
21
+ "cross_attention_hidden_size": null,
22
+ "d_model": 1024,
23
+ "decoder_attention_heads": 16,
24
+ "decoder_ffn_dim": 4096,
25
+ "decoder_layerdrop": 0.0,
26
+ "decoder_layers": 12,
27
+ "decoder_start_token_id": 2,
28
+ "diversity_penalty": 0.0,
29
+ "do_sample": false,
30
+ "dropout": 0.1,
31
+ "early_stopping": true,
32
+ "encoder_attention_heads": 16,
33
+ "encoder_ffn_dim": 4096,
34
+ "encoder_layerdrop": 0.0,
35
+ "encoder_layers": 12,
36
+ "encoder_no_repeat_ngram_size": 0,
37
+ "eos_token_id": 2,
38
+ "finetuning_task": null,
39
+ "forced_bos_token_id": 0,
40
+ "forced_eos_token_id": 2,
41
+ "gradient_checkpointing": false,
42
+ "id2label": {
43
+ "0": "LABEL_0",
44
+ "1": "LABEL_1",
45
+ "2": "LABEL_2"
46
+ },
47
+ "init_std": 0.02,
48
+ "is_decoder": true,
49
+ "is_encoder_decoder": false,
50
+ "label2id": {
51
+ "LABEL_0": 0,
52
+ "LABEL_1": 1,
53
+ "LABEL_2": 2
54
+ },
55
+ "length_penalty": 1.0,
56
+ "max_length": 20,
57
+ "max_position_embeddings": 1024,
58
+ "min_length": 0,
59
+ "model_type": "bart",
60
+ "no_repeat_ngram_size": 3,
61
+ "normalize_before": false,
62
+ "num_beam_groups": 1,
63
+ "num_beams": 4,
64
+ "num_hidden_layers": 12,
65
+ "num_return_sequences": 1,
66
+ "output_attentions": false,
67
+ "output_hidden_states": false,
68
+ "output_scores": false,
69
+ "pad_token_id": 1,
70
+ "prefix": null,
71
+ "problem_type": null,
72
+ "pruned_heads": {},
73
+ "remove_invalid_values": false,
74
+ "repetition_penalty": 1.0,
75
+ "return_dict": true,
76
+ "return_dict_in_generate": false,
77
+ "scale_embedding": false,
78
+ "sep_token_id": null,
79
+ "task_specific_params": {
80
+ "summarization": {
81
+ "length_penalty": 1.0,
82
+ "max_length": 128,
83
+ "min_length": 12,
84
+ "num_beams": 4
85
+ },
86
+ "summarization_cnn": {
87
+ "length_penalty": 2.0,
88
+ "max_length": 142,
89
+ "min_length": 56,
90
+ "num_beams": 4
91
+ },
92
+ "summarization_xsum": {
93
+ "length_penalty": 1.0,
94
+ "max_length": 62,
95
+ "min_length": 11,
96
+ "num_beams": 6
97
+ }
98
+ },
99
+ "temperature": 1.0,
100
+ "tie_encoder_decoder": false,
101
+ "tie_word_embeddings": true,
102
+ "tokenizer_class": null,
103
+ "top_k": 50,
104
+ "top_p": 1.0,
105
+ "torch_dtype": "float32",
106
+ "torchscript": false,
107
+ "transformers_version": "4.17.0.dev0",
108
+ "use_bfloat16": false,
109
+ "use_cache": false,
110
+ "vocab_size": 50265
111
+ },
112
+ "decoder_start_token_id": 0,
113
+ "encoder": {
114
+ "_name_or_path": "facebook/wav2vec2-large-lv60",
115
+ "activation_dropout": 0.1,
116
+ "adapter_kernel_size": 3,
117
+ "adapter_stride": 2,
118
+ "add_adapter": true,
119
+ "add_cross_attention": false,
120
+ "apply_spec_augment": true,
121
+ "architectures": [
122
+ "Wav2Vec2ForPreTraining"
123
+ ],
124
+ "attention_dropout": 0.1,
125
+ "bad_words_ids": null,
126
+ "bos_token_id": 1,
127
+ "chunk_size_feed_forward": 0,
128
+ "classifier_proj_size": 256,
129
+ "codevector_dim": 768,
130
+ "contrastive_logits_temperature": 0.1,
131
+ "conv_bias": true,
132
+ "conv_dim": [
133
+ 512,
134
+ 512,
135
+ 512,
136
+ 512,
137
+ 512,
138
+ 512,
139
+ 512
140
+ ],
141
+ "conv_kernel": [
142
+ 10,
143
+ 3,
144
+ 3,
145
+ 3,
146
+ 3,
147
+ 2,
148
+ 2
149
+ ],
150
+ "conv_stride": [
151
+ 5,
152
+ 2,
153
+ 2,
154
+ 2,
155
+ 2,
156
+ 2,
157
+ 2
158
+ ],
159
+ "cross_attention_hidden_size": null,
160
+ "ctc_loss_reduction": "sum",
161
+ "ctc_zero_infinity": false,
162
+ "decoder_start_token_id": null,
163
+ "diversity_loss_weight": 0.1,
164
+ "diversity_penalty": 0.0,
165
+ "do_sample": false,
166
+ "do_stable_layer_norm": true,
167
+ "early_stopping": false,
168
+ "encoder_no_repeat_ngram_size": 0,
169
+ "eos_token_id": 2,
170
+ "feat_extract_activation": "gelu",
171
+ "feat_extract_dropout": 0.0,
172
+ "feat_extract_norm": "layer",
173
+ "feat_proj_dropout": 0.0,
174
+ "feat_quantizer_dropout": 0.0,
175
+ "final_dropout": 0.0,
176
+ "finetuning_task": null,
177
+ "forced_bos_token_id": null,
178
+ "forced_eos_token_id": null,
179
+ "gradient_checkpointing": false,
180
+ "hidden_act": "gelu",
181
+ "hidden_dropout": 0.1,
182
+ "hidden_dropout_prob": 0.1,
183
+ "hidden_size": 1024,
184
+ "id2label": {
185
+ "0": "LABEL_0",
186
+ "1": "LABEL_1"
187
+ },
188
+ "initializer_range": 0.02,
189
+ "intermediate_size": 4096,
190
+ "is_decoder": false,
191
+ "is_encoder_decoder": false,
192
+ "label2id": {
193
+ "LABEL_0": 0,
194
+ "LABEL_1": 1
195
+ },
196
+ "layer_norm_eps": 1e-05,
197
+ "layerdrop": 0.0,
198
+ "length_penalty": 1.0,
199
+ "mask_feature_length": 10,
200
+ "mask_feature_min_masks": 0,
201
+ "mask_feature_prob": 0.0,
202
+ "mask_time_length": 10,
203
+ "mask_time_min_masks": 2,
204
+ "mask_time_prob": 0.1,
205
+ "max_length": 20,
206
+ "min_length": 0,
207
+ "model_type": "wav2vec2",
208
+ "no_repeat_ngram_size": 0,
209
+ "num_adapter_layers": 3,
210
+ "num_attention_heads": 16,
211
+ "num_beam_groups": 1,
212
+ "num_beams": 1,
213
+ "num_codevector_groups": 2,
214
+ "num_codevectors_per_group": 320,
215
+ "num_conv_pos_embedding_groups": 16,
216
+ "num_conv_pos_embeddings": 128,
217
+ "num_feat_extract_layers": 7,
218
+ "num_hidden_layers": 24,
219
+ "num_negatives": 100,
220
+ "num_return_sequences": 1,
221
+ "output_attentions": false,
222
+ "output_hidden_size": 1024,
223
+ "output_hidden_states": false,
224
+ "output_scores": false,
225
+ "pad_token_id": 0,
226
+ "prefix": null,
227
+ "problem_type": null,
228
+ "proj_codevector_dim": 768,
229
+ "pruned_heads": {},
230
+ "remove_invalid_values": false,
231
+ "repetition_penalty": 1.0,
232
+ "return_dict": true,
233
+ "return_dict_in_generate": false,
234
+ "sep_token_id": null,
235
+ "task_specific_params": null,
236
+ "tdnn_dilation": [
237
+ 1,
238
+ 2,
239
+ 3,
240
+ 1,
241
+ 1
242
+ ],
243
+ "tdnn_dim": [
244
+ 512,
245
+ 512,
246
+ 512,
247
+ 512,
248
+ 1500
249
+ ],
250
+ "tdnn_kernel": [
251
+ 5,
252
+ 3,
253
+ 3,
254
+ 1,
255
+ 1
256
+ ],
257
+ "temperature": 1.0,
258
+ "tie_encoder_decoder": false,
259
+ "tie_word_embeddings": true,
260
+ "tokenizer_class": null,
261
+ "top_k": 50,
262
+ "top_p": 1.0,
263
+ "torch_dtype": null,
264
+ "torchscript": false,
265
+ "transformers_version": "4.17.0.dev0",
266
+ "use_bfloat16": false,
267
+ "use_weighted_layer_sum": false,
268
+ "vocab_size": 32,
269
+ "xvector_output_dim": 512
270
+ },
271
+ "eos_token_id": 2,
272
+ "is_encoder_decoder": true,
273
+ "max_length": 50,
274
+ "model_type": "speech-encoder-decoder",
275
+ "pad_token_id": 1,
276
+ "processor_class": "Wav2Vec2Processor",
277
+ "tie_word_embeddings": false,
278
+ "torch_dtype": "float32",
279
+ "transformers_version": null,
280
+ "use_cache": false
281
+ }
create_model.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import SpeechEncoderDecoderModel, AutoFeatureExtractor, AutoTokenizer, Wav2Vec2Processor, BartConfig, BartForCausalLM
2
+ import torch
3
+
4
+ # checkpoints to leverage
5
+ encoder_id = "facebook/wav2vec2-large-lv60"
6
+ decoder_id = "facebook/bart-large"
7
+
8
+ feature_extractor = AutoFeatureExtractor.from_pretrained(encoder_id)
9
+ feature_extractor.save_pretrained("./")
10
+ tokenizer = AutoTokenizer.from_pretrained(decoder_id)
11
+ tokenizer.save_pretrained("./")
12
+
13
+ decoder_config = BartConfig.from_pretrained(decoder_id, is_decoder=True)
14
+ decoder = BartForCausalLM(decoder_config)
15
+ decoder.save_pretrained("decoder") # save the decoder
16
+
17
+ model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(encoder_id, "decoder", encoder_add_adapter=True)
18
+ model.config.decoder_start_token_id = model.decoder.config.bos_token_id
19
+ model.config.pad_token_id = model.decoder.config.pad_token_id
20
+ model.config.eos_token_id = model.decoder.config.eos_token_id
21
+ model.config.max_length = 50
22
+ model.config.num_beams = 1
23
+ model.config.encoder.layerdrop = 0.0
24
+ model.config.use_cache = False
25
+ model.config.decoder.use_cache = False
26
+ model.config.processor_class = "Wav2Vec2Processor"
27
+
28
+ # same enc regularisation as wav2vec2-2-bart
29
+ model.config.encoder.feat_proj_dropout = 0.0
30
+ model.config.encoder.final_dropout = 0.0
31
+ model.config.encoder.mask_time_prob = 0.1
32
+
33
+ # check if generation works
34
+ out = model.generate(torch.ones((1, 2000)))
35
+
36
+ model.save_pretrained("./")
37
+
38
+
decoder/config.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.1,
3
+ "activation_function": "gelu",
4
+ "add_bias_logits": false,
5
+ "add_final_layer_norm": false,
6
+ "architectures": [
7
+ "BartForCausalLM"
8
+ ],
9
+ "attention_dropout": 0.1,
10
+ "bos_token_id": 0,
11
+ "classif_dropout": 0.1,
12
+ "classifier_dropout": 0.0,
13
+ "d_model": 1024,
14
+ "decoder_attention_heads": 16,
15
+ "decoder_ffn_dim": 4096,
16
+ "decoder_layerdrop": 0.0,
17
+ "decoder_layers": 12,
18
+ "decoder_start_token_id": 2,
19
+ "dropout": 0.1,
20
+ "early_stopping": true,
21
+ "encoder_attention_heads": 16,
22
+ "encoder_ffn_dim": 4096,
23
+ "encoder_layerdrop": 0.0,
24
+ "encoder_layers": 12,
25
+ "eos_token_id": 2,
26
+ "forced_bos_token_id": 0,
27
+ "forced_eos_token_id": 2,
28
+ "gradient_checkpointing": false,
29
+ "id2label": {
30
+ "0": "LABEL_0",
31
+ "1": "LABEL_1",
32
+ "2": "LABEL_2"
33
+ },
34
+ "init_std": 0.02,
35
+ "is_decoder": true,
36
+ "is_encoder_decoder": false,
37
+ "label2id": {
38
+ "LABEL_0": 0,
39
+ "LABEL_1": 1,
40
+ "LABEL_2": 2
41
+ },
42
+ "max_position_embeddings": 1024,
43
+ "model_type": "bart",
44
+ "no_repeat_ngram_size": 3,
45
+ "normalize_before": false,
46
+ "num_beams": 4,
47
+ "num_hidden_layers": 12,
48
+ "pad_token_id": 1,
49
+ "scale_embedding": false,
50
+ "task_specific_params": {
51
+ "summarization": {
52
+ "length_penalty": 1.0,
53
+ "max_length": 128,
54
+ "min_length": 12,
55
+ "num_beams": 4
56
+ },
57
+ "summarization_cnn": {
58
+ "length_penalty": 2.0,
59
+ "max_length": 142,
60
+ "min_length": 56,
61
+ "num_beams": 4
62
+ },
63
+ "summarization_xsum": {
64
+ "length_penalty": 1.0,
65
+ "max_length": 62,
66
+ "min_length": 11,
67
+ "num_beams": 6
68
+ }
69
+ },
70
+ "torch_dtype": "float32",
71
+ "transformers_version": "4.17.0.dev0",
72
+ "use_cache": true,
73
+ "vocab_size": 50265
74
+ }
decoder/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acf0d12d6cbb678d05e22fc7cb9b59d867bba6ee761b430c2fe52080d6cf3367
3
+ size 1016449417
merges.txt ADDED
The diff for this file is too large to render. See raw diff
preprocessor_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "padding_side": "right",
6
+ "padding_value": 0.0,
7
+ "return_attention_mask": true,
8
+ "sampling_rate": 16000
9
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8650d56f95c7a13b51a4b2af6362fac0147c3bfe9ed53b8ad8f961c8cedc908c
3
+ size 2353895281
run_librispeech.sh ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ CUDA_VISIBLE_DEVICES=0 python run_speech_recognition_seq2seq.py \
3
+ --dataset_name="librispeech_asr" \
4
+ --model_name_or_path="./" \
5
+ --tokenizer_name="./" \
6
+ --dataset_config_name="clean" \
7
+ --train_split_name="train.100" \
8
+ --eval_split_name="validation" \
9
+ --output_dir="./" \
10
+ --preprocessing_num_workers="1" \
11
+ --length_column_name="input_length" \
12
+ --overwrite_output_dir \
13
+ --num_train_epochs="25" \
14
+ --per_device_train_batch_size="8" \
15
+ --per_device_eval_batch_size="8" \
16
+ --gradient_accumulation_steps="4" \
17
+ --generation_max_length="40" \
18
+ --generation_num_beams="1" \
19
+ --learning_rate="3e-5" \
20
+ --warmup_steps="1000" \
21
+ --evaluation_strategy="steps" \
22
+ --text_column_name="text" \
23
+ --save_steps="1500" \
24
+ --eval_steps="1500" \
25
+ --logging_steps="1" \
26
+ --save_total_limit="1" \
27
+ --freeze_feature_encoder \
28
+ --gradient_checkpointing \
29
+ --fp16 \
30
+ --group_by_length \
31
+ --predict_with_generate \
32
+ --do_lower_case \
33
+ --do_eval --do_train \
34
+ --push_to_hub \
35
+ --use_auth_token
36
+
run_speech_recognition_seq2seq.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team. 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
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence speech
20
+ # recognition task. Pointers for this are left as comments.
21
+
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Dict, List, Optional, Union
27
+
28
+ import datasets
29
+ import torch
30
+ from datasets import DatasetDict, load_dataset, load_metric
31
+
32
+ import bitsandbytes as bnb
33
+ import transformers
34
+ from transformers import (
35
+ AutoConfig,
36
+ AutoFeatureExtractor,
37
+ AutoModelForSpeechSeq2Seq,
38
+ AutoProcessor,
39
+ AutoTokenizer,
40
+ HfArgumentParser,
41
+ Seq2SeqTrainer,
42
+ Seq2SeqTrainingArguments,
43
+ set_seed,
44
+ )
45
+ from transformers.trainer_pt_utils import get_parameter_names
46
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
47
+ from transformers.utils import check_min_version
48
+ from transformers.utils.versions import require_version
49
+ from transformers.optimization import Adafactor
50
+
51
+
52
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
53
+ check_min_version("4.17.0.dev0")
54
+
55
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ @dataclass
61
+ class ModelArguments:
62
+ """
63
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
64
+ """
65
+
66
+ model_name_or_path: str = field(
67
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
68
+ )
69
+ config_name: Optional[str] = field(
70
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
71
+ )
72
+ tokenizer_name: Optional[str] = field(
73
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
74
+ )
75
+ feature_extractor_name: Optional[str] = field(
76
+ default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
77
+ )
78
+ cache_dir: Optional[str] = field(
79
+ default=None,
80
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
81
+ )
82
+ use_fast_tokenizer: bool = field(
83
+ default=True,
84
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
85
+ )
86
+ model_revision: str = field(
87
+ default="main",
88
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
89
+ )
90
+ use_auth_token: bool = field(
91
+ default=False,
92
+ metadata={
93
+ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
94
+ "with private models)."
95
+ },
96
+ )
97
+ freeze_feature_encoder: bool = field(
98
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
99
+ )
100
+
101
+
102
+ @dataclass
103
+ class DataTrainingArguments:
104
+ """
105
+ Arguments pertaining to what data we are going to input our model for training and eval.
106
+ """
107
+
108
+ dataset_name: str = field(
109
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
110
+ )
111
+ dataset_config_name: Optional[str] = field(
112
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
113
+ )
114
+ text_column: Optional[str] = field(
115
+ default=None,
116
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
117
+ )
118
+ overwrite_cache: bool = field(
119
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
120
+ )
121
+ preprocessing_num_workers: Optional[int] = field(
122
+ default=None,
123
+ metadata={"help": "The number of processes to use for the preprocessing."},
124
+ )
125
+ max_train_samples: Optional[int] = field(
126
+ default=None,
127
+ metadata={
128
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
129
+ "value if set."
130
+ },
131
+ )
132
+ max_eval_samples: Optional[int] = field(
133
+ default=None,
134
+ metadata={
135
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
136
+ "value if set."
137
+ },
138
+ )
139
+ audio_column_name: str = field(
140
+ default="audio",
141
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
142
+ )
143
+ text_column_name: str = field(
144
+ default="text",
145
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
146
+ )
147
+ max_duration_in_seconds: float = field(
148
+ default=20.0,
149
+ metadata={
150
+ "help": "Truncate audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
151
+ },
152
+ )
153
+ min_duration_in_seconds: float = field(
154
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
155
+ )
156
+ preprocessing_only: bool = field(
157
+ default=False,
158
+ metadata={
159
+ "help": "Whether to only do data preprocessing and skip training. "
160
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
161
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
162
+ "so that the cached datasets can consequently be loaded in distributed training"
163
+ },
164
+ )
165
+ train_split_name: str = field(
166
+ default="train",
167
+ metadata={
168
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
169
+ },
170
+ )
171
+ eval_split_name: str = field(
172
+ default="test",
173
+ metadata={
174
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
175
+ },
176
+ )
177
+ do_lower_case: bool = field(
178
+ default=True,
179
+ metadata={"help": "Whether the target text should be lower cased."},
180
+ )
181
+
182
+
183
+ @dataclass
184
+ class DataCollatorSpeechSeq2SeqWithPadding:
185
+ """
186
+ Data collator that will dynamically pad the inputs received.
187
+ Args:
188
+ processor ([`Wav2Vec2Processor`])
189
+ The processor used for proccessing the data.
190
+ decoder_start_token_id (`int`)
191
+ The begin-of-sentence of the decoder.
192
+ """
193
+
194
+ processor: Any
195
+ decoder_start_token_id: int
196
+
197
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
198
+ # split inputs and labels since they have to be of different lenghts and need
199
+ # different padding methods
200
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
201
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
202
+
203
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
204
+
205
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
206
+
207
+ # replace padding with -100 to ignore loss correctly
208
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
209
+
210
+ # if bos token is appended in previous tokenization step,
211
+ # cut bos token here as it's append later anyways
212
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
213
+ labels = labels[:, 1:]
214
+
215
+ batch["labels"] = labels
216
+
217
+ return batch
218
+
219
+
220
+ def main():
221
+ # 1. Parse input arguments
222
+ # See all possible arguments in src/transformers/training_args.py
223
+ # or by passing the --help flag to this script.
224
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
225
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
226
+
227
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
228
+ # If we pass only one argument to the script and it's the path to a json file,
229
+ # let's parse it to get our arguments.
230
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
231
+ else:
232
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
233
+
234
+ # 2. Setup logging
235
+ logging.basicConfig(
236
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
237
+ datefmt="%m/%d/%Y %H:%M:%S",
238
+ handlers=[logging.StreamHandler(sys.stdout)],
239
+ )
240
+ log_level = training_args.get_process_log_level()
241
+ logger.setLevel(log_level)
242
+ datasets.utils.logging.set_verbosity(log_level)
243
+ transformers.utils.logging.set_verbosity(log_level)
244
+ transformers.utils.logging.enable_default_handler()
245
+ transformers.utils.logging.enable_explicit_format()
246
+
247
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
248
+
249
+ # Log on each process the small summary:
250
+ logger.warning(
251
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
252
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
253
+ )
254
+ logger.info(f"Training/evaluation parameters {training_args}")
255
+
256
+ # Set the verbosity to info of the Transformers logger (on main process only):
257
+ if is_main_process(training_args.local_rank):
258
+ transformers.utils.logging.set_verbosity_info()
259
+ logger.info("Training/evaluation parameters %s", training_args)
260
+
261
+ # 3. Detecting last checkpoint and eventualy continue from last checkpoint
262
+ last_checkpoint = None
263
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
264
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
265
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
266
+ raise ValueError(
267
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
268
+ "Use --overwrite_output_dir to overcome."
269
+ )
270
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
271
+ logger.info(
272
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
273
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
274
+ )
275
+
276
+ # Set seed before initializing model.
277
+ set_seed(training_args.seed)
278
+
279
+ # 4. Load dataset
280
+ raw_datasets = DatasetDict()
281
+
282
+ if training_args.do_train:
283
+ raw_datasets["train"] = load_dataset(
284
+ data_args.dataset_name, data_args.dataset_config_name, split=data_args.train_split_name
285
+ )
286
+
287
+ if training_args.do_eval:
288
+ raw_datasets["eval"] = load_dataset(
289
+ data_args.dataset_name, data_args.dataset_config_name, split=data_args.eval_split_name
290
+ )
291
+
292
+ if data_args.audio_column_name not in next(iter(raw_datasets.values())).column_names:
293
+ raise ValueError(
294
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
295
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
296
+ f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
297
+ )
298
+
299
+ if data_args.text_column_name not in next(iter(raw_datasets.values())).column_names:
300
+ raise ValueError(
301
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
302
+ "Make sure to set `--text_column_name` to the correct text column - one of "
303
+ f"{', '.join(next(iter(raw_datasets.values())).column_names)}."
304
+ )
305
+
306
+ # 5. Load pretrained model, tokenizer, and feature extractor
307
+ #
308
+ # Distributed training:
309
+ # The .from_pretrained methods guarantee that only one local process can concurrently
310
+ config = AutoConfig.from_pretrained(
311
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
312
+ cache_dir=model_args.cache_dir,
313
+ revision=model_args.model_revision,
314
+ use_auth_token=True if model_args.use_auth_token else None,
315
+ )
316
+
317
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
318
+ model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
319
+ cache_dir=model_args.cache_dir,
320
+ revision=model_args.model_revision,
321
+ use_auth_token=True if model_args.use_auth_token else None,
322
+ )
323
+ tokenizer = AutoTokenizer.from_pretrained(
324
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
325
+ cache_dir=model_args.cache_dir,
326
+ use_fast=model_args.use_fast_tokenizer,
327
+ revision=model_args.model_revision,
328
+ use_auth_token=True if model_args.use_auth_token else None,
329
+ )
330
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
331
+ model_args.model_name_or_path,
332
+ config=config,
333
+ cache_dir=model_args.cache_dir,
334
+ revision=model_args.model_revision,
335
+ use_auth_token=True if model_args.use_auth_token else None,
336
+ )
337
+
338
+ if model.config.decoder_start_token_id is None:
339
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
340
+
341
+ if model_args.freeze_feature_encoder:
342
+ model.freeze_feature_encoder()
343
+
344
+ # 6. Resample speech dataset if necassary
345
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
346
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
347
+ raw_datasets = raw_datasets.cast_column(
348
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
349
+ )
350
+
351
+ # 7. Preprocessing the datasets.
352
+ # We need to read the audio files as arrays and tokenize the targets.
353
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
354
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
355
+ audio_column_name = data_args.audio_column_name
356
+ num_workers = data_args.preprocessing_num_workers
357
+ text_column_name = data_args.text_column_name
358
+ model_input_name = feature_extractor.model_input_names[0]
359
+ do_lower_case = data_args.do_lower_case
360
+
361
+ if data_args.max_train_samples is not None:
362
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
363
+
364
+ if data_args.max_eval_samples is not None:
365
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
366
+
367
+ def prepare_dataset(batch):
368
+ # process audio
369
+ sample = batch[audio_column_name]
370
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
371
+ # process audio length
372
+ batch[model_input_name] = inputs.input_values[0]
373
+ batch["input_length"] = len(batch["input_values"])
374
+
375
+ # process targets
376
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
377
+ batch["labels"] = tokenizer(input_str).input_ids
378
+ return batch
379
+
380
+ with training_args.main_process_first(desc="dataset map pre-processing"):
381
+ vectorized_datasets = raw_datasets.map(
382
+ prepare_dataset,
383
+ remove_columns=next(iter(raw_datasets.values())).column_names,
384
+ num_proc=data_args.preprocessing_num_workers,
385
+ desc="preprocess train dataset",
386
+ )
387
+
388
+ # filter data that is shorter than min_input_length or longer than
389
+ # max_input_length
390
+ def is_audio_in_length_range(length):
391
+ return length > min_input_length and length < max_input_length
392
+
393
+ vectorized_datasets = vectorized_datasets.filter(
394
+ is_audio_in_length_range,
395
+ num_proc=num_workers,
396
+ input_columns=["input_length"],
397
+ )
398
+
399
+ # for large datasets it is advised to run the preprocessing on a
400
+ # single machine first with `args.preprocessing_only` since there will mostly likely
401
+ # be a timeout when running the script in distributed mode.
402
+ # In a second step `args.preprocessing_only` can then be set to `False` to load the
403
+ # cached dataset
404
+ if data_args.preprocessing_only:
405
+ cache = {k: v.cache_files for k, v in vectorized_datasets.items()}
406
+ logger.info(f"Data preprocessing finished. Files cached at {cache}.")
407
+ return
408
+
409
+ # 8. Load Metric
410
+ metric = load_metric("wer")
411
+
412
+ def compute_metrics(pred):
413
+ pred_ids = pred.predictions
414
+
415
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
416
+
417
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
418
+ # we do not want to group tokens when computing the metrics
419
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
420
+
421
+ wer = metric.compute(predictions=pred_str, references=label_str)
422
+
423
+ return {"wer": wer}
424
+
425
+ # 9. Create a single speech processor
426
+ if is_main_process(training_args.local_rank):
427
+ # save feature extractor, tokenizer and config
428
+ feature_extractor.save_pretrained(training_args.output_dir)
429
+ tokenizer.save_pretrained(training_args.output_dir)
430
+ config.save_pretrained(training_args.output_dir)
431
+
432
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
433
+
434
+ # 10. Define data collator
435
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
436
+ processor=processor, decoder_start_token_id=model.config.decoder_start_token_id
437
+ )
438
+
439
+ decay_parameters = get_parameter_names(model, [torch.nn.LayerNorm])
440
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
441
+ optimizer_grouped_parameters = [
442
+ {
443
+ "params": [p for n, p in model.named_parameters() if n in decay_parameters],
444
+ "weight_decay": training_args.weight_decay,
445
+ },
446
+ {
447
+ "params": [p for n, p in model.named_parameters() if n not in decay_parameters],
448
+ "weight_decay": 0.0,
449
+ },
450
+ ]
451
+
452
+ optimizer = bnb.optim.Adam8bit(
453
+ params=optimizer_grouped_parameters,
454
+ lr=training_args.learning_rate,
455
+ betas=(training_args.adam_beta1, training_args.adam_beta2),
456
+ eps=training_args.adam_epsilon,
457
+ )
458
+
459
+ """optimizer = Adafactor(
460
+ params=optimizer_grouped_parameters,
461
+ lr=training_args.learning_rate,
462
+ beta1=training_args.adam_beta1,
463
+ eps=training_args.adam_epsilon,
464
+ relative_step=False,
465
+ )"""
466
+
467
+
468
+ optimizers = (optimizer, None)
469
+
470
+
471
+ #11. Initialize Trainer
472
+
473
+ trainer = Seq2SeqTrainer(
474
+ model=model,
475
+ args=training_args,
476
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
477
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
478
+ tokenizer=feature_extractor,
479
+ data_collator=data_collator,
480
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
481
+ optimizers=optimizers,
482
+ )
483
+
484
+ # 12. Training
485
+ if training_args.do_train:
486
+ checkpoint = None
487
+ if training_args.resume_from_checkpoint is not None:
488
+ checkpoint = training_args.resume_from_checkpoint
489
+ elif last_checkpoint is not None:
490
+ checkpoint = last_checkpoint
491
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
492
+ trainer.save_model() # Saves the feature extractor too for easy upload
493
+
494
+ metrics = train_result.metrics
495
+ max_train_samples = (
496
+ data_args.max_train_samples
497
+ if data_args.max_train_samples is not None
498
+ else len(vectorized_datasets["train"])
499
+ )
500
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
501
+ trainer.log_metrics("train", metrics)
502
+ trainer.save_metrics("train", metrics)
503
+ trainer.save_state()
504
+
505
+ # 13. Evaluation
506
+ results = {}
507
+ if training_args.do_eval:
508
+ logger.info("*** Evaluate ***")
509
+ metrics = trainer.evaluate(
510
+ metric_key_prefix="eval", max_length=model.config.max_length, num_beams=model.config.num_beams
511
+ )
512
+ max_eval_samples = (
513
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
514
+ )
515
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
516
+
517
+ trainer.log_metrics("eval", metrics)
518
+ trainer.save_metrics("eval", metrics)
519
+
520
+ # 14. Write Training Stats
521
+ kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "speech recognition"}
522
+ if data_args.dataset_name is not None:
523
+ kwargs["dataset_tags"] = data_args.dataset_name
524
+ if data_args.dataset_config_name is not None:
525
+ kwargs["dataset_args"] = data_args.dataset_config_name
526
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
527
+ else:
528
+ kwargs["dataset"] = data_args.dataset_name
529
+
530
+ if training_args.push_to_hub:
531
+ trainer.push_to_hub(**kwargs)
532
+ else:
533
+ trainer.create_model_card(**kwargs)
534
+
535
+ return results
536
+
537
+
538
+ if __name__ == "__main__":
539
+ main()
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": false}}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"errors": "replace", "bos_token": "<s>", "eos_token": "</s>", "sep_token": "</s>", "cls_token": "<s>", "unk_token": "<unk>", "pad_token": "<pad>", "mask_token": "<mask>", "add_prefix_space": false, "trim_offsets": true, "model_max_length": 1024, "special_tokens_map_file": null, "name_or_path": "facebook/bart-large", "tokenizer_class": "BartTokenizer"}
vocab.json ADDED
The diff for this file is too large to render. See raw diff