comodoro commited on
Commit
0c6089d
1 Parent(s): a4b44de

Added the weak baseline model readme and eval script

Browse files
Files changed (2) hide show
  1. README.md +131 -3
  2. eval.py +163 -0
README.md CHANGED
@@ -1,3 +1,131 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ language: cs
2
+ datasets:
3
+ - mozilla-foundation/common_voice_8_0
4
+ metrics:
5
+ - wer
6
+ tags:
7
+ - generated_from_trainer
8
+ - audio
9
+ - automatic-speech-recognition
10
+ - speech
11
+ - xlsr-fine-tuning-week
12
+ license: apache-2.0
13
+ model-index:
14
+ - name: Czech comodoro Wav2Vec2 XLSR 300M CV8
15
+ results:
16
+ - task:
17
+ name: Speech Recognition
18
+ type: automatic-speech-recognition
19
+ dataset:
20
+ name: Common Voice 8.0 cs
21
+ type: mozilla-foundation/common_voice_8_0
22
+ args: cs
23
+ metrics:
24
+ - name: Test WER
25
+ type: wer
26
+ value: 0.47455377483706096
27
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
28
+ should probably proofread and complete it, then remove this comment. -->
29
+
30
+ # wav2vec2-xls-r-300m-cs-cv8
31
+
32
+ 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.0 dataset.
33
+ It achieves the following results on the evaluation set:
34
+ - WER: 0.47455377483706096
35
+ - CER: 0.10877155235645618
36
+
37
+ ## Model description
38
+
39
+ Fine-tuned [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53) on Czech using the [Common Voice](https://huggingface.co/datasets/common_voice) dataset.
40
+ When using this model, make sure that your speech input is sampled at 16kHz.
41
+
42
+
43
+ The model can be used directly (without a language model) as follows:
44
+
45
+ ```python
46
+ import torch
47
+ import torchaudio
48
+ from datasets import load_dataset
49
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
50
+
51
+ test_dataset = load_dataset("mozilla-foundation/common_voice_8_0", "cs", split="test[:2%]")
52
+
53
+ processor = Wav2Vec2Processor.from_pretrained("comodoro/wav2vec2-xls-r-300m-cs-cv8")
54
+ model = Wav2Vec2ForCTC.from_pretrained("comodoro/wav2vec2-xls-r-300m-cs-cv8")
55
+
56
+ resampler = torchaudio.transforms.Resample(48_000, 16_000)
57
+
58
+ # Preprocessing the datasets.
59
+ # We need to read the aduio files as arrays
60
+ def speech_file_to_array_fn(batch):
61
+ speech_array, sampling_rate = torchaudio.load(batch["path"])
62
+ batch["speech"] = resampler(speech_array).squeeze().numpy()
63
+ return batch
64
+
65
+ test_dataset = test_dataset.map(speech_file_to_array_fn)
66
+ inputs = processor(test_dataset[:2]["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
67
+
68
+ with torch.no_grad():
69
+ logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
70
+
71
+ predicted_ids = torch.argmax(logits, dim=-1)
72
+
73
+ print("Prediction:", processor.batch_decode(predicted_ids))
74
+ print("Reference:", test_dataset[:2]["sentence"])
75
+ ```
76
+
77
+ ## Evaluation
78
+
79
+ The model can be evaluated using the attached `eval.py` script.
80
+
81
+ ## Training and evaluation data
82
+
83
+ The Common Voice 8.0 `train` and `validation` datasets were used for training
84
+
85
+ ## Training procedure
86
+
87
+ ### Training hyperparameters
88
+
89
+ The following hyperparameters were used during training:
90
+ - learning_rate: 7e-05
91
+ - train_batch_size: 32
92
+ - eval_batch_size: 8
93
+ - seed: 42
94
+ - gradient_accumulation_steps: 20
95
+ - total_train_batch_size: 640
96
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
97
+ - lr_scheduler_type: linear
98
+ - lr_scheduler_warmup_steps: 500
99
+ - num_epochs: 150
100
+ - mixed_precision_training: Native AMP
101
+
102
+ ### Training results
103
+
104
+ | Training Loss | Epoch | Step | Validation Loss | Wer | Cer |
105
+ |:-------------:|:------:|:----:|:---------------:|:------:|:------:|
106
+ | 7.2926 | 8.06 | 250 | 3.8497 | 1.0 | 1.0 |
107
+ | 3.417 | 16.13 | 500 | 3.2852 | 1.0 | 0.9857 |
108
+ | 2.0264 | 24.19 | 750 | 0.7099 | 0.7342 | 0.1768 |
109
+ | 0.4018 | 32.25 | 1000 | 0.6188 | 0.6415 | 0.1551 |
110
+ | 0.2444 | 40.32 | 1250 | 0.6632 | 0.6362 | 0.1600 |
111
+ | 0.1882 | 48.38 | 1500 | 0.6070 | 0.5783 | 0.1388 |
112
+ | 0.153 | 56.44 | 1750 | 0.6425 | 0.5720 | 0.1377 |
113
+ | 0.1214 | 64.51 | 2000 | 0.6363 | 0.5546 | 0.1337 |
114
+ | 0.1011 | 72.57 | 2250 | 0.6310 | 0.5222 | 0.1224 |
115
+ | 0.0879 | 80.63 | 2500 | 0.6353 | 0.5258 | 0.1253 |
116
+ | 0.0782 | 88.7 | 2750 | 0.6078 | 0.4904 | 0.1127 |
117
+ | 0.0709 | 96.76 | 3000 | 0.6465 | 0.4960 | 0.1154 |
118
+ | 0.0661 | 104.82 | 3250 | 0.6622 | 0.4945 | 0.1166 |
119
+ | 0.0616 | 112.89 | 3500 | 0.6440 | 0.4786 | 0.1104 |
120
+ | 0.0579 | 120.95 | 3750 | 0.6815 | 0.4887 | 0.1144 |
121
+ | 0.0549 | 129.03 | 4000 | 0.6603 | 0.4780 | 0.1105 |
122
+ | 0.0527 | 137.09 | 4250 | 0.6652 | 0.4749 | 0.1090 |
123
+ | 0.0506 | 145.16 | 4500 | 0.6958 | 0.4846 | 0.1133 |
124
+
125
+
126
+ ### Framework versions
127
+
128
+ - Transformers 4.16.0.dev0
129
+ - Pytorch 1.10.1+cu102
130
+ - Datasets 1.17.1.dev0
131
+ - Tokenizers 0.11.0
eval.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from datasets import load_dataset, load_metric, Audio, Dataset
3
+ from transformers import pipeline, AutoFeatureExtractor
4
+ import re
5
+ import argparse
6
+ import unicodedata
7
+ from typing import Dict
8
+
9
+
10
+ def log_results(result: Dataset, args: Dict[str, str]):
11
+ """ DO NOT CHANGE. This function computes and logs the result metrics. """
12
+
13
+ log_outputs = args.log_outputs
14
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
15
+
16
+ # load metric
17
+ wer = load_metric("wer")
18
+ cer = load_metric("cer")
19
+
20
+ # compute metrics
21
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
22
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
23
+
24
+ # print & log results
25
+ result_str = (
26
+ f"WER: {wer_result}\n"
27
+ f"CER: {cer_result}"
28
+ )
29
+ print(result_str)
30
+
31
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
32
+ f.write(result_str)
33
+
34
+ # log all results in text file. Possibly interesting for analysis
35
+ if log_outputs is not None:
36
+ pred_file = f"log_{dataset_id}_predictions.txt"
37
+ target_file = f"log_{dataset_id}_targets.txt"
38
+
39
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
40
+
41
+ # mapping function to write output
42
+ def write_to_file(batch, i):
43
+ p.write(f"{i}" + "\n")
44
+ p.write(batch["prediction"] + "\n")
45
+ t.write(f"{i}" + "\n")
46
+ t.write(batch["target"] + "\n")
47
+
48
+ result.map(write_to_file, with_indices=True)
49
+
50
+
51
+ def normalize_text(text: str) -> str:
52
+ """ DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
53
+
54
+
55
+ CHARS = {
56
+ 'ü': 'ue',
57
+ 'ö': 'oe',
58
+ 'ï': 'i',
59
+ 'ë': 'e',
60
+ 'ä': 'ae',
61
+ 'ã': 'a',
62
+ 'à': 'á',
63
+ 'ø': 'o',
64
+ 'è': 'é',
65
+ 'ê': 'é',
66
+ 'å': 'ó',
67
+ 'î': 'i',
68
+ 'ñ': 'ň',
69
+ 'ç': 's',
70
+ 'ľ': 'l',
71
+ 'ż': 'ž',
72
+ 'ł': 'w',
73
+ 'ć': 'č',
74
+ 'þ': 't',
75
+ 'ß': 'ss',
76
+ 'ę': 'en',
77
+ 'ą': 'an',
78
+ 'æ': 'ae',
79
+ }
80
+
81
+ def replace_chars(sentence):
82
+ result = ''
83
+ for ch in sentence:
84
+ new = CHARS[ch] if ch in CHARS else ch
85
+ result += new
86
+
87
+ return result
88
+
89
+ chars_to_remove_regex = '[\,\?\.\!\-\;\:\/\"\“\„\%\”\�\–\'\`\«\»\—\’\…]'
90
+
91
+ text = text.lower()
92
+ # normalize non-standard (stylized) unicode characters
93
+ text = unicodedata.normalize('NFKC', text)
94
+ # remove punctuation
95
+ text = re.sub(chars_to_ignore_regex, "", text)
96
+ batch["sentence"] = replace_chars(batch['sentence'])
97
+
98
+ # Let's also make sure we split on all kinds of newlines, spaces, etc...
99
+ text = " ".join(text.split())
100
+
101
+ return text
102
+
103
+
104
+ def main(args):
105
+ # load dataset
106
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
107
+
108
+ # for testing: only process the first two examples as a test
109
+ # dataset = dataset.select(range(10))
110
+
111
+ # load processor
112
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
113
+ sampling_rate = feature_extractor.sampling_rate
114
+
115
+ # resample audio
116
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
117
+
118
+ # load eval pipeline
119
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
120
+
121
+ # map function to decode audio
122
+ def map_to_pred(batch):
123
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
124
+
125
+ batch["prediction"] = prediction["text"]
126
+ batch["target"] = normalize_text(batch["sentence"])
127
+ return batch
128
+
129
+ # run inference on all examples
130
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
131
+
132
+ # compute and log_results
133
+ # do not change function below
134
+ log_results(result, args)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ parser = argparse.ArgumentParser()
139
+
140
+ parser.add_argument(
141
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
142
+ )
143
+ parser.add_argument(
144
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
145
+ )
146
+ parser.add_argument(
147
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
148
+ )
149
+ parser.add_argument(
150
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
151
+ )
152
+ parser.add_argument(
153
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to None. For long audio files a good value would be 5.0 seconds."
154
+ )
155
+ parser.add_argument(
156
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to None. For long audio files a good value would be 1.0 seconds."
157
+ )
158
+ parser.add_argument(
159
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
160
+ )
161
+ args = parser.parse_args()
162
+
163
+ main(args)