✨ Initial script configurations.
Browse files- run.sh +48 -0
- run_speech_recognition_seq2seq_streaming.py +769 -0
run.sh
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# source: https://github.com/kamfonas/whisper-fine-tuning-event/compare/master...minor-mods-by-farsipal
|
2 |
+
|
3 |
+
python run_speech_recognition_seq2seq_streaming.py \
|
4 |
+
--model_name_or_path 'openai/whisper-medium' \
|
5 |
+
--model_revision main \
|
6 |
+
--do_train True \
|
7 |
+
--do_eval True \
|
8 |
+
--use_auth_token False \
|
9 |
+
--freeze_feature_encoder False \
|
10 |
+
--freeze_encoder False \
|
11 |
+
--model_index_name 'Whisper Medium Danish (CV11 + FLEAURS)' \
|
12 |
+
--dataset_name 'mozilla-foundation/common_voice_11_0,google/fleurs' \
|
13 |
+
--dataset_config_name 'da,da_dk' \
|
14 |
+
--train_split_name 'train+validation,train+validation' \
|
15 |
+
--eval_split_name 'test,-' \
|
16 |
+
--text_column_name 'sentence,raw_transcription' \
|
17 |
+
--audio_column_name 'audio,audio' \
|
18 |
+
--streaming False \
|
19 |
+
--max_duration_in_seconds 30 \
|
20 |
+
--do_lower_case False \
|
21 |
+
--do_remove_punctuation False \
|
22 |
+
--do_normalize_eval True \
|
23 |
+
--language danish \
|
24 |
+
--task transcribe \
|
25 |
+
--shuffle_buffer_size 500 \
|
26 |
+
--output_dir './' \
|
27 |
+
--overwrite_output_dir True \
|
28 |
+
--per_device_train_batch_size 32 \
|
29 |
+
--gradient_accumulation_steps 1 \
|
30 |
+
--learning_rate 8e-6 \
|
31 |
+
--dropout 0.1 \
|
32 |
+
--warmup_steps 500 \
|
33 |
+
--max_steps 10000 \
|
34 |
+
--eval_steps 1000 \
|
35 |
+
--gradient_checkpointing True \
|
36 |
+
--cache_dir '~/.cache' \
|
37 |
+
--fp16 True \
|
38 |
+
--evaluation_strategy steps \
|
39 |
+
--per_device_eval_batch_size 8 \
|
40 |
+
--predict_with_generate True \
|
41 |
+
--generation_max_length 225 \
|
42 |
+
--save_steps 1000 \
|
43 |
+
--logging_steps 25 \
|
44 |
+
--report_to tensorboard \
|
45 |
+
--load_best_model_at_end True \
|
46 |
+
--metric_for_best_model wer \
|
47 |
+
--greater_is_better False \
|
48 |
+
--push_to_hub
|
run_speech_recognition_seq2seq_streaming.py
ADDED
@@ -0,0 +1,769 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2022 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 |
+
with 🤗 Datasets' streaming mode.
|
19 |
+
"""
|
20 |
+
# This progam was modified by Michael Kamfonas (mkamfonas@infokarta.com) on Dec 11 2022
|
21 |
+
# - added options for drpout, gradient_checkpointing, use_cache, stopping_strategy and streaming
|
22 |
+
# - restructured it to enable both streaming and non-streaming modes
|
23 |
+
# - allows concatenation of mutiple datasets (single-string comma-separated) for interleaving
|
24 |
+
# The following params must have the same number of comma-separated (,) elements:
|
25 |
+
# dataset_name,
|
26 |
+
# dataset_config_name,
|
27 |
+
# train_split_name and eval_split_name (each element plus-separated (+) for multiple splits),
|
28 |
+
# text_column_name and audio_column_name
|
29 |
+
|
30 |
+
|
31 |
+
import logging
|
32 |
+
import os
|
33 |
+
import sys
|
34 |
+
from dataclasses import dataclass, field
|
35 |
+
from typing import Any, Dict, List, Optional, Union
|
36 |
+
|
37 |
+
import datasets
|
38 |
+
import torch
|
39 |
+
from datasets import Audio, DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
|
40 |
+
from torch.utils.data import IterableDataset
|
41 |
+
|
42 |
+
import evaluate
|
43 |
+
import transformers
|
44 |
+
from transformers import (
|
45 |
+
AutoConfig,
|
46 |
+
AutoFeatureExtractor,
|
47 |
+
AutoModelForSpeechSeq2Seq,
|
48 |
+
AutoProcessor,
|
49 |
+
AutoTokenizer,
|
50 |
+
HfArgumentParser,
|
51 |
+
Seq2SeqTrainer,
|
52 |
+
Seq2SeqTrainingArguments,
|
53 |
+
TrainerCallback,
|
54 |
+
set_seed,
|
55 |
+
)
|
56 |
+
from transformers.trainer_pt_utils import IterableDatasetShard
|
57 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
58 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
59 |
+
from transformers.utils.versions import require_version
|
60 |
+
from transformers.models.whisper.english_normalizer import BasicTextNormalizer
|
61 |
+
|
62 |
+
TEXT_COL_NAME="text"
|
63 |
+
AUDIO_COL_NAME="audio"
|
64 |
+
|
65 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
66 |
+
check_min_version("4.25.0.dev0")
|
67 |
+
|
68 |
+
require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
|
69 |
+
|
70 |
+
logger = logging.getLogger(__name__)
|
71 |
+
|
72 |
+
|
73 |
+
@dataclass
|
74 |
+
class ModelArguments:
|
75 |
+
"""
|
76 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
77 |
+
"""
|
78 |
+
|
79 |
+
model_name_or_path: str = field(
|
80 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
81 |
+
)
|
82 |
+
config_name: Optional[str] = field(
|
83 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
84 |
+
)
|
85 |
+
tokenizer_name: Optional[str] = field(
|
86 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
87 |
+
)
|
88 |
+
feature_extractor_name: Optional[str] = field(
|
89 |
+
default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
|
90 |
+
)
|
91 |
+
cache_dir: Optional[str] = field(
|
92 |
+
default=None,
|
93 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
94 |
+
)
|
95 |
+
use_fast_tokenizer: bool = field(
|
96 |
+
default=True,
|
97 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
98 |
+
)
|
99 |
+
model_revision: str = field(
|
100 |
+
default="main",
|
101 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
102 |
+
)
|
103 |
+
use_auth_token: bool = field(
|
104 |
+
default=False,
|
105 |
+
metadata={
|
106 |
+
"help": (
|
107 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
108 |
+
"with private models)."
|
109 |
+
)
|
110 |
+
},
|
111 |
+
)
|
112 |
+
freeze_feature_encoder: bool = field(
|
113 |
+
default=True, metadata={"help": "Deprecated - Whether to freeze the feature encoder layers of the model."}
|
114 |
+
)
|
115 |
+
freeze_encoder: bool = field(
|
116 |
+
default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
|
117 |
+
)
|
118 |
+
forced_decoder_ids: List[List[int]] = field(
|
119 |
+
default=None,
|
120 |
+
metadata={
|
121 |
+
"help": (
|
122 |
+
"A list of pairs of integers which indicates a mapping from generation indices to token indices "
|
123 |
+
"that will be forced before sampling. For example, [[0, 123]] means the first generated token "
|
124 |
+
"will always be a token of index 123."
|
125 |
+
)
|
126 |
+
},
|
127 |
+
)
|
128 |
+
suppress_tokens: List[int] = field(
|
129 |
+
default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
|
130 |
+
)
|
131 |
+
model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
|
132 |
+
|
133 |
+
## added by Michael Kamfonas
|
134 |
+
use_cache: bool = field(
|
135 |
+
default=False, metadata={"help": "Whether to use cache."}
|
136 |
+
)
|
137 |
+
|
138 |
+
dropout: float = field(
|
139 |
+
default = 0.0, metadata = {"help": "dropout probability."}
|
140 |
+
)
|
141 |
+
|
142 |
+
attention_dropout: float = field(
|
143 |
+
default = 0.0, metadata = {"help": "attention_dropout probability."}
|
144 |
+
)
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
@dataclass
|
149 |
+
class DataTrainingArguments:
|
150 |
+
"""
|
151 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
152 |
+
"""
|
153 |
+
|
154 |
+
dataset_name: str = field(
|
155 |
+
default=None,
|
156 |
+
metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
157 |
+
)
|
158 |
+
dataset_config_name: Optional[str] = field(
|
159 |
+
default=None,
|
160 |
+
metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
161 |
+
)
|
162 |
+
text_column: Optional[str] = field(
|
163 |
+
default=None,
|
164 |
+
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
|
165 |
+
)
|
166 |
+
max_train_samples: Optional[int] = field(
|
167 |
+
default=None,
|
168 |
+
metadata={
|
169 |
+
"help": (
|
170 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
171 |
+
"value if set."
|
172 |
+
)
|
173 |
+
},
|
174 |
+
)
|
175 |
+
max_eval_samples: Optional[int] = field(
|
176 |
+
default=None,
|
177 |
+
metadata={
|
178 |
+
"help": (
|
179 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
180 |
+
"value if set."
|
181 |
+
)
|
182 |
+
},
|
183 |
+
)
|
184 |
+
audio_column_name: str = field(
|
185 |
+
default="audio",
|
186 |
+
metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
|
187 |
+
)
|
188 |
+
text_column_name: str = field(
|
189 |
+
default="text",
|
190 |
+
metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
|
191 |
+
)
|
192 |
+
max_duration_in_seconds: float = field(
|
193 |
+
default=20.0,
|
194 |
+
metadata={
|
195 |
+
"help": (
|
196 |
+
"Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
|
197 |
+
" 'max_duration_in_seconds`"
|
198 |
+
)
|
199 |
+
},
|
200 |
+
)
|
201 |
+
min_duration_in_seconds: float = field(
|
202 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
203 |
+
)
|
204 |
+
train_split_name: str = field(
|
205 |
+
default="train",
|
206 |
+
metadata={
|
207 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
208 |
+
},
|
209 |
+
)
|
210 |
+
eval_split_name: str = field(
|
211 |
+
default="test",
|
212 |
+
metadata={
|
213 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
214 |
+
},
|
215 |
+
)
|
216 |
+
do_lower_case: bool = field(
|
217 |
+
default=False,
|
218 |
+
metadata={"help": "Whether the target text should be lower cased."},
|
219 |
+
)
|
220 |
+
do_remove_punctuation: bool = field(
|
221 |
+
default=False,
|
222 |
+
metadata={"help": "Whether the target text should be striped of punctuation."},
|
223 |
+
)
|
224 |
+
do_normalize_eval: bool = field(
|
225 |
+
default=True,
|
226 |
+
metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
|
227 |
+
)
|
228 |
+
language: str = field(
|
229 |
+
default=None,
|
230 |
+
metadata={
|
231 |
+
"help": (
|
232 |
+
"Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
|
233 |
+
"only. For English speech recognition, it should be set to `None`."
|
234 |
+
)
|
235 |
+
},
|
236 |
+
)
|
237 |
+
task: str = field(
|
238 |
+
default="transcribe",
|
239 |
+
metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
|
240 |
+
)
|
241 |
+
shuffle_buffer_size: Optional[int] = field(
|
242 |
+
default=500,
|
243 |
+
metadata={
|
244 |
+
"help": (
|
245 |
+
"The number of streamed examples to download before shuffling them. The large the buffer, "
|
246 |
+
"the closer it is to real offline shuffling."
|
247 |
+
)
|
248 |
+
},
|
249 |
+
)
|
250 |
+
stopping_strategy: Optional[str] = field(
|
251 |
+
default="all_exhausted",
|
252 |
+
metadata={
|
253 |
+
"help": "Strategy used to consume interleaved data. Default = 'all_exhausted'"
|
254 |
+
}
|
255 |
+
)
|
256 |
+
streaming: bool = field(
|
257 |
+
default=True,
|
258 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the data."},
|
259 |
+
)
|
260 |
+
|
261 |
+
@dataclass
|
262 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
263 |
+
"""
|
264 |
+
Data collator that will dynamically pad the inputs received.
|
265 |
+
Args:
|
266 |
+
processor ([`WhisperProcessor`])
|
267 |
+
The processor used for processing the data.
|
268 |
+
decoder_start_token_id (`int`)
|
269 |
+
The begin-of-sentence of the decoder.
|
270 |
+
"""
|
271 |
+
|
272 |
+
processor: Any
|
273 |
+
decoder_start_token_id: int
|
274 |
+
|
275 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
276 |
+
# split inputs and labels since they have to be of different lengths and need
|
277 |
+
# different padding methods
|
278 |
+
model_input_name = self.processor.model_input_names[0]
|
279 |
+
input_features = [{model_input_name: feature[model_input_name]} for feature in features]
|
280 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
281 |
+
|
282 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
283 |
+
|
284 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
285 |
+
|
286 |
+
# replace padding with -100 to ignore loss correctly
|
287 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
288 |
+
|
289 |
+
# if bos token is appended in previous tokenization step,
|
290 |
+
# cut bos token here as it's append later anyways
|
291 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
292 |
+
labels = labels[:, 1:]
|
293 |
+
|
294 |
+
batch["labels"] = labels
|
295 |
+
|
296 |
+
return batch
|
297 |
+
|
298 |
+
|
299 |
+
def load_streaming_dataset(dataset_name, dataset_config_name, split="train", **kwargs):
|
300 |
+
"""
|
301 |
+
Utility function to load a dataset in streaming mode. For datasets with multiple splits,
|
302 |
+
each split is loaded individually and then splits combined by taking alternating examples from
|
303 |
+
each (interleaving).
|
304 |
+
"""
|
305 |
+
if "+" in split:
|
306 |
+
# load multiple splits separated by the `+` symbol with streaming mode
|
307 |
+
dataset_splits = [
|
308 |
+
load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs)
|
309 |
+
for split_name in split.split("+")
|
310 |
+
]
|
311 |
+
# interleave multiple splits to form one dataset
|
312 |
+
interleaved_dataset = interleave_datasets(dataset_splits)
|
313 |
+
return interleaved_dataset
|
314 |
+
else:
|
315 |
+
# load a single split *with* streaming mode
|
316 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)
|
317 |
+
return dataset
|
318 |
+
|
319 |
+
def load_multiple_streaming_datasets(
|
320 |
+
dataset_names: List,
|
321 |
+
dataset_config_names: List,
|
322 |
+
splits: Optional[List] = None,
|
323 |
+
text_column_names: Optional[List] = None,
|
324 |
+
audio_column_names: Optional[List] = None,
|
325 |
+
sampling_rate: Optional[int] = 16000,
|
326 |
+
stopping_strategy: Optional[str] = "all_exhausted",
|
327 |
+
streaming = True,
|
328 |
+
**kwargs
|
329 |
+
):
|
330 |
+
|
331 |
+
if len(dataset_names) != len(dataset_config_names):
|
332 |
+
raise ValueError(
|
333 |
+
f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
|
334 |
+
f" {len(dataset_config_names)} configs."
|
335 |
+
)
|
336 |
+
|
337 |
+
if splits is not None and len(splits) != len(dataset_names):
|
338 |
+
raise ValueError(
|
339 |
+
f"Ensure one train_split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
|
340 |
+
)
|
341 |
+
|
342 |
+
if text_column_names is not None and len(text_column_names) != len(dataset_names):
|
343 |
+
raise ValueError(
|
344 |
+
f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
|
345 |
+
f" {len(text_column_names)} text column names."
|
346 |
+
)
|
347 |
+
|
348 |
+
if audio_column_names is not None and len(audio_column_names) != len(dataset_names):
|
349 |
+
raise ValueError(
|
350 |
+
f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
|
351 |
+
f" {len(audio_column_names)} text column names."
|
352 |
+
)
|
353 |
+
|
354 |
+
splits = splits if splits is not None \
|
355 |
+
else ["train" for i in range(len(dataset_names))]
|
356 |
+
|
357 |
+
text_column_names = (
|
358 |
+
text_column_names if text_column_names is not None \
|
359 |
+
else [TEXT_COL_NAME for i in range(len(dataset_names))]
|
360 |
+
)
|
361 |
+
|
362 |
+
audio_column_names = (
|
363 |
+
audio_column_names if audio_column_names is not None \
|
364 |
+
else [AUDIO_COL_NAME for i in range(len(dataset_names))]
|
365 |
+
)
|
366 |
+
|
367 |
+
all_data_splits = []
|
368 |
+
# iterate over the datasets we want to interleave
|
369 |
+
for dset, cfgNm, splt, txtColNm, audColNm in zip(dataset_names,dataset_config_names,\
|
370 |
+
splits,text_column_names, audio_column_names):
|
371 |
+
|
372 |
+
dset_splits = [load_dataset(dset, cfgNm, split=c, streaming=streaming, **kwargs) \
|
373 |
+
for c in splt.split('+') if c != '-']
|
374 |
+
|
375 |
+
if streaming:
|
376 |
+
dset_splits = [ds if TEXT_COL_NAME in ds.features else ds.rename_column(txtColNm, TEXT_COL_NAME) \
|
377 |
+
for ds in dset_splits ]
|
378 |
+
dset_splits = [ds if AUDIO_COL_NAME in ds.features else ds.rename_column(audColNm, AUDIO_COL_NAME) \
|
379 |
+
for ds in dset_splits]
|
380 |
+
|
381 |
+
if len(dset_splits)>0 and sampling_rate != next(iter(dset_splits[0]))[AUDIO_COL_NAME]['sampling_rate']:
|
382 |
+
dset_splits = [ds.cast_column(AUDIO_COL_NAME, Audio(sampling_rate)) for ds in dset_splits]
|
383 |
+
else:
|
384 |
+
|
385 |
+
dset_splits = [ds if TEXT_COL_NAME in ds.column_names else ds.rename_column(txtColNm, TEXT_COL_NAME) \
|
386 |
+
for ds in dset_splits ]
|
387 |
+
dset_splits = [ds if AUDIO_COL_NAME in ds.column_names else ds.rename_column(audColNm, AUDIO_COL_NAME) \
|
388 |
+
for ds in dset_splits]
|
389 |
+
|
390 |
+
if len(dset_splits)>0 and sampling_rate != next(iter(dset_splits[0]))[AUDIO_COL_NAME]['sampling_rate']:
|
391 |
+
dset_splits = [ds.cast_column(AUDIO_COL_NAME, Audio(sampling_rate)) for ds in dset_splits]
|
392 |
+
|
393 |
+
cols2keep = set([AUDIO_COL_NAME, TEXT_COL_NAME])
|
394 |
+
|
395 |
+
dset_splits = [ds.remove_columns(set(ds.features.keys()) - cols2keep) for ds in dset_splits]
|
396 |
+
|
397 |
+
all_data_splits += dset_splits
|
398 |
+
|
399 |
+
return interleave_datasets(all_data_splits, stopping_strategy=stopping_strategy)
|
400 |
+
|
401 |
+
def main():
|
402 |
+
# 1. Parse input arguments
|
403 |
+
# See all possible arguments in src/transformers/training_args.py
|
404 |
+
# or by passing the --help flag to this script.
|
405 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
406 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
407 |
+
|
408 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
409 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
410 |
+
# let's parse it to get our arguments.
|
411 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
412 |
+
else:
|
413 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
414 |
+
|
415 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
416 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
417 |
+
send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
|
418 |
+
|
419 |
+
# 2. Setup logging
|
420 |
+
logging.basicConfig(
|
421 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
422 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
423 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
424 |
+
)
|
425 |
+
log_level = training_args.get_process_log_level()
|
426 |
+
logger.setLevel(log_level)
|
427 |
+
datasets.utils.logging.set_verbosity(log_level)
|
428 |
+
transformers.utils.logging.set_verbosity(log_level)
|
429 |
+
transformers.utils.logging.enable_default_handler()
|
430 |
+
transformers.utils.logging.enable_explicit_format()
|
431 |
+
|
432 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
433 |
+
|
434 |
+
# Log on each process the small summary:
|
435 |
+
logger.warning(
|
436 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
437 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
438 |
+
)
|
439 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
440 |
+
|
441 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
442 |
+
if is_main_process(training_args.local_rank):
|
443 |
+
transformers.utils.logging.set_verbosity_info()
|
444 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
445 |
+
|
446 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
447 |
+
last_checkpoint = None
|
448 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
449 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
450 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
451 |
+
raise ValueError(
|
452 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
453 |
+
"Use --overwrite_output_dir to overcome."
|
454 |
+
)
|
455 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
456 |
+
logger.info(
|
457 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
458 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
459 |
+
)
|
460 |
+
|
461 |
+
# Set seed before initializing model.
|
462 |
+
set_seed(training_args.seed)
|
463 |
+
|
464 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
465 |
+
#
|
466 |
+
# Distributed training:
|
467 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
468 |
+
config = AutoConfig.from_pretrained(
|
469 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
470 |
+
cache_dir=model_args.cache_dir,
|
471 |
+
revision=model_args.model_revision,
|
472 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
473 |
+
)
|
474 |
+
|
475 |
+
config.update({ "forced_decoder_ids": model_args.forced_decoder_ids,
|
476 |
+
"suppress_tokens": model_args.suppress_tokens})
|
477 |
+
|
478 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
479 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
480 |
+
cache_dir=model_args.cache_dir,
|
481 |
+
revision=model_args.model_revision,
|
482 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
483 |
+
)
|
484 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
485 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
486 |
+
cache_dir=model_args.cache_dir,
|
487 |
+
use_fast=model_args.use_fast_tokenizer,
|
488 |
+
revision=model_args.model_revision,
|
489 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
490 |
+
)
|
491 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
492 |
+
model_args.model_name_or_path,
|
493 |
+
config=config,
|
494 |
+
cache_dir=model_args.cache_dir,
|
495 |
+
revision=model_args.model_revision,
|
496 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
497 |
+
)
|
498 |
+
|
499 |
+
model.config.use_cache = model_args.use_cache
|
500 |
+
model.config.dropout = model_args.dropout
|
501 |
+
model.config.attention_dropout = model_args.attention_dropout
|
502 |
+
if training_args.gradient_checkpointing:
|
503 |
+
model.gradient_checkpointing_enable()
|
504 |
+
|
505 |
+
if model.config.decoder_start_token_id is None:
|
506 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
507 |
+
|
508 |
+
# deprecated
|
509 |
+
#if model_args.freeze_feature_encoder:
|
510 |
+
# model.freeze_feature_encoder()
|
511 |
+
|
512 |
+
if model_args.freeze_encoder:
|
513 |
+
model.freeze_encoder()
|
514 |
+
model.model.encoder.gradient_checkpointing = False
|
515 |
+
|
516 |
+
if data_args.language is not None:
|
517 |
+
# We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
518 |
+
tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
|
519 |
+
|
520 |
+
|
521 |
+
# 4. Load dataset
|
522 |
+
raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
|
523 |
+
|
524 |
+
# if training_args.do_train:
|
525 |
+
# raw_datasets["train"] = load_streaming_dataset(
|
526 |
+
# data_args.dataset_name,
|
527 |
+
# data_args.dataset_config_name,
|
528 |
+
# split=data_args.train_split_name,
|
529 |
+
# use_auth_token=True if model_args.use_auth_token else None,
|
530 |
+
# )
|
531 |
+
|
532 |
+
# if training_args.do_eval:
|
533 |
+
# raw_datasets["eval"] = load_streaming_dataset(
|
534 |
+
# data_args.dataset_name,
|
535 |
+
# data_args.dataset_config_name,
|
536 |
+
# split=data_args.eval_split_name,
|
537 |
+
# use_auth_token=True if model_args.use_auth_token else None,
|
538 |
+
# )
|
539 |
+
|
540 |
+
if training_args.do_train:
|
541 |
+
raw_datasets["train"] = load_multiple_streaming_datasets(
|
542 |
+
dataset_names=data_args.dataset_name.split(","),
|
543 |
+
dataset_config_names=data_args.dataset_config_name.split(","),
|
544 |
+
splits = data_args.train_split_name.split(","),
|
545 |
+
text_column_names = data_args.text_column_name.split(","),
|
546 |
+
sampling_rate = feature_extractor.sampling_rate,
|
547 |
+
streaming=data_args.streaming,
|
548 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
549 |
+
)
|
550 |
+
|
551 |
+
if training_args.do_eval:
|
552 |
+
raw_datasets["eval"] = load_multiple_streaming_datasets(
|
553 |
+
dataset_names=data_args.dataset_name.split(","),
|
554 |
+
dataset_config_names=data_args.dataset_config_name.split(","),
|
555 |
+
splits = data_args.eval_split_name.split(","),
|
556 |
+
text_column_names = data_args.text_column_name.split(","),
|
557 |
+
sampling_rate = feature_extractor.sampling_rate,
|
558 |
+
streaming=False,
|
559 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
560 |
+
)
|
561 |
+
|
562 |
+
raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
|
563 |
+
|
564 |
+
if AUDIO_COL_NAME not in raw_datasets_features:
|
565 |
+
raise ValueError(
|
566 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
567 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
568 |
+
f"{', '.join(raw_datasets_features)}."
|
569 |
+
)
|
570 |
+
|
571 |
+
if TEXT_COL_NAME not in raw_datasets_features:
|
572 |
+
raise ValueError(
|
573 |
+
f"--text_column_name {TEXT_COL_NAME} not found in dataset. "
|
574 |
+
"Make sure to set `--text_column_name` to the the respective correct text columns."
|
575 |
+
)
|
576 |
+
|
577 |
+
|
578 |
+
# 6. Resample speech dataset if necessary
|
579 |
+
#dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
|
580 |
+
#if dataset_sampling_rate != feature_extractor.sampling_rate:
|
581 |
+
# raw_datasets = raw_datasets.cast_column(
|
582 |
+
# data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
|
583 |
+
# )
|
584 |
+
|
585 |
+
# 7. Preprocessing the datasets.
|
586 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
587 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
588 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
589 |
+
audio_column_name = AUDIO_COL_NAME
|
590 |
+
text_column_name = TEXT_COL_NAME
|
591 |
+
model_input_name = feature_extractor.model_input_names[0]
|
592 |
+
do_lower_case = data_args.do_lower_case
|
593 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
594 |
+
normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
|
595 |
+
|
596 |
+
if data_args.max_train_samples is not None:
|
597 |
+
raw_datasets["train"] = (
|
598 |
+
raw_datasets["train"].take(data_args.max_train_samples)
|
599 |
+
if data_args.streaming
|
600 |
+
else raw_datasets["train"].select(range(data_args.max_train_samples))
|
601 |
+
)
|
602 |
+
|
603 |
+
if data_args.max_eval_samples is not None:
|
604 |
+
raw_datasets["eval"] = (
|
605 |
+
raw_datasets["eval"].take(data_args.max_eval_samples)
|
606 |
+
if data_args.streaming
|
607 |
+
else raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
608 |
+
)
|
609 |
+
|
610 |
+
def prepare_dataset(batch):
|
611 |
+
# process audio
|
612 |
+
sample = batch[audio_column_name]
|
613 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
614 |
+
# process audio length
|
615 |
+
batch[model_input_name] = inputs.get(model_input_name)[0]
|
616 |
+
batch["input_length"] = len(sample["array"])
|
617 |
+
|
618 |
+
# process targets
|
619 |
+
input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
|
620 |
+
if do_remove_punctuation:
|
621 |
+
input_str = normalizer(input_str).strip()
|
622 |
+
batch["labels"] = tokenizer(input_str).input_ids
|
623 |
+
return batch
|
624 |
+
|
625 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
626 |
+
vectorized_datasets = raw_datasets.map(
|
627 |
+
prepare_dataset,
|
628 |
+
remove_columns=raw_datasets_features,
|
629 |
+
num_proc=training_args.dataloader_num_workers if training_args.dataloader_num_workers else 1
|
630 |
+
).with_format("torch")
|
631 |
+
|
632 |
+
if training_args.do_train and data_args.streaming:
|
633 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
634 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
|
635 |
+
buffer_size=data_args.shuffle_buffer_size,
|
636 |
+
seed=training_args.seed,
|
637 |
+
)
|
638 |
+
|
639 |
+
# filter training data that is shorter than min_input_length or longer than
|
640 |
+
# max_input_length
|
641 |
+
def is_audio_in_length_range(length):
|
642 |
+
return min_input_length < length < max_input_length
|
643 |
+
|
644 |
+
if training_args.do_train:
|
645 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
646 |
+
is_audio_in_length_range,
|
647 |
+
input_columns=["input_length"],
|
648 |
+
)
|
649 |
+
|
650 |
+
# 8. Load Metric
|
651 |
+
metric = evaluate.load("wer")
|
652 |
+
do_normalize_eval = data_args.do_normalize_eval
|
653 |
+
|
654 |
+
def compute_metrics(pred):
|
655 |
+
pred_ids = pred.predictions
|
656 |
+
|
657 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
658 |
+
|
659 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
660 |
+
# we do not want to group tokens when computing the metrics
|
661 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
662 |
+
|
663 |
+
if do_normalize_eval:
|
664 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
665 |
+
label_str = [normalizer(label) for label in label_str]
|
666 |
+
# filtering step to only evaluate the samples that correspond to non-zero references:
|
667 |
+
pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
|
668 |
+
label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
|
669 |
+
|
670 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
671 |
+
|
672 |
+
return {"wer": wer}
|
673 |
+
|
674 |
+
# 9. Create a single speech processor
|
675 |
+
if is_main_process(training_args.local_rank):
|
676 |
+
# save feature extractor, tokenizer and config
|
677 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
678 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
679 |
+
config.save_pretrained(training_args.output_dir)
|
680 |
+
|
681 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
682 |
+
|
683 |
+
# 10. Define data collator
|
684 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
685 |
+
processor=processor,
|
686 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
687 |
+
)
|
688 |
+
|
689 |
+
# 11. Configure Trainer
|
690 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
691 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
692 |
+
class ShuffleCallback(TrainerCallback):
|
693 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
694 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
695 |
+
pass # set_epoch() is handled by the Trainer
|
696 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
697 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
698 |
+
|
699 |
+
# Initialize Trainer
|
700 |
+
trainer = Seq2SeqTrainer(
|
701 |
+
model=model,
|
702 |
+
args=training_args,
|
703 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
704 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
705 |
+
tokenizer=feature_extractor,
|
706 |
+
data_collator=data_collator,
|
707 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
708 |
+
callbacks=[ShuffleCallback()] if data_args.streaming else None,
|
709 |
+
)
|
710 |
+
|
711 |
+
# 12. Training
|
712 |
+
if training_args.do_train:
|
713 |
+
checkpoint = None
|
714 |
+
if training_args.resume_from_checkpoint is not None:
|
715 |
+
checkpoint = training_args.resume_from_checkpoint
|
716 |
+
elif last_checkpoint is not None:
|
717 |
+
checkpoint = last_checkpoint
|
718 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
719 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
720 |
+
|
721 |
+
metrics = train_result.metrics
|
722 |
+
if data_args.max_train_samples:
|
723 |
+
metrics["train_samples"] = data_args.max_train_samples
|
724 |
+
trainer.log_metrics("train", metrics)
|
725 |
+
trainer.save_metrics("train", metrics)
|
726 |
+
trainer.save_state()
|
727 |
+
|
728 |
+
# 13. Evaluation
|
729 |
+
results = {}
|
730 |
+
if training_args.do_eval:
|
731 |
+
logger.info("*** Evaluate ***")
|
732 |
+
metrics = trainer.evaluate(
|
733 |
+
metric_key_prefix="eval",
|
734 |
+
max_length=training_args.generation_max_length,
|
735 |
+
num_beams=training_args.generation_num_beams,
|
736 |
+
)
|
737 |
+
if data_args.max_eval_samples:
|
738 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
739 |
+
|
740 |
+
trainer.log_metrics("eval", metrics)
|
741 |
+
trainer.save_metrics("eval", metrics)
|
742 |
+
|
743 |
+
# 14. Write Training Stats
|
744 |
+
kwargs = {
|
745 |
+
"finetuned_from": model_args.model_name_or_path,
|
746 |
+
"tasks": "automatic-speech-recognition",
|
747 |
+
"tags": "whisper-event",
|
748 |
+
}
|
749 |
+
if data_args.dataset_name is not None:
|
750 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
751 |
+
if data_args.dataset_config_name is not None:
|
752 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
753 |
+
else:
|
754 |
+
kwargs["dataset"] = data_args.dataset_name
|
755 |
+
if "common_voice" in data_args.dataset_name:
|
756 |
+
kwargs["language"] = data_args.dataset_config_name[:2]
|
757 |
+
if model_args.model_index_name is not None:
|
758 |
+
kwargs["model_name"] = model_args.model_index_name
|
759 |
+
|
760 |
+
if training_args.push_to_hub:
|
761 |
+
trainer.push_to_hub(**kwargs)
|
762 |
+
else:
|
763 |
+
trainer.create_model_card(**kwargs)
|
764 |
+
|
765 |
+
return results
|
766 |
+
|
767 |
+
|
768 |
+
if __name__ == "__main__":
|
769 |
+
main()
|