模型概述
模型特點
模型能力
使用案例
🚀 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}
}



