tarekziade HF Staff commited on
Commit
e3da1ed
·
verified ·
1 Parent(s): d1e995e

MIC Wav2Vec2-integration (files_sha256 705477e73486)

Browse files
Files changed (3) hide show
  1. README.md +26 -0
  2. integration.json +89 -0
  3. integrations/transformers/usage.md +87 -0
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - mic
4
+ - test-artifact
5
+ base_model:
6
+ - facebook/wav2vec2-base-960h
7
+ ---
8
+
9
+ # MIC: Wav2Vec2 CTC speech recognition
10
+
11
+ 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.
12
+
13
+ Usage path: Wav2Vec2Processor + Wav2Vec2ForCTC, greedy CTC decoding, batched.
14
+
15
+ | File | What it is |
16
+ | --- | --- |
17
+ | [`integration.json`](integration.json) | Manifest: checkpoints, which fixture covers each, frameworks, entry points, variants, unsupported targets, comparison rules |
18
+ | [`integrations/transformers/usage.md`](integrations/transformers/usage.md) | Transformers contract, written as doc-builder runnable markdown: the same blocks are documentation and test |
19
+
20
+ | Checkpoint | Slim fixture (every framework PR) |
21
+ | --- | --- |
22
+ | [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) | [`hf-internal-testing/proto-wav2vec2-base-960h-slim`](https://huggingface.co/hf-internal-testing/proto-wav2vec2-base-960h-slim) |
23
+
24
+ Checked outputs: `predicted_ids`, `predicted_text`, `logits`, `feature_extractor_config_keys`, `training.loss`, `training.gradients`, `training.updated`.
25
+
26
+ 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.
integration.json ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mic": "0.3",
3
+ "name": "Wav2Vec2 CTC speech recognition",
4
+ "usage": "Wav2Vec2Processor + Wav2Vec2ForCTC, greedy CTC decoding, batched",
5
+ "architecture": "Wav2Vec2ForCTC",
6
+ "checkpoints": {
7
+ "facebook/wav2vec2-base-960h": {
8
+ "fixture": "hf-internal-testing/proto-wav2vec2-base-960h-slim"
9
+ }
10
+ },
11
+ "fixtures": {
12
+ "hf-internal-testing/proto-wav2vec2-base-960h-slim": {
13
+ "built_from": "facebook/wav2vec2-base-960h",
14
+ "covers": [
15
+ "facebook/wav2vec2-base-960h"
16
+ ],
17
+ "build": {
18
+ "seed": 17,
19
+ "accept_insensitive": {
20
+ "input_values:halve": "Wav2Vec2-base's bias-free first convolution feeds a group norm, so at fixture size the output ignores input amplitude (5e-5, random or overfit); the real checkpoint moves by 3.9. Amplitude regressions need the real-checkpoint run."
21
+ }
22
+ }
23
+ }
24
+ },
25
+ "integrations": {
26
+ "transformers": {
27
+ "entry_point": "integrations/transformers/usage.md",
28
+ "format": "runnable-markdown",
29
+ "requires": [
30
+ "transformers>=5",
31
+ "torch"
32
+ ],
33
+ "targets": [
34
+ "fixtures",
35
+ "checkpoints"
36
+ ],
37
+ "variants": {
38
+ "default": {},
39
+ "eager": {
40
+ "attn_implementation": "eager"
41
+ },
42
+ "bfloat16": {
43
+ "dtype": "bfloat16"
44
+ }
45
+ },
46
+ "training": true,
47
+ "resources": {
48
+ "fixture": {
49
+ "memory_gb": 1,
50
+ "download_mb": 20
51
+ },
52
+ "facebook/wav2vec2-base-960h": {
53
+ "memory_gb": 2,
54
+ "download_mb": 378
55
+ }
56
+ }
57
+ }
58
+ },
59
+ "outputs": {
60
+ "runtime": {
61
+ "compare": "exact"
62
+ },
63
+ "predicted_ids": {
64
+ "compare": "exact"
65
+ },
66
+ "predicted_text": {
67
+ "compare": "exact"
68
+ },
69
+ "logits": {
70
+ "compare": "allclose",
71
+ "atol": 0.0001,
72
+ "rtol": 0.0001
73
+ },
74
+ "feature_extractor_config_keys": {
75
+ "compare": "exact"
76
+ },
77
+ "training.loss": {
78
+ "compare": "allclose",
79
+ "atol": 0.0001,
80
+ "rtol": 0.0001
81
+ },
82
+ "training.gradients": {
83
+ "compare": "all_true"
84
+ },
85
+ "training.updated": {
86
+ "compare": "true"
87
+ }
88
+ }
89
+ }
integrations/transformers/usage.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wav2Vec2: CTC speech recognition with Transformers
2
+
3
+ This page is the Transformers contract of the Wav2Vec2 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 `facebook/wav2vec2-base-960h`. 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.
4
+
5
+ The audio is synthetic, so the example runs offline: four one-second clips, each a distinct pair of tones.
6
+
7
+ ## Transcribe a batch
8
+
9
+ ```py runnable:ctc
10
+ import math
11
+
12
+ import torch
13
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor, set_seed
14
+ import json # doc-builder: hide
15
+ import os # doc-builder: hide
16
+
17
+ model_id = "facebook/wav2vec2-base-960h"
18
+ model_id = os.environ.get("MIC_MODEL", model_id) # doc-builder: hide
19
+ variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}")) # doc-builder: hide
20
+ device = "cuda" if torch.cuda.is_available() else "cpu"
21
+ set_seed(0) # seeds torch, NumPy, and Python: loading, dropout, and data augmentation draw random numbers
22
+
23
+ processor = Wav2Vec2Processor.from_pretrained(model_id)
24
+ model = Wav2Vec2ForCTC.from_pretrained(model_id).to(device)
25
+ if variant: # doc-builder: hide
26
+ model = Wav2Vec2ForCTC.from_pretrained(model_id, **variant).to(device)
27
+
28
+ sampling_rate = 16000
29
+ half = torch.arange(sampling_rate // 2) / sampling_rate
30
+ tones = [(220, 880), (440, 1320), (660, 330), (990, 550)]
31
+ 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]
32
+ inputs = processor(clips, sampling_rate=sampling_rate, return_tensors="pt", padding=True).to(device, model.dtype) # floating-point inputs follow the model's dtype
33
+
34
+ with torch.no_grad():
35
+ logits = model(**inputs).logits
36
+ predicted_ids = logits.argmax(dim=-1)
37
+ print(processor.batch_decode(predicted_ids))
38
+ ```
39
+
40
+ ## Read the preprocessing configuration
41
+
42
+ Integrations read the feature extractor's configuration without building a processor.
43
+
44
+ ```py runnable:ctc:3
45
+ from transformers.models.auto.feature_extraction_auto import get_feature_extractor_config
46
+
47
+ feature_config = get_feature_extractor_config(model_id)
48
+ print(sorted(feature_config))
49
+ ```
50
+
51
+ ## One training step
52
+
53
+ ```py runnable:ctc:3
54
+ transcripts = ["RED", "GREEN", "BLUE", "YELLOW"]
55
+ labels = processor(text=transcripts, return_tensors="pt", padding=True).input_ids.to(device)
56
+ labels = labels.masked_fill(labels == processor.tokenizer.pad_token_id, -100)
57
+
58
+ model.train()
59
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
60
+ loss = model(**inputs, labels=labels).loss
61
+ loss.backward()
62
+ before = {name: p.detach().clone() for name, p in model.named_parameters()} # doc-builder: hide
63
+ optimizer.step()
64
+ print(f"loss: {loss.item():.4f}")
65
+
66
+ if os.environ.get("MIC_RUNNER"): # doc-builder: hide
67
+ named = dict(model.named_parameters())
68
+ # First and last layers: LayerDrop (0.1) may skip any encoder layer in a training step.
69
+ checked = ("wav2vec2.feature_extractor.conv_layers.0.conv.weight", "lm_head.weight")
70
+ result = {
71
+ "runtime": {
72
+ "device": model.device.type,
73
+ "dtype": str(model.dtype).removeprefix("torch."),
74
+ "attn_implementation": model.config._attn_implementation,
75
+ },
76
+ "predicted_ids": predicted_ids.tolist(),
77
+ "predicted_text": processor.batch_decode(predicted_ids),
78
+ "logits": logits.float().tolist(),
79
+ "feature_extractor_config_keys": sorted(feature_config),
80
+ "training": {
81
+ "loss": loss.item(),
82
+ "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},
83
+ "updated": any(not torch.equal(p, before[n]) for n, p in named.items()),
84
+ },
85
+ }
86
+ print(json.dumps(result))
87
+ ```