模型简介
模型特点
模型能力
使用案例
🚀 Whisper
Whisper是一款用于自动语音识别(ASR)和语音翻译的先进模型,由OpenAI的Alec Radford等人在论文Robust Speech Recognition via Large-Scale Weak Supervision中提出。该模型在超过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"])
要转录本地音频文件,只需在调用pipeline时传入音频文件的路径:
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会自动预测源音频的语言。如果事先知道源音频的语言,可以将其作为参数传递给pipeline:
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 large-v3-turbo模型,你需要安装必要的库。以下是安装步骤:
安装依赖库
pip install --upgrade pip
pip install --upgrade transformers datasets[audio] accelerate
可选安装
如果你想使用Flash Attention 2,需要先安装Flash Attention:
pip install flash-attn --no-build-isolation
💻 使用示例
基础用法
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")
并行转录多个音频文件
result = pipe(["audio_1.mp3", "audio_2.mp3"], batch_size=2)
启用特定解码策略
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)
指定源音频语言和任务
result = pipe(sample, generate_kwargs={"language": "english", "task": "translate"})
获取时间戳
# 句子级时间戳
result = pipe(sample, return_timestamps=True)
print(result["chunks"])
# 单词级时间戳
result = pipe(sample, return_timestamps="word")
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是一个基于Transformer的编码器 - 解码器模型,也被称为序列到序列模型。Whisper模型有两种类型:仅支持英语的模型和多语言模型。仅支持英语的模型是在英语语音识别任务上进行训练的,而多语言模型则同时在多语言语音识别和语音翻译任务上进行训练。对于语音识别任务,模型预测的转录文本与音频语言相同;对于语音翻译任务,模型预测的转录文本为英语。
Whisper的检查点有五种不同大小的配置。其中最小的四种有仅支持英语和多语言两种版本,最大的检查点只有多语言版本。所有十个预训练的检查点都可以在Hugging Face Hub上找到。以下表格总结了这些检查点,并提供了它们在Hub上的链接:
大小 | 参数数量 | 仅英语版本 | 多语言版本 |
---|---|---|---|
tiny | 39 M | ✓ | ✓ |
base | 74 M | ✓ | ✓ |
small | 244 M | ✓ | ✓ |
medium | 769 M | ✓ | ✓ |
large | 1550 M | x | ✓ |
large-v2 | 1550 M | x | ✓ |
large-v3 | 1550 M | x | ✓ |
large-v3-turbo | 809 M | x | ✓ |
微调
预训练的Whisper模型在不同的数据集和领域中表现出了很强的泛化能力。然而,通过微调,可以进一步提高其在某些语言和任务上的预测能力。博客文章Fine-Tune Whisper with 🤗 Transformers提供了一个逐步指南,介绍了如何使用低至5小时的标注数据来微调Whisper模型。
评估使用
这些模型的主要目标用户是研究当前模型的鲁棒性、泛化能力、性能、偏差和局限性的AI研究人员。然而,Whisper对于开发者来说,作为一种自动语音识别(ASR)解决方案也可能非常有用,特别是在英语语音识别方面。我们认识到,一旦模型发布,就不可能将其使用限制在“预期”用途上,也很难制定合理的准则来界定什么是研究,什么不是研究。
这些模型主要在自动语音识别和语音翻译为英语的任务上进行训练和评估。它们在约10种语言的自动语音识别任务中表现出了很强的性能。它们可能还具有其他能力,特别是在某些任务(如语音活动检测、说话人分类或说话人分割)上进行微调时,但在这些领域尚未进行全面评估。我们强烈建议用户在特定的上下文和领域中对模型进行全面评估后再进行部署。
特别是,我们警告不要使用Whisper模型在未经个人同意的情况下转录其录音,或声称使用这些模型进行任何形式的主观分类。我们不建议在高风险领域(如决策场景)中使用该模型,因为准确性的缺陷可能会导致结果出现明显的偏差。这些模型旨在转录和翻译语音,将其用于分类不仅未经过评估,而且不合适,特别是用于推断人类属性时。
训练数据
未提供相关信息。
性能和局限性
我们的研究表明,与许多现有的自动语音识别系统相比,这些模型在应对口音、背景噪音、专业语言方面表现出了更强的鲁棒性,并且在多种语言到英语的零样本翻译方面也有出色表现;在语音识别和翻译的准确性方面接近当前的先进水平。
然而,由于这些模型是使用大规模的嘈杂数据进行弱监督训练的,因此预测结果可能包含音频输入中实际未说出的文本(即幻觉现象)。我们推测,这是因为模型在利用其对语言的一般知识时,会同时尝试预测音频中的下一个单词和转录音频本身。
这些模型在不同语言上的表现并不均衡,我们发现对于资源较少和/或曝光度较低的语言,或者训练数据较少的语言,模型的准确性较低。此外,模型在特定语言的不同口音和方言上也表现出了差异,这可能包括不同性别、种族、年龄或其他人口统计学特征的说话者之间的单词错误率较高。我们的完整评估结果在本次发布的论文中有所呈现。
此外,模型的序列到序列架构使其容易生成重复的文本,虽然可以通过束搜索和温度调度在一定程度上缓解这一问题,但无法完全解决。论文中对这些局限性进行了进一步分析。在资源较少和/或曝光度较低的语言上,这种行为和幻觉现象可能会更严重。
更广泛的影响
我们预计Whisper模型的转录能力可用于改进无障碍工具。虽然Whisper模型本身不能直接用于实时转录,但其速度和规模表明,其他人可以在其基础上构建允许接近实时语音识别和翻译的应用程序。基于Whisper模型构建的有益应用程序的真正价值表明,这些模型的不同表现可能会产生实际的经济影响。
发布Whisper也存在潜在的双重用途问题。虽然我们希望这项技术主要用于有益的目的,但使自动语音识别技术更易于获取可能会使更多的人能够构建强大的监控技术或扩大现有的监控工作,因为其速度和准确性使得对大量音频通信进行经济实惠的自动转录和翻译成为可能。此外,这些模型可能具有直接识别特定个人的能力,这反过来又带来了与双重用途和不同表现相关的安全问题。实际上,我们预计转录成本并不是扩大监控项目的限制因素。
BibTeX引用
@misc{radford2022whisper,
doi = {10.48550/ARXIV.2212.04356},
url = {https://arxiv.org/abs/2212.04356},
author = {Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},
title = {Robust Speech Recognition via Large-Scale Weak Supervision},
publisher = {arXiv},
year = {2022},
copyright = {arXiv.org perpetual, non-exclusive license}
}
🔧 技术细节
额外的速度和内存优化
你可以对Whisper应用额外的速度和内存优化,以进一步降低推理速度和显存要求。
分块长音频处理
Whisper的感受野为30秒。要转录超过这个时长的音频,需要使用以下两种长音频算法之一:
- 顺序算法:使用“滑动窗口”进行缓冲推理,逐个转录30秒的音频片段。
- 分块算法:将长音频文件分割成较短的片段(片段之间有小的重叠),独立转录每个片段,然后在边界处拼接转录结果。
在以下两种情况下,应使用顺序长音频算法:
- 转录准确性是最重要的因素,而速度不是主要考虑因素。
- 你正在转录批量长音频文件,在这种情况下,顺序算法的延迟与分块算法相当,但准确性可提高多达0.5%的单词错误率。
相反,在以下情况下应使用分块算法:
- 转录速度是最重要的因素。
- 你正在转录单个长音频文件。
默认情况下,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支持Flash-Attention 2,并且你没有使用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文档。
📄 许可证
本项目采用MIT许可证。



