Jakob Poncelet
commited on
Commit
•
b9e18f6
1
Parent(s):
7765f50
Scripts
Browse files- README.md +55 -0
- scripts/cgn-dev.py +94 -0
- scripts/jobfile_eval.job +34 -0
- scripts/jobfile_eval_gpu.job +21 -0
- scripts/jobfile_large.job +20 -0
- scripts/run-cgn-large.sh +47 -0
- scripts/run_eval_whisper_streaming_local.py +151 -0
- scripts/run_speech_recognition_seq2seq_streaming.py +634 -0
- scripts/subs-annot.py +94 -0
README.md
CHANGED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
tags:
|
4 |
+
- whisper-event
|
5 |
+
- generated_from_trainer
|
6 |
+
datasets:
|
7 |
+
- kul-speech-lab/CGN
|
8 |
+
metrics:
|
9 |
+
- wer
|
10 |
+
model-index:
|
11 |
+
- name: Whisper Large CGN
|
12 |
+
results:
|
13 |
+
- task:
|
14 |
+
name: Automatic Speech Recognition
|
15 |
+
type: automatic-speech-recognition
|
16 |
+
dataset:
|
17 |
+
name: kul-speech-lab/CGN
|
18 |
+
type: kul-speech-lab/CGN
|
19 |
+
config: cgn-dev.py
|
20 |
+
split: test
|
21 |
+
metrics:
|
22 |
+
- name: Wer
|
23 |
+
type: wer
|
24 |
+
value: 9.6159
|
25 |
+
---
|
26 |
+
|
27 |
+
# Whisper Large CGN
|
28 |
+
|
29 |
+
This model is a fine-tuned version of [openai/whisper-large-v2](https://huggingface.co/openai/whisper-large-v2) on the kul-speech-lab/CGN dataset.
|
30 |
+
It achieves the following results on the evaluation set:
|
31 |
+
- Loss: 0.23932012915611267
|
32 |
+
- Wer: 9.615871912312803
|
33 |
+
|
34 |
+
### Training hyperparameters
|
35 |
+
|
36 |
+
The following hyperparameters were used during training:
|
37 |
+
- learning_rate: 1e-05
|
38 |
+
- train_batch_size: 32
|
39 |
+
- eval_batch_size: 16
|
40 |
+
- gradient_accumulation_steps: 2
|
41 |
+
- seed: 42
|
42 |
+
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
43 |
+
- lr_scheduler_type: linear
|
44 |
+
- lr_scheduler_warmup_steps: 500
|
45 |
+
- training_steps: 15000
|
46 |
+
- mixed_precision_training: Native AMP
|
47 |
+
|
48 |
+
### Framework versions
|
49 |
+
|
50 |
+
- Transformers 4.26.0.dev0
|
51 |
+
- Pytorch 1.13.0
|
52 |
+
- Datasets 2.7.1.dev0
|
53 |
+
- Tokenizers 0.13.2
|
54 |
+
|
55 |
+
Whisper large model finetuned on Flemish part of Corpus Gesproken Nederlands (CGN).
|
scripts/cgn-dev.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import kaldiio
|
3 |
+
|
4 |
+
import datasets
|
5 |
+
from transformers.utils import logging
|
6 |
+
|
7 |
+
|
8 |
+
logger = logging.get_logger(__name__)
|
9 |
+
|
10 |
+
_DESCRIPTION = "Corpus Gesproken Nederlands"
|
11 |
+
|
12 |
+
_FILEPATHS = {
|
13 |
+
"fbank_pitch": "/esat/spchtemp/scratch/jponcele/espnet2/dump/fbank_pitch/dev_s",
|
14 |
+
"raw": "/esat/spchtemp/scratch/jponcele/espnet2/dump/raw/dev_s"
|
15 |
+
}
|
16 |
+
|
17 |
+
_FEATURES_NAME = {
|
18 |
+
"fbank_pitch": "feats.scp",
|
19 |
+
"raw": "wav.scp"
|
20 |
+
}
|
21 |
+
|
22 |
+
|
23 |
+
class CGNConfig(datasets.BuilderConfig):
|
24 |
+
def __init__(self, **kwargs):
|
25 |
+
"""
|
26 |
+
Args:
|
27 |
+
data_dir: `string`, the path to the folder containing the files in the
|
28 |
+
downloaded .tar
|
29 |
+
citation: `string`, citation for the data set
|
30 |
+
url: `string`, url for information about the data set
|
31 |
+
**kwargs: keyword arguments forwarded to super.
|
32 |
+
"""
|
33 |
+
super(CGNConfig, self).__init__(version=datasets.Version("2.6.1", ""), **kwargs)
|
34 |
+
|
35 |
+
|
36 |
+
class CGN(datasets.GeneratorBasedBuilder):
|
37 |
+
|
38 |
+
DEFAULT_WRITER_BATCH_SIZE = 256
|
39 |
+
DEFAULT_CONFIG_NAME = "raw"
|
40 |
+
BUILDER_CONFIGS = [
|
41 |
+
CGNConfig(name="raw", description="All Components")
|
42 |
+
]
|
43 |
+
|
44 |
+
def _info(self):
|
45 |
+
return datasets.DatasetInfo(
|
46 |
+
description=_DESCRIPTION,
|
47 |
+
features=datasets.Features(
|
48 |
+
{
|
49 |
+
"audio": datasets.Value("string"),
|
50 |
+
"text": datasets.Value("string"),
|
51 |
+
"id": datasets.Value("string"),
|
52 |
+
}
|
53 |
+
),
|
54 |
+
supervised_keys=("text",),
|
55 |
+
)
|
56 |
+
|
57 |
+
def _split_generators(self, _):
|
58 |
+
|
59 |
+
return [
|
60 |
+
datasets.SplitGenerator(
|
61 |
+
name="test",
|
62 |
+
gen_kwargs={}
|
63 |
+
)
|
64 |
+
]
|
65 |
+
|
66 |
+
def _generate_examples(self):
|
67 |
+
|
68 |
+
data_dirs = [_FILEPATHS[self.config.name]]
|
69 |
+
for data_dir in data_dirs:
|
70 |
+
with open(f"{data_dir}/text", "r") as txtfile:
|
71 |
+
lines = txtfile.readlines()
|
72 |
+
texts = {line.rstrip().split(' ')[0]: ' '.join(line.rstrip().split(' ')[1:]) for line in lines if len(line.rstrip().split(' ')) > 1}
|
73 |
+
|
74 |
+
featfile = f"{data_dir}/{_FEATURES_NAME[self.config.name]}"
|
75 |
+
|
76 |
+
with open(featfile, "r") as txtfile:
|
77 |
+
feats_generator = dict(map(lambda s: s.strip().split(maxsplit=1), txtfile))
|
78 |
+
|
79 |
+
#if featfile.endswith(".scp"):
|
80 |
+
# feats_generator = kaldiio.load_scp(featfile)
|
81 |
+
#elif featfile.endswith(".npz"):
|
82 |
+
# feats_generator = np.load(featfile)
|
83 |
+
|
84 |
+
for key, (uttid, transcript) in enumerate(texts.items()):
|
85 |
+
if uttid not in feats_generator:
|
86 |
+
logger.warning(f"Missing utterance: {uttid}")
|
87 |
+
continue
|
88 |
+
|
89 |
+
wav = feats_generator[uttid]
|
90 |
+
#if isinstance(feats, tuple):
|
91 |
+
# sr, feats = feats
|
92 |
+
#feats = np.expand_dims(feats, axis=1)
|
93 |
+
|
94 |
+
yield key, {"audio": wav, "text": transcript, "id": uttid}
|
scripts/jobfile_eval.job
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Universe = vanilla
|
2 |
+
|
3 |
+
RequestCpus = 8
|
4 |
+
RequestMemory = 30G
|
5 |
+
+RequestWallTime = 30000
|
6 |
+
request_GPUs = 0
|
7 |
+
|
8 |
+
Requirements = (Has_avx)\
|
9 |
+
&&(machine!="audioslave.esat.kuleuven.be")\
|
10 |
+
&&(machine!="z4-demo.esat.kuleuven.be")\
|
11 |
+
&&(machine!="xyzzy.esat.kuleuven.be")\
|
12 |
+
&&(machine!="z8-demo.esat.kuleuven.be")\
|
13 |
+
&&(machine!="stadius-nc-4.esat.kuleuven.be")\
|
14 |
+
&&(machine!="stadius-nc-5.esat.kuleuven.be")\
|
15 |
+
&&(machine!="aristoteles.esat.kuleuven.be")\
|
16 |
+
&&(machine!="andromeda.esat.kuleuven.be")\
|
17 |
+
&&(machine!="cauchy.esat.kuleuven.be")\
|
18 |
+
&&(machine!="euler.esat.kuleuven.be")\
|
19 |
+
&&(machine!="gauss.esat.kuleuven.be")\
|
20 |
+
&&(machine!="fig.esat.kuleuven.be")\
|
21 |
+
&&(machine!="nasu.esat.kuleuven.be")\
|
22 |
+
&&(machine!="fehu.esat.kuleuven.be")
|
23 |
+
|
24 |
+
NiceUser = true
|
25 |
+
initialdir = /users/spraak/jponcele/whisper/finetune_event/whisper_runs
|
26 |
+
|
27 |
+
Executable = /esat/spchtemp/scratch/jponcele/anaconda3/envs/whisper/bin/python
|
28 |
+
Arguments = "run_eval_whisper_streaming_local.py --model_size=$(size) --dataset=$(dataset)"
|
29 |
+
|
30 |
+
Log = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).log
|
31 |
+
Output = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).out
|
32 |
+
Error = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).err
|
33 |
+
|
34 |
+
Queue
|
scripts/jobfile_eval_gpu.job
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Universe = vanilla
|
2 |
+
|
3 |
+
RequestCpus = 4
|
4 |
+
RequestMemory = 30G
|
5 |
+
+RequestWallTime = 30000
|
6 |
+
request_GPUs = 1
|
7 |
+
|
8 |
+
Requirements = (Has_avx)\
|
9 |
+
&&((GPUs_GlobalMemoryMb >= 15000)||(CUDAGlobalMemoryMb >= 15000))
|
10 |
+
|
11 |
+
NiceUser = true
|
12 |
+
initialdir = /users/spraak/jponcele/whisper/finetune_event/whisper_runs
|
13 |
+
|
14 |
+
Executable = /esat/spchtemp/scratch/jponcele/anaconda3/envs/whisper/bin/python
|
15 |
+
Arguments = "run_eval_whisper_streaming_local.py --model_size=$(size) --dataset=$(dataset) --device=gpu --batch_size=$(bs)"
|
16 |
+
|
17 |
+
Log = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).log
|
18 |
+
Output = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).out
|
19 |
+
Error = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-eval-$(dataset)-$(size).err
|
20 |
+
|
21 |
+
Queue
|
scripts/jobfile_large.job
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Universe = vanilla
|
2 |
+
|
3 |
+
RequestCpus = 8
|
4 |
+
RequestMemory = 30G
|
5 |
+
+RequestWallTime = 43000
|
6 |
+
request_GPUs = 1
|
7 |
+
|
8 |
+
Requirements = (machine=="aristoteles.esat.kuleuven.be")
|
9 |
+
|
10 |
+
NiceUser = false
|
11 |
+
initialdir = /users/spraak/jponcele/whisper/finetune_event/whisper_runs
|
12 |
+
|
13 |
+
Executable = run-cgn-$(size).sh
|
14 |
+
Arguments = ""
|
15 |
+
|
16 |
+
Log = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-$(size).log
|
17 |
+
Output = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-$(size).out
|
18 |
+
Error = /esat/audioslave/jponcele/whisper/finetuning_event/CGN/condor/condor-$(size).err
|
19 |
+
|
20 |
+
Queue
|
scripts/run-cgn-large.sh
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env bash
|
2 |
+
export PYTHONPATH=""
|
3 |
+
source /esat/spchtemp/scratch/jponcele/anaconda3/bin/activate whisper
|
4 |
+
python --version
|
5 |
+
|
6 |
+
#--dataset_config_name="nl" \
|
7 |
+
#--language="dutch" \
|
8 |
+
|
9 |
+
python run_speech_recognition_seq2seq_streaming.py \
|
10 |
+
--model_name_or_path="openai/whisper-large-v2" \
|
11 |
+
--dataset_name="kul-speech-lab/CGN" \
|
12 |
+
--train_split_name="train+validation" \
|
13 |
+
--eval_split_name="test" \
|
14 |
+
--language="dutch" \
|
15 |
+
--task="transcribe" \
|
16 |
+
--model_index_name="Whisper Large (v2) CGN" \
|
17 |
+
--max_steps="15000" \
|
18 |
+
--output_dir="/esat/audioslave/jponcele/whisper/finetuning_event/CGN/large" \
|
19 |
+
--per_device_train_batch_size="32" \
|
20 |
+
--per_device_eval_batch_size="16" \
|
21 |
+
--gradient_accumulation_steps="2" \
|
22 |
+
--logging_steps="100" \
|
23 |
+
--learning_rate="1e-5" \
|
24 |
+
--warmup_steps="500" \
|
25 |
+
--evaluation_strategy="steps" \
|
26 |
+
--eval_steps="1000" \
|
27 |
+
--save_strategy="steps" \
|
28 |
+
--save_steps="1000" \
|
29 |
+
--generation_max_length="225" \
|
30 |
+
--length_column_name="input_length" \
|
31 |
+
--max_duration_in_seconds="30" \
|
32 |
+
--text_column_name="transcription" \
|
33 |
+
--freeze_feature_encoder="False" \
|
34 |
+
--report_to="tensorboard" \
|
35 |
+
--metric_for_best_model="wer" \
|
36 |
+
--greater_is_better="False" \
|
37 |
+
--load_best_model_at_end \
|
38 |
+
--gradient_checkpointing \
|
39 |
+
--fp16 \
|
40 |
+
--do_train \
|
41 |
+
--do_eval \
|
42 |
+
--predict_with_generate \
|
43 |
+
--do_normalize_eval \
|
44 |
+
--streaming \
|
45 |
+
--use_auth_token
|
46 |
+
# --overwrite_output_dir
|
47 |
+
# --push_to_hub
|
scripts/run_eval_whisper_streaming_local.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import re
|
4 |
+
import argparse
|
5 |
+
|
6 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"].replace("CUDA", "")
|
7 |
+
|
8 |
+
from transformers import pipeline
|
9 |
+
from transformers.models.whisper.english_normalizer import BasicTextNormalizer
|
10 |
+
from datasets import load_dataset, Audio
|
11 |
+
|
12 |
+
whisper_norm = BasicTextNormalizer()
|
13 |
+
|
14 |
+
def simple_norm(utt):
|
15 |
+
norm_utt = re.sub(r'[^\w\s]', '', utt) # remove punctualisation
|
16 |
+
norm_utt = " ".join(norm_utt.split()) # remove whitespaces
|
17 |
+
norm_utt = norm_utt.lower()
|
18 |
+
return norm_utt
|
19 |
+
|
20 |
+
def data(dataset):
|
21 |
+
for i, item in enumerate(dataset):
|
22 |
+
yield {**item["audio"], "reference": item["text"], "utt_id": item["id"]}
|
23 |
+
|
24 |
+
def get_ckpt(path, ckpt_id):
|
25 |
+
if ckpt_id != 0:
|
26 |
+
model = os.path.join(path, "checkpoint-%i" % ckpt)
|
27 |
+
else:
|
28 |
+
dirs = [d for d in os.listdir(path) if d.startswith("checkpoint-")]
|
29 |
+
ckpts = [int(d.split('-')[-1]) for d in dirs]
|
30 |
+
last_ckpt = sorted(ckpts)[-1]
|
31 |
+
model = os.path.join(path, "checkpoint-%s" % last_ckpt)
|
32 |
+
return model
|
33 |
+
|
34 |
+
def main(args):
|
35 |
+
batch_size = args.batch_size
|
36 |
+
|
37 |
+
if args.device == "cpu":
|
38 |
+
device_id = -1
|
39 |
+
elif args.device == "gpu":
|
40 |
+
device_id = 0
|
41 |
+
else:
|
42 |
+
raise NotImplementedError("unknown device %s, should be cpu/gpu" % args.device)
|
43 |
+
|
44 |
+
model_dir = os.path.join(args.expdir, args.model_size)
|
45 |
+
#model = os.path.join(get_ckpt(model_dir, args.checkpoint), 'pytorch_model.bin')
|
46 |
+
#model = get_ckpt(model_dir, args.checkpoint)
|
47 |
+
|
48 |
+
model = model_dir
|
49 |
+
#model = "openai/whisper-tiny"
|
50 |
+
|
51 |
+
whisper_asr = pipeline(
|
52 |
+
"automatic-speech-recognition", model=model, device=device_id
|
53 |
+
)
|
54 |
+
|
55 |
+
whisper_asr.model.config.forced_decoder_ids = (
|
56 |
+
whisper_asr.tokenizer.get_decoder_prompt_ids(
|
57 |
+
language=args.language, task="transcribe"
|
58 |
+
)
|
59 |
+
)
|
60 |
+
|
61 |
+
if args.dataset == 'cgn-dev':
|
62 |
+
dataset_path = "./cgn-dev/cgn-dev.py"
|
63 |
+
elif args.dataset == 'subs-annot':
|
64 |
+
dataset_path = "./subs-annot/subs-annot.py"
|
65 |
+
else:
|
66 |
+
raise NotImplementedError('unknown dataset %s' % args.dataset)
|
67 |
+
|
68 |
+
cache_dir = "/esat/audioslave/jponcele/hf_cache"
|
69 |
+
dataset = load_dataset(dataset_path, name="raw", split="test", cache_dir=cache_dir, streaming=True)
|
70 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
|
71 |
+
|
72 |
+
utterances = []
|
73 |
+
predictions = []
|
74 |
+
references = []
|
75 |
+
|
76 |
+
# run streamed inference
|
77 |
+
for out in whisper_asr(data(dataset), batch_size=batch_size):
|
78 |
+
predictions.append(out["text"])
|
79 |
+
utterances.append(out["utt_id"][0])
|
80 |
+
references.append(out["reference"][0])
|
81 |
+
#break
|
82 |
+
|
83 |
+
result_dir = os.path.join(args.expdir, "results", args.dataset)
|
84 |
+
os.makedirs(result_dir, exist_ok=True)
|
85 |
+
|
86 |
+
with open(os.path.join(result_dir, "whisper_%s.txt" % args.model_size), "w") as pd:
|
87 |
+
for i, utt in enumerate(utterances):
|
88 |
+
pred = predictions[i]
|
89 |
+
pd.write(utt + ' ' + pred + '\n')
|
90 |
+
|
91 |
+
with open(os.path.join(result_dir, "whisper_%s_normW.txt" % args.model_size), "w") as pd:
|
92 |
+
for i, utt in enumerate(utterances):
|
93 |
+
pred = whisper_norm(predictions[i])
|
94 |
+
pd.write(utt + ' ' + pred + '\n')
|
95 |
+
|
96 |
+
with open(os.path.join(result_dir, "whisper_%s_normS.txt" % args.model_size), "w") as pd:
|
97 |
+
for i, utt in enumerate(utterances):
|
98 |
+
pred = simple_norm(predictions[i])
|
99 |
+
pd.write(utt + ' ' + pred + '\n')
|
100 |
+
|
101 |
+
|
102 |
+
|
103 |
+
if __name__ == "__main__":
|
104 |
+
parser = argparse.ArgumentParser()
|
105 |
+
|
106 |
+
parser.add_argument(
|
107 |
+
"--expdir",
|
108 |
+
type=str,
|
109 |
+
default="/esat/audioslave/jponcele/whisper/finetuning_event/CGN",
|
110 |
+
help="Directory with finetuned models",
|
111 |
+
)
|
112 |
+
parser.add_argument(
|
113 |
+
"--model_size",
|
114 |
+
type=str,
|
115 |
+
default="tiny",
|
116 |
+
help="Model size",
|
117 |
+
)
|
118 |
+
parser.add_argument(
|
119 |
+
"--checkpoint",
|
120 |
+
type=int,
|
121 |
+
default=0,
|
122 |
+
help="Load specific checkpoint. 0 means latest",
|
123 |
+
)
|
124 |
+
parser.add_argument(
|
125 |
+
"--dataset",
|
126 |
+
type=str,
|
127 |
+
default="cgn-dev",
|
128 |
+
help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
|
129 |
+
)
|
130 |
+
parser.add_argument(
|
131 |
+
"--device",
|
132 |
+
type=str,
|
133 |
+
default="cpu",
|
134 |
+
help="cpu/gpu",
|
135 |
+
)
|
136 |
+
parser.add_argument(
|
137 |
+
"--batch_size",
|
138 |
+
type=int,
|
139 |
+
default=16,
|
140 |
+
help="Number of samples to go through each streamed batch.",
|
141 |
+
)
|
142 |
+
parser.add_argument(
|
143 |
+
"--language",
|
144 |
+
type=str,
|
145 |
+
default="dutch",
|
146 |
+
help="Two letter language code for the transcription language, e.g. use 'en' for English.",
|
147 |
+
)
|
148 |
+
|
149 |
+
args = parser.parse_args()
|
150 |
+
main(args)
|
151 |
+
|
scripts/run_speech_recognition_seq2seq_streaming.py
ADDED
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for sequence to sequence speech recognition
|
18 |
+
with 🤗 Datasets' streaming mode.
|
19 |
+
"""
|
20 |
+
# You can also adapt this script for your own sequence to sequence speech
|
21 |
+
# recognition task. Pointers for this are left as comments.
|
22 |
+
|
23 |
+
import logging
|
24 |
+
import os
|
25 |
+
import sys
|
26 |
+
from dataclasses import dataclass, field
|
27 |
+
from typing import Any, Dict, List, Optional, Union
|
28 |
+
|
29 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"].replace("CUDA", "")
|
30 |
+
|
31 |
+
import datasets
|
32 |
+
import torch
|
33 |
+
from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
|
34 |
+
from torch.utils.data import IterableDataset
|
35 |
+
|
36 |
+
import evaluate
|
37 |
+
import transformers
|
38 |
+
from transformers import (
|
39 |
+
AutoConfig,
|
40 |
+
AutoFeatureExtractor,
|
41 |
+
AutoModelForSpeechSeq2Seq,
|
42 |
+
AutoProcessor,
|
43 |
+
AutoTokenizer,
|
44 |
+
HfArgumentParser,
|
45 |
+
Seq2SeqTrainer,
|
46 |
+
Seq2SeqTrainingArguments,
|
47 |
+
TrainerCallback,
|
48 |
+
set_seed,
|
49 |
+
)
|
50 |
+
from transformers.models.whisper.english_normalizer import BasicTextNormalizer
|
51 |
+
from transformers.trainer_pt_utils import IterableDatasetShard
|
52 |
+
from transformers.trainer_utils import get_last_checkpoint, is_main_process
|
53 |
+
from transformers.utils import check_min_version, send_example_telemetry
|
54 |
+
from transformers.utils.versions import require_version
|
55 |
+
|
56 |
+
|
57 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
58 |
+
check_min_version("4.25.0.dev0")
|
59 |
+
|
60 |
+
require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
|
61 |
+
|
62 |
+
logger = logging.getLogger(__name__)
|
63 |
+
|
64 |
+
|
65 |
+
@dataclass
|
66 |
+
class ModelArguments:
|
67 |
+
"""
|
68 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
69 |
+
"""
|
70 |
+
|
71 |
+
model_name_or_path: str = field(
|
72 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
73 |
+
)
|
74 |
+
config_name: Optional[str] = field(
|
75 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
76 |
+
)
|
77 |
+
tokenizer_name: Optional[str] = field(
|
78 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
79 |
+
)
|
80 |
+
feature_extractor_name: Optional[str] = field(
|
81 |
+
default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
|
82 |
+
)
|
83 |
+
cache_dir: Optional[str] = field(
|
84 |
+
default=None,
|
85 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
86 |
+
)
|
87 |
+
use_fast_tokenizer: bool = field(
|
88 |
+
default=True,
|
89 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
90 |
+
)
|
91 |
+
model_revision: str = field(
|
92 |
+
default="main",
|
93 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
94 |
+
)
|
95 |
+
use_auth_token: bool = field(
|
96 |
+
default=False,
|
97 |
+
metadata={
|
98 |
+
"help": (
|
99 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
100 |
+
"with private models)."
|
101 |
+
)
|
102 |
+
},
|
103 |
+
)
|
104 |
+
freeze_feature_encoder: bool = field(
|
105 |
+
default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
|
106 |
+
)
|
107 |
+
freeze_encoder: bool = field(
|
108 |
+
default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
|
109 |
+
)
|
110 |
+
forced_decoder_ids: List[List[int]] = field(
|
111 |
+
default=None,
|
112 |
+
metadata={
|
113 |
+
"help": (
|
114 |
+
"A list of pairs of integers which indicates a mapping from generation indices to token indices "
|
115 |
+
"that will be forced before sampling. For example, [[0, 123]] means the first generated token "
|
116 |
+
"will always be a token of index 123."
|
117 |
+
)
|
118 |
+
},
|
119 |
+
)
|
120 |
+
suppress_tokens: List[int] = field(
|
121 |
+
default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
|
122 |
+
)
|
123 |
+
model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
|
124 |
+
|
125 |
+
|
126 |
+
@dataclass
|
127 |
+
class DataTrainingArguments:
|
128 |
+
"""
|
129 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
130 |
+
"""
|
131 |
+
|
132 |
+
dataset_name: str = field(
|
133 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
134 |
+
)
|
135 |
+
dataset_config_name: Optional[str] = field(
|
136 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
137 |
+
)
|
138 |
+
text_column: Optional[str] = field(
|
139 |
+
default=None,
|
140 |
+
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
|
141 |
+
)
|
142 |
+
max_train_samples: Optional[int] = field(
|
143 |
+
default=None,
|
144 |
+
metadata={
|
145 |
+
"help": (
|
146 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
147 |
+
"value if set."
|
148 |
+
)
|
149 |
+
},
|
150 |
+
)
|
151 |
+
max_eval_samples: Optional[int] = field(
|
152 |
+
default=None,
|
153 |
+
metadata={
|
154 |
+
"help": (
|
155 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
156 |
+
"value if set."
|
157 |
+
)
|
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 |
+
max_duration_in_seconds: float = field(
|
169 |
+
default=20.0,
|
170 |
+
metadata={
|
171 |
+
"help": (
|
172 |
+
"Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
|
173 |
+
" 'max_duration_in_seconds`"
|
174 |
+
)
|
175 |
+
},
|
176 |
+
)
|
177 |
+
min_duration_in_seconds: float = field(
|
178 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
179 |
+
)
|
180 |
+
train_split_name: str = field(
|
181 |
+
default="train",
|
182 |
+
metadata={
|
183 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
184 |
+
},
|
185 |
+
)
|
186 |
+
eval_split_name: str = field(
|
187 |
+
default="test",
|
188 |
+
metadata={
|
189 |
+
"help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
|
190 |
+
},
|
191 |
+
)
|
192 |
+
do_lower_case: bool = field(
|
193 |
+
default=False,
|
194 |
+
metadata={"help": "Whether the target text should be lower cased."},
|
195 |
+
)
|
196 |
+
do_remove_punctuation: bool = field(
|
197 |
+
default=False,
|
198 |
+
metadata={"help": "Whether the target text should be striped of punctuation."},
|
199 |
+
)
|
200 |
+
do_normalize_eval: bool = field(
|
201 |
+
default=True,
|
202 |
+
metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
|
203 |
+
)
|
204 |
+
language: str = field(
|
205 |
+
default=None,
|
206 |
+
metadata={
|
207 |
+
"help": (
|
208 |
+
"Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
|
209 |
+
"only. For English speech recognition, it should be set to `None`."
|
210 |
+
)
|
211 |
+
},
|
212 |
+
)
|
213 |
+
task: str = field(
|
214 |
+
default="transcribe",
|
215 |
+
metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
|
216 |
+
)
|
217 |
+
shuffle_buffer_size: Optional[int] = field(
|
218 |
+
default=500,
|
219 |
+
metadata={
|
220 |
+
"help": (
|
221 |
+
"The number of streamed examples to download before shuffling them. The large the buffer, "
|
222 |
+
"the closer it is to real offline shuffling."
|
223 |
+
)
|
224 |
+
},
|
225 |
+
)
|
226 |
+
streaming: bool = field(
|
227 |
+
default=True,
|
228 |
+
metadata={"help": "Whether to use streaming mode to load and pre-process the data."},
|
229 |
+
)
|
230 |
+
|
231 |
+
|
232 |
+
@dataclass
|
233 |
+
class DataCollatorSpeechSeq2SeqWithPadding:
|
234 |
+
"""
|
235 |
+
Data collator that will dynamically pad the inputs received.
|
236 |
+
Args:
|
237 |
+
processor ([`WhisperProcessor`])
|
238 |
+
The processor used for processing the data.
|
239 |
+
decoder_start_token_id (`int`)
|
240 |
+
The begin-of-sentence of the decoder.
|
241 |
+
"""
|
242 |
+
|
243 |
+
processor: Any
|
244 |
+
decoder_start_token_id: int
|
245 |
+
|
246 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
247 |
+
# split inputs and labels since they have to be of different lengths and need
|
248 |
+
# different padding methods
|
249 |
+
model_input_name = self.processor.model_input_names[0]
|
250 |
+
input_features = [{model_input_name: feature[model_input_name]} for feature in features]
|
251 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
252 |
+
|
253 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
254 |
+
|
255 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
256 |
+
|
257 |
+
# replace padding with -100 to ignore loss correctly
|
258 |
+
labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
259 |
+
|
260 |
+
# if bos token is appended in previous tokenization step,
|
261 |
+
# cut bos token here as it's append later anyways
|
262 |
+
if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
|
263 |
+
labels = labels[:, 1:]
|
264 |
+
|
265 |
+
batch["labels"] = labels
|
266 |
+
|
267 |
+
return batch
|
268 |
+
|
269 |
+
|
270 |
+
def load_maybe_streaming_dataset(dataset_name, dataset_config_name, split="train", streaming=True, **kwargs):
|
271 |
+
"""
|
272 |
+
Utility function to load a dataset in streaming mode. For datasets with multiple splits,
|
273 |
+
each split is loaded individually and then splits combined by taking alternating examples from
|
274 |
+
each (interleaving).
|
275 |
+
"""
|
276 |
+
if "+" in split:
|
277 |
+
# load multiple splits separated by the `+` symbol with streaming mode
|
278 |
+
dataset_splits = [
|
279 |
+
load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=streaming, **kwargs)
|
280 |
+
for split_name in split.split("+")
|
281 |
+
]
|
282 |
+
# interleave multiple splits to form one dataset
|
283 |
+
interleaved_dataset = interleave_datasets(dataset_splits)
|
284 |
+
return interleaved_dataset
|
285 |
+
else:
|
286 |
+
# load a single split *with* streaming mode
|
287 |
+
dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=streaming, **kwargs)
|
288 |
+
return dataset
|
289 |
+
|
290 |
+
|
291 |
+
def main():
|
292 |
+
# 1. Parse input arguments
|
293 |
+
# See all possible arguments in src/transformers/training_args.py
|
294 |
+
# or by passing the --help flag to this script.
|
295 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
296 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
|
297 |
+
|
298 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
299 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
300 |
+
# let's parse it to get our arguments.
|
301 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
302 |
+
else:
|
303 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
304 |
+
|
305 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
306 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
307 |
+
send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
|
308 |
+
|
309 |
+
# 2. Setup logging
|
310 |
+
logging.basicConfig(
|
311 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
312 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
313 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
314 |
+
)
|
315 |
+
log_level = training_args.get_process_log_level()
|
316 |
+
logger.setLevel(log_level)
|
317 |
+
datasets.utils.logging.set_verbosity(log_level)
|
318 |
+
transformers.utils.logging.set_verbosity(log_level)
|
319 |
+
transformers.utils.logging.enable_default_handler()
|
320 |
+
transformers.utils.logging.enable_explicit_format()
|
321 |
+
|
322 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
323 |
+
|
324 |
+
# Log on each process the small summary:
|
325 |
+
logger.warning(
|
326 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
327 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
328 |
+
)
|
329 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
330 |
+
|
331 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
332 |
+
if is_main_process(training_args.local_rank):
|
333 |
+
transformers.utils.logging.set_verbosity_info()
|
334 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
335 |
+
|
336 |
+
# 3. Detecting last checkpoint and eventually continue from last checkpoint
|
337 |
+
last_checkpoint = None
|
338 |
+
|
339 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
340 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
341 |
+
logger.info(f"Last CHECKPOINT {last_checkpoint}")
|
342 |
+
|
343 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
344 |
+
raise ValueError(
|
345 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
346 |
+
"Use --overwrite_output_dir to overcome."
|
347 |
+
)
|
348 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
349 |
+
logger.info(
|
350 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
351 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
352 |
+
)
|
353 |
+
|
354 |
+
# Set seed before initializing model.
|
355 |
+
set_seed(training_args.seed)
|
356 |
+
|
357 |
+
# 4. Load dataset
|
358 |
+
raw_datasets = IterableDatasetDict() if data_args.streaming else DatasetDict()
|
359 |
+
|
360 |
+
if training_args.do_train:
|
361 |
+
raw_datasets["train"] = load_maybe_streaming_dataset(
|
362 |
+
data_args.dataset_name,
|
363 |
+
data_args.dataset_config_name,
|
364 |
+
split=data_args.train_split_name,
|
365 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
366 |
+
streaming=data_args.streaming,
|
367 |
+
)
|
368 |
+
|
369 |
+
if training_args.do_eval:
|
370 |
+
raw_datasets["eval"] = load_maybe_streaming_dataset(
|
371 |
+
data_args.dataset_name,
|
372 |
+
data_args.dataset_config_name,
|
373 |
+
split=data_args.eval_split_name,
|
374 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
375 |
+
streaming=data_args.streaming,
|
376 |
+
)
|
377 |
+
|
378 |
+
raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
|
379 |
+
|
380 |
+
if data_args.audio_column_name not in raw_datasets_features:
|
381 |
+
raise ValueError(
|
382 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
383 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
384 |
+
f"{', '.join(raw_datasets_features)}."
|
385 |
+
)
|
386 |
+
|
387 |
+
if data_args.text_column_name not in raw_datasets_features:
|
388 |
+
raise ValueError(
|
389 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
390 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
391 |
+
f"{', '.join(raw_datasets_features)}."
|
392 |
+
)
|
393 |
+
|
394 |
+
# 5. Load pretrained model, tokenizer, and feature extractor
|
395 |
+
#
|
396 |
+
# Distributed training:
|
397 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
398 |
+
config = AutoConfig.from_pretrained(
|
399 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
400 |
+
cache_dir=model_args.cache_dir,
|
401 |
+
revision=model_args.model_revision,
|
402 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
403 |
+
)
|
404 |
+
|
405 |
+
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
|
406 |
+
|
407 |
+
if training_args.gradient_checkpointing:
|
408 |
+
config.update({"use_cache": False})
|
409 |
+
|
410 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
411 |
+
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
|
412 |
+
cache_dir=model_args.cache_dir,
|
413 |
+
revision=model_args.model_revision,
|
414 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
415 |
+
)
|
416 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
417 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
418 |
+
cache_dir=model_args.cache_dir,
|
419 |
+
use_fast=model_args.use_fast_tokenizer,
|
420 |
+
revision=model_args.model_revision,
|
421 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
422 |
+
)
|
423 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
424 |
+
model_args.model_name_or_path,
|
425 |
+
config=config,
|
426 |
+
cache_dir=model_args.cache_dir,
|
427 |
+
revision=model_args.model_revision,
|
428 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
429 |
+
)
|
430 |
+
|
431 |
+
if model.config.decoder_start_token_id is None:
|
432 |
+
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
|
433 |
+
|
434 |
+
if model_args.freeze_feature_encoder:
|
435 |
+
model.freeze_feature_encoder()
|
436 |
+
|
437 |
+
if model_args.freeze_encoder:
|
438 |
+
model.freeze_encoder()
|
439 |
+
|
440 |
+
if data_args.language is not None:
|
441 |
+
# We only need to set the task id when the language is specified (i.e. in a multilingual setting)
|
442 |
+
tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
|
443 |
+
|
444 |
+
# 6. Resample speech dataset if necessary
|
445 |
+
dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
|
446 |
+
if dataset_sampling_rate != feature_extractor.sampling_rate:
|
447 |
+
raw_datasets = raw_datasets.cast_column(
|
448 |
+
data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
|
449 |
+
)
|
450 |
+
|
451 |
+
# 7. Preprocessing the datasets.
|
452 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
453 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
454 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
455 |
+
audio_column_name = data_args.audio_column_name
|
456 |
+
text_column_name = data_args.text_column_name
|
457 |
+
model_input_name = feature_extractor.model_input_names[0]
|
458 |
+
do_lower_case = data_args.do_lower_case
|
459 |
+
do_remove_punctuation = data_args.do_remove_punctuation
|
460 |
+
normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
|
461 |
+
|
462 |
+
if data_args.max_train_samples is not None:
|
463 |
+
raw_datasets["train"] = (
|
464 |
+
raw_datasets["train"].take(data_args.max_train_samples)
|
465 |
+
if data_args.streaming
|
466 |
+
else raw_datasets["train"].select(range(data_args.max_train_samples))
|
467 |
+
)
|
468 |
+
|
469 |
+
if data_args.max_eval_samples is not None:
|
470 |
+
raw_datasets["eval"] = (
|
471 |
+
raw_datasets["eval"].take(data_args.max_eval_samples)
|
472 |
+
if data_args.streaming
|
473 |
+
else raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
474 |
+
)
|
475 |
+
|
476 |
+
def prepare_dataset(batch):
|
477 |
+
# process audio
|
478 |
+
sample = batch[audio_column_name]
|
479 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
480 |
+
# process audio length
|
481 |
+
batch[model_input_name] = inputs.get(model_input_name)[0]
|
482 |
+
batch["input_length"] = len(sample["array"])
|
483 |
+
|
484 |
+
# process targets
|
485 |
+
input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
|
486 |
+
if do_remove_punctuation:
|
487 |
+
input_str = normalizer(input_str).strip()
|
488 |
+
batch["labels"] = tokenizer(input_str).input_ids
|
489 |
+
return batch
|
490 |
+
|
491 |
+
with training_args.main_process_first(desc="dataset map pre-processing"):
|
492 |
+
vectorized_datasets = raw_datasets.map(
|
493 |
+
prepare_dataset,
|
494 |
+
remove_columns=raw_datasets_features,
|
495 |
+
).with_format("torch")
|
496 |
+
|
497 |
+
if training_args.do_train and data_args.streaming:
|
498 |
+
# manually shuffle if streaming (done by the trainer for non-streaming)
|
499 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
|
500 |
+
buffer_size=data_args.shuffle_buffer_size,
|
501 |
+
seed=training_args.seed,
|
502 |
+
)
|
503 |
+
|
504 |
+
# filter training data that is shorter than min_input_length or longer than
|
505 |
+
# max_input_length
|
506 |
+
def is_audio_in_length_range(length):
|
507 |
+
return min_input_length < length < max_input_length
|
508 |
+
|
509 |
+
if training_args.do_train:
|
510 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].filter(
|
511 |
+
is_audio_in_length_range,
|
512 |
+
input_columns=["input_length"],
|
513 |
+
)
|
514 |
+
|
515 |
+
# 8. Load Metric
|
516 |
+
metric = evaluate.load("wer")
|
517 |
+
do_normalize_eval = data_args.do_normalize_eval
|
518 |
+
|
519 |
+
def compute_metrics(pred):
|
520 |
+
pred_ids = pred.predictions
|
521 |
+
|
522 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
523 |
+
|
524 |
+
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
|
525 |
+
# we do not want to group tokens when computing the metrics
|
526 |
+
label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
|
527 |
+
|
528 |
+
if do_normalize_eval:
|
529 |
+
pred_str = [normalizer(pred) for pred in pred_str]
|
530 |
+
label_str = [normalizer(label) for label in label_str]
|
531 |
+
# filtering step to only evaluate the samples that correspond to non-zero references:
|
532 |
+
pred_str = [pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0]
|
533 |
+
label_str = [label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0]
|
534 |
+
|
535 |
+
wer = 100 * metric.compute(predictions=pred_str, references=label_str)
|
536 |
+
|
537 |
+
return {"wer": wer}
|
538 |
+
|
539 |
+
# 9. Create a single speech processor
|
540 |
+
if is_main_process(training_args.local_rank):
|
541 |
+
# save feature extractor, tokenizer and config
|
542 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
543 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
544 |
+
config.save_pretrained(training_args.output_dir)
|
545 |
+
|
546 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
547 |
+
|
548 |
+
# 10. Define data collator
|
549 |
+
data_collator = DataCollatorSpeechSeq2SeqWithPadding(
|
550 |
+
processor=processor,
|
551 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
552 |
+
)
|
553 |
+
|
554 |
+
# 11. Configure Trainer
|
555 |
+
# Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
|
556 |
+
# Only required for streaming: Trainer automatically shuffles non-streaming datasets
|
557 |
+
class ShuffleCallback(TrainerCallback):
|
558 |
+
def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
|
559 |
+
if isinstance(train_dataloader.dataset, IterableDatasetShard):
|
560 |
+
pass # set_epoch() is handled by the Trainer
|
561 |
+
elif isinstance(train_dataloader.dataset, IterableDataset):
|
562 |
+
train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
|
563 |
+
|
564 |
+
# Initialize Trainer
|
565 |
+
trainer = Seq2SeqTrainer(
|
566 |
+
model=model,
|
567 |
+
args=training_args,
|
568 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
569 |
+
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
|
570 |
+
tokenizer=feature_extractor,
|
571 |
+
data_collator=data_collator,
|
572 |
+
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
|
573 |
+
callbacks=[ShuffleCallback()] if data_args.streaming else None,
|
574 |
+
)
|
575 |
+
|
576 |
+
# 12. Training
|
577 |
+
if training_args.do_train:
|
578 |
+
checkpoint = None
|
579 |
+
if training_args.resume_from_checkpoint is not None:
|
580 |
+
checkpoint = training_args.resume_from_checkpoint
|
581 |
+
elif last_checkpoint is not None:
|
582 |
+
checkpoint = last_checkpoint
|
583 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
584 |
+
trainer.save_model() # Saves the feature extractor too for easy upload
|
585 |
+
|
586 |
+
metrics = train_result.metrics
|
587 |
+
if data_args.max_train_samples:
|
588 |
+
metrics["train_samples"] = data_args.max_train_samples
|
589 |
+
trainer.log_metrics("train", metrics)
|
590 |
+
trainer.save_metrics("train", metrics)
|
591 |
+
trainer.save_state()
|
592 |
+
|
593 |
+
# 13. Evaluation
|
594 |
+
results = {}
|
595 |
+
if training_args.do_eval:
|
596 |
+
logger.info("*** Evaluate ***")
|
597 |
+
metrics = trainer.evaluate(
|
598 |
+
metric_key_prefix="eval",
|
599 |
+
max_length=training_args.generation_max_length,
|
600 |
+
num_beams=training_args.generation_num_beams,
|
601 |
+
)
|
602 |
+
if data_args.max_eval_samples:
|
603 |
+
metrics["eval_samples"] = data_args.max_eval_samples
|
604 |
+
|
605 |
+
trainer.log_metrics("eval", metrics)
|
606 |
+
trainer.save_metrics("eval", metrics)
|
607 |
+
|
608 |
+
# 14. Write Training Stats
|
609 |
+
kwargs = {
|
610 |
+
"finetuned_from": model_args.model_name_or_path,
|
611 |
+
"tasks": "automatic-speech-recognition",
|
612 |
+
"tags": "whisper-event",
|
613 |
+
}
|
614 |
+
if data_args.dataset_name is not None:
|
615 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
616 |
+
if data_args.dataset_config_name is not None:
|
617 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
618 |
+
else:
|
619 |
+
kwargs["dataset"] = data_args.dataset_name
|
620 |
+
if "common_voice" in data_args.dataset_name:
|
621 |
+
kwargs["language"] = data_args.dataset_config_name[:2]
|
622 |
+
if model_args.model_index_name is not None:
|
623 |
+
kwargs["model_name"] = model_args.model_index_name
|
624 |
+
|
625 |
+
if training_args.push_to_hub:
|
626 |
+
trainer.push_to_hub(**kwargs)
|
627 |
+
else:
|
628 |
+
trainer.create_model_card(**kwargs)
|
629 |
+
|
630 |
+
return results
|
631 |
+
|
632 |
+
|
633 |
+
if __name__ == "__main__":
|
634 |
+
main()
|
scripts/subs-annot.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import kaldiio
|
3 |
+
|
4 |
+
import datasets
|
5 |
+
from transformers.utils import logging
|
6 |
+
|
7 |
+
|
8 |
+
logger = logging.get_logger(__name__)
|
9 |
+
|
10 |
+
_DESCRIPTION = "Annotated Subtitles"
|
11 |
+
|
12 |
+
_FILEPATHS = {
|
13 |
+
"fbank_pitch": "/esat/spchtemp/scratch/jponcele/espnet2/dump/fbank_pitch/subs_annot",
|
14 |
+
"raw": "/esat/spchtemp/scratch/jponcele/espnet2/dump/raw/subs_annot"
|
15 |
+
}
|
16 |
+
|
17 |
+
_FEATURES_NAME = {
|
18 |
+
"fbank_pitch": "feats.scp",
|
19 |
+
"raw": "wav.scp"
|
20 |
+
}
|
21 |
+
|
22 |
+
|
23 |
+
class CGNConfig(datasets.BuilderConfig):
|
24 |
+
def __init__(self, **kwargs):
|
25 |
+
"""
|
26 |
+
Args:
|
27 |
+
data_dir: `string`, the path to the folder containing the files in the
|
28 |
+
downloaded .tar
|
29 |
+
citation: `string`, citation for the data set
|
30 |
+
url: `string`, url for information about the data set
|
31 |
+
**kwargs: keyword arguments forwarded to super.
|
32 |
+
"""
|
33 |
+
super(CGNConfig, self).__init__(version=datasets.Version("2.6.1", ""), **kwargs)
|
34 |
+
|
35 |
+
|
36 |
+
class CGN(datasets.GeneratorBasedBuilder):
|
37 |
+
|
38 |
+
DEFAULT_WRITER_BATCH_SIZE = 256
|
39 |
+
DEFAULT_CONFIG_NAME = "raw"
|
40 |
+
BUILDER_CONFIGS = [
|
41 |
+
CGNConfig(name="raw", description="All Components")
|
42 |
+
]
|
43 |
+
|
44 |
+
def _info(self):
|
45 |
+
return datasets.DatasetInfo(
|
46 |
+
description=_DESCRIPTION,
|
47 |
+
features=datasets.Features(
|
48 |
+
{
|
49 |
+
"audio": datasets.Value("string"),
|
50 |
+
"text": datasets.Value("string"),
|
51 |
+
"id": datasets.Value("string"),
|
52 |
+
}
|
53 |
+
),
|
54 |
+
supervised_keys=("text",),
|
55 |
+
)
|
56 |
+
|
57 |
+
def _split_generators(self, _):
|
58 |
+
|
59 |
+
return [
|
60 |
+
datasets.SplitGenerator(
|
61 |
+
name="test",
|
62 |
+
gen_kwargs={}
|
63 |
+
)
|
64 |
+
]
|
65 |
+
|
66 |
+
def _generate_examples(self):
|
67 |
+
|
68 |
+
data_dirs = [_FILEPATHS[self.config.name]]
|
69 |
+
for data_dir in data_dirs:
|
70 |
+
with open(f"{data_dir}/text", "r") as txtfile:
|
71 |
+
lines = txtfile.readlines()
|
72 |
+
texts = {line.rstrip().split(' ')[0]: ' '.join(line.rstrip().split(' ')[1:]) for line in lines if len(line.rstrip().split(' ')) > 1}
|
73 |
+
|
74 |
+
featfile = f"{data_dir}/{_FEATURES_NAME[self.config.name]}"
|
75 |
+
|
76 |
+
with open(featfile, "r") as txtfile:
|
77 |
+
feats_generator = dict(map(lambda s: s.strip().split(maxsplit=1), txtfile))
|
78 |
+
|
79 |
+
#if featfile.endswith(".scp"):
|
80 |
+
# feats_generator = kaldiio.load_scp(featfile)
|
81 |
+
#elif featfile.endswith(".npz"):
|
82 |
+
# feats_generator = np.load(featfile)
|
83 |
+
|
84 |
+
for key, (uttid, transcript) in enumerate(texts.items()):
|
85 |
+
if uttid not in feats_generator:
|
86 |
+
logger.warning(f"Missing utterance: {uttid}")
|
87 |
+
continue
|
88 |
+
|
89 |
+
wav = feats_generator[uttid]
|
90 |
+
#if isinstance(feats, tuple):
|
91 |
+
# sr, feats = feats
|
92 |
+
#feats = np.expand_dims(feats, axis=1)
|
93 |
+
|
94 |
+
yield key, {"audio": wav, "text": transcript, "id": uttid}
|