HuggingFace镜像/distil-small.en
模型介绍
文件和版本
分析

Distil-Whisper: distil-small.en

Distil-Whisper 在论文 Robust Knowledge Distillation via Large-Scale Pseudo Labelling 中提出。 它是 Whisper 模型的蒸馏版本,推理速度快 6 倍,体积缩小 49%,并且在分布外评测集上的 WER 表现与原版差距不超过 1%。

本仓库是 distil-small.en 的托管仓库,它是 Whisper small.en 的蒸馏变体。 它是参数最少的 Distil-Whisper 检查点,仅有 1.66 亿参数,是内存受限应用场景(如端侧部署)的理想选择。

对于大多数其他应用场景,推荐使用 distil-medium.en 或 distil-large-v2 检查点,因为它们速度更快,且 WER 表现更优:

模型参数量 / M相对延迟 ↑短文本 WER ↓长文本 WER ↓
large-v315501.08.411.0
large-v215501.09.111.7
distil-large-v37566.39.710.8
distil-large-v27565.810.111.6
distil-medium.en3946.811.112.4
distil-small.en1665.612.112.8

注意: Distil-Whisper 目前仅支持英语语音识别。我们正与社区合作,将 Whisper 蒸馏至其他语言。如果你对将 Whisper 蒸馏到你的语言感兴趣,请查阅提供的训练代码。多语言检查点就绪后,我们将更新 Distil-Whisper 仓库!

为什么 distil-small.en 比 distil-large-v2 更慢?

虽然 distil-medium.en 和 distil-large-v2 各使用两个解码器层,而 distil-small.en 则使用了四个。更多的解码器层能够提升模型的 WER 性能,但代价是推理速度变慢。我们发现,四个层是让 distil-small.en 达到合理 WER 性能的最低要求——其 WER 表现与 Whisper large-v2 的差距在 3% 以内,同时速度提升了 5.6 倍。当我们尝试仅用两层进行知识蒸馏时,模型比 large-v2 差超过 5%,尽管速度提升了 7.8 倍。我们将蒸馏一个两层 small.en 模型的工作留待未来完成。

使用方法

Distil-Whisper 从 Hugging Face 🤗 Transformers 4.35 版本起获得支持。要运行该模型,请先安装最新版本的 Transformers 库。在本示例中,我们还将安装 🤗 Datasets 以便从 Hugging Face Hub 加载小型语音数据集:

pip install --upgrade pip
pip install --upgrade transformers accelerate datasets[audio]

短音频转录

该模型可配合 pipeline 类使用,以转录短音频文件(< 30 秒),方法如下:

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 = "distil-whisper/distil-small.en"

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,
    max_new_tokens=128,
    torch_dtype=torch_dtype,
    device=device,
)

dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
sample = dataset[0]["audio"]

result = pipe(sample)
print(result["text"])

要转录本地音频文件,只需在调用 pipeline 时传入音频文件的路径即可:

- result = pipe(sample)
+ result = pipe("audio.mp3")

长音频转录

Distil-Whisper 采用分块算法来转录长音频文件(超过 30 秒)。在实际使用中,该分块长音频算法比 Whisper 论文中 OpenAI 提出的顺序算法快 9 倍(参见 Distil-Whisper 论文 表 7)。

要启用分块,请向 pipeline 传入 chunk_length_s 参数。对于 Distil-Whisper,15 秒的分块长度效果最佳。要启用批处理,请传入 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 = "distil-whisper/distil-small.en"

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,
    max_new_tokens=128,
    chunk_length_s=15,
    batch_size=16,
    torch_dtype=torch_dtype,
    device=device,
)

dataset = load_dataset("distil-whisper/librispeech_long", "default", split="validation")
sample = dataset[0]["audio"]

result = pipe(sample)
print(result["text"])

推测解码

Distil-Whisper 可以作为 Whisper 的辅助模型,用于推测解码。 推测解码在数学上保证了与 Whisper 完全相同的输出,同时速度提升 2 倍。 这使其成为现有 Whisper 管道的理想即插即用替代方案,因为输出结果完全一致。

在下面的代码片段中,我们将辅助模型 Distil-Whisper 独立加载到主 Whisper 管道中。然后 将其指定为生成时的"辅助模型":

from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
import torch
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

assistant_model_id = "distil-whisper/distil-small.en"

assistant_model = AutoModelForSpeechSeq2Seq.from_pretrained(
    assistant_model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
assistant_model.to(device)

model_id = "openai/whisper-medium.en"

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,
    max_new_tokens=128,
    generate_kwargs={"assistant_model": assistant_model},
    torch_dtype=torch_dtype,
    device=device,
)

dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
sample = dataset[0]["audio"]

result = pipe(sample)
print(result["text"])

额外的速度与内存优化

你可以在 Distil-Whisper 上应用额外的速度和内存优化,具体内容如下。

Flash Attention

如果你的 GPU 支持,我们建议使用 Flash-Attention 2。 为此,你需要先安装 Flash Attention:

pip install flash-attn --no-build-isolation

然后你只需将 use_flash_attention_2=True 传递给 from_pretrained 即可:

- model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True)
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True, use_flash_attention_2=True)

Torch Scale-Product-Attention (SDPA)

如果你的 GPU 不支持 Flash Attention,我们建议使用 BetterTransformers。 为此,你需要先安装 optimum:

pip install --upgrade optimum

然后,在使用模型之前,先将其转换为 "BetterTransformer" 模型:

model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True)
+ model = model.to_bettertransformer()

在 openai-whisper 中运行 Distil-Whisper

若要在原始 Whisper 格式下使用该模型,请确保已安装 openai-whisper 包:

pip install --upgrade openai-whisper

以下代码片段展示了如何使用 🤗 Datasets 加载 LibriSpeech 数据集中的示例文件并进行转录:

import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from whisper import load_model, transcribe

distil_small_en = hf_hub_download(repo_id="distil-whisper/distil-small.en", filename="original-model.bin")
model = load_model(distil_small_en)

dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
sample = dataset[0]["audio"]["array"]
sample = torch.from_numpy(sample).float()

pred_out = transcribe(model, audio=sample)
print(pred_out["text"])

注意,首次运行示例时,模型权重将会被下载并保存到你的缓存目录中。之后,你可以直接复用同一示例,权重会从缓存中加载,无需再次下载。

要转录本地音频文件,只需将音频文件的路径作为 audio 参数传递给 transcribe:

pred_out = transcribe(model, audio="audio.mp3")

Whisper.cpp

Distil-Whisper 可以通过 Whisper.cpp 仓库运行,使用原始的长音频顺序转录算法。在一项 临时基准测试 中,distil-small.en 在 Mac M1 上的速度是 large-v2 的 4 倍以上,同时在长音频上的 WER 差距仅在 1.4% 以内。

快速上手步骤:

  1. 克隆 Whisper.cpp 仓库:
git clone https://github.com/ggerganov/whisper.cpp.git
cd whisper.cpp
  1. 从 Hugging Face Hub 下载 distil-small.en 的 ggml 权重文件:
python -c "from huggingface_hub import hf_hub_download; hf_hub_download(repo_id='distil-whisper/distil-small.en', filename='ggml-distil-small.en.bin', local_dir='./models')"

注意,如果你没有安装 huggingface_hub 包,也可以使用 wget 来下载权重文件:

wget https://huggingface.co/distil-whisper/distil-small.en/resolve/main/ggml-distil-small.en.bin -P ./models
  1. 使用提供的示例音频运行推理:
make -j && ./main -m models/ggml-distil-small.en.bin -f samples/jfk.wav

Transformers.js

Distil-Whisper 甚至可以通过 Transformers.js 完全在浏览器中运行:

  1. 从 NPM 安装 Transformers.js:
npm i @xenova/transformers
  1. 导入库,并使用 pipeline API 执行推理。
import { pipeline } from '@xenova/transformers';

const transcriber = await pipeline('automatic-speech-recognition', 'distil-whisper/distil-small.en');

const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
const output = await transcriber(url);
// { text: " And so my fellow Americans, ask not what your country can do for you. Ask what you can do for your country." }

在线体验 Distil-Whisper Web 演示,亲自动手试试吧。你会发现,它完全在浏览器中本地运行:无需任何服务器!

更多信息请参阅文档。

Candle

敬请期待!

8bit & 4bit 量化

敬请期待!

模型详情

Distil-Whisper 继承了 Whisper 的编码器-解码器架构。编码器将语音向量输入序列映射为隐藏状态向量序列。解码器则以自回归方式逐词预测文本 token,其预测条件为所有已生成的前序 token 及编码器的隐藏状态。因此,编码器只需前向传播一次,而解码器的执行次数等于生成的 token 总数。实际上,这意味着解码器占据了超过 90% 的总推理时间。所以,为了优化延迟,重点在于最小化解码器的推理时间。

在对 Whisper 模型进行蒸馏时,我们在保持编码器不变的前提下减少了解码器的层数。编码器(图中绿色部分)从教师模型完整复制到学生模型,并在训练过程中保持冻结。学生模型的解码器由教师模型解码器层的一个子集组成,这些层从间隔最大的层进行初始化。随后,模型通过 KL 散度损失与伪标签损失的加权和进行训练。

评估

以下代码片段演示了如何使用流式模式在 LibriSpeech validation.clean 数据集上评估 Distil-Whisper 模型,即无需将音频数据下载到本地设备。

首先,我们需要安装所需的软件包,包括用于流式加载音频数据的 🤗 Datasets 和用于执行 WER 计算的 🤗 Evaluate:

pip install --upgrade pip
pip install --upgrade transformers datasets[audio] evaluate jiwer

然后可以按照以下示例端到端地运行评估:

from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
from transformers.models.whisper.english_normalizer import EnglishTextNormalizer
from datasets import load_dataset
from evaluate import load
import torch
from tqdm import tqdm

# define our torch configuration
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model_id = "distil-whisper/distil-small.en"

# load the model + processor
model =  AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, use_safetensors=True, low_cpu_mem_usage=True)
model = model.to(device)
processor = AutoProcessor.from_pretrained(model_id)

# load the dataset with streaming mode
dataset = load_dataset("librispeech_asr", "clean", split="validation", streaming=True)

# define the evaluation metric
wer_metric = load("wer")
normalizer = EnglishTextNormalizer(processor.tokenizer.english_spelling_normalizer)

def inference(batch):
    # 1. Pre-process the audio data to log-mel spectrogram inputs
    audio = [sample["array"] for sample in batch["audio"]]
    input_features = processor(audio, sampling_rate=batch["audio"][0]["sampling_rate"], return_tensors="pt").input_features
    input_features = input_features.to(device, dtype=torch_dtype)
    
    # 2. Auto-regressively generate the predicted token ids
    pred_ids = model.generate(input_features, max_new_tokens=128)
    
    # 3. Decode the token ids to the final transcription
    batch["transcription"] = processor.batch_decode(pred_ids, skip_special_tokens=True)
    batch["reference"] = batch["text"]
    return batch

dataset = dataset.map(function=inference, batched=True, batch_size=16)

all_transcriptions = []
all_references = []

# iterate over the dataset and run inference
for i, result in tqdm(enumerate(dataset), desc="Evaluating..."):
    all_transcriptions.append(result["transcription"])
    all_references.append(result["reference"])

# normalize predictions and references
all_transcriptions = [normalizer(transcription) for transcription in all_transcriptions]
all_references = [normalizer(reference) for reference in all_references]

# compute the WER metric
wer = 100 * wer_metric.compute(predictions=all_transcriptions, references=all_references)
print(wer)

打印输出:

3.4326070294536297

用途

Distil-Whisper 旨在作为 Whisper 在英语语音识别领域的直接替代方案。具体来说,它在分布外测试数据上取得了与 Whisper 相当的 WER 表现,同时在短音频和长音频上的推理速度均提升 6 倍。

数据

Distil-Whisper 基于 Hugging Face Hub 上 9 个开源、许可宽松的语音数据集中的 22,000 小时音频数据进行训练:

DatasetSize / hSpeakersDomainLicence
People's Speech12,000unknownInternet ArchiveCC-BY-SA-4.0
Common Voice 133,000unknownNarrated WikipediaCC0-1.0
GigaSpeech2,500unknownAudiobook, podcast, YouTubeapache-2.0
Fisher1,96011,900Telephone conversationsLDC
LibriSpeech9602,480AudiobooksCC-BY-4.0
VoxPopuli5401,310European ParliamentCC0
TED-LIUM4502,030TED talksCC-BY-NC-ND 3.0
SwitchBoard260540Telephone conversationsLDC
AMI100unknownMeetingsCC-BY-4.0
总计21,77018,260+

合并后的数据集涵盖 10 个不同领域,包含超过 5 万名说话人。这种数据多样性对于确保蒸馏模型在不同音频分布和噪声条件下具有鲁棒性至关重要。

随后,使用 Whisper large-v2 模型对音频数据进行伪标注:我们利用 Whisper 为训练集中的所有音频生成预测结果,并将其作为训练时的目标标签。采用伪标签可以确保转录文本在各数据集之间具有一致的格式,同时在训练过程中提供序列级的蒸馏信号。

WER 过滤

Whisper 生成的伪标签预测可能存在转写错误和幻觉现象。为了确保仅在准确的伪标签上进行训练,我们在训练过程中采用了一种简单的 WER 启发式策略。首先,对 Whisper 伪标签和各数据集提供的真实标签进行归一化处理,然后计算两者之间的 WER。若 WER 超过指定阈值,则丢弃该训练样本;否则,保留该样本用于训练。

Distil-Whisper 论文第 9.2 节展示了该过滤机制对提升蒸馏模型下游性能的有效性。我们也将 Distil-Whisper 对幻觉的鲁棒性部分归因于此过滤机制。

训练

该模型共训练了 50,000 个优化步(或 12 个 epoch),批量大小为 2056。Tensorboard 训练日志可在此查看:https://huggingface.co/distil-whisper/distil-small.en/tensorboard?params=scalars#frame

结果

在分布外(OOD)短音频上,蒸馏模型的 WER 与 Whisper 的差距在 1% 以内;在 OOD 长音频上,蒸馏模型比 Whisper 低 0.1%。这一性能优势归因于更低的幻觉率。

如需查看各数据集的详细评测结果,请参阅 Distil-Whisper 论文中的表 16 和表 17。

Distil-Whisper 还在 ESB 基准数据集上进行了评测,该评测是 OpenASR 排行榜的一部分,其 WER 与 Whisper 的差距在 0.2% 以内。

复现 Distil-Whisper

用于复现 Distil-Whisper 的训练和评测代码可在 Distil-Whisper 仓库中找到:https://github.com/huggingface/distil-whisper/tree/main/training

许可证

Distil-Whisper 继承了 OpenAI Whisper 模型的 MIT 许可证。

引用

如果你使用了该模型,请考虑引用 Distil-Whisper 论文:

@misc{gandhi2023distilwhisper,
      title={Distil-Whisper: Robust Knowledge Distillation via Large-Scale Pseudo Labelling}, 
      author={Sanchit Gandhi and Patrick von Platen and Alexander M. Rush},
      year={2023},
      eprint={2311.00430},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

致谢

  • 感谢 OpenAI 提供 Whisper 模型 和原始代码库
  • 感谢 Hugging Face 🤗 Transformers 完成模型集成
  • 感谢 Google TPU Research Cloud (TRC) 项目提供 Cloud TPU v4s 资源
  • 感谢 @rsonavane 在 LibriSpeech 数据集上发布了 Distil-Whisper 的早期迭代版本