Update README.md

#11
by sanchit-gandhi HF staff - opened
Files changed (1) hide show
  1. README.md +108 -73
README.md CHANGED
@@ -45,120 +45,153 @@ pipeline_tag: automatic-speech-recognition
45
  license: apache-2.0
46
  ---
47
 
48
- # Whisper
49
 
50
- [OpenAI's Whisper](https://openai.com/blog/whisper/)
 
 
51
 
52
- The Whisper model was proposed in [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf) by Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever.
 
53
 
54
- **Disclaimer**: Content from **this** model card has been written by the Hugging Face team, and parts of it were copy pasted from the original model card.
 
55
 
 
56
 
57
- ## Intro
 
58
 
59
- The first paragraphs of the abstract read as follows :
 
 
 
60
 
61
- > We study the capabilities of speech processing systems trained simply to predict large amounts of transcripts of audio on the internet. When scaled to 680,000 hours of multilingual and multitask supervision, the resulting models generalize well to standard benchmarks and are often competitive with prior fully supervised results but in a zeroshot transfer setting without the need for any finetuning.
62
- > When compared to humans, the models approach their accuracy and robustness. We are releasing models and inference code to serve as a foundation for further work on robust speech processing.
63
-
64
- The original code repository can be found [here](https://github.com/openai/whisper).
65
-
66
- ## Model details
67
-
68
- The Whisper models are trained for speech recognition and translation tasks, capable of transcribing speech audio into the text in the language it is spoken (ASR) as well as translated into English (speech translation). Researchers at OpenAI developed the models to study the robustness of speech processing systems trained under large-scale weak supervision. There are 9 models of different sizes and capabilities, summarised in the following table.
69
-
70
- | Size | Parameters | English-only model | Multilingual model |
71
- |:------:|:----------:|:------------------:|:------------------:|
72
- | tiny | 39 M | βœ“ | βœ“ |
73
- | base | 74 M | βœ“ | βœ“ |
74
- | small | 244 M | βœ“ | βœ“ |
75
- | medium | 769 M | βœ“ | βœ“ |
76
- | large | 1550 M | | βœ“ |
77
-
78
-
79
-
80
- ## Model description
81
-
82
- Whisper is an auto-regressive automatic speech recognition encoder-decoder model that was trained on 680 000 hours of 16kHz sampled multilingual audio. It was fully trained in a supervised manner, with multiple tasks :
83
-
84
- - English transcription
85
- - Any-to-English speech translation
86
- - Non-English transcription
87
- - No speech prediction
88
-
89
- To each task corresponds a sequence of tokens that are given to the decoder as *context tokens*. The beginning of a transcription always starts with `<|startoftranscript|>` which is why the `decoder_start_token` is always set to `tokenizer.encode("<|startoftranscript|>")`. The following token should be the language token, which is automatically detected in the original code. Finally, the task is define using either `<|transcribe|>` or `<|translate|>`. In addition, a `<|notimestamps|>` token is added if the task does not include timestamp prediction.
90
 
 
 
 
 
 
 
 
 
91
 
92
  # Usage
93
 
94
- To transcribe or translate audio files, the model has to be used along a `WhisperProcessor`. The `WhisperProcessor.get_decoder_prompt_ids` function is used to get a list of `( idx, token )` tuples, which can either be set in the config, or directly passed to the generate function, as `forced_decoder_ids`.
95
-
96
 
97
- ## Transcription
98
- In the following example, the english only model is used. We set the `decoder_input_ids` accordingly.
99
 
 
 
 
100
 
101
- ### English to english
102
- The "<|en|>" token is used to specify that the speech is in english and should be transcribed to english
103
 
104
  ```python
105
  >>> from transformers import WhisperProcessor, WhisperForConditionalGeneration
106
  >>> from datasets import load_dataset
107
- >>> import torch
108
 
109
  >>> # load model and processor
110
  >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
111
  >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
112
 
113
- >>> # load dummy dataset and read soundfiles
114
  >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
115
- >>> input_features = processor(ds[0]["audio"]["array"], return_tensors="pt").input_features
116
-
117
- >>> # Generate logits
118
- >>> logits = model(input_features, decoder_input_ids = torch.tensor([[50258]])).logits
119
- >>> # take argmax and decode
120
- >>> predicted_ids = torch.argmax(logits, dim=-1)
121
- >>> transcription = processor.batch_decode(predicted_ids)
122
- ['<|startoftranscript|>']
123
- ```
124
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  ## Evaluation
127
 
128
- This code snippet shows how to evaluate **openai/whisper-tiny.en** on LibriSpeech's "clean" and "other" test data.
129
 
130
  ```python
131
  >>> from datasets import load_dataset
132
  >>> from transformers import WhisperForConditionalGeneration, WhisperProcessor
133
- >>> import soundfile as sf
134
  >>> import torch
135
  >>> from evaluate import load
136
 
 
137
 
138
- >>> librispeech_eval = load_dataset("librispeech_asr", "clean", split="test")
139
-
140
- >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en").to("cuda")
141
  >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
 
142
 
143
  >>> def map_to_pred(batch):
144
- >>> input_features = processor(batch["audio"]["array"], return_tensors="pt").input_features
145
-
 
 
146
  >>> with torch.no_grad():
147
- >>> logits = model(input_features.to("cuda")).logits
148
-
149
- >>> predicted_ids = torch.argmax(logits, dim=-1)
150
- >>> transcription = processor.batch_decode(predicted_ids, normalize = True)
151
- >>> batch['text'] = processor.tokenizer._normalize(batch['text'])
152
- >>> batch["transcription"] = transcription
153
  >>> return batch
154
 
155
- >>> result = librispeech_eval.map(map_to_pred, batched=True, batch_size=1, remove_columns=["speech"])
156
 
157
  >>> wer = load("wer")
158
- >>> print(wer.compute(predictions=ds["text"], references=ds["transcription"]))
159
- 0.14857607503498355
160
  ```
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
  ### Evaluated Use
164
 
@@ -195,12 +228,14 @@ There are also potential dual use concerns that come with releasing Whisper. Whi
195
 
196
 
197
  ### BibTeX entry and citation info
198
- *Since no official citation was provided, we use the following in the mean time*
199
  ```bibtex
200
  @misc{radford2022whisper,
201
- title={Robust Speech Recognition via Large-Scale Weak Supervision.},
202
- author={Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever},
203
- year={2022},
204
- url={https://cdn.openai.com/papers/whisper.pdf},
 
 
 
205
  }
206
  ```
 
45
  license: apache-2.0
46
  ---
47
 
48
+ # Whisper
49
 
50
+ Whisper is a pre-trained model for automatic speech recognition (ASR) and speech translation. Trained on 680k hours
51
+ of labelled data, Whisper models demonstrate a strong ability to generalise to many datasets and domains **without** the need
52
+ for fine-tuning.
53
 
54
+ Whisper was proposed in the paper [Robust Speech Recognition via Large-Scale Weak Supervision](https://arxiv.org/abs/2212.04356)
55
+ by Alec Radford et al. from OpenAI. The original code repository can be found [here](https://github.com/openai/whisper).
56
 
57
+ **Disclaimer**: Content for this model card has partly been written by the Hugging Face team, and parts of it were
58
+ copied and pasted from the original model card.
59
 
60
+ ## Model details
61
 
62
+ Whisper is a Transformer based encoder-decoder model, also referred to as a _sequence-to-sequence_ model.
63
+ It was trained on 680k hours of labelled speech data annotated using large-scale weak supervision.
64
 
65
+ The models were trained on either English-only data or multilingual data. The English-only models were trained
66
+ on the task of speech recognition. The multilingual models were trained on both speech recognition and speech
67
+ translation. For speech recognition, the model predicts transcriptions in the *same* language as the audio.
68
+ For speech translation, the model predicts transcriptions to a *different* language to the audio.
69
 
70
+ Whisper checkpoints come in five configurations of varying model sizes.
71
+ The smallest four are trained on either English-only or multilingual data.
72
+ The largest checkpoints are multilingual only. All ten of the pre-trained checkpoints
73
+ are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The
74
+ checkpoints are summarised in the following table with links to the models on the Hub:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ | Size | Parameters | English-only | Multilingual |
77
+ |----------|------------|------------------------------------------------------|-----------------------------------------------------|
78
+ | tiny | 39 M | [βœ“](https://huggingface.co/openai/whisper-tiny.en) | [βœ“](https://huggingface.co/openai/whisper-tiny) |
79
+ | base | 74 M | [βœ“](https://huggingface.co/openai/whisper-base.en) | [βœ“](https://huggingface.co/openai/whisper-base) |
80
+ | small | 244 M | [βœ“](https://huggingface.co/openai/whisper-small.en) | [βœ“](https://huggingface.co/openai/whisper-small) |
81
+ | medium | 769 M | [βœ“](https://huggingface.co/openai/whisper-medium.en) | [βœ“](https://huggingface.co/openai/whisper-medium) |
82
+ | large | 1550 M | x | [βœ“](https://huggingface.co/openai/whisper-large) |
83
+ | large-v2 | 1550 M | x | [βœ“](https://huggingface.co/openai/whisper-large-v2) |
84
 
85
  # Usage
86
 
87
+ This checkpoint is an *English-only* model, meaning it can be used for English speech recognition. Multilingual speech
88
+ recognition or speech translation is possible through use of a multilingual checkpoint.
89
 
90
+ To transcribe audio samples, the model has to be used alongside a [`WhisperProcessor`](https://huggingface.co/docs/transformers/model_doc/whisper#transformers.WhisperProcessor).
 
91
 
92
+ The `WhisperProcessor` is used to:
93
+ 1. Pre-process the audio inputs (converting them to log-Mel spectrograms for the model)
94
+ 2. Post-process the model outputs (converting them from tokens to text)
95
 
96
+ ## Transcription
 
97
 
98
  ```python
99
  >>> from transformers import WhisperProcessor, WhisperForConditionalGeneration
100
  >>> from datasets import load_dataset
 
101
 
102
  >>> # load model and processor
103
  >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
104
  >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
105
 
106
+ >>> # load dummy dataset and read audio files
107
  >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
108
+ >>> sample = ds[0]["audio"]
109
+ >>> input_features = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt").input_features
 
 
 
 
 
 
 
110
 
111
+ >>> # generate token ids
112
+ >>> predicted_ids = model.generate(input_features)
113
+ >>> # decode token ids to text
114
+ >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=False)
115
+ ['<|startoftranscript|><|notimestamps|> Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.<|endoftext|>']
116
+
117
+ >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
118
+ [' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.']
119
+ ```
120
+ The context tokens can be removed from the start of the transcription by setting `skip_special_tokens=True`.
121
 
122
  ## Evaluation
123
 
124
+ This code snippet shows how to evaluate Whisper tiny.en on [LibriSpeech test-clean](https://huggingface.co/datasets/librispeech_asr):
125
 
126
  ```python
127
  >>> from datasets import load_dataset
128
  >>> from transformers import WhisperForConditionalGeneration, WhisperProcessor
 
129
  >>> import torch
130
  >>> from evaluate import load
131
 
132
+ >>> librispeech_test_clean = load_dataset("librispeech_asr", "clean", split="test")
133
 
 
 
 
134
  >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
135
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en").to("cuda")
136
 
137
  >>> def map_to_pred(batch):
138
+ >>> audio = batch["audio"]
139
+ >>> input_features = processor(audio["array"], sampling_rate=audio["sampling_rate"], return_tensors="pt").input_features
140
+ >>> batch["reference"] = processor.tokenizer._normalize(batch['text'])
141
+ >>>
142
  >>> with torch.no_grad():
143
+ >>> predicted_ids = model.generate(input_features.to("cuda"))[0]
144
+ >>> transcription = processor.decode(predicted_ids)
145
+ >>> batch["prediction"] = processor.tokenizer._normalize(transcription)
 
 
 
146
  >>> return batch
147
 
148
+ >>> result = librispeech_test_clean.map(map_to_pred)
149
 
150
  >>> wer = load("wer")
151
+ >>> print(100 * wer.compute(references=result["reference"], predictions=result["prediction"]))
152
+ 5.655609406528749
153
  ```
154
 
155
+ ## Long-Form Transcription
156
+
157
+ The Whisper model is intrinsically designed to work on audio samples of up to 30s in duration. However, by using a chunking
158
+ algorithm, it can be used to transcribe audio samples of up to arbitrary length. This is possible through Transformers
159
+ [`pipeline`](https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)
160
+ method. Chunking is enabled by setting `chunk_length_s=30` when instantiating the pipeline. It can also be extended to
161
+ predict utterance level timestamps by passing `return_timestamps=True`:
162
+
163
+ ```python
164
+ >>> import torch
165
+ >>> from transformers import pipeline
166
+ >>> from datasets import load_dataset
167
+
168
+ >>> device = "cuda:0" if torch.cuda.is_available() else "cpu"
169
+
170
+ >>> pipe = pipeline(
171
+ >>> "automatic-speech-recognition",
172
+ >>> model="openai/whisper-tiny.en",
173
+ >>> chunk_length_s=30,
174
+ >>> device=device,
175
+ >>> )
176
+
177
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
178
+ >>> sample = ds[0]["audio"]
179
+
180
+ >>> prediction = pipe(sample)["text"]
181
+ " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel."
182
+
183
+ >>> # we can also return timestamps for the predictions
184
+ >>> prediction = pipe(sample, return_timestamps=True)["chunks"]
185
+ [{'text': ' Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.',
186
+ 'timestamp': (0.0, 5.44)}]
187
+ ```
188
+
189
+ ## Fine-Tuning
190
+
191
+ The pre-trained Whisper model demonstrates a strong ability to generalise to different datasets and domains. However,
192
+ its predictive capabilities can be improved further for certain languages and tasks through *fine-tuning*. The blog
193
+ post [Fine-Tune Whisper with πŸ€— Transformers](https://huggingface.co/blog/fine-tune-whisper) provides a step-by-step
194
+ guide to fine-tuning the Whisper model with as little as 5 hours of labelled data.
195
 
196
  ### Evaluated Use
197
 
 
228
 
229
 
230
  ### BibTeX entry and citation info
 
231
  ```bibtex
232
  @misc{radford2022whisper,
233
+ doi = {10.48550/ARXIV.2212.04356},
234
+ url = {https://arxiv.org/abs/2212.04356},
235
+ author = {Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},
236
+ title = {Robust Speech Recognition via Large-Scale Weak Supervision},
237
+ publisher = {arXiv},
238
+ year = {2022},
239
+ copyright = {arXiv.org perpetual, non-exclusive license}
240
  }
241
  ```