Commit
•
ada7ca7
1
Parent(s):
fdf77d5
eval model on test sv
Browse files- .gitignore +6 -0
- requirements.txt +10 -0
- requirements_mac.txt +10 -0
- run.sh +40 -0
- run_speech_recognition_seq2seq_streaming.py +933 -0
.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*venv/
|
2 |
+
runs/
|
3 |
+
creds.txt
|
4 |
+
wandb/
|
5 |
+
dlc/
|
6 |
+
tests/
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.7
|
2 |
+
torchaudio==0.13.1
|
3 |
+
git+https://github.com/huggingface/transformers
|
4 |
+
git+https://github.com/huggingface/datasets
|
5 |
+
librosa
|
6 |
+
jiwer
|
7 |
+
evaluate>=0.3.0
|
8 |
+
more-itertools
|
9 |
+
tensorboard
|
10 |
+
wandb
|
requirements_mac.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.7
|
2 |
+
torchaudio==0.11.0
|
3 |
+
git+https://github.com/huggingface/transformers
|
4 |
+
git+https://github.com/huggingface/datasets
|
5 |
+
librosa
|
6 |
+
jiwer
|
7 |
+
evaluate>=0.3.0
|
8 |
+
more-itertools
|
9 |
+
tensorboard
|
10 |
+
wandb
|
run.sh
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python $1run_speech_recognition_seq2seq_streaming.py \
|
2 |
+
--model_name_or_path="openai/whisper-medium" \
|
3 |
+
--dataset_train_name="mozilla-foundation/common_voice_11_0,mozilla-foundation/common_voice_11_0,mozilla-foundation/common_voice_11_0,babelbox/babelbox_voice,NbAiLab/NST,NbAiLab/NPSC,google/fleurs,google/fleurs,google/fleurs" \
|
4 |
+
--dataset_train_config_name="sv-SE,da,nn-NO,nst,no-distant,16K_mp3_nynorsk,sv_se,da_dk,nb_no" \
|
5 |
+
--language_train="sv,da,no,sv,no,no,sv,da,no" \
|
6 |
+
--train_split_name="train+validation,train+validation,train+validation,train,train+test,train+validation,train+validation,train+validation,train+validation" \
|
7 |
+
--dataset_eval_name="mozilla-foundation/common_voice_11_0" \
|
8 |
+
--dataset_eval_config_name="sv-SE" \
|
9 |
+
--language_eval="sv" \
|
10 |
+
--eval_split_name="test" \
|
11 |
+
--model_index_name="Whisper Medium Nordic" \
|
12 |
+
--num_train_epochs="1" \
|
13 |
+
--output_dir="./" \
|
14 |
+
--per_device_train_batch_size="32" \
|
15 |
+
--per_device_eval_batch_size="16" \
|
16 |
+
--logging_steps="25" \
|
17 |
+
--learning_rate="1e-5" \
|
18 |
+
--warmup_steps="500" \
|
19 |
+
--evaluation_strategy="steps" \
|
20 |
+
--eval_steps="1000" \
|
21 |
+
--save_strategy="steps" \
|
22 |
+
--save_steps="1000" \
|
23 |
+
--generation_max_length="225" \
|
24 |
+
--length_column_name="input_length" \
|
25 |
+
--max_duration_in_seconds="30" \
|
26 |
+
--text_column_name="sentence,text,raw_transcription" \
|
27 |
+
--freeze_feature_encoder="False" \
|
28 |
+
--report_to="wandb" \
|
29 |
+
--save_total_limit="3" \
|
30 |
+
--metric_for_best_model="wer" \
|
31 |
+
--greater_is_better="False" \
|
32 |
+
--load_best_model_at_end \
|
33 |
+
--gradient_checkpointing \
|
34 |
+
--overwrite_output_dir \
|
35 |
+
--do_eval \
|
36 |
+
--fp16 \
|
37 |
+
--predict_with_generate \
|
38 |
+
--do_normalize_eval \
|
39 |
+
--streaming \
|
40 |
+
--use_auth_token
|
run_speech_recognition_seq2seq_streaming.py
ADDED
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# You can also adapt this script for your own sequence to sequence speech
|
21 |
+
# recognition task. Pointers for this are left as comments.
|
22 |
+
|
23 |
+
import json
|
24 |
+
import logging
|
25 |
+
import os
|
26 |
+
import subprocess
|
27 |
+
import sys
|
28 |
+
from dataclasses import dataclass, field
|
29 |
+
from typing import Any, Dict, List, Optional, Union
|
30 |
+
|
31 |
+
import datasets
|
32 |
+
import torch
|
33 |
+
import wandb
|
34 |
+
from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
|
35 |
+
from torch.utils.data import IterableDataset
|
36 |
+
|
37 |
+
import evaluate
|
38 |
+
import transformers
|
39 |
+
from transformers import (
|
40 |
+
AutoConfig,
|
41 |
+
AutoFeatureExtractor,
|
42 |
+
AutoModelForSpeechSeq2Seq,
|
43 |
+
AutoProcessor,
|
44 |
+
AutoTokenizer,
|
45 |
+
HfArgumentParser,
|
46 |
+
Seq2SeqTrainer,
|
47 |
+
Seq2SeqTrainingArguments,
|
48 |
+
TrainerCallback,
|
49 |
+
set_seed,
|
50 |
+
)
|
51 |
+
from transformers.models.whisper.english_normalizer import BasicTextNormalizer
|
52 |
+
from transformers.models.whisper.tokenization_whisper import TO_LANGUAGE_CODE, LANGUAGES
|
53 |
+
from transformers.trainer_pt_utils import IterableDatasetShard
|
54 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
55 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
56 |
+
from transformers.utils.versions import require_version
|
57 |
+
|
58 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
59 |
+
check_min_version("4.25.0.dev0")
|
60 |
+
|
61 |
+
require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
|
62 |
+
|
63 |
+
logger = logging.getLogger(__name__)
|
64 |
+
|
65 |
+
SENDING_NOTIFICATION = "*** Sending notification to email ***"
|
66 |
+
RECIPIENT_ADDRESS = "marinone94@gmail.com"
|
67 |
+
|
68 |
+
wandb_token = os.environ.get("WANDB_TOKEN", "None")
|
69 |
+
hf_token = os.environ.get("HF_TOKEN", None)
|
70 |
+
if (hf_token is None or wandb_token == "None") and os.path.exists("./creds.txt"):
|
71 |
+
with open("./creds.txt", "r") as f:
|
72 |
+
lines = f.readlines()
|
73 |
+
for line in lines:
|
74 |
+
key, value = line.split("=")
|
75 |
+
if key == "HF_TOKEN":
|
76 |
+
hf_token = value.strip()
|
77 |
+
if key == "WANDB_TOKEN":
|
78 |
+
wandb_token = value.strip()
|
79 |
+
if key == "EMAIL_ADDRESS":
|
80 |
+
os.environ["EMAIL_ADDRESS"] = value.strip()
|
81 |
+
if key == "EMAIL_PASSWORD":
|
82 |
+
os.environ["EMAIL_PASSWORD"] = value.strip()
|
83 |
+
|
84 |
+
if hf_token is not None:
|
85 |
+
try:
|
86 |
+
os.makedirs("/root/.huggingface", exist_ok=True)
|
87 |
+
with open("/root/.huggingface/token", "w") as f:
|
88 |
+
f.write(hf_token)
|
89 |
+
logger.info("Huggingface API key set")
|
90 |
+
except (PermissionError, OSError):
|
91 |
+
logger.warning("Huggingface API key not set, relying on ~/.huggingface/token")
|
92 |
+
else:
|
93 |
+
logger.warning("Huggingface API key not set, relying on ~/.huggingface/token")
|
94 |
+
|
95 |
+
wandb.login(key=wandb_token, relogin=True, timeout=5)
|
96 |
+
wandb.init(project="whisper", entity="pn-aa")
|
97 |
+
|
98 |
+
logger.info("Wandb API key set, logging to wandb")
|
99 |
+
|
100 |
+
|
101 |
+
@dataclass
|
102 |
+
class ModelArguments:
|
103 |
+
"""
|
104 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
105 |
+
"""
|
106 |
+
|
107 |
+
model_name_or_path: str = field(
|
108 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
109 |
+
)
|
110 |
+
config_name: Optional[str] = field(
|
111 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
112 |
+
)
|
113 |
+
tokenizer_name: Optional[str] = field(
|
114 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
115 |
+
)
|
116 |
+
feature_extractor_name: Optional[str] = field(
|
117 |
+
default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
|
118 |
+
)
|
119 |
+
cache_dir: Optional[str] = field(
|
120 |
+
default=None,
|
121 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
122 |
+
)
|
123 |
+
use_fast_tokenizer: bool = field(
|
124 |
+
default=True,
|
125 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
126 |
+
)
|
127 |
+
model_revision: str = field(
|
128 |
+
default="main",
|
129 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
130 |
+
)
|
131 |
+
use_auth_token: bool = field(
|
132 |
+
default=False,
|
133 |
+
metadata={
|
134 |
+
"help": (
|
135 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
136 |
+
"with private models)."
|
137 |
+
)
|
138 |
+
},
|
139 |
+
)
|
140 |
+
freeze_feature_encoder: bool = field(
|
141 |
+
default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
|
142 |
+
)
|
143 |
+
freeze_encoder: bool = field(
|
144 |
+
default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
|
145 |
+
)
|
146 |
+
forced_decoder_ids: List[List[int]] = field(
|
147 |
+
default=None,
|
148 |
+
metadata={
|
149 |
+
"help": (
|
150 |
+
"A list of pairs of integers which indicates a mapping from generation indices to token indices "
|
151 |
+
"that will be forced before sampling. For example, [[0, 123]] means the first generated token "
|
152 |
+
"will always be a token of index 123."
|
153 |
+
)
|
154 |
+
},
|
155 |
+
)
|
156 |
+
suppress_tokens: List[int] = field(
|
157 |
+
default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
|
158 |
+
)
|
159 |
+
model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
|
160 |
+
|
161 |
+
|
162 |
+
@dataclass
|
163 |
+
class DataTrainingArguments:
|
164 |
+
"""
|
165 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
166 |
+
"""
|
167 |
+
|
168 |
+
dataset_train_name: str = field(
|
169 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
170 |
+
)
|
171 |
+
dataset_train_config_name: Optional[str] = field(
|
172 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
173 |
+
)
|
174 |
+
dataset_eval_name: str = field(
|
175 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
176 |
+
)
|
177 |
+
dataset_eval_config_name: Optional[str] = field(
|
178 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
179 |
+
)
|
180 |
+
text_column: Optional[str] = field(
|
181 |
+
default=None,
|
182 |
+
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
|
183 |
+
)
|
184 |
+
max_train_samples: Optional[int] = field(
|
185 |
+
default=None,
|
186 |
+
metadata={
|
187 |
+
"help": (
|
188 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
189 |
+
"value if set."
|
190 |
+
)
|
191 |
+
},
|
192 |
+
)
|
193 |
+
max_eval_samples: Optional[int] = field(
|
194 |
+
default=None,
|
195 |
+
metadata={
|
196 |
+
"help": (
|
197 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
198 |
+
"value if set."
|
199 |
+
)
|
200 |
+
},
|
201 |
+
)
|
202 |
+
audio_column_name: str = field(
|
203 |
+
default="audio",
|
204 |
+
metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
|
205 |
+
)
|
206 |
+
text_column_name: str = field(
|
207 |
+
default="text",
|
208 |
+
metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
|
209 |
+
)
|
210 |
+
max_duration_in_seconds: float = field(
|
211 |
+
default=20.0,
|
212 |
+
metadata={
|
213 |
+
"help": (
|
214 |
+
"Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
|
215 |
+
" 'max_duration_in_seconds`"
|
216 |
+
)
|
217 |
+
},
|
218 |
+
)
|
219 |
+
min_duration_in_seconds: float = field(
|
220 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
221 |
+
)
|
222 |
+
train_split_name: str = field(
|
223 |
+
default="train",
|
224 |
+
metadata={
|
225 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
226 |
+
},
|
227 |
+
)
|
228 |
+
eval_split_name: str = field(
|
229 |
+
default="test",
|
230 |
+
metadata={
|
231 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
232 |
+
},
|
233 |
+
)
|
234 |
+
do_lower_case: bool = field(
|
235 |
+
default=False,
|
236 |
+
metadata={"help": "Whether the target text should be lower cased."},
|
237 |
+
)
|
238 |
+
do_remove_punctuation: bool = field(
|
239 |
+
default=False,
|
240 |
+
metadata={"help": "Whether the target text should be striped of punctuation."},
|
241 |
+
)
|
242 |
+
do_normalize_eval: bool = field(
|
243 |
+
default=True,
|
244 |
+
metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
|
245 |
+
)
|
246 |
+
language_train: str = field(
|
247 |
+
default=None,
|
248 |
+
metadata={
|
249 |
+
"help": (
|
250 |
+
"Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
|
251 |
+
"only. For English speech recognition, it should be set to `None`."
|
252 |
+
)
|
253 |
+
},
|
254 |
+
)
|
255 |
+
language_eval: str = field(
|
256 |
+
default=None,
|
257 |
+
metadata={
|
258 |
+
"help": (
|
259 |
+
"Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
|
260 |
+
"only. For English speech recognition, it should be set to `None`."
|
261 |
+
)
|
262 |
+
},
|
263 |
+
)
|
264 |
+
task: str = field(
|
265 |
+
default="transcribe",
|
266 |
+
metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
|
267 |
+
)
|
268 |
+
shuffle_buffer_size: Optional[int] = field(
|
269 |
+
default=500,
|
270 |
+
metadata={
|
271 |
+
"help": (
|
272 |
+
"The number of streamed examples to download before shuffling them. The large the buffer, "
|
273 |
+
"the closer it is to real offline shuffling."
|
274 |
+
)
|
275 |
+
},
|
276 |
+
)
|
277 |
+
streaming: bool = field(
|
278 |
+
default=True,
|
279 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the data."},
|
280 |
+
)
|
281 |
+
|
282 |
+
|
283 |
+
@dataclass
|
284 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
285 |
+
"""
|
286 |
+
Data collator that will dynamically pad the inputs received.
|
287 |
+
Args:
|
288 |
+
processor ([`WhisperProcessor`])
|
289 |
+
The processor used for processing the data.
|
290 |
+
decoder_start_token_id (`int`)
|
291 |
+
The begin-of-sentence of the decoder.
|
292 |
+
"""
|
293 |
+
|
294 |
+
processor: Any
|
295 |
+
decoder_start_token_id: int
|
296 |
+
task_id: int
|
297 |
+
# TODO: remove - infer language from dataset
|
298 |
+
language_id: int = -100
|
299 |
+
|
300 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
301 |
+
# split inputs and labels since they have to be of different lengths and need
|
302 |
+
# different padding methods
|
303 |
+
model_input_name = self.processor.model_input_names[0]
|
304 |
+
input_features = [{model_input_name: feature[model_input_name]} for feature in features]
|
305 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
306 |
+
# lang_features = [f"<|{TO_LANGUAGE_CODE[feature['language']]}|>" for feature in features]
|
307 |
+
|
308 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
309 |
+
|
310 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
311 |
+
|
312 |
+
# replace padding with -100 to ignore loss correctly
|
313 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
314 |
+
|
315 |
+
# if bos token is appended in previous tokenization step,
|
316 |
+
# cut bos token here as it's append later anyways
|
317 |
+
|
318 |
+
# lang_token_ids = self.processor.tokenizer(lang_features).input_ids
|
319 |
+
# # Replace language and task if they are in the beginning, otherwise add them
|
320 |
+
# if (labels[:, 1] == self.task_id).all().cpu().item():
|
321 |
+
# labels[:, 0] = lang_token_ids
|
322 |
+
# labels[:, 1] = torch.full_like(labels[:, 1], self.task_id)
|
323 |
+
# else:
|
324 |
+
# # convert task id to tensor of labels dim to concatenate
|
325 |
+
# task_id = torch.full_like(labels[:, 0], self.task_id)
|
326 |
+
# labels = torch.cat((lang_token_ids, task_id, labels), dim=1)
|
327 |
+
|
328 |
+
# Set language to pad token
|
329 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
330 |
+
labels[:, 1] = torch.full_like(labels[:, 1], -100)
|
331 |
+
# labels[:, 0] = torch.full_like(labels[:, 0], -100)
|
332 |
+
# labels[:, 1] = torch.full_like(labels[:, 1], -100)
|
333 |
+
|
334 |
+
# remove start of sentence token from labels
|
335 |
+
# if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
336 |
+
# labels = labels[:, 1:]
|
337 |
+
|
338 |
+
# # add start of sentence token to labels + language + task
|
339 |
+
# labels = torch.cat((torch.full_like(labels[:, 0], self.task_id).unsqueeze(0).T, labels), dim=-1)
|
340 |
+
# labels = torch.cat((torch.full_like(labels[:, 0], self.language_id).unsqueeze(0).T, labels), dim=-1)
|
341 |
+
# labels = torch.cat((torch.full_like(labels[:, 0], self.decoder_start_token_id).unsqueeze(0).T, labels), dim=-1)
|
342 |
+
|
343 |
+
batch["labels"] = labels
|
344 |
+
|
345 |
+
return batch
|
346 |
+
|
347 |
+
|
348 |
+
def notify_me(recipient, message=None):
|
349 |
+
"""
|
350 |
+
Send an email to the specified address with the specified message
|
351 |
+
"""
|
352 |
+
sender = os.environ.get("EMAIL_ADDRESS", None)
|
353 |
+
password = os.environ.get("EMAIL_PASSWORD", None)
|
354 |
+
if sender is None:
|
355 |
+
logging.warning("No email address specified, not sending notification")
|
356 |
+
if password is None:
|
357 |
+
logging.warning("No email password specified, not sending notification")
|
358 |
+
if message is None:
|
359 |
+
message = "Training is finished!"
|
360 |
+
|
361 |
+
if sender is not None:
|
362 |
+
import smtplib
|
363 |
+
from email.mime.text import MIMEText
|
364 |
+
|
365 |
+
msg = MIMEText(message)
|
366 |
+
msg["Subject"] = "Training updates..."
|
367 |
+
msg["From"] = "marinone.auto@gmail.com"
|
368 |
+
msg["To"] = recipient
|
369 |
+
|
370 |
+
# send the email
|
371 |
+
smtp_obj = smtplib.SMTP("smtp.gmail.com", 587)
|
372 |
+
smtp_obj.starttls()
|
373 |
+
smtp_obj.login(sender, password)
|
374 |
+
smtp_obj.sendmail(sender, recipient, msg.as_string())
|
375 |
+
smtp_obj.quit()
|
376 |
+
|
377 |
+
|
378 |
+
def rename_col_and_resample(dataset, dataset_name, text_column_names, text_col_name_ref, audio_column_name, sampling_rate):
|
379 |
+
raw_datasets_features = list(dataset.features.keys())
|
380 |
+
logger.info(f"Dataset {dataset_name} - Features: {raw_datasets_features}")
|
381 |
+
|
382 |
+
if text_col_name_ref not in raw_datasets_features:
|
383 |
+
if len(text_column_names) == 1:
|
384 |
+
raise ValueError("None of the text column names provided found in dataset."
|
385 |
+
f"Text columns: {text_column_names}"
|
386 |
+
f"Dataset columns: {raw_datasets_features}")
|
387 |
+
flag = False
|
388 |
+
for text_column_name in text_column_names:
|
389 |
+
if text_column_name in raw_datasets_features:
|
390 |
+
logger.info(f"Renaming text column {text_column_name} to {text_col_name_ref}")
|
391 |
+
dataset = dataset.rename_column(text_column_name, text_col_name_ref)
|
392 |
+
flag = True
|
393 |
+
break
|
394 |
+
if flag is False:
|
395 |
+
raise ValueError("None of the text column names provided found in dataset."
|
396 |
+
f"Text columns: {text_column_names}"
|
397 |
+
f"Dataset columns: {raw_datasets_features}")
|
398 |
+
if audio_column_name is not None and sampling_rate is not None:
|
399 |
+
ds_sr = int(dataset.features[audio_column_name].sampling_rate)
|
400 |
+
if ds_sr != sampling_rate:
|
401 |
+
dataset = dataset.cast_column(
|
402 |
+
audio_column_name, datasets.features.Audio(sampling_rate=sampling_rate)
|
403 |
+
)
|
404 |
+
|
405 |
+
raw_datasets_features = list(dataset.features.keys())
|
406 |
+
raw_datasets_features.remove(audio_column_name)
|
407 |
+
raw_datasets_features.remove(text_col_name_ref)
|
408 |
+
# Keep only audio and sentence
|
409 |
+
dataset = dataset.remove_columns(column_names=raw_datasets_features)
|
410 |
+
return dataset
|
411 |
+
|
412 |
+
|
413 |
+
def load_maybe_streaming_dataset(
|
414 |
+
dataset_names,
|
415 |
+
dataset_config_names,
|
416 |
+
split="train",
|
417 |
+
streaming=True,
|
418 |
+
audio_column_name=None,
|
419 |
+
sampling_rate=None,
|
420 |
+
**kwargs
|
421 |
+
):
|
422 |
+
"""
|
423 |
+
Utility function to load a dataset in streaming mode. For datasets with multiple splits,
|
424 |
+
each split is loaded individually and then splits combined by taking alternating examples from
|
425 |
+
each (interleaving).
|
426 |
+
"""
|
427 |
+
text_column_names = None
|
428 |
+
if "text_column_name" in kwargs:
|
429 |
+
text_column_names = kwargs.pop("text_column_name").split(",")
|
430 |
+
text_col_name_ref = text_column_names[0]
|
431 |
+
|
432 |
+
if "," in dataset_names or "+" in split:
|
433 |
+
# load multiple splits separated by the `+` symbol with streaming mode
|
434 |
+
dataset_splits = []
|
435 |
+
for dataset_name, dataset_config_name, split_names in zip(
|
436 |
+
dataset_names.split(","), dataset_config_names.split(","), split.split(",")
|
437 |
+
):
|
438 |
+
for split_name in split_names.split("+"):
|
439 |
+
if dataset_config_name:
|
440 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=streaming, **kwargs)
|
441 |
+
else:
|
442 |
+
dataset = load_dataset(dataset_name, split=split_name, streaming=streaming, **kwargs)
|
443 |
+
|
444 |
+
dataset = rename_col_and_resample(
|
445 |
+
dataset,
|
446 |
+
dataset_name,
|
447 |
+
text_column_names,
|
448 |
+
text_col_name_ref,
|
449 |
+
audio_column_name,
|
450 |
+
sampling_rate
|
451 |
+
)
|
452 |
+
|
453 |
+
dataset_splits.append(dataset)
|
454 |
+
|
455 |
+
# interleave multiple splits to form one dataset
|
456 |
+
interleaved_dataset = interleave_datasets(dataset_splits, stopping_strategy="all_exhausted")
|
457 |
+
return interleaved_dataset
|
458 |
+
else:
|
459 |
+
# load a single split *with* streaming mode
|
460 |
+
|
461 |
+
dataset = load_dataset(dataset_names, dataset_config_names, split=split, streaming=streaming, **kwargs)
|
462 |
+
dataset = rename_col_and_resample(
|
463 |
+
dataset,
|
464 |
+
dataset_names,
|
465 |
+
text_column_names,
|
466 |
+
text_col_name_ref,
|
467 |
+
audio_column_name,
|
468 |
+
sampling_rate
|
469 |
+
)
|
470 |
+
return dataset
|
471 |
+
|
472 |
+
|
473 |
+
def print_data_samples(dataset, tokenizer, max_samples=5):
|
474 |
+
shown_samples = 0
|
475 |
+
for batch in dataset:
|
476 |
+
print("Target: ", tokenizer.decode(batch["labels"]))
|
477 |
+
shown_samples += len(batch)
|
478 |
+
if shown_samples >= max_samples:
|
479 |
+
break
|
480 |
+
|
481 |
+
|
482 |
+
def main():
|
483 |
+
# 1. Parse input arguments
|
484 |
+
# See all possible arguments in src/transformers/training_args.py
|
485 |
+
# or by passing the --help flag to this script.
|
486 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
487 |
+
logger.info("*** Parse args ***")
|
488 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
489 |
+
|
490 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
491 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
492 |
+
# let's parse it to get our arguments.
|
493 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
494 |
+
else:
|
495 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
496 |
+
|
497 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
498 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
499 |
+
send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
|
500 |
+
|
501 |
+
# 2. Setup logging
|
502 |
+
logger.info("*** Setup logging ***")
|
503 |
+
logging.basicConfig(
|
504 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
505 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
506 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
507 |
+
)
|
508 |
+
log_level = training_args.get_process_log_level()
|
509 |
+
logger.setLevel(log_level)
|
510 |
+
datasets.utils.logging.set_verbosity(log_level)
|
511 |
+
transformers.utils.logging.set_verbosity(log_level)
|
512 |
+
transformers.utils.logging.enable_default_handler()
|
513 |
+
transformers.utils.logging.enable_explicit_format()
|
514 |
+
|
515 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
516 |
+
|
517 |
+
# Log on each process the small summary:
|
518 |
+
logger.warning(
|
519 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
520 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
521 |
+
)
|
522 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
523 |
+
|
524 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
525 |
+
if is_main_process(training_args.local_rank):
|
526 |
+
transformers.utils.logging.set_verbosity_info()
|
527 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
528 |
+
|
529 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
530 |
+
last_checkpoint = None
|
531 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
532 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
533 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
534 |
+
raise ValueError(
|
535 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
536 |
+
"Use --overwrite_output_dir to overcome."
|
537 |
+
)
|
538 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
539 |
+
logger.info(
|
540 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
541 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
542 |
+
)
|
543 |
+
|
544 |
+
# Set seed before initializing model.
|
545 |
+
set_seed(training_args.seed)
|
546 |
+
|
547 |
+
# Load feature extractor
|
548 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
549 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
550 |
+
cache_dir=model_args.cache_dir,
|
551 |
+
revision=model_args.model_revision,
|
552 |
+
use_auth_token=hf_token if model_args.use_auth_token else None,
|
553 |
+
)
|
554 |
+
|
555 |
+
# 4. Load dataset
|
556 |
+
logger.info("*** Load dataset ***")
|
557 |
+
raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
|
558 |
+
|
559 |
+
if len(data_args.language_eval.split(",")) > 1:
|
560 |
+
raise ValueError("Implementation does not support multiple language evaluation.")
|
561 |
+
|
562 |
+
if training_args.do_train:
|
563 |
+
raw_datasets["train"] = load_maybe_streaming_dataset(
|
564 |
+
data_args.dataset_train_name,
|
565 |
+
data_args.dataset_train_config_name,
|
566 |
+
split=data_args.train_split_name,
|
567 |
+
use_auth_token=hf_token if model_args.use_auth_token else None,
|
568 |
+
streaming=data_args.streaming,
|
569 |
+
text_column_name=data_args.text_column_name,
|
570 |
+
audio_column_name=data_args.audio_column_name,
|
571 |
+
sampling_rate=int(feature_extractor.sampling_rate),
|
572 |
+
# language=data_args.language_train
|
573 |
+
)
|
574 |
+
|
575 |
+
if training_args.do_eval:
|
576 |
+
raw_datasets["eval"] = load_maybe_streaming_dataset(
|
577 |
+
data_args.dataset_eval_name,
|
578 |
+
data_args.dataset_eval_config_name,
|
579 |
+
split=data_args.eval_split_name,
|
580 |
+
use_auth_token=hf_token if model_args.use_auth_token else None,
|
581 |
+
streaming=data_args.streaming,
|
582 |
+
text_column_name=data_args.text_column_name,
|
583 |
+
audio_column_name=data_args.audio_column_name,
|
584 |
+
sampling_rate=int(feature_extractor.sampling_rate),
|
585 |
+
# language=data_args.language_eval
|
586 |
+
)
|
587 |
+
|
588 |
+
raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
|
589 |
+
|
590 |
+
if data_args.audio_column_name not in raw_datasets_features:
|
591 |
+
raise ValueError(
|
592 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset. "
|
593 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
594 |
+
f"{', '.join(raw_datasets_features)}."
|
595 |
+
)
|
596 |
+
|
597 |
+
data_args.text_column_name = data_args.text_column_name.split(",")[0]
|
598 |
+
if data_args.text_column_name not in raw_datasets_features:
|
599 |
+
raise ValueError(
|
600 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset. "
|
601 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
602 |
+
f"{', '.join(raw_datasets_features)}."
|
603 |
+
)
|
604 |
+
|
605 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
606 |
+
logger.info("*** Load pretrained model, tokenizer, and feature extractor ***")
|
607 |
+
# Distributed training:
|
608 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
609 |
+
config = AutoConfig.from_pretrained(
|
610 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
611 |
+
cache_dir=model_args.cache_dir,
|
612 |
+
revision=model_args.model_revision,
|
613 |
+
use_auth_token=hf_token if model_args.use_auth_token else None
|
614 |
+
)
|
615 |
+
|
616 |
+
# Forced decoder ids will be overwritten before evaluation
|
617 |
+
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
|
618 |
+
|
619 |
+
if training_args.gradient_checkpointing:
|
620 |
+
config.update({"use_cache": False})
|
621 |
+
|
622 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
623 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
624 |
+
cache_dir=model_args.cache_dir,
|
625 |
+
use_fast=model_args.use_fast_tokenizer,
|
626 |
+
revision=model_args.model_revision,
|
627 |
+
use_auth_token=hf_token if model_args.use_auth_token else None,
|
628 |
+
)
|
629 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
630 |
+
model_args.model_name_or_path,
|
631 |
+
config=config,
|
632 |
+
cache_dir=model_args.cache_dir,
|
633 |
+
revision=model_args.model_revision,
|
634 |
+
use_auth_token=hf_token if model_args.use_auth_token else None,
|
635 |
+
)
|
636 |
+
|
637 |
+
if model.config.decoder_start_token_id is None:
|
638 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
639 |
+
|
640 |
+
if model_args.freeze_feature_encoder:
|
641 |
+
model.freeze_feature_encoder()
|
642 |
+
|
643 |
+
if model_args.freeze_encoder:
|
644 |
+
model.freeze_encoder()
|
645 |
+
|
646 |
+
tokenizer.set_prefix_tokens(language="swedish", task=data_args.task)
|
647 |
+
|
648 |
+
# if data_args.language_train is not None and len(data_args.language_train.split(",")) == 1:
|
649 |
+
# # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
650 |
+
# # If more than a langugae is specified, it will be specified in the data collator
|
651 |
+
# tokenizer.set_prefix_tokens(language=data_args.language_train, task=data_args.task)
|
652 |
+
# elif data_args.language_train is not None and len(data_args.language_train.split(",")) > 1:
|
653 |
+
# # make sure language and task are not stored in the model config
|
654 |
+
# model.config.forced_decoder_ids = None
|
655 |
+
|
656 |
+
# 6. Resample speech dataset if necessary
|
657 |
+
# logger.info("*** Resample dataset ***")
|
658 |
+
# dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
|
659 |
+
# if dataset_sampling_rate != feature_extractor.sampling_rate:
|
660 |
+
|
661 |
+
|
662 |
+
# 7. Preprocessing the datasets.
|
663 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
664 |
+
logger.info("*** Preprocess dataset ***")
|
665 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
666 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
667 |
+
audio_column_name = data_args.audio_column_name
|
668 |
+
text_column_name = data_args.text_column_name
|
669 |
+
model_input_name = feature_extractor.model_input_names[0]
|
670 |
+
do_lower_case = data_args.do_lower_case
|
671 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
672 |
+
normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
|
673 |
+
|
674 |
+
if data_args.max_train_samples is not None:
|
675 |
+
raw_datasets["train"] = (
|
676 |
+
raw_datasets["train"].take(data_args.max_train_samples)
|
677 |
+
if data_args.streaming
|
678 |
+
else raw_datasets["train"].select(range(data_args.max_train_samples))
|
679 |
+
)
|
680 |
+
|
681 |
+
if data_args.max_eval_samples is not None:
|
682 |
+
raw_datasets["eval"] = (
|
683 |
+
raw_datasets["eval"].take(data_args.max_eval_samples)
|
684 |
+
if data_args.streaming
|
685 |
+
else raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
686 |
+
)
|
687 |
+
|
688 |
+
def prepare_dataset(batch):
|
689 |
+
# process audio
|
690 |
+
sample = batch[audio_column_name]
|
691 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
692 |
+
# process audio length
|
693 |
+
batch[model_input_name] = inputs.get(model_input_name)[0]
|
694 |
+
batch["input_length"] = len(sample["array"])
|
695 |
+
|
696 |
+
# process targets
|
697 |
+
input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
|
698 |
+
if do_remove_punctuation:
|
699 |
+
input_str = normalizer(input_str).strip()
|
700 |
+
batch["labels"] = tokenizer(input_str).input_ids
|
701 |
+
return batch
|
702 |
+
|
703 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
704 |
+
# raw_datasets_features.remove("language")
|
705 |
+
vectorized_datasets = raw_datasets.map(
|
706 |
+
prepare_dataset,
|
707 |
+
remove_columns=raw_datasets_features,
|
708 |
+
).with_format("torch")
|
709 |
+
|
710 |
+
if training_args.do_train and data_args.streaming:
|
711 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
712 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
|
713 |
+
buffer_size=data_args.shuffle_buffer_size,
|
714 |
+
seed=training_args.seed,
|
715 |
+
)
|
716 |
+
|
717 |
+
# filter training data that is shorter than min_input_length or longer than
|
718 |
+
# max_input_length
|
719 |
+
def is_audio_in_length_range(length):
|
720 |
+
return min_input_length < length < max_input_length
|
721 |
+
|
722 |
+
if training_args.do_train:
|
723 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
724 |
+
is_audio_in_length_range,
|
725 |
+
input_columns=["input_length"],
|
726 |
+
)
|
727 |
+
|
728 |
+
# 8. Load Metric
|
729 |
+
logger.info("*** Load metric ***")
|
730 |
+
metric = evaluate.load("wer")
|
731 |
+
do_normalize_eval = data_args.do_normalize_eval
|
732 |
+
|
733 |
+
def compute_metrics(pred):
|
734 |
+
pred_ids = pred.predictions
|
735 |
+
|
736 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
737 |
+
|
738 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
739 |
+
# we do not want to group tokens when computing the metrics
|
740 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
741 |
+
|
742 |
+
if do_normalize_eval:
|
743 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
744 |
+
label_str = [normalizer(label) for label in label_str]
|
745 |
+
# filtering step to only evaluate the samples that correspond to non-zero references:
|
746 |
+
pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
|
747 |
+
label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
|
748 |
+
|
749 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
750 |
+
|
751 |
+
return {"wer": wer}
|
752 |
+
|
753 |
+
# 9. Create a single speech processor
|
754 |
+
logger.info("*** Init processor ***")
|
755 |
+
if is_main_process(training_args.local_rank):
|
756 |
+
# save feature extractor, tokenizer and config
|
757 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
758 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
759 |
+
config.save_pretrained(training_args.output_dir)
|
760 |
+
|
761 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
762 |
+
|
763 |
+
# 10. Define data collator
|
764 |
+
task_token = data_args.task
|
765 |
+
if not task_token.startswith('<|'):
|
766 |
+
task_token = f'<{task_token}>'
|
767 |
+
task_id = tokenizer(task_token).input_ids[0]
|
768 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
769 |
+
processor=processor,
|
770 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
771 |
+
task_id=task_id
|
772 |
+
)
|
773 |
+
|
774 |
+
# 11. Configure Trainer
|
775 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
776 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
777 |
+
logger.info("*** Set shuffle callback ***")
|
778 |
+
class ShuffleCallback(TrainerCallback):
|
779 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
780 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
781 |
+
pass # set_epoch() is handled by the Trainer
|
782 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
783 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
784 |
+
|
785 |
+
|
786 |
+
# Initialize Trainer
|
787 |
+
logger.info("*** Init trainer ***")
|
788 |
+
trainer = Seq2SeqTrainer(
|
789 |
+
model=model,
|
790 |
+
args=training_args,
|
791 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
792 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
793 |
+
tokenizer=feature_extractor,
|
794 |
+
data_collator=data_collator,
|
795 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
796 |
+
callbacks=[ShuffleCallback()] if data_args.streaming else None,
|
797 |
+
)
|
798 |
+
logger.info("*** Trainer initialized ***")
|
799 |
+
|
800 |
+
orig_push_to_hub = trainer.args.push_to_hub
|
801 |
+
trainer.args.push_to_hub = False
|
802 |
+
|
803 |
+
# 12. Training
|
804 |
+
if training_args.do_train:
|
805 |
+
logger.info("*** Train ***")
|
806 |
+
print_data_samples(vectorized_datasets["train"], tokenizer)
|
807 |
+
checkpoint = None
|
808 |
+
if training_args.resume_from_checkpoint is not None:
|
809 |
+
checkpoint = training_args.resume_from_checkpoint
|
810 |
+
elif last_checkpoint is not None:
|
811 |
+
checkpoint = last_checkpoint
|
812 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
813 |
+
logger.info("*** Training completed ***")
|
814 |
+
logger.info("*** Saving model ***")
|
815 |
+
# We don't want to push the model to the hub now
|
816 |
+
# so we temporarily set to false the push_to_hub attribute
|
817 |
+
# and then reset it to the original value
|
818 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
819 |
+
logger.info("*** Model saved ***")
|
820 |
+
metrics = train_result.metrics
|
821 |
+
if data_args.max_train_samples:
|
822 |
+
metrics["train_samples"] = data_args.max_train_samples
|
823 |
+
logger.info("*** Logging metrics ***")
|
824 |
+
trainer.log_metrics("train", metrics)
|
825 |
+
logger.info("*** Metrics logged ***")
|
826 |
+
logger.info("*** Saving metrics ***")
|
827 |
+
trainer.save_metrics("train", metrics)
|
828 |
+
logger.info("*** Metrics saved ***")
|
829 |
+
logger.info("*** Saving state ***")
|
830 |
+
trainer.save_state()
|
831 |
+
logger.info("*** State saved ***")
|
832 |
+
|
833 |
+
# Run a test prediction to check outputs
|
834 |
+
predictions = trainer.predict(
|
835 |
+
test_dataset=vectorized_datasets["eval"].shuffle(seed=training_args.seed).take(5),
|
836 |
+
metric_key_prefix="test",
|
837 |
+
max_length=training_args.generation_max_length,
|
838 |
+
num_beams=training_args.generation_num_beams,
|
839 |
+
)
|
840 |
+
logger.info("*** Test prediction done ***")
|
841 |
+
preds = tokenizer.batch_decode(predictions.predictions)
|
842 |
+
labels = tokenizer.batch_decode(predictions.label_ids)
|
843 |
+
pred_labels = [f"Prediction: {pred}\nLabel: {label}\n" for pred, label in zip(preds, labels)]
|
844 |
+
logger.info("Before setting language and task")
|
845 |
+
logger.info(f"{pred_labels}")
|
846 |
+
language_name = LANGUAGES[data_args.language_eval]
|
847 |
+
trainer.model.config.forced_decoder_ids = \
|
848 |
+
tokenizer.get_decoder_prompt_ids(language=language_name, task=data_args.task, no_timestamps=True)
|
849 |
+
preds = tokenizer.batch_decode(predictions.predictions)
|
850 |
+
labels = tokenizer.batch_decode(predictions.label_ids)
|
851 |
+
pred_labels = [f"Prediction: {pred}\nLabel: {label}\n" for pred, label in zip(preds, labels)]
|
852 |
+
logger.info("After setting language and task")
|
853 |
+
logger.info(f"{pred_labels}")
|
854 |
+
|
855 |
+
# 13. Evaluation
|
856 |
+
results = {}
|
857 |
+
if training_args.do_eval:
|
858 |
+
logger.info("*** Evaluate ***")
|
859 |
+
print_data_samples(vectorized_datasets["eval"], tokenizer)
|
860 |
+
metrics = trainer.evaluate(
|
861 |
+
metric_key_prefix="eval",
|
862 |
+
max_length=training_args.generation_max_length,
|
863 |
+
num_beams=training_args.generation_num_beams,
|
864 |
+
)
|
865 |
+
logger.info("*** Evaluation done ***")
|
866 |
+
if data_args.max_eval_samples:
|
867 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
868 |
+
logger.info("*** Logging metrics ***")
|
869 |
+
trainer.log_metrics("eval", metrics)
|
870 |
+
logger.info("*** Metrics logged ***")
|
871 |
+
logger.info("*** Saving metrics ***")
|
872 |
+
trainer.save_metrics("eval", metrics)
|
873 |
+
logger.info("*** Metrics saved ***")
|
874 |
+
|
875 |
+
# 14. Write Training Stats
|
876 |
+
logger.info("*** Writing training stats ***")
|
877 |
+
kwargs = {
|
878 |
+
"finetuned_from": model_args.model_name_or_path,
|
879 |
+
"tasks": "automatic-speech-recognition",
|
880 |
+
"tags": "whisper-event",
|
881 |
+
}
|
882 |
+
if data_args.dataset_train_name is not None:
|
883 |
+
dataset_names = list(data_args.dataset_train_name.split(","))
|
884 |
+
kwargs["dataset_tags"] = dataset_names
|
885 |
+
# if data_args.dataset_train_config_name is not None:
|
886 |
+
# dataset_config_names = list(data_args.dataset_train_config_name.split(","))
|
887 |
+
# dataset_config_names_list = [f"{ds_name} {ds_cfg_name}" for ds_name, ds_cfg_name in zip(dataset_names, dataset_config_names)]
|
888 |
+
# else:
|
889 |
+
# dataset_config_names_list = dataset_names
|
890 |
+
# kwargs["dataset"] = "\n".join(dataset_config_names_list)
|
891 |
+
# if "common_voice" in data_args.dataset_name:
|
892 |
+
# kwargs["language"] = data_args.dataset_config_name[:2]
|
893 |
+
if data_args.language_train is not None:
|
894 |
+
languages = list(set(data_args.language_train.split(",")))
|
895 |
+
kwargs["language"] = languages
|
896 |
+
if model_args.model_index_name is not None:
|
897 |
+
kwargs["model_name"] = model_args.model_index_name
|
898 |
+
|
899 |
+
logger.info("*** Training stats written ***")
|
900 |
+
logger.info(json.dumps(kwargs, indent=4))
|
901 |
+
|
902 |
+
# Training complete notification
|
903 |
+
logger.info("*** Training and eval complete ***")
|
904 |
+
logger.info(SENDING_NOTIFICATION)
|
905 |
+
with open(os.path.join(training_args.output_dir, "train_results.json"), "r") as f:
|
906 |
+
train_results = json.load(f)
|
907 |
+
with open(os.path.join(training_args.output_dir, "eval_results.json"), "r") as f:
|
908 |
+
eval_results = json.load(f)
|
909 |
+
notify_me(recipient=RECIPIENT_ADDRESS,
|
910 |
+
message=f"Training complete! {train_results = } {eval_results = }")
|
911 |
+
|
912 |
+
trainer.args.push_to_hub = orig_push_to_hub
|
913 |
+
if training_args.push_to_hub:
|
914 |
+
logger.info("*** Pushing to hub ***")
|
915 |
+
trainer.push_to_hub(**kwargs)
|
916 |
+
logger.info("*** Pushed to hub ***")
|
917 |
+
logger.info(SENDING_NOTIFICATION)
|
918 |
+
else:
|
919 |
+
logger.info("*** Creating model card ***")
|
920 |
+
trainer.create_model_card(**kwargs)
|
921 |
+
logger.info("*** Model card created ***")
|
922 |
+
logger.info(SENDING_NOTIFICATION)
|
923 |
+
|
924 |
+
with open(os.path.join(training_args.output_dir, "README.md"), "r") as f:
|
925 |
+
readme = f.read()
|
926 |
+
notify_me(recipient=RECIPIENT_ADDRESS,
|
927 |
+
message=f"Model pushed to hub! {readme = }")
|
928 |
+
|
929 |
+
return results
|
930 |
+
|
931 |
+
|
932 |
+
if __name__ == "__main__":
|
933 |
+
main()
|