AlexN commited on
Commit
aff1b86
1 Parent(s): 072f549
.ipynb_checkpoints/run-checkpoint.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_ctc.py \
2
+ --dataset_name="mozilla-foundation/common_voice_8_0" \
3
+ --model_name_or_path="./checkpoint-18000-keep" \
4
+ --dataset_config_name="pt" \
5
+ --output_dir="./" \
6
+ --overwrite_output_dir \
7
+ --num_train_epochs="16" \
8
+ --per_device_train_batch_size="64" \
9
+ --per_device_eval_batch_size="64" \
10
+ --gradient_accumulation_steps="1" \
11
+ --learning_rate="1e-4" \
12
+ --warmup_steps="2000" \
13
+ --length_column_name="input_length" \
14
+ --evaluation_strategy="steps" \
15
+ --text_column_name="sentence" \
16
+ --save_steps="500" \
17
+ --eval_steps="500" \
18
+ --logging_steps="100" \
19
+ --layerdrop="0.0" \
20
+ --activation_dropout="0.05" \
21
+ --save_total_limit="3" \
22
+ --freeze_feature_encoder \
23
+ --feat_proj_dropout="0.0" \
24
+ --mask_time_prob="0.65" \
25
+ --mask_time_length="10" \
26
+ --mask_feature_prob="0.3" \
27
+ --mask_feature_length="10" \
28
+ --gradient_checkpointing \
29
+ --report_to="wandb" \
30
+ --run_name="xls-r-300m-fr" \
31
+ --max_eval_samples="4500" \
32
+ --max_duration_in_seconds="10" \
33
+ --use_auth_token \
34
+ --fp16 \
35
+ --group_by_length \
36
+ --preprocessing_num_workers="64" \
37
+ --do_train --do_eval \
38
+ --load_best_model_at_end \
39
+ --push_to_hub
.ipynb_checkpoints/validate-checkpoint.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ python eval.py --model_id="./" --dataset="mozilla-foundation/common_voice_8_0" --config="fr" --split="test" --log_outputs
2
+ python eval.py --model_id="./" --dataset="speech-recognition-community-v2/dev_data" --config="fr" \
3
+ --split="validation" --chunk_length_s="5.0" --stride_length_s="1.0" --log_outputs
eval.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ import unicodedata
5
+ from typing import Dict
6
+
7
+ import torch
8
+ from datasets import Audio, Dataset, load_dataset, load_metric
9
+
10
+ from transformers import AutoFeatureExtractor, pipeline
11
+
12
+
13
+ def log_results(result: Dataset, args: Dict[str, str]):
14
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
15
+
16
+ log_outputs = args.log_outputs
17
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
18
+
19
+ # load metric
20
+ wer = load_metric("wer")
21
+ cer = load_metric("cer")
22
+
23
+ # compute metrics
24
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
25
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
26
+
27
+ # print & log results
28
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
29
+ print(result_str)
30
+
31
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
32
+ f.write(result_str)
33
+
34
+ # log all results in text file. Possibly interesting for analysis
35
+ if log_outputs is not None:
36
+ pred_file = f"log_{dataset_id}_predictions.txt"
37
+ target_file = f"log_{dataset_id}_targets.txt"
38
+
39
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
40
+
41
+ # mapping function to write output
42
+ def write_to_file(batch, i):
43
+ p.write(f"{i}" + "\n")
44
+ p.write(batch["prediction"] + "\n")
45
+ t.write(f"{i}" + "\n")
46
+ t.write(batch["target"] + "\n")
47
+
48
+ result.map(write_to_file, with_indices=True)
49
+
50
+
51
+ chars_to_remove_regex = r'[\,\?\.\!\-\_\;\:\"\“\%\‘\”\�\^]'
52
+
53
+ def remove_accents(text):
54
+ nfkd_form = unicodedata.normalize('NFKD', text)
55
+ return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
56
+
57
+ def remove_special_characters(text):
58
+ text = re.sub(chars_to_remove_regex, '', text).lower()
59
+ text = re.sub("ç", r'[cedille]', text)
60
+ text = re.sub("&", r'et', text)
61
+ text = re.sub("%", r' pourcents', text)
62
+ text = re.sub("([0-9]+)(,|.)([0-9+])", r'\1 virgule \3', text)
63
+ text = re.sub("\$", r'dollar', text)
64
+ text = re.sub("\£", r'livre', text)
65
+ text = re.sub("\€", r'euro', text)
66
+ text = remove_accents(text)
67
+ text = re.sub(r"\[cedille\]", 'ç', text) + " "
68
+ return text
69
+
70
+ def normalize_text(text: str) -> str:
71
+ text = remove_special_characters(text)
72
+
73
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
74
+ # note that order is important here!
75
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
76
+
77
+ for t in token_sequences_to_ignore:
78
+ text = " ".join(text.split(t))
79
+
80
+ return text
81
+
82
+
83
+ def main(args):
84
+ # load dataset
85
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
86
+
87
+ # for testing: only process the first two examples as a test
88
+ # dataset = dataset.select(range(2))
89
+
90
+ # load processor
91
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
92
+ sampling_rate = feature_extractor.sampling_rate
93
+
94
+ # resample audio
95
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
96
+
97
+ # load eval pipeline
98
+ if args.device is None:
99
+ args.device = 0 if torch.cuda.is_available() else -1
100
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
101
+
102
+ # map function to decode audio
103
+ def map_to_pred(batch):
104
+ prediction = asr(
105
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
106
+ )
107
+
108
+ batch["prediction"] = prediction["text"] # "".join(prediction["text"].split("<s>"))
109
+ batch["target"] = normalize_text(batch["sentence"])
110
+ return batch
111
+
112
+ # run inference on all examples
113
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
114
+
115
+ # compute and log_results
116
+ # do not change function below
117
+ log_results(result, args)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ parser = argparse.ArgumentParser()
122
+
123
+ parser.add_argument(
124
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
125
+ )
126
+ parser.add_argument(
127
+ "--dataset",
128
+ type=str,
129
+ required=True,
130
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
131
+ )
132
+ parser.add_argument(
133
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
134
+ )
135
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
136
+ parser.add_argument(
137
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
138
+ )
139
+ parser.add_argument(
140
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
141
+ )
142
+ parser.add_argument(
143
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
144
+ )
145
+ parser.add_argument(
146
+ "--device",
147
+ type=int,
148
+ default=None,
149
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
150
+ )
151
+ args = parser.parse_args()
152
+
153
+ main(args)
run.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_ctc.py \
2
+ --dataset_name="mozilla-foundation/common_voice_8_0" \
3
+ --model_name_or_path="./checkpoint-18000-keep" \
4
+ --dataset_config_name="pt" \
5
+ --output_dir="./" \
6
+ --overwrite_output_dir \
7
+ --num_train_epochs="16" \
8
+ --per_device_train_batch_size="64" \
9
+ --per_device_eval_batch_size="64" \
10
+ --gradient_accumulation_steps="1" \
11
+ --learning_rate="1e-4" \
12
+ --warmup_steps="2000" \
13
+ --length_column_name="input_length" \
14
+ --evaluation_strategy="steps" \
15
+ --text_column_name="sentence" \
16
+ --save_steps="500" \
17
+ --eval_steps="500" \
18
+ --logging_steps="100" \
19
+ --layerdrop="0.0" \
20
+ --activation_dropout="0.05" \
21
+ --save_total_limit="3" \
22
+ --freeze_feature_encoder \
23
+ --feat_proj_dropout="0.0" \
24
+ --mask_time_prob="0.65" \
25
+ --mask_time_length="10" \
26
+ --mask_feature_prob="0.3" \
27
+ --mask_feature_length="10" \
28
+ --gradient_checkpointing \
29
+ --report_to="wandb" \
30
+ --run_name="xls-r-300m-fr" \
31
+ --max_eval_samples="4500" \
32
+ --max_duration_in_seconds="10" \
33
+ --use_auth_token \
34
+ --fp16 \
35
+ --group_by_length \
36
+ --preprocessing_num_workers="64" \
37
+ --do_train --do_eval \
38
+ --load_best_model_at_end \
39
+ --push_to_hub
run_speech_recognition_ctc.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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
+
16
+ """ Fine-tuning a 🤗 Transformers CTC model for automatic speech recognition"""
17
+
18
+ import functools
19
+ import json
20
+ import logging
21
+ import os
22
+ import re
23
+ import sys
24
+ import warnings
25
+ from dataclasses import dataclass, field
26
+ from typing import Dict, List, Optional, Union
27
+ import unicodedata
28
+
29
+ import datasets
30
+ import numpy as np
31
+ import torch
32
+ from datasets import DatasetDict, load_dataset, load_metric
33
+
34
+ import transformers
35
+ from transformers import (
36
+ AutoConfig,
37
+ AutoFeatureExtractor,
38
+ AutoModelForCTC,
39
+ AutoProcessor,
40
+ AutoTokenizer,
41
+ HfArgumentParser,
42
+ Trainer,
43
+ TrainingArguments,
44
+ Wav2Vec2Processor,
45
+ Wav2Vec2CTCTokenizer,
46
+ set_seed,
47
+ )
48
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
49
+ from transformers.utils import check_min_version
50
+ from transformers.utils.versions import require_version
51
+
52
+
53
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
54
+ check_min_version("4.16.0.dev0")
55
+
56
+ require_version("datasets>=1.13.3", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
57
+
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ def list_field(default=None, metadata=None):
63
+ return field(default_factory=lambda: default, metadata=metadata)
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ """
69
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
70
+ """
71
+
72
+ model_name_or_path: str = field(
73
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
74
+ )
75
+ tokenizer_name_or_path: Optional[str] = field(
76
+ default=None,
77
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
78
+ )
79
+ cache_dir: Optional[str] = field(
80
+ default=None,
81
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
82
+ )
83
+ freeze_feature_encoder: bool = field(
84
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
85
+ )
86
+ attention_dropout: float = field(
87
+ default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
88
+ )
89
+ activation_dropout: float = field(
90
+ default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
91
+ )
92
+ feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
93
+ hidden_dropout: float = field(
94
+ default=0.0,
95
+ metadata={
96
+ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
97
+ },
98
+ )
99
+ final_dropout: float = field(
100
+ default=0.0,
101
+ metadata={"help": "The dropout probability for the final projection layer."},
102
+ )
103
+ mask_time_prob: float = field(
104
+ default=0.05,
105
+ metadata={
106
+ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
107
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
108
+ "vectors will be masked along the time axis."
109
+ },
110
+ )
111
+ mask_time_length: int = field(
112
+ default=10,
113
+ metadata={"help": "Length of vector span to mask along the time axis."},
114
+ )
115
+ mask_feature_prob: float = field(
116
+ default=0.0,
117
+ metadata={
118
+ "help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
119
+ "span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
120
+ },
121
+ )
122
+ mask_feature_length: int = field(
123
+ default=10,
124
+ metadata={"help": "Length of vector span to mask along the feature axis."},
125
+ )
126
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
127
+ ctc_loss_reduction: Optional[str] = field(
128
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
129
+ )
130
+
131
+
132
+ @dataclass
133
+ class DataTrainingArguments:
134
+ """
135
+ Arguments pertaining to what data we are going to input our model for training and eval.
136
+
137
+ Using `HfArgumentParser` we can turn this class
138
+ into argparse arguments to be able to specify them on
139
+ the command line.
140
+ """
141
+
142
+ dataset_name: str = field(
143
+ metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
144
+ )
145
+ dataset_config_name: str = field(
146
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
147
+ )
148
+ train_split_name: str = field(
149
+ default="train+validation",
150
+ metadata={
151
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
152
+ },
153
+ )
154
+ eval_split_name: str = field(
155
+ default="test",
156
+ metadata={
157
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'test'"
158
+ },
159
+ )
160
+ audio_column_name: str = field(
161
+ default="audio",
162
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
163
+ )
164
+ text_column_name: str = field(
165
+ default="text",
166
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
167
+ )
168
+ overwrite_cache: bool = field(
169
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
170
+ )
171
+ preprocessing_num_workers: Optional[int] = field(
172
+ default=None,
173
+ metadata={"help": "The number of processes to use for the preprocessing."},
174
+ )
175
+ max_train_samples: Optional[int] = field(
176
+ default=None,
177
+ metadata={
178
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
179
+ "value if set."
180
+ },
181
+ )
182
+ max_eval_samples: Optional[int] = field(
183
+ default=None,
184
+ metadata={
185
+ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
186
+ "value if set."
187
+ },
188
+ )
189
+ chars_to_ignore: Optional[List[str]] = list_field(
190
+ default=None,
191
+ metadata={"help": "A list of characters to remove from the transcripts."},
192
+ )
193
+ eval_metrics: List[str] = list_field(
194
+ default=["wer"],
195
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
196
+ )
197
+ max_duration_in_seconds: float = field(
198
+ default=20.0,
199
+ metadata={
200
+ "help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
201
+ },
202
+ )
203
+ min_duration_in_seconds: float = field(
204
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
205
+ )
206
+ preprocessing_only: bool = field(
207
+ default=False,
208
+ metadata={
209
+ "help": "Whether to only do data preprocessing and skip training. "
210
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
211
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
212
+ "so that the cached datasets can consequently be loaded in distributed training"
213
+ },
214
+ )
215
+ use_auth_token: bool = field(
216
+ default=False,
217
+ metadata={
218
+ "help": "If :obj:`True`, will use the token generated when running"
219
+ ":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
220
+ },
221
+ )
222
+ unk_token: str = field(
223
+ default="[UNK]",
224
+ metadata={"help": "The unk token for the tokenizer"},
225
+ )
226
+ pad_token: str = field(
227
+ default="[PAD]",
228
+ metadata={"help": "The padding token for the tokenizer"},
229
+ )
230
+ word_delimiter_token: str = field(
231
+ default="|",
232
+ metadata={"help": "The word delimiter token for the tokenizer"},
233
+ )
234
+ phoneme_language: Optional[str] = field(
235
+ default=None,
236
+ metadata={
237
+ "help": "The target language that should be used be"
238
+ " passed to the tokenizer for tokenization. Note that"
239
+ " this is only relevant if the model classifies the"
240
+ " input audio to a sequence of phoneme sequences."
241
+ },
242
+ )
243
+
244
+
245
+ @dataclass
246
+ class DataCollatorCTCWithPadding:
247
+ """
248
+ Data collator that will dynamically pad the inputs received.
249
+ Args:
250
+ processor (:class:`~transformers.AutoProcessor`)
251
+ The processor used for proccessing the data.
252
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
253
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
254
+ among:
255
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
256
+ sequence if provided).
257
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
258
+ maximum acceptable input length for the model if that argument is not provided.
259
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
260
+ different lengths).
261
+ max_length (:obj:`int`, `optional`):
262
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
263
+ max_length_labels (:obj:`int`, `optional`):
264
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
265
+ pad_to_multiple_of (:obj:`int`, `optional`):
266
+ If set will pad the sequence to a multiple of the provided value.
267
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
268
+ 7.5 (Volta).
269
+ """
270
+
271
+ processor: AutoProcessor
272
+ padding: Union[bool, str] = "longest"
273
+ pad_to_multiple_of: Optional[int] = None
274
+ pad_to_multiple_of_labels: Optional[int] = None
275
+
276
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
277
+ # split inputs and labels since they have to be of different lenghts and need
278
+ # different padding methods
279
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
280
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
281
+
282
+ batch = self.processor.pad(
283
+ input_features,
284
+ padding=self.padding,
285
+ pad_to_multiple_of=self.pad_to_multiple_of,
286
+ return_tensors="pt",
287
+ )
288
+
289
+ with self.processor.as_target_processor():
290
+ labels_batch = self.processor.pad(
291
+ label_features,
292
+ padding=self.padding,
293
+ pad_to_multiple_of=self.pad_to_multiple_of_labels,
294
+ return_tensors="pt",
295
+ )
296
+
297
+ # replace padding with -100 to ignore loss correctly
298
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
299
+
300
+ batch["labels"] = labels
301
+
302
+ return batch
303
+
304
+
305
+ def create_vocabulary_from_data(
306
+ datasets: DatasetDict,
307
+ word_delimiter_token: Optional[str] = None,
308
+ unk_token: Optional[str] = None,
309
+ pad_token: Optional[str] = None,
310
+ ):
311
+ # Given training and test labels create vocabulary
312
+ def extract_all_chars(batch):
313
+ all_text = " ".join(batch["target_text"])
314
+ vocab = list(set(all_text))
315
+ return {"vocab": [vocab], "all_text": [all_text]}
316
+
317
+ vocabs = datasets.map(
318
+ extract_all_chars,
319
+ batched=True,
320
+ batch_size=-1,
321
+ keep_in_memory=True,
322
+ remove_columns=datasets["train"].column_names,
323
+ )
324
+
325
+ # take union of all unique characters in each dataset
326
+ vocab_set = functools.reduce(
327
+ lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values()
328
+ )
329
+
330
+ vocab_dict = {v: k for k, v in enumerate(sorted(list(vocab_set)))}
331
+
332
+ # replace white space with delimiter token
333
+ if word_delimiter_token is not None:
334
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
335
+ del vocab_dict[" "]
336
+
337
+ # add unk and pad token
338
+ if unk_token is not None:
339
+ vocab_dict[unk_token] = len(vocab_dict)
340
+
341
+ if pad_token is not None:
342
+ vocab_dict[pad_token] = len(vocab_dict)
343
+
344
+ return vocab_dict
345
+
346
+
347
+ def main():
348
+ # See all possible arguments in src/transformers/training_args.py
349
+ # or by passing the --help flag to this script.
350
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
351
+
352
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
353
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
354
+ # If we pass only one argument to the script and it's the path to a json file,
355
+ # let's parse it to get our arguments.
356
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
357
+ else:
358
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
359
+
360
+ # Detecting last checkpoint.
361
+ last_checkpoint = None
362
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
363
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
364
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
365
+ raise ValueError(
366
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
367
+ "Use --overwrite_output_dir to overcome."
368
+ )
369
+ elif last_checkpoint is not None:
370
+ logger.info(
371
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
372
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
373
+ )
374
+
375
+ # Setup logging
376
+ logging.basicConfig(
377
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
378
+ datefmt="%m/%d/%Y %H:%M:%S",
379
+ handlers=[logging.StreamHandler(sys.stdout)],
380
+ )
381
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
382
+
383
+ # Log on each process the small summary:
384
+ logger.warning(
385
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
386
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
387
+ )
388
+ # Set the verbosity to info of the Transformers logger (on main process only):
389
+ if is_main_process(training_args.local_rank):
390
+ transformers.utils.logging.set_verbosity_info()
391
+ logger.info("Training/evaluation parameters %s", training_args)
392
+
393
+ # Set seed before initializing model.
394
+ set_seed(training_args.seed)
395
+
396
+ # 1. First, let's load the dataset
397
+ raw_datasets = DatasetDict()
398
+
399
+ if training_args.do_train:
400
+ raw_datasets["train"] = load_dataset(
401
+ data_args.dataset_name,
402
+ data_args.dataset_config_name,
403
+ split=data_args.train_split_name,
404
+ use_auth_token=data_args.use_auth_token,
405
+ cache_dir="../downloaded_data/"
406
+ )
407
+
408
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
409
+ raise ValueError(
410
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
411
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
412
+ f"{', '.join(raw_datasets['train'].column_names)}."
413
+ )
414
+
415
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
416
+ raise ValueError(
417
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
418
+ "Make sure to set `--text_column_name` to the correct text column - one of "
419
+ f"{', '.join(raw_datasets['train'].column_names)}."
420
+ )
421
+
422
+ if data_args.max_train_samples is not None:
423
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
424
+
425
+ if training_args.do_eval:
426
+ raw_datasets["eval"] = load_dataset(
427
+ data_args.dataset_name,
428
+ data_args.dataset_config_name,
429
+ split=data_args.eval_split_name,
430
+ use_auth_token=data_args.use_auth_token,
431
+ cache_dir="../downloaded_data/"
432
+ )
433
+
434
+ if data_args.max_eval_samples is not None:
435
+ raw_datasets["eval"] = raw_datasets["eval"].shuffle(seed=42).select(range(data_args.max_eval_samples))
436
+
437
+ # 2. We remove some special characters from the datasets
438
+ # that make training complicated and do not help in transcribing the speech
439
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
440
+ # that could be easily picked up by the model
441
+ text_column_name = data_args.text_column_name
442
+
443
+ chars_to_remove_regex = r'[\,\?\.\!\-\_\;\:\"\“\%\‘\”\�\^]'
444
+
445
+ def remove_accents(input_str):
446
+ nfkd_form = unicodedata.normalize('NFKD', input_str)
447
+ return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
448
+
449
+ def remove_special_characters(batch):
450
+ batch["target_text"] = re.sub(chars_to_remove_regex, '', batch[text_column_name]).lower()
451
+ batch["target_text"] = re.sub("ç", r'[cedille]', batch["target_text"])
452
+ batch["target_text"] = re.sub("&", r'et', batch["target_text"])
453
+ batch["target_text"] = re.sub("%", r' pourcents', batch["target_text"])
454
+ batch["target_text"] = re.sub("([0-9]+)(,|.)([0-9+])", r'\1 virgule \3', batch["target_text"])
455
+ batch["target_text"] = re.sub("\$", r'dollar', batch["target_text"])
456
+ batch["target_text"] = re.sub("\£", r'livre', batch["target_text"])
457
+ batch["target_text"] = re.sub("\€", r'euro', batch["target_text"])
458
+ batch["target_text"] = remove_accents(batch["target_text"])
459
+ batch["target_text"] = re.sub(r"\[cedille\]", 'ç', batch["target_text"]) + " "
460
+ return batch
461
+
462
+ with training_args.main_process_first(desc="dataset map special characters removal"):
463
+ raw_datasets = raw_datasets.map(
464
+ remove_special_characters,
465
+ remove_columns=[text_column_name],
466
+ desc="remove special characters from datasets"
467
+ )
468
+
469
+ # save special tokens for tokenizer
470
+ word_delimiter_token = data_args.word_delimiter_token
471
+ unk_token = data_args.unk_token
472
+ pad_token = data_args.pad_token
473
+
474
+ # 3. Next, let's load the config as we might need it to create
475
+ # the tokenizer
476
+ # load config
477
+ config = AutoConfig.from_pretrained(
478
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
479
+ )
480
+
481
+ # 4. Next, if no tokenizer file is defined,
482
+ # we create the vocabulary of the model by extracting all unique characters from
483
+ # the training and evaluation datasets
484
+ # We need to make sure that only first rank saves vocabulary
485
+ # make sure all processes wait until vocab is created
486
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
487
+ tokenizer_kwargs = {}
488
+ if tokenizer_name_or_path is None:
489
+ # save vocab in training output dir
490
+ tokenizer_name_or_path = training_args.output_dir
491
+
492
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
493
+
494
+ with training_args.main_process_first():
495
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
496
+ os.remove(vocab_file)
497
+
498
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
499
+ if not os.path.isfile(vocab_file):
500
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
501
+ vocab_dict = create_vocabulary_from_data(
502
+ raw_datasets,
503
+ word_delimiter_token=word_delimiter_token,
504
+ unk_token=unk_token,
505
+ pad_token=pad_token,
506
+ )
507
+
508
+ # save vocab dict to be loaded into tokenizer
509
+ with open(vocab_file, "w") as file:
510
+ json.dump(vocab_dict, file)
511
+
512
+ # if tokenizer has just been created
513
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
514
+ tokenizer_kwargs = {
515
+ "config": config if config.tokenizer_class is not None else None,
516
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
517
+ "unk_token": unk_token,
518
+ "pad_token": pad_token,
519
+ "word_delimiter_token": word_delimiter_token,
520
+ }
521
+
522
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
523
+ # Note for distributed training, the .from_pretrained methods guarantee that only
524
+ # one local process can concurrently download model & vocab.
525
+
526
+ # load feature_extractor and tokenizer
527
+ tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(
528
+ tokenizer_name_or_path,
529
+ use_auth_token=data_args.use_auth_token,
530
+ **tokenizer_kwargs,
531
+ )
532
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
533
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
534
+ )
535
+
536
+ # adapt config
537
+ config.update(
538
+ {
539
+ "feat_proj_dropout": model_args.feat_proj_dropout,
540
+ "attention_dropout": model_args.attention_dropout,
541
+ "hidden_dropout": model_args.hidden_dropout,
542
+ "final_dropout": model_args.final_dropout,
543
+ "mask_time_prob": model_args.mask_time_prob,
544
+ "mask_time_length": model_args.mask_time_length,
545
+ "mask_feature_prob": model_args.mask_feature_prob,
546
+ "mask_feature_length": model_args.mask_feature_length,
547
+ "gradient_checkpointing": training_args.gradient_checkpointing,
548
+ "layerdrop": model_args.layerdrop,
549
+ "ctc_loss_reduction": model_args.ctc_loss_reduction,
550
+ "pad_token_id": tokenizer.pad_token_id,
551
+ "vocab_size": len(tokenizer),
552
+ "activation_dropout": model_args.activation_dropout,
553
+ }
554
+ )
555
+
556
+ # create model
557
+ model = AutoModelForCTC.from_pretrained(
558
+ model_args.model_name_or_path,
559
+ cache_dir=model_args.cache_dir,
560
+ config=config,
561
+ use_auth_token=data_args.use_auth_token,
562
+ )
563
+
564
+ # freeze encoder
565
+ if model_args.freeze_feature_encoder:
566
+ model.freeze_feature_encoder()
567
+
568
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
569
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
570
+ # so that we just need to set the correct target sampling rate and normalize the input
571
+ # via the `feature_extractor`
572
+
573
+ # make sure that dataset decodes audio with correct sampling rate
574
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
575
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
576
+ raw_datasets = raw_datasets.cast_column(
577
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
578
+ )
579
+
580
+ # derive max & min input length for sample rate & max duration
581
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
582
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
583
+ audio_column_name = data_args.audio_column_name
584
+ num_workers = data_args.preprocessing_num_workers
585
+
586
+ # `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
587
+ phoneme_language = data_args.phoneme_language
588
+
589
+ # Preprocessing the datasets.
590
+ # We need to read the audio files as arrays and tokenize the targets.
591
+ def prepare_dataset(batch):
592
+ # load audio
593
+ sample = batch[audio_column_name]
594
+
595
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
596
+ batch["input_values"] = inputs.input_values[0]
597
+ batch["input_length"] = len(batch["input_values"])
598
+
599
+ # encode targets
600
+ additional_kwargs = {}
601
+ if phoneme_language is not None:
602
+ additional_kwargs["phonemizer_lang"] = phoneme_language
603
+
604
+ batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
605
+ return batch
606
+
607
+ with training_args.main_process_first(desc="dataset map preprocessing"):
608
+ vectorized_datasets = raw_datasets.map(
609
+ prepare_dataset,
610
+ remove_columns=next(iter(raw_datasets.values())).column_names,
611
+ batch_size=-1,
612
+ desc="preprocess datasets",cache_dir="../data_cache/"
613
+ )
614
+
615
+ def is_audio_in_length_range(length):
616
+ return length > min_input_length and length < max_input_length
617
+
618
+ # filter data that is shorter than min_input_length
619
+ vectorized_datasets = vectorized_datasets.filter(
620
+ is_audio_in_length_range,
621
+ num_proc=num_workers,
622
+ input_columns=["input_length"],
623
+ )
624
+
625
+ # 7. Next, we can prepare the training.
626
+ # Let's use word error rate (WER) as our evaluation metric,
627
+ # instantiate a data collator and the trainer
628
+
629
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
630
+ eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}
631
+
632
+ # for large datasets it is advised to run the preprocessing on a
633
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
634
+ # be a timeout when running the script in distributed mode.
635
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
636
+ # cached dataset
637
+ if data_args.preprocessing_only:
638
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
639
+ return
640
+
641
+ def compute_metrics(pred):
642
+ pred_logits = pred.predictions
643
+ pred_ids = np.argmax(pred_logits, axis=-1)
644
+
645
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
646
+
647
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)#being sure to remove <s> from the output
648
+ # we do not want to group tokens when computing the metrics
649
+ label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
650
+
651
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
652
+
653
+ return metrics
654
+
655
+ # Now save everything to be able to create a single processor later
656
+ if is_main_process(training_args.local_rank):
657
+ # save feature extractor, tokenizer and config
658
+ feature_extractor.save_pretrained(training_args.output_dir)
659
+ tokenizer.save_pretrained(training_args.output_dir)
660
+ config.save_pretrained(training_args.output_dir)
661
+
662
+ try:
663
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
664
+ except (OSError, KeyError):
665
+ warnings.warn(
666
+ "Loading a processor from a feature extractor config that does not"
667
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
668
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
669
+ " `'processor_class': 'Wav2Vec2Processor'`",
670
+ FutureWarning,
671
+ )
672
+ processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
673
+
674
+ # Instantiate custom data collator
675
+ data_collator = DataCollatorCTCWithPadding(processor=processor)
676
+
677
+ # Initialize Trainer
678
+ trainer = Trainer(
679
+ model=model,
680
+ data_collator=data_collator,
681
+ args=training_args,
682
+ compute_metrics=compute_metrics,
683
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
684
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
685
+ tokenizer=feature_extractor,
686
+ )
687
+
688
+ # 8. Finally, we can start training
689
+
690
+ # Training
691
+ if training_args.do_train:
692
+
693
+ # use last checkpoint if exist
694
+ if last_checkpoint is not None:
695
+ checkpoint = last_checkpoint
696
+ elif os.path.isdir(model_args.model_name_or_path):
697
+ checkpoint = model_args.model_name_or_path
698
+ else:
699
+ checkpoint = None
700
+
701
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
702
+ trainer.save_model()
703
+
704
+ metrics = train_result.metrics
705
+ max_train_samples = (
706
+ data_args.max_train_samples
707
+ if data_args.max_train_samples is not None
708
+ else len(vectorized_datasets["train"])
709
+ )
710
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
711
+
712
+ trainer.log_metrics("train", metrics)
713
+ trainer.save_metrics("train", metrics)
714
+ trainer.save_state()
715
+
716
+ # Evaluation
717
+ results = {}
718
+ if training_args.do_eval:
719
+ logger.info("*** Evaluate ***")
720
+ metrics = trainer.evaluate()
721
+ max_eval_samples = (
722
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
723
+ )
724
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
725
+
726
+ trainer.log_metrics("eval", metrics)
727
+ trainer.save_metrics("eval", metrics)
728
+
729
+ # Write model card and (optionally) push to hub
730
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
731
+ kwargs = {
732
+ "finetuned_from": model_args.model_name_or_path,
733
+ "tasks": "speech-recognition",
734
+ "tags": ["automatic-speech-recognition", "robust-speech-event", data_args.dataset_name],
735
+ "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
736
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
737
+ }
738
+ if "common_voice" in data_args.dataset_name:
739
+ kwargs["language"] = config_name
740
+
741
+ if training_args.push_to_hub:
742
+ trainer.push_to_hub(**kwargs)
743
+ else:
744
+ trainer.create_model_card(**kwargs)
745
+
746
+ return results
747
+
748
+
749
+ if __name__ == "__main__":
750
+ main()
validate.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ python eval.py --model_id="./" --dataset="mozilla-foundation/common_voice_8_0" --config="fr" --split="test" --log_outputs
2
+ python eval.py --model_id="./" --dataset="speech-recognition-community-v2/dev_data" --config="fr" \
3
+ --split="validation" --chunk_length_s="5.0" --stride_length_s="1.0" --log_outputs