8位量化为何未提升Whisper-Large-V3在NVIDIA T4 GPU的推理速度?
Whisper-Large-V3 8位量化推理速度变慢问题排查
我使用Hugging Face Transformers进行Whisper推理,通过bitsandbytes实现load_in_8bit量化。在NVIDIA T4 GPU上以8位模式加载Whisper-Large-V3时,对27秒的sample.mp3文件推理耗时增至原模式的5倍,nvidia-smi显示GPU利用率仅为33%——按常理量化应提升GPU推理速度,此现象与预期不符。
可能的原因及优化方案
- 数据类型不匹配引发额外开销:手动将输入特征转为
torch.float16,可能与8位量化模型的输入精度要求不匹配,触发不必要的类型转换耗时。建议去掉手动类型转换步骤,让特征提取器返回的张量自动适配模型的设备与精度。 - 设备调度不合理:
device_map='auto'可能导致部分模型层落在CPU上,或引发GPU与CPU间频繁数据传输,拖慢推理速度。可强制设置device_map='cuda',确保模型全量加载到GPU。 - 量化配置未开启硬件优化:默认的8位量化未针对T4 GPU做适配,添加
bnb_8bit_use_double_quant=True和bnb_8bit_quant_type="nf4"参数,能提升量化模型的推理效率与稳定性。 - 生成参数未适配量化模型:Whisper的
generate默认参数可能包含冗余计算步骤,比如采样或多beam搜索,可通过设置do_sample=False、beam_size=1减少无效计算,同时明确开启use_cache=True复用中间结果。
修改后的推理代码
import torch from transformers import WhisperFeatureExtractor, WhisperTokenizerFast, AutoModelForSpeechSeq2Seq from transformers.pipelines.audio_classification import ffmpeg_read MODEL_NAME = "openai/whisper-large-v3" tokenizer = WhisperTokenizerFast.from_pretrained(MODEL_NAME) feature_extractor = WhisperFeatureExtractor.from_pretrained(MODEL_NAME) # 优化量化配置与设备映射,确保全量GPU加载 model_8bit = AutoModelForSpeechSeq2Seq.from_pretrained( MODEL_NAME, device_map='cuda', load_in_8bit=True, bnb_8bit_use_double_quant=True, bnb_8bit_quant_type="nf4" ) sample = "sample.mp3" #27s long with torch.inference_mode(): with open(sample, "rb") as f: inputs = f.read() inputs = ffmpeg_read(inputs, feature_extractor.sampling_rate) # 自动适配模型设备与精度,去掉手动类型转换 input_features = feature_extractor( inputs, sampling_rate=feature_extractor.sampling_rate, return_tensors='pt' )['input_features'].to(model_8bit.device) # 优化generate参数,减少冗余计算 forced_decoder_ids_output = model_8bit.generate( input_features=input_features, return_timestamps=False, do_sample=False, beam_size=1, use_cache=True ) out = tokenizer.decode(forced_decoder_ids_output.squeeze()) print(out)
内容的提问来源于stack exchange,提问作者buio
相关产品推荐
相关产品推荐

