Update custom model files, README, and requirements
Browse files- README.md +52 -178
- asr_config.py +4 -0
- asr_modeling.py +23 -6
- asr_processing.py +3 -2
- handler.py +114 -0
- projectors.py +24 -100
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,199 +1,73 @@
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
---
|
| 5 |
|
| 6 |
-
#
|
| 7 |
|
| 8 |
-
|
| 9 |
|
|
|
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 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 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 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 |
-
|
| 180 |
|
| 181 |
-
|
| 182 |
|
| 183 |
-
|
| 184 |
|
| 185 |
-
|
| 186 |
|
| 187 |
-
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
|
| 191 |
-
|
|
|
|
|
|
|
| 192 |
|
| 193 |
-
##
|
| 194 |
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
##
|
| 198 |
|
| 199 |
-
[
|
|
|
|
|
|
|
|
|
| 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_config.py
CHANGED
|
@@ -18,6 +18,7 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 18 |
user_prompt: str = "Transcribe: <audio>",
|
| 19 |
encoder_dim: Optional[int] = None,
|
| 20 |
llm_dim: Optional[int] = None,
|
|
|
|
| 21 |
audio_sample_rate: int = 16000,
|
| 22 |
projector_init_std: float = 0.02,
|
| 23 |
projector_pool_stride: int = 4,
|
|
@@ -26,6 +27,7 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 26 |
projector_type: str = "moe", # "moe", "swiglu", "residual", "shared_moe", "mlp", "qformer"
|
| 27 |
projector_num_layers: int = 2, # Number of layers (for residual projector)
|
| 28 |
projector_dropout: float = 0.0, # Dropout rate for projector layers
|
|
|
|
| 29 |
# MoE-specific configuration
|
| 30 |
num_experts: int = 4, # Number of experts in MoE projectors
|
| 31 |
num_experts_per_tok: int = 2, # Top-k experts per token
|
|
@@ -66,6 +68,7 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 66 |
self.user_prompt = user_prompt
|
| 67 |
self.encoder_dim = encoder_dim
|
| 68 |
self.llm_dim = llm_dim
|
|
|
|
| 69 |
self.audio_sample_rate = audio_sample_rate
|
| 70 |
self.projector_init_std = projector_init_std
|
| 71 |
self.projector_pool_stride = projector_pool_stride
|
|
@@ -74,6 +77,7 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 74 |
self.projector_type = projector_type
|
| 75 |
self.projector_num_layers = projector_num_layers
|
| 76 |
self.projector_dropout = projector_dropout
|
|
|
|
| 77 |
# MoE-specific configuration
|
| 78 |
self.num_experts = num_experts
|
| 79 |
self.num_experts_per_tok = num_experts_per_tok
|
|
|
|
| 18 |
user_prompt: str = "Transcribe: <audio>",
|
| 19 |
encoder_dim: Optional[int] = None,
|
| 20 |
llm_dim: Optional[int] = None,
|
| 21 |
+
encoder_stride: int = 2, # Temporal downsampling factor of audio encoder
|
| 22 |
audio_sample_rate: int = 16000,
|
| 23 |
projector_init_std: float = 0.02,
|
| 24 |
projector_pool_stride: int = 4,
|
|
|
|
| 27 |
projector_type: str = "moe", # "moe", "swiglu", "residual", "shared_moe", "mlp", "qformer"
|
| 28 |
projector_num_layers: int = 2, # Number of layers (for residual projector)
|
| 29 |
projector_dropout: float = 0.0, # Dropout rate for projector layers
|
| 30 |
+
projector_downsample: bool = True, # Whether to downsample in MLP projector
|
| 31 |
# MoE-specific configuration
|
| 32 |
num_experts: int = 4, # Number of experts in MoE projectors
|
| 33 |
num_experts_per_tok: int = 2, # Top-k experts per token
|
|
|
|
| 68 |
self.user_prompt = user_prompt
|
| 69 |
self.encoder_dim = encoder_dim
|
| 70 |
self.llm_dim = llm_dim
|
| 71 |
+
self.encoder_stride = encoder_stride
|
| 72 |
self.audio_sample_rate = audio_sample_rate
|
| 73 |
self.projector_init_std = projector_init_std
|
| 74 |
self.projector_pool_stride = projector_pool_stride
|
|
|
|
| 77 |
self.projector_type = projector_type
|
| 78 |
self.projector_num_layers = projector_num_layers
|
| 79 |
self.projector_dropout = projector_dropout
|
| 80 |
+
self.projector_downsample = projector_downsample
|
| 81 |
# MoE-specific configuration
|
| 82 |
self.num_experts = num_experts
|
| 83 |
self.num_experts_per_tok = num_experts_per_tok
|
asr_modeling.py
CHANGED
|
@@ -81,6 +81,7 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 81 |
super().__init__(config)
|
| 82 |
|
| 83 |
self.system_prompt = config.system_prompt
|
|
|
|
| 84 |
target_dtype = getattr(torch, config.model_dtype)
|
| 85 |
|
| 86 |
# Audio encoder (frozen)
|
|
@@ -138,6 +139,17 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 138 |
full_model = WhisperModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
|
| 139 |
encoder = full_model.encoder
|
| 140 |
del full_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
else:
|
| 142 |
encoder = AutoModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
|
| 143 |
|
|
@@ -207,7 +219,7 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 207 |
self.tokenizer.pad_token = "<|finetune_right_pad_id|>"
|
| 208 |
|
| 209 |
# Add audio token
|
| 210 |
-
existing_special = self.tokenizer
|
| 211 |
if "<audio>" not in existing_special:
|
| 212 |
self.tokenizer.add_special_tokens(
|
| 213 |
{"additional_special_tokens": existing_special + ["<audio>"]}
|
|
@@ -260,7 +272,12 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 260 |
except ImportError:
|
| 261 |
from asr_processing import ASRProcessor # type: ignore[no-redef]
|
| 262 |
|
| 263 |
-
return ASRProcessor(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
def state_dict(self, *args, **kwargs):
|
| 266 |
"""Only save trainable projector weights."""
|
|
@@ -284,8 +301,8 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 284 |
encoder_out = self.audio_tower(input_features=audio_features)
|
| 285 |
hidden_states = encoder_out.last_hidden_state
|
| 286 |
|
| 287 |
-
# Truncate to actual audio length (mel_frames -> encoder_frames via stride
|
| 288 |
-
real_encoder_len = audio_attention_mask.sum(dim=-1) //
|
| 289 |
max_real_len = int(real_encoder_len.max().item())
|
| 290 |
hidden_states = hidden_states[:, :max_real_len]
|
| 291 |
|
|
@@ -365,10 +382,10 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 365 |
"""Calculate number of audio tokens based on actual audio length.
|
| 366 |
|
| 367 |
Uses attention mask to get real audio length, then computes:
|
| 368 |
-
mel_frames -> encoder_frames (stride
|
| 369 |
"""
|
| 370 |
mel_len = int(audio_attention_mask.sum(dim=-1).max().item())
|
| 371 |
-
encoder_output_len = mel_len //
|
| 372 |
return int(self.projector.get_output_length(encoder_output_len))
|
| 373 |
|
| 374 |
@torch.no_grad()
|
|
|
|
| 81 |
super().__init__(config)
|
| 82 |
|
| 83 |
self.system_prompt = config.system_prompt
|
| 84 |
+
self.encoder_stride = config.encoder_stride
|
| 85 |
target_dtype = getattr(torch, config.model_dtype)
|
| 86 |
|
| 87 |
# Audio encoder (frozen)
|
|
|
|
| 139 |
full_model = WhisperModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
|
| 140 |
encoder = full_model.encoder
|
| 141 |
del full_model
|
| 142 |
+
elif "glm" in config.audio_model_id.lower():
|
| 143 |
+
# GLM-ASR models use audio_tower as the encoder
|
| 144 |
+
# Requires transformers >= 5.x or installed from source
|
| 145 |
+
from transformers import AutoModelForSeq2SeqLM
|
| 146 |
+
|
| 147 |
+
full_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 148 |
+
config.audio_model_id, trust_remote_code=True, **encoder_kwargs
|
| 149 |
+
)
|
| 150 |
+
# GLM stores encoder at audio_tower (GlmAsrEncoder)
|
| 151 |
+
encoder = full_model.audio_tower
|
| 152 |
+
del full_model
|
| 153 |
else:
|
| 154 |
encoder = AutoModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
|
| 155 |
|
|
|
|
| 219 |
self.tokenizer.pad_token = "<|finetune_right_pad_id|>"
|
| 220 |
|
| 221 |
# Add audio token
|
| 222 |
+
existing_special = getattr(self.tokenizer, "additional_special_tokens", None) or []
|
| 223 |
if "<audio>" not in existing_special:
|
| 224 |
self.tokenizer.add_special_tokens(
|
| 225 |
{"additional_special_tokens": existing_special + ["<audio>"]}
|
|
|
|
| 272 |
except ImportError:
|
| 273 |
from asr_processing import ASRProcessor # type: ignore[no-redef]
|
| 274 |
|
| 275 |
+
return ASRProcessor(
|
| 276 |
+
feature_extractor=self.feature_extractor,
|
| 277 |
+
tokenizer=self.tokenizer,
|
| 278 |
+
projector=self.projector,
|
| 279 |
+
encoder_stride=self.encoder_stride,
|
| 280 |
+
)
|
| 281 |
|
| 282 |
def state_dict(self, *args, **kwargs):
|
| 283 |
"""Only save trainable projector weights."""
|
|
|
|
| 301 |
encoder_out = self.audio_tower(input_features=audio_features)
|
| 302 |
hidden_states = encoder_out.last_hidden_state
|
| 303 |
|
| 304 |
+
# Truncate to actual audio length (mel_frames -> encoder_frames via encoder stride)
|
| 305 |
+
real_encoder_len = audio_attention_mask.sum(dim=-1) // self.encoder_stride
|
| 306 |
max_real_len = int(real_encoder_len.max().item())
|
| 307 |
hidden_states = hidden_states[:, :max_real_len]
|
| 308 |
|
|
|
|
| 382 |
"""Calculate number of audio tokens based on actual audio length.
|
| 383 |
|
| 384 |
Uses attention mask to get real audio length, then computes:
|
| 385 |
+
mel_frames -> encoder_frames (via encoder stride) -> projector output tokens
|
| 386 |
"""
|
| 387 |
mel_len = int(audio_attention_mask.sum(dim=-1).max().item())
|
| 388 |
+
encoder_output_len = mel_len // self.encoder_stride
|
| 389 |
return int(self.projector.get_output_length(encoder_output_len))
|
| 390 |
|
| 391 |
@torch.no_grad()
|
asr_processing.py
CHANGED
|
@@ -19,11 +19,12 @@ class ASRProcessor(ProcessorMixin):
|
|
| 19 |
AUDIO_TOKEN = "<audio>"
|
| 20 |
TRANSCRIBE_PROMPT = "Transcribe: "
|
| 21 |
|
| 22 |
-
def __init__(self, feature_extractor, tokenizer, projector=None):
|
| 23 |
self.feature_extractor = feature_extractor
|
| 24 |
self.tokenizer = tokenizer
|
| 25 |
self.audio_token_id = tokenizer.convert_tokens_to_ids(self.AUDIO_TOKEN)
|
| 26 |
self.projector = projector
|
|
|
|
| 27 |
|
| 28 |
def __call__(
|
| 29 |
self,
|
|
@@ -60,7 +61,7 @@ class ASRProcessor(ProcessorMixin):
|
|
| 60 |
|
| 61 |
# Use actual audio length (from attention mask) for token count
|
| 62 |
real_mel_len = audio_inputs["attention_mask"].sum(dim=-1).max().item()
|
| 63 |
-
encoder_output_len = real_mel_len //
|
| 64 |
num_audio_tokens = self.projector.get_output_length(encoder_output_len)
|
| 65 |
else:
|
| 66 |
num_audio_tokens = 0
|
|
|
|
| 19 |
AUDIO_TOKEN = "<audio>"
|
| 20 |
TRANSCRIBE_PROMPT = "Transcribe: "
|
| 21 |
|
| 22 |
+
def __init__(self, feature_extractor, tokenizer, projector=None, encoder_stride: int = 2):
|
| 23 |
self.feature_extractor = feature_extractor
|
| 24 |
self.tokenizer = tokenizer
|
| 25 |
self.audio_token_id = tokenizer.convert_tokens_to_ids(self.AUDIO_TOKEN)
|
| 26 |
self.projector = projector
|
| 27 |
+
self.encoder_stride = encoder_stride
|
| 28 |
|
| 29 |
def __call__(
|
| 30 |
self,
|
|
|
|
| 61 |
|
| 62 |
# Use actual audio length (from attention mask) for token count
|
| 63 |
real_mel_len = audio_inputs["attention_mask"].sum(dim=-1).max().item()
|
| 64 |
+
encoder_output_len = real_mel_len // self.encoder_stride
|
| 65 |
num_audio_tokens = self.projector.get_output_length(encoder_output_len)
|
| 66 |
else:
|
| 67 |
num_audio_tokens = 0
|
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)
|
projectors.py
CHANGED
|
@@ -23,45 +23,48 @@ from transformers.models.llama.modeling_llama import LlamaRMSNorm
|
|
| 23 |
|
| 24 |
|
| 25 |
class MLPAudioProjector(nn.Module):
|
| 26 |
-
"""2-layer MLP projector with conv-based 2x temporal downsampling.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def __init__(self, config):
|
| 29 |
super().__init__()
|
| 30 |
|
| 31 |
encoder_dim = getattr(config, "encoder_dim", 768)
|
| 32 |
llm_dim = getattr(config, "llm_dim", 2048)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
self.downsample = nn.Conv1d(
|
| 35 |
-
encoder_dim, encoder_dim, kernel_size=3, stride=2, padding=1, bias=False
|
| 36 |
-
)
|
| 37 |
self.linear_1 = nn.Linear(encoder_dim, llm_dim, bias=False)
|
| 38 |
self.act = nn.GELU()
|
| 39 |
self.linear_2 = nn.Linear(llm_dim, llm_dim, bias=False)
|
| 40 |
-
|
| 41 |
-
self.apply(self._init_weights)
|
| 42 |
-
|
| 43 |
-
def _init_weights(self, module):
|
| 44 |
-
if isinstance(module, nn.Linear):
|
| 45 |
-
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 46 |
-
elif isinstance(module, nn.Conv1d):
|
| 47 |
-
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 48 |
-
if module.bias is not None:
|
| 49 |
-
nn.init.zeros_(module.bias)
|
| 50 |
|
| 51 |
def get_output_length(self, input_length: int) -> int:
|
| 52 |
"""Calculate output sequence length given input length."""
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
def forward(self, x):
|
| 57 |
"""
|
| 58 |
x: [Batch, Seq_Len, Dim]
|
| 59 |
-
Returns: [Batch, Seq_Len // 2, llm_dim]
|
| 60 |
"""
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
| 65 |
|
| 66 |
x = self.linear_1(x)
|
| 67 |
x = self.act(x)
|
|
@@ -578,84 +581,6 @@ class QFormerAudioProjector(nn.Module):
|
|
| 578 |
return self.linear(query_proj)
|
| 579 |
|
| 580 |
|
| 581 |
-
# =============================================================================
|
| 582 |
-
# Transformer Projector
|
| 583 |
-
# =============================================================================
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
class TransformerAudioProjector(nn.Module):
|
| 587 |
-
"""
|
| 588 |
-
Transformer Projector (FunASR Style).
|
| 589 |
-
Projects to LLM dim first, then applies transformer blocks for context mixing.
|
| 590 |
-
"""
|
| 591 |
-
|
| 592 |
-
def __init__(self, config):
|
| 593 |
-
super().__init__()
|
| 594 |
-
# Default stride 6: Whisper (2x) * Projector (6x) = 12x total → ~8 Hz
|
| 595 |
-
# Matches FunASR's total stride (6x encoder * 2x projector = 12x)
|
| 596 |
-
self.k = getattr(config, "projector_pool_stride", 6)
|
| 597 |
-
|
| 598 |
-
encoder_dim = config.encoder_dim
|
| 599 |
-
llm_dim = config.llm_dim
|
| 600 |
-
|
| 601 |
-
# Input: Stacked frames (e.g. 1280 * 2 = 2560)
|
| 602 |
-
in_dim = encoder_dim * self.k
|
| 603 |
-
|
| 604 |
-
# FFN hidden dim for initial projection (balanced compression)
|
| 605 |
-
# 7680 → 4096 → 2048 distributes compression evenly (~2x each layer)
|
| 606 |
-
ffn_dim = getattr(config, "projector_hidden_dim", None) or 4096
|
| 607 |
-
|
| 608 |
-
# FunASR-style projection: linear1 -> relu -> linear2
|
| 609 |
-
self.linear1 = nn.Linear(in_dim, ffn_dim)
|
| 610 |
-
self.relu = nn.ReLU()
|
| 611 |
-
self.linear2 = nn.Linear(ffn_dim, llm_dim)
|
| 612 |
-
|
| 613 |
-
# Transformer blocks operating at llm_dim
|
| 614 |
-
num_layers = getattr(config, "projector_num_layers", 2)
|
| 615 |
-
if num_layers > 0:
|
| 616 |
-
encoder_layer = nn.TransformerEncoderLayer(
|
| 617 |
-
d_model=llm_dim,
|
| 618 |
-
nhead=getattr(config, "projector_num_heads", 8),
|
| 619 |
-
dim_feedforward=1024, # Match FunASR (audio complexity is LLM-independent)
|
| 620 |
-
dropout=0.0,
|
| 621 |
-
activation="relu",
|
| 622 |
-
batch_first=True,
|
| 623 |
-
norm_first=True,
|
| 624 |
-
)
|
| 625 |
-
self.blocks = nn.TransformerEncoder(
|
| 626 |
-
encoder_layer, num_layers=num_layers, enable_nested_tensor=False
|
| 627 |
-
)
|
| 628 |
-
else:
|
| 629 |
-
self.blocks = None
|
| 630 |
-
|
| 631 |
-
def forward(self, x):
|
| 632 |
-
# x: [Batch, Seq, Dim]
|
| 633 |
-
batch, seq, dim = x.shape
|
| 634 |
-
|
| 635 |
-
# Padding to multiple of k
|
| 636 |
-
chunk_num = (seq - 1) // self.k + 1
|
| 637 |
-
pad_num = chunk_num * self.k - seq
|
| 638 |
-
if pad_num > 0:
|
| 639 |
-
x = F.pad(x, (0, 0, 0, pad_num))
|
| 640 |
-
|
| 641 |
-
# Frame stacking: [B, S, D] -> [B, S/k, D*k]
|
| 642 |
-
x = x.contiguous().view(batch, chunk_num, dim * self.k)
|
| 643 |
-
|
| 644 |
-
# FunASR-style projection to LLM dim
|
| 645 |
-
x = self.linear1(x)
|
| 646 |
-
x = self.relu(x)
|
| 647 |
-
x = self.linear2(x)
|
| 648 |
-
|
| 649 |
-
# Transformer context mixing
|
| 650 |
-
if self.blocks is not None:
|
| 651 |
-
x = self.blocks(x)
|
| 652 |
-
|
| 653 |
-
return x
|
| 654 |
-
|
| 655 |
-
def get_output_length(self, input_length: int) -> int:
|
| 656 |
-
return (input_length - 1) // self.k + 1
|
| 657 |
-
|
| 658 |
-
|
| 659 |
# =============================================================================
|
| 660 |
# Projector Registry
|
| 661 |
# =============================================================================
|
|
@@ -666,5 +591,4 @@ PROJECTOR_CLASSES = {
|
|
| 666 |
"swiglu": SwiGLUAudioProjector,
|
| 667 |
"shared_moe": SharedMoEAudioProjector,
|
| 668 |
"qformer": QFormerAudioProjector,
|
| 669 |
-
"transformer": TransformerAudioProjector,
|
| 670 |
}
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
class MLPAudioProjector(nn.Module):
|
| 26 |
+
"""2-layer MLP projector with optional conv-based 2x temporal downsampling.
|
| 27 |
+
|
| 28 |
+
When projector_downsample=True (default): Uses Conv1d stride-2 for 2x downsampling.
|
| 29 |
+
When projector_downsample=False: No downsampling, just MLP projection (like GLM-ASR).
|
| 30 |
+
"""
|
| 31 |
|
| 32 |
def __init__(self, config):
|
| 33 |
super().__init__()
|
| 34 |
|
| 35 |
encoder_dim = getattr(config, "encoder_dim", 768)
|
| 36 |
llm_dim = getattr(config, "llm_dim", 2048)
|
| 37 |
+
self.use_downsample = getattr(config, "projector_downsample", True)
|
| 38 |
+
|
| 39 |
+
if self.use_downsample:
|
| 40 |
+
self.downsample = nn.Conv1d(
|
| 41 |
+
encoder_dim, encoder_dim, kernel_size=3, stride=2, padding=1, bias=False
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
self.downsample = None
|
| 45 |
|
|
|
|
|
|
|
|
|
|
| 46 |
self.linear_1 = nn.Linear(encoder_dim, llm_dim, bias=False)
|
| 47 |
self.act = nn.GELU()
|
| 48 |
self.linear_2 = nn.Linear(llm_dim, llm_dim, bias=False)
|
| 49 |
+
# Using PyTorch default initialization (like GLM-ASR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
def get_output_length(self, input_length: int) -> int:
|
| 52 |
"""Calculate output sequence length given input length."""
|
| 53 |
+
if self.use_downsample:
|
| 54 |
+
# Conv stride=2 halves the length (with padding=1, kernel=3)
|
| 55 |
+
return (input_length + 1) // 2
|
| 56 |
+
return input_length
|
| 57 |
|
| 58 |
def forward(self, x):
|
| 59 |
"""
|
| 60 |
x: [Batch, Seq_Len, Dim]
|
| 61 |
+
Returns: [Batch, Seq_Len // 2, llm_dim] if downsampling, else [Batch, Seq_Len, llm_dim]
|
| 62 |
"""
|
| 63 |
+
if self.downsample is not None:
|
| 64 |
+
# Conv1d expects [Batch, Channels, Seq_Len]
|
| 65 |
+
x = x.transpose(1, 2)
|
| 66 |
+
x = self.downsample(x)
|
| 67 |
+
x = x.transpose(1, 2)
|
| 68 |
|
| 69 |
x = self.linear_1(x)
|
| 70 |
x = self.act(x)
|
|
|
|
| 581 |
return self.linear(query_proj)
|
| 582 |
|
| 583 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
# =============================================================================
|
| 585 |
# Projector Registry
|
| 586 |
# =============================================================================
|
|
|
|
| 591 |
"swiglu": SwiGLUAudioProjector,
|
| 592 |
"shared_moe": SharedMoEAudioProjector,
|
| 593 |
"qformer": QFormerAudioProjector,
|
|
|
|
| 594 |
}
|
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
|