-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval_lora.py
140 lines (121 loc) · 5.36 KB
/
eval_lora.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import torch
import numpy as np
import evaluate
import argparse
import gc
from transformers import WhisperProcessor, WhisperForConditionalGeneration
from peft import PeftModel, PeftConfig
from torch.utils.data import DataLoader
from dataclasses import dataclass
from typing import Any, Dict, List, Union
from tqdm import tqdm
from load_datasets import load_process_datasets
@dataclass
class DataCollatorSpeechSeq2SeqWithPadding:
processor: Any
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
# split inputs and labels since they have to be of different lengths and need different padding methods
# first treat the audio inputs by simply returning torch tensors
input_features = [{"input_features": feature["input_features"]}
for feature in features]
batch = self.processor.feature_extractor.pad(
input_features, return_tensors="pt")
# get the tokenized label sequences
label_features = [{"input_ids": feature["labels"]}
for feature in features]
# pad the labels to max length
labels_batch = self.processor.tokenizer.pad(
label_features, return_tensors="pt")
# replace padding with -100 to ignore loss correctly
labels = labels_batch["input_ids"].masked_fill(
labels_batch.attention_mask.ne(1), -100)
# if bos token is appended in previous tokenization step,
# cut bos token here as it's append later anyways
if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():
labels = labels[:, 1:]
batch["labels"] = labels
return batch
# TODO Move to ArgumentParser
datasets_settings = [
["mdcc", {}],
["common_voice", {"language_abbr": "zh-HK"}],
["aishell_1", {}],
["thchs_30", {}],
["magicdata", {}],
]
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Model setups
parser.add_argument("--peft_model_id",
default="Oblivion208/whisper-large-v2-lora-mix")
parser.add_argument("--task", default="transcribe")
parser.add_argument("--language", default="zh")
parser.add_argument("--batch_size", default=64, type=int)
parser.add_argument("--max_new_tokens", default=255, type=int)
parser.add_argument("--kbit_infer", default=False, action="store_true")
parser.add_argument("--metric", default="cer")
parser.add_argument("--device", default="cuda")
# Dataset setups
parser.add_argument("--num_test_samples", default=1000, type=int)
parser.add_argument("--max_input_length", default=30.0, type=float)
parser.add_argument("--test_only", default=True, type=bool)
parser.add_argument("--streaming", default=False, type=bool)
parser.add_argument("--num_proc", default=4, type=int)
args = parser.parse_args()
print(f"Settings: {args}")
# Load pretrained
peft_config = PeftConfig.from_pretrained(args.peft_model_id)
processor = WhisperProcessor.from_pretrained(
peft_config.base_model_name_or_path, task=args.task, language=args.language)
forced_decoder_ids = processor.get_decoder_prompt_ids(
language=args.language, task=args.task)
ds = load_process_datasets(
datasets_settings,
processor,
max_input_length=args.max_input_length,
num_test_samples=args.num_test_samples,
test_only=args.test_only,
streaming=args.streaming,
num_proc=args.num_proc,
)
print("test sample: ", next(iter(ds["test"])))
data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)
eval_dataloader = DataLoader(
ds["test"], batch_size=args.batch_size, collate_fn=data_collator)
# TODO 8-bit training and inference very slow
model = WhisperForConditionalGeneration.from_pretrained(
peft_config.base_model_name_or_path,
load_in_8bit=args.kbit_infer,
device_map="auto",
)
model = PeftModel.from_pretrained(model, args.peft_model_id)
model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(
language=args.language, task=args.task)
# model.config.suppress_tokens = []
model.eval()
metric = evaluate.load(args.metric)
for step, batch in enumerate(tqdm(eval_dataloader)):
with torch.cuda.amp.autocast():
with torch.no_grad():
generated_tokens = (
model.generate(
input_features=batch["input_features"].to(args.device),
forced_decoder_ids=forced_decoder_ids,
max_new_tokens=args.max_new_tokens,
).cpu().numpy()
)
labels = batch["labels"].cpu().numpy()
labels = np.where(labels != -100, labels,
processor.tokenizer.pad_token_id)
decoded_preds = processor.tokenizer.batch_decode(
generated_tokens, skip_special_tokens=True)
decoded_labels = processor.tokenizer.batch_decode(
labels, skip_special_tokens=True)
metric.add_batch(
predictions=decoded_preds,
references=decoded_labels,
)
del generated_tokens, labels, batch
gc.collect()
cer = 100 * metric.compute()
print(f"{cer=}")