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-v3-turbo-quantized.w4a16",
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("==========================================")1podman run --rm -it --device nvidia.com/gpu=all -p 8000:8000 \
2 --ipc=host \
3--env "HUGGING_FACE_HUB_TOKEN=$HF_TOKEN" \
4--env "HF_HUB_OFFLINE=0" -v ~/.cache/vllm:/home/vllm/.cache \
5--name=vllm \
6registry.access.redhat.com/rhaiis/rh-vllm-cuda \
7vllm serve \
8--tensor-parallel-size 8 \
9--max-model-len 32768 \
10--enforce-eager --model RedHatAI/whisper-large-v3-turbo-quantized.w4a161# Setting up vllm server with ServingRuntime
2# Save as: vllm-servingruntime.yaml
3apiVersion: serving.kserve.io/v1alpha1
4kind: ServingRuntime
5metadata:
6 name: vllm-cuda-runtime # OPTIONAL CHANGE: set a unique name
7 annotations:
8 openshift.io/display-name: vLLM NVIDIA GPU ServingRuntime for KServe
9 opendatahub.io/recommended-accelerators: '["nvidia.com/gpu"]'
10 labels:
11 opendatahub.io/dashboard: 'true'
12spec:
13 annotations:
14 prometheus.io/port: '8080'
15 prometheus.io/path: '/metrics'
16 multiModel: false
17 supportedModelFormats:
18 - autoSelect: true
19 name: vLLM
20 containers:
21 - name: kserve-container
22 image: quay.io/modh/vllm:rhoai-2.25-cuda # CHANGE if needed. If AMD: quay.io/modh/vllm:rhoai-2.25-rocm
23 command:
24 - python
25 - -m
26 - vllm.entrypoints.openai.api_server
27 args:
28 - "--port=8080"
29 - "--model=/mnt/models"
30 - "--served-model-name={{.Name}}"
31 env:
32 - name: HF_HOME
33 value: /tmp/hf_home
34 ports:
35 - containerPort: 8080
36 protocol: TCP1# Attach model to vllm server. This is an NVIDIA template
2# Save as: inferenceservice.yaml
3apiVersion: serving.kserve.io/v1beta1
4kind: InferenceService
5metadata:
6 annotations:
7 openshift.io/display-name: whisper-large-v3-turbo-quantized.w4a16 # OPTIONAL CHANGE
8 serving.kserve.io/deploymentMode: RawDeployment
9 name: whisper-large-v3-turbo-quantized.w4a16 # specify model name. This value will be used to invoke the model in the payload
10 labels:
11 opendatahub.io/dashboard: 'true'
12spec:
13 predictor:
14 maxReplicas: 1
15 minReplicas: 1
16 model:
17 modelFormat:
18 name: vLLM
19 name: ''
20 resources:
21 limits:
22 cpu: '2' # this is model specific
23 memory: 8Gi # this is model specific
24 nvidia.com/gpu: '1' # this is accelerator specific
25 requests: # same comment for this block
26 cpu: '1'
27 memory: 4Gi
28 nvidia.com/gpu: '1'
29 runtime: vllm-cuda-runtime # must match the ServingRuntime name above
30 storageUri: oci://registry.redhat.io/rhelai1/modelcar-whisper-large-v3-turbo-quantized-w4a16:1.5
31 tolerations:
32 - effect: NoSchedule
33 key: nvidia.com/gpu
34 operator: Exists1# make sure first to be in the project where you want to deploy the model
2# oc project <project-name>
3
4# apply both resources to run model
5
6# Apply the ServingRuntime
7oc apply -f vllm-servingruntime.yaml
81# Replace <inference-service-name> and <cluster-ingress-domain> below:
2# - Run `oc get inferenceservice` to find your URL if unsure.
3
4# Call the server using curl:
5curl https://<inference-service-name>-predictor-default.<domain>/v1/chat/completions
6 -H "Content-Type: application/json" \
7 -d '{
8 "model": "whisper-large-v3-turbo-quantized.w4a16",
9 "stream": true,
10 "stream_options": {
11 "include_usage": true
12 },
13 "max_tokens": 1,
14 "messages": [
15 {
16 "role": "user",
17 "content": "How can a bee fly when its wings are so small?"
18 }
19 ]
20}'
21python quantize.py --model_path openai/whisper-large-v3-turbo --quant_path "output_dir/whisper-large-v3-turbo-quantized.w4a16" --calib_size 1024 --group_size 64 --dampening_frac 0.01 --actorder weight1import 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('--actorder', type=str, default="dynamic")
19parser.add_argument('--group_size', type=int, default=128)
20parser.add_argument('--save_dir', type=str, required=True)
21
22
23args = parser.parse_args()
24model_id = args.model_path
25
26model = TraceableWhisperForConditionalGeneration.from_pretrained(
27 model_id,
28 device_map="auto",
29 torch_dtype="auto",
30)
31model.config.forced_decoder_ids = None
32processor = WhisperProcessor.from_pretrained(model_id)
33
34# Configure processor the dataset task.
35processor.tokenizer.set_prefix_tokens(language="en", task="transcribe")
36
37# Select calibration dataset.
38DATASET_ID = "MLCommons/peoples_speech"
39DATASET_SUBSET = "test"
40DATASET_SPLIT = "test"
41
42# Select number of samples for calibration. 512 samples is a good place to start.
43# Increasing the number of samples can improve accuracy.
44
45NUM_CALIBRATION_SAMPLES = args.calib_size
46MAX_SEQUENCE_LENGTH = 2048
47dampening_frac=args.dampening_frac
48actorder_arg=args.actorder
49group_size=args.group_size
50
51# Load dataset and preprocess.
52ds = load_dataset(
53 DATASET_ID,
54 DATASET_SUBSET,
55 split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]",
56 trust_remote_code=True,
57)
58
59def preprocess(example):
60 return {
61 "array": example["audio"]["array"],
62 "sampling_rate": example["audio"]["sampling_rate"],
63 "text": " " + example["text"].capitalize(),
64 }
65
66ds = ds.map(preprocess, remove_columns=ds.column_names)
67
68# Process inputs.
69def process(sample):
70 inputs = processor(
71 audio=sample["array"],
72 sampling_rate=sample["sampling_rate"],
73 text=sample["text"],
74 add_special_tokens=True,
75 return_tensors="pt",
76 )
77
78 inputs["input_features"] = inputs["input_features"].to(dtype=model.dtype)
79 inputs["decoder_input_ids"] = inputs["labels"]
80 del inputs["labels"]
81
82 return inputs
83
84ds = ds.map(process, remove_columns=ds.column_names)
85
86# Define a oneshot data collator for multimodal inputs.
87def data_collator(batch):
88 assert len(batch) == 1
89 return {key: torch.tensor(value) for key, value in batch[0].items()}
90
91ignore=["lm_head"]
92
93# Recipe
94recipe = GPTQModifier(
95 targets="Linear",
96 config_groups={
97 "config_group": QuantizationScheme(
98 targets=["Linear"],
99 weights=QuantizationArgs(
100 num_bits=4,
101 type=QuantizationType.INT,
102 strategy=QuantizationStrategy.GROUP,
103 group_size=group_size,
104 symmetric=True,
105 dynamic=False,
106 actorder=getattr(ActivationOrdering, actorder_arg.upper()),
107 ),
108 ),
109 },
110 sequential_targets=["WhisperEncoderLayer", "WhisperDecoderLayer"],
111 ignore=["re:.*lm_head"],
112 update_size=NUM_CALIBRATION_SAMPLES,
113 dampening_frac=dampening_frac
114)
115
116# Apply algorithms.
117oneshot(
118 model=model,
119 dataset=ds,
120 recipe=recipe,
121 max_seq_length=MAX_SEQUENCE_LENGTH,
122 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
123 data_collator=data_collator,
124)
125
126
127# Save to disk compressed.
128save_name = f"{model_id.split('/')[-1]}-quantized.w4a16"
129save_path = os.path.join(args.save_dir, save_name)
130print("Saving model:", save_path)
131model.save_pretrained(save_path, save_compressed=True)
132processor.save_pretrained(save_path)lmms-eval \
--model=whisper_vllm \
--model_args="pretrained=neuralmagic-ent/whisper-large-v3-turbo-quantized.w4a16" \
--batch_size 64 \
--output_path <output_file_path> \
--tasks librispeechlmms-eval \
--model=whisper_vllm \
--model_args="pretrained=neuralmagic-ent/whisper-large-v3-turbo-quantized.w4a16" \
--batch_size 64 \
--output_path <output_file_path> \
--tasks fleurs| Benchmark | Split | BF16 | W4A16 | Recovery (%) |
|---|---|---|---|---|
| LibriSpeech (WER) | test-clean | 2.1876 | 2.1951 | 99.66% |
| test-other | 3.8992 | 4.0411 | 96.49% | |
| Fleurs (X→en, WER) | cmn_hans_cn | 7.8019 | 8.3448 | 93.49% |
| en | 4.0236 | 4.0580 | 99.15 | |
| yue_hant_hk | 9.4210 | 11.8108 | 97.77% |