shimmyshimmer commited on
Commit
d01a317
·
verified ·
1 Parent(s): 9d6e2eb

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +467 -102
README.md CHANGED
@@ -1,199 +1,564 @@
1
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  library_name: transformers
3
- tags: []
4
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # Model Card for Model ID
 
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
 
9
 
 
 
 
10
 
 
 
11
 
12
- ## Model Details
 
 
13
 
14
- ### Model Description
15
 
16
- <!-- Provide a longer summary of what this model is. -->
 
 
 
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
 
28
- ### Model Sources [optional]
 
29
 
30
- <!-- Provide the basic links for the model. -->
 
 
 
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
 
36
- ## Uses
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
 
 
 
39
 
40
- ### Direct Use
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
 
43
 
44
- [More Information Needed]
45
 
46
- ### Downstream Use [optional]
 
 
 
47
 
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
 
50
- [More Information Needed]
 
 
51
 
52
- ### Out-of-Scope Use
 
 
 
 
 
 
 
 
53
 
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
 
 
 
 
 
 
 
 
 
55
 
56
- [More Information Needed]
 
57
 
58
- ## Bias, Risks, and Limitations
 
59
 
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
 
62
- [More Information Needed]
63
 
64
- ### Recommendations
 
65
 
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
 
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
 
 
 
69
 
70
- ## How to Get Started with the Model
 
 
71
 
72
- Use the code below to get started with the model.
 
 
73
 
74
- [More Information Needed]
 
 
75
 
76
- ## Training Details
 
 
 
77
 
78
- ### Training Data
79
 
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
 
81
 
82
- [More Information Needed]
83
 
84
- ### Training Procedure
 
 
 
85
 
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
 
88
- #### Preprocessing [optional]
 
 
 
 
 
 
 
 
 
89
 
90
- [More Information Needed]
 
91
 
 
 
 
92
 
93
- #### Training Hyperparameters
94
 
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
 
96
 
97
- #### Speeds, Sizes, Times [optional]
98
 
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
 
 
 
 
 
100
 
101
- [More Information Needed]
102
 
103
- ## Evaluation
 
104
 
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
 
107
- ### Testing Data, Factors & Metrics
 
 
108
 
109
- #### Testing Data
 
 
 
110
 
111
- <!-- This should link to a Dataset Card if possible. -->
112
 
113
- [More Information Needed]
 
 
 
 
 
 
 
114
 
115
- #### Factors
 
116
 
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
 
 
 
118
 
119
- [More Information Needed]
 
 
120
 
121
- #### Metrics
 
122
 
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
 
125
- [More Information Needed]
 
126
 
127
- ### Results
 
 
128
 
129
- [More Information Needed]
130
 
131
- #### Summary
 
 
132
 
 
133
 
 
 
 
134
 
135
- ## Model Examination [optional]
 
136
 
137
- <!-- Relevant interpretability work for the model goes here -->
 
138
 
139
- [More Information Needed]
 
140
 
141
- ## Environmental Impact
 
142
 
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
 
 
144
 
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
 
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
 
153
- ## Technical Specifications [optional]
154
 
155
- ### Model Architecture and Objective
 
 
 
 
156
 
157
- [More Information Needed]
 
 
 
158
 
159
- ### Compute Infrastructure
 
 
 
 
 
 
 
 
 
160
 
161
- [More Information Needed]
162
 
163
- #### Hardware
164
 
165
- [More Information Needed]
 
 
 
166
 
167
- #### Software
168
 
169
- [More Information Needed]
170
 
171
- ## Citation [optional]
172
 
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
 
175
- **BibTeX:**
176
 
177
- [More Information Needed]
178
 
179
- **APA:**
180
 
181
- [More Information Needed]
182
 
183
- ## Glossary [optional]
184
 
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
 
187
- [More Information Needed]
188
 
189
- ## More Information [optional]
190
 
191
- [More Information Needed]
192
 
193
- ## Model Card Authors [optional]
194
 
195
- [More Information Needed]
196
 
197
- ## Model Card Contact
198
 
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ - zh
5
+ - de
6
+ - es
7
+ - ru
8
+ - ko
9
+ - fr
10
+ - ja
11
+ - pt
12
+ - tr
13
+ - pl
14
+ - ca
15
+ - nl
16
+ - ar
17
+ - sv
18
+ - it
19
+ - id
20
+ - hi
21
+ - fi
22
+ - vi
23
+ - he
24
+ - uk
25
+ - el
26
+ - ms
27
+ - cs
28
+ - ro
29
+ - da
30
+ - hu
31
+ - ta
32
+ - 'no'
33
+ - th
34
+ - ur
35
+ - hr
36
+ - bg
37
+ - lt
38
+ - la
39
+ - mi
40
+ - ml
41
+ - cy
42
+ - sk
43
+ - te
44
+ - fa
45
+ - lv
46
+ - bn
47
+ - sr
48
+ - az
49
+ - sl
50
+ - kn
51
+ - et
52
+ - mk
53
+ - br
54
+ - eu
55
+ - is
56
+ - hy
57
+ - ne
58
+ - mn
59
+ - bs
60
+ - kk
61
+ - sq
62
+ - sw
63
+ - gl
64
+ - mr
65
+ - pa
66
+ - si
67
+ - km
68
+ - sn
69
+ - yo
70
+ - so
71
+ - af
72
+ - oc
73
+ - ka
74
+ - be
75
+ - tg
76
+ - sd
77
+ - gu
78
+ - am
79
+ - yi
80
+ - lo
81
+ - uz
82
+ - fo
83
+ - ht
84
+ - ps
85
+ - tk
86
+ - nn
87
+ - mt
88
+ - sa
89
+ - lb
90
+ - my
91
+ - bo
92
+ - tl
93
+ - mg
94
+ - as
95
+ - tt
96
+ - haw
97
+ - ln
98
+ - ha
99
+ - ba
100
+ - jw
101
+ - su
102
+ license: mit
103
+ tags:
104
+ - audio
105
+ - automatic-speech-recognition
106
+ - unsloth
107
+ widget:
108
+ - example_title: Librispeech sample 1
109
+ src: https://cdn-media.huggingface.co/speech_samples/sample1.flac
110
+ - example_title: Librispeech sample 2
111
+ src: https://cdn-media.huggingface.co/speech_samples/sample2.flac
112
+ pipeline_tag: automatic-speech-recognition
113
+ base_model:
114
+ - openai/whisper-large-v3
115
+ - openai/whisper-large-v3-turbo
116
  library_name: transformers
 
117
  ---
118
+ <div>
119
+ <p style="margin-bottom: 0; margin-top: 0;">
120
+ <strong>See <a href="https://huggingface.co/collections/unsloth/text-to-speech-tts-models-68007ab12522e96be1e02155">our collection</a> for all our TTS model uploads.</strong>
121
+ </p>
122
+ <p style="margin-bottom: 0;">
123
+ <em>Learn to fine-tune TTS models - <a href="https://docs.unsloth.ai/basics/text-to-speech-tts-fine-tuning">Read our Guide</a>.</em>
124
+ </p>
125
+ <p style="margin-top: 0;margin-bottom: 0;">
126
+ <em><a href="https://docs.unsloth.ai/basics/unsloth-dynamic-v2.0-gguf">Unsloth Dynamic 2.0</a> achieves superior accuracy & outperforms other leading quants.</em>
127
+ </p>
128
+ <div style="display: flex; gap: 5px; align-items: center; ">
129
+ <a href="https://github.com/unslothai/unsloth/">
130
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="133">
131
+ </a>
132
+ <a href="https://discord.gg/unsloth">
133
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/Discord%20button.png" width="173">
134
+ </a>
135
+ <a href="https://docs.unsloth.ai/basics/text-to-speech-tts-fine-tuning">
136
+ <img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="143">
137
+ </a>
138
+ </div>
139
+ <h1 style="margin-top: 0rem;">✨ Run & Fine-tune TTS models with Unsloth!</h1>
140
+ </div>
141
+
142
+ - Fine-tune TTS models for free using our Google [Colab notebooks here](https://docs.unsloth.ai/get-started/unsloth-notebooks#text-to-speech-tts-notebooks)!
143
+ - Read our Blog about TTS support: [unsloth.ai/blog/tts](https://docs.unsloth.ai/basics/text-to-speech-tts-fine-tuning)
144
+
145
+ | Unsloth supports | Free Notebooks | Performance | Memory use |
146
+ |-----------------|--------------------------------------------------------------------------------------------------------------------------|-------------|----------|
147
+ | **Orpheus-TTS** | [▶️ Start on Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Orpheus_(3B)-TTS.ipynb) | 1.5x faster | 58% less |
148
+ | **Whisper Large V3** | [▶️ Start on Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Whisper.ipynb) | 1.5x faster | 50% less |
149
+ | **Qwen3 (14B)** | [▶️ Start on Colab](https://docs.unsloth.ai/get-started/unsloth-notebooks) | 2x faster | 70% less |
150
+ | **Llama 3.2 Vision (11B)** | [▶️ Start on Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_(11B)-Vision.ipynb) | 1.8x faster | 50% less |
151
+
152
+ # Whisper
153
+
154
+ Whisper is a state-of-the-art model for automatic speech recognition (ASR) and speech translation, proposed in the paper
155
+ [Robust Speech Recognition via Large-Scale Weak Supervision](https://huggingface.co/papers/2212.04356) by Alec Radford
156
+ et al. from OpenAI. Trained on >5M hours of labeled data, Whisper demonstrates a strong ability to generalise to many
157
+ datasets and domains in a zero-shot setting.
158
+
159
+ Whisper large-v3-turbo is a finetuned version of a pruned [Whisper large-v3](https://huggingface.co/openai/whisper-large-v3). In other words, it's the exact same model, except that the number of decoding layers have reduced from 32 to 4.
160
+ As a result, the model is way faster, at the expense of a minor quality degradation. You can find more details about it [in this GitHub discussion](https://github.com/openai/whisper/discussions/2363).
161
+
162
+ **Disclaimer**: Content for this model card has partly been written by the 🤗 Hugging Face team, and partly copied and
163
+ pasted from the original model card.
164
+
165
+ ## Usage
166
+
167
+ Whisper large-v3-turbo is supported in Hugging Face 🤗 Transformers. To run the model, first install the Transformers
168
+ library. For this example, we'll also install 🤗 Datasets to load toy audio dataset from the Hugging Face Hub, and
169
+ 🤗 Accelerate to reduce the model loading time:
170
+
171
+ ```bash
172
+ pip install --upgrade pip
173
+ pip install --upgrade transformers datasets[audio] accelerate
174
+ ```
175
+
176
+ The model can be used with the [`pipeline`](https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)
177
+ class to transcribe audios of arbitrary length:
178
+
179
+ ```python
180
+ import torch
181
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
182
+ from datasets import load_dataset
183
+
184
+
185
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
186
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
187
+
188
+ model_id = "openai/whisper-large-v3-turbo"
189
+
190
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
191
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
192
+ )
193
+ model.to(device)
194
+
195
+ processor = AutoProcessor.from_pretrained(model_id)
196
+
197
+ pipe = pipeline(
198
+ "automatic-speech-recognition",
199
+ model=model,
200
+ tokenizer=processor.tokenizer,
201
+ feature_extractor=processor.feature_extractor,
202
+ torch_dtype=torch_dtype,
203
+ device=device,
204
+ )
205
+
206
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
207
+ sample = dataset[0]["audio"]
208
+
209
+ result = pipe(sample)
210
+ print(result["text"])
211
+ ```
212
+
213
+ To transcribe a local audio file, simply pass the path to your audio file when you call the pipeline:
214
+
215
+ ```python
216
+ result = pipe("audio.mp3")
217
+ ```
218
+
219
+ Multiple audio files can be transcribed in parallel by specifying them as a list and setting the `batch_size` parameter:
220
+
221
+ ```python
222
+ result = pipe(["audio_1.mp3", "audio_2.mp3"], batch_size=2)
223
+ ```
224
+
225
+ Transformers is compatible with all Whisper decoding strategies, such as temperature fallback and condition on previous
226
+ tokens. The following example demonstrates how to enable these heuristics:
227
+
228
+ ```python
229
+ generate_kwargs = {
230
+ "max_new_tokens": 448,
231
+ "num_beams": 1,
232
+ "condition_on_prev_tokens": False,
233
+ "compression_ratio_threshold": 1.35, # zlib compression ratio threshold (in token space)
234
+ "temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
235
+ "logprob_threshold": -1.0,
236
+ "no_speech_threshold": 0.6,
237
+ "return_timestamps": True,
238
+ }
239
 
240
+ result = pipe(sample, generate_kwargs=generate_kwargs)
241
+ ```
242
 
243
+ Whisper predicts the language of the source audio automatically. If the source audio language is known *a-priori*, it
244
+ can be passed as an argument to the pipeline:
245
 
246
+ ```python
247
+ result = pipe(sample, generate_kwargs={"language": "english"})
248
+ ```
249
 
250
+ By default, Whisper performs the task of *speech transcription*, where the source audio language is the same as the target
251
+ text language. To perform *speech translation*, where the target text is in English, set the task to `"translate"`:
252
 
253
+ ```python
254
+ result = pipe(sample, generate_kwargs={"task": "translate"})
255
+ ```
256
 
257
+ Finally, the model can be made to predict timestamps. For sentence-level timestamps, pass the `return_timestamps` argument:
258
 
259
+ ```python
260
+ result = pipe(sample, return_timestamps=True)
261
+ print(result["chunks"])
262
+ ```
263
 
264
+ And for word-level timestamps:
265
 
266
+ ```python
267
+ result = pipe(sample, return_timestamps="word")
268
+ print(result["chunks"])
269
+ ```
 
 
 
270
 
271
+ The above arguments can be used in isolation or in combination. For example, to perform the task of speech transcription
272
+ where the source audio is in French, and we want to return sentence-level timestamps, the following can be used:
273
 
274
+ ```python
275
+ result = pipe(sample, return_timestamps=True, generate_kwargs={"language": "french", "task": "translate"})
276
+ print(result["chunks"])
277
+ ```
278
 
279
+ <details>
 
 
280
 
281
+ <summary> For more control over the generation parameters, use the model + processor API directly: </summary>
282
 
283
+ ```python
284
+ import torch
285
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
286
+ from datasets import Audio, load_dataset
287
 
 
288
 
289
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
290
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
291
 
292
+ model_id = "openai/whisper-large-v3-turbo"
293
 
294
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
295
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
296
+ )
297
+ model.to(device)
298
 
299
+ processor = AutoProcessor.from_pretrained(model_id)
300
 
301
+ dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
302
+ dataset = dataset.cast_column("audio", Audio(processor.feature_extractor.sampling_rate))
303
+ sample = dataset[0]["audio"]
304
 
305
+ inputs = processor(
306
+ sample["array"],
307
+ sampling_rate=sample["sampling_rate"],
308
+ return_tensors="pt",
309
+ truncation=False,
310
+ padding="longest",
311
+ return_attention_mask=True,
312
+ )
313
+ inputs = inputs.to(device, dtype=torch_dtype)
314
 
315
+ gen_kwargs = {
316
+ "max_new_tokens": 448,
317
+ "num_beams": 1,
318
+ "condition_on_prev_tokens": False,
319
+ "compression_ratio_threshold": 1.35, # zlib compression ratio threshold (in token space)
320
+ "temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
321
+ "logprob_threshold": -1.0,
322
+ "no_speech_threshold": 0.6,
323
+ "return_timestamps": True,
324
+ }
325
 
326
+ pred_ids = model.generate(**inputs, **gen_kwargs)
327
+ pred_text = processor.batch_decode(pred_ids, skip_special_tokens=True, decode_with_timestamps=False)
328
 
329
+ print(pred_text)
330
+ ```
331
 
332
+ </details>
333
 
334
+ ## Additional Speed & Memory Improvements
335
 
336
+ You can apply additional speed and memory improvements to Whisper to further reduce the inference speed and VRAM
337
+ requirements.
338
 
339
+ ### Chunked Long-Form
340
 
341
+ Whisper has a receptive field of 30-seconds. To transcribe audios longer than this, one of two long-form algorithms are
342
+ required:
343
+ 1. **Sequential:** uses a "sliding window" for buffered inference, transcribing 30-second slices one after the other
344
+ 2. **Chunked:** splits long audio files into shorter ones (with a small overlap between segments), transcribes each segment independently, and stitches the resulting transcriptions at the boundaries
345
 
346
+ The sequential long-form algorithm should be used in either of the following scenarios:
347
+ 1. Transcription accuracy is the most important factor, and speed is less of a consideration
348
+ 2. You are transcribing **batches** of long audio files, in which case the latency of sequential is comparable to chunked, while being up to 0.5% WER more accurate
349
 
350
+ Conversely, the chunked algorithm should be used when:
351
+ 1. Transcription speed is the most important factor
352
+ 2. You are transcribing a **single** long audio file
353
 
354
+ By default, Transformers uses the sequential algorithm. To enable the chunked algorithm, pass the `chunk_length_s`
355
+ parameter to the `pipeline`. For large-v3, a chunk length of 30-seconds is optimal. To activate batching over long
356
+ audio files, pass the argument `batch_size`:
357
 
358
+ ```python
359
+ import torch
360
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
361
+ from datasets import load_dataset
362
 
 
363
 
364
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
365
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
366
 
367
+ model_id = "openai/whisper-large-v3-turbo"
368
 
369
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
370
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
371
+ )
372
+ model.to(device)
373
 
374
+ processor = AutoProcessor.from_pretrained(model_id)
375
 
376
+ pipe = pipeline(
377
+ "automatic-speech-recognition",
378
+ model=model,
379
+ tokenizer=processor.tokenizer,
380
+ feature_extractor=processor.feature_extractor,
381
+ chunk_length_s=30,
382
+ batch_size=16, # batch size for inference - set based on your device
383
+ torch_dtype=torch_dtype,
384
+ device=device,
385
+ )
386
 
387
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
388
+ sample = dataset[0]["audio"]
389
 
390
+ result = pipe(sample)
391
+ print(result["text"])
392
+ ```
393
 
394
+ #### Torch compile
395
 
396
+ The Whisper forward pass is compatible with [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html)
397
+ for 4.5x speed-ups.
398
 
399
+ **Note:** `torch.compile` is currently not compatible with the Chunked long-form algorithm or Flash Attention 2 ⚠️
400
 
401
+ ```python
402
+ import torch
403
+ from torch.nn.attention import SDPBackend, sdpa_kernel
404
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
405
+ from datasets import load_dataset
406
+ from tqdm import tqdm
407
 
408
+ torch.set_float32_matmul_precision("high")
409
 
410
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
411
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
412
 
413
+ model_id = "openai/whisper-large-v3-turbo"
414
 
415
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
416
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
417
+ ).to(device)
418
 
419
+ # Enable static cache and compile the forward pass
420
+ model.generation_config.cache_implementation = "static"
421
+ model.generation_config.max_new_tokens = 256
422
+ model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
423
 
424
+ processor = AutoProcessor.from_pretrained(model_id)
425
 
426
+ pipe = pipeline(
427
+ "automatic-speech-recognition",
428
+ model=model,
429
+ tokenizer=processor.tokenizer,
430
+ feature_extractor=processor.feature_extractor,
431
+ torch_dtype=torch_dtype,
432
+ device=device,
433
+ )
434
 
435
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
436
+ sample = dataset[0]["audio"]
437
 
438
+ # 2 warmup steps
439
+ for _ in tqdm(range(2), desc="Warm-up step"):
440
+ with sdpa_kernel(SDPBackend.MATH):
441
+ result = pipe(sample.copy(), generate_kwargs={"min_new_tokens": 256, "max_new_tokens": 256})
442
 
443
+ # fast run
444
+ with sdpa_kernel(SDPBackend.MATH):
445
+ result = pipe(sample.copy())
446
 
447
+ print(result["text"])
448
+ ```
449
 
450
+ #### Flash Attention 2
451
 
452
+ We recommend using [Flash-Attention 2](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#flashattention-2) if your GPU supports it and you are not using [torch.compile](#torch-compile).
453
+ To do so, first install [Flash Attention](https://github.com/Dao-AILab/flash-attention):
454
 
455
+ ```
456
+ pip install flash-attn --no-build-isolation
457
+ ```
458
 
459
+ Then pass `attn_implementation="flash_attention_2"` to `from_pretrained`:
460
 
461
+ ```python
462
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="flash_attention_2")
463
+ ```
464
 
465
+ #### Torch Scale-Product-Attention (SDPA)
466
 
467
+ If your GPU does not support Flash Attention, we recommend making use of PyTorch [scaled dot-product attention (SDPA)](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html).
468
+ This attention implementation is activated **by default** for PyTorch versions 2.1.1 or greater. To check
469
+ whether you have a compatible PyTorch version, run the following Python code snippet:
470
 
471
+ ```python
472
+ from transformers.utils import is_torch_sdpa_available
473
 
474
+ print(is_torch_sdpa_available())
475
+ ```
476
 
477
+ If the above returns `True`, you have a valid version of PyTorch installed and SDPA is activated by default. If it
478
+ returns `False`, you need to upgrade your PyTorch version according to the [official instructions](https://pytorch.org/get-started/locally/)
479
 
480
+ Once a valid PyTorch version is installed, SDPA is activated by default. It can also be set explicitly by specifying
481
+ `attn_implementation="sdpa"` as follows:
482
 
483
+ ```python
484
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="sdpa")
485
+ ```
486
 
487
+ For more information about how to use the SDPA refer to the [Transformers SDPA documentation](https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention).
488
 
 
 
 
 
 
489
 
490
+ ## Model details
491
 
492
+ Whisper is a Transformer based encoder-decoder model, also referred to as a _sequence-to-sequence_ model. There are two
493
+ flavours of Whisper model: English-only and multilingual. The English-only models were trained on the task of English
494
+ speech recognition. The multilingual models were trained simultaneously on multilingual speech recognition and speech
495
+ translation. For speech recognition, the model predicts transcriptions in the *same* language as the audio. For speech
496
+ translation, the model predicts transcriptions to a *different* language to the audio.
497
 
498
+ Whisper checkpoints come in five configurations of varying model sizes. The smallest four are available as English-only
499
+ and multilingual. The largest checkpoints are multilingual only. All ten of the pre-trained checkpoints
500
+ are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The
501
+ checkpoints are summarised in the following table with links to the models on the Hub:
502
 
503
+ | Size | Parameters | English-only | Multilingual |
504
+ |----------|------------|------------------------------------------------------|-----------------------------------------------------|
505
+ | tiny | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny) |
506
+ | base | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |
507
+ | small | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |
508
+ | medium | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |
509
+ | large | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |
510
+ | large-v2 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v2) |
511
+ | large-v3 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v3) |
512
+ | large-v3-turbo | 809 M | x | [✓](https://huggingface.co/openai/whisper-large-v3-turbo) |
513
 
 
514
 
515
+ ## Fine-Tuning
516
 
517
+ The pre-trained Whisper model demonstrates a strong ability to generalise to different datasets and domains. However,
518
+ its predictive capabilities can be improved further for certain languages and tasks through *fine-tuning*. The blog
519
+ post [Fine-Tune Whisper with 🤗 Transformers](https://huggingface.co/blog/fine-tune-whisper) provides a step-by-step
520
+ guide to fine-tuning the Whisper model with as little as 5 hours of labelled data.
521
 
522
+ ### Evaluated Use
523
 
524
+ The primary intended users of these models are AI researchers studying robustness, generalization, capabilities, biases, and constraints of the current model. However, Whisper is also potentially quite useful as an ASR solution for developers, especially for English speech recognition. We recognize that once models are released, it is impossible to restrict access to only “intended” uses or to draw reasonable guidelines around what is or is not research.
525
 
526
+ The models are primarily trained and evaluated on ASR and speech translation to English tasks. They show strong ASR results in ~10 languages. They may exhibit additional capabilities, particularly if fine-tuned on certain tasks like voice activity detection, speaker classification, or speaker diarization but have not been robustly evaluated in these areas. We strongly recommend that users perform robust evaluations of the models in a particular context and domain before deploying them.
527
 
528
+ In particular, we caution against using Whisper models to transcribe recordings of individuals taken without their consent or purporting to use these models for any kind of subjective classification. We recommend against use in high-risk domains like decision-making contexts, where flaws in accuracy can lead to pronounced flaws in outcomes. The models are intended to transcribe and translate speech, use of the model for classification is not only not evaluated but also not appropriate, particularly to infer human attributes.
529
 
 
530
 
531
+ ## Training Data
532
 
533
+ No information provided.
534
 
535
+ ## Performance and Limitations
536
 
537
+ Our studies show that, over many existing ASR systems, the models exhibit improved robustness to accents, background noise, technical language, as well as zero shot translation from multiple languages into English; and that accuracy on speech recognition and translation is near the state-of-the-art level.
538
 
539
+ However, because the models are trained in a weakly supervised manner using large-scale noisy data, the predictions may include texts that are not actually spoken in the audio input (i.e. hallucination). We hypothesize that this happens because, given their general knowledge of language, the models combine trying to predict the next word in audio with trying to transcribe the audio itself.
540
 
541
+ Our models perform unevenly across languages, and we observe lower accuracy on low-resource and/or low-discoverability languages or languages where we have less training data. The models also exhibit disparate performance on different accents and dialects of particular languages, which may include higher word error rate across speakers of different genders, races, ages, or other demographic criteria. Our full evaluation results are presented in [the paper accompanying this release](https://cdn.openai.com/papers/whisper.pdf).
542
 
543
+ In addition, the sequence-to-sequence architecture of the model makes it prone to generating repetitive texts, which can be mitigated to some degree by beam search and temperature scheduling but not perfectly. Further analysis on these limitations are provided in [the paper](https://cdn.openai.com/papers/whisper.pdf). It is likely that this behavior and hallucinations may be worse on lower-resource and/or lower-discoverability languages.
544
 
 
545
 
546
+ ## Broader Implications
547
 
548
+ We anticipate that Whisper models’ transcription capabilities may be used for improving accessibility tools. While Whisper models cannot be used for real-time transcription out of the box – their speed and size suggest that others may be able to build applications on top of them that allow for near-real-time speech recognition and translation. The real value of beneficial applications built on top of Whisper models suggests that the disparate performance of these models may have real economic implications.
549
 
550
+ There are also potential dual use concerns that come with releasing Whisper. While we hope the technology will be used primarily for beneficial purposes, making ASR technology more accessible could enable more actors to build capable surveillance technologies or scale up existing surveillance efforts, as the speed and accuracy allow for affordable automatic transcription and translation of large volumes of audio communication. Moreover, these models may have some capabilities to recognize specific individuals out of the box, which in turn presents safety concerns related both to dual use and disparate performance. In practice, we expect that the cost of transcription is not the limiting factor of scaling up surveillance projects.
551
 
552
+
553
+ ### BibTeX entry and citation info
554
+ ```bibtex
555
+ @misc{radford2022whisper,
556
+ doi = {10.48550/ARXIV.2212.04356},
557
+ url = {https://arxiv.org/abs/2212.04356},
558
+ author = {Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},
559
+ title = {Robust Speech Recognition via Large-Scale Weak Supervision},
560
+ publisher = {arXiv},
561
+ year = {2022},
562
+ copyright = {arXiv.org perpetual, non-exclusive license}
563
+ }
564
+ ```