模型简介
模型特点
模型能力
使用案例
语言:
- 英语
- 中文
- 德语
- 西班牙语
- 俄语
- 韩语
- 法语
- 日语
- 葡萄牙语
- 土耳其语
- 波兰语
- 加泰罗尼亚语
- 荷兰语
- 阿拉伯语
- 瑞典语
- 意大利语
- 印尼语
- 印地语
- 芬兰语
- 越南语
- 希伯来语
- 乌克兰语
- 希腊语
- 马来语
- 捷克语
- 罗马尼亚语
- 丹麦语
- 匈牙利语
- 泰米尔语
- 挪威语
- 泰语
- 乌尔都语
- 克罗地亚语
- 保加利亚语
- 立陶宛语
- 拉丁语
- 毛利语
- 马拉雅拉姆语
- 威尔士语
- 斯洛伐克语
- 泰卢固语
- 波斯语
- 拉脱维亚语
- 孟加拉语
- 塞尔维亚语
- 阿塞拜疆语
- 斯洛文尼亚语
- 卡纳达语
- 爱沙尼亚语
- 马其顿语
- 布列塔尼语
- 巴斯克语
- 冰岛语
- 亚美尼亚语
- 尼泊尔语
- 蒙古语
- 波斯尼亚语
- 哈萨克语
- 阿尔巴尼亚语
- 斯瓦希里语
- 加利西亚语
- 马拉地语
- 旁遮普语
- 僧伽罗语
- 高棉语
- 绍纳语
- 约鲁巴语
- 索马里语
- 南非荷兰语
- 奥克语
- 格鲁吉亚语
- 白俄罗斯语
- 塔吉克语
- 信德语
- 古吉拉特语
- 阿姆哈拉语
- 意第绪语
- 老挝语
- 乌兹别克语
- 法罗语
- 海地克里奥尔语
- 普什图语
- 土库曼语
- 新挪威语
- 马耳他语
- 梵语
- 卢森堡语
- 缅甸语
- 藏语
- 他加禄语
- 马尔加什语
- 阿萨姆语
- 鞑靼语
- 夏威夷语
- 林加拉语
- 豪萨语
- 巴什基尔语
- 爪哇语
- 巽他语 许可证: MIT 标签:
- 音频
- 自动语音识别 小部件:
- 示例标题: Librispeech 样本1 来源: https://cdn-media.huggingface.co/speech_samples/sample1.flac
- 示例标题: Librispeech 样本2 来源: https://cdn-media.huggingface.co/speech_samples/sample2.flac 流水线标签: 自动语音识别 基础模型:
- openai/whisper-large-v3 库名称: transformers
Whisper
Whisper 是由 OpenAI 的 Alec Radford 等人在论文《通过大规模弱监督实现鲁棒的语音识别》中提出的最先进的自动语音识别(ASR)和语音翻译模型。该模型在超过500万小时的标注数据上训练,展示了在零样本设置下对多种数据集和领域的强大泛化能力。
Whisper large-v3-turbo 是经过剪枝的 Whisper large-v3 的微调版本。换句话说,它是完全相同的模型,只是解码层从32层减少到4层。因此,模型速度大幅提升,但质量略有下降。更多细节可以在这个 GitHub 讨论中找到。
免责声明: 本模型卡的内容部分由 🤗 Hugging Face 团队撰写,部分复制粘贴自原始模型卡。
使用方法
Whisper large-v3-turbo 在 Hugging Face 🤗 Transformers 中得到支持。要运行该模型,首先安装 Transformers 库。在此示例中,我们还将安装 🤗 Datasets 以从 Hugging Face Hub 加载玩具音频数据集,以及 🤗 Accelerate 以减少模型加载时间:
pip install --upgrade pip
pip install --upgrade transformers datasets[audio] accelerate
该模型可以与 pipeline
类一起使用,以转录任意长度的音频:
import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from datasets import load_dataset
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "openai/whisper-large-v3-turbo"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
model.to(device)
processor = AutoProcessor.from_pretrained(model_id)
pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
torch_dtype=torch_dtype,
device=device,
)
dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
sample = dataset[0]["audio"]
result = pipe(sample)
print(result["text"])
要转录本地音频文件,只需在调用管道时传递音频文件的路径:
result = pipe("audio.mp3")
可以通过指定音频文件列表并设置 batch_size
参数来并行转录多个音频文件:
result = pipe(["audio_1.mp3", "audio_2.mp3"], batch_size=2)
Transformers 兼容所有 Whisper 解码策略,例如温度回退和基于先前令牌的条件。以下示例演示如何启用这些启发式方法:
generate_kwargs = {
"max_new_tokens": 448,
"num_beams": 1,
"condition_on_prev_tokens": False,
"compression_ratio_threshold": 1.35, # zlib 压缩比阈值(在令牌空间中)
"temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
"logprob_threshold": -1.0,
"no_speech_threshold": 0.6,
"return_timestamps": True,
}
result = pipe(sample, generate_kwargs=generate_kwargs)
Whisper 会自动预测源音频的语言。如果已知源音频语言,可以将其作为参数传递给管道:
result = pipe(sample, generate_kwargs={"language": "english"})
默认情况下,Whisper 执行语音转录任务,其中源音频语言与目标文本语言相同。要执行语音翻译任务,其中目标文本为英语,将任务设置为 "translate"
:
result = pipe(sample, generate_kwargs={"task": "translate"})
最后,可以让模型预测时间戳。对于句子级时间戳,传递 return_timestamps
参数:
result = pipe(sample, return_timestamps=True)
print(result["chunks"])
对于单词级时间戳:
result = pipe(sample, return_timestamps="word")
print(result["chunks"])
上述参数可以单独使用或组合使用。例如,要执行源音频为法语的语音转录任务,并返回句子级时间戳,可以使用以下代码:
result = pipe(sample, return_timestamps=True, generate_kwargs={"language": "french", "task": "translate"})
print(result["chunks"])
要更精细地控制生成参数,直接使用模型 + 处理器 API:
import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
from datasets import Audio, load_dataset
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "openai/whisper-large-v3-turbo"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
)
model.to(device)
processor = AutoProcessor.from_pretrained(model_id)
dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
dataset = dataset.cast_column("audio", Audio(processor.feature_extractor.sampling_rate))
sample = dataset[0]["audio"]
inputs = processor(
sample["array"],
sampling_rate=sample["sampling_rate"],
return_tensors="pt",
truncation=False,
padding="longest",
return_attention_mask=True,
)
inputs = inputs.to(device, dtype=torch_dtype)
gen_kwargs = {
"max_new_tokens": 448,
"num_beams": 1,
"condition_on_prev_tokens": False,
"compression_ratio_threshold": 1.35, # zlib 压缩比阈值(在令牌空间中)
"temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
"logprob_threshold": -1.0,
"no_speech_threshold": 0.6,
"return_timestamps": True,
}
pred_ids = model.generate(**inputs, **gen_kwargs)
pred_text = processor.batch_decode(pred_ids, skip_special_tokens=True, decode_with_timestamps=False)
print(pred_text)
额外的速度和内存改进
您可以对 Whisper 应用额外的速度和内存改进,以进一步减少推理速度和 VRAM 需求。
分块长格式
Whisper 的接收域为30秒。要转录超过此长度的音频,需要以下两种长格式算法之一:
- 顺序式: 使用“滑动窗口”进行缓冲推理,逐个转录30秒的片段
- 分块式: 将长音频文件分割为较短的片段(片段之间有少量重叠),独立转录每个片段,并在边界处拼接生成的转录
在以下任一情况下应使用顺序式长格式算法:
- 转录准确性是最重要的因素,速度次之
- 您正在转录批量长音频文件,此时顺序式的延迟与分块式相当,但准确性高出0.5% WER
相反,在以下情况下应使用分块式算法:
- 转录速度是最重要的因素
- 您正在转录单个长音频文件
默认情况下,Transformers 使用顺序式算法。要启用分块式算法,将 chunk_length_s
参数传递给 pipeline
。对于 large-v3,30秒的块长度是最优的。要对长音频文件启用批处理,传递参数 batch_size
:
import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from datasets import load_dataset
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "openai/whisper-large-v3-turbo"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
)
model.to(device)
processor = AutoProcessor.from_pretrained(model_id)
pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
chunk_length_s=30,
batch_size=16, # 推理的批处理大小 - 根据您的设备设置
torch_dtype=torch_dtype,
device=device,
)
dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
sample = dataset[0]["audio"]
result = pipe(sample)
print(result["text"])
Torch 编译
Whisper 的前向传递与 torch.compile
兼容,可实现4.5倍的速度提升。
注意: torch.compile
目前与分块式长格式算法或 Flash Attention 2 不兼容 ⚠️
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from datasets import load_dataset
from tqdm import tqdm
torch.set_float32_matmul_precision("high")
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "openai/whisper-large-v3-turbo"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
).to(device)
# 启用静态缓存并编译前向传递
model.generation_config.cache_implementation = "static"
model.generation_config.max_new_tokens = 256
model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
processor = AutoProcessor.from_pretrained(model_id)
pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
torch_dtype=torch_dtype,
device=device,
)
dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
sample = dataset[0]["audio"]
# 2 个预热步骤
for _ in tqdm(range(2), desc="Warm-up step"):
with sdpa_kernel(SDPBackend.MATH):
result = pipe(sample.copy(), generate_kwargs={"min_new_tokens": 256, "max_new_tokens": 256})
# 快速运行
with sdpa_kernel(SDPBackend.MATH):
result = pipe(sample.copy())
print(result["text"])
Flash Attention 2
如果您的 GPU 支持且未使用 torch.compile,我们建议使用 Flash-Attention 2。为此,首先安装 Flash Attention:
pip install flash-attn --no-build-isolation
然后将 attn_implementation="flash_attention_2"
传递给 from_pretrained
:
model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="flash_attention_2")
Torch 缩放点积注意力 (SDPA)
如果您的 GPU 不支持 Flash Attention,我们建议使用 PyTorch 缩放点积注意力 (SDPA)。此注意力实现在 PyTorch 2.1.1 或更高版本中默认启用。要检查您是否有兼容的 PyTorch 版本,运行以下 Python 代码片段:
from transformers.utils import is_torch_sdpa_available
print(is_torch_sdpa_available())
如果上述返回 True
,则表示您安装了有效的 PyTorch 版本且 SDPA 默认启用。如果返回 False
,您需要根据官方说明升级 PyTorch 版本。
安装有效的 PyTorch 版本后,SDPA 默认启用。也可以通过指定 attn_implementation="sdpa"
显式设置:
model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="sdpa")
有关如何使用 SDPA 的更多信息,请参阅 Transformers SDPA 文档。
模型详情
Whisper 是一个基于 Transformer 的编码器-解码器模型,也称为序列到序列模型。Whisper 模型有两种风格:仅英语和多语言。仅英语模型在英语语音识别任务上训练。多语言模型同时在多语言语音识别和语音翻译任务上训练。对于语音识别,模型预测与音频相同语言的转录。对于语音翻译,模型预测与音频不同语言的转录。
Whisper 检查点有五种不同模型大小的配置。最小的四种可作为仅英语和多语言使用。最大的检查点仅有多语言版本。所有十个预训练检查点都可在 Hugging Face Hub 上找到。检查点在下表中总结,并附有 Hub 上的模型链接:
大小 | 参数数量 | 仅英语 | 多语言 |
---|---|---|---|
tiny | 39 M | ✓ | ✓ |
base | 74 M | [✓](https |



