comodoro commited on
Commit
5d125d2
1 Parent(s): a4b44de

Added the weak baseline model readme and eval script

Browse files
Files changed (2) hide show
  1. README.md +135 -3
  2. eval.py +163 -0
README.md CHANGED
@@ -1,3 +1,135 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+
5
+ language: cs
6
+ datasets:
7
+ - mozilla-foundation/common_voice_8_0
8
+ metrics:
9
+ - wer
10
+ tags:
11
+ - generated_from_trainer
12
+ - audio
13
+ - automatic-speech-recognition
14
+ - speech
15
+ - xlsr-fine-tuning-week
16
+ license: apache-2.0
17
+ model-index:
18
+ - name: Czech comodoro Wav2Vec2 XLSR 300M CV8
19
+ results:
20
+ - task:
21
+ name: Speech Recognition
22
+ type: automatic-speech-recognition
23
+ dataset:
24
+ name: Common Voice 8.0 cs
25
+ type: mozilla-foundation/common_voice_8_0
26
+ args: cs
27
+ metrics:
28
+ - name: Test WER
29
+ type: wer
30
+ value: 0.47455377483706096
31
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
32
+ should probably proofread and complete it, then remove this comment. -->
33
+
34
+ # wav2vec2-xls-r-300m-cs-cv8
35
+
36
+ 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.
37
+ It achieves the following results on the evaluation set:
38
+ - WER: 0.47455377483706096
39
+ - CER: 0.10877155235645618
40
+
41
+ ## Model description
42
+
43
+ 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.
44
+ When using this model, make sure that your speech input is sampled at 16kHz.
45
+
46
+
47
+ The model can be used directly (without a language model) as follows:
48
+
49
+ ```python
50
+ import torch
51
+ import torchaudio
52
+ from datasets import load_dataset
53
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
54
+
55
+ test_dataset = load_dataset("mozilla-foundation/common_voice_8_0", "cs", split="test[:2%]")
56
+
57
+ processor = Wav2Vec2Processor.from_pretrained("comodoro/wav2vec2-xls-r-300m-cs-cv8")
58
+ model = Wav2Vec2ForCTC.from_pretrained("comodoro/wav2vec2-xls-r-300m-cs-cv8")
59
+
60
+ resampler = torchaudio.transforms.Resample(48_000, 16_000)
61
+
62
+ # Preprocessing the datasets.
63
+ # We need to read the aduio files as arrays
64
+ def speech_file_to_array_fn(batch):
65
+ speech_array, sampling_rate = torchaudio.load(batch["path"])
66
+ batch["speech"] = resampler(speech_array).squeeze().numpy()
67
+ return batch
68
+
69
+ test_dataset = test_dataset.map(speech_file_to_array_fn)
70
+ inputs = processor(test_dataset[:2]["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
71
+
72
+ with torch.no_grad():
73
+ logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
74
+
75
+ predicted_ids = torch.argmax(logits, dim=-1)
76
+
77
+ print("Prediction:", processor.batch_decode(predicted_ids))
78
+ print("Reference:", test_dataset[:2]["sentence"])
79
+ ```
80
+
81
+ ## Evaluation
82
+
83
+ The model can be evaluated using the attached `eval.py` script.
84
+
85
+ ## Training and evaluation data
86
+
87
+ The Common Voice 8.0 `train` and `validation` datasets were used for training
88
+
89
+ ## Training procedure
90
+
91
+ ### Training hyperparameters
92
+
93
+ The following hyperparameters were used during training:
94
+ - learning_rate: 7e-05
95
+ - train_batch_size: 32
96
+ - eval_batch_size: 8
97
+ - seed: 42
98
+ - gradient_accumulation_steps: 20
99
+ - total_train_batch_size: 640
100
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
101
+ - lr_scheduler_type: linear
102
+ - lr_scheduler_warmup_steps: 500
103
+ - num_epochs: 150
104
+ - mixed_precision_training: Native AMP
105
+
106
+ ### Training results
107
+
108
+ | Training Loss | Epoch | Step | Validation Loss | Wer | Cer |
109
+ |:-------------:|:------:|:----:|:---------------:|:------:|:------:|
110
+ | 7.2926 | 8.06 | 250 | 3.8497 | 1.0 | 1.0 |
111
+ | 3.417 | 16.13 | 500 | 3.2852 | 1.0 | 0.9857 |
112
+ | 2.0264 | 24.19 | 750 | 0.7099 | 0.7342 | 0.1768 |
113
+ | 0.4018 | 32.25 | 1000 | 0.6188 | 0.6415 | 0.1551 |
114
+ | 0.2444 | 40.32 | 1250 | 0.6632 | 0.6362 | 0.1600 |
115
+ | 0.1882 | 48.38 | 1500 | 0.6070 | 0.5783 | 0.1388 |
116
+ | 0.153 | 56.44 | 1750 | 0.6425 | 0.5720 | 0.1377 |
117
+ | 0.1214 | 64.51 | 2000 | 0.6363 | 0.5546 | 0.1337 |
118
+ | 0.1011 | 72.57 | 2250 | 0.6310 | 0.5222 | 0.1224 |
119
+ | 0.0879 | 80.63 | 2500 | 0.6353 | 0.5258 | 0.1253 |
120
+ | 0.0782 | 88.7 | 2750 | 0.6078 | 0.4904 | 0.1127 |
121
+ | 0.0709 | 96.76 | 3000 | 0.6465 | 0.4960 | 0.1154 |
122
+ | 0.0661 | 104.82 | 3250 | 0.6622 | 0.4945 | 0.1166 |
123
+ | 0.0616 | 112.89 | 3500 | 0.6440 | 0.4786 | 0.1104 |
124
+ | 0.0579 | 120.95 | 3750 | 0.6815 | 0.4887 | 0.1144 |
125
+ | 0.0549 | 129.03 | 4000 | 0.6603 | 0.4780 | 0.1105 |
126
+ | 0.0527 | 137.09 | 4250 | 0.6652 | 0.4749 | 0.1090 |
127
+ | 0.0506 | 145.16 | 4500 | 0.6958 | 0.4846 | 0.1133 |
128
+
129
+
130
+ ### Framework versions
131
+
132
+ - Transformers 4.16.0.dev0
133
+ - Pytorch 1.10.1+cu102
134
+ - Datasets 1.17.1.dev0
135
+ - 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)