MIC Whisper-integration (files_sha256 295a044e9f48)
Browse filesFiles changed (3)
- README.mdAdded+26
- integration.jsonAdded+101
- integrations/transformers/usage.mdAdded+145
1234567891011121314151617181920212223242526---tags: - mic - test-artifactbase_model: - openai/whisper-tiny---
# MIC: Whisper speech recognition
Model integration contract (MIC) for one usage path, across the checkpoints that share it. This repository holds the contract code and the manifest; each framework keeps its own expected results and pins this repository by revision. The model repositories are unchanged. It is a test artifact, not a model: exclude it from model search.
Usage path: WhisperProcessor + WhisperForConditionalGeneration.generate, English transcription, batched.
| File | What it is || --- | --- || [`integration.json`](integration.json) | Manifest: checkpoints, which fixture covers each, frameworks, entry points, variants, unsupported targets, comparison rules || [`integrations/transformers/usage.md`](integrations/transformers/usage.md) | Transformers contract, written as doc-builder runnable markdown: the same blocks are documentation and test |
| Checkpoint | Slim fixture (every framework PR) || --- | --- || [`openai/whisper-tiny`](https://huggingface.co/openai/whisper-tiny) | [`hf-internal-testing/proto-whisper-tiny-slim`](https://huggingface.co/hf-internal-testing/proto-whisper-tiny-slim) |
Checked outputs: `generated_tokens`, `generated_text`, `label_logprobs`, `timestamped_tokens`, `timestamped_text`, `feature_extractor_config_keys`, `max_length_tokens`, `assisted_tokens`, `longform_tokens`, `training.loss`, `training.gradients`, `training.updated`.
A fixture pass and a real-checkpoint pass have different scopes; either establishes agreement on fixed inputs and a recorded runtime, not correctness on arbitrary inputs.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101{ "mic": "0.3", "name": "Whisper speech recognition", "usage": "WhisperProcessor + WhisperForConditionalGeneration.generate, English transcription, batched", "architecture": "WhisperForConditionalGeneration", "checkpoints": { "openai/whisper-tiny": { "fixture": "hf-internal-testing/proto-whisper-tiny-slim" } }, "fixtures": { "hf-internal-testing/proto-whisper-tiny-slim": { "built_from": "openai/whisper-tiny", "covers": [ "openai/whisper-tiny" ], "build": { "seed": 17 } } }, "integrations": { "transformers": { "entry_point": "integrations/transformers/usage.md", "format": "runnable-markdown", "requires": [ "transformers>=5", "torch" ], "targets": [ "fixtures", "checkpoints" ], "variants": { "default": {}, "eager": { "attn_implementation": "eager" }, "bfloat16": { "dtype": "bfloat16" } }, "training": true, "resources": { "fixture": { "memory_gb": 1, "download_mb": 20 }, "openai/whisper-tiny": { "memory_gb": 1, "download_mb": 151 } } } }, "outputs": { "runtime": { "compare": "exact" }, "generated_tokens": { "compare": "exact" }, "generated_text": { "compare": "exact" }, "label_logprobs": { "compare": "allclose", "atol": 0.0001, "rtol": 0.0001 }, "timestamped_tokens": { "compare": "exact" }, "timestamped_text": { "compare": "exact" }, "feature_extractor_config_keys": { "compare": "exact" }, "max_length_tokens": { "compare": "exact" }, "assisted_tokens": { "compare": "exact" }, "longform_tokens": { "compare": "exact" }, "training.loss": { "compare": "allclose", "atol": 0.0001, "rtol": 0.0001 }, "training.gradients": { "compare": "all_true" }, "training.updated": { "compare": "true" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# Whisper: speech recognition with Transformers
This page is the Transformers contract of the Whisper MIC and also a usage example. [doc-builder](https://github.com/huggingface/doc-builder/blob/main/docs/runnable-code-blocks.md) renders the `runnable` blocks below as documentation, and its pytest plugin runs them as written against `openai/whisper-tiny`. The MIC runner runs the same blocks against each slim fixture and each checkpoint in [`integration.json`](../../integration.json). Lines marked `# doc-builder: hide` only matter there: they swap in the pinned checkpoint or variant and print the result record.
The audio is synthetic, so the example runs offline: four one-second clips, each a distinct pair of tones. A real checkpoint transcribes them as noise; the slim fixture is trained to name them.
## Transcribe a batch
```py runnable:transcribeimport math
import torchfrom transformers import WhisperForConditionalGeneration, WhisperProcessor, set_seedimport json # doc-builder: hideimport os # doc-builder: hide
model_id = "openai/whisper-tiny"model_id = os.environ.get("MIC_MODEL", model_id) # doc-builder: hidevariant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}")) # doc-builder: hidedevice = "cuda" if torch.cuda.is_available() else "cpu"set_seed(0) # seeds torch, NumPy, and Python: loading, dropout, and data augmentation draw random numbers
processor = WhisperProcessor.from_pretrained(model_id)model = WhisperForConditionalGeneration.from_pretrained(model_id).to(device)if variant: # doc-builder: hide model = WhisperForConditionalGeneration.from_pretrained(model_id, **variant).to(device)
sampling_rate = 16000half = torch.arange(sampling_rate // 2) / sampling_ratetones = [(220, 880), (440, 1320), (660, 330), (990, 550)]clips = [torch.cat([torch.sin(2 * math.pi * a * half), torch.sin(2 * math.pi * b * half)]).mul(0.5).numpy() for a, b in tones]inputs = processor(clips, sampling_rate=sampling_rate, return_tensors="pt").to(device, model.dtype) # floating-point inputs follow the model's dtype
generated = model.generate(inputs.input_features, language="en", task="transcribe", max_new_tokens=8)print(processor.batch_decode(generated, skip_special_tokens=True))```
## Transcribe with timestamps
Whisper can predict segment timestamps; decoding with `decode_with_timestamps=True` keeps them in the text. Integrations also read the feature extractor's configuration without building a processor.
```py runnable:transcribe:3from transformers.models.auto.feature_extraction_auto import get_feature_extractor_config
timestamped = model.generate(inputs.input_features, language="en", task="transcribe", return_timestamps=True, max_new_tokens=8)timestamped_text = processor.batch_decode(timestamped, decode_with_timestamps=True)print(timestamped_text)
feature_config = get_feature_extractor_config(model_id)print(sorted(feature_config))```
## Limit the transcript length
For Whisper, `max_length` counts transcript tokens: `generate` adds the forced start, language, and task tokens on top.
```py runnable:transcribe:3limited = model.generate(inputs.input_features, language="en", task="transcribe", max_length=1)print(processor.batch_decode(limited, skip_special_tokens=True))```
## Speculative decoding
A smaller decoder-only Whisper can draft tokens that the full model verifies, as [Distil-Whisper](https://huggingface.co/distil-whisper/distil-large-v3) does. Here the checkpoint's own decoder, loaded as `WhisperForCausalLM`, is the assistant; the transcript must not change. Assisted generation takes one clip at a time.
```py runnable:transcribe:3from transformers import WhisperForCausalLM
assistant = WhisperForCausalLM.from_pretrained(model_id).to(device)if variant: # doc-builder: hide assistant = WhisperForCausalLM.from_pretrained(model_id, **variant).to(device)assisted = [ model.generate(features[None], language="en", task="transcribe", max_new_tokens=8, assistant_model=assistant)[0].tolist() for features in inputs.input_features]print(processor.batch_decode(assisted, skip_special_tokens=True))```
## Transcribe long audio in a batch
Audio longer than 30 seconds is transcribed segment by segment. Keep the full audio (`truncation=False`), pad the batch to its longest clip, and pass the attention mask; `condition_on_prev_tokens=True` prompts each segment with the previous one's text.
```py runnable:transcribe:3long_clips = [ torch.cat([torch.from_numpy(clips[(start + k) % len(clips)]) for k in range(seconds)]).numpy() for start, seconds in ((0, 36), (1, 32))]long_inputs = processor( long_clips, sampling_rate=sampling_rate, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True).to(device, model.dtype)longform = model.generate( **long_inputs, language="en", task="transcribe", condition_on_prev_tokens=True, return_timestamps=True, temperature=0.0, max_new_tokens=8,)print(processor.batch_decode(longform, skip_special_tokens=True))```
## One training step
```py runnable:transcribe:3transcripts = [" red", " green", " blue", " yellow"]processor.tokenizer.set_prefix_tokens(language="english", task="transcribe", predict_timestamps=False)targets = processor.tokenizer(transcripts, return_tensors="pt", padding=True).to(device)decoder_input_ids = targets.input_ids[:, :-1]labels = targets.input_ids[:, 1:].masked_fill(targets.attention_mask[:, 1:] == 0, -100)
with torch.no_grad(): # doc-builder: hide # Teacher-forced log-probabilities of the reference transcripts. logprobs = model(input_features=inputs.input_features, decoder_input_ids=decoder_input_ids).logits.float().log_softmax(-1) label_logprobs = logprobs.gather(-1, labels.clamp(min=0)[..., None])[..., 0].masked_fill(labels == -100, 0.0)
model.train()optimizer = torch.optim.SGD(model.parameters(), lr=0.01)loss = model(input_features=inputs.input_features, decoder_input_ids=decoder_input_ids, labels=labels).lossloss.backward()before = {name: p.detach().clone() for name, p in model.named_parameters()} # doc-builder: hideoptimizer.step()print(f"loss: {loss.item():.4f}")
if os.environ.get("MIC_RUNNER"): # doc-builder: hide named = dict(model.named_parameters()) checked = ("model.encoder.conv1.weight", "model.decoder.layers.0.encoder_attn.q_proj.weight") result = { "runtime": { "device": model.device.type, "dtype": str(model.dtype).removeprefix("torch."), "attn_implementation": model.config._attn_implementation, }, "generated_tokens": generated.tolist(), "generated_text": processor.batch_decode(generated, skip_special_tokens=True), "label_logprobs": label_logprobs.tolist(), "timestamped_tokens": timestamped.tolist(), "timestamped_text": timestamped_text, "feature_extractor_config_keys": sorted(feature_config), "max_length_tokens": limited.tolist(), "assisted_tokens": assisted, "longform_tokens": longform.tolist(), "training": { "loss": loss.item(), "gradients": {n: bool(named[n].grad is not None and torch.count_nonzero(named[n].grad) > 0 and torch.isfinite(named[n].grad).all()) for n in checked}, "updated": any(not torch.equal(p, before[n]) for n, p in named.items()), }, } print(json.dumps(result))```README.mdAdded+26
integration.jsonAdded+101
integrations/transformers/usage.mdAdded+145