模型简介
模型特点
模型能力
使用案例
🚀 Whisper
Whisper是一款先进的自动语音识别(ASR)和语音翻译模型,由OpenAI的Alec Radford等人在论文 Robust Speech Recognition via Large-Scale Weak Supervision 中提出。该模型在超过500万小时的标注数据上进行训练,在零样本设置下,对许多数据集和领域都展现出了强大的泛化能力。
🚀 快速开始
Whisper large-v3在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"
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:
```python import torch from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor from datasets import Audio, load_datasetdevice = "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"
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)
</details>
## ✨ 主要特性
### 模型架构
Whisper large-v3与之前的 [large](https://huggingface.co/openai/whisper-large) 和 [large-v2](https://huggingface.co/openai/whisper-large-v2) 模型具有相同的架构,但有以下细微差异:
1. 频谱图输入使用128个梅尔频率 bins,而不是80个。
2. 新增了粤语的语言标记。
### 训练数据
该模型在100万小时的弱标记音频和400万小时使用Whisper [large-v2](https://huggingface.co/openai/whisper-large-v2) 收集的伪标记音频上进行训练。模型在这个混合数据集上训练了2.0个周期。
### 性能提升
large-v3模型在多种语言上表现出了更好的性能,与Whisper [large-v2](https://huggingface.co/openai/whisper-large-v2) 相比,错误率降低了10%到20%。
## 🔧 技术细节
### 模型类型
Whisper是一种基于Transformer的编码器 - 解码器模型,也称为 _序列到序列_ 模型。有两种类型的Whisper模型:仅英语和多语言。仅英语模型在英语语音识别任务上进行训练。多语言模型同时在多语言语音识别和语音翻译任务上进行训练。对于语音识别,模型预测与音频 _相同_ 语言的转录。对于语音翻译,模型预测与音频 _不同_ 语言的转录。
### 模型配置
Whisper检查点有五种不同模型大小的配置。最小的四种有仅英语和多语言版本。最大的检查点仅有多语言版本。所有十个预训练检查点都可以在 [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper) 上找到。以下表格总结了这些检查点,并提供了Hub上模型的链接:
| 大小 | 参数数量 | 仅英语 | 多语言 |
| ---- | ---- | ---- | ---- |
| tiny | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny) |
| base | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |
| small | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |
| medium | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |
| large | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |
| large-v2 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v2) |
| large-v3 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v3) |
### 训练数据
large-v3检查点在100万小时的弱标记音频和400万小时使用Whisper large-v2收集的伪标记音频上进行训练。如 [随附论文](https://cdn.openai.com/papers/whisper.pdf) 中所述,我们发现给定语言的转录性能与该语言的训练数据量直接相关。
### 性能和局限性
- **优点**:与许多现有的ASR系统相比,该模型对口音、背景噪音、专业语言具有更强的鲁棒性,并且能够从多种语言零样本翻译为英语;语音识别和翻译的准确性接近当前的先进水平。
- **缺点**:
- 由于模型是使用大规模噪声数据进行弱监督训练的,预测结果可能包含音频输入中实际未说出的文本(即幻觉)。
- 模型在不同语言上的表现不均衡,在低资源和/或低可发现性语言或训练数据较少的语言上,准确性较低。
- 模型在特定语言的不同口音和方言上表现也不同,这可能包括不同性别、种族、年龄或其他人口统计标准的说话者之间的单词错误率较高。
- 模型的序列到序列架构使其容易生成重复文本,尽管可以通过束搜索和温度调度在一定程度上缓解,但无法完全解决。
## 📚 详细文档
### 额外的速度和内存优化
可以对Whisper应用额外的速度和内存优化,以进一步降低推理速度和显存要求。
#### 分块长音频处理
Whisper的接收域为30秒。要转录超过此长度的音频,需要使用以下两种长音频算法之一:
1. **顺序算法**:使用“滑动窗口”进行缓冲推理,逐个转录30秒的片段。
2. **分块算法**:将长音频文件分割成较短的文件(片段之间有小的重叠),独立转录每个片段,并在边界处拼接生成的转录结果。
在以下情况下应使用顺序长音频算法:
1. 转录准确性是最重要的因素,而速度不是主要考虑因素。
2. 正在转录 **批量** 长音频文件,在这种情况下,顺序算法的延迟与分块算法相当,但准确性可提高多达0.5%的单词错误率。
相反,在以下情况下应使用分块算法:
1. 转录速度是最重要的因素。
2. 正在转录 **单个** 长音频文件。
默认情况下,Transformers使用顺序算法。要启用分块算法,请将 `chunk_length_s` 参数传递给 `pipeline`。对于large-v3,30秒的分块长度是最优的。要对长音频文件进行批处理,请传递参数 `batch_size`:
```python
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"
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"
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:
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模型对不同的数据集和领域具有很强的泛化能力。然而,通过 微调,可以进一步提高其在某些语言和任务上的预测能力。博客文章 Fine-Tune Whisper with 🤗 Transformers 提供了一个逐步指南,介绍如何使用低至5小时的标记数据对Whisper模型进行微调。
评估使用
这些模型的主要目标用户是研究当前模型的鲁棒性、泛化能力、功能、偏差和局限性的AI研究人员。然而,Whisper作为一种ASR解决方案,对开发者也可能非常有用,特别是在英语语音识别方面。我们认识到,一旦模型发布,就不可能将其访问限制在“预期”用途上,也难以围绕什么是或不是研究制定合理的指导方针。
这些模型主要在ASR和语音翻译为英语的任务上进行训练和评估。它们在约10种语言的语音识别中表现出强大的性能。它们可能具有额外的功能,特别是如果在某些任务(如语音活动检测、说话人分类或说话人分割)上进行微调,但在这些领域尚未进行全面评估。我们强烈建议用户在特定上下文和领域中对模型进行全面评估后再部署。
特别是,我们警告不要使用Whisper模型转录未经个人同意录制的音频,或声称使用这些模型进行任何主观分类。我们不建议在高风险领域(如决策环境)中使用,因为准确性的缺陷可能导致结果出现明显缺陷。这些模型旨在转录和翻译语音,将模型用于分类不仅未经过评估,而且不合适,特别是用于推断人类属性。
📄 许可证
本项目采用Apache 2.0许可证。
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}
}



