Views
No views yet
1from vllm.assets.audio import AudioAsset
2from vllm import LLM, SamplingParams
3
4# prepare model
5llm = LLM(
6 model="neuralmagic/whisper-large-v2-quantized.w8a8",
7 max_model_len=448,
8 max_num_seqs=400,
9 limit_mm_per_prompt={"audio": 1},
10)
11
12# prepare inputs
13inputs = { # Test explicit encoder/decoder prompt
14 "encoder_prompt": {
15 "prompt": "",
16 "multi_modal_data": {
17 "audio": AudioAsset("winning_call").audio_and_sample_rate,
18 },
19 },
20 "decoder_prompt": "<|startoftranscript|>",
21}
22
23# generate response
24print("========== SAMPLE GENERATION ==============")
25outputs = llm.generate(inputs, SamplingParams(temperature=0.0, max_tokens=64))
26print(f"PROMPT : {outputs[0].prompt}")
27print(f"RESPONSE: {outputs[0].outputs[0].text}")
28print("==========================================")python quantize.py --model_path openai/whisper-large-v2 --quant_path "output_dir/whisper-large-v2-quantized.w8a8" --calib_size 1024 --dampening_frac 0.011import torch
2import argparse
3from datasets import load_dataset
4from transformers import WhisperProcessor
5from llmcompressor import oneshot
6from llmcompressor.modifiers.quantization import GPTQModifier
7from llmcompressor.transformers.tracing import TraceableWhisperForConditionalGeneration
8import os
9from compressed_tensors.quantization import QuantizationArgs, QuantizationType, QuantizationStrategy, ActivationOrdering, QuantizationScheme
10from llmcompressor.modifiers.smoothquant import SmoothQuantModifier
11
12parser = argparse.ArgumentParser()
13parser.add_argument('--model_path', type=str)
14parser.add_argument('--quant_path', type=str)
15parser.add_argument('--calib_size', type=int, default=256)
16parser.add_argument('--dampening_frac', type=float, default=0.1)
17parser.add_argument('--observer', type=str, default="minmax")
18parser.add_argument('--save_dir', type=str, required=True)
19
20
21args = parser.parse_args()
22model_id = args.model_path
23
24model = TraceableWhisperForConditionalGeneration.from_pretrained(
25 model_id,
26 device_map="auto",
27 torch_dtype="auto",
28)
29model.config.forced_decoder_ids = None
30processor = WhisperProcessor.from_pretrained(model_id)
31
32# Configure processor the dataset task.
33processor.tokenizer.set_prefix_tokens(language="en", task="transcribe")
34
35# Select calibration dataset.
36DATASET_ID = "MLCommons/peoples_speech"
37DATASET_SUBSET = "test"
38DATASET_SPLIT = "test"
39
40# Select number of samples for calibration. 512 samples is a good place to start.
41# Increasing the number of samples can improve accuracy.
42
43NUM_CALIBRATION_SAMPLES = args.calib_size
44MAX_SEQUENCE_LENGTH = 2048
45dampening_frac=args.dampening_frac
46actorder_arg=args.actorder
47group_size=args.group_size
48
49# Load dataset and preprocess.
50ds = load_dataset(
51 DATASET_ID,
52 DATASET_SUBSET,
53 split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]",
54 trust_remote_code=True,
55)
56
57def preprocess(example):
58 return {
59 "array": example["audio"]["array"],
60 "sampling_rate": example["audio"]["sampling_rate"],
61 "text": " " + example["text"].capitalize(),
62 }
63
64ds = ds.map(preprocess, remove_columns=ds.column_names)
65
66# Process inputs.
67def process(sample):
68 inputs = processor(
69 audio=sample["array"],
70 sampling_rate=sample["sampling_rate"],
71 text=sample["text"],
72 add_special_tokens=True,
73 return_tensors="pt",
74 )
75
76 inputs["input_features"] = inputs["input_features"].to(dtype=model.dtype)
77 inputs["decoder_input_ids"] = inputs["labels"]
78 del inputs["labels"]
79
80 return inputs
81
82ds = ds.map(process, remove_columns=ds.column_names)
83
84# Define a oneshot data collator for multimodal inputs.
85def data_collator(batch):
86 assert len(batch) == 1
87 return {key: torch.tensor(value) for key, value in batch[0].items()}
88
89ignore=["lm_head"]
90
91#Recipe
92recipe = [
93 GPTQModifier(
94 targets="Linear",
95 scheme="W8A8",
96 sequential_targets=["WhisperEncoderLayer", "WhisperDecoderLayer"],
97 ignore=ignore,
98 )
99]
100
101# Apply algorithms.
102oneshot(
103 model=model,
104 dataset=ds,
105 recipe=recipe,
106 max_seq_length=MAX_SEQUENCE_LENGTH,
107 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
108 data_collator=data_collator,
109)
110
111
112# Save to disk compressed.
113save_name = f"{model_id.split('/')[-1]}-quantized.w8a8"
114save_path = os.path.join(args.save_dir, save_name)
115print("Saving model:", save_path)
116model.save_pretrained(save_path, save_compressed=True)
117processor.save_pretrained(save_path)lmms-eval \
--model=whisper_vllm \
--model_args="pretrained=neuralmagic-ent/whisper-large-v2-quantized.w8a8" \
--batch_size 64 \
--output_path <output_file_path> \
--tasks librispeechlmms-eval \
--model=whisper_vllm \
--model_args="pretrained=neuralmagic-ent/whisper-large-v2-quantized.w8a8" \
--batch_size 64 \
--output_path <output_file_path> \
--tasks fleurs| Benchmark | Split | BF16 | w8a8 | Recovery (%) |
|---|---|---|---|---|
| LibriSpeech (WER) | test-clean | 3.1437 | 3.1343 | 100.30% |
| test-other | 5.2362 | 5.2021 | 100.66% | |
| Fleurs (X→en, WER) | cmn_hans_cn | 15.2148 | 15.4498 | 98.48% |
| en | 4.0717 | 4.0717 | 100.00% | |
| yue_hant_hk | 8.5106 | 8.3830 | 101.52% |