模型简介
模型特点
模型能力
使用案例
语言:
- 英语
- 中文
- 德语
- 西班牙语
- 俄语
- 韩语
- 法语
- 日语
- 葡萄牙语
- 土耳其语
- 波兰语
- 加泰罗尼亚语
- 荷兰语
- 阿拉伯语
- 瑞典语
- 意大利语
- 印尼语
- 印地语
- 芬兰语
- 越南语
- 希伯来语
- 乌克兰语
- 希腊语
- 马来语
- 捷克语
- 罗马尼亚语
- 丹麦语
- 匈牙利语
- 泰米尔语
- 挪威语
- 泰语
- 乌尔都语
- 克罗地亚语
- 保加利亚语
- 立陶宛语
- 拉丁语
- 毛利语
- 马拉雅拉姆语
- 威尔士语
- 斯洛伐克语
- 泰卢固语
- 波斯语
- 拉脱维亚语
- 孟加拉语
- 塞尔维亚语
- 阿塞拜疆语
- 斯洛文尼亚语
- 卡纳达语
- 爱沙尼亚语
- 马其顿语
- 布列塔尼语
- 巴斯克语
- 冰岛语
- 亚美尼亚语
- 尼泊尔语
- 蒙古语
- 波斯尼亚语
- 哈萨克语
- 阿尔巴尼亚语
- 斯瓦希里语
- 加利西亚语
- 马拉地语
- 旁遮普语
- 僧伽罗语
- 高棉语
- 绍纳语
- 约鲁巴语
- 索马里语
- 南非荷兰语
- 奥克语
- 格鲁吉亚语
- 白俄罗斯语
- 塔吉克语
- 信德语
- 古吉拉特语
- 阿姆哈拉语
- 意第绪语
- 老挝语
- 乌兹别克语
- 法罗语
- 海地克里奥尔语
- 普什图语
- 土库曼语
- 新挪威语
- 马耳他语
- 梵语
- 卢森堡语
- 缅甸语
- 藏语
- 他加禄语
- 马尔加什语
- 阿萨姆语
- 鞑靼语
- 夏威夷语
- 林加拉语
- 豪萨语
- 巴什基尔语
- 爪哇语
- 巽他语 标签:
- 音频
- 自动语音识别
- hf-asr排行榜 小部件:
- 示例标题: Librispeech样本1 src: https://cdn-media.huggingface.co/speech_samples/sample1.flac
- 示例标题: Librispeech样本2 src: https://cdn-media.huggingface.co/speech_samples/sample2.flac 管道标签: 自动语音识别 许可证: apache-2.0
Whisper
Whisper是由OpenAI的Alec Radford等人在论文通过大规模弱监督实现鲁棒语音识别中提出的最先进的自动语音识别(ASR)和语音翻译模型。该模型在超过500万小时的标注数据上训练,展示了在零样本设置下对多种数据集和领域的强大泛化能力。
Whisper large-v3的架构与之前的large和large-v2模型相同,只有以下细微差异:
- 频谱图输入使用128个梅尔频率箱而非80个
- 新增了粤语的语言标记
Whisper large-v3模型在100万小时的弱标注音频和400万小时使用Whisper large-v2收集的伪标注音频上训练。模型在这个混合数据集上训练了2.0个周期。
与Whisper large-v2相比,large-v3模型在多种语言上表现出性能提升,错误率降低了10%至20%。有关可用检查点的更多详情,请参阅模型详情部分。
免责声明: 本模型卡的内容部分由🤗 Hugging Face团队编写,部分复制粘贴自原始模型卡。
使用
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"])
要转录本地音频文件,只需在调用管道时传递音频文件的路径:
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"
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"
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支持且未使用torch.compile,我们建议使用Flash-Attention 2。为此,首先安装Flash Attention:
pip install flash-attn --no-build-isolation
然后向from_pretrained
传递attn_implementation="flash_attention_2"
:
model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="flash_attention_2")
Torch Scale-Product-Attention (SDPA)
如果您的GPU不支持Flash Attention,我们建议使用PyTorchscaled dot-product attention (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 | [✓](https://huggingface.co/openai |



