HuggingFace镜像/whisper-large-v3-turbo
模型介绍文件和版本分析

Whisper

Whisper 是一种先进的自动语音识别(ASR)和语音翻译模型,由 OpenAI 的 Alec Radford 等人在论文
通过大规模弱监督实现稳健语音识别 中提出。该模型在超过 500 万小时的标注数据上训练,展现了在零样本设置下对多种数据集和领域的强大泛化能力。

Whisper large-v3-turbo 是经过剪枝优化的 Whisper large-v3 版本。换言之,这是完全相同的模型,只是解码层数从 32 层减少到了 4 层。
因此,模型速度大幅提升,但代价是质量略有下降。更多详情可参阅 GitHub 讨论。

免责声明:本模型卡内容部分由 🤗 Hugging Face 团队撰写,部分复制粘贴自原始模型卡。

使用方法

Hugging Face 🤗 Transformers 支持 Whisper large-v3-turbo。要运行该模型,首先需安装 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 解码策略兼容,例如温度回退(temperature fallback)和基于前序标记的条件解码。以下示例展示了如何启用这些启发式方法:

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)

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 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 应用额外的速度和内存优化,以进一步降低推理速度并减少显存占用。

分块长音频处理

Whisper 的接收域为 30 秒。要转录超过此时长的音频,需采用以下两种长音频算法之一:

  1. 顺序处理: 使用“滑动窗口”进行缓冲推理,依次转录 30 秒的音频片段
  2. 分块处理: 将长音频文件分割为较短的片段(各段之间有少量重叠),独立转录每个片段,并在边界处拼接最终结果

在以下任一场景中应使用顺序长音频算法:

  1. 转录准确性最为重要,而速度次之
  2. 您正在转录批量长音频文件,此时顺序处理的延迟与分块处理相当,同时准确率可提升 0.5% WER

相反,分块算法适用于以下情况:

  1. 转录速度最为关键
  2. 您正在处理单个长音频文件

默认情况下,Transformers 使用顺序算法。要启用分块算法,需向 pipeline 传递 chunk_length_s 参数。对于 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 支持且未使用 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 缩放点积注意力 (SDPA)

若您的 GPU 不支持 Flash Attention,我们推荐使用 PyTorch 的缩放点积注意力 (SDPA)。
该注意力实现在 PyTorch 2.1.1 及以上版本中默认启用。您可以通过运行以下 Python 代码片段来检查当前 PyTorch 版本是否兼容:

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链接:

规格参数量仅英语版多语言版
tiny39 M✓✓
base74 M✓✓
small244 M✓✓
medium769 M✓✓
large1550 Mx✓
large-v21550 Mx✓
large-v31550 Mx✓
large-v3-turbo809 Mx✓

微调

预训练的Whisper模型展现出强大的跨数据集和跨领域泛化能力。但通过微调可进一步提升其在特定语言和任务上的预测性能。博客文章使用🤗 Transformers微调Whisper提供了分步指南,仅需5小时标注数据即可完成微调。

评估用途

这些模型的主要目标用户是研究当前模型鲁棒性、泛化能力、性能边界、偏见及局限性的AI研究人员。但Whisper也可作为开发者的ASR解决方案,尤其适用于英语语音识别。我们意识到模型一旦发布,既无法限制仅用于"目标"场景,也难以界定合理的研究边界。

模型主要针对ASR和语音翻译至英语任务进行训练评估,在约10种语言中展现出强劲的ASR效果。若在语音活动检测、说话人分类或说话人日志等任务上微调,可能表现出额外能力,但这些领域尚未经过严格评估。强烈建议用户在部署前针对特定场景和领域进行全面评估。

特别警示:请勿使用Whisper转录未经当事人同意的录音,或将其用于任何主观分类场景。不建议在高风险领域(如决策场景)使用,因为准确率缺陷可能导致严重后果。该模型设计用途仅为语音转录和翻译,未经评估的分类应用(特别是涉及人类特征推断)极不恰当。

训练数据

未提供相关信息。

性能与局限

研究表明,相比现有ASR系统,该模型在口音、背景噪声、专业术语的鲁棒性方面表现更优,并具备多语言到英语的零样本翻译能力,其语音识别和翻译准确率接近最先进水平。

但由于模型采用弱监督方式在大规模噪声数据上训练,预测结果可能包含音频中未实际出现的内容(即幻觉现象)。我们推测这是因为模型在结合语言通用知识预测下一词时,与音频转录任务产生了交互。

模型在不同语言上表现不均,在低资源/低可见性语言或训练数据不足的语言上准确率较低。对于特定语言的不同口音和方言(可能涉及性别、种族、年龄等人口统计特征),模型表现也存在差异。完整评估结果详见随版本发布的论文。

此外,序列到序列架构可能导致文本重复生成,虽可通过束搜索和温度调度部分缓解,但无法完全避免。论文中提供了更多关于这些局限的分析。在低资源/低可见性语言上,此类行为和幻觉现象可能更严重。

广泛影响

我们预期Whisper的转录能力可用于改进无障碍工具。虽然模型本身不支持实时转录,但其速度和体积优势使得开发者能基于其构建近实时语音识别和翻译应用。基于Whisper构建的优质应用的实际价值表明,模型性能差异可能产生真实的经济影响。

发布Whisper也存在潜在的双重用途风险。虽然我们希望该技术主要用于有益领域,但ASR技术的普及可能使更多行为体能够构建监控技术或扩大现有监控规模——因为其速度和准确性使得海量音频通信的自动转录/翻译成本大幅降低。此外,这些模型可能具备开箱即用的特定个体识别能力,进而引发与双重用途和性能差异相关的安全隐患。实际上,我们认为转录成本并非监控项目规模化的限制因素。

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}
}