chmanoj commited on
Commit
48c833e
β€’
1 Parent(s): 460a6d6

Add eval WER and model card

Browse files
Files changed (2) hide show
  1. README.md +101 -0
  2. eval.py +156 -0
README.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - te
4
+ license: apache-2.0
5
+ tags:
6
+ - automatic-speech-recognition
7
+ - openslr_SLR66
8
+ - generated_from_trainer
9
+ - robust-speech-event
10
+ datasets:
11
+ - openslr
12
+ - SLR66
13
+ metrics:
14
+ - wer
15
+ model-index:
16
+ - name: xls-r-1B-te
17
+ results:
18
+ - task:
19
+ type: automatic-speech-recognition
20
+ name: Speech Recognition
21
+ dataset:
22
+ type: openslr
23
+ name: Open SLR
24
+ args: SLR66
25
+ metrics:
26
+ - type: wer
27
+ value: 0.51
28
+ name: Test WER
29
+ - type: cer
30
+ value: 0.097
31
+ name: Test CER
32
+
33
+ ---
34
+
35
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
36
+ should probably proofread and complete it, then remove this comment. -->
37
+
38
+ #
39
+
40
+ This model is a fine-tuned version of [facebook/wav2vec2-xls-r-2b](https://huggingface.co/facebook/wav2vec2-xls-r-2b) on the OPENSLR_SLR66 - NA dataset.
41
+ It achieves the following results on the evaluation set:
42
+ - Loss: 0.4253
43
+ - Wer: 0.5109
44
+
45
+
46
+ ### Evaluation metrics
47
+
48
+ | Metric | Split | Decode with LM | Value |
49
+ |:------:|:------:|:--------------:|:---------:|
50
+ | WER | Train | No | |
51
+ | CER | Train | No | |
52
+ | WER | Test | No | |
53
+ | CER | Test | No | |
54
+ | WER | Train | Yes | |
55
+ | CER | Train | Yes | |
56
+ | WER | Test | Yes | |
57
+ | CER | Test | Yes | |
58
+
59
+
60
+ ## Model description
61
+
62
+ More information needed
63
+
64
+ ## Intended uses & limitations
65
+
66
+ More information needed
67
+
68
+ ## Training and evaluation data
69
+
70
+ More information needed
71
+
72
+ ## Training procedure
73
+
74
+ ### Training hyperparameters
75
+
76
+ The following hyperparameters were used during training:
77
+ - learning_rate: 2e-05
78
+ - train_batch_size: 4
79
+ - eval_batch_size: 4
80
+ - seed: 42
81
+ - gradient_accumulation_steps: 12
82
+ - total_train_batch_size: 64
83
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
84
+ - learning_rate: 3e-6
85
+ - lr_scheduler_type: linear
86
+ - lr_scheduler_warmup_steps: 2000
87
+ - num_epochs: 150.0
88
+ - hidden_dropout: 0.15
89
+ - mixed_precision_training: Native AMP
90
+
91
+ ### Training results
92
+
93
+
94
+
95
+
96
+ ### Framework versions
97
+
98
+ - Transformers 4.16.0.dev0
99
+ - Pytorch 1.10.1+cu102
100
+ - Datasets 1.17.1.dev0
101
+ - Tokenizers 0.11.0
eval.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ from typing import Dict
5
+
6
+ from datasets import Audio, Dataset, load_dataset, load_metric, DatasetDict
7
+
8
+ from transformers import AutoFeatureExtractor, pipeline
9
+
10
+
11
+ def log_results(result: Dataset, args: Dict[str, str]):
12
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
13
+
14
+ log_outputs = args.log_outputs
15
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
16
+
17
+ # load metric
18
+ wer = load_metric("wer")
19
+ cer = load_metric("cer")
20
+
21
+ # compute metrics
22
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
23
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
24
+
25
+ # print & log results
26
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
27
+ print(result_str)
28
+
29
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
30
+ f.write(result_str)
31
+
32
+ # log all results in text file. Possibly interesting for analysis
33
+ if log_outputs is not None:
34
+ pred_file = f"log_{dataset_id}_predictions.txt"
35
+ target_file = f"log_{dataset_id}_targets.txt"
36
+
37
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
38
+
39
+ # mapping function to write output
40
+ def write_to_file(batch, i):
41
+ p.write(f"{i}" + "\n")
42
+ p.write(batch["prediction"] + "\n")
43
+ t.write(f"{i}" + "\n")
44
+ t.write(batch["target"] + "\n")
45
+
46
+ result.map(write_to_file, with_indices=True)
47
+
48
+
49
+ def normalize_text(text: str) -> str:
50
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
51
+
52
+ chars_to_ignore_regex = '[,?.!\-\;\:"β€œ%β€˜β€οΏ½β€”β€™β€¦β€“]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
53
+
54
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
55
+
56
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
57
+ # note that order is important here!
58
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
59
+
60
+ for t in token_sequences_to_ignore:
61
+ text = " ".join(text.split(t))
62
+
63
+ return text
64
+
65
+
66
+ def get_telugu_dataset(validation_split=False):
67
+ dataset = load_dataset('openslr', 'SLR66')
68
+
69
+ seed=1242
70
+
71
+ if validation_split:
72
+ train_testvalid = dataset['train'].train_test_split(test_size=0.2, seed=seed)
73
+ # Split the 10% test + valid in half test, half valid
74
+ test_valid = train_testvalid['test'].train_test_split(test_size=0.33, seed=seed)
75
+ # gather everyone if you want to have a single DatasetDict
76
+ out_dataset = DatasetDict({
77
+ 'train': train_testvalid['train'],
78
+ 'test': test_valid['test'],
79
+ 'valid': test_valid['train']})
80
+ else:
81
+ train_testvalid = dataset['train'].train_test_split(test_size=0.25, seed=seed)
82
+ out_dataset = DatasetDict({
83
+ 'train': train_testvalid['train'],
84
+ 'test': train_testvalid['test']})
85
+ return out_dataset
86
+
87
+
88
+ def main(args):
89
+ # load dataset
90
+ te_dataset = get_telugu_dataset(validation_split=False)
91
+ def load_te_dataset(split):
92
+ return te_dataset[split]
93
+
94
+ # dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
95
+ dataset = load_te_dataset(split=args.split)
96
+
97
+ # for testing: only process the first two examples as a test
98
+ # dataset = dataset.select(range(10))
99
+
100
+ # load processor
101
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
102
+ sampling_rate = feature_extractor.sampling_rate
103
+
104
+ # resample audio
105
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
106
+
107
+ # load eval pipeline
108
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=0)
109
+
110
+ # map function to decode audio
111
+ def map_to_pred(batch):
112
+ prediction = asr(
113
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
114
+ )
115
+
116
+ batch["prediction"] = prediction["text"]
117
+ batch["target"] = normalize_text(batch["sentence"])
118
+ return batch
119
+
120
+ # run inference on all examples
121
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
122
+
123
+ # compute and log_results
124
+ # do not change function below
125
+ log_results(result, args)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ # python eval.py --model_id="xls-r-2B-te" --dataset="openslr" --config="te" --split="test" --log_outputs
130
+ parser = argparse.ArgumentParser()
131
+
132
+ parser.add_argument(
133
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with πŸ€— Transformers"
134
+ )
135
+ parser.add_argument(
136
+ "--dataset",
137
+ type=str,
138
+ required=True,
139
+ help="Dataset name to evaluate the `model_id`. Should be loadable with πŸ€— Datasets",
140
+ )
141
+ parser.add_argument(
142
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
143
+ )
144
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
145
+ parser.add_argument(
146
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
147
+ )
148
+ parser.add_argument(
149
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
150
+ )
151
+ parser.add_argument(
152
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
153
+ )
154
+ args = parser.parse_args()
155
+
156
+ main(args)