模型简介
模型特点
模型能力
使用案例
🚀 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
✨ 主要特性
- 多语言支持:支持多种语言,包括英语、中文、德语、西班牙语等。
- 零样本泛化:在零样本设置下对许多数据集和领域都表现出强大的泛化能力。
- 速度提升:Whisper large-v3-turbo版本通过减少解码层数量,大幅提升了模型速度。
📦 安装指南
pip install --upgrade pip
pip install --upgrade transformers datasets[audio] accelerate
💻 使用示例
基础用法
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 compression ratio threshold (in token space)
"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"})
进行语音翻译
result = pipe(sample, generate_kwargs={"task": "translate"})
预测时间戳
- 句子级时间戳
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 compression ratio threshold (in token space)
"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的接收域为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, # batch size for inference - set based on your device
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)
# Enable static cache and compile the forward pass
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 warmup steps
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})
# fast run
with sdpa_kernel(SDPBackend.MATH):
result = pipe(sample.copy())
print(result["text"])
Flash Attention 2
如果你的GPU支持Flash-Attention 2,并且你没有使用torch.compile,我们建议使用它。要使用它,首先安装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 | ✓ | ✓ |
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也带来了潜在的双重用途问题。虽然我们希望这项技术主要用于有益目的,但使自动语音识别技术更易于使用可能会使更多人能够构建强大的监控技术或扩大现有监控工作的规模,因为其速度和准确性使得大规模音频通信的自动转录和翻译变得经济可行。此外,这些模型可能具有直接识别特定个人的能力,这反过来又带来了与双重用途和不同性能相关的安全问题。实际上,我们预计转录成本不是扩大监控项目的限制因素。
📄 许可证
本项目采用MIT许可证。
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}
}



