mazesmazes commited on
Commit
7b56ba4
·
verified ·
1 Parent(s): 60a49c3

Update custom model files, README, and requirements

Browse files
Files changed (5) hide show
  1. README.md +52 -178
  2. asr_modeling.py +1 -1
  3. asr_pipeline.py +3 -0
  4. handler.py +114 -0
  5. requirements.txt +6 -0
README.md CHANGED
@@ -1,199 +1,73 @@
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
+ license: mit
3
+ language:
4
+ - en
5
+ datasets:
6
+ - speechbrain/LoquaciousSet
7
+ base_model:
8
+ - openai/whisper-large-v3-turbo
9
+ - HuggingFaceTB/SmolLM3-3B
10
+ pipeline_tag: automatic-speech-recognition
11
+ tags:
12
+ - asr
13
+ - speech-recognition
14
+ - audio
15
+ - smollm
16
+ - whisper
17
+ - mlp
18
  ---
19
 
20
+ # Tiny Audio
21
 
22
+ A speech recognition model trained in 24 hours on a single GPU for ~$12. Built with the [Tiny Audio](https://github.com/alexkroman/tiny-audio) codebase—a minimal, hackable framework for training ASR models.
23
 
24
+ ## Architecture
25
 
26
+ ```
27
+ Audio (16kHz) → Whisper Encoder (frozen) → MLP Projector (trained) → SmolLM3-3B (frozen) → Text
28
+ ```
29
 
30
+ **MLP Projector:**
31
+ - Convolutional downsampling: 4x sequence compression via two stride-2 conv layers
32
+ - Linear (1280 → 2048) → GELU → Linear (2048 → 2048)
33
+ - Output normalization: RMSNorm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  ## Training Details
36
 
37
+ | | |
38
+ |---|---|
39
+ | **Dataset** | LoquaciousSet (25,000 hours) |
40
+ | **Hardware** | Single NVIDIA A40 40GB |
41
+ | **Training Time** | ~24 hours |
42
+ | **Cost** | ~$12 |
43
+ | **Trainable Parameters** | ~12M (projector only) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ ## Performance
46
 
47
+ **Word Error Rate (WER): 12.14%** on LoquaciousSet test set.
48
 
49
+ See the [community leaderboard](https://github.com/alexkroman/tiny-audio#leaderboard) for comparisons.
50
 
51
+ ## Usage
52
 
53
+ ```python
54
+ from transformers import pipeline
55
 
56
+ pipe = pipeline("automatic-speech-recognition", model="mazesmazes/tiny-audio", trust_remote_code=True)
57
 
58
+ result = pipe("path/to/audio.wav")
59
+ print(result["text"])
60
+ ```
61
 
62
+ ## Limitations
63
 
64
+ - English only
65
+ - Optimized for 16kHz audio; other sample rates are resampled automatically
66
+ - Performance may degrade on heavily accented speech, noisy environments, or domain-specific jargon
67
+ - Maximum audio length limited by context window
68
 
69
+ ## Learn More
70
 
71
+ - **[Train your own model](https://github.com/alexkroman/tiny-audio)** — The full codebase with training scripts
72
+ - **[Free 3-hour course](https://github.com/alexkroman/tiny-audio/blob/main/docs/course/0-course-overview.md)** — Build your own ASR system from scratch
73
+ - **[Submit to leaderboard](https://github.com/alexkroman/tiny-audio#leaderboard)** — Share your trained model
asr_modeling.py CHANGED
@@ -168,7 +168,7 @@ class ASRModel(PreTrainedModel, GenerationMixin):
168
  decoder_kwargs = {
169
  "attn_implementation": config.attn_implementation,
170
  "trust_remote_code": True,
171
- "tie_word_embeddings": False,
172
  "low_cpu_mem_usage": True,
173
  "dtype": dtype,
174
  }
 
168
  decoder_kwargs = {
169
  "attn_implementation": config.attn_implementation,
170
  "trust_remote_code": True,
171
+ "tie_word_embeddings": True,
172
  "low_cpu_mem_usage": True,
173
  "dtype": dtype,
174
  }
asr_pipeline.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from pathlib import Path
2
  from typing import Any
3
 
@@ -473,4 +474,6 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
473
  tokens = tokens[0]
474
 
475
  text = self.tokenizer.decode(tokens, skip_special_tokens=True).strip()
 
 
476
  return {"text": text}
 
1
+ import re
2
  from pathlib import Path
3
  from typing import Any
4
 
 
474
  tokens = tokens[0]
475
 
476
  text = self.tokenizer.decode(tokens, skip_special_tokens=True).strip()
477
+ # Strip <think>...</think> tags (Qwen3 doesn't respect /no_think prompt)
478
+ text = re.sub(r"<think>.*?</think>\s*", "", text, flags=re.DOTALL).strip()
479
  return {"text": text}
handler.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom inference handler for HuggingFace Inference Endpoints."""
2
+
3
+ from typing import Any, Dict, List, Union
4
+
5
+ import torch
6
+
7
+ try:
8
+ # For remote execution, imports are relative
9
+ from .asr_modeling import ASRModel
10
+ from .asr_pipeline import ASRPipeline
11
+ except ImportError:
12
+ # For local execution, imports are not relative
13
+ from asr_modeling import ASRModel # type: ignore[no-redef]
14
+ from asr_pipeline import ASRPipeline # type: ignore[no-redef]
15
+
16
+
17
+ class EndpointHandler:
18
+ def __init__(self, path: str = ""):
19
+ import os
20
+
21
+ import nltk
22
+
23
+ nltk.download("punkt_tab", quiet=True)
24
+
25
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
26
+
27
+ # Enable TF32 for faster matmul on Ampere+ GPUs (A100, etc.)
28
+ # Also beneficial for T4 (Turing) which supports TensorFloat-32
29
+ torch.backends.cuda.matmul.allow_tf32 = True
30
+ torch.backends.cudnn.allow_tf32 = True
31
+
32
+ # Set device and dtype
33
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
34
+
35
+ # Use float16 for better T4 compatibility (bfloat16 not well supported on T4)
36
+ # T4 has excellent float16 performance with tensor cores
37
+ self.dtype = torch.float16 if self.device == "cuda" else torch.float32
38
+
39
+ # Enable CUDA optimizations
40
+ if torch.cuda.is_available():
41
+ torch.backends.cudnn.benchmark = True
42
+
43
+ # Prepare model kwargs for pipeline
44
+ model_kwargs = {
45
+ "dtype": self.dtype,
46
+ "low_cpu_mem_usage": True,
47
+ }
48
+ if torch.cuda.is_available():
49
+ model_kwargs["attn_implementation"] = (
50
+ "flash_attention_2" if self._is_flash_attn_available() else "sdpa"
51
+ )
52
+
53
+ # Load model (this loads the model, tokenizer, and feature extractor)
54
+ self.model = ASRModel.from_pretrained(path, **model_kwargs)
55
+
56
+ # Instantiate custom pipeline - it will get feature_extractor and tokenizer from model
57
+ self.pipe = ASRPipeline(
58
+ model=self.model,
59
+ feature_extractor=self.model.feature_extractor,
60
+ tokenizer=self.model.tokenizer,
61
+ device=self.device,
62
+ )
63
+
64
+ # Apply torch.compile if enabled (after model is loaded by pipeline)
65
+ # Use "default" mode for T4 - better compatibility than "reduce-overhead"
66
+ # "reduce-overhead" is better for A100+ but can be slower on older GPUs
67
+ if torch.cuda.is_available() and os.getenv("ENABLE_TORCH_COMPILE", "1") == "1":
68
+ compile_mode = os.getenv("TORCH_COMPILE_MODE", "default")
69
+ self.model = torch.compile(self.model, mode=compile_mode)
70
+ self.pipe.model = self.model
71
+
72
+ # Warmup the model to trigger compilation and optimize kernels
73
+ if torch.cuda.is_available():
74
+ self._warmup()
75
+
76
+ def _is_flash_attn_available(self):
77
+ """Check if flash attention is available."""
78
+ import importlib.util
79
+
80
+ return importlib.util.find_spec("flash_attn") is not None
81
+
82
+ def _warmup(self):
83
+ """Warmup to trigger model compilation and allocate GPU memory."""
84
+ try:
85
+ # Create dummy audio (1 second at config sample rate)
86
+ sample_rate = self.pipe.model.config.audio_sample_rate
87
+ dummy_audio = torch.randn(sample_rate, dtype=torch.float32)
88
+
89
+ # Run inference to trigger torch.compile and kernel optimization
90
+ with torch.inference_mode():
91
+ warmup_tokens = self.pipe.model.config.inference_warmup_tokens
92
+ _ = self.pipe(
93
+ {"raw": dummy_audio, "sampling_rate": sample_rate},
94
+ max_new_tokens=warmup_tokens,
95
+ )
96
+
97
+ # Force CUDA synchronization to ensure kernels are compiled
98
+ if torch.cuda.is_available():
99
+ torch.cuda.synchronize()
100
+ # Clear cache after warmup to free memory
101
+ torch.cuda.empty_cache()
102
+
103
+ except Exception as e:
104
+ print(f"Warmup skipped due to: {e}")
105
+
106
+ def __call__(self, data: Dict[str, Any]) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
107
+ inputs = data.get("inputs")
108
+ if inputs is None:
109
+ raise ValueError("Missing 'inputs' in request data")
110
+
111
+ # Pass through any parameters from request, let model config provide defaults
112
+ params = data.get("parameters", {})
113
+
114
+ return self.pipe(inputs, **params)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Core dependencies for tiny-audio model inference
2
+ # This file is pushed to HuggingFace for model repository
3
+
4
+ # Transformers - main library for model loading and inference
5
+ transformers>=4.57.0
6
+ truecase