Adds README stuff, scripts, train config
Browse files- README.md +41 -9
- infer.py +108 -0
- run_speech_recognition_ctc.py +1157 -0
- train.json +46 -0
README.md
CHANGED
@@ -17,7 +17,7 @@ model-index:
|
|
17 |
name: Automatic Speech Recognition
|
18 |
type: automatic-speech-recognition
|
19 |
dataset:
|
20 |
-
name:
|
21 |
type: common_voice_13_0
|
22 |
config: eo
|
23 |
split: validation
|
@@ -26,33 +26,64 @@ model-index:
|
|
26 |
- name: Wer
|
27 |
type: wer
|
28 |
value: 0.05342994850125446
|
|
|
|
|
|
|
29 |
---
|
30 |
|
31 |
-
|
32 |
-
should probably proofread and complete it, then remove this comment. -->
|
33 |
|
34 |
-
|
35 |
-
|
36 |
-
This model is a fine-tuned version of [xekri/wav2vec2-common_voice_13_0-eo-10](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-10) on the MOZILLA-FOUNDATION/COMMON_VOICE_13_0 - EO dataset.
|
37 |
It achieves the following results on the evaluation set:
|
38 |
- Loss: 0.0391
|
39 |
- Cer: 0.0098
|
40 |
- Wer: 0.0534
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
## Model description
|
43 |
|
44 |
-
|
45 |
|
46 |
## Intended uses & limitations
|
47 |
|
48 |
-
|
|
|
|
|
49 |
|
50 |
## Training and evaluation data
|
51 |
|
52 |
-
|
53 |
|
54 |
## Training procedure
|
55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
### Training hyperparameters
|
57 |
|
58 |
The following hyperparameters were used during training:
|
@@ -62,6 +93,7 @@ The following hyperparameters were used during training:
|
|
62 |
- seed: 42
|
63 |
- gradient_accumulation_steps: 2
|
64 |
- total_train_batch_size: 32
|
|
|
65 |
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
66 |
- lr_scheduler_type: linear
|
67 |
- lr_scheduler_warmup_steps: 500
|
|
|
17 |
name: Automatic Speech Recognition
|
18 |
type: automatic-speech-recognition
|
19 |
dataset:
|
20 |
+
name: mozilla-foundation/common_voice_13_0
|
21 |
type: common_voice_13_0
|
22 |
config: eo
|
23 |
split: validation
|
|
|
26 |
- name: Wer
|
27 |
type: wer
|
28 |
value: 0.05342994850125446
|
29 |
+
- name: CER
|
30 |
+
type: cer
|
31 |
+
value: 0.0098
|
32 |
---
|
33 |
|
34 |
+
# wav2vec2-common_voice_13_0-eo-10_1, an Esperanto speech recognizer
|
|
|
35 |
|
36 |
+
This model is a fine-tuned version of [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53) on the [mozilla-foundation/common_voice_13_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_13_0) Esperanto dataset.
|
|
|
|
|
37 |
It achieves the following results on the evaluation set:
|
38 |
- Loss: 0.0391
|
39 |
- Cer: 0.0098
|
40 |
- Wer: 0.0534
|
41 |
|
42 |
+
The first 10 examples in the evaluation set:
|
43 |
+
|
44 |
+
| Actual<br>Predicted | CER |
|
45 |
+
|:--------------------|:----|
|
46 |
+
| `la orienta parto apud benino kaj niĝerio estis nomita sklavmarbordo`<br>`la orienta parto apud benino kaj niĝerio estis nomita sklafmarbordo` | 0.014925373134328358 |
|
47 |
+
| `en la sekva jaro li ricevis premion`<br>`en la sekva jaro li ricevis premion` | 0.0 |
|
48 |
+
| `ŝi studis historion ĉe la universitato de brita kolumbio`<br>`ŝi studis historion ĉe la universitato de brita kolumbio` | 0.0 |
|
49 |
+
| `larĝaj ŝtupoj kuras al la fasado`<br>`larĝaj ŝtupoj kuras al la fasado` | 0.0 |
|
50 |
+
| `la municipo ĝuas duan epokon de etendo kaj disvolviĝo`<br>`la municipo ĝuas duan epokon de etendo kaj disvolviĝo` | 0.0 |
|
51 |
+
| `li estis ankaŭ katedrestro kaj dekano`<br>`li estis ankaŭ katedresto kaj dekano` | 0.02702702702702703 |
|
52 |
+
| `librovendejo apartenas al la muzeo`<br>`librovendejo apartenas al l muzeo` | 0.029411764705882353 |
|
53 |
+
| `ĝi estas kutime malfacile videbla kaj troviĝas en subkreskaĵaro de arbaroj`<br>`ĝi estas kutime malfacile videbla kaj troviĝas en subkreskaĵo de arbaroj` | 0.02702702702702703 |
|
54 |
+
| `unue ili estas ruĝaj poste brunaj`<br>`unue ili estas ruĝaj poste brunaj` | 0.0 |
|
55 |
+
| `la loĝantaro laboras en la proksima ĉefurbo`<br>`la loĝantaro laboras en la proksima ĉefurbo` | 0.0 |
|
56 |
+
|
57 |
+
The differences in results for the above compared to the previous model ([xekri/wav2vec2-common_voice_13_0-eo-10](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-10)) are:
|
58 |
+
* eepokon -> epokon
|
59 |
+
* katedristo -> katedresto
|
60 |
+
* al la muzeo -> al l muzeo
|
61 |
+
|
62 |
## Model description
|
63 |
|
64 |
+
See [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53). This model is a version of [xekri/wav2vec2-common_voice_13_0-eo-10](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-10) trained for 5 more epochs.
|
65 |
|
66 |
## Intended uses & limitations
|
67 |
|
68 |
+
Speech recognition for Esperanto. The base model was pretrained and finetuned on 16kHz sampled speech audio. When using the model make sure that your speech input is also sampled at 16KHz.
|
69 |
+
|
70 |
+
The output is all lowercase, no punctuation.
|
71 |
|
72 |
## Training and evaluation data
|
73 |
|
74 |
+
The training split was set to `train` while the eval split was set to `validation`. Some files were filtered out of the train and validation dataset due to bad data; see [xekri/wav2vec2-common_voice_13_0-eo-3](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-3) for a detailed discussion. In summary, I used `xekri/wav2vec2-common_voice_13_0-eo-3` as a detector to detect bad files, then hardcoded those files into the trainer code to be filtered out.
|
75 |
|
76 |
## Training procedure
|
77 |
|
78 |
+
I used a modified version of [`run_speech_recognition_ctc.py`](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition) for training. See [`run_speech_recognition_ctc.py`](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-10/blob/main/run_speech_recognition_ctc.py) in this repo.
|
79 |
+
|
80 |
+
The parameters to the trainer are in [train.json](https://huggingface.co/xekri/wav2vec2-common_voice_13_0-eo-10/blob/main/train.json) in this repo.
|
81 |
+
|
82 |
+
The key changes between this training run and `xekri/wav2vec2-common_voice_13_0-eo-3`, aside from the filtering and use of the full training and validation sets are:
|
83 |
+
|
84 |
+
* Layer drop probability is 20%
|
85 |
+
* Train only for 5 epochs
|
86 |
+
|
87 |
### Training hyperparameters
|
88 |
|
89 |
The following hyperparameters were used during training:
|
|
|
93 |
- seed: 42
|
94 |
- gradient_accumulation_steps: 2
|
95 |
- total_train_batch_size: 32
|
96 |
+
- layerdrop: 0.2
|
97 |
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
98 |
- lr_scheduler_type: linear
|
99 |
- lr_scheduler_warmup_steps: 500
|
infer.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
import os
|
3 |
+
import os.path
|
4 |
+
import re
|
5 |
+
|
6 |
+
from datasets import load_dataset
|
7 |
+
from datasets import Audio
|
8 |
+
import jiwer
|
9 |
+
import torch
|
10 |
+
from transformers import AutoProcessor, Wav2Vec2ForCTC
|
11 |
+
from transformers.models.wav2vec2.processing_wav2vec2 import Wav2Vec2Processor
|
12 |
+
|
13 |
+
MODEL = "xekri/wav2vec2-common_voice_13_0-eo-10_1"
|
14 |
+
DATA = "validation[:10]"
|
15 |
+
|
16 |
+
chars_to_ignore_regex = "[-!\"'(),.:;=?_`¨«¸»ʼ‑–—‘’“”„…‹›♫?]"
|
17 |
+
chars_to_substitute = {
|
18 |
+
"przy": "pŝe",
|
19 |
+
"byn": "bin",
|
20 |
+
"cx": "ĉ",
|
21 |
+
"sx": "ŝ",
|
22 |
+
"fi": "fi",
|
23 |
+
"fl": "fl",
|
24 |
+
"ǔ": "ŭ",
|
25 |
+
"ñ": "nj",
|
26 |
+
"á": "a",
|
27 |
+
"é": "e",
|
28 |
+
"ü": "ŭ",
|
29 |
+
"y": "j",
|
30 |
+
"qu": "ku",
|
31 |
+
}
|
32 |
+
|
33 |
+
|
34 |
+
def remove_special_characters(text: str) -> str:
|
35 |
+
text = re.sub(chars_to_ignore_regex, "", text)
|
36 |
+
text = text.lower()
|
37 |
+
return text
|
38 |
+
|
39 |
+
|
40 |
+
def substitute_characters(text: str) -> str:
|
41 |
+
for k, v in chars_to_substitute.items():
|
42 |
+
text.replace(k, v)
|
43 |
+
text = text.lower()
|
44 |
+
return text
|
45 |
+
|
46 |
+
|
47 |
+
@dataclasses.dataclass
|
48 |
+
class EvalResult:
|
49 |
+
filename: str
|
50 |
+
cer: float
|
51 |
+
loss: float
|
52 |
+
actual: str
|
53 |
+
predicted: str
|
54 |
+
|
55 |
+
def print(self) -> None:
|
56 |
+
print(f"FILE {self.filename}")
|
57 |
+
print(f"CERR {self.cer}")
|
58 |
+
print(f"LOSS {self.loss}")
|
59 |
+
print(f"ACTU {self.actual}")
|
60 |
+
print(f"PRED {self.predicted}")
|
61 |
+
|
62 |
+
|
63 |
+
def evaluate(processor: Wav2Vec2Processor, model, example) -> EvalResult:
|
64 |
+
"""Evaluates a single example."""
|
65 |
+
audio_file = example["path"]
|
66 |
+
d, n = os.path.split(audio_file)
|
67 |
+
f = os.listdir(d)[0]
|
68 |
+
audio_file = os.path.join(d, f, n)
|
69 |
+
|
70 |
+
inputs = processor(
|
71 |
+
audio=example["audio"]["array"], sampling_rate=16000, return_tensors="pt"
|
72 |
+
)
|
73 |
+
|
74 |
+
with torch.no_grad():
|
75 |
+
logits = model(**inputs).logits
|
76 |
+
predicted_ids = logits.argmax(dim=-1)
|
77 |
+
predict = processor.batch_decode(predicted_ids)[0]
|
78 |
+
|
79 |
+
actual = example["sentence"]
|
80 |
+
actual = substitute_characters(remove_special_characters(actual))
|
81 |
+
inputs["labels"] = processor(text=actual, return_tensors="pt").input_ids
|
82 |
+
loss = model(**inputs).loss
|
83 |
+
cer = jiwer.cer(actual, predict)
|
84 |
+
|
85 |
+
return EvalResult(os.path.basename(audio_file), cer, loss, actual, predict)
|
86 |
+
|
87 |
+
|
88 |
+
def run() -> None:
|
89 |
+
cv13 = load_dataset(
|
90 |
+
"mozilla-foundation/common_voice_13_0",
|
91 |
+
"eo",
|
92 |
+
split=DATA,
|
93 |
+
)
|
94 |
+
cv13 = cv13.cast_column("audio", Audio(sampling_rate=16000))
|
95 |
+
|
96 |
+
processor: Wav2Vec2Processor = AutoProcessor.from_pretrained(MODEL)
|
97 |
+
model = Wav2Vec2ForCTC.from_pretrained(MODEL)
|
98 |
+
|
99 |
+
print("| Actual<br>Predicted | CER |")
|
100 |
+
print("|:--------------------|:----|")
|
101 |
+
|
102 |
+
for i, example in enumerate(cv13):
|
103 |
+
results = evaluate(processor, model, example)
|
104 |
+
print(f"| `{results.actual}`<br>`{results.predicted}` | {results.cer} |")
|
105 |
+
|
106 |
+
|
107 |
+
if __name__ == "__main__":
|
108 |
+
run()
|
run_speech_recognition_ctc.py
ADDED
@@ -0,0 +1,1157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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# limitations under the License.
|
16 |
+
|
17 |
+
""" Fine-tuning a 🤗 Transformers CTC model for automatic speech recognition"""
|
18 |
+
|
19 |
+
import functools
|
20 |
+
import json
|
21 |
+
import logging
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
import sys
|
25 |
+
import warnings
|
26 |
+
from dataclasses import dataclass, field
|
27 |
+
from typing import Any, Dict, List, Optional, Union
|
28 |
+
|
29 |
+
import datasets
|
30 |
+
import evaluate
|
31 |
+
import numpy as np
|
32 |
+
import torch
|
33 |
+
from datasets import DatasetDict, load_dataset
|
34 |
+
|
35 |
+
import transformers
|
36 |
+
from transformers import (
|
37 |
+
AutoConfig,
|
38 |
+
AutoFeatureExtractor,
|
39 |
+
AutoModelForCTC,
|
40 |
+
AutoProcessor,
|
41 |
+
AutoTokenizer,
|
42 |
+
HfArgumentParser,
|
43 |
+
Trainer,
|
44 |
+
TrainingArguments,
|
45 |
+
Wav2Vec2Processor,
|
46 |
+
set_seed,
|
47 |
+
)
|
48 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
49 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
50 |
+
from transformers.utils.versions import require_version
|
51 |
+
|
52 |
+
|
53 |
+
_BAD_TEST_FILES = [
|
54 |
+
"common_voice_eo_25214319.mp3",
|
55 |
+
"common_voice_eo_25006596.mp3",
|
56 |
+
"common_voice_eo_27472721.mp3",
|
57 |
+
"common_voice_eo_27715088.mp3",
|
58 |
+
"common_voice_eo_27715091.mp3",
|
59 |
+
"common_voice_eo_26677019.mp3",
|
60 |
+
"common_voice_eo_26677023.mp3",
|
61 |
+
"common_voice_eo_20555291.mp3",
|
62 |
+
"common_voice_eo_25001942.mp3",
|
63 |
+
"common_voice_eo_25457354.mp3",
|
64 |
+
"common_voice_eo_25457355.mp3",
|
65 |
+
"common_voice_eo_25457365.mp3",
|
66 |
+
"common_voice_eo_25457373.mp3",
|
67 |
+
"common_voice_eo_25457396.mp3",
|
68 |
+
"common_voice_eo_25457397.mp3",
|
69 |
+
"common_voice_eo_25457409.mp3",
|
70 |
+
"common_voice_eo_25457410.mp3",
|
71 |
+
"common_voice_eo_25457412.mp3",
|
72 |
+
"common_voice_eo_25457442.mp3",
|
73 |
+
"common_voice_eo_25457444.mp3",
|
74 |
+
"common_voice_eo_25457445.mp3",
|
75 |
+
"common_voice_eo_25457577.mp3",
|
76 |
+
"common_voice_eo_25457578.mp3",
|
77 |
+
"common_voice_eo_28064453.mp3",
|
78 |
+
"common_voice_eo_25047803.mp3",
|
79 |
+
"common_voice_eo_25048418.mp3",
|
80 |
+
"common_voice_eo_25048419.mp3",
|
81 |
+
"common_voice_eo_25048421.mp3",
|
82 |
+
"common_voice_eo_25048423.mp3",
|
83 |
+
"common_voice_eo_25048428.mp3",
|
84 |
+
"common_voice_eo_25048574.mp3",
|
85 |
+
"common_voice_eo_25885643.mp3",
|
86 |
+
"common_voice_eo_25885645.mp3",
|
87 |
+
"common_voice_eo_26794882.mp3",
|
88 |
+
"common_voice_eo_27356529.mp3",
|
89 |
+
"common_voice_eo_25012640.mp3",
|
90 |
+
"common_voice_eo_25303457.mp3",
|
91 |
+
"common_voice_eo_18153931.mp3",
|
92 |
+
"common_voice_eo_18776206.mp3",
|
93 |
+
"common_voice_eo_18776208.mp3",
|
94 |
+
"common_voice_eo_18776219.mp3",
|
95 |
+
"common_voice_eo_18776220.mp3",
|
96 |
+
"common_voice_eo_18776222.mp3",
|
97 |
+
"common_voice_eo_18776223.mp3",
|
98 |
+
"common_voice_eo_18776236.mp3",
|
99 |
+
"common_voice_eo_18776238.mp3",
|
100 |
+
"common_voice_eo_18776244.mp3",
|
101 |
+
"common_voice_eo_18776248.mp3",
|
102 |
+
"common_voice_eo_18776285.mp3",
|
103 |
+
"common_voice_eo_18776287.mp3",
|
104 |
+
"common_voice_eo_18776297.mp3",
|
105 |
+
"common_voice_eo_18776298.mp3",
|
106 |
+
"common_voice_eo_25047998.mp3",
|
107 |
+
"common_voice_eo_25047999.mp3",
|
108 |
+
"common_voice_eo_25048000.mp3",
|
109 |
+
"common_voice_eo_25048001.mp3",
|
110 |
+
"common_voice_eo_25048002.mp3",
|
111 |
+
"common_voice_eo_25053113.mp3",
|
112 |
+
"common_voice_eo_25068355.mp3",
|
113 |
+
"common_voice_eo_25333056.mp3",
|
114 |
+
"common_voice_eo_25371639.mp3",
|
115 |
+
"common_voice_eo_25371640.mp3",
|
116 |
+
"common_voice_eo_25371641.mp3",
|
117 |
+
"common_voice_eo_25371642.mp3",
|
118 |
+
"common_voice_eo_25371643.mp3",
|
119 |
+
"common_voice_eo_22441946.mp3",
|
120 |
+
"common_voice_eo_26622121.mp3",
|
121 |
+
"common_voice_eo_25167318.mp3",
|
122 |
+
"common_voice_eo_25252685.mp3",
|
123 |
+
"common_voice_eo_25252698.mp3",
|
124 |
+
"common_voice_eo_25518636.mp3",
|
125 |
+
]
|
126 |
+
|
127 |
+
_BAD_VALIDATION_FILES = [
|
128 |
+
"common_voice_eo_25392669.mp3",
|
129 |
+
"common_voice_eo_25392674.mp3",
|
130 |
+
"common_voice_eo_25392675.mp3",
|
131 |
+
"common_voice_eo_25392676.mp3",
|
132 |
+
"common_voice_eo_25392678.mp3",
|
133 |
+
"common_voice_eo_25392693.mp3",
|
134 |
+
"common_voice_eo_25392694.mp3",
|
135 |
+
"common_voice_eo_25392695.mp3",
|
136 |
+
"common_voice_eo_25392697.mp3",
|
137 |
+
"common_voice_eo_25392701.mp3",
|
138 |
+
"common_voice_eo_25392702.mp3",
|
139 |
+
"common_voice_eo_25392708.mp3",
|
140 |
+
"common_voice_eo_25392709.mp3",
|
141 |
+
"common_voice_eo_25408881.mp3",
|
142 |
+
"common_voice_eo_25408882.mp3",
|
143 |
+
"common_voice_eo_25408885.mp3",
|
144 |
+
"common_voice_eo_27380623.mp3",
|
145 |
+
]
|
146 |
+
|
147 |
+
_BAD_TRAIN_FILES = [
|
148 |
+
"common_voice_eo_25365027.mp3",
|
149 |
+
"common_voice_eo_25365472.mp3",
|
150 |
+
"common_voice_eo_25365480.mp3",
|
151 |
+
"common_voice_eo_25365532.mp3",
|
152 |
+
"common_voice_eo_25365695.mp3",
|
153 |
+
"common_voice_eo_25365744.mp3",
|
154 |
+
"common_voice_eo_25365804.mp3",
|
155 |
+
"common_voice_eo_25365836.mp3",
|
156 |
+
"common_voice_eo_25365855.mp3",
|
157 |
+
"common_voice_eo_25372587.mp3",
|
158 |
+
"common_voice_eo_25401060.mp3",
|
159 |
+
"common_voice_eo_25430837.mp3",
|
160 |
+
"common_voice_eo_25444509.mp3",
|
161 |
+
"common_voice_eo_25240777.mp3",
|
162 |
+
"common_voice_eo_24942754.mp3",
|
163 |
+
"common_voice_eo_24942755.mp3",
|
164 |
+
"common_voice_eo_24990372.mp3",
|
165 |
+
"common_voice_eo_24990385.mp3",
|
166 |
+
"common_voice_eo_24990390.mp3",
|
167 |
+
"common_voice_eo_24990397.mp3",
|
168 |
+
"common_voice_eo_24990413.mp3",
|
169 |
+
"common_voice_eo_24990427.mp3",
|
170 |
+
"common_voice_eo_24990429.mp3",
|
171 |
+
"common_voice_eo_24990435.mp3",
|
172 |
+
"common_voice_eo_24990441.mp3",
|
173 |
+
"common_voice_eo_24990454.mp3",
|
174 |
+
"common_voice_eo_24990457.mp3",
|
175 |
+
"common_voice_eo_24990459.mp3",
|
176 |
+
"common_voice_eo_24990490.mp3",
|
177 |
+
"common_voice_eo_25529345.mp3",
|
178 |
+
"common_voice_eo_25648750.mp3",
|
179 |
+
"common_voice_eo_28670472.mp3",
|
180 |
+
"common_voice_eo_27931966.mp3",
|
181 |
+
"common_voice_eo_28252265.mp3",
|
182 |
+
"common_voice_eo_25454951.mp3",
|
183 |
+
"common_voice_eo_25927616.mp3",
|
184 |
+
"common_voice_eo_25153203.mp3",
|
185 |
+
"common_voice_eo_25238543.mp3",
|
186 |
+
"common_voice_eo_25284237.mp3",
|
187 |
+
"common_voice_eo_25460131.mp3",
|
188 |
+
"common_voice_eo_25460185.mp3",
|
189 |
+
"common_voice_eo_25460186.mp3",
|
190 |
+
"common_voice_eo_25460188.mp3",
|
191 |
+
"common_voice_eo_25460189.mp3",
|
192 |
+
"common_voice_eo_25446723.mp3",
|
193 |
+
"common_voice_eo_26025150.mp3",
|
194 |
+
"common_voice_eo_26640189.mp3",
|
195 |
+
"common_voice_eo_26888468.mp3",
|
196 |
+
"common_voice_eo_24844824.mp3",
|
197 |
+
"common_voice_eo_25022506.mp3",
|
198 |
+
"common_voice_eo_25022507.mp3",
|
199 |
+
"common_voice_eo_25022516.mp3",
|
200 |
+
"common_voice_eo_25032858.mp3",
|
201 |
+
"common_voice_eo_25032859.mp3",
|
202 |
+
"common_voice_eo_25032865.mp3",
|
203 |
+
"common_voice_eo_25243988.mp3",
|
204 |
+
"common_voice_eo_25244009.mp3",
|
205 |
+
"common_voice_eo_25266094.mp3",
|
206 |
+
"common_voice_eo_25266141.mp3",
|
207 |
+
"common_voice_eo_25285278.mp3",
|
208 |
+
"common_voice_eo_25286768.mp3",
|
209 |
+
"common_voice_eo_25457171.mp3",
|
210 |
+
"common_voice_eo_25467641.mp3",
|
211 |
+
"common_voice_eo_25467723.mp3",
|
212 |
+
"common_voice_eo_25467791.mp3",
|
213 |
+
"common_voice_eo_25467820.mp3",
|
214 |
+
"common_voice_eo_25467943.mp3",
|
215 |
+
"common_voice_eo_25478612.mp3",
|
216 |
+
"common_voice_eo_25478623.mp3",
|
217 |
+
"common_voice_eo_25478631.mp3",
|
218 |
+
"common_voice_eo_25478756.mp3",
|
219 |
+
"common_voice_eo_25478762.mp3",
|
220 |
+
"common_voice_eo_25478768.mp3",
|
221 |
+
"common_voice_eo_25478769.mp3",
|
222 |
+
"common_voice_eo_25479150.mp3",
|
223 |
+
"common_voice_eo_25479203.mp3",
|
224 |
+
"common_voice_eo_25479229.mp3",
|
225 |
+
"common_voice_eo_25517673.mp3",
|
226 |
+
"common_voice_eo_25517677.mp3",
|
227 |
+
"common_voice_eo_25527739.mp3",
|
228 |
+
"common_voice_eo_25975149.mp3",
|
229 |
+
"common_voice_eo_26193748.mp3",
|
230 |
+
"common_voice_eo_28401039.mp3",
|
231 |
+
"common_voice_eo_28421315.mp3",
|
232 |
+
"common_voice_eo_28937347.mp3",
|
233 |
+
"common_voice_eo_24890414.mp3",
|
234 |
+
"common_voice_eo_25294479.mp3",
|
235 |
+
"common_voice_eo_25438966.mp3",
|
236 |
+
"common_voice_eo_28855568.mp3",
|
237 |
+
"common_voice_eo_29011007.mp3",
|
238 |
+
"common_voice_eo_24599888.mp3",
|
239 |
+
"common_voice_eo_26964252.mp3",
|
240 |
+
"common_voice_eo_26964496.mp3",
|
241 |
+
"common_voice_eo_26964510.mp3",
|
242 |
+
"common_voice_eo_25432789.mp3",
|
243 |
+
"common_voice_eo_26688158.mp3",
|
244 |
+
"common_voice_eo_28516354.mp3",
|
245 |
+
"common_voice_eo_24790865.mp3",
|
246 |
+
"common_voice_eo_24790897.mp3",
|
247 |
+
"common_voice_eo_24790898.mp3",
|
248 |
+
"common_voice_eo_24790899.mp3",
|
249 |
+
"common_voice_eo_24790900.mp3",
|
250 |
+
"common_voice_eo_25362713.mp3",
|
251 |
+
"common_voice_eo_27585084.mp3",
|
252 |
+
"common_voice_eo_24813131.mp3",
|
253 |
+
"common_voice_eo_25035262.mp3",
|
254 |
+
"common_voice_eo_26000289.mp3",
|
255 |
+
"common_voice_eo_26003943.mp3",
|
256 |
+
"common_voice_eo_26283983.mp3",
|
257 |
+
"common_voice_eo_28708931.mp3",
|
258 |
+
"common_voice_eo_28037217.mp3",
|
259 |
+
"common_voice_eo_29273106.mp3",
|
260 |
+
"common_voice_eo_26006657.mp3",
|
261 |
+
"common_voice_eo_25399924.mp3",
|
262 |
+
"common_voice_eo_27982431.mp3",
|
263 |
+
"common_voice_eo_25893779.mp3",
|
264 |
+
"common_voice_eo_27842061.mp3",
|
265 |
+
"common_voice_eo_25052385.mp3",
|
266 |
+
"common_voice_eo_25807395.mp3",
|
267 |
+
"common_voice_eo_25807985.mp3",
|
268 |
+
"common_voice_eo_25808039.mp3",
|
269 |
+
"common_voice_eo_25808407.mp3",
|
270 |
+
"common_voice_eo_25809036.mp3",
|
271 |
+
"common_voice_eo_27487795.mp3",
|
272 |
+
"common_voice_eo_28460556.mp3",
|
273 |
+
"common_voice_eo_28884851.mp3",
|
274 |
+
"common_voice_eo_24819719.mp3",
|
275 |
+
"common_voice_eo_25153594.mp3",
|
276 |
+
"common_voice_eo_25234585.mp3",
|
277 |
+
"common_voice_eo_25245164.mp3",
|
278 |
+
"common_voice_eo_27538877.mp3",
|
279 |
+
"common_voice_eo_24862771.mp3",
|
280 |
+
"common_voice_eo_25070167.mp3",
|
281 |
+
"common_voice_eo_26381720.mp3",
|
282 |
+
"common_voice_eo_28110376.mp3",
|
283 |
+
]
|
284 |
+
|
285 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
286 |
+
# check_min_version("4.29.0.dev0")
|
287 |
+
|
288 |
+
require_version(
|
289 |
+
"datasets>=1.18.0",
|
290 |
+
"To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt",
|
291 |
+
)
|
292 |
+
|
293 |
+
|
294 |
+
logger = logging.getLogger(__name__)
|
295 |
+
|
296 |
+
|
297 |
+
def list_field(default=None, metadata=None):
|
298 |
+
return field(default_factory=lambda: default, metadata=metadata)
|
299 |
+
|
300 |
+
|
301 |
+
def dict_field(default=None, metadata=None):
|
302 |
+
return field(default_factory=lambda: default, metadata=metadata)
|
303 |
+
|
304 |
+
|
305 |
+
@dataclass
|
306 |
+
class ModelArguments:
|
307 |
+
"""
|
308 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
309 |
+
"""
|
310 |
+
|
311 |
+
model_name_or_path: str = field(
|
312 |
+
metadata={
|
313 |
+
"help": "Path to pretrained model or model identifier from huggingface.co/models"
|
314 |
+
}
|
315 |
+
)
|
316 |
+
tokenizer_name_or_path: Optional[str] = field(
|
317 |
+
default=None,
|
318 |
+
metadata={
|
319 |
+
"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"
|
320 |
+
},
|
321 |
+
)
|
322 |
+
cache_dir: Optional[str] = field(
|
323 |
+
default=None,
|
324 |
+
metadata={
|
325 |
+
"help": "Where do you want to store the pretrained models downloaded from huggingface.co"
|
326 |
+
},
|
327 |
+
)
|
328 |
+
freeze_feature_encoder: bool = field(
|
329 |
+
default=True,
|
330 |
+
metadata={"help": "Whether to freeze the feature encoder layers of the model."},
|
331 |
+
)
|
332 |
+
attention_dropout: float = field(
|
333 |
+
default=0.0,
|
334 |
+
metadata={"help": "The dropout ratio for the attention probabilities."},
|
335 |
+
)
|
336 |
+
activation_dropout: float = field(
|
337 |
+
default=0.0,
|
338 |
+
metadata={
|
339 |
+
"help": "The dropout ratio for activations inside the fully connected layer."
|
340 |
+
},
|
341 |
+
)
|
342 |
+
feat_proj_dropout: float = field(
|
343 |
+
default=0.0, metadata={"help": "The dropout ratio for the projected features."}
|
344 |
+
)
|
345 |
+
hidden_dropout: float = field(
|
346 |
+
default=0.0,
|
347 |
+
metadata={
|
348 |
+
"help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
|
349 |
+
},
|
350 |
+
)
|
351 |
+
final_dropout: float = field(
|
352 |
+
default=0.0,
|
353 |
+
metadata={"help": "The dropout probability for the final projection layer."},
|
354 |
+
)
|
355 |
+
mask_time_prob: float = field(
|
356 |
+
default=0.05,
|
357 |
+
metadata={
|
358 |
+
"help": (
|
359 |
+
"Probability of each feature vector along the time axis to be chosen as the start of the vector"
|
360 |
+
"span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
|
361 |
+
"vectors will be masked along the time axis."
|
362 |
+
)
|
363 |
+
},
|
364 |
+
)
|
365 |
+
mask_time_length: int = field(
|
366 |
+
default=10,
|
367 |
+
metadata={"help": "Length of vector span to mask along the time axis."},
|
368 |
+
)
|
369 |
+
mask_feature_prob: float = field(
|
370 |
+
default=0.0,
|
371 |
+
metadata={
|
372 |
+
"help": (
|
373 |
+
"Probability of each feature vector along the feature axis to be chosen as the start of the vectorspan"
|
374 |
+
" to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature"
|
375 |
+
" bins will be masked along the time axis."
|
376 |
+
)
|
377 |
+
},
|
378 |
+
)
|
379 |
+
mask_feature_length: int = field(
|
380 |
+
default=10,
|
381 |
+
metadata={"help": "Length of vector span to mask along the feature axis."},
|
382 |
+
)
|
383 |
+
layerdrop: float = field(
|
384 |
+
default=0.0, metadata={"help": "The LayerDrop probability."}
|
385 |
+
)
|
386 |
+
ctc_loss_reduction: Optional[str] = field(
|
387 |
+
default="mean",
|
388 |
+
metadata={
|
389 |
+
"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."
|
390 |
+
},
|
391 |
+
)
|
392 |
+
|
393 |
+
|
394 |
+
@dataclass
|
395 |
+
class DataTrainingArguments:
|
396 |
+
"""
|
397 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
398 |
+
|
399 |
+
Using `HfArgumentParser` we can turn this class
|
400 |
+
into argparse arguments to be able to specify them on
|
401 |
+
the command line.
|
402 |
+
"""
|
403 |
+
|
404 |
+
dataset_name: str = field(
|
405 |
+
metadata={
|
406 |
+
"help": "The configuration name of the dataset to use (via the datasets library)."
|
407 |
+
}
|
408 |
+
)
|
409 |
+
dataset_config_name: str = field(
|
410 |
+
default=None,
|
411 |
+
metadata={
|
412 |
+
"help": "The configuration name of the dataset to use (via the datasets library)."
|
413 |
+
},
|
414 |
+
)
|
415 |
+
train_split_name: str = field(
|
416 |
+
default="train+validation",
|
417 |
+
metadata={
|
418 |
+
"help": (
|
419 |
+
"The name of the training data set split to use (via the datasets library). Defaults to "
|
420 |
+
"'train+validation'"
|
421 |
+
)
|
422 |
+
},
|
423 |
+
)
|
424 |
+
eval_split_name: str = field(
|
425 |
+
default="test",
|
426 |
+
metadata={
|
427 |
+
"help": "The name of the evaluation data set split to use (via the datasets library). Defaults to 'test'"
|
428 |
+
},
|
429 |
+
)
|
430 |
+
audio_column_name: str = field(
|
431 |
+
default="audio",
|
432 |
+
metadata={
|
433 |
+
"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
|
434 |
+
},
|
435 |
+
)
|
436 |
+
text_column_name: str = field(
|
437 |
+
default="text",
|
438 |
+
metadata={
|
439 |
+
"help": "The name of the dataset column containing the text data. Defaults to 'text'"
|
440 |
+
},
|
441 |
+
)
|
442 |
+
overwrite_cache: bool = field(
|
443 |
+
default=False,
|
444 |
+
metadata={"help": "Overwrite the cached preprocessed datasets or not."},
|
445 |
+
)
|
446 |
+
preprocessing_num_workers: Optional[int] = field(
|
447 |
+
default=None,
|
448 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
449 |
+
)
|
450 |
+
max_train_samples: Optional[int] = field(
|
451 |
+
default=None,
|
452 |
+
metadata={
|
453 |
+
"help": (
|
454 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
455 |
+
"value if set."
|
456 |
+
)
|
457 |
+
},
|
458 |
+
)
|
459 |
+
max_eval_samples: Optional[int] = field(
|
460 |
+
default=None,
|
461 |
+
metadata={
|
462 |
+
"help": (
|
463 |
+
"For debugging purposes or quicker training, truncate the number of validation examples to this "
|
464 |
+
"value if set."
|
465 |
+
)
|
466 |
+
},
|
467 |
+
)
|
468 |
+
chars_to_ignore: Optional[List[str]] = list_field(
|
469 |
+
default=None,
|
470 |
+
metadata={"help": "A list of characters to remove from the transcripts."},
|
471 |
+
)
|
472 |
+
chars_to_substitute: Optional[Dict[str, str]] = dict_field(
|
473 |
+
default=None,
|
474 |
+
metadata={"help": "A dict of characters to replace."},
|
475 |
+
)
|
476 |
+
eval_metrics: List[str] = list_field(
|
477 |
+
default=["wer"],
|
478 |
+
metadata={
|
479 |
+
"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"
|
480 |
+
},
|
481 |
+
)
|
482 |
+
max_duration_in_seconds: float = field(
|
483 |
+
default=20.0,
|
484 |
+
metadata={
|
485 |
+
"help": (
|
486 |
+
"Filter audio files that are longer than `max_duration_in_seconds` seconds to"
|
487 |
+
" 'max_duration_in_seconds`"
|
488 |
+
)
|
489 |
+
},
|
490 |
+
)
|
491 |
+
min_duration_in_seconds: float = field(
|
492 |
+
default=0.0,
|
493 |
+
metadata={
|
494 |
+
"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"
|
495 |
+
},
|
496 |
+
)
|
497 |
+
preprocessing_only: bool = field(
|
498 |
+
default=False,
|
499 |
+
metadata={
|
500 |
+
"help": (
|
501 |
+
"Whether to only do data preprocessing and skip training. This is especially useful when data"
|
502 |
+
" preprocessing errors out in distributed training due to timeout. In this case, one should run the"
|
503 |
+
" preprocessing in a non-distributed setup with `preprocessing_only=True` so that the cached datasets"
|
504 |
+
" can consequently be loaded in distributed training"
|
505 |
+
)
|
506 |
+
},
|
507 |
+
)
|
508 |
+
use_auth_token: bool = field(
|
509 |
+
default=False,
|
510 |
+
metadata={
|
511 |
+
"help": (
|
512 |
+
"If :obj:`True`, will use the token generated when running"
|
513 |
+
":obj:`huggingface-cli login` as HTTP bearer authorization for remote files."
|
514 |
+
)
|
515 |
+
},
|
516 |
+
)
|
517 |
+
unk_token: str = field(
|
518 |
+
default="[UNK]",
|
519 |
+
metadata={"help": "The unk token for the tokenizer"},
|
520 |
+
)
|
521 |
+
pad_token: str = field(
|
522 |
+
default="[PAD]",
|
523 |
+
metadata={"help": "The padding token for the tokenizer"},
|
524 |
+
)
|
525 |
+
word_delimiter_token: str = field(
|
526 |
+
default="|",
|
527 |
+
metadata={"help": "The word delimiter token for the tokenizer"},
|
528 |
+
)
|
529 |
+
phoneme_language: Optional[str] = field(
|
530 |
+
default=None,
|
531 |
+
metadata={
|
532 |
+
"help": (
|
533 |
+
"The target language that should be used be"
|
534 |
+
" passed to the tokenizer for tokenization. Note that"
|
535 |
+
" this is only relevant if the model classifies the"
|
536 |
+
" input audio to a sequence of phoneme sequences."
|
537 |
+
)
|
538 |
+
},
|
539 |
+
)
|
540 |
+
|
541 |
+
|
542 |
+
@dataclass
|
543 |
+
class DataCollatorCTCWithPadding:
|
544 |
+
"""
|
545 |
+
Data collator that will dynamically pad the inputs received.
|
546 |
+
Args:
|
547 |
+
processor (:class:`~transformers.AutoProcessor`)
|
548 |
+
The processor used for proccessing the data.
|
549 |
+
padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
|
550 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
|
551 |
+
among:
|
552 |
+
* :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
553 |
+
sequence if provided).
|
554 |
+
* :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
|
555 |
+
maximum acceptable input length for the model if that argument is not provided.
|
556 |
+
* :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
|
557 |
+
different lengths).
|
558 |
+
max_length (:obj:`int`, `optional`):
|
559 |
+
Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
|
560 |
+
max_length_labels (:obj:`int`, `optional`):
|
561 |
+
Maximum length of the ``labels`` returned list and optionally padding length (see above).
|
562 |
+
pad_to_multiple_of (:obj:`int`, `optional`):
|
563 |
+
If set will pad the sequence to a multiple of the provided value.
|
564 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
|
565 |
+
7.5 (Volta).
|
566 |
+
"""
|
567 |
+
|
568 |
+
processor: Wav2Vec2Processor
|
569 |
+
padding: Union[bool, str] = "longest"
|
570 |
+
pad_to_multiple_of: Optional[int] = None
|
571 |
+
pad_to_multiple_of_labels: Optional[int] = None
|
572 |
+
|
573 |
+
def __call__(
|
574 |
+
self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
|
575 |
+
) -> Dict[str, torch.Tensor]:
|
576 |
+
# split inputs and labels since they have to be of different lenghts and need
|
577 |
+
# different padding methods
|
578 |
+
input_features = [
|
579 |
+
{"input_values": feature["input_values"]} for feature in features
|
580 |
+
]
|
581 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
582 |
+
|
583 |
+
batch = self.processor.pad(
|
584 |
+
input_features,
|
585 |
+
padding=self.padding,
|
586 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
587 |
+
return_tensors="pt",
|
588 |
+
)
|
589 |
+
|
590 |
+
labels_batch = self.processor.pad(
|
591 |
+
labels=label_features,
|
592 |
+
padding=self.padding,
|
593 |
+
pad_to_multiple_of=self.pad_to_multiple_of_labels,
|
594 |
+
return_tensors="pt",
|
595 |
+
)
|
596 |
+
|
597 |
+
# replace padding with -100 to ignore loss correctly
|
598 |
+
labels = labels_batch["input_ids"].masked_fill(
|
599 |
+
labels_batch.attention_mask.ne(1), -100
|
600 |
+
)
|
601 |
+
|
602 |
+
batch["labels"] = labels
|
603 |
+
if "attention_mask" in batch:
|
604 |
+
batch["attention_mask"] = batch["attention_mask"].to(torch.long)
|
605 |
+
|
606 |
+
return batch
|
607 |
+
|
608 |
+
|
609 |
+
def create_vocabulary_from_data(
|
610 |
+
vocab_datasets: DatasetDict,
|
611 |
+
word_delimiter_token: Optional[str] = None,
|
612 |
+
unk_token: Optional[str] = None,
|
613 |
+
pad_token: Optional[str] = None,
|
614 |
+
):
|
615 |
+
# Given training and test labels create vocabulary
|
616 |
+
def extract_all_chars(batch):
|
617 |
+
all_text = " ".join(batch["target_text"])
|
618 |
+
vocab = list(set(all_text))
|
619 |
+
return {"vocab": [vocab], "all_text": [all_text]}
|
620 |
+
|
621 |
+
vocabs = vocab_datasets.map(
|
622 |
+
extract_all_chars,
|
623 |
+
batched=True,
|
624 |
+
batch_size=-1,
|
625 |
+
keep_in_memory=True,
|
626 |
+
remove_columns=vocab_datasets["train"].column_names,
|
627 |
+
)
|
628 |
+
|
629 |
+
# take union of all unique characters in each dataset
|
630 |
+
vocab_set = functools.reduce(
|
631 |
+
lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]),
|
632 |
+
vocabs.values(),
|
633 |
+
)
|
634 |
+
|
635 |
+
vocab_dict = {v: k for k, v in enumerate(sorted(vocab_set))}
|
636 |
+
|
637 |
+
# replace white space with delimiter token
|
638 |
+
if word_delimiter_token is not None:
|
639 |
+
vocab_dict[word_delimiter_token] = vocab_dict[" "]
|
640 |
+
del vocab_dict[" "]
|
641 |
+
|
642 |
+
# add unk and pad token
|
643 |
+
if unk_token is not None:
|
644 |
+
vocab_dict[unk_token] = len(vocab_dict)
|
645 |
+
|
646 |
+
if pad_token is not None:
|
647 |
+
vocab_dict[pad_token] = len(vocab_dict)
|
648 |
+
|
649 |
+
return vocab_dict
|
650 |
+
|
651 |
+
|
652 |
+
def main():
|
653 |
+
# See all possible arguments in src/transformers/training_args.py
|
654 |
+
# or by passing the --help flag to this script.
|
655 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
656 |
+
|
657 |
+
parser = HfArgumentParser(
|
658 |
+
(ModelArguments, DataTrainingArguments, TrainingArguments)
|
659 |
+
)
|
660 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
661 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
662 |
+
# let's parse it to get our arguments.
|
663 |
+
model_args, data_args, training_args = parser.parse_json_file(
|
664 |
+
json_file=os.path.abspath(sys.argv[1])
|
665 |
+
)
|
666 |
+
else:
|
667 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
668 |
+
|
669 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
670 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
671 |
+
send_example_telemetry("run_speech_recognition_ctc", model_args, data_args)
|
672 |
+
|
673 |
+
# Setup logging
|
674 |
+
logging.basicConfig(
|
675 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
676 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
677 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
678 |
+
)
|
679 |
+
logger.setLevel(
|
680 |
+
logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
|
681 |
+
)
|
682 |
+
|
683 |
+
# Detecting last checkpoint.
|
684 |
+
last_checkpoint = None
|
685 |
+
if (
|
686 |
+
os.path.isdir(training_args.output_dir)
|
687 |
+
and training_args.do_train
|
688 |
+
and not training_args.overwrite_output_dir
|
689 |
+
):
|
690 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
691 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
692 |
+
raise ValueError(
|
693 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
694 |
+
"Use --overwrite_output_dir to overcome."
|
695 |
+
)
|
696 |
+
elif last_checkpoint is not None:
|
697 |
+
logger.info(
|
698 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
699 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
700 |
+
)
|
701 |
+
|
702 |
+
# Log on each process the small summary:
|
703 |
+
logger.warning(
|
704 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
705 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
706 |
+
)
|
707 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
708 |
+
if is_main_process(training_args.local_rank):
|
709 |
+
transformers.utils.logging.set_verbosity_info()
|
710 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
711 |
+
|
712 |
+
# Set seed before initializing model.
|
713 |
+
set_seed(training_args.seed)
|
714 |
+
|
715 |
+
# 1. First, let's load the dataset
|
716 |
+
print("======== STEP 1: load dataset")
|
717 |
+
raw_datasets = DatasetDict()
|
718 |
+
|
719 |
+
if training_args.do_train:
|
720 |
+
raw_datasets["train"] = load_dataset(
|
721 |
+
data_args.dataset_name,
|
722 |
+
data_args.dataset_config_name,
|
723 |
+
split=data_args.train_split_name,
|
724 |
+
use_auth_token=data_args.use_auth_token,
|
725 |
+
)
|
726 |
+
|
727 |
+
if data_args.audio_column_name not in raw_datasets["train"].column_names:
|
728 |
+
raise ValueError(
|
729 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'."
|
730 |
+
" Make sure to set `--audio_column_name` to the correct audio column - one of"
|
731 |
+
f" {', '.join(raw_datasets['train'].column_names)}."
|
732 |
+
)
|
733 |
+
|
734 |
+
if data_args.text_column_name not in raw_datasets["train"].column_names:
|
735 |
+
raise ValueError(
|
736 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
737 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
738 |
+
f"{', '.join(raw_datasets['train'].column_names)}."
|
739 |
+
)
|
740 |
+
|
741 |
+
if data_args.max_train_samples is not None:
|
742 |
+
raw_datasets["train"] = raw_datasets["train"].select(
|
743 |
+
range(data_args.max_train_samples)
|
744 |
+
)
|
745 |
+
|
746 |
+
if training_args.do_eval:
|
747 |
+
raw_datasets["eval"] = load_dataset(
|
748 |
+
data_args.dataset_name,
|
749 |
+
data_args.dataset_config_name,
|
750 |
+
split=data_args.eval_split_name,
|
751 |
+
use_auth_token=data_args.use_auth_token,
|
752 |
+
)
|
753 |
+
|
754 |
+
if data_args.max_eval_samples is not None:
|
755 |
+
raw_datasets["eval"] = raw_datasets["eval"].select(
|
756 |
+
range(data_args.max_eval_samples)
|
757 |
+
)
|
758 |
+
|
759 |
+
# 2. We remove some special characters from the datasets
|
760 |
+
# that make training complicated and do not help in transcribing the speech
|
761 |
+
# E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
|
762 |
+
# that could be easily picked up by the model
|
763 |
+
print("======== STEP 2: Massage characters")
|
764 |
+
chars_to_ignore_regex = (
|
765 |
+
f'[{"".join(data_args.chars_to_ignore)}]'
|
766 |
+
if data_args.chars_to_ignore is not None
|
767 |
+
else None
|
768 |
+
)
|
769 |
+
text_column_name = data_args.text_column_name
|
770 |
+
|
771 |
+
def remove_special_characters(batch):
|
772 |
+
text = batch[text_column_name]
|
773 |
+
if chars_to_ignore_regex is not None:
|
774 |
+
text = re.sub(chars_to_ignore_regex, "", batch[text_column_name])
|
775 |
+
batch["target_text"] = text.lower() + " "
|
776 |
+
return batch
|
777 |
+
|
778 |
+
def substitute_characters(batch):
|
779 |
+
text: str = batch["target_text"]
|
780 |
+
if data_args.chars_to_substitute is not None:
|
781 |
+
for k, v in data_args.chars_to_substitute.items():
|
782 |
+
text.replace(k, v)
|
783 |
+
batch["target_text"] = text.lower()
|
784 |
+
return batch
|
785 |
+
|
786 |
+
with training_args.main_process_first(
|
787 |
+
desc="dataset map special characters removal"
|
788 |
+
):
|
789 |
+
raw_datasets = raw_datasets.map(
|
790 |
+
remove_special_characters,
|
791 |
+
remove_columns=[text_column_name],
|
792 |
+
desc="remove special characters from datasets",
|
793 |
+
)
|
794 |
+
|
795 |
+
with training_args.main_process_first(
|
796 |
+
desc="dataset map special characters substitute"
|
797 |
+
):
|
798 |
+
raw_datasets = raw_datasets.map(
|
799 |
+
substitute_characters,
|
800 |
+
desc="substitute special characters in datasets",
|
801 |
+
)
|
802 |
+
|
803 |
+
# save special tokens for tokenizer
|
804 |
+
word_delimiter_token = data_args.word_delimiter_token
|
805 |
+
unk_token = data_args.unk_token
|
806 |
+
pad_token = data_args.pad_token
|
807 |
+
|
808 |
+
with training_args.main_process_first(
|
809 |
+
desc="filter out bad data"
|
810 |
+
):
|
811 |
+
def is_good_quality(path: str) -> bool:
|
812 |
+
filename = os.path.basename(path)
|
813 |
+
if filename in _BAD_TEST_FILES:
|
814 |
+
return False
|
815 |
+
if filename in _BAD_VALIDATION_FILES:
|
816 |
+
return False
|
817 |
+
if filename in _BAD_TRAIN_FILES:
|
818 |
+
return False
|
819 |
+
return True
|
820 |
+
|
821 |
+
# filter data that sucks
|
822 |
+
raw_datasets = raw_datasets.filter(
|
823 |
+
function=is_good_quality,
|
824 |
+
num_proc=data_args.preprocessing_num_workers,
|
825 |
+
input_columns=["path"]
|
826 |
+
)
|
827 |
+
|
828 |
+
# 3. Next, let's load the config as we might need it to create
|
829 |
+
# the tokenizer
|
830 |
+
# load config
|
831 |
+
print("======== STEP 3: load config")
|
832 |
+
config = AutoConfig.from_pretrained(
|
833 |
+
model_args.model_name_or_path,
|
834 |
+
cache_dir=model_args.cache_dir,
|
835 |
+
use_auth_token=data_args.use_auth_token,
|
836 |
+
)
|
837 |
+
|
838 |
+
# 4. Next, if no tokenizer file is defined,
|
839 |
+
# we create the vocabulary of the model by extracting all unique characters from
|
840 |
+
# the training and evaluation datasets
|
841 |
+
# We need to make sure that only first rank saves vocabulary
|
842 |
+
# make sure all processes wait until vocab is created
|
843 |
+
print("======== STEP 4: maybe create vocabulary")
|
844 |
+
tokenizer_name_or_path = model_args.tokenizer_name_or_path
|
845 |
+
tokenizer_kwargs = {}
|
846 |
+
if tokenizer_name_or_path is None:
|
847 |
+
# save vocab in training output dir
|
848 |
+
tokenizer_name_or_path = training_args.output_dir
|
849 |
+
|
850 |
+
vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
|
851 |
+
print(f"==== Saving tokenizer vocab to {vocab_file}")
|
852 |
+
|
853 |
+
with training_args.main_process_first():
|
854 |
+
if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
|
855 |
+
try:
|
856 |
+
os.remove(vocab_file)
|
857 |
+
print("Removed vocab_file")
|
858 |
+
except OSError:
|
859 |
+
# in shared file-systems it might be the case that
|
860 |
+
# two processes try to delete the vocab file at the some time
|
861 |
+
pass
|
862 |
+
|
863 |
+
with training_args.main_process_first(desc="dataset map vocabulary creation"):
|
864 |
+
if not os.path.isfile(vocab_file):
|
865 |
+
os.makedirs(tokenizer_name_or_path, exist_ok=True)
|
866 |
+
vocab_dict = create_vocabulary_from_data(
|
867 |
+
raw_datasets,
|
868 |
+
word_delimiter_token=word_delimiter_token,
|
869 |
+
unk_token=unk_token,
|
870 |
+
pad_token=pad_token,
|
871 |
+
)
|
872 |
+
|
873 |
+
# save vocab dict to be loaded into tokenizer
|
874 |
+
with open(vocab_file, "w") as file:
|
875 |
+
json.dump(vocab_dict, file)
|
876 |
+
print("Wrote vocab_file")
|
877 |
+
|
878 |
+
# if tokenizer has just been created
|
879 |
+
# it is defined by `tokenizer_class` if present in config else by `model_type`
|
880 |
+
tokenizer_kwargs = {
|
881 |
+
"config": config if config.tokenizer_class is not None else None,
|
882 |
+
"tokenizer_type": config.model_type
|
883 |
+
if config.tokenizer_class is None
|
884 |
+
else None,
|
885 |
+
"unk_token": unk_token,
|
886 |
+
"pad_token": pad_token,
|
887 |
+
"word_delimiter_token": word_delimiter_token,
|
888 |
+
}
|
889 |
+
|
890 |
+
# 5. Now we can instantiate the feature extractor, tokenizer and model
|
891 |
+
# Note for distributed training, the .from_pretrained methods guarantee that only
|
892 |
+
# one local process can concurrently download model & vocab.
|
893 |
+
|
894 |
+
# load feature_extractor and tokenizer
|
895 |
+
print("======== STEP 5: instantiate things")
|
896 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
897 |
+
tokenizer_name_or_path,
|
898 |
+
use_auth_token=data_args.use_auth_token,
|
899 |
+
**tokenizer_kwargs,
|
900 |
+
)
|
901 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
902 |
+
model_args.model_name_or_path,
|
903 |
+
cache_dir=model_args.cache_dir,
|
904 |
+
use_auth_token=data_args.use_auth_token,
|
905 |
+
)
|
906 |
+
|
907 |
+
# adapt config
|
908 |
+
config.update(
|
909 |
+
{
|
910 |
+
"feat_proj_dropout": model_args.feat_proj_dropout,
|
911 |
+
"attention_dropout": model_args.attention_dropout,
|
912 |
+
"hidden_dropout": model_args.hidden_dropout,
|
913 |
+
"final_dropout": model_args.final_dropout,
|
914 |
+
"mask_time_prob": model_args.mask_time_prob,
|
915 |
+
"mask_time_length": model_args.mask_time_length,
|
916 |
+
"mask_feature_prob": model_args.mask_feature_prob,
|
917 |
+
"mask_feature_length": model_args.mask_feature_length,
|
918 |
+
"gradient_checkpointing": training_args.gradient_checkpointing,
|
919 |
+
"layerdrop": model_args.layerdrop,
|
920 |
+
"ctc_loss_reduction": model_args.ctc_loss_reduction,
|
921 |
+
"pad_token_id": tokenizer.pad_token_id,
|
922 |
+
"vocab_size": len(tokenizer),
|
923 |
+
"activation_dropout": model_args.activation_dropout,
|
924 |
+
}
|
925 |
+
)
|
926 |
+
|
927 |
+
# create model
|
928 |
+
model = AutoModelForCTC.from_pretrained(
|
929 |
+
model_args.model_name_or_path,
|
930 |
+
cache_dir=model_args.cache_dir,
|
931 |
+
config=config,
|
932 |
+
use_auth_token=data_args.use_auth_token,
|
933 |
+
)
|
934 |
+
|
935 |
+
# freeze encoder
|
936 |
+
if model_args.freeze_feature_encoder:
|
937 |
+
model.freeze_feature_encoder()
|
938 |
+
|
939 |
+
# 6. Now we preprocess the datasets including loading the audio, resampling and normalization
|
940 |
+
# Thankfully, `datasets` takes care of automatically loading and resampling the audio,
|
941 |
+
# so that we just need to set the correct target sampling rate and normalize the input
|
942 |
+
# via the `feature_extractor`
|
943 |
+
print("======== STEP 6: preprocess datasets")
|
944 |
+
|
945 |
+
# make sure that dataset decodes audio with correct sampling rate
|
946 |
+
dataset_sampling_rate = (
|
947 |
+
next(iter(raw_datasets.values()))
|
948 |
+
.features[data_args.audio_column_name]
|
949 |
+
.sampling_rate
|
950 |
+
)
|
951 |
+
if dataset_sampling_rate != feature_extractor.sampling_rate:
|
952 |
+
raw_datasets = raw_datasets.cast_column(
|
953 |
+
data_args.audio_column_name,
|
954 |
+
datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
|
955 |
+
)
|
956 |
+
|
957 |
+
# derive max & min input length for sample rate & max duration
|
958 |
+
max_input_length = (
|
959 |
+
data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
960 |
+
)
|
961 |
+
min_input_length = (
|
962 |
+
data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
963 |
+
)
|
964 |
+
audio_column_name = data_args.audio_column_name
|
965 |
+
num_workers = data_args.preprocessing_num_workers
|
966 |
+
|
967 |
+
# `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
|
968 |
+
phoneme_language = data_args.phoneme_language
|
969 |
+
|
970 |
+
# Preprocessing the datasets.
|
971 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
972 |
+
def prepare_dataset(batch):
|
973 |
+
# load audio
|
974 |
+
sample = batch[audio_column_name]
|
975 |
+
|
976 |
+
inputs = feature_extractor(
|
977 |
+
sample["array"], sampling_rate=sample["sampling_rate"]
|
978 |
+
)
|
979 |
+
batch["input_values"] = inputs.input_values[0]
|
980 |
+
batch["input_length"] = len(batch["input_values"])
|
981 |
+
|
982 |
+
# encode targets
|
983 |
+
additional_kwargs = {}
|
984 |
+
if phoneme_language is not None:
|
985 |
+
additional_kwargs["phonemizer_lang"] = phoneme_language
|
986 |
+
|
987 |
+
batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
|
988 |
+
return batch
|
989 |
+
|
990 |
+
with training_args.main_process_first(desc="dataset map preprocessing"):
|
991 |
+
vectorized_datasets = raw_datasets.map(
|
992 |
+
prepare_dataset,
|
993 |
+
remove_columns=next(iter(raw_datasets.values())).column_names,
|
994 |
+
num_proc=num_workers,
|
995 |
+
desc="preprocess datasets",
|
996 |
+
)
|
997 |
+
|
998 |
+
def is_audio_in_length_range(length):
|
999 |
+
return length > min_input_length and length < max_input_length
|
1000 |
+
|
1001 |
+
# filter data that is shorter than min_input_length
|
1002 |
+
vectorized_datasets = vectorized_datasets.filter(
|
1003 |
+
is_audio_in_length_range,
|
1004 |
+
num_proc=num_workers,
|
1005 |
+
input_columns=["input_length"],
|
1006 |
+
)
|
1007 |
+
|
1008 |
+
# 7. Next, we can prepare the training.
|
1009 |
+
# Let's use word error rate (WER) as our evaluation metric,
|
1010 |
+
# instantiate a data collator and the trainer
|
1011 |
+
print("======== STEP 7: prepare training")
|
1012 |
+
|
1013 |
+
# Define evaluation metrics during training, *i.e.* word error rate, character error rate
|
1014 |
+
eval_metrics = {metric: evaluate.load(metric) for metric in data_args.eval_metrics}
|
1015 |
+
|
1016 |
+
# for large datasets it is advised to run the preprocessing on a
|
1017 |
+
# single machine first with ``args.preprocessing_only`` since there will mostly likely
|
1018 |
+
# be a timeout when running the script in distributed mode.
|
1019 |
+
# In a second step ``args.preprocessing_only`` can then be set to `False` to load the
|
1020 |
+
# cached dataset
|
1021 |
+
if data_args.preprocessing_only:
|
1022 |
+
logger.info(
|
1023 |
+
f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}"
|
1024 |
+
)
|
1025 |
+
return
|
1026 |
+
|
1027 |
+
def compute_metrics(pred):
|
1028 |
+
pred_logits = pred.predictions
|
1029 |
+
pred_ids = np.argmax(pred_logits, axis=-1)
|
1030 |
+
|
1031 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
1032 |
+
|
1033 |
+
pred_str = tokenizer.batch_decode(pred_ids)
|
1034 |
+
# we do not want to group tokens when computing the metrics
|
1035 |
+
label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
|
1036 |
+
|
1037 |
+
metrics = {
|
1038 |
+
k: v.compute(predictions=pred_str, references=label_str)
|
1039 |
+
for k, v in eval_metrics.items()
|
1040 |
+
}
|
1041 |
+
|
1042 |
+
return metrics
|
1043 |
+
|
1044 |
+
# Now save everything to be able to create a single processor later
|
1045 |
+
# make sure all processes wait until data is saved
|
1046 |
+
with training_args.main_process_first():
|
1047 |
+
# only the main process saves them
|
1048 |
+
if is_main_process(training_args.local_rank):
|
1049 |
+
# save feature extractor, tokenizer and config
|
1050 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
1051 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
1052 |
+
config.save_pretrained(training_args.output_dir)
|
1053 |
+
|
1054 |
+
try:
|
1055 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
1056 |
+
except (OSError, KeyError):
|
1057 |
+
warnings.warn(
|
1058 |
+
"Loading a processor from a feature extractor config that does not"
|
1059 |
+
" include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
|
1060 |
+
" attribute to your `preprocessor_config.json` file to suppress this warning: "
|
1061 |
+
" `'processor_class': 'Wav2Vec2Processor'`",
|
1062 |
+
FutureWarning,
|
1063 |
+
)
|
1064 |
+
processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
|
1065 |
+
|
1066 |
+
# Instantiate custom data collator
|
1067 |
+
data_collator = DataCollatorCTCWithPadding(processor=processor)
|
1068 |
+
|
1069 |
+
# Initialize Trainer
|
1070 |
+
trainer = Trainer(
|
1071 |
+
model=model,
|
1072 |
+
data_collator=data_collator,
|
1073 |
+
args=training_args,
|
1074 |
+
compute_metrics=compute_metrics,
|
1075 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
1076 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
1077 |
+
tokenizer=processor,
|
1078 |
+
)
|
1079 |
+
|
1080 |
+
# 8. Finally, we can start training
|
1081 |
+
print("======== STEP 8: train")
|
1082 |
+
|
1083 |
+
# Training
|
1084 |
+
if training_args.do_train:
|
1085 |
+
# use last checkpoint if exist
|
1086 |
+
if last_checkpoint is not None:
|
1087 |
+
checkpoint = last_checkpoint
|
1088 |
+
elif os.path.isdir(model_args.model_name_or_path):
|
1089 |
+
checkpoint = model_args.model_name_or_path
|
1090 |
+
else:
|
1091 |
+
checkpoint = None
|
1092 |
+
|
1093 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
1094 |
+
trainer.save_model()
|
1095 |
+
|
1096 |
+
metrics = train_result.metrics
|
1097 |
+
max_train_samples = (
|
1098 |
+
data_args.max_train_samples
|
1099 |
+
if data_args.max_train_samples is not None
|
1100 |
+
else len(vectorized_datasets["train"])
|
1101 |
+
)
|
1102 |
+
metrics["train_samples"] = min(
|
1103 |
+
max_train_samples, len(vectorized_datasets["train"])
|
1104 |
+
)
|
1105 |
+
|
1106 |
+
trainer.log_metrics("train", metrics)
|
1107 |
+
trainer.save_metrics("train", metrics)
|
1108 |
+
trainer.save_state()
|
1109 |
+
|
1110 |
+
# Evaluation
|
1111 |
+
print("======== STEP 9: eval")
|
1112 |
+
results = {}
|
1113 |
+
if training_args.do_eval:
|
1114 |
+
logger.info("*** Evaluate ***")
|
1115 |
+
metrics = trainer.evaluate()
|
1116 |
+
max_eval_samples = (
|
1117 |
+
data_args.max_eval_samples
|
1118 |
+
if data_args.max_eval_samples is not None
|
1119 |
+
else len(vectorized_datasets["eval"])
|
1120 |
+
)
|
1121 |
+
metrics["eval_samples"] = min(
|
1122 |
+
max_eval_samples, len(vectorized_datasets["eval"])
|
1123 |
+
)
|
1124 |
+
|
1125 |
+
trainer.log_metrics("eval", metrics)
|
1126 |
+
trainer.save_metrics("eval", metrics)
|
1127 |
+
|
1128 |
+
# Write model card and (optionally) push to hub
|
1129 |
+
print("======== STEP 10: write model card, push to hub")
|
1130 |
+
|
1131 |
+
config_name = (
|
1132 |
+
data_args.dataset_config_name
|
1133 |
+
if data_args.dataset_config_name is not None
|
1134 |
+
else "na"
|
1135 |
+
)
|
1136 |
+
kwargs = {
|
1137 |
+
"finetuned_from": model_args.model_name_or_path,
|
1138 |
+
"tasks": "automatic-speech-recognition",
|
1139 |
+
"tags": ["automatic-speech-recognition", data_args.dataset_name],
|
1140 |
+
"dataset_args": (
|
1141 |
+
f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split:"
|
1142 |
+
f" {data_args.eval_split_name}"
|
1143 |
+
),
|
1144 |
+
"dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
|
1145 |
+
}
|
1146 |
+
if "common_voice" in data_args.dataset_name:
|
1147 |
+
kwargs["language"] = config_name
|
1148 |
+
|
1149 |
+
if training_args.push_to_hub:
|
1150 |
+
trainer.create_model_card(**kwargs)
|
1151 |
+
trainer.push_to_hub(**kwargs)
|
1152 |
+
|
1153 |
+
return results
|
1154 |
+
|
1155 |
+
|
1156 |
+
if __name__ == "__main__":
|
1157 |
+
main()
|
train.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"dataset_name": "mozilla-foundation/common_voice_13_0",
|
3 |
+
"model_name_or_path": "facebook/wav2vec2-large-xlsr-53",
|
4 |
+
"dataset_config_name": "eo",
|
5 |
+
"output_dir": "./wav2vec2-common_voice_13_0-eo-10",
|
6 |
+
"train_split_name": "train",
|
7 |
+
"eval_split_name": "validation",
|
8 |
+
"eval_metrics": ["cer", "wer"],
|
9 |
+
"overwrite_output_dir": false,
|
10 |
+
"preprocessing_num_workers": 1,
|
11 |
+
"num_train_epochs": 5,
|
12 |
+
"per_device_train_batch_size": 16,
|
13 |
+
"gradient_accumulation_steps": 2,
|
14 |
+
"gradient_checkpointing": true,
|
15 |
+
"learning_rate": 3e-5,
|
16 |
+
"warmup_steps": 500,
|
17 |
+
"evaluation_strategy": "steps",
|
18 |
+
"text_column_name": "sentence",
|
19 |
+
"length_column_name": "input_length",
|
20 |
+
"save_steps": 1000,
|
21 |
+
"eval_steps": 1000,
|
22 |
+
"layerdrop": 0.2,
|
23 |
+
"save_total_limit": 3,
|
24 |
+
"freeze_feature_encoder": true,
|
25 |
+
"chars_to_ignore": "-!\"'(),.:;=?_`¨«¸»ʼ‑–—‘’“”„…‹›♫?",
|
26 |
+
"chars_to_substitute": {
|
27 |
+
"przy": "pŝe",
|
28 |
+
"byn": "bin",
|
29 |
+
"cx": "ĉ",
|
30 |
+
"sx": "ŝ",
|
31 |
+
"fi": "fi",
|
32 |
+
"fl": "fl",
|
33 |
+
"ǔ": "ŭ",
|
34 |
+
"ñ": "nj",
|
35 |
+
"á": "a",
|
36 |
+
"é": "e",
|
37 |
+
"ü": "ŭ",
|
38 |
+
"y": "j",
|
39 |
+
"qu": "ku"
|
40 |
+
},
|
41 |
+
"fp16": true,
|
42 |
+
"group_by_length": true,
|
43 |
+
"push_to_hub": true,
|
44 |
+
"do_train": true,
|
45 |
+
"do_eval": true
|
46 |
+
}
|