pere commited on
Commit
5cf146f
1 Parent(s): 193f249
.gitattributes CHANGED
@@ -25,3 +25,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ *.txt filter=lfs diff=lfs merge=lfs -text
29
+ *unigram*.* filter=lfs diff=lfs merge=lfs -text
NbAiLab_NPSC_16K_mp3_nynorsk_test_eval_results.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ed28ce85f9486af2150732dc9833fd7c292c124e0100e8f9f20b25fdd1bcfd4
3
+ size 49
NbAiLab_NPSC_16K_mp3_nynorsk_test_eval_results_no_lang_model.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ad6da4ab72c542e88f1b751239f053f2d0a3dd03cc51b5c4600b44b967e977b
3
+ size 49
add_kenlm.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from transformers import AutoProcessor
3
+ from transformers import Wav2Vec2ProcessorWithLM
4
+ from pyctcdecode import build_ctcdecoder
5
+
6
+
7
+ def main(args):
8
+ processor = AutoProcessor.from_pretrained(args.model_name_or_path)
9
+ vocab_dict = processor.tokenizer.get_vocab()
10
+ sorted_vocab_dict = {
11
+ k.lower(): v for k, v in sorted(vocab_dict.items(), key=lambda item: item[1])
12
+ }
13
+ decoder = build_ctcdecoder(
14
+ labels=list(sorted_vocab_dict.keys()),
15
+ kenlm_model_path=args.kenlm_model_path,
16
+ )
17
+ processor_with_lm = Wav2Vec2ProcessorWithLM(
18
+ feature_extractor=processor.feature_extractor,
19
+ tokenizer=processor.tokenizer,
20
+ decoder=decoder,
21
+ )
22
+ processor_with_lm.save_pretrained(args.model_name_or_path)
23
+ print(f"Run: ~/bin/build_binary language_model/*.arpa language_model/5gram.bin -T $(pwd) && rm language_model/*.arpa")
24
+
25
+ def parse_args():
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument('--model_name_or_path', default="./", help='Model name or path. Defaults to ./')
28
+ parser.add_argument('--kenlm_model_path', required=True, help='Path to KenLM arpa file.')
29
+ args = parser.parse_args()
30
+ return args
31
+
32
+ if __name__ == "__main__":
33
+ args = parse_args()
34
+ main(args)
added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"<s>": 32, "</s>": 33}
all_results.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 40.0,
3
+ "eval_loss": 0.35698655247688293,
4
+ "eval_runtime": 52.1875,
5
+ "eval_samples": 825,
6
+ "eval_samples_per_second": 15.808,
7
+ "eval_steps_per_second": 0.996,
8
+ "eval_wer": 0.21414389713529355,
9
+ "train_loss": 0.896209309619406,
10
+ "train_runtime": 25745.3803,
11
+ "train_samples": 7354,
12
+ "train_samples_per_second": 11.426,
13
+ "train_steps_per_second": 0.357
14
+ }
alphabet.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"labels": [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u00e5", "\u00e6", "\u00f8", "\u2047", "", "<s>", "</s>"], "is_bpe": false}
config.json ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "KBLab/wav2vec2-large-voxrex",
3
+ "activation_dropout": 0.055,
4
+ "adapter_kernel_size": 3,
5
+ "adapter_stride": 2,
6
+ "add_adapter": false,
7
+ "apply_spec_augment": true,
8
+ "architectures": [
9
+ "Wav2Vec2ForCTC"
10
+ ],
11
+ "attention_dropout": 0.094,
12
+ "bos_token_id": 1,
13
+ "classifier_proj_size": 256,
14
+ "codevector_dim": 768,
15
+ "contrastive_logits_temperature": 0.1,
16
+ "conv_bias": true,
17
+ "conv_dim": [
18
+ 512,
19
+ 512,
20
+ 512,
21
+ 512,
22
+ 512,
23
+ 512,
24
+ 512
25
+ ],
26
+ "conv_kernel": [
27
+ 10,
28
+ 3,
29
+ 3,
30
+ 3,
31
+ 3,
32
+ 2,
33
+ 2
34
+ ],
35
+ "conv_stride": [
36
+ 5,
37
+ 2,
38
+ 2,
39
+ 2,
40
+ 2,
41
+ 2,
42
+ 2
43
+ ],
44
+ "ctc_loss_reduction": "mean",
45
+ "ctc_zero_infinity": false,
46
+ "diversity_loss_weight": 0.1,
47
+ "do_stable_layer_norm": true,
48
+ "eos_token_id": 2,
49
+ "feat_extract_activation": "gelu",
50
+ "feat_extract_dropout": 0.0,
51
+ "feat_extract_norm": "layer",
52
+ "feat_proj_dropout": 0.04,
53
+ "feat_quantizer_dropout": 0.0,
54
+ "final_dropout": 0.0,
55
+ "hidden_act": "gelu",
56
+ "hidden_dropout": 0.047,
57
+ "hidden_size": 1024,
58
+ "initializer_range": 0.02,
59
+ "intermediate_size": 4096,
60
+ "layer_norm_eps": 1e-05,
61
+ "layerdrop": 0.041,
62
+ "mask_channel_length": 10,
63
+ "mask_channel_min_space": 1,
64
+ "mask_channel_other": 0.0,
65
+ "mask_channel_prob": 0.0,
66
+ "mask_channel_selection": "static",
67
+ "mask_feature_length": 64,
68
+ "mask_feature_min_masks": 0,
69
+ "mask_feature_prob": 0.25,
70
+ "mask_time_length": 10,
71
+ "mask_time_min_masks": 2,
72
+ "mask_time_min_space": 1,
73
+ "mask_time_other": 0.0,
74
+ "mask_time_prob": 0.082,
75
+ "mask_time_selection": "static",
76
+ "model_type": "wav2vec2",
77
+ "num_adapter_layers": 3,
78
+ "num_attention_heads": 16,
79
+ "num_codevector_groups": 2,
80
+ "num_codevectors_per_group": 320,
81
+ "num_conv_pos_embedding_groups": 16,
82
+ "num_conv_pos_embeddings": 128,
83
+ "num_feat_extract_layers": 7,
84
+ "num_hidden_layers": 24,
85
+ "num_negatives": 100,
86
+ "output_hidden_size": 1024,
87
+ "pad_token_id": 31,
88
+ "proj_codevector_dim": 768,
89
+ "tdnn_dilation": [
90
+ 1,
91
+ 2,
92
+ 3,
93
+ 1,
94
+ 1
95
+ ],
96
+ "tdnn_dim": [
97
+ 512,
98
+ 512,
99
+ 512,
100
+ 512,
101
+ 1500
102
+ ],
103
+ "tdnn_kernel": [
104
+ 5,
105
+ 3,
106
+ 3,
107
+ 1,
108
+ 1
109
+ ],
110
+ "torch_dtype": "float32",
111
+ "transformers_version": "4.17.0.dev0",
112
+ "use_weighted_layer_sum": false,
113
+ "vocab_size": 34,
114
+ "xvector_output_dim": 512
115
+ }
eval.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
54
+
55
+ text = re.sub(chars_to_ignore_regex, "", text.lower()) + " "
56
+ text = re.sub('[áàâ]', 'a', text)
57
+ text = re.sub('[ä]', 'æ', text)
58
+ text = re.sub('[éèëê]', 'e', text)
59
+ text = re.sub('[íìïî]', 'i', text)
60
+ text = re.sub('[óòöô]', 'o', text)
61
+ text = re.sub('[ö]', 'ø', text)
62
+ text = re.sub('[ç]', 'c', text)
63
+ text = re.sub('[úùüû]', 'u', text)
64
+ text = re.sub('\s', ' ', text)
65
+ text = re.sub('<ee>', 'eee', text)
66
+ text = re.sub('<qq>', 'qqq', text)
67
+ text = re.sub('<mm>', 'mmm', text)
68
+ text = re.sub('<inaudible>', 'xxx', text)
69
+ text = re.sub('[<>]', '', text)
70
+
71
+ # # In addition, we can normalize the target text, e.g. removing new lines characters etc...
72
+ # # note that order is important here!
73
+ # token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
74
+
75
+ # for t in token_sequences_to_ignore:
76
+ # text = " ".join(text.split(t))
77
+
78
+ return text
79
+
80
+
81
+ def main(args):
82
+ # load dataset
83
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
84
+
85
+ # for testing: only process the first two examples as a test
86
+ # dataset = dataset.select(range(10))
87
+
88
+ # load processor
89
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
90
+ sampling_rate = feature_extractor.sampling_rate
91
+
92
+ # resample audio
93
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
94
+
95
+ # load eval pipeline
96
+ if args.device is None:
97
+ args.device = 0 if torch.cuda.is_available() else -1
98
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
99
+
100
+ # map function to decode audio
101
+ def map_to_pred(batch):
102
+ prediction = asr(
103
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
104
+ )
105
+
106
+ batch["prediction"] = prediction["text"]
107
+ batch["target"] = normalize_text(batch["text"])
108
+ return batch
109
+
110
+ # run inference on all examples
111
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
112
+
113
+ # compute and log_results
114
+ # do not change function below
115
+ log_results(result, args)
116
+
117
+
118
+ if __name__ == "__main__":
119
+ parser = argparse.ArgumentParser()
120
+
121
+ parser.add_argument(
122
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
123
+ )
124
+ parser.add_argument(
125
+ "--dataset",
126
+ type=str,
127
+ required=True,
128
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
129
+ )
130
+ parser.add_argument(
131
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
132
+ )
133
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
134
+ parser.add_argument(
135
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
136
+ )
137
+ parser.add_argument(
138
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
139
+ )
140
+ parser.add_argument(
141
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
142
+ )
143
+ parser.add_argument(
144
+ "--device",
145
+ type=int,
146
+ default=None,
147
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
148
+ )
149
+ args = parser.parse_args()
150
+
151
+ main(args)
eval_results.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 40.0,
3
+ "eval_loss": 0.35698655247688293,
4
+ "eval_runtime": 52.1875,
5
+ "eval_samples": 825,
6
+ "eval_samples_per_second": 15.808,
7
+ "eval_steps_per_second": 0.996,
8
+ "eval_wer": 0.21414389713529355
9
+ }
language_model/5gram.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab572020f4871ec611ad95a92071040bafe77c4633de2d26166006749e964129
3
+ size 3981756555
language_model/attrs.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"alpha": 0.5, "beta": 1.5, "unk_score_offset": -10.0, "score_boundary": true}
language_model/unigrams.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48aeb02d80e42421057e95161188779f1cdace619908c0feeab767d1cadb44cb
3
+ size 14892613
log_NbAiLab_NPSC_16K_mp3_nynorsk_test_predictions.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b98d304c7f36c039cd2e791141a6f8822405cf949216ff660d73a9d0f19390d6
3
+ size 67295
log_NbAiLab_NPSC_16K_mp3_nynorsk_test_predictions_no_lang_model.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5dcc454a467aa8b06d24b95425a90188b6426ac8fdb66086bd790b236bac0adc
3
+ size 67397
log_NbAiLab_NPSC_16K_mp3_nynorsk_test_targets.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0755805652d10110cf798b5558d40def38c504be77ea23d85c49b564214e4035
3
+ size 68478
log_NbAiLab_NPSC_16K_mp3_nynorsk_test_targets_no_lang_model.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0755805652d10110cf798b5558d40def38c504be77ea23d85c49b564214e4035
3
+ size 68478
preprocessor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "padding_side": "right",
6
+ "padding_value": 0,
7
+ "processor_class": "Wav2Vec2ProcessorWithLM",
8
+ "return_attention_mask": true,
9
+ "sampling_rate": 16000
10
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8d5d272bf5e836fcfa6de6249caafb0e0ba5f080ffcb6054fdb5b983a7b5d21
3
+ size 1262063089
run.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_ctc.py \
2
+ --dataset_name="NbAiLab/NPSC" \
3
+ --model_name_or_path="KBLab/wav2vec2-large-voxrex" \
4
+ --dataset_config_name="16K_mp3_nynorsk" \
5
+ --output_dir="./" \
6
+ --overwrite_output_dir \
7
+ --num_train_epochs="80" \
8
+ --per_device_train_batch_size="16" \
9
+ --per_device_eval_batch_size="16" \
10
+ --gradient_accumulation_steps="2" \
11
+ --learning_rate="1e-4" \
12
+ --warmup_steps="2000" \
13
+ --length_column_name="input_length" \
14
+ --evaluation_strategy="steps" \
15
+ --text_column_name="text" \
16
+ --save_steps="500" \
17
+ --eval_steps="500" \
18
+ --logging_steps="100" \
19
+ --layerdrop="0.041" \
20
+ --attention_dropout="0.094" \
21
+ --activation_dropout="0.055" \
22
+ --hidden_dropout="0.047" \
23
+ --save_total_limit="3" \
24
+ --freeze_feature_encoder \
25
+ --feat_proj_dropout="0.04" \
26
+ --mask_time_prob="0.082" \
27
+ --mask_time_length="10" \
28
+ --mask_feature_prob="0.25" \
29
+ --mask_feature_length="64" \
30
+ --gradient_checkpointing \
31
+ --min_duration_in_seconds="0.5" \
32
+ --max_duration_in_seconds="30.0" \
33
+ --use_auth_token \
34
+ --seed="42" \
35
+ --fp16 \
36
+ --group_by_length \
37
+ --do_train --do_eval \
38
+ --push_to_hub \
39
+ --preprocessing_num_workers="32"
run_speech_recognition_ctc.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 transformers
34
+ from transformers import (
35
+ AutoConfig,
36
+ AutoFeatureExtractor,
37
+ AutoModelForCTC,
38
+ AutoProcessor,
39
+ AutoTokenizer,
40
+ HfArgumentParser,
41
+ Trainer,
42
+ TrainingArguments,
43
+ Wav2Vec2Processor,
44
+ set_seed,
45
+ )
46
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
47
+ from transformers.utils import check_min_version
48
+ from transformers.utils.versions import require_version
49
+
50
+
51
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
52
+ check_min_version("4.16.0.dev0")
53
+
54
+ require_version("datasets>=1.13.3", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ def list_field(default=None, metadata=None):
61
+ return field(default_factory=lambda: default, metadata=metadata)
62
+
63
+
64
+ @dataclass
65
+ class ModelArguments:
66
+ """
67
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
68
+ """
69
+
70
+ model_name_or_path: str = field(
71
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
72
+ )
73
+ tokenizer_name_or_path: Optional[str] = field(
74
+ default=None,
75
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
76
+ )
77
+ cache_dir: Optional[str] = field(
78
+ default=None,
79
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
80
+ )
81
+ freeze_feature_encoder: bool = field(
82
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
83
+ )
84
+ attention_dropout: float = field(
85
+ default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
86
+ )
87
+ activation_dropout: float = field(
88
+ default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
89
+ )
90
+ feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
91
+ hidden_dropout: float = field(
92
+ default=0.0,
93
+ metadata={
94
+ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
95
+ },
96
+ )
97
+ final_dropout: float = field(
98
+ default=0.0,
99
+ metadata={"help": "The dropout probability for the final projection layer."},
100
+ )
101
+ mask_time_prob: float = field(
102
+ default=0.05,
103
+ metadata={
104
+ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
105
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
106
+ "vectors will be masked along the time axis."
107
+ },
108
+ )
109
+ mask_time_length: int = field(
110
+ default=10,
111
+ metadata={"help": "Length of vector span to mask along the time axis."},
112
+ )
113
+ mask_feature_prob: float = field(
114
+ default=0.0,
115
+ metadata={
116
+ "help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
117
+ "span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
118
+ },
119
+ )
120
+ mask_feature_length: int = field(
121
+ default=10,
122
+ metadata={"help": "Length of vector span to mask along the feature axis."},
123
+ )
124
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
125
+ ctc_loss_reduction: Optional[str] = field(
126
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
127
+ )
128
+ ctc_zero_infinity: Optional[bool] = field(
129
+ default=False, metadata={"help": "If True, will try yo aboud the CTC loss goinf to infinity."}
130
+ )
131
+
132
+ @dataclass
133
+ class DataTrainingArguments:
134
+ """
135
+ Arguments pertaining to what data we are going to input our model for training and eval.
136
+
137
+ Using `HfArgumentParser` we can turn this class
138
+ into argparse arguments to be able to specify them on
139
+ the command line.
140
+ """
141
+
142
+ dataset_name: str = field(
143
+ metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
144
+ )
145
+ dataset_config_name: str = field(
146
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
147
+ )
148
+ train_split_name: str = field(
149
+ default="train+validation",
150
+ metadata={
151
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
152
+ },
153
+ )
154
+ eval_split_name: str = field(
155
+ default="test",
156
+ metadata={
157
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
158
+ },
159
+ )
160
+ audio_column_name: str = field(
161
+ default="audio",
162
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
163
+ )
164
+ text_column_name: str = field(
165
+ default="text",
166
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
167
+ )
168
+ overwrite_cache: bool = field(
169
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
170
+ )
171
+ preprocessing_num_workers: Optional[int] = field(
172
+ default=None,
173
+ metadata={"help": "The number of processes to use for the preprocessing."},
174
+ )
175
+ max_train_samples: Optional[int] = field(
176
+ default=None,
177
+ metadata={
178
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
179
+ "value if set."
180
+ },
181
+ )
182
+ max_eval_samples: Optional[int] = field(
183
+ default=None,
184
+ metadata={
185
+ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
186
+ "value if set."
187
+ },
188
+ )
189
+ chars_to_ignore: Optional[List[str]] = list_field(
190
+ default=None,
191
+ metadata={"help": "A list of characters to remove from the transcripts."},
192
+ )
193
+ eval_metrics: List[str] = list_field(
194
+ default=["wer"],
195
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
196
+ )
197
+ max_duration_in_seconds: float = field(
198
+ default=20.0,
199
+ metadata={
200
+ "help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
201
+ },
202
+ )
203
+ min_duration_in_seconds: float = field(
204
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
205
+ )
206
+ preprocessing_only: bool = field(
207
+ default=False,
208
+ metadata={
209
+ "help": "Whether to only do data preprocessing and skip training. "
210
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
211
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
212
+ "so that the cached datasets can consequently be loaded in distributed training"
213
+ },
214
+ )
215
+ use_auth_token: bool = field(
216
+ default=False,
217
+ metadata={
218
+ "help": "If :obj:`True`, will use the token generated when running"
219
+ ":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
220
+ },
221
+ )
222
+ unk_token: str = field(
223
+ default="[UNK]",
224
+ metadata={"help": "The unk token for the tokenizer"},
225
+ )
226
+ pad_token: str = field(
227
+ default="[PAD]",
228
+ metadata={"help": "The padding token for the tokenizer"},
229
+ )
230
+ word_delimiter_token: str = field(
231
+ default="|",
232
+ metadata={"help": "The word delimiter token for the tokenizer"},
233
+ )
234
+ phoneme_language: Optional[str] = field(
235
+ default=None,
236
+ metadata={
237
+ "help": "The target language that should be used be"
238
+ " passed to the tokenizer for tokenization. Note that"
239
+ " this is only relevant if the model classifies the"
240
+ " input audio to a sequence of phoneme sequences."
241
+ },
242
+ )
243
+
244
+
245
+ @dataclass
246
+ class DataCollatorCTCWithPadding:
247
+ """
248
+ Data collator that will dynamically pad the inputs received.
249
+ Args:
250
+ processor (:class:`~transformers.AutoProcessor`)
251
+ The processor used for proccessing the data.
252
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
253
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
254
+ among:
255
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
256
+ sequence if provided).
257
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
258
+ maximum acceptable input length for the model if that argument is not provided.
259
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
260
+ different lengths).
261
+ max_length (:obj:`int`, `optional`):
262
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
263
+ max_length_labels (:obj:`int`, `optional`):
264
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
265
+ pad_to_multiple_of (:obj:`int`, `optional`):
266
+ If set will pad the sequence to a multiple of the provided value.
267
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
268
+ 7.5 (Volta).
269
+ """
270
+
271
+ processor: AutoProcessor
272
+ padding: Union[bool, str] = "longest"
273
+ pad_to_multiple_of: Optional[int] = None
274
+ pad_to_multiple_of_labels: Optional[int] = None
275
+
276
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
277
+ # split inputs and labels since they have to be of different lenghts and need
278
+ # different padding methods
279
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
280
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
281
+
282
+ batch = self.processor.pad(
283
+ input_features,
284
+ padding=self.padding,
285
+ pad_to_multiple_of=self.pad_to_multiple_of,
286
+ return_tensors="pt",
287
+ )
288
+
289
+ with self.processor.as_target_processor():
290
+ labels_batch = self.processor.pad(
291
+ label_features,
292
+ padding=self.padding,
293
+ pad_to_multiple_of=self.pad_to_multiple_of_labels,
294
+ return_tensors="pt",
295
+ )
296
+
297
+ # replace padding with -100 to ignore loss correctly
298
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
299
+
300
+ batch["labels"] = labels
301
+
302
+ return batch
303
+
304
+
305
+ def create_vocabulary_from_data(
306
+ datasets: DatasetDict,
307
+ word_delimiter_token: Optional[str] = None,
308
+ unk_token: Optional[str] = None,
309
+ pad_token: Optional[str] = None,
310
+ ):
311
+ # Given training and test labels create vocabulary
312
+ def extract_all_chars(batch):
313
+ all_text = " ".join(batch["target_text"])
314
+ vocab = list(set(all_text))
315
+ return {"vocab": [vocab], "all_text": [all_text]}
316
+
317
+ vocabs = datasets.map(
318
+ extract_all_chars,
319
+ batched=True,
320
+ batch_size=-1,
321
+ keep_in_memory=True,
322
+ remove_columns=datasets["train"].column_names,
323
+ )
324
+
325
+ # take union of all unique characters in each dataset
326
+ vocab_set = functools.reduce(
327
+ lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values()
328
+ )
329
+
330
+ vocab_dict = {v: k for k, v in enumerate(sorted(list(vocab_set)))}
331
+
332
+ # replace white space with delimiter token
333
+ if word_delimiter_token is not None:
334
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
335
+ del vocab_dict[" "]
336
+
337
+ # add unk and pad token
338
+ if unk_token is not None:
339
+ vocab_dict[unk_token] = len(vocab_dict)
340
+
341
+ if pad_token is not None:
342
+ vocab_dict[pad_token] = len(vocab_dict)
343
+
344
+ return vocab_dict
345
+
346
+
347
+ def main():
348
+ # See all possible arguments in src/transformers/training_args.py
349
+ # or by passing the --help flag to this script.
350
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
351
+
352
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
353
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
354
+ # If we pass only one argument to the script and it's the path to a json file,
355
+ # let's parse it to get our arguments.
356
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
357
+ else:
358
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
359
+
360
+ # Detecting last checkpoint.
361
+ last_checkpoint = None
362
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
363
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
364
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
365
+ raise ValueError(
366
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
367
+ "Use --overwrite_output_dir to overcome."
368
+ )
369
+ elif last_checkpoint is not None:
370
+ logger.info(
371
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
372
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
373
+ )
374
+
375
+ # Setup logging
376
+ logging.basicConfig(
377
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
378
+ datefmt="%m/%d/%Y %H:%M:%S",
379
+ handlers=[logging.StreamHandler(sys.stdout)],
380
+ )
381
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
382
+
383
+ # Log on each process the small summary:
384
+ logger.warning(
385
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
386
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
387
+ )
388
+ # Set the verbosity to info of the Transformers logger (on main process only):
389
+ if is_main_process(training_args.local_rank):
390
+ transformers.utils.logging.set_verbosity_info()
391
+ logger.info("Training/evaluation parameters %s", training_args)
392
+
393
+ # Set seed before initializing model.
394
+ set_seed(training_args.seed)
395
+
396
+ # Pre-processing dataset
397
+ import re
398
+ def filter_numeric(entry):
399
+ return (
400
+ "0" not in entry["text"]
401
+ and "1" not in entry["text"]
402
+ and "2" not in entry["text"]
403
+ and "3" not in entry["text"]
404
+ and "4" not in entry["text"]
405
+ and "5" not in entry["text"]
406
+ and "6" not in entry["text"]
407
+ and "7" not in entry["text"]
408
+ and "8" not in entry["text"]
409
+ and "9" not in entry["text"]
410
+ )
411
+
412
+ #def filter_inaudible(entry):
413
+ # return not re.search("\d|<inaudible>", entry["text"], flags=re.IGNORECASE)
414
+ #
415
+ #def filter_nynorsk(entry):
416
+ # return re.search("nn-no", entry["sentence_language_code"], flags=re.IGNORECASE)
417
+
418
+ def filter_tooshort(entry):
419
+ #print(f"The audio sample ({entry["audio"]["path"]}) is too small, and has been omitted. "
420
+ return (len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)
421
+
422
+ def map_dataset(entry):
423
+ batch = {"text": entry["text"].lower()}
424
+ batch["text"] = re.sub('[áàâ]', 'a', batch["text"])
425
+ batch["text"] = re.sub('[ä]', 'æ', batch["text"])
426
+ batch["text"] = re.sub('[éèëê]', 'e', batch["text"])
427
+ batch["text"] = re.sub('[íìïî]', 'i', batch["text"])
428
+ batch["text"] = re.sub('[óòöô]', 'o', batch["text"])
429
+ batch["text"] = re.sub('[ö]', 'ø', batch["text"])
430
+ batch["text"] = re.sub('[ç]', 'c', batch["text"])
431
+ batch["text"] = re.sub('[úùüû]', 'u', batch["text"])
432
+ batch["text"] = re.sub('\s', ' ', batch["text"])
433
+ batch["text"] = re.sub('<ee>', 'eee', batch["text"])
434
+ batch["text"] = re.sub('<qq>', 'qqq', batch["text"])
435
+ batch["text"] = re.sub('<mm>', 'mmm', batch["text"])
436
+ batch["text"] = re.sub('<inaudible>', 'xxx', batch["text"])
437
+ # batch["text"] = re.sub('<inaudible>', '?', batch["text"])
438
+ if "<" in batch["text"]:
439
+ raise ValueError(batch["text"])
440
+ return batch
441
+
442
+ # 1. First, let's load the dataset
443
+ raw_datasets = DatasetDict()
444
+
445
+ if training_args.do_train:
446
+ raw_datasets["train"] = load_dataset(
447
+ data_args.dataset_name,
448
+ data_args.dataset_config_name,
449
+ split=data_args.train_split_name,
450
+ use_auth_token=data_args.use_auth_token,
451
+ ).shuffle()
452
+ raw_datasets["train"] = raw_datasets["train"].filter(filter_numeric).filter(filter_tooshort)
453
+ raw_datasets["train"] = raw_datasets["train"].map(map_dataset)
454
+
455
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
456
+ raise ValueError(
457
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
458
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
459
+ f"{', '.join(raw_datasets['train'].column_names)}."
460
+ )
461
+
462
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
463
+ raise ValueError(
464
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
465
+ "Make sure to set `--text_column_name` to the correct text column - one of "
466
+ f"{', '.join(raw_datasets['train'].column_names)}."
467
+ )
468
+
469
+ if data_args.max_train_samples is not None:
470
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
471
+
472
+ if training_args.do_eval:
473
+ raw_datasets["eval"] = load_dataset(
474
+ data_args.dataset_name,
475
+ data_args.dataset_config_name,
476
+ split=data_args.eval_split_name,
477
+ use_auth_token=data_args.use_auth_token,
478
+ ).shuffle()
479
+ raw_datasets["eval"] = raw_datasets["eval"].filter(filter_numeric).filter(filter_tooshort)
480
+ raw_datasets["eval"] = raw_datasets["eval"].map(map_dataset)
481
+
482
+ if data_args.max_eval_samples is not None:
483
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
484
+
485
+
486
+ # 2. We remove some special characters from the datasets
487
+ # that make training complicated and do not help in transcribing the speech
488
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
489
+ # that could be easily picked up by the model
490
+ #chars_to_ignore_regex = (
491
+ # f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
492
+ #)
493
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
494
+
495
+ text_column_name = data_args.text_column_name
496
+
497
+ def remove_special_characters(batch):
498
+ if chars_to_ignore_regex is not None:
499
+ batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
500
+ else:
501
+ batch["target_text"] = batch[text_column_name].lower() + " "
502
+ return batch
503
+
504
+ with training_args.main_process_first(desc="dataset map special characters removal"):
505
+ raw_datasets = raw_datasets.map(
506
+ remove_special_characters,
507
+ remove_columns=[text_column_name],
508
+ desc="remove special characters from datasets",
509
+ )
510
+
511
+ # save special tokens for tokenizer
512
+ word_delimiter_token = data_args.word_delimiter_token
513
+ unk_token = data_args.unk_token
514
+ pad_token = data_args.pad_token
515
+
516
+ # 3. Next, let's load the config as we might need it to create
517
+ # the tokenizer
518
+ # load config
519
+ config = AutoConfig.from_pretrained(
520
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
521
+ )
522
+
523
+ # 4. Next, if no tokenizer file is defined,
524
+ # we create the vocabulary of the model by extracting all unique characters from
525
+ # the training and evaluation datasets
526
+ # We need to make sure that only first rank saves vocabulary
527
+ # make sure all processes wait until vocab is created
528
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
529
+ tokenizer_kwargs = {}
530
+ if tokenizer_name_or_path is None:
531
+ # save vocab in training output dir
532
+ tokenizer_name_or_path = training_args.output_dir
533
+
534
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
535
+
536
+ with training_args.main_process_first():
537
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
538
+ os.remove(vocab_file)
539
+
540
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
541
+ if not os.path.isfile(vocab_file):
542
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
543
+ vocab_dict = create_vocabulary_from_data(
544
+ raw_datasets,
545
+ word_delimiter_token=word_delimiter_token,
546
+ unk_token=unk_token,
547
+ pad_token=pad_token,
548
+ )
549
+
550
+ # save vocab dict to be loaded into tokenizer
551
+ with open(vocab_file, "w") as file:
552
+ json.dump(vocab_dict, file)
553
+
554
+ # if tokenizer has just been created
555
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
556
+ tokenizer_kwargs = {
557
+ "config": config if config.tokenizer_class is not None else None,
558
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
559
+ "unk_token": unk_token,
560
+ "pad_token": pad_token,
561
+ "word_delimiter_token": word_delimiter_token,
562
+ }
563
+
564
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
565
+ # Note for distributed training, the .from_pretrained methods guarantee that only
566
+ # one local process can concurrently download model & vocab.
567
+
568
+ # load feature_extractor and tokenizer
569
+ tokenizer = AutoTokenizer.from_pretrained(
570
+ tokenizer_name_or_path,
571
+ use_auth_token=data_args.use_auth_token,
572
+ **tokenizer_kwargs,
573
+ )
574
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
575
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
576
+ )
577
+
578
+ # adapt config
579
+ config.update(
580
+ {
581
+ "feat_proj_dropout": model_args.feat_proj_dropout,
582
+ "attention_dropout": model_args.attention_dropout,
583
+ "hidden_dropout": model_args.hidden_dropout,
584
+ "final_dropout": model_args.final_dropout,
585
+ "mask_time_prob": model_args.mask_time_prob,
586
+ "mask_time_length": model_args.mask_time_length,
587
+ "mask_feature_prob": model_args.mask_feature_prob,
588
+ "mask_feature_length": model_args.mask_feature_length,
589
+ "gradient_checkpointing": training_args.gradient_checkpointing,
590
+ "layerdrop": model_args.layerdrop,
591
+ "ctc_loss_reduction": model_args.ctc_loss_reduction,
592
+ "ctc_zero_infinity": model_args.ctc_zero_infinity,
593
+ "pad_token_id": tokenizer.pad_token_id,
594
+ "vocab_size": len(tokenizer),
595
+ "activation_dropout": model_args.activation_dropout,
596
+ }
597
+ )
598
+
599
+ # create model
600
+ model = AutoModelForCTC.from_pretrained(
601
+ model_args.model_name_or_path,
602
+ cache_dir=model_args.cache_dir,
603
+ config=config,
604
+ use_auth_token=data_args.use_auth_token,
605
+ )
606
+
607
+ # freeze encoder
608
+ if model_args.freeze_feature_encoder:
609
+ model.freeze_feature_encoder()
610
+
611
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
612
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
613
+ # so that we just need to set the correct target sampling rate and normalize the input
614
+ # via the `feature_extractor`
615
+
616
+ # make sure that dataset decodes audio with correct sampling rate
617
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
618
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
619
+ raw_datasets = raw_datasets.cast_column(
620
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
621
+ )
622
+
623
+ # derive max & min input length for sample rate & max duration
624
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
625
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
626
+ audio_column_name = data_args.audio_column_name
627
+ num_workers = data_args.preprocessing_num_workers
628
+
629
+ # `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
630
+ phoneme_language = data_args.phoneme_language
631
+
632
+ # Preprocessing the datasets.
633
+ # We need to read the audio files as arrays and tokenize the targets.
634
+ def prepare_dataset(batch):
635
+ # load audio
636
+ sample = batch[audio_column_name]
637
+
638
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
639
+ batch["input_values"] = inputs.input_values[0]
640
+ batch["input_length"] = len(batch["input_values"])
641
+
642
+ # encode targets
643
+ additional_kwargs = {}
644
+ if phoneme_language is not None:
645
+ additional_kwargs["phonemizer_lang"] = phoneme_language
646
+
647
+ batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
648
+ return batch
649
+
650
+ with training_args.main_process_first(desc="dataset map preprocessing"):
651
+ vectorized_datasets = raw_datasets.map(
652
+ prepare_dataset,
653
+ remove_columns=next(iter(raw_datasets.values())).column_names,
654
+ num_proc=num_workers,
655
+ desc="preprocess datasets",
656
+ )
657
+
658
+ def is_audio_in_length_range(length):
659
+ return length > min_input_length and length < max_input_length
660
+
661
+ # filter data that is shorter than min_input_length
662
+ vectorized_datasets = vectorized_datasets.filter(
663
+ is_audio_in_length_range,
664
+ num_proc=num_workers,
665
+ input_columns=["input_length"],
666
+ )
667
+
668
+ # 7. Next, we can prepare the training.
669
+ # Let's use word error rate (WER) as our evaluation metric,
670
+ # instantiate a data collator and the trainer
671
+
672
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
673
+ eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}
674
+
675
+ # for large datasets it is advised to run the preprocessing on a
676
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
677
+ # be a timeout when running the script in distributed mode.
678
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
679
+ # cached dataset
680
+ if data_args.preprocessing_only:
681
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
682
+ return
683
+
684
+ def compute_metrics(pred):
685
+ pred_logits = pred.predictions
686
+ pred_ids = np.argmax(pred_logits, axis=-1)
687
+
688
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
689
+
690
+ pred_str = tokenizer.batch_decode(pred_ids)
691
+ # we do not want to group tokens when computing the metrics
692
+ label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
693
+
694
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
695
+
696
+ return metrics
697
+
698
+ # Now save everything to be able to create a single processor later
699
+ if is_main_process(training_args.local_rank):
700
+ # save feature extractor, tokenizer and config
701
+ feature_extractor.save_pretrained(training_args.output_dir)
702
+ tokenizer.save_pretrained(training_args.output_dir)
703
+ config.save_pretrained(training_args.output_dir)
704
+
705
+ try:
706
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
707
+ except (OSError, KeyError):
708
+ warnings.warn(
709
+ "Loading a processor from a feature extractor config that does not"
710
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
711
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
712
+ " `'processor_class': 'Wav2Vec2Processor'`",
713
+ FutureWarning,
714
+ )
715
+ processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
716
+
717
+ # Instantiate custom data collator
718
+ data_collator = DataCollatorCTCWithPadding(processor=processor)
719
+
720
+ # Initialize Trainer
721
+ trainer = Trainer(
722
+ model=model,
723
+ data_collator=data_collator,
724
+ args=training_args,
725
+ compute_metrics=compute_metrics,
726
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
727
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
728
+ tokenizer=feature_extractor,
729
+ )
730
+
731
+ # 8. Finally, we can start training
732
+
733
+ # Training
734
+ if training_args.do_train:
735
+
736
+ # use last checkpoint if exist
737
+ if last_checkpoint is not None:
738
+ checkpoint = last_checkpoint
739
+ elif os.path.isdir(model_args.model_name_or_path):
740
+ checkpoint = model_args.model_name_or_path
741
+ else:
742
+ checkpoint = None
743
+
744
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
745
+ trainer.save_model()
746
+
747
+ metrics = train_result.metrics
748
+ max_train_samples = (
749
+ data_args.max_train_samples
750
+ if data_args.max_train_samples is not None
751
+ else len(vectorized_datasets["train"])
752
+ )
753
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
754
+
755
+ trainer.log_metrics("train", metrics)
756
+ trainer.save_metrics("train", metrics)
757
+ trainer.save_state()
758
+
759
+ # Evaluation
760
+ results = {}
761
+ if training_args.do_eval:
762
+ logger.info("*** Evaluate ***")
763
+ metrics = trainer.evaluate()
764
+ max_eval_samples = (
765
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
766
+ )
767
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
768
+
769
+ trainer.log_metrics("eval", metrics)
770
+ trainer.save_metrics("eval", metrics)
771
+
772
+ # Write model card and (optionally) push to hub
773
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
774
+ kwargs = {
775
+ "finetuned_from": model_args.model_name_or_path,
776
+ "tasks": "speech-recognition",
777
+ "tags": ["automatic-speech-recognition", data_args.dataset_name],
778
+ "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
779
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
780
+ }
781
+ if "common_voice" in data_args.dataset_name:
782
+ kwargs["language"] = config_name
783
+
784
+ if training_args.push_to_hub:
785
+ trainer.push_to_hub(**kwargs)
786
+ else:
787
+ trainer.create_model_card(**kwargs)
788
+
789
+ return results
790
+
791
+
792
+ if __name__ == "__main__":
793
+ main()
runs/Feb05_15-59-35_dante/1644073207.5513232/events.out.tfevents.1644073207.dante.2625060.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:362da1f3278e08c8d2885e51c17415f55316029cb4db2b1a674844b79d1f8ad0
3
+ size 4756
runs/Feb05_15-59-35_dante/events.out.tfevents.1644073207.dante.2625060.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:609a294ed52ebef007124dbb2231bcbce9e7219085c29d846fac7e37b72d50e4
3
+ size 46177
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "[UNK]", "pad_token": "[PAD]", "additional_special_tokens": [{"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}]}
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "bos_token": "<s>", "eos_token": "</s>", "pad_token": "[PAD]", "do_lower_case": false, "word_delimiter_token": "|", "special_tokens_map_file": null, "tokenizer_file": null, "name_or_path": "./", "tokenizer_class": "Wav2Vec2CTCTokenizer", "processor_class": "Wav2Vec2ProcessorWithLM"}
train_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 40.0,
3
+ "train_loss": 0.896209309619406,
4
+ "train_runtime": 25745.3803,
5
+ "train_samples": 7354,
6
+ "train_samples_per_second": 11.426,
7
+ "train_steps_per_second": 0.357
8
+ }
trainer_state.json ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 40.0,
5
+ "global_step": 9200,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 0.43,
12
+ "learning_rate": 3.675e-06,
13
+ "loss": 10.3748,
14
+ "step": 100
15
+ },
16
+ {
17
+ "epoch": 0.87,
18
+ "learning_rate": 7.35e-06,
19
+ "loss": 9.8141,
20
+ "step": 200
21
+ },
22
+ {
23
+ "epoch": 1.3,
24
+ "learning_rate": 1.1099999999999999e-05,
25
+ "loss": 5.6549,
26
+ "step": 300
27
+ },
28
+ {
29
+ "epoch": 1.74,
30
+ "learning_rate": 1.485e-05,
31
+ "loss": 3.4055,
32
+ "step": 400
33
+ },
34
+ {
35
+ "epoch": 2.17,
36
+ "learning_rate": 1.8599999999999998e-05,
37
+ "loss": 3.086,
38
+ "step": 500
39
+ },
40
+ {
41
+ "epoch": 2.17,
42
+ "eval_loss": 3.0773141384124756,
43
+ "eval_runtime": 54.4742,
44
+ "eval_samples_per_second": 15.145,
45
+ "eval_steps_per_second": 0.955,
46
+ "eval_wer": 1.0,
47
+ "step": 500
48
+ },
49
+ {
50
+ "epoch": 2.61,
51
+ "learning_rate": 2.2349999999999998e-05,
52
+ "loss": 2.9844,
53
+ "step": 600
54
+ },
55
+ {
56
+ "epoch": 3.04,
57
+ "learning_rate": 2.6099999999999997e-05,
58
+ "loss": 2.957,
59
+ "step": 700
60
+ },
61
+ {
62
+ "epoch": 3.48,
63
+ "learning_rate": 2.985e-05,
64
+ "loss": 2.912,
65
+ "step": 800
66
+ },
67
+ {
68
+ "epoch": 3.91,
69
+ "learning_rate": 3.36e-05,
70
+ "loss": 2.8929,
71
+ "step": 900
72
+ },
73
+ {
74
+ "epoch": 4.35,
75
+ "learning_rate": 3.735e-05,
76
+ "loss": 2.8532,
77
+ "step": 1000
78
+ },
79
+ {
80
+ "epoch": 4.35,
81
+ "eval_loss": 2.839279890060425,
82
+ "eval_runtime": 54.2914,
83
+ "eval_samples_per_second": 15.196,
84
+ "eval_steps_per_second": 0.958,
85
+ "eval_wer": 1.0,
86
+ "step": 1000
87
+ },
88
+ {
89
+ "epoch": 4.78,
90
+ "learning_rate": 4.11e-05,
91
+ "loss": 2.595,
92
+ "step": 1100
93
+ },
94
+ {
95
+ "epoch": 5.22,
96
+ "learning_rate": 4.484999999999999e-05,
97
+ "loss": 1.9229,
98
+ "step": 1200
99
+ },
100
+ {
101
+ "epoch": 5.65,
102
+ "learning_rate": 4.8599999999999995e-05,
103
+ "loss": 1.3521,
104
+ "step": 1300
105
+ },
106
+ {
107
+ "epoch": 6.09,
108
+ "learning_rate": 5.234999999999999e-05,
109
+ "loss": 1.0772,
110
+ "step": 1400
111
+ },
112
+ {
113
+ "epoch": 6.52,
114
+ "learning_rate": 5.6099999999999995e-05,
115
+ "loss": 0.9738,
116
+ "step": 1500
117
+ },
118
+ {
119
+ "epoch": 6.52,
120
+ "eval_loss": 0.728294849395752,
121
+ "eval_runtime": 54.3803,
122
+ "eval_samples_per_second": 15.171,
123
+ "eval_steps_per_second": 0.956,
124
+ "eval_wer": 0.4889855346506571,
125
+ "step": 1500
126
+ },
127
+ {
128
+ "epoch": 6.96,
129
+ "learning_rate": 5.985e-05,
130
+ "loss": 0.891,
131
+ "step": 1600
132
+ },
133
+ {
134
+ "epoch": 7.39,
135
+ "learning_rate": 6.359999999999999e-05,
136
+ "loss": 0.7848,
137
+ "step": 1700
138
+ },
139
+ {
140
+ "epoch": 7.83,
141
+ "learning_rate": 6.735e-05,
142
+ "loss": 0.7527,
143
+ "step": 1800
144
+ },
145
+ {
146
+ "epoch": 8.26,
147
+ "learning_rate": 7.11e-05,
148
+ "loss": 0.7279,
149
+ "step": 1900
150
+ },
151
+ {
152
+ "epoch": 8.7,
153
+ "learning_rate": 7.484999999999999e-05,
154
+ "loss": 0.6763,
155
+ "step": 2000
156
+ },
157
+ {
158
+ "epoch": 8.7,
159
+ "eval_loss": 0.5340386033058167,
160
+ "eval_runtime": 53.7943,
161
+ "eval_samples_per_second": 15.336,
162
+ "eval_steps_per_second": 0.967,
163
+ "eval_wer": 0.36617188238630993,
164
+ "step": 2000
165
+ },
166
+ {
167
+ "epoch": 9.13,
168
+ "learning_rate": 7.4e-05,
169
+ "loss": 0.6165,
170
+ "step": 2100
171
+ },
172
+ {
173
+ "epoch": 9.57,
174
+ "learning_rate": 7.295833333333332e-05,
175
+ "loss": 0.6021,
176
+ "step": 2200
177
+ },
178
+ {
179
+ "epoch": 10.0,
180
+ "learning_rate": 7.191666666666666e-05,
181
+ "loss": 0.5904,
182
+ "step": 2300
183
+ },
184
+ {
185
+ "epoch": 10.43,
186
+ "learning_rate": 7.087499999999999e-05,
187
+ "loss": 0.5469,
188
+ "step": 2400
189
+ },
190
+ {
191
+ "epoch": 10.87,
192
+ "learning_rate": 6.983333333333333e-05,
193
+ "loss": 0.5303,
194
+ "step": 2500
195
+ },
196
+ {
197
+ "epoch": 10.87,
198
+ "eval_loss": 0.45213818550109863,
199
+ "eval_runtime": 53.7095,
200
+ "eval_samples_per_second": 15.36,
201
+ "eval_steps_per_second": 0.968,
202
+ "eval_wer": 0.31398317103148343,
203
+ "step": 2500
204
+ },
205
+ {
206
+ "epoch": 11.3,
207
+ "learning_rate": 6.879166666666667e-05,
208
+ "loss": 0.5061,
209
+ "step": 2600
210
+ },
211
+ {
212
+ "epoch": 11.74,
213
+ "learning_rate": 6.775e-05,
214
+ "loss": 0.4928,
215
+ "step": 2700
216
+ },
217
+ {
218
+ "epoch": 12.17,
219
+ "learning_rate": 6.670833333333333e-05,
220
+ "loss": 0.4693,
221
+ "step": 2800
222
+ },
223
+ {
224
+ "epoch": 12.61,
225
+ "learning_rate": 6.566666666666666e-05,
226
+ "loss": 0.4733,
227
+ "step": 2900
228
+ },
229
+ {
230
+ "epoch": 13.04,
231
+ "learning_rate": 6.4625e-05,
232
+ "loss": 0.4765,
233
+ "step": 3000
234
+ },
235
+ {
236
+ "epoch": 13.04,
237
+ "eval_loss": 0.4181167483329773,
238
+ "eval_runtime": 53.0777,
239
+ "eval_samples_per_second": 15.543,
240
+ "eval_steps_per_second": 0.98,
241
+ "eval_wer": 0.2853361066464971,
242
+ "step": 3000
243
+ },
244
+ {
245
+ "epoch": 13.48,
246
+ "learning_rate": 6.358333333333332e-05,
247
+ "loss": 0.4396,
248
+ "step": 3100
249
+ },
250
+ {
251
+ "epoch": 13.91,
252
+ "learning_rate": 6.254166666666666e-05,
253
+ "loss": 0.4359,
254
+ "step": 3200
255
+ },
256
+ {
257
+ "epoch": 14.35,
258
+ "learning_rate": 6.149999999999999e-05,
259
+ "loss": 0.4173,
260
+ "step": 3300
261
+ },
262
+ {
263
+ "epoch": 14.78,
264
+ "learning_rate": 6.045833333333333e-05,
265
+ "loss": 0.408,
266
+ "step": 3400
267
+ },
268
+ {
269
+ "epoch": 15.22,
270
+ "learning_rate": 5.941666666666666e-05,
271
+ "loss": 0.4219,
272
+ "step": 3500
273
+ },
274
+ {
275
+ "epoch": 15.22,
276
+ "eval_loss": 0.41555172204971313,
277
+ "eval_runtime": 52.8273,
278
+ "eval_samples_per_second": 15.617,
279
+ "eval_steps_per_second": 0.984,
280
+ "eval_wer": 0.2933724118370048,
281
+ "step": 3500
282
+ },
283
+ {
284
+ "epoch": 15.65,
285
+ "learning_rate": 5.8374999999999996e-05,
286
+ "loss": 0.4022,
287
+ "step": 3600
288
+ },
289
+ {
290
+ "epoch": 16.09,
291
+ "learning_rate": 5.733333333333333e-05,
292
+ "loss": 0.3932,
293
+ "step": 3700
294
+ },
295
+ {
296
+ "epoch": 16.52,
297
+ "learning_rate": 5.629166666666666e-05,
298
+ "loss": 0.374,
299
+ "step": 3800
300
+ },
301
+ {
302
+ "epoch": 16.96,
303
+ "learning_rate": 5.5249999999999994e-05,
304
+ "loss": 0.3697,
305
+ "step": 3900
306
+ },
307
+ {
308
+ "epoch": 17.39,
309
+ "learning_rate": 5.420833333333333e-05,
310
+ "loss": 0.3564,
311
+ "step": 4000
312
+ },
313
+ {
314
+ "epoch": 17.39,
315
+ "eval_loss": 0.3925444483757019,
316
+ "eval_runtime": 54.1337,
317
+ "eval_samples_per_second": 15.24,
318
+ "eval_steps_per_second": 0.961,
319
+ "eval_wer": 0.2509218114777347,
320
+ "step": 4000
321
+ },
322
+ {
323
+ "epoch": 17.83,
324
+ "learning_rate": 5.316666666666666e-05,
325
+ "loss": 0.3784,
326
+ "step": 4100
327
+ },
328
+ {
329
+ "epoch": 18.26,
330
+ "learning_rate": 5.212499999999999e-05,
331
+ "loss": 0.3805,
332
+ "step": 4200
333
+ },
334
+ {
335
+ "epoch": 18.7,
336
+ "learning_rate": 5.1083333333333326e-05,
337
+ "loss": 0.3419,
338
+ "step": 4300
339
+ },
340
+ {
341
+ "epoch": 19.13,
342
+ "learning_rate": 5.0041666666666666e-05,
343
+ "loss": 0.3344,
344
+ "step": 4400
345
+ },
346
+ {
347
+ "epoch": 19.57,
348
+ "learning_rate": 4.899999999999999e-05,
349
+ "loss": 0.3282,
350
+ "step": 4500
351
+ },
352
+ {
353
+ "epoch": 19.57,
354
+ "eval_loss": 0.3824474811553955,
355
+ "eval_runtime": 54.4571,
356
+ "eval_samples_per_second": 15.15,
357
+ "eval_steps_per_second": 0.955,
358
+ "eval_wer": 0.24203460338470265,
359
+ "step": 4500
360
+ },
361
+ {
362
+ "epoch": 20.0,
363
+ "learning_rate": 4.795833333333333e-05,
364
+ "loss": 0.3447,
365
+ "step": 4600
366
+ },
367
+ {
368
+ "epoch": 20.43,
369
+ "learning_rate": 4.691666666666666e-05,
370
+ "loss": 0.3308,
371
+ "step": 4700
372
+ },
373
+ {
374
+ "epoch": 20.87,
375
+ "learning_rate": 4.5875e-05,
376
+ "loss": 0.3056,
377
+ "step": 4800
378
+ },
379
+ {
380
+ "epoch": 21.3,
381
+ "learning_rate": 4.483333333333333e-05,
382
+ "loss": 0.3069,
383
+ "step": 4900
384
+ },
385
+ {
386
+ "epoch": 21.74,
387
+ "learning_rate": 4.379166666666666e-05,
388
+ "loss": 0.3118,
389
+ "step": 5000
390
+ },
391
+ {
392
+ "epoch": 21.74,
393
+ "eval_loss": 0.36364665627479553,
394
+ "eval_runtime": 52.4627,
395
+ "eval_samples_per_second": 15.725,
396
+ "eval_steps_per_second": 0.991,
397
+ "eval_wer": 0.2354164696984022,
398
+ "step": 5000
399
+ },
400
+ {
401
+ "epoch": 22.17,
402
+ "learning_rate": 4.2749999999999996e-05,
403
+ "loss": 0.3108,
404
+ "step": 5100
405
+ },
406
+ {
407
+ "epoch": 22.61,
408
+ "learning_rate": 4.170833333333333e-05,
409
+ "loss": 0.3034,
410
+ "step": 5200
411
+ },
412
+ {
413
+ "epoch": 23.04,
414
+ "learning_rate": 4.066666666666667e-05,
415
+ "loss": 0.3132,
416
+ "step": 5300
417
+ },
418
+ {
419
+ "epoch": 23.48,
420
+ "learning_rate": 3.9624999999999994e-05,
421
+ "loss": 0.3024,
422
+ "step": 5400
423
+ },
424
+ {
425
+ "epoch": 23.91,
426
+ "learning_rate": 3.8583333333333334e-05,
427
+ "loss": 0.2919,
428
+ "step": 5500
429
+ },
430
+ {
431
+ "epoch": 23.91,
432
+ "eval_loss": 0.3614845275878906,
433
+ "eval_runtime": 52.502,
434
+ "eval_samples_per_second": 15.714,
435
+ "eval_steps_per_second": 0.99,
436
+ "eval_wer": 0.22813652264347167,
437
+ "step": 5500
438
+ },
439
+ {
440
+ "epoch": 24.35,
441
+ "learning_rate": 3.754166666666666e-05,
442
+ "loss": 0.2868,
443
+ "step": 5600
444
+ },
445
+ {
446
+ "epoch": 24.78,
447
+ "learning_rate": 3.65e-05,
448
+ "loss": 0.2929,
449
+ "step": 5700
450
+ },
451
+ {
452
+ "epoch": 25.22,
453
+ "learning_rate": 3.545833333333333e-05,
454
+ "loss": 0.2956,
455
+ "step": 5800
456
+ },
457
+ {
458
+ "epoch": 25.65,
459
+ "learning_rate": 3.4416666666666665e-05,
460
+ "loss": 0.2818,
461
+ "step": 5900
462
+ },
463
+ {
464
+ "epoch": 26.09,
465
+ "learning_rate": 3.3375e-05,
466
+ "loss": 0.2961,
467
+ "step": 6000
468
+ },
469
+ {
470
+ "epoch": 26.09,
471
+ "eval_loss": 0.35476088523864746,
472
+ "eval_runtime": 52.7192,
473
+ "eval_samples_per_second": 15.649,
474
+ "eval_steps_per_second": 0.986,
475
+ "eval_wer": 0.2254892691689515,
476
+ "step": 6000
477
+ },
478
+ {
479
+ "epoch": 26.52,
480
+ "learning_rate": 3.233333333333333e-05,
481
+ "loss": 0.2816,
482
+ "step": 6100
483
+ },
484
+ {
485
+ "epoch": 26.96,
486
+ "learning_rate": 3.1291666666666664e-05,
487
+ "loss": 0.2788,
488
+ "step": 6200
489
+ },
490
+ {
491
+ "epoch": 27.39,
492
+ "learning_rate": 3.0249999999999997e-05,
493
+ "loss": 0.272,
494
+ "step": 6300
495
+ },
496
+ {
497
+ "epoch": 27.83,
498
+ "learning_rate": 2.920833333333333e-05,
499
+ "loss": 0.2756,
500
+ "step": 6400
501
+ },
502
+ {
503
+ "epoch": 28.26,
504
+ "learning_rate": 2.8166666666666662e-05,
505
+ "loss": 0.284,
506
+ "step": 6500
507
+ },
508
+ {
509
+ "epoch": 28.26,
510
+ "eval_loss": 0.3526020646095276,
511
+ "eval_runtime": 52.8188,
512
+ "eval_samples_per_second": 15.619,
513
+ "eval_steps_per_second": 0.984,
514
+ "eval_wer": 0.2208565755885412,
515
+ "step": 6500
516
+ },
517
+ {
518
+ "epoch": 28.7,
519
+ "learning_rate": 2.7125e-05,
520
+ "loss": 0.2721,
521
+ "step": 6600
522
+ },
523
+ {
524
+ "epoch": 29.13,
525
+ "learning_rate": 2.608333333333333e-05,
526
+ "loss": 0.2601,
527
+ "step": 6700
528
+ },
529
+ {
530
+ "epoch": 29.57,
531
+ "learning_rate": 2.5041666666666664e-05,
532
+ "loss": 0.2462,
533
+ "step": 6800
534
+ },
535
+ {
536
+ "epoch": 30.0,
537
+ "learning_rate": 2.3999999999999997e-05,
538
+ "loss": 0.271,
539
+ "step": 6900
540
+ },
541
+ {
542
+ "epoch": 30.43,
543
+ "learning_rate": 2.295833333333333e-05,
544
+ "loss": 0.2566,
545
+ "step": 7000
546
+ },
547
+ {
548
+ "epoch": 30.43,
549
+ "eval_loss": 0.35256850719451904,
550
+ "eval_runtime": 52.6434,
551
+ "eval_samples_per_second": 15.671,
552
+ "eval_steps_per_second": 0.988,
553
+ "eval_wer": 0.22047839652075257,
554
+ "step": 7000
555
+ },
556
+ {
557
+ "epoch": 30.87,
558
+ "learning_rate": 2.1916666666666663e-05,
559
+ "loss": 0.2612,
560
+ "step": 7100
561
+ },
562
+ {
563
+ "epoch": 31.3,
564
+ "learning_rate": 2.0874999999999996e-05,
565
+ "loss": 0.2524,
566
+ "step": 7200
567
+ },
568
+ {
569
+ "epoch": 31.74,
570
+ "learning_rate": 1.983333333333333e-05,
571
+ "loss": 0.254,
572
+ "step": 7300
573
+ },
574
+ {
575
+ "epoch": 32.17,
576
+ "learning_rate": 1.879166666666666e-05,
577
+ "loss": 0.2446,
578
+ "step": 7400
579
+ },
580
+ {
581
+ "epoch": 32.61,
582
+ "learning_rate": 1.7749999999999998e-05,
583
+ "loss": 0.2422,
584
+ "step": 7500
585
+ },
586
+ {
587
+ "epoch": 32.61,
588
+ "eval_loss": 0.35690072178840637,
589
+ "eval_runtime": 53.8708,
590
+ "eval_samples_per_second": 15.314,
591
+ "eval_steps_per_second": 0.965,
592
+ "eval_wer": 0.2172638744445495,
593
+ "step": 7500
594
+ },
595
+ {
596
+ "epoch": 33.04,
597
+ "learning_rate": 1.670833333333333e-05,
598
+ "loss": 0.2549,
599
+ "step": 7600
600
+ },
601
+ {
602
+ "epoch": 33.48,
603
+ "learning_rate": 1.5666666666666667e-05,
604
+ "loss": 0.2547,
605
+ "step": 7700
606
+ },
607
+ {
608
+ "epoch": 33.91,
609
+ "learning_rate": 1.4625e-05,
610
+ "loss": 0.2553,
611
+ "step": 7800
612
+ },
613
+ {
614
+ "epoch": 34.35,
615
+ "learning_rate": 1.3583333333333333e-05,
616
+ "loss": 0.2445,
617
+ "step": 7900
618
+ },
619
+ {
620
+ "epoch": 34.78,
621
+ "learning_rate": 1.2541666666666665e-05,
622
+ "loss": 0.2472,
623
+ "step": 8000
624
+ },
625
+ {
626
+ "epoch": 34.78,
627
+ "eval_loss": 0.35918259620666504,
628
+ "eval_runtime": 52.3221,
629
+ "eval_samples_per_second": 15.768,
630
+ "eval_steps_per_second": 0.994,
631
+ "eval_wer": 0.21660206107591945,
632
+ "step": 8000
633
+ },
634
+ {
635
+ "epoch": 35.22,
636
+ "learning_rate": 1.1499999999999998e-05,
637
+ "loss": 0.2608,
638
+ "step": 8100
639
+ },
640
+ {
641
+ "epoch": 35.65,
642
+ "learning_rate": 1.0458333333333333e-05,
643
+ "loss": 0.2482,
644
+ "step": 8200
645
+ },
646
+ {
647
+ "epoch": 36.09,
648
+ "learning_rate": 9.416666666666666e-06,
649
+ "loss": 0.2464,
650
+ "step": 8300
651
+ },
652
+ {
653
+ "epoch": 36.52,
654
+ "learning_rate": 8.374999999999999e-06,
655
+ "loss": 0.2347,
656
+ "step": 8400
657
+ },
658
+ {
659
+ "epoch": 36.96,
660
+ "learning_rate": 7.333333333333333e-06,
661
+ "loss": 0.2337,
662
+ "step": 8500
663
+ },
664
+ {
665
+ "epoch": 36.96,
666
+ "eval_loss": 0.36245495080947876,
667
+ "eval_runtime": 54.1316,
668
+ "eval_samples_per_second": 15.241,
669
+ "eval_steps_per_second": 0.961,
670
+ "eval_wer": 0.21716932967760236,
671
+ "step": 8500
672
+ },
673
+ {
674
+ "epoch": 37.39,
675
+ "learning_rate": 6.291666666666666e-06,
676
+ "loss": 0.2392,
677
+ "step": 8600
678
+ },
679
+ {
680
+ "epoch": 37.83,
681
+ "learning_rate": 5.25e-06,
682
+ "loss": 0.2347,
683
+ "step": 8700
684
+ },
685
+ {
686
+ "epoch": 38.26,
687
+ "learning_rate": 4.208333333333333e-06,
688
+ "loss": 0.2455,
689
+ "step": 8800
690
+ },
691
+ {
692
+ "epoch": 38.7,
693
+ "learning_rate": 3.1666666666666663e-06,
694
+ "loss": 0.243,
695
+ "step": 8900
696
+ },
697
+ {
698
+ "epoch": 39.13,
699
+ "learning_rate": 2.1249999999999996e-06,
700
+ "loss": 0.2315,
701
+ "step": 9000
702
+ },
703
+ {
704
+ "epoch": 39.13,
705
+ "eval_loss": 0.3579612374305725,
706
+ "eval_runtime": 52.3246,
707
+ "eval_samples_per_second": 15.767,
708
+ "eval_steps_per_second": 0.994,
709
+ "eval_wer": 0.21546752387255366,
710
+ "step": 9000
711
+ },
712
+ {
713
+ "epoch": 39.57,
714
+ "learning_rate": 1.0833333333333333e-06,
715
+ "loss": 0.2489,
716
+ "step": 9100
717
+ },
718
+ {
719
+ "epoch": 40.0,
720
+ "learning_rate": 4.166666666666666e-08,
721
+ "loss": 0.227,
722
+ "step": 9200
723
+ },
724
+ {
725
+ "epoch": 40.0,
726
+ "step": 9200,
727
+ "total_flos": 6.4078116974997864e+19,
728
+ "train_loss": 0.896209309619406,
729
+ "train_runtime": 25745.3803,
730
+ "train_samples_per_second": 11.426,
731
+ "train_steps_per_second": 0.357
732
+ }
733
+ ],
734
+ "max_steps": 9200,
735
+ "num_train_epochs": 40,
736
+ "total_flos": 6.4078116974997864e+19,
737
+ "trial_name": null,
738
+ "trial_params": null
739
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c45605b42b58fbf08f0a50a498b37f42abf5163ce81ddbbf3d684bb8da4e8a6
3
+ size 3055
vocab.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26, "å": 27, "æ": 28, "ø": 29, "|": 0, "[UNK]": 30, "[PAD]": 31}