bakrianoo commited on
Commit
c9f41c7
1 Parent(s): fb2dc12

update README

Browse files
README.md CHANGED
@@ -1,309 +1,105 @@
1
  ---
2
- language: ar
 
 
 
 
 
 
3
  datasets:
4
- - common_voice
5
  metrics:
6
  - wer
7
- tags:
8
- - audio
9
- - automatic-speech-recognition
10
- - speech
11
- - xlsr-fine-tuning-week
12
- license: apache-2.0
13
  model-index:
14
  - name: Sinai Voice Arabic Speech Recognition Model
15
  results:
16
  - task:
17
- name: Speech Recognition
18
  type: automatic-speech-recognition
 
19
  dataset:
 
20
  name: Common Voice ar
21
- type: common_voice
22
  args: ar
23
  metrics:
24
- - name: Test WER
25
- type: wer
26
- value: 23.80
 
 
 
 
 
 
 
 
27
  ---
 
 
28
 
29
  # Sinai Voice Arabic Speech Recognition Model
30
- # نموذج **صوت سيناء** للتعرف على الأصوات العربية الفصحى و تحويلها إلى نصوص
31
- Fine-tuned [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53)
32
- on Arabic using the [Common Voice](https://huggingface.co/datasets/common_voice)
33
-
34
- Most of evaluation codes in this documentation are INSPIRED by [elgeish/wav2vec2-large-xlsr-53-arabic](https://huggingface.co/elgeish/wav2vec2-large-xlsr-53-arabic)
35
-
36
- Please install:
37
- - [PyTorch](https://pytorch.org/)
38
- - `$ pip3 install jiwer lang_trans torchaudio datasets transformers pandas tqdm`
39
-
40
- ## Benchmark
41
-
42
- We evaluated the model against different Arabic-STT Wav2Vec models.
43
-
44
- [**WER**: Word Error Rate] The Lowest score you get, the best model you have
45
-
46
- | | Model | [using transliteration](https://pypi.org/project/lang-trans/) | WER | Training Datasets |
47
- |---:|:--------------------------------------|:---------------------|---------:|---------:|
48
- | 1 | bakrianoo/sinai-voice-ar-stt | True | 0.238001 |Common Voice 6|
49
- | 2 | elgeish/wav2vec2-large-xlsr-53-arabic | True | 0.266527 |Common Voice 6 + Arabic Speech Corpus|
50
- | 3 | othrif/wav2vec2-large-xlsr-arabic | True | 0.298122 |Common Voice 6|
51
- | 4 | bakrianoo/sinai-voice-ar-stt | False | 0.448987 |Common Voice 6|
52
- | 5 | othrif/wav2vec2-large-xlsr-arabic | False | 0.464004 |Common Voice 6|
53
- | 6 | anas/wav2vec2-large-xlsr-arabic | True | 0.506191 |Common Voice 4|
54
- | 7 | anas/wav2vec2-large-xlsr-arabic | False | 0.622288 |Common Voice 4|
55
-
56
-
57
- <details>
58
- <summary>We used the following <b>CODE</b> to generate the above results</summary>
59
-
60
- ```python
61
- import jiwer
62
- import torch
63
- from tqdm.auto import tqdm
64
- import torchaudio
65
- from datasets import load_dataset
66
- from lang_trans.arabic import buckwalter
67
- from transformers import set_seed, Wav2Vec2ForCTC, Wav2Vec2Processor
68
- import pandas as pd
69
-
70
- # load test dataset
71
- set_seed(42)
72
- test_split = load_dataset("common_voice", "ar", split="test")
73
-
74
- # init sample rate resamplers
75
- resamplers = { # all three sampling rates exist in test split
76
- 48000: torchaudio.transforms.Resample(48000, 16000),
77
- 44100: torchaudio.transforms.Resample(44100, 16000),
78
- 32000: torchaudio.transforms.Resample(32000, 16000),
79
- }
80
 
81
- # WER composer
82
- transformation = jiwer.Compose([
83
- # normalize some diacritics, remove punctuation, and replace Persian letters with Arabic ones
84
- jiwer.SubstituteRegexes({
85
- r'[auiFNKo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~_،؟»\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?;:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.؛«!"]': "", "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\u06D6": "",
86
- r"[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\{]": "A", "p": "h", "ک": "k", "ی": "y"}),
87
- # default transformation below
88
- jiwer.RemoveMultipleSpaces(),
89
- jiwer.Strip(),
90
- jiwer.SentencesToListOfWords(),
91
- jiwer.RemoveEmptyStrings(),
92
- ])
93
-
94
- def prepare_example(example):
95
- speech, sampling_rate = torchaudio.load(example["path"])
96
- if sampling_rate in resamplers:
97
- example["speech"] = resamplers[sampling_rate](speech).squeeze().numpy()
98
- else:
99
- example["speech"] = resamplers[4800](speech).squeeze().numpy()
100
- return example
101
-
102
- def predict(batch):
103
- inputs = processor(batch["speech"], sampling_rate=16000, return_tensors="pt", padding=True)
104
- with torch.no_grad():
105
- predicted = torch.argmax(model(inputs.input_values.to("cuda")).logits, dim=-1)
106
- predicted[predicted == -100] = processor.tokenizer.pad_token_id # see fine-tuning script
107
- batch["predicted"] = processor.batch_decode(predicted)
108
- return batch
109
-
110
- # prepare the test dataset
111
- test_split = test_split.map(prepare_example)
112
 
113
- stt_models = [
114
- "elgeish/wav2vec2-large-xlsr-53-arabic",
115
- "othrif/wav2vec2-large-xlsr-arabic",
116
- "anas/wav2vec2-large-xlsr-arabic",
117
- "bakrianoo/sinai-voice-ar-stt"
118
- ]
119
 
120
- stt_results = []
 
 
 
121
 
122
- for model_path in tqdm(stt_models):
123
- processor = Wav2Vec2Processor.from_pretrained(model_path)
124
- model = Wav2Vec2ForCTC.from_pretrained(model_path).to("cuda").eval()
125
-
126
- test_split_preds = test_split.map(predict, batched=True, batch_size=56, remove_columns=["speech"])
127
-
128
- orig_metrics = jiwer.compute_measures(
129
- truth=[s for s in test_split_preds["sentence"]],
130
- hypothesis=[s for s in test_split_preds["predicted"]],
131
- truth_transform=transformation,
132
- hypothesis_transform=transformation,
133
- )
134
-
135
- trans_metrics = jiwer.compute_measures(
136
- truth=[buckwalter.trans(s) for s in test_split_preds["sentence"]], # Buckwalter transliteration
137
- hypothesis=[buckwalter.trans(s) for s in test_split_preds["predicted"]], # Buckwalter transliteration
138
- truth_transform=transformation,
139
- hypothesis_transform=transformation,
140
- )
141
-
142
- stt_results.append({
143
- "model": model_path,
144
- "using_transliation": True,
145
- "WER": trans_metrics["wer"]
146
- })
147
-
148
- stt_results.append({
149
- "model": model_path,
150
- "using_transliation": False,
151
- "WER": orig_metrics["wer"]
152
- })
153
-
154
- del model
155
- del processor
156
-
157
- stt_results_df = pd.DataFrame(stt_results)
158
- stt_results_df = stt_results_df.sort_values('WER', axis=0, ascending=True)
159
- stt_results_df.head(n=50)
160
 
 
 
161
  ```
162
- </details>
163
 
164
 
165
- ## Usage
166
 
167
- The model can be used directly (without a language model) as follows:
168
  ```python
169
- import torch
170
  import torchaudio
171
- from datasets import load_dataset
172
- from lang_trans.arabic import buckwalter
173
- from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
174
- dataset = load_dataset("common_voice", "ar", split="test[:10]")
175
- resamplers = { # all three sampling rates exist in test split
176
- 48000: torchaudio.transforms.Resample(48000, 16000),
177
- 44100: torchaudio.transforms.Resample(44100, 16000),
178
- 32000: torchaudio.transforms.Resample(32000, 16000),
179
- }
180
-
181
- def prepare_example(example):
182
- speech, sampling_rate = torchaudio.load(example["path"])
183
- if sampling_rate in resamplers:
184
- example["speech"] = resamplers[sampling_rate](speech).squeeze().numpy()
185
- else:
186
- example["speech"] = resamplers[4800](speech).squeeze().numpy()
187
- return example
188
-
189
- dataset = dataset.map(prepare_example)
190
- processor = Wav2Vec2Processor.from_pretrained("bakrianoo/sinai-voice-ar-stt")
191
- model = Wav2Vec2ForCTC.from_pretrained("bakrianoo/sinai-voice-ar-stt").eval()
192
- def predict(batch):
193
- inputs = processor(batch["speech"], sampling_rate=16000, return_tensors="pt", padding=True)
194
- with torch.no_grad():
195
- predicted = torch.argmax(model(inputs.input_values).logits, dim=-1)
196
- predicted[predicted == -100] = processor.tokenizer.pad_token_id # see fine-tuning script
197
- batch["predicted"] = processor.tokenizer.batch_decode(predicted)
198
- return batch
199
- dataset = dataset.map(predict, batched=True, batch_size=1, remove_columns=["speech"])
200
- for reference, predicted in zip(dataset["sentence"], dataset["predicted"]):
201
- print("reference:", reference)
202
- print("predicted:", predicted)
203
- print("--")
204
- ```
205
- Here's the output:
206
- ```
207
- reference: ألديك قلم ؟
208
- predicted: ألديك قلم
209
- --
210
- reference: ليست هناك مسافة على هذه الأرض أبعد من يوم أمس.
211
- predicted: ليست نارك مسافة على هذه الأرض أبعد من يوم أمس
212
- --
213
- reference: إنك تكبر المشكلة.
214
- predicted: إنك تكبر المشكلة
215
- --
216
- reference: يرغب أن يلتقي بك.
217
- predicted: يرغب أن يلتقي بك
218
- --
219
- reference: إنهم لا يعرفون لماذا حتى.
220
- predicted: إنهم لا يعرفون لماذا حتى
221
- --
222
- reference: سيسعدني مساعدتك أي وقت تحب.
223
- predicted: سيسعدن مساعثتك أي وقد تحب
224
- --
225
- reference: أَحَبُّ نظريّة علمية إليّ هي أن حلقات زحل مكونة بالكا��ل من الأمتعة المفقودة.
226
- predicted: أحب نظرية علمية إلي هي أن أحلقتز حلم كوينا بالكامل من الأمت عن المفقودة
227
- --
228
- reference: سأشتري له قلماً.
229
- predicted: سأشتري له قلما
230
- --
231
- reference: أين المشكلة ؟
232
- predicted: أين المشكل
233
- --
234
- reference: وَلِلَّهِ يَسْجُدُ مَا فِي السَّمَاوَاتِ وَمَا فِي الْأَرْضِ مِنْ دَابَّةٍ وَالْمَلَائِكَةُ وَهُمْ لَا يَسْتَكْبِرُونَ
235
- predicted: ولله يسجد ما في السماوات وما في الأرض من دابة والملائكة وهم لا يستكبرون
236
- ```
237
-
238
- ## Evaluation
239
-
240
- The model can be evaluated as follows on the Arabic test data of Common Voice:
241
- ```python
242
- import jiwer
243
  import torch
244
- import torchaudio
245
- from datasets import load_dataset
246
- from lang_trans.arabic import buckwalter
247
- from transformers import set_seed, Wav2Vec2ForCTC, Wav2Vec2Processor
248
- set_seed(42)
249
- test_split = load_dataset("common_voice", "ar", split="test")
250
- resamplers = { # all three sampling rates exist in test split
251
- 48000: torchaudio.transforms.Resample(48000, 16000),
252
- 44100: torchaudio.transforms.Resample(44100, 16000),
253
- 32000: torchaudio.transforms.Resample(32000, 16000),
254
- }
255
-
256
- def prepare_example(example):
257
- speech, sampling_rate = torchaudio.load(example["path"])
258
- if sampling_rate in resamplers:
259
- example["speech"] = resamplers[sampling_rate](speech).squeeze().numpy()
260
- else:
261
- example["speech"] = resamplers[4800](speech).squeeze().numpy()
262
- return example
263
-
264
- test_split = test_split.map(prepare_example)
265
- processor = Wav2Vec2Processor.from_pretrained("bakrianoo/sinai-voice-ar-stt")
266
- model = Wav2Vec2ForCTC.from_pretrained("bakrianoo/sinai-voice-ar-stt").to("cuda").eval()
267
- def predict(batch):
268
- inputs = processor(batch["speech"], sampling_rate=16000, return_tensors="pt", padding=True)
269
- with torch.no_grad():
270
- predicted = torch.argmax(model(inputs.input_values.to("cuda")).logits, dim=-1)
271
- predicted[predicted == -100] = processor.tokenizer.pad_token_id # see fine-tuning script
272
- batch["predicted"] = processor.batch_decode(predicted)
273
- return batch
274
- test_split = test_split.map(predict, batched=True, batch_size=16, remove_columns=["speech"])
275
 
276
- transformation = jiwer.Compose([
277
- # normalize some diacritics, remove punctuation, and replace Persian letters with Arabic ones
278
- jiwer.SubstituteRegexes({
279
- r'[auiFNKo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~_،؟»\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?;:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.؛«!"]': "", "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\u06D6": "",
280
- r"[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\{]": "A", "p": "h", "ک": "k", "ی": "y"}),
281
- # default transformation below
282
- jiwer.RemoveMultipleSpaces(),
283
- jiwer.Strip(),
284
- jiwer.SentencesToListOfWords(),
285
- jiwer.RemoveEmptyStrings(),
286
- ])
287
 
288
- metrics = jiwer.compute_measures(
289
- truth=[buckwalter.trans(s) for s in test_split["sentence"]], # Buckwalter transliteration
290
- hypothesis=[buckwalter.trans(s) for s in test_split["predicted"]],
291
- truth_transform=transformation,
292
- hypothesis_transform=transformation,
293
- )
294
- print(f"WER: {metrics['wer']:.2%}")
295
- ```
296
- **Test Result**: 23.80%
297
 
298
- [**WER**: Word Error Rate] The Lowest score you get, the best model you have
 
299
 
 
 
300
 
301
- ## Other Arabic Voice recognition Models
 
302
 
303
- الكلمات لا تكفى لشكر أولئك الذين يؤمنون أن هنالك أمل, و يسعون من أجله
304
 
305
- - [elgeish/wav2vec2-large-xlsr-53-arabic](https://huggingface.co/elgeish/wav2vec2-large-xlsr-53-arabic)
306
- - [othrif/wav2vec2-large-xlsr-arabic](https://huggingface.co/othrif/wav2vec2-large-xlsr-arabic)
307
- - [anas/wav2vec2-large-xlsr-arabic](https://huggingface.co/anas/wav2vec2-large-xlsr-arabic)
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
 
1
  ---
2
+ language:
3
+ - ar
4
+
5
+ license: apache-2.0
6
+ tags:
7
+ - automatic-speech-recognition
8
+ - robust-speech-event
9
  datasets:
10
+ - mozilla-foundation/common_voice_8_0
11
  metrics:
12
  - wer
13
+ - cer
 
 
 
 
 
14
  model-index:
15
  - name: Sinai Voice Arabic Speech Recognition Model
16
  results:
17
  - task:
 
18
  type: automatic-speech-recognition
19
+ name: Speech Recognition
20
  dataset:
21
+ type: mozilla-foundation/common_voice_8_0
22
  name: Common Voice ar
 
23
  args: ar
24
  metrics:
25
+ - type: wer # Required. Example: wer
26
+ value: 0.18 # Required. Example: 20.90
27
+ name: Test WER # Optional. Example: Test WER
28
+
29
+ - type: cer # Required. Example: wer
30
+ value: 0.051 # Required. Example: 20.90
31
+ name: Test CER # Optional. Example: Test WER
32
+
33
+ WER: 0.18855042016806722
34
+ CER: 0.05138746531806014
35
+
36
  ---
37
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
38
+ should probably proofread and complete it, then remove this comment. -->
39
 
40
  # Sinai Voice Arabic Speech Recognition Model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ # نموذج **صوت سيناء** للتعرف على الأصوات العربية الفصحى و تحويلها إلى نصوص
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ This model is a fine-tuned version of [facebook/wav2vec2-xls-r-300m](https://huggingface.co/facebook/wav2vec2-xls-r-300m) on the common_voice 8 dataset.
 
 
 
 
 
45
 
46
+ It achieves the following results on the evaluation set:
47
+ - Loss: 0.22
48
+ - Wer: 0.189
49
+ - Cer: 0.051
50
 
51
+ #### Evaluation Commands
52
+ 1. To evaluate on `mozilla-foundation/common_voice_8_0` with split `test`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ ```bash
55
+ python eval.py --model_id bakrianoo/sinai-voice-ar-stt --dataset mozilla-foundation/common_voice_8_0 --config ar --split test
56
  ```
 
57
 
58
 
59
+ ### Inference Without LM
60
 
 
61
  ```python
62
+ from transformers import (Wav2Vec2Processor, Wav2Vec2ForCTC)
63
  import torchaudio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ def speech_file_to_array_fn(voice_path, resampling_to=16000):
67
+ speech_array, sampling_rate = torchaudio.load(voice_path)
68
+ resampler = torchaudio.transforms.Resample(sampling_rate, resampling_to)
69
+
70
+ return resampler(speech_array)[0].numpy(), sampling_rate
 
 
 
 
 
 
71
 
72
+ # load the model
73
+ cp = "bakrianoo/sinai-voice-ar-stt"
74
+ processor = Wav2Vec2Processor.from_pretrained(cp)
75
+ model = Wav2Vec2ForCTC.from_pretrained(cp)
 
 
 
 
 
76
 
77
+ # recognize the text in a sample sound file
78
+ sound_path = './my_voice.mp3'
79
 
80
+ sample, sr = speech_file_to_array_fn(sound_path)
81
+ inputs = processor([sample], sampling_rate=16_000, return_tensors="pt", padding=True)
82
 
83
+ with torch.no_grad():
84
+ logits = model(inputs.input_values,).logits
85
 
86
+ predicted_ids = torch.argmax(logits, dim=-1)
87
 
88
+ print("Prediction:", processor.batch_decode(predicted_ids))
89
+ ```
 
90
 
91
+ ### Training hyperparameters
92
+
93
+ The following hyperparameters were used during training:
94
+ - learning_rate: 0.0002
95
+ - train_batch_size: 32
96
+ - eval_batch_size: 10
97
+ - seed: 42
98
+ - gradient_accumulation_steps: 2
99
+ - total_train_batch_size: 128
100
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
101
+ - lr_scheduler_type: linear
102
+ - lr_scheduler_warmup_steps: 1000
103
+ - num_epochs: 8.32
104
+ - mixed_precision_training: Native AMP
105
 
eval.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ from typing import Dict
5
+
6
+ import torch
7
+ from datasets import Audio, Dataset, load_dataset, load_metric
8
+
9
+ from transformers import AutoFeatureExtractor, pipeline
10
+
11
+
12
+ def log_results(result: Dataset, args: Dict[str, str]):
13
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
14
+
15
+ log_outputs = args.log_outputs
16
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
17
+
18
+ # load metric
19
+ wer = load_metric("wer")
20
+ cer = load_metric("cer")
21
+
22
+ # compute metrics
23
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
24
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
25
+
26
+ # print & log results
27
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
28
+ print(result_str)
29
+
30
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
31
+ f.write(result_str)
32
+
33
+ # log all results in text file. Possibly interesting for analysis
34
+ if log_outputs is not None:
35
+ pred_file = f"log_{dataset_id}_predictions.txt"
36
+ target_file = f"log_{dataset_id}_targets.txt"
37
+
38
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
39
+
40
+ # mapping function to write output
41
+ def write_to_file(batch, i):
42
+ p.write(f"{i}" + "\n")
43
+ p.write(batch["prediction"] + "\n")
44
+ t.write(f"{i}" + "\n")
45
+ t.write(batch["target"] + "\n")
46
+
47
+ result.map(write_to_file, with_indices=True)
48
+
49
+
50
+ def normalize_text(text: str) -> str:
51
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
52
+
53
+ chars_to_ignore_regex = '[zx.rﺃ“—`»NٍqAُ«☭ﻻْۛjQ,R?IDdٌOwemھa\'cۙMJ:”ًکWXZ؛;(ۘ…P)YCFٰۗsiۖklSng–fh\-Ep!ٓLVِۚBtyUTKHڨvbuGچَ؟]'
54
+
55
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
56
+
57
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
58
+ # note that order is important here!
59
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
60
+
61
+ for t in token_sequences_to_ignore:
62
+ text = " ".join(text.split(t))
63
+
64
+ return text
65
+
66
+
67
+ def main(args):
68
+ # load dataset
69
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
70
+
71
+ # for testing: only process the first two examples as a test
72
+ # dataset = dataset.select(range(10))
73
+
74
+ # load processor
75
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
76
+ sampling_rate = feature_extractor.sampling_rate
77
+
78
+ # resample audio
79
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
80
+
81
+ # load eval pipeline
82
+ if args.device is None:
83
+ args.device = 0 if torch.cuda.is_available() else -1
84
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
85
+
86
+ # map function to decode audio
87
+ def map_to_pred(batch):
88
+ prediction = asr(
89
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
90
+ )
91
+
92
+ batch["prediction"] = prediction["text"]
93
+ batch["target"] = normalize_text(batch["sentence"])
94
+ return batch
95
+
96
+ # run inference on all examples
97
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names, batch_size=5)
98
+
99
+ # compute and log_results
100
+ # do not change function below
101
+ log_results(result, args)
102
+
103
+
104
+ if __name__ == "__main__":
105
+ parser = argparse.ArgumentParser()
106
+
107
+ parser.add_argument(
108
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
109
+ )
110
+ parser.add_argument(
111
+ "--dataset",
112
+ type=str,
113
+ required=True,
114
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
115
+ )
116
+ parser.add_argument(
117
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
118
+ )
119
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
120
+ parser.add_argument(
121
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
122
+ )
123
+ parser.add_argument(
124
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
125
+ )
126
+ parser.add_argument(
127
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
128
+ )
129
+ parser.add_argument(
130
+ "--device",
131
+ type=int,
132
+ default=None,
133
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
134
+ )
135
+ args = parser.parse_args()
136
+
137
+ main(args)
log_mozilla-foundation_common_voice_8_0_ar_test_predictions.txt ADDED
The diff for this file is too large to render. See raw diff
log_mozilla-foundation_common_voice_8_0_ar_test_targets.txt ADDED
The diff for this file is too large to render. See raw diff
mozilla-foundation_common_voice_8_0_ar_test_eval_results.txt ADDED
@@ -0,0 +1,2 @@
 
 
1
+ WER: 0.18855042016806722
2
+ CER: 0.05138746531806014
run_speech_recognition_ctc_bnb.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
28
+ import datasets
29
+ import numpy as np
30
+ import torch
31
+ from datasets import DatasetDict, load_dataset, load_metric
32
+
33
+ import bitsandbytes as bnb
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
+ set_seed,
46
+ )
47
+ from transformers.trainer_pt_utils import get_parameter_names
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
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ def list_field(default=None, metadata=None):
56
+ return field(default_factory=lambda: default, metadata=metadata)
57
+
58
+
59
+ @dataclass
60
+ class ModelArguments:
61
+ """
62
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
63
+ """
64
+
65
+ model_name_or_path: str = field(
66
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
67
+ )
68
+ tokenizer_name_or_path: Optional[str] = field(
69
+ default=None,
70
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
71
+ )
72
+ cache_dir: Optional[str] = field(
73
+ default=None,
74
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
75
+ )
76
+ freeze_feature_encoder: bool = field(
77
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
78
+ )
79
+ attention_dropout: float = field(
80
+ default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
81
+ )
82
+ activation_dropout: float = field(
83
+ default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
84
+ )
85
+ feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
86
+ hidden_dropout: float = field(
87
+ default=0.0,
88
+ metadata={
89
+ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
90
+ },
91
+ )
92
+ final_dropout: float = field(
93
+ default=0.0,
94
+ metadata={"help": "The dropout probability for the final projection layer."},
95
+ )
96
+ mask_time_prob: float = field(
97
+ default=0.05,
98
+ metadata={
99
+ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
100
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
101
+ "vectors will be masked along the time axis."
102
+ },
103
+ )
104
+ mask_time_length: int = field(
105
+ default=10,
106
+ metadata={"help": "Length of vector span to mask along the time axis."},
107
+ )
108
+ mask_feature_prob: float = field(
109
+ default=0.0,
110
+ metadata={
111
+ "help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
112
+ "span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
113
+ },
114
+ )
115
+ mask_feature_length: int = field(
116
+ default=10,
117
+ metadata={"help": "Length of vector span to mask along the feature axis."},
118
+ )
119
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
120
+ ctc_loss_reduction: Optional[str] = field(
121
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
122
+ )
123
+
124
+
125
+ @dataclass
126
+ class DataTrainingArguments:
127
+ """
128
+ Arguments pertaining to what data we are going to input our model for training and eval.
129
+
130
+ Using `HfArgumentParser` we can turn this class
131
+ into argparse arguments to be able to specify them on
132
+ the command line.
133
+ """
134
+
135
+ dataset_name: str = field(
136
+ metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
137
+ )
138
+ dataset_config_name: str = field(
139
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
140
+ )
141
+ train_split_name: str = field(
142
+ default="train+validation",
143
+ metadata={
144
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
145
+ },
146
+ )
147
+ eval_split_name: str = field(
148
+ default="test",
149
+ metadata={
150
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
151
+ },
152
+ )
153
+ audio_column_name: str = field(
154
+ default="audio",
155
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
156
+ )
157
+ text_column_name: str = field(
158
+ default="text",
159
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
160
+ )
161
+ overwrite_cache: bool = field(
162
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
163
+ )
164
+ preprocessing_num_workers: Optional[int] = field(
165
+ default=None,
166
+ metadata={"help": "The number of processes to use for the preprocessing."},
167
+ )
168
+ max_train_samples: Optional[int] = field(
169
+ default=None,
170
+ metadata={
171
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
172
+ "value if set."
173
+ },
174
+ )
175
+ max_eval_samples: Optional[int] = field(
176
+ default=None,
177
+ metadata={
178
+ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
179
+ "value if set."
180
+ },
181
+ )
182
+ chars_to_ignore: Optional[List[str]] = list_field(
183
+ default=['چ', 'y', 'ۗ', 'n', 'J', 'C', 'K', 'V', 'g', ';', 'M', '?', 'u', 'S', 'ٌ', 'h', 'ً', '“', 'ۛ', 'r', 'P', '–', 'ﻻ', 'W', 'p', "'", 'o', 'Z', 'ۘ', 'ٰ', 'D', 'B', 'U', 'ﺃ', 'E', 'a', '»', '(', 'X', 'f', 'َ', '\\', 'l', 'x', 'v', 'ۖ', 'w', '”', 'ٍ', 'F', 'j', 'H', '…', '`', 'ڨ', 'O', ',', 'q', 'A', 'ِ', 'ٓ', '!', '؛', 'I', 't', 'ک', 'z', 'k', 's', '؟', 'd', 'G', 'ۚ', 'T', '—', 'R', ')', '«', 'Q', '☭', 'L', 'N', '-', 'Y', 'e', '.', 'c', ':', 'i', 'm', 'ُ', 'ۙ', 'ْ', 'b', 'ھ'],
184
+ metadata={"help": "A list of characters to remove from the transcripts."},
185
+ )
186
+ eval_metrics: List[str] = list_field(
187
+ default=["wer"],
188
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
189
+ )
190
+ max_duration_in_seconds: float = field(
191
+ default=20.0,
192
+ metadata={
193
+ "help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
194
+ },
195
+ )
196
+ min_duration_in_seconds: float = field(
197
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
198
+ )
199
+ preprocessing_only: bool = field(
200
+ default=False,
201
+ metadata={
202
+ "help": "Whether to only do data preprocessing and skip training. "
203
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
204
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
205
+ "so that the cached datasets can consequently be loaded in distributed training"
206
+ },
207
+ )
208
+ use_auth_token: bool = field(
209
+ default=False,
210
+ metadata={
211
+ "help": "If :obj:`True`, will use the token generated when running"
212
+ ":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
213
+ },
214
+ )
215
+ unk_token: str = field(
216
+ default="[UNK]",
217
+ metadata={"help": "The unk token for the tokenizer"},
218
+ )
219
+ pad_token: str = field(
220
+ default="[PAD]",
221
+ metadata={"help": "The padding token for the tokenizer"},
222
+ )
223
+ word_delimiter_token: str = field(
224
+ default="|",
225
+ metadata={"help": "The word delimiter token for the tokenizer"},
226
+ )
227
+ phoneme_language: Optional[str] = field(
228
+ default=None,
229
+ metadata={
230
+ "help": "The target language that should be used be"
231
+ " passed to the tokenizer for tokenization. Note that"
232
+ " this is only relevant if the model classifies the"
233
+ " input audio to a sequence of phoneme sequences."
234
+ },
235
+ )
236
+
237
+
238
+ @dataclass
239
+ class DataCollatorCTCWithPadding:
240
+ """
241
+ Data collator that will dynamically pad the inputs received.
242
+ Args:
243
+ processor (:class:`~transformers.AutoProcessor`)
244
+ The processor used for proccessing the data.
245
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
246
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
247
+ among:
248
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
249
+ sequence if provided).
250
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
251
+ maximum acceptable input length for the model if that argument is not provided.
252
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
253
+ different lengths).
254
+ max_length (:obj:`int`, `optional`):
255
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
256
+ max_length_labels (:obj:`int`, `optional`):
257
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
258
+ pad_to_multiple_of (:obj:`int`, `optional`):
259
+ If set will pad the sequence to a multiple of the provided value.
260
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
261
+ 7.5 (Volta).
262
+ """
263
+
264
+ processor: AutoProcessor
265
+ padding: Union[bool, str] = "longest"
266
+ pad_to_multiple_of: Optional[int] = None
267
+ pad_to_multiple_of_labels: Optional[int] = None
268
+
269
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
270
+ # split inputs and labels since they have to be of different lenghts and need
271
+ # different padding methods
272
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
273
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
274
+
275
+ batch = self.processor.pad(
276
+ input_features,
277
+ padding=self.padding,
278
+ pad_to_multiple_of=self.pad_to_multiple_of,
279
+ return_tensors="pt",
280
+ )
281
+
282
+ with self.processor.as_target_processor():
283
+ labels_batch = self.processor.pad(
284
+ label_features,
285
+ padding=self.padding,
286
+ pad_to_multiple_of=self.pad_to_multiple_of_labels,
287
+ return_tensors="pt",
288
+ )
289
+
290
+ # replace padding with -100 to ignore loss correctly
291
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
292
+
293
+ batch["labels"] = labels
294
+
295
+ return batch
296
+
297
+
298
+ def create_vocabulary_from_data(
299
+ datasets: DatasetDict,
300
+ word_delimiter_token: Optional[str] = None,
301
+ unk_token: Optional[str] = None,
302
+ pad_token: Optional[str] = None,
303
+ ):
304
+ # Given training and test labels create vocabulary
305
+ def extract_all_chars(batch):
306
+ all_text = " ".join(batch["target_text"])
307
+ vocab = list(set(all_text))
308
+ return {"vocab": [vocab], "all_text": [all_text]}
309
+
310
+ vocabs = datasets.map(
311
+ extract_all_chars,
312
+ batched=True,
313
+ batch_size=-1,
314
+ keep_in_memory=True,
315
+ remove_columns=datasets["train"].column_names,
316
+ )
317
+
318
+ # take union of all unique characters in each dataset
319
+ vocab_set = functools.reduce(
320
+ lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values()
321
+ )
322
+
323
+ vocab_dict = {v: k for k, v in enumerate(sorted(list(vocab_set)))}
324
+
325
+ # replace white space with delimiter token
326
+ if word_delimiter_token is not None:
327
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
328
+ del vocab_dict[" "]
329
+
330
+ # add unk and pad token
331
+ if unk_token is not None:
332
+ vocab_dict[unk_token] = len(vocab_dict)
333
+
334
+ if pad_token is not None:
335
+ vocab_dict[pad_token] = len(vocab_dict)
336
+
337
+ return vocab_dict
338
+
339
+
340
+ def main():
341
+ # See all possible arguments in src/transformers/training_args.py
342
+ # or by passing the --help flag to this script.
343
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
344
+
345
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
346
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
347
+ # If we pass only one argument to the script and it's the path to a json file,
348
+ # let's parse it to get our arguments.
349
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
350
+ else:
351
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
352
+
353
+ # Detecting last checkpoint.
354
+ last_checkpoint = None
355
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
356
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
357
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
358
+ raise ValueError(
359
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
360
+ "Use --overwrite_output_dir to overcome."
361
+ )
362
+ elif last_checkpoint is not None:
363
+ logger.info(
364
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
365
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
366
+ )
367
+
368
+ # Setup logging
369
+ logging.basicConfig(
370
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
371
+ datefmt="%m/%d/%Y %H:%M:%S",
372
+ handlers=[logging.StreamHandler(sys.stdout)],
373
+ )
374
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
375
+
376
+ # Log on each process the small summary:
377
+ logger.warning(
378
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
379
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
380
+ )
381
+ # Set the verbosity to info of the Transformers logger (on main process only):
382
+ if is_main_process(training_args.local_rank):
383
+ transformers.utils.logging.set_verbosity_info()
384
+ logger.info("Training/evaluation parameters %s", training_args)
385
+
386
+ # Set seed before initializing model.
387
+ set_seed(training_args.seed)
388
+
389
+ # 1. First, let's load the dataset
390
+ raw_datasets = DatasetDict()
391
+
392
+ if training_args.do_train:
393
+ raw_datasets["train"] = load_dataset(
394
+ data_args.dataset_name,
395
+ data_args.dataset_config_name,
396
+ split=data_args.train_split_name,
397
+ use_auth_token=data_args.use_auth_token,
398
+ )
399
+
400
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
401
+ raise ValueError(
402
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
403
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
404
+ f"{', '.join(raw_datasets['train'].column_names)}."
405
+ )
406
+
407
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
408
+ raise ValueError(
409
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
410
+ "Make sure to set `--text_column_name` to the correct text column - one of "
411
+ f"{', '.join(raw_datasets['train'].column_names)}."
412
+ )
413
+
414
+ if data_args.max_train_samples is not None:
415
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
416
+
417
+ if training_args.do_eval:
418
+ raw_datasets["eval"] = load_dataset(
419
+ data_args.dataset_name,
420
+ data_args.dataset_config_name,
421
+ split=data_args.eval_split_name,
422
+ use_auth_token=data_args.use_auth_token,
423
+ )
424
+
425
+ if data_args.max_eval_samples is not None:
426
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
427
+
428
+ # 2. We remove some special characters from the datasets
429
+ # that make training complicated and do not help in transcribing the speech
430
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
431
+ # that could be easily picked up by the model
432
+ chars_to_ignore_regex = (
433
+ f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
434
+ )
435
+ text_column_name = data_args.text_column_name
436
+
437
+ def remove_special_characters(batch):
438
+ if chars_to_ignore_regex is not None:
439
+ batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
440
+ else:
441
+ batch["target_text"] = batch[text_column_name].lower() + " "
442
+ return batch
443
+
444
+ with training_args.main_process_first(desc="dataset map special characters removal"):
445
+ raw_datasets = raw_datasets.map(
446
+ remove_special_characters,
447
+ remove_columns=[text_column_name],
448
+ desc="remove special characters from datasets",
449
+ )
450
+
451
+ # save special tokens for tokenizer
452
+ word_delimiter_token = data_args.word_delimiter_token
453
+ unk_token = data_args.unk_token
454
+ pad_token = data_args.pad_token
455
+
456
+ # 3. Next, let's load the config as we might need it to create
457
+ # the tokenizer
458
+ # load config
459
+ config = AutoConfig.from_pretrained(
460
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
461
+ )
462
+
463
+ # 4. Next, if no tokenizer file is defined,
464
+ # we create the vocabulary of the model by extracting all unique characters from
465
+ # the training and evaluation datasets
466
+ # We need to make sure that only first rank saves vocabulary
467
+ # make sure all processes wait until vocab is created
468
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
469
+ tokenizer_kwargs = {}
470
+ if tokenizer_name_or_path is None:
471
+ # save vocab in training output dir
472
+ tokenizer_name_or_path = training_args.output_dir
473
+
474
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
475
+
476
+ with training_args.main_process_first():
477
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
478
+ os.remove(vocab_file)
479
+
480
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
481
+ if not os.path.isfile(vocab_file):
482
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
483
+ vocab_dict = create_vocabulary_from_data(
484
+ raw_datasets,
485
+ word_delimiter_token=word_delimiter_token,
486
+ unk_token=unk_token,
487
+ pad_token=pad_token,
488
+ )
489
+
490
+ # save vocab dict to be loaded into tokenizer
491
+ with open(vocab_file, "w") as file:
492
+ json.dump(vocab_dict, file)
493
+
494
+ # if tokenizer has just been created
495
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
496
+ tokenizer_kwargs = {
497
+ "config": config if config.tokenizer_class is not None else None,
498
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
499
+ "unk_token": unk_token,
500
+ "pad_token": pad_token,
501
+ "word_delimiter_token": word_delimiter_token,
502
+ }
503
+
504
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
505
+ # Note for distributed training, the .from_pretrained methods guarantee that only
506
+ # one local process can concurrently download model & vocab.
507
+
508
+ # load feature_extractor and tokenizer
509
+ tokenizer = AutoTokenizer.from_pretrained(
510
+ tokenizer_name_or_path,
511
+ use_auth_token=data_args.use_auth_token,
512
+ **tokenizer_kwargs,
513
+ )
514
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
515
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
516
+ )
517
+
518
+ # adapt config
519
+ config.update(
520
+ {
521
+ "feat_proj_dropout": model_args.feat_proj_dropout,
522
+ "attention_dropout": model_args.attention_dropout,
523
+ "hidden_dropout": model_args.hidden_dropout,
524
+ "final_dropout": model_args.final_dropout,
525
+ "mask_time_prob": model_args.mask_time_prob,
526
+ "mask_time_length": model_args.mask_time_length,
527
+ "mask_feature_prob": model_args.mask_feature_prob,
528
+ "mask_feature_length": model_args.mask_feature_length,
529
+ "gradient_checkpointing": training_args.gradient_checkpointing,
530
+ "layerdrop": model_args.layerdrop,
531
+ "ctc_loss_reduction": model_args.ctc_loss_reduction,
532
+ "pad_token_id": tokenizer.pad_token_id,
533
+ "vocab_size": len(tokenizer),
534
+ "activation_dropout": model_args.activation_dropout,
535
+ }
536
+ )
537
+
538
+ # create model
539
+ model = AutoModelForCTC.from_pretrained(
540
+ model_args.model_name_or_path,
541
+ cache_dir=model_args.cache_dir,
542
+ config=config,
543
+ use_auth_token=data_args.use_auth_token,
544
+ )
545
+
546
+ # freeze encoder
547
+ if model_args.freeze_feature_encoder:
548
+ model.freeze_feature_encoder()
549
+
550
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
551
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
552
+ # so that we just need to set the correct target sampling rate and normalize the input
553
+ # via the `feature_extractor`
554
+
555
+ # make sure that dataset decodes audio with correct sampling rate
556
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
557
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
558
+ raw_datasets = raw_datasets.cast_column(
559
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
560
+ )
561
+
562
+ # derive max & min input length for sample rate & max duration
563
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
564
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
565
+ audio_column_name = data_args.audio_column_name
566
+ num_workers = data_args.preprocessing_num_workers
567
+
568
+ # `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
569
+ phoneme_language = data_args.phoneme_language
570
+
571
+ # Preprocessing the datasets.
572
+ # We need to read the audio files as arrays and tokenize the targets.
573
+ def prepare_dataset(batch):
574
+ # load audio
575
+ sample = batch[audio_column_name]
576
+
577
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
578
+ batch["input_values"] = inputs.input_values[0]
579
+ batch["input_length"] = len(batch["input_values"])
580
+
581
+ # encode targets
582
+ additional_kwargs = {}
583
+ if phoneme_language is not None:
584
+ additional_kwargs["phonemizer_lang"] = phoneme_language
585
+
586
+ batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
587
+ return batch
588
+
589
+ with training_args.main_process_first(desc="dataset map preprocessing"):
590
+ vectorized_datasets = raw_datasets.map(
591
+ prepare_dataset,
592
+ remove_columns=next(iter(raw_datasets.values())).column_names,
593
+ num_proc=num_workers,
594
+ desc="preprocess datasets",
595
+ )
596
+
597
+ def is_audio_in_length_range(length):
598
+ return length > min_input_length and length < max_input_length
599
+
600
+ # filter data that is shorter than min_input_length
601
+ vectorized_datasets = vectorized_datasets.filter(
602
+ is_audio_in_length_range,
603
+ num_proc=num_workers,
604
+ input_columns=["input_length"],
605
+ )
606
+
607
+ # 7. Next, we can prepare the training.
608
+ # Let's use word error rate (WER) as our evaluation metric,
609
+ # instantiate a data collator and the trainer
610
+
611
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
612
+ eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}
613
+
614
+ # for large datasets it is advised to run the preprocessing on a
615
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
616
+ # be a timeout when running the script in distributed mode.
617
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
618
+ # cached dataset
619
+ if data_args.preprocessing_only:
620
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
621
+ return
622
+
623
+ def compute_metrics(pred):
624
+ pred_logits = pred.predictions
625
+ pred_ids = np.argmax(pred_logits, axis=-1)
626
+
627
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
628
+
629
+ pred_str = tokenizer.batch_decode(pred_ids)
630
+ # we do not want to group tokens when computing the metrics
631
+ label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
632
+
633
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
634
+
635
+ return metrics
636
+
637
+ # Now save everything to be able to create a single processor later
638
+ if is_main_process(training_args.local_rank):
639
+ # save feature extractor, tokenizer and config
640
+ feature_extractor.save_pretrained(training_args.output_dir)
641
+ tokenizer.save_pretrained(training_args.output_dir)
642
+ config.save_pretrained(training_args.output_dir)
643
+
644
+ try:
645
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
646
+ except (OSError, KeyError):
647
+ warnings.warn(
648
+ "Loading a processor from a feature extractor config that does not"
649
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
650
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
651
+ " `'processor_class': 'Wav2Vec2Processor'`",
652
+ FutureWarning,
653
+ )
654
+ processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
655
+
656
+ # Instantiate custom data collator
657
+ data_collator = DataCollatorCTCWithPadding(processor=processor)
658
+
659
+ decay_parameters = get_parameter_names(model, [torch.nn.LayerNorm])
660
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
661
+ optimizer_grouped_parameters = [
662
+ {
663
+ "params": [p for n, p in model.named_parameters() if n in decay_parameters],
664
+ "weight_decay": training_args.weight_decay,
665
+ },
666
+ {
667
+ "params": [p for n, p in model.named_parameters() if n not in decay_parameters],
668
+ "weight_decay": 0.0,
669
+ },
670
+ ]
671
+ optimizer = bnb.optim.Adam8bit(
672
+ params=optimizer_grouped_parameters,
673
+ lr=training_args.learning_rate,
674
+ betas=(training_args.adam_beta1, training_args.adam_beta2),
675
+ eps=training_args.adam_epsilon,
676
+ )
677
+
678
+ optimizers = (optimizer, None)
679
+
680
+ # Initialize Trainer
681
+ trainer = Trainer(
682
+ model=model,
683
+ data_collator=data_collator,
684
+ args=training_args,
685
+ compute_metrics=compute_metrics,
686
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
687
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
688
+ tokenizer=feature_extractor,
689
+ optimizers=optimizers,
690
+ )
691
+
692
+ # 8. Finally, we can start training
693
+
694
+ # Training
695
+ if training_args.do_train:
696
+
697
+ # use last checkpoint if exist
698
+ if last_checkpoint is not None:
699
+ checkpoint = last_checkpoint
700
+ elif os.path.isdir(model_args.model_name_or_path):
701
+ checkpoint = model_args.model_name_or_path
702
+ else:
703
+ checkpoint = None
704
+
705
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
706
+ trainer.save_model()
707
+
708
+ metrics = train_result.metrics
709
+ max_train_samples = (
710
+ data_args.max_train_samples
711
+ if data_args.max_train_samples is not None
712
+ else len(vectorized_datasets["train"])
713
+ )
714
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
715
+
716
+ trainer.log_metrics("train", metrics)
717
+ trainer.save_metrics("train", metrics)
718
+ trainer.save_state()
719
+
720
+ # Evaluation
721
+ results = {}
722
+ if training_args.do_eval:
723
+ logger.info("*** Evaluate ***")
724
+ metrics = trainer.evaluate()
725
+ max_eval_samples = (
726
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
727
+ )
728
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
729
+
730
+ trainer.log_metrics("eval", metrics)
731
+ trainer.save_metrics("eval", metrics)
732
+
733
+ # Write model card and (optionally) push to hub
734
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
735
+ kwargs = {
736
+ "finetuned_from": model_args.model_name_or_path,
737
+ "tasks": "speech-recognition",
738
+ "tags": ["automatic-speech-recognition", data_args.dataset_name],
739
+ "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
740
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
741
+ }
742
+ if "common_voice" in data_args.dataset_name:
743
+ kwargs["language"] = config_name
744
+
745
+ if training_args.push_to_hub:
746
+ trainer.push_to_hub(**kwargs)
747
+ else:
748
+ trainer.create_model_card(**kwargs)
749
+
750
+ return results
751
+
752
+
753
+ if __name__ == "__main__":
754
+ main()
trainer_state.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
- "best_metric": 0.4493387111903199,
3
- "best_model_checkpoint": "/workspace/cv-corpus-8.0-2022-01-19/output/checkpoint-1000",
4
  "epoch": 8.317338451695457,
5
  "global_step": 13000,
6
  "is_hyper_param_search": false,
1
  {
2
+ "best_metric": 0.18776850201669637,
3
+ "best_model_checkpoint": "/workspace/cv-corpus-8.0-2022-01-19/output/checkpoint-13000",
4
  "epoch": 8.317338451695457,
5
  "global_step": 13000,
6
  "is_hyper_param_search": false,