shimmyshimmer commited on
Commit
353628e
·
verified ·
1 Parent(s): 9be1d11

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +476 -103
README.md CHANGED
@@ -1,199 +1,572 @@
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
+ tags:
103
+ - audio
104
+ - automatic-speech-recognition
105
+ - hf-asr-leaderboard
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
+ license: apache-2.0
114
  ---
115
+ <div>
116
+ <p style="margin-bottom: 0; margin-top: 0;">
117
+ <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>
118
+ </p>
119
+ <p style="margin-bottom: 0;">
120
+ <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>
121
+ </p>
122
+ <p style="margin-top: 0;margin-bottom: 0;">
123
+ <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>
124
+ </p>
125
+ <div style="display: flex; gap: 5px; align-items: center; ">
126
+ <a href="https://github.com/unslothai/unsloth/">
127
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="133">
128
+ </a>
129
+ <a href="https://discord.gg/unsloth">
130
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/Discord%20button.png" width="173">
131
+ </a>
132
+ <a href="https://docs.unsloth.ai/basics/text-to-speech-tts-fine-tuning">
133
+ <img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="143">
134
+ </a>
135
+ </div>
136
+ <h1 style="margin-top: 0rem;">✨ Run & Fine-tune TTS models with Unsloth!</h1>
137
+ </div>
138
+
139
+ - 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)!
140
+ - Read our Blog about TTS support: [unsloth.ai/blog/tts](https://docs.unsloth.ai/basics/text-to-speech-tts-fine-tuning)
141
+
142
+ | Unsloth supports | Free Notebooks | Performance | Memory use |
143
+ |-----------------|--------------------------------------------------------------------------------------------------------------------------|-------------|----------|
144
+ | **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 |
145
+ | **Whisper Large V3** | [▶️ Start on Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Whisper.ipynb) | 1.5x faster | 50% less |
146
+ | **Qwen3 (14B)** | [▶️ Start on Colab](https://docs.unsloth.ai/get-started/unsloth-notebooks) | 2x faster | 70% less |
147
+ | **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 |
148
+
149
+ # Whisper
150
+
151
+ Whisper is a state-of-the-art model for automatic speech recognition (ASR) and speech translation, proposed in the paper
152
+ [Robust Speech Recognition via Large-Scale Weak Supervision](https://huggingface.co/papers/2212.04356) by Alec Radford
153
+ et al. from OpenAI. Trained on >5M hours of labeled data, Whisper demonstrates a strong ability to generalise to many
154
+ datasets and domains in a zero-shot setting.
155
+
156
+ Whisper large-v3 has the same architecture as the previous [large](https://huggingface.co/openai/whisper-large) and [large-v2](https://huggingface.co/openai/whisper-large-v2)
157
+ models, except for the following minor differences:
158
+
159
+ 1. The spectrogram input uses 128 Mel frequency bins instead of 80
160
+ 2. A new language token for Cantonese
161
+
162
+ The Whisper large-v3 model was trained on 1 million hours of weakly labeled audio and 4 million hours of pseudo-labeled
163
+ audio collected using Whisper [large-v2](https://huggingface.co/openai/whisper-large-v2) . The model was trained for 2.0 epochs over this mixture dataset.
164
+
165
+ The large-v3 model shows improved performance over a wide variety of languages, showing 10% to 20% reduction of errors
166
+ compared to Whisper [large-v2](https://huggingface.co/openai/whisper-large-v2) . For more details on the different checkpoints available, refer to the section [Model details](#model-details).
167
+
168
+ **Disclaimer**: Content for this model card has partly been written by the 🤗 Hugging Face team, and partly copied and
169
+ pasted from the original model card.
170
+
171
+ ## Usage
172
+
173
+ Whisper large-v3 is supported in Hugging Face 🤗 Transformers. To run the model, first install the Transformers
174
+ library. For this example, we'll also install 🤗 Datasets to load toy audio dataset from the Hugging Face Hub, and
175
+ 🤗 Accelerate to reduce the model loading time:
176
+
177
+ ```bash
178
+ pip install --upgrade pip
179
+ pip install --upgrade transformers datasets[audio] accelerate
180
+ ```
181
+
182
+ The model can be used with the [`pipeline`](https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)
183
+ class to transcribe audios of arbitrary length:
184
+
185
+ ```python
186
+ import torch
187
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
188
+ from datasets import load_dataset
189
+
190
+
191
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
192
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
193
+
194
+ model_id = "openai/whisper-large-v3"
195
+
196
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
197
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
198
+ )
199
+ model.to(device)
200
 
201
+ processor = AutoProcessor.from_pretrained(model_id)
202
+
203
+ pipe = pipeline(
204
+ "automatic-speech-recognition",
205
+ model=model,
206
+ tokenizer=processor.tokenizer,
207
+ feature_extractor=processor.feature_extractor,
208
+ torch_dtype=torch_dtype,
209
+ device=device,
210
+ )
211
 
212
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
213
+ sample = dataset[0]["audio"]
214
+
215
+ result = pipe(sample)
216
+ print(result["text"])
217
+ ```
218
+
219
+ To transcribe a local audio file, simply pass the path to your audio file when you call the pipeline:
220
 
221
+ ```python
222
+ result = pipe("audio.mp3")
223
+ ```
224
 
225
+ Multiple audio files can be transcribed in parallel by specifying them as a list and setting the `batch_size` parameter:
226
 
227
+ ```python
228
+ result = pipe(["audio_1.mp3", "audio_2.mp3"], batch_size=2)
229
+ ```
230
 
231
+ Transformers is compatible with all Whisper decoding strategies, such as temperature fallback and condition on previous
232
+ tokens. The following example demonstrates how to enable these heuristics:
233
 
234
+ ```python
235
+ generate_kwargs = {
236
+ "max_new_tokens": 448,
237
+ "num_beams": 1,
238
+ "condition_on_prev_tokens": False,
239
+ "compression_ratio_threshold": 1.35, # zlib compression ratio threshold (in token space)
240
+ "temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
241
+ "logprob_threshold": -1.0,
242
+ "no_speech_threshold": 0.6,
243
+ "return_timestamps": True,
244
+ }
245
 
246
+ result = pipe(sample, generate_kwargs=generate_kwargs)
247
+ ```
248
 
249
+ Whisper predicts the language of the source audio automatically. If the source audio language is known *a-priori*, it
250
+ can be passed as an argument to the pipeline:
 
 
 
 
 
251
 
252
+ ```python
253
+ result = pipe(sample, generate_kwargs={"language": "english"})
254
+ ```
255
 
256
+ By default, Whisper performs the task of *speech transcription*, where the source audio language is the same as the target
257
+ text language. To perform *speech translation*, where the target text is in English, set the task to `"translate"`:
258
 
259
+ ```python
260
+ result = pipe(sample, generate_kwargs={"task": "translate"})
261
+ ```
262
 
263
+ Finally, the model can be made to predict timestamps. For sentence-level timestamps, pass the `return_timestamps` argument:
264
 
265
+ ```python
266
+ result = pipe(sample, return_timestamps=True)
267
+ print(result["chunks"])
268
+ ```
269
 
270
+ And for word-level timestamps:
271
 
272
+ ```python
273
+ result = pipe(sample, return_timestamps="word")
274
+ print(result["chunks"])
275
+ ```
276
 
277
+ The above arguments can be used in isolation or in combination. For example, to perform the task of speech transcription
278
+ where the source audio is in French, and we want to return sentence-level timestamps, the following can be used:
279
 
280
+ ```python
281
+ result = pipe(sample, return_timestamps=True, generate_kwargs={"language": "french", "task": "translate"})
282
+ print(result["chunks"])
283
+ ```
284
 
285
+ <details>
286
 
287
+ <summary> For more control over the generation parameters, use the model + processor API directly: </summary>
288
 
289
+ ```python
290
+ import torch
291
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
292
+ from datasets import Audio, load_dataset
293
 
 
294
 
295
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
296
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
297
 
298
+ model_id = "openai/whisper-large-v3"
299
 
300
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
301
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
302
+ )
303
+ model.to(device)
304
 
305
+ processor = AutoProcessor.from_pretrained(model_id)
306
 
307
+ dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
308
+ dataset = dataset.cast_column("audio", Audio(processor.feature_extractor.sampling_rate))
309
+ sample = dataset[0]["audio"]
310
 
311
+ inputs = processor(
312
+ sample["array"],
313
+ sampling_rate=sample["sampling_rate"],
314
+ return_tensors="pt",
315
+ truncation=False,
316
+ padding="longest",
317
+ return_attention_mask=True,
318
+ )
319
+ inputs = inputs.to(device, dtype=torch_dtype)
320
 
321
+ gen_kwargs = {
322
+ "max_new_tokens": 448,
323
+ "num_beams": 1,
324
+ "condition_on_prev_tokens": False,
325
+ "compression_ratio_threshold": 1.35, # zlib compression ratio threshold (in token space)
326
+ "temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
327
+ "logprob_threshold": -1.0,
328
+ "no_speech_threshold": 0.6,
329
+ "return_timestamps": True,
330
+ }
331
 
332
+ pred_ids = model.generate(**inputs, **gen_kwargs)
333
+ pred_text = processor.batch_decode(pred_ids, skip_special_tokens=True, decode_with_timestamps=False)
334
 
335
+ print(pred_text)
336
+ ```
337
 
338
+ </details>
339
 
340
+ ## Additional Speed & Memory Improvements
341
 
342
+ You can apply additional speed and memory improvements to Whisper to further reduce the inference speed and VRAM
343
+ requirements.
344
 
345
+ ### Chunked Long-Form
346
 
347
+ Whisper has a receptive field of 30-seconds. To transcribe audios longer than this, one of two long-form algorithms are
348
+ required:
349
+ 1. **Sequential:** uses a "sliding window" for buffered inference, transcribing 30-second slices one after the other
350
+ 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
351
 
352
+ The sequential long-form algorithm should be used in either of the following scenarios:
353
+ 1. Transcription accuracy is the most important factor, and speed is less of a consideration
354
+ 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
355
 
356
+ Conversely, the chunked algorithm should be used when:
357
+ 1. Transcription speed is the most important factor
358
+ 2. You are transcribing a **single** long audio file
359
 
360
+ By default, Transformers uses the sequential algorithm. To enable the chunked algorithm, pass the `chunk_length_s`
361
+ parameter to the `pipeline`. For large-v3, a chunk length of 30-seconds is optimal. To activate batching over long
362
+ audio files, pass the argument `batch_size`:
363
 
364
+ ```python
365
+ import torch
366
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
367
+ from datasets import load_dataset
368
 
369
 
370
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
371
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
372
 
373
+ model_id = "openai/whisper-large-v3"
374
 
375
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
376
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
377
+ )
378
+ model.to(device)
379
 
380
+ processor = AutoProcessor.from_pretrained(model_id)
381
 
382
+ pipe = pipeline(
383
+ "automatic-speech-recognition",
384
+ model=model,
385
+ tokenizer=processor.tokenizer,
386
+ feature_extractor=processor.feature_extractor,
387
+ chunk_length_s=30,
388
+ batch_size=16, # batch size for inference - set based on your device
389
+ torch_dtype=torch_dtype,
390
+ device=device,
391
+ )
392
 
393
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
394
+ sample = dataset[0]["audio"]
395
 
396
+ result = pipe(sample)
397
+ print(result["text"])
398
+ ```
399
 
400
+ #### Torch compile
401
 
402
+ The Whisper forward pass is compatible with [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html)
403
+ for 4.5x speed-ups.
404
 
405
+ **Note:** `torch.compile` is currently not compatible with the Chunked long-form algorithm or Flash Attention 2 ⚠️
406
 
407
+ ```python
408
+ import torch
409
+ from torch.nn.attention import SDPBackend, sdpa_kernel
410
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
411
+ from datasets import load_dataset
412
+ from tqdm import tqdm
413
 
414
+ torch.set_float32_matmul_precision("high")
415
 
416
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
417
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
418
 
419
+ model_id = "openai/whisper-large-v3"
420
 
421
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
422
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True
423
+ ).to(device)
424
 
425
+ # Enable static cache and compile the forward pass
426
+ model.generation_config.cache_implementation = "static"
427
+ model.generation_config.max_new_tokens = 256
428
+ model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
429
 
430
+ processor = AutoProcessor.from_pretrained(model_id)
431
 
432
+ pipe = pipeline(
433
+ "automatic-speech-recognition",
434
+ model=model,
435
+ tokenizer=processor.tokenizer,
436
+ feature_extractor=processor.feature_extractor,
437
+ torch_dtype=torch_dtype,
438
+ device=device,
439
+ )
440
 
441
+ dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
442
+ sample = dataset[0]["audio"]
443
 
444
+ # 2 warmup steps
445
+ for _ in tqdm(range(2), desc="Warm-up step"):
446
+ with sdpa_kernel(SDPBackend.MATH):
447
+ result = pipe(sample.copy(), generate_kwargs={"min_new_tokens": 256, "max_new_tokens": 256})
448
 
449
+ # fast run
450
+ with sdpa_kernel(SDPBackend.MATH):
451
+ result = pipe(sample.copy())
452
 
453
+ print(result["text"])
454
+ ```
455
 
456
+ #### Flash Attention 2
457
 
458
+ 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).
459
+ To do so, first install [Flash Attention](https://github.com/Dao-AILab/flash-attention):
460
 
461
+ ```
462
+ pip install flash-attn --no-build-isolation
463
+ ```
464
 
465
+ Then pass `attn_implementation="flash_attention_2"` to `from_pretrained`:
466
 
467
+ ```python
468
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="flash_attention_2")
469
+ ```
470
 
471
+ #### Torch Scale-Product-Attention (SDPA)
472
 
473
+ 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).
474
+ This attention implementation is activated **by default** for PyTorch versions 2.1.1 or greater. To check
475
+ whether you have a compatible PyTorch version, run the following Python code snippet:
 
 
476
 
477
+ ```python
478
+ from transformers.utils import is_torch_sdpa_available
479
 
480
+ print(is_torch_sdpa_available())
481
+ ```
482
 
483
+ If the above returns `True`, you have a valid version of PyTorch installed and SDPA is activated by default. If it
484
+ returns `False`, you need to upgrade your PyTorch version according to the [official instructions](https://pytorch.org/get-started/locally/)
485
 
486
+ Once a valid PyTorch version is installed, SDPA is activated by default. It can also be set explicitly by specifying
487
+ `attn_implementation="sdpa"` as follows:
488
 
489
+ ```python
490
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, attn_implementation="sdpa")
491
+ ```
492
 
493
+ 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).
494
 
 
495
 
496
+ ## Model details
497
 
498
+ Whisper is a Transformer based encoder-decoder model, also referred to as a _sequence-to-sequence_ model. There are two
499
+ flavours of Whisper model: English-only and multilingual. The English-only models were trained on the task of English
500
+ speech recognition. The multilingual models were trained simultaneously on multilingual speech recognition and speech
501
+ translation. For speech recognition, the model predicts transcriptions in the *same* language as the audio. For speech
502
+ translation, the model predicts transcriptions to a *different* language to the audio.
503
 
504
+ Whisper checkpoints come in five configurations of varying model sizes. The smallest four are available as English-only
505
+ and multilingual. The largest checkpoints are multilingual only. All ten of the pre-trained checkpoints
506
+ are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The
507
+ checkpoints are summarised in the following table with links to the models on the Hub:
508
 
509
+ | Size | Parameters | English-only | Multilingual |
510
+ |----------|------------|------------------------------------------------------|-----------------------------------------------------|
511
+ | tiny | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny) |
512
+ | base | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |
513
+ | small | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |
514
+ | medium | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |
515
+ | large | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |
516
+ | large-v2 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v2) |
517
+ | large-v3 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large-v3) |
518
 
 
519
 
520
+ ## Fine-Tuning
521
 
522
+ The pre-trained Whisper model demonstrates a strong ability to generalise to different datasets and domains. However,
523
+ its predictive capabilities can be improved further for certain languages and tasks through *fine-tuning*. The blog
524
+ post [Fine-Tune Whisper with 🤗 Transformers](https://huggingface.co/blog/fine-tune-whisper) provides a step-by-step
525
+ guide to fine-tuning the Whisper model with as little as 5 hours of labelled data.
526
 
527
+ ### Evaluated Use
528
 
529
+ 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.
530
 
531
+ 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.
532
 
533
+ 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.
534
 
 
535
 
536
+ ## Training Data
537
 
538
+ The large-v3 checkpoint is trained on 1 million hours of weakly labeled audio and 4 million hours of pseudo-labeled audio collected using Whisper large-v2.
539
 
540
+ As discussed in [the accompanying paper](https://cdn.openai.com/papers/whisper.pdf), we see that performance on transcription in a given language is directly correlated with the amount of training data we employ in that language.
541
 
 
542
 
543
+ ## Performance and Limitations
544
+
545
+ 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.
546
+
547
+ 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.
548
+
549
+ 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).
550
+
551
+ 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.
552
+
553
+
554
+ ## Broader Implications
555
+
556
+ 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.
557
+
558
+ 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.
559
+
560
+
561
+ ### BibTeX entry and citation info
562
+ ```bibtex
563
+ @misc{radford2022whisper,
564
+ doi = {10.48550/ARXIV.2212.04356},
565
+ url = {https://arxiv.org/abs/2212.04356},
566
+ author = {Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},
567
+ title = {Robust Speech Recognition via Large-Scale Weak Supervision},
568
+ publisher = {arXiv},
569
+ year = {2022},
570
+ copyright = {arXiv.org perpetual, non-exclusive license}
571
+ }
572
+ ```