mazesmazes commited on
Commit
32f4ac1
·
verified ·
1 Parent(s): 2f24ce4

Training in progress - step 5000

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
asr_config.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import transformers
4
+
5
+
6
+ class ASRConfig(transformers.PretrainedConfig):
7
+ """Configuration class for the ASR model.
8
+
9
+ This config combines settings for:
10
+ - Audio encoder (GLM-ASR/Whisper)
11
+ - Text decoder (Qwen)
12
+ - Projector (MLP, MOSA, MoE, QFormer)
13
+ - Generation parameters
14
+ - Training options (SpecAugment, LoRA)
15
+ """
16
+
17
+ model_type = "asr_model"
18
+ is_composition = True
19
+
20
+ def __init__(
21
+ self,
22
+ audio_model_id: str = "zai-org/GLM-ASR-Nano-2512",
23
+ text_model_id: str = "Qwen/Qwen3-0.6B",
24
+ attn_implementation: str = "flash_attention_2",
25
+ model_dtype: str = "bfloat16",
26
+ num_beams: Optional[int] = None,
27
+ system_prompt: str = "You are a helpful assistant.",
28
+ encoder_dim: Optional[int] = None,
29
+ llm_dim: Optional[int] = None,
30
+ # Encoder conv layers: list of (padding, kernel_size, stride) tuples
31
+ # Default is Whisper/GLM-ASR structure: conv1(k=3,s=1,p=1) + conv2(k=3,s=2,p=1)
32
+ encoder_conv_layers: Optional[list] = None,
33
+ audio_sample_rate: int = 16000,
34
+ projector_pool_stride: int = 4,
35
+ downsample_rate: int = 5, # Granite default
36
+ projector_hidden_dim: Optional[int] = None,
37
+ projector_type: str = "mlp", # "mlp", "mosa", "moe", "qformer"
38
+ projector_num_layers: int = 2, # Number of layers in MLP projector
39
+ projector_init_std: float = 0.02, # Weight initialization std
40
+ projector_dropout: float = 0.0, # Dropout rate for projector layers
41
+ # MoE-specific configuration
42
+ num_experts: int = 4, # Number of experts in MoE projectors
43
+ num_experts_per_tok: int = 2, # Top-k experts per token
44
+ router_aux_loss_coef: float = 0.01, # Auxiliary loss coefficient for load balancing
45
+ # QFormer-specific configuration (Granite defaults)
46
+ qformer_window_size: int = 15, # Window size for QFormer processing
47
+ qformer_hidden_size: Optional[int] = None, # QFormer hidden size (defaults to encoder_dim)
48
+ qformer_num_layers: int = 2, # Number of QFormer transformer layers
49
+ qformer_num_heads: int = 16, # Number of attention heads in QFormer
50
+ qformer_intermediate_size: Optional[int] = None, # FFN size (defaults to 4x hidden)
51
+ label_smoothing: float = 0.0, # Label smoothing for cross-entropy loss
52
+ inference_warmup_tokens: int = 10,
53
+ # SpecAugment settings
54
+ use_specaugment: bool = False,
55
+ num_time_masks: int = 2,
56
+ time_mask_length: int = 10,
57
+ num_freq_masks: int = 0,
58
+ freq_mask_length: int = 10,
59
+ # LoRA configuration (for Stage 2 fine-tuning)
60
+ use_lora: bool = False,
61
+ lora_rank: int = 8, # SALMONN default
62
+ lora_alpha: int = 32, # SALMONN default (scaling factor 4.0)
63
+ lora_dropout: float = 0.0,
64
+ lora_target_modules: Optional[list] = None, # Default: all linear layers
65
+ freeze_projector: bool = False, # True for Stage 2 (LoRA-only training)
66
+ max_new_tokens: Optional[int] = None,
67
+ min_new_tokens: Optional[int] = None,
68
+ repetition_penalty: Optional[float] = None,
69
+ length_penalty: Optional[float] = None,
70
+ no_repeat_ngram_size: Optional[int] = None,
71
+ use_cache: Optional[bool] = None,
72
+ **kwargs,
73
+ ):
74
+ """Initialize ASR model configuration.
75
+
76
+ Args:
77
+ audio_model_id: HuggingFace model ID for audio encoder (GLM-ASR/Whisper)
78
+ text_model_id: HuggingFace model ID for text decoder (Qwen)
79
+ attn_implementation: Attention implementation ("flash_attention_2", "sdpa", "eager")
80
+ model_dtype: Model dtype ("bfloat16", "float16", "float32")
81
+ projector_type: Projector architecture ("mlp", "mosa", "moe", "qformer")
82
+ use_lora: Enable LoRA adapters for Stage 2 fine-tuning
83
+ use_specaugment: Enable SpecAugment data augmentation
84
+ """
85
+ # Set default generation parameters (greedy decoding only)
86
+ generation_defaults = {
87
+ "num_beams": 1,
88
+ "max_new_tokens": 128,
89
+ "min_new_tokens": 0,
90
+ "repetition_penalty": 1.0,
91
+ "length_penalty": 1.0,
92
+ "no_repeat_ngram_size": 0, # Prevent repeating 3-grams like "so so so"
93
+ "use_cache": True,
94
+ }
95
+
96
+ # Apply defaults (config.json values take precedence)
97
+ kwargs = {**generation_defaults, **kwargs}
98
+
99
+ self.audio_model_id = audio_model_id
100
+ self.text_model_id = text_model_id
101
+ self.attn_implementation = attn_implementation
102
+ self.model_dtype = model_dtype
103
+ self.system_prompt = system_prompt
104
+ self.encoder_dim = encoder_dim
105
+ self.llm_dim = llm_dim
106
+ # Default conv layers for Whisper/GLM-ASR: [(pad, kernel, stride), ...]
107
+ self.encoder_conv_layers = encoder_conv_layers or [(1, 3, 1), (1, 3, 2)]
108
+ self.audio_sample_rate = audio_sample_rate
109
+ self.projector_init_std = projector_init_std
110
+ self.projector_pool_stride = projector_pool_stride
111
+ self.downsample_rate = downsample_rate
112
+ self.projector_hidden_dim = projector_hidden_dim
113
+ self.projector_type = projector_type
114
+ self.projector_num_layers = projector_num_layers
115
+ self.projector_dropout = projector_dropout
116
+ # MoE-specific configuration
117
+ self.num_experts = num_experts
118
+ self.num_experts_per_tok = num_experts_per_tok
119
+ self.router_aux_loss_coef = router_aux_loss_coef
120
+ # QFormer-specific configuration
121
+ self.qformer_window_size = qformer_window_size
122
+ self.qformer_hidden_size = qformer_hidden_size
123
+ self.qformer_num_layers = qformer_num_layers
124
+ self.qformer_num_heads = qformer_num_heads
125
+ self.qformer_intermediate_size = qformer_intermediate_size
126
+ self.label_smoothing = label_smoothing
127
+ self.inference_warmup_tokens = inference_warmup_tokens
128
+ # SpecAugment configuration
129
+ self.use_specaugment = use_specaugment
130
+ self.num_time_masks = num_time_masks
131
+ self.time_mask_length = time_mask_length
132
+ self.num_freq_masks = num_freq_masks
133
+ self.freq_mask_length = freq_mask_length
134
+ # LoRA configuration
135
+ self.use_lora = use_lora
136
+ self.lora_rank = lora_rank
137
+ self.lora_alpha = lora_alpha
138
+ self.lora_dropout = lora_dropout
139
+ self.lora_target_modules = lora_target_modules or [
140
+ "q_proj",
141
+ "k_proj",
142
+ "v_proj",
143
+ "o_proj",
144
+ "gate_proj",
145
+ "up_proj",
146
+ "down_proj",
147
+ ]
148
+ self.freeze_projector = freeze_projector
149
+
150
+ # Generation parameters (use explicit value if provided, else use default)
151
+ self.num_beams = num_beams if num_beams is not None else generation_defaults["num_beams"]
152
+ self.max_new_tokens = (
153
+ max_new_tokens if max_new_tokens is not None else generation_defaults["max_new_tokens"]
154
+ )
155
+ self.min_new_tokens = (
156
+ min_new_tokens if min_new_tokens is not None else generation_defaults["min_new_tokens"]
157
+ )
158
+ self.repetition_penalty = (
159
+ repetition_penalty
160
+ if repetition_penalty is not None
161
+ else generation_defaults["repetition_penalty"]
162
+ )
163
+ self.length_penalty = (
164
+ length_penalty if length_penalty is not None else generation_defaults["length_penalty"]
165
+ )
166
+ self.no_repeat_ngram_size = (
167
+ no_repeat_ngram_size
168
+ if no_repeat_ngram_size is not None
169
+ else generation_defaults["no_repeat_ngram_size"]
170
+ )
171
+ self.use_cache = use_cache if use_cache is not None else generation_defaults["use_cache"]
172
+
173
+ if "audio_config" not in kwargs:
174
+ self.audio_config = transformers.AutoConfig.from_pretrained(audio_model_id)
175
+ # Override dtype to match model_dtype
176
+ self.audio_config.dtype = model_dtype
177
+ else:
178
+ self.audio_config = kwargs.pop("audio_config")
179
+
180
+ if "text_config" not in kwargs:
181
+ self.text_config = transformers.AutoConfig.from_pretrained(
182
+ text_model_id, trust_remote_code=True
183
+ )
184
+ # Override dtype to match model_dtype
185
+ self.text_config.dtype = model_dtype
186
+ else:
187
+ self.text_config = kwargs.pop("text_config")
188
+
189
+ if isinstance(self.text_config, dict):
190
+ # Reconstruct config from dict using the model_type stored in the dict
191
+ model_type = self.text_config["model_type"]
192
+ config_class = transformers.AutoConfig.for_model(model_type).__class__
193
+ self.text_config = config_class(**self.text_config)
194
+
195
+ if isinstance(self.audio_config, dict):
196
+ model_type = self.audio_config.get("model_type")
197
+ if model_type:
198
+ config_class = transformers.AutoConfig.for_model(model_type).__class__
199
+ self.audio_config = config_class(**self.audio_config)
200
+
201
+ super().__init__(**kwargs)
202
+
203
+ # Point encoder to audio_config so pipeline uses correct feature extractor
204
+ # The pipeline looks for config.encoder._name_or_path for feature extractor
205
+ self.encoder = self.audio_config
206
+
207
+ self.auto_map = {
208
+ "AutoConfig": "asr_config.ASRConfig",
209
+ "AutoModel": "asr_modeling.ASRModel",
210
+ "AutoModelForSpeechSeq2Seq": "asr_modeling.ASRModel",
211
+ "AutoProcessor": "asr_processing.ASRProcessor",
212
+ }
213
+ self.custom_pipelines = {
214
+ "automatic-speech-recognition": {
215
+ "impl": "asr_pipeline.ASRPipeline",
216
+ "pt": ["AutoModelForSpeechSeq2Seq"],
217
+ "tf": [],
218
+ "type": "audio",
219
+ }
220
+ }
221
+ self.architectures = ["ASRModel"]
222
+ self.pipeline_tag = "automatic-speech-recognition"
223
+
224
+
225
+ transformers.AutoConfig.register("asr_model", ASRConfig)
asr_modeling.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from threading import Thread
4
+ from typing import Iterator, Optional, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from transformers import (
9
+ AutoConfig,
10
+ AutoModel,
11
+ AutoModelForCausalLM,
12
+ AutoTokenizer,
13
+ PreTrainedModel,
14
+ TextIteratorStreamer,
15
+ )
16
+ from transformers.generation import GenerationMixin
17
+ from transformers.modeling_outputs import CausalLMOutputWithPast
18
+
19
+ try:
20
+ from .asr_config import ASRConfig
21
+ from .projectors import PROJECTOR_CLASSES
22
+ except ImportError:
23
+ from asr_config import ASRConfig # type: ignore[no-redef]
24
+ from projectors import PROJECTOR_CLASSES # type: ignore[no-redef]
25
+
26
+
27
+ from torchaudio.transforms import SpecAugment
28
+
29
+
30
+ class ASRModel(PreTrainedModel, GenerationMixin):
31
+ """Audio-to-text model combining an audio encoder, projector, and language model."""
32
+
33
+ config_class = ASRConfig
34
+ base_model_prefix = "model"
35
+ main_input_name = "input_features"
36
+ _supports_flash_attn_2 = True
37
+ supports_gradient_checkpointing = True
38
+ _is_loading_from_pretrained: bool = False
39
+ _pretrained_model_path: Optional[str] = None
40
+
41
+ TRANSCRIBE_PROMPT = "Transcribe speech to text" # Audio tokens come BEFORE this
42
+
43
+ @classmethod
44
+ def from_pretrained(cls, pretrained_model_name_or_path: str, *args, **kwargs) -> "ASRModel":
45
+ """Load model from pretrained, handling device placement correctly."""
46
+ from safetensors.torch import load_file
47
+ from transformers.utils.hub import cached_file
48
+
49
+ config = kwargs.pop("config", None)
50
+ if config is None:
51
+ config = ASRConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
52
+
53
+ # Set flag to avoid device_map="auto" in sub-model loaders
54
+ cls._is_loading_from_pretrained = True
55
+ cls._pretrained_model_path = pretrained_model_name_or_path
56
+
57
+ try:
58
+ model = cls(config, **kwargs)
59
+
60
+ # Load projector weights from safetensors
61
+ subfolder = kwargs.get("subfolder")
62
+ revision = kwargs.get("revision")
63
+ cache_kwargs = {}
64
+ if subfolder:
65
+ cache_kwargs["subfolder"] = subfolder
66
+ if revision:
67
+ cache_kwargs["revision"] = revision
68
+
69
+ model_file = cached_file(
70
+ pretrained_model_name_or_path,
71
+ "model.safetensors",
72
+ _raise_exceptions_for_missing_entries=False,
73
+ **cache_kwargs,
74
+ )
75
+
76
+ if model_file is not None:
77
+ state_dict = load_file(model_file)
78
+ model.load_state_dict(state_dict, strict=False)
79
+
80
+ # Load LoRA adapters if use_lora is enabled
81
+ if getattr(config, "use_lora", False):
82
+ # Check for adapter_config.json (required by PEFT to load adapters)
83
+ adapter_config_file = cached_file(
84
+ pretrained_model_name_or_path,
85
+ "adapter_config.json",
86
+ _raise_exceptions_for_missing_entries=False,
87
+ **cache_kwargs,
88
+ )
89
+ if adapter_config_file is not None:
90
+ # Load saved adapter weights using the original repo_id/path
91
+ # PEFT handles Hub downloads and caching internally
92
+ from peft import PeftModel
93
+
94
+ model.language_model = PeftModel.from_pretrained(
95
+ model.language_model,
96
+ pretrained_model_name_or_path,
97
+ is_trainable=True,
98
+ **cache_kwargs,
99
+ )
100
+ else:
101
+ # No saved adapters - initialize fresh LLM LoRA for training
102
+ from peft import LoraConfig, get_peft_model
103
+
104
+ lora_config = LoraConfig(
105
+ r=config.lora_rank,
106
+ lora_alpha=config.lora_alpha,
107
+ target_modules=config.lora_target_modules,
108
+ lora_dropout=config.lora_dropout,
109
+ bias="none",
110
+ task_type="CAUSAL_LM",
111
+ )
112
+ model.language_model = get_peft_model(model.language_model, lora_config)
113
+
114
+ return model
115
+ finally:
116
+ cls._is_loading_from_pretrained = False
117
+ cls._pretrained_model_path = None
118
+
119
+ def __init__(self, config: ASRConfig, **kwargs) -> None:
120
+ super().__init__(config)
121
+
122
+ self.system_prompt = config.system_prompt
123
+ target_dtype = getattr(torch, config.model_dtype)
124
+
125
+ # Audio encoder (frozen)
126
+ self.audio_tower = self._load_audio_encoder(config, target_dtype)
127
+
128
+ # Language model (frozen)
129
+ self.language_model = self._load_language_model(config, target_dtype)
130
+
131
+ # Initialize tokenizer and special tokens
132
+ self._init_tokenizer(config)
133
+
134
+ # Set up generation config with greedy decoding defaults
135
+ self.generation_config = self.language_model.generation_config
136
+ self.generation_config.max_new_tokens = config.max_new_tokens
137
+ self.generation_config.min_new_tokens = config.min_new_tokens
138
+ self.generation_config.num_beams = config.num_beams
139
+ self.generation_config.do_sample = False
140
+ # Clear sampling params (inherited from LLM) since we use greedy decoding
141
+ self.generation_config.temperature = None
142
+ self.generation_config.top_p = None
143
+ self.generation_config.top_k = None
144
+ self.generation_config.use_cache = config.use_cache
145
+ self.generation_config.length_penalty = config.length_penalty
146
+ self.generation_config.repetition_penalty = config.repetition_penalty
147
+ self.generation_config.no_repeat_ngram_size = config.no_repeat_ngram_size
148
+ self.generation_config.eos_token_id = [
149
+ self.tokenizer.convert_tokens_to_ids("<|im_end|>"),
150
+ self.tokenizer.convert_tokens_to_ids("<|endoftext|>"),
151
+ ]
152
+ self.generation_config.pad_token_id = self.tokenizer.pad_token_id
153
+
154
+ # Feature extractor for audio preprocessing
155
+ self.feature_extractor = self._create_feature_extractor(config)
156
+
157
+ # Audio projector (trainable unless freeze_projector is set)
158
+ self.projector = self._create_projector(config, target_dtype)
159
+
160
+ # Setup LoRA if enabled (Stage 2 fine-tuning)
161
+ # Skip if loading from pretrained - from_pretrained will handle adapter loading
162
+ if getattr(config, "use_lora", False) and not getattr(
163
+ self.__class__, "_is_loading_from_pretrained", False
164
+ ):
165
+ self._setup_lora(config)
166
+
167
+ # Freeze projector if specified (for Stage 2 LoRA-only training)
168
+ if getattr(config, "freeze_projector", False):
169
+ self.projector.requires_grad_(False)
170
+
171
+ # SpecAugment for data augmentation during training
172
+ if getattr(config, "use_specaugment", False):
173
+ self.spec_augment = SpecAugment(
174
+ n_time_masks=config.num_time_masks,
175
+ time_mask_param=config.time_mask_length,
176
+ n_freq_masks=config.num_freq_masks,
177
+ freq_mask_param=config.freq_mask_length,
178
+ )
179
+ else:
180
+ self.spec_augment = None
181
+
182
+ # For model parallelism
183
+ self._no_split_modules = getattr(self.language_model, "_no_split_modules", [])
184
+
185
+ def _create_feature_extractor(self, config: ASRConfig):
186
+ """Create the appropriate feature extractor for the audio encoder."""
187
+ from transformers import AutoFeatureExtractor
188
+
189
+ feature_extractor = AutoFeatureExtractor.from_pretrained(config.audio_model_id)
190
+ # Disable padding by default - use actual audio length
191
+ feature_extractor.padding = False
192
+ return feature_extractor
193
+
194
+ @classmethod
195
+ def _load_audio_encoder(cls, config: ASRConfig, dtype: torch.dtype) -> nn.Module:
196
+ """Load and freeze the audio encoder."""
197
+ encoder_kwargs = {
198
+ "attn_implementation": config.attn_implementation,
199
+ "low_cpu_mem_usage": True,
200
+ "dtype": dtype,
201
+ }
202
+
203
+ if "whisper" in config.audio_model_id.lower():
204
+ from transformers import WhisperModel
205
+
206
+ full_model = WhisperModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
207
+ encoder = full_model.encoder
208
+ del full_model
209
+ elif "glm" in config.audio_model_id.lower():
210
+ # GLM-ASR models use audio_tower as the encoder
211
+ # Requires transformers >= 5.x or installed from source
212
+ from transformers import AutoModelForSeq2SeqLM
213
+
214
+ full_model = AutoModelForSeq2SeqLM.from_pretrained(
215
+ config.audio_model_id, trust_remote_code=True, **encoder_kwargs
216
+ )
217
+ # GLM stores encoder at audio_tower (GlmAsrEncoder)
218
+ encoder = full_model.audio_tower
219
+ # Clear references to free VRAM from the LLM decoder
220
+ full_model.language_model = None
221
+ full_model.multi_modal_projector = None
222
+ del full_model
223
+ else:
224
+ encoder = AutoModel.from_pretrained(config.audio_model_id, **encoder_kwargs)
225
+
226
+ encoder.requires_grad_(False)
227
+ encoder.eval()
228
+ return encoder
229
+
230
+ @classmethod
231
+ def _load_language_model(cls, config: ASRConfig, dtype: torch.dtype) -> PreTrainedModel:
232
+ """Load and freeze the language model."""
233
+ decoder_kwargs = {
234
+ "attn_implementation": config.attn_implementation,
235
+ "trust_remote_code": True,
236
+ "tie_word_embeddings": False,
237
+ "low_cpu_mem_usage": True,
238
+ "dtype": dtype,
239
+ }
240
+
241
+ decoder = AutoModelForCausalLM.from_pretrained(config.text_model_id, **decoder_kwargs)
242
+ decoder.config.use_cache = getattr(config, "use_cache", True)
243
+ decoder.requires_grad_(False)
244
+ decoder.eval()
245
+ return decoder
246
+
247
+ def _create_projector(self, config: ASRConfig, dtype: torch.dtype) -> nn.Module:
248
+ """Create the trainable audio projector."""
249
+ # Auto-detect dimensions if not specified
250
+ if config.encoder_dim is None:
251
+ enc_cfg = self.audio_tower.config
252
+ config.encoder_dim = getattr(enc_cfg, "hidden_size", None) or getattr(
253
+ enc_cfg, "d_model", None
254
+ )
255
+ if config.encoder_dim is None:
256
+ raise ValueError("Could not auto-detect encoder_dim. Please specify in config.")
257
+
258
+ if config.llm_dim is None:
259
+ dec_cfg = self.language_model.config
260
+ config.llm_dim = getattr(dec_cfg, "hidden_size", None) or getattr(
261
+ dec_cfg, "d_model", None
262
+ )
263
+ if config.llm_dim is None:
264
+ raise ValueError("Could not auto-detect llm_dim. Please specify in config.")
265
+
266
+ # Select projector type based on config
267
+ projector_type = getattr(config, "projector_type", "mlp")
268
+ projector_class = PROJECTOR_CLASSES.get(projector_type)
269
+ if projector_class is None:
270
+ raise ValueError(
271
+ f"Unknown projector_type: {projector_type}. "
272
+ f"Valid options: {list(PROJECTOR_CLASSES.keys())}"
273
+ )
274
+ projector = projector_class(config)
275
+
276
+ # Move projector to same device as language model (important when using quantization)
277
+ device = next(self.language_model.parameters()).device
278
+ return projector.to(device=device, dtype=dtype)
279
+
280
+ def _setup_lora(self, config: ASRConfig):
281
+ """Apply LoRA adapters to the language model for Stage 2 fine-tuning."""
282
+ from peft import LoraConfig, get_peft_model
283
+
284
+ lora_config = LoraConfig(
285
+ r=config.lora_rank,
286
+ lora_alpha=config.lora_alpha,
287
+ target_modules=config.lora_target_modules,
288
+ lora_dropout=config.lora_dropout,
289
+ bias="none",
290
+ task_type="CAUSAL_LM",
291
+ )
292
+ self.language_model = get_peft_model(self.language_model, lora_config)
293
+
294
+ def _init_tokenizer(self, config: ASRConfig):
295
+ """Initialize tokenizer with audio token."""
296
+ self.tokenizer = AutoTokenizer.from_pretrained(config.text_model_id, trust_remote_code=True)
297
+
298
+ # Set pad token
299
+ if (
300
+ self.tokenizer.pad_token is None
301
+ or self.tokenizer.pad_token_id == self.tokenizer.eos_token_id
302
+ ) and "<|finetune_right_pad_id|>" in self.tokenizer.get_vocab():
303
+ self.tokenizer.pad_token = "<|finetune_right_pad_id|>"
304
+
305
+ # Add audio token
306
+ existing_special = getattr(self.tokenizer, "additional_special_tokens", None) or []
307
+ if "<audio>" not in existing_special:
308
+ self.tokenizer.add_special_tokens(
309
+ {"additional_special_tokens": existing_special + ["<audio>"]}
310
+ )
311
+ self.language_model.resize_token_embeddings(len(self.tokenizer), mean_resizing=False)
312
+
313
+ self.audio_token_id = self.tokenizer.convert_tokens_to_ids("<audio>")
314
+ self.tokenizer.padding_side = "right"
315
+
316
+ # Sync token IDs to configs
317
+ for cfg in [self.config.text_config, self.language_model.config, self.generation_config]:
318
+ if cfg is not None:
319
+ cfg.pad_token_id = self.tokenizer.pad_token_id
320
+ cfg.eos_token_id = self.tokenizer.eos_token_id
321
+ cfg.bos_token_id = self.tokenizer.bos_token_id
322
+
323
+ def _init_weights(self, _module):
324
+ """Weight initialization (projector weights are initialized in MoEAudioProjector)."""
325
+ pass
326
+
327
+ def _set_gradient_checkpointing(self, enable: bool = True, gradient_checkpointing_func=None):
328
+ """Enable/disable gradient checkpointing for the language model."""
329
+ # The LLM still stores activations during forward for backprop to projector
330
+ # Gradient checkpointing trades compute for memory by recomputing activations
331
+ if hasattr(self.language_model, "_set_gradient_checkpointing"):
332
+ self.language_model._set_gradient_checkpointing(enable, gradient_checkpointing_func)
333
+ elif hasattr(self.language_model, "gradient_checkpointing_enable") and enable:
334
+ self.language_model.gradient_checkpointing_enable(
335
+ gradient_checkpointing_kwargs={"use_reentrant": False}
336
+ )
337
+ elif hasattr(self.language_model, "gradient_checkpointing_disable") and not enable:
338
+ self.language_model.gradient_checkpointing_disable()
339
+
340
+ def get_input_embeddings(self) -> nn.Module:
341
+ return self.language_model.get_input_embeddings()
342
+
343
+ def set_input_embeddings(self, value: nn.Module) -> None:
344
+ self.language_model.set_input_embeddings(value)
345
+
346
+ def get_output_embeddings(self) -> nn.Module:
347
+ return self.language_model.get_output_embeddings()
348
+
349
+ def set_output_embeddings(self, value: nn.Module) -> None:
350
+ self.language_model.set_output_embeddings(value)
351
+
352
+ def get_processor(self):
353
+ """Get the processor for this model."""
354
+ try:
355
+ from .asr_processing import ASRProcessor
356
+ except ImportError:
357
+ from asr_processing import ASRProcessor # type: ignore[no-redef]
358
+
359
+ return ASRProcessor(
360
+ feature_extractor=self.feature_extractor,
361
+ tokenizer=self.tokenizer,
362
+ projector=self.projector,
363
+ encoder_conv_layers=self.config.encoder_conv_layers,
364
+ )
365
+
366
+ def state_dict(self, *args, **kwargs) -> dict[str, torch.Tensor]:
367
+ """Only save trainable projector weights."""
368
+ return {f"projector.{k}": v for k, v in self.projector.state_dict().items()}
369
+
370
+ def _compute_encoder_output_lengths(
371
+ self,
372
+ audio_attention_mask: torch.Tensor,
373
+ ) -> torch.Tensor:
374
+ """Compute per-sample encoder output lengths using conv layer formulas.
375
+
376
+ Args:
377
+ audio_attention_mask: Mask indicating real vs padded mel frames (batch, mel_len)
378
+
379
+ Returns:
380
+ Tensor of encoder output lengths per sample (batch,)
381
+ """
382
+ # Get mel frame lengths from attention mask
383
+ lengths = audio_attention_mask.sum(dim=-1)
384
+
385
+ # Apply conv layer formulas: output = (input + 2*pad - (kernel-1) - 1) // stride + 1
386
+ for padding, kernel_size, stride in self.config.encoder_conv_layers:
387
+ lengths = (lengths + 2 * padding - (kernel_size - 1) - 1) // stride + 1
388
+
389
+ return lengths
390
+
391
+ def _encode_audio(
392
+ self,
393
+ audio_features: torch.Tensor,
394
+ audio_attention_mask: torch.Tensor,
395
+ ) -> torch.Tensor:
396
+ """Encode audio and project to LLM embedding space.
397
+
398
+ Args:
399
+ audio_features: Mel spectrogram features (batch, n_mels, mel_len)
400
+ audio_attention_mask: Mask indicating real vs padded mel frames (batch, mel_len)
401
+
402
+ Returns:
403
+ Flattened audio embeddings of shape (total_audio_tokens, hidden_dim).
404
+ """
405
+ with torch.no_grad():
406
+ encoder_out = self.audio_tower(input_features=audio_features)
407
+ hidden_states = encoder_out.last_hidden_state
408
+
409
+ # Compute per-sample encoder output lengths using conv formulas
410
+ encoder_lengths = self._compute_encoder_output_lengths(audio_attention_mask)
411
+
412
+ # Project to LLM space
413
+ audio_embeds = self.projector(hidden_states)
414
+
415
+ # Compute per-sample projector output lengths
416
+ projector_lengths = torch.tensor(
417
+ [self.projector.get_output_length(int(length.item())) for length in encoder_lengths],
418
+ device=audio_embeds.device,
419
+ )
420
+
421
+ # Create valid mask for variable-length samples and extract only real embeddings
422
+ max_len = audio_embeds.shape[1]
423
+ valid_mask = (
424
+ torch.arange(max_len, device=audio_embeds.device)[None, :] < projector_lengths[:, None]
425
+ )
426
+ return audio_embeds[valid_mask]
427
+
428
+ def forward(
429
+ self,
430
+ input_ids: Optional[torch.Tensor] = None,
431
+ input_features: Optional[torch.Tensor] = None,
432
+ audio_attention_mask: Optional[torch.Tensor] = None,
433
+ attention_mask: Optional[torch.Tensor] = None,
434
+ position_ids: Optional[torch.Tensor] = None,
435
+ past_key_values: Optional[torch.Tensor] = None,
436
+ inputs_embeds: Optional[torch.Tensor] = None,
437
+ labels: Optional[torch.Tensor] = None,
438
+ use_cache: Optional[bool] = None,
439
+ cache_position: Optional[torch.Tensor] = None,
440
+ **kwargs,
441
+ ) -> CausalLMOutputWithPast:
442
+ """Forward pass for training and inference."""
443
+ # Get text embeddings if not provided
444
+ if inputs_embeds is None:
445
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
446
+
447
+ if input_features is not None and input_ids is not None:
448
+ # Apply SpecAugment during training if enabled
449
+ if self.training and self.spec_augment is not None:
450
+ input_features = self.spec_augment(input_features)
451
+
452
+ # Encode audio -> flattened (total_audio_tokens, hidden_dim)
453
+ audio_embeds = self._encode_audio(input_features, audio_attention_mask)
454
+
455
+ # Replace <audio> token placeholders with audio embeddings using masked_scatter
456
+ audio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)
457
+ inputs_embeds = inputs_embeds.masked_scatter(
458
+ audio_token_mask.to(inputs_embeds.device),
459
+ audio_embeds.to(inputs_embeds.device, dtype=inputs_embeds.dtype),
460
+ )
461
+
462
+ # Run through language model (let it compute loss if labels provided)
463
+ outputs = self.language_model(
464
+ attention_mask=attention_mask,
465
+ position_ids=position_ids,
466
+ past_key_values=past_key_values,
467
+ inputs_embeds=inputs_embeds,
468
+ labels=labels,
469
+ use_cache=use_cache,
470
+ cache_position=cache_position,
471
+ **kwargs,
472
+ )
473
+
474
+ # Add auxiliary loss from MoE projectors if available
475
+ if outputs.loss is not None and hasattr(self.projector, "get_aux_loss"):
476
+ aux_loss = self.projector.get_aux_loss()
477
+ if aux_loss is not None and aux_loss.numel() > 0:
478
+ outputs.loss = outputs.loss + aux_loss.to(outputs.loss.device)
479
+
480
+ return outputs
481
+
482
+ def prepare_inputs_for_generation(self, *args, **kwargs):
483
+ """Prepare inputs for generation, handling audio features for cached decoding."""
484
+ input_features = kwargs.pop("input_features", None)
485
+ cache_position = kwargs.get("cache_position")
486
+
487
+ model_inputs = self.language_model.prepare_inputs_for_generation(*args, **kwargs)
488
+
489
+ # Only pass audio features on the first generation step (cache_position[0] == 0)
490
+ if cache_position is not None and cache_position[0] == 0 and input_features is not None:
491
+ model_inputs["input_features"] = input_features
492
+
493
+ return model_inputs
494
+
495
+ def _get_num_audio_tokens(
496
+ self,
497
+ audio_attention_mask: torch.Tensor,
498
+ ) -> int:
499
+ """Calculate number of audio tokens based on actual audio length.
500
+
501
+ Uses attention mask to get real audio length, then computes:
502
+ mel_frames -> encoder_frames (via conv formulas) -> projector output tokens
503
+ """
504
+ encoder_lengths = self._compute_encoder_output_lengths(audio_attention_mask)
505
+ # Use max length for batch (all samples should have same token count for generation)
506
+ encoder_output_len = int(encoder_lengths.max().item())
507
+ return int(self.projector.get_output_length(encoder_output_len))
508
+
509
+ @torch.no_grad()
510
+ def generate(
511
+ self,
512
+ input_ids: Optional[torch.Tensor] = None,
513
+ input_features: Optional[torch.Tensor] = None,
514
+ audio_attention_mask: Optional[torch.Tensor] = None,
515
+ attention_mask: Optional[torch.Tensor] = None,
516
+ system_prompt: Optional[str] = None,
517
+ **generate_kwargs,
518
+ ) -> torch.Tensor:
519
+ """Generate transcription from audio input.
520
+
521
+ Can be called in two ways:
522
+ 1. With input_ids containing <audio> tokens (from processor)
523
+ 2. With just audio, and we build the prompt internally
524
+ """
525
+ if input_features is None:
526
+ raise ValueError("input_features required for generation")
527
+ if audio_attention_mask is None:
528
+ raise ValueError("audio_attention_mask required for generation")
529
+
530
+ device = input_features.device
531
+ batch_size = input_features.shape[0]
532
+
533
+ # Encode audio -> flattened embeddings
534
+ audio_embeds = self._encode_audio(input_features, audio_attention_mask)
535
+
536
+ # If input_ids not provided, build prompt with correct number of audio tokens
537
+ if input_ids is None:
538
+ num_audio_tokens = self._get_num_audio_tokens(audio_attention_mask)
539
+ audio_placeholder = "<audio>" * num_audio_tokens
540
+
541
+ system_prompt = system_prompt or self.system_prompt
542
+
543
+ messages: list[dict[str, str]] = []
544
+ if system_prompt:
545
+ messages.append({"role": "system", "content": system_prompt})
546
+ # Audio BEFORE prompt for proper causal attention
547
+ messages.append(
548
+ {"role": "user", "content": audio_placeholder + " " + self.TRANSCRIBE_PROMPT}
549
+ )
550
+
551
+ chat_result = self.tokenizer.apply_chat_template(
552
+ messages,
553
+ tokenize=True,
554
+ add_generation_prompt=True,
555
+ return_tensors="pt",
556
+ enable_thinking=False, # Disable Qwen3 thinking mode for ASR
557
+ )
558
+ input_ids = chat_result.input_ids.to(device)
559
+
560
+ if input_ids.dim() == 1:
561
+ input_ids = input_ids.unsqueeze(0)
562
+ if input_ids.shape[0] == 1 and batch_size > 1:
563
+ input_ids = input_ids.expand(batch_size, -1)
564
+
565
+ attention_mask = torch.ones_like(input_ids)
566
+
567
+ # Get text embeddings and replace audio tokens with audio embeddings
568
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
569
+ audio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)
570
+ inputs_embeds = inputs_embeds.masked_scatter(
571
+ audio_token_mask.to(inputs_embeds.device),
572
+ audio_embeds.to(inputs_embeds.device, dtype=inputs_embeds.dtype),
573
+ )
574
+
575
+ # Generate using language model
576
+ output = self.language_model.generate(
577
+ inputs_embeds=inputs_embeds,
578
+ attention_mask=attention_mask,
579
+ generation_config=self.generation_config,
580
+ **generate_kwargs,
581
+ )
582
+
583
+ # When using inputs_embeds without input_ids, generate returns only new tokens
584
+ if isinstance(output, torch.Tensor):
585
+ return output
586
+ return output.sequences
587
+
588
+ def generate_streaming(
589
+ self,
590
+ input_features: torch.Tensor,
591
+ audio_attention_mask: torch.Tensor,
592
+ system_prompt: Optional[str] = None,
593
+ **generate_kwargs,
594
+ ) -> Iterator[str]:
595
+ """Generate transcription with streaming token output.
596
+
597
+ Yields partial transcript strings as tokens are generated.
598
+ Reduces time-to-first-word by streaming tokens as they're decoded.
599
+
600
+ Args:
601
+ input_features: Mel spectrogram features (batch, n_mels, mel_len)
602
+ audio_attention_mask: Mask for real vs padded mel frames (batch, mel_len)
603
+ system_prompt: Optional system prompt override
604
+ **generate_kwargs: Additional generation arguments
605
+
606
+ Yields:
607
+ Partial transcript text as each token is generated
608
+ """
609
+ device = input_features.device
610
+ batch_size = input_features.shape[0]
611
+
612
+ # Encode audio -> flattened embeddings
613
+ audio_embeds = self._encode_audio(input_features, audio_attention_mask)
614
+
615
+ # Build prompt with correct number of audio tokens
616
+ num_audio_tokens = self._get_num_audio_tokens(audio_attention_mask)
617
+ audio_placeholder = "<audio>" * num_audio_tokens
618
+
619
+ system_prompt = system_prompt or self.system_prompt
620
+
621
+ messages: list[dict[str, str]] = []
622
+ if system_prompt:
623
+ messages.append({"role": "system", "content": system_prompt})
624
+ # Audio BEFORE prompt for proper causal attention
625
+ messages.append(
626
+ {"role": "user", "content": audio_placeholder + " " + self.TRANSCRIBE_PROMPT}
627
+ )
628
+
629
+ chat_result = self.tokenizer.apply_chat_template(
630
+ messages,
631
+ tokenize=True,
632
+ add_generation_prompt=True,
633
+ return_tensors="pt",
634
+ enable_thinking=False, # Disable Qwen3 thinking mode for ASR
635
+ )
636
+ input_ids = chat_result.input_ids.to(device)
637
+
638
+ if input_ids.dim() == 1:
639
+ input_ids = input_ids.unsqueeze(0)
640
+ if input_ids.shape[0] == 1 and batch_size > 1:
641
+ input_ids = input_ids.expand(batch_size, -1)
642
+
643
+ attention_mask = torch.ones_like(input_ids)
644
+
645
+ # Get text embeddings and replace audio tokens with audio embeddings
646
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
647
+ audio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)
648
+ inputs_embeds = inputs_embeds.masked_scatter(
649
+ audio_token_mask.to(inputs_embeds.device),
650
+ audio_embeds.to(inputs_embeds.device, dtype=inputs_embeds.dtype),
651
+ )
652
+
653
+ # Setup streamer for token-by-token output
654
+ streamer = TextIteratorStreamer(
655
+ self.tokenizer,
656
+ skip_prompt=True,
657
+ skip_special_tokens=True,
658
+ )
659
+
660
+ # Prepare generation kwargs
661
+ gen_kwargs = {
662
+ "inputs_embeds": inputs_embeds,
663
+ "attention_mask": attention_mask,
664
+ "generation_config": self.generation_config,
665
+ "streamer": streamer,
666
+ **generate_kwargs,
667
+ }
668
+
669
+ # Run generation in background thread
670
+ thread = Thread(target=self.language_model.generate, kwargs=gen_kwargs)
671
+ thread.start()
672
+
673
+ # Yield tokens as they're generated, filtering out <think>...</think> blocks
674
+ # Start assuming no think block - only filter when we see <think>
675
+ in_think_block = False
676
+ buffer = ""
677
+
678
+ for text in streamer:
679
+ buffer += text
680
+
681
+ # Check for think block start (in case model outputs think blocks)
682
+ while "<think>" in buffer:
683
+ in_think_block = True
684
+ # Yield any text before <think>
685
+ before_think = buffer.split("<think>")[0]
686
+ if before_think:
687
+ yield before_think
688
+ buffer = buffer.split("<think>", 1)[-1]
689
+
690
+ # Check for think block end
691
+ while in_think_block and "</think>" in buffer:
692
+ in_think_block = False
693
+ buffer = buffer.split("</think>", 1)[-1]
694
+
695
+ # Yield text if not in think block
696
+ if not in_think_block and buffer:
697
+ yield buffer
698
+ buffer = ""
699
+
700
+ # Yield any remaining buffer
701
+ if buffer and not in_think_block:
702
+ yield buffer
703
+
704
+ thread.join()
705
+
706
+ @torch.no_grad()
707
+ def generate_text_only(
708
+ self,
709
+ messages: list[dict[str, str]],
710
+ max_new_tokens: int = 256,
711
+ **generate_kwargs,
712
+ ) -> str:
713
+ """Generate text using only the LLM (no audio encoding).
714
+
715
+ Used for SIFT-style response generation from metadata prompts.
716
+
717
+ Args:
718
+ messages: List of chat messages [{"role": "user", "content": "..."}]
719
+ max_new_tokens: Maximum tokens to generate
720
+ **generate_kwargs: Additional generation arguments
721
+
722
+ Returns:
723
+ Generated text response
724
+ """
725
+ device = next(self.language_model.parameters()).device
726
+
727
+ # Apply chat template
728
+ input_ids = self.tokenizer.apply_chat_template(
729
+ messages,
730
+ tokenize=True,
731
+ add_generation_prompt=True,
732
+ return_tensors="pt",
733
+ enable_thinking=False,
734
+ ).to(device)
735
+
736
+ if input_ids.dim() == 1:
737
+ input_ids = input_ids.unsqueeze(0)
738
+
739
+ attention_mask = torch.ones_like(input_ids)
740
+
741
+ # Generate using language model directly
742
+ output = self.language_model.generate(
743
+ input_ids=input_ids,
744
+ attention_mask=attention_mask,
745
+ max_new_tokens=max_new_tokens,
746
+ do_sample=False,
747
+ pad_token_id=self.tokenizer.pad_token_id,
748
+ eos_token_id=self.tokenizer.eos_token_id,
749
+ **generate_kwargs,
750
+ )
751
+
752
+ # Decode only the new tokens
753
+ new_tokens = output[0, input_ids.shape[1] :]
754
+ response = self.tokenizer.decode(new_tokens, skip_special_tokens=True)
755
+ return response.strip()
756
+
757
+ def save_pretrained(self, save_directory: Union[str, Path], **kwargs) -> None:
758
+ """Save model, tokenizer, and processor."""
759
+ import shutil
760
+ from pathlib import Path as PathlibPath
761
+
762
+ save_dir = PathlibPath(save_directory)
763
+ save_dir.mkdir(parents=True, exist_ok=True)
764
+
765
+ # Update config with actual vocab size
766
+ self.config.vocab_size = self.language_model.config.vocab_size
767
+ self.config.text_config.vocab_size = self.language_model.config.vocab_size
768
+
769
+ if hasattr(self.audio_tower.config, "num_mel_bins"):
770
+ self.config.audio_config.num_mel_bins = self.audio_tower.config.num_mel_bins
771
+
772
+ # Save model (temporarily remove non-serializable attributes)
773
+ tokenizer = self.tokenizer
774
+ del self.tokenizer
775
+
776
+ try:
777
+ super().save_pretrained(save_dir, **kwargs)
778
+ finally:
779
+ self.tokenizer = tokenizer
780
+
781
+ # Save tokenizer and feature extractor
782
+ self.tokenizer.save_pretrained(save_dir)
783
+ self.feature_extractor.save_pretrained(save_dir)
784
+
785
+ # Save LoRA adapters if present (creates adapter_model.safetensors and adapter_config.json)
786
+ # Don't save embedding layers - the <audio> token embedding is never used
787
+ # (it's replaced with projected audio embeddings before the LLM sees it)
788
+ if hasattr(self.language_model, "peft_config"):
789
+ self.language_model.save_pretrained(save_dir, save_embedding_layers=False)
790
+
791
+ # Clear base_model_name_or_path in adapter_config.json to prevent HF pipeline
792
+ # from redirecting to the base LLM repo (like Qwen) which breaks feature
793
+ # extractor loading for multimodal models. If a repo_id is provided, use that
794
+ # so the model can be loaded directly from the Hub.
795
+ adapter_config_path = save_dir / "adapter_config.json"
796
+ if adapter_config_path.exists():
797
+ with adapter_config_path.open() as f:
798
+ adapter_config = json.load(f)
799
+
800
+ # Use repo_id if available, otherwise clear to prevent redirect.
801
+ # Use empty string instead of None to avoid str(None) -> "None" bug
802
+ # in some transformers/PEFT versions.
803
+ repo_id = (
804
+ kwargs.get("repo_id")
805
+ or kwargs.get("push_to_hub_model_id")
806
+ or getattr(self.config, "pretrained_model_path", None)
807
+ or "" # Use empty string instead of None
808
+ )
809
+ adapter_config["base_model_name_or_path"] = repo_id
810
+
811
+ with adapter_config_path.open("w") as f:
812
+ json.dump(adapter_config, f, indent=2)
813
+
814
+ # Add processor auto_map to preprocessor_config.json
815
+ config_path = save_dir / "preprocessor_config.json"
816
+ if config_path.exists():
817
+ with config_path.open() as f:
818
+ processor_config = json.load(f)
819
+ else:
820
+ processor_config = {}
821
+
822
+ processor_config.update(
823
+ {
824
+ "processor_class": "ASRProcessor",
825
+ "auto_map": {"AutoProcessor": "asr_processing.ASRProcessor"},
826
+ }
827
+ )
828
+
829
+ with config_path.open("w") as f:
830
+ json.dump(processor_config, f, indent=2)
831
+
832
+ # Copy source files for auto-loading
833
+ src_dir = PathlibPath(__file__).parent
834
+ for asr_file in src_dir.glob("asr_*.py"):
835
+ shutil.copy(asr_file, save_dir / asr_file.name)
836
+ # Copy projectors module
837
+ shutil.copy(src_dir / "projectors.py", save_dir / "projectors.py")
838
+ # Copy diarization module
839
+ shutil.copy(src_dir / "diarization.py", save_dir / "diarization.py")
840
+
841
+ def push_to_hub(self, repo_id: str, **kwargs) -> str:
842
+ """Push model to HuggingFace Hub, ensuring adapter_config points to repo.
843
+
844
+ IMPORTANT: Sets base_model_name_or_path in adapter_config.json to repo_id
845
+ so that transformers pipeline() can load the model correctly. Without this,
846
+ the pipeline tries to load from "None" which fails.
847
+ """
848
+ # Store repo_id in config so save_pretrained can access it
849
+ self.config.pretrained_model_path = repo_id
850
+ # Call parent's push_to_hub
851
+ return super().push_to_hub(repo_id, **kwargs)
852
+
853
+ def create_or_update_model_card(self, output_dir: Union[str, Path]) -> None:
854
+ """No-op for model card creation - we use MODEL_CARD.md in repo instead."""
855
+ pass
856
+
857
+
858
+ # Register with transformers Auto classes
859
+ AutoConfig.register("asr_model", ASRConfig)
860
+ AutoModel.register(ASRConfig, ASRModel)
asr_pipeline.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ASR pipeline for audio-to-text transcription with optional timestamps and diarization."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import torch
9
+ import transformers
10
+
11
+ try:
12
+ from .asr_modeling import ASRModel
13
+ except ImportError:
14
+ from asr_modeling import ASRModel # type: ignore[no-redef]
15
+
16
+
17
+ def _get_device() -> str:
18
+ """Get best available device for non-transformers models."""
19
+ if torch.cuda.is_available():
20
+ return "cuda"
21
+ if torch.backends.mps.is_available():
22
+ return "mps"
23
+ return "cpu"
24
+
25
+
26
+ class ForcedAligner:
27
+ """Lazy-loaded forced aligner for word-level timestamps using torchaudio wav2vec2."""
28
+
29
+ _bundle = None
30
+ _model = None
31
+ _labels = None
32
+ _dictionary = None
33
+
34
+ @classmethod
35
+ def get_instance(cls, device: str = "cuda"):
36
+ """Get or create the forced alignment model (singleton).
37
+
38
+ Args:
39
+ device: Device to run model on ("cuda" or "cpu")
40
+
41
+ Returns:
42
+ Tuple of (model, labels, dictionary)
43
+ """
44
+ if cls._model is None:
45
+ import torchaudio
46
+
47
+ cls._bundle = torchaudio.pipelines.WAV2VEC2_ASR_BASE_960H
48
+ cls._model = cls._bundle.get_model().to(device)
49
+ cls._model.eval()
50
+ cls._labels = cls._bundle.get_labels()
51
+ cls._dictionary = {c: i for i, c in enumerate(cls._labels)}
52
+ return cls._model, cls._labels, cls._dictionary
53
+
54
+ @classmethod
55
+ def align(
56
+ cls,
57
+ audio: np.ndarray,
58
+ text: str,
59
+ sample_rate: int = 16000,
60
+ _language: str = "eng",
61
+ _batch_size: int = 16,
62
+ ) -> list[dict]:
63
+ """Align transcript to audio and return word-level timestamps.
64
+
65
+ Args:
66
+ audio: Audio waveform as numpy array
67
+ text: Transcript text to align
68
+ sample_rate: Audio sample rate (default 16000)
69
+ _language: ISO-639-3 language code (default "eng" for English, unused)
70
+ _batch_size: Batch size for alignment model (unused)
71
+
72
+ Returns:
73
+ List of dicts with 'word', 'start', 'end' keys
74
+ """
75
+ import torchaudio
76
+ from torchaudio.functional import forced_align, merge_tokens
77
+
78
+ device = _get_device()
79
+ model, labels, dictionary = cls.get_instance(device)
80
+
81
+ # Convert audio to tensor (copy to ensure array is writable)
82
+ if isinstance(audio, np.ndarray):
83
+ waveform = torch.from_numpy(audio.copy()).float()
84
+ else:
85
+ waveform = audio.clone().float()
86
+
87
+ # Ensure 2D (channels, time)
88
+ if waveform.dim() == 1:
89
+ waveform = waveform.unsqueeze(0)
90
+
91
+ # Resample if needed (wav2vec2 expects 16kHz)
92
+ if sample_rate != cls._bundle.sample_rate:
93
+ waveform = torchaudio.functional.resample(
94
+ waveform, sample_rate, cls._bundle.sample_rate
95
+ )
96
+
97
+ waveform = waveform.to(device)
98
+
99
+ # Get emissions from model
100
+ with torch.inference_mode():
101
+ emissions, _ = model(waveform)
102
+ emissions = torch.log_softmax(emissions, dim=-1)
103
+
104
+ emission = emissions[0].cpu()
105
+
106
+ # Normalize text: uppercase, keep only valid characters
107
+ transcript = text.upper()
108
+ # Build tokens from transcript
109
+ tokens = []
110
+ for char in transcript:
111
+ if char in dictionary:
112
+ tokens.append(dictionary[char])
113
+ elif char == " ":
114
+ tokens.append(dictionary.get("|", dictionary.get(" ", 0)))
115
+
116
+ if not tokens:
117
+ return []
118
+
119
+ targets = torch.tensor([tokens], dtype=torch.int32)
120
+
121
+ # Run forced alignment
122
+ # Note: forced_align is deprecated in torchaudio 2.6+ and will be removed in 2.9 (late 2025)
123
+ # No official replacement announced yet. See https://github.com/pytorch/audio/issues/3902
124
+ aligned_tokens, scores = forced_align(emission.unsqueeze(0), targets, blank=0)
125
+
126
+ # Use torchaudio's merge_tokens to get token spans (removes blanks and merges repeats)
127
+ token_spans = merge_tokens(aligned_tokens[0], scores[0])
128
+
129
+ # Convert frame indices to time (model stride is 320 samples at 16kHz = 20ms)
130
+ frame_duration = 320 / cls._bundle.sample_rate
131
+
132
+ # Group token spans into words based on pipe separator
133
+ words = text.split()
134
+ word_timestamps = []
135
+ current_word_start = None
136
+ current_word_end = None
137
+ word_idx = 0
138
+
139
+ for span in token_spans:
140
+ token_char = labels[span.token]
141
+ if token_char == "|": # Word separator
142
+ if current_word_start is not None and word_idx < len(words):
143
+ word_timestamps.append(
144
+ {
145
+ "word": words[word_idx],
146
+ "start": current_word_start * frame_duration,
147
+ "end": current_word_end * frame_duration,
148
+ }
149
+ )
150
+ word_idx += 1
151
+ current_word_start = None
152
+ current_word_end = None
153
+ else:
154
+ if current_word_start is None:
155
+ current_word_start = span.start
156
+ current_word_end = span.end
157
+
158
+ # Don't forget the last word
159
+ if current_word_start is not None and word_idx < len(words):
160
+ word_timestamps.append(
161
+ {
162
+ "word": words[word_idx],
163
+ "start": current_word_start * frame_duration,
164
+ "end": current_word_end * frame_duration,
165
+ }
166
+ )
167
+
168
+ return word_timestamps
169
+
170
+
171
+ try:
172
+ from .diarization import SpeakerDiarizer
173
+ except ImportError:
174
+ from diarization import SpeakerDiarizer # type: ignore[no-redef]
175
+
176
+ # Re-export for backwards compatibility
177
+ __all__ = ["ForcedAligner", "SpeakerDiarizer", "ASRPipeline"]
178
+
179
+
180
+ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
181
+ """ASR Pipeline for audio-to-text transcription."""
182
+
183
+ model: ASRModel
184
+
185
+ def __init__(self, model: ASRModel, **kwargs):
186
+ """Initialize ASR pipeline.
187
+
188
+ Args:
189
+ model: ASRModel instance for transcription
190
+ **kwargs: Additional arguments (feature_extractor, tokenizer, device)
191
+ """
192
+ feature_extractor = kwargs.pop("feature_extractor", None)
193
+ tokenizer = kwargs.pop("tokenizer", model.tokenizer)
194
+
195
+ if feature_extractor is None:
196
+ feature_extractor = model.get_processor().feature_extractor
197
+
198
+ super().__init__(
199
+ model=model, feature_extractor=feature_extractor, tokenizer=tokenizer, **kwargs
200
+ )
201
+ self._current_audio = None
202
+
203
+ def _sanitize_parameters(self, **kwargs):
204
+ """Intercept our custom parameters before parent class validates them."""
205
+ # Remove our custom parameters so parent doesn't see them
206
+ kwargs.pop("return_timestamps", None)
207
+ kwargs.pop("return_speakers", None)
208
+ kwargs.pop("num_speakers", None)
209
+ kwargs.pop("min_speakers", None)
210
+ kwargs.pop("max_speakers", None)
211
+ kwargs.pop("hf_token", None)
212
+ kwargs.pop("user_prompt", None)
213
+ kwargs.pop("diarization_backend", None)
214
+
215
+ return super()._sanitize_parameters(**kwargs)
216
+
217
+ def __call__(
218
+ self,
219
+ inputs,
220
+ **kwargs,
221
+ ):
222
+ """Transcribe audio with optional word-level timestamps and speaker diarization.
223
+
224
+ Args:
225
+ inputs: Audio input (file path, dict with array/sampling_rate, etc.)
226
+ return_timestamps: If True, return word-level timestamps using forced alignment
227
+ return_speakers: If True, return speaker labels for each word
228
+ user_prompt: Custom transcription prompt (default: "Transcribe: ")
229
+ num_speakers: Exact number of speakers (if known, for diarization)
230
+ min_speakers: Minimum number of speakers (for diarization)
231
+ max_speakers: Maximum number of speakers (for diarization)
232
+ hf_token: HuggingFace token for pyannote models (or set HF_TOKEN env var)
233
+ diarization_backend: Backend for diarization ("pyannote" or "local")
234
+ **kwargs: Additional arguments passed to the pipeline
235
+
236
+ Returns:
237
+ Dict with 'text' key, 'words' key if return_timestamps=True,
238
+ and speaker labels on words if return_speakers=True
239
+ """
240
+ # Extract our params before super().__call__ (which will also call _sanitize_parameters)
241
+ return_timestamps = kwargs.pop("return_timestamps", False)
242
+ return_speakers = kwargs.pop("return_speakers", False)
243
+ user_prompt = kwargs.pop("user_prompt", None)
244
+ diarization_params = {
245
+ "num_speakers": kwargs.pop("num_speakers", None),
246
+ "min_speakers": kwargs.pop("min_speakers", None),
247
+ "max_speakers": kwargs.pop("max_speakers", None),
248
+ "hf_token": kwargs.pop("hf_token", None),
249
+ "backend": kwargs.pop("diarization_backend", "pyannote"),
250
+ }
251
+
252
+ if return_speakers:
253
+ return_timestamps = True
254
+
255
+ # Set custom user prompt if provided
256
+ original_prompt = None
257
+ if user_prompt:
258
+ original_prompt = self.model.TRANSCRIBE_PROMPT
259
+ self.model.TRANSCRIBE_PROMPT = user_prompt
260
+
261
+ # Store audio for timestamp alignment and diarization
262
+ if return_timestamps or return_speakers:
263
+ self._current_audio = self._extract_audio(inputs)
264
+
265
+ # Run standard transcription
266
+ result = super().__call__(inputs, **kwargs)
267
+
268
+ # Add timestamps if requested
269
+ if return_timestamps and self._current_audio is not None:
270
+ text = result.get("text", "")
271
+ if text:
272
+ try:
273
+ words = ForcedAligner.align(
274
+ self._current_audio["array"],
275
+ text,
276
+ sample_rate=self._current_audio.get("sampling_rate", 16000),
277
+ )
278
+ result["words"] = words
279
+ except Exception as e:
280
+ result["words"] = []
281
+ result["timestamp_error"] = str(e)
282
+ else:
283
+ result["words"] = []
284
+
285
+ # Add speaker diarization if requested
286
+ if return_speakers and self._current_audio is not None:
287
+ try:
288
+ # Run diarization
289
+ speaker_segments = SpeakerDiarizer.diarize(
290
+ self._current_audio["array"],
291
+ sample_rate=self._current_audio.get("sampling_rate", 16000),
292
+ **{k: v for k, v in diarization_params.items() if v is not None},
293
+ )
294
+ result["speaker_segments"] = speaker_segments
295
+
296
+ # Assign speakers to words
297
+ if result.get("words"):
298
+ result["words"] = SpeakerDiarizer.assign_speakers_to_words(
299
+ result["words"],
300
+ speaker_segments,
301
+ )
302
+ except Exception as e:
303
+ result["speaker_segments"] = []
304
+ result["diarization_error"] = str(e)
305
+
306
+ # Clean up
307
+ self._current_audio = None
308
+ if original_prompt is not None:
309
+ self.model.TRANSCRIBE_PROMPT = original_prompt
310
+
311
+ return result
312
+
313
+ def _extract_audio(self, inputs) -> dict | None:
314
+ """Extract audio array from various input formats using HF utilities."""
315
+ from transformers.pipelines.audio_utils import ffmpeg_read
316
+
317
+ if isinstance(inputs, dict):
318
+ if "array" in inputs:
319
+ return {
320
+ "array": inputs["array"],
321
+ "sampling_rate": inputs.get("sampling_rate", 16000),
322
+ }
323
+ if "raw" in inputs:
324
+ return {
325
+ "array": inputs["raw"],
326
+ "sampling_rate": inputs.get("sampling_rate", 16000),
327
+ }
328
+ elif isinstance(inputs, str):
329
+ # File path - load audio using ffmpeg (same as HF pipeline)
330
+ with Path(inputs).open("rb") as f:
331
+ audio = ffmpeg_read(f.read(), sampling_rate=16000)
332
+ return {"array": audio, "sampling_rate": 16000}
333
+ elif isinstance(inputs, bytes):
334
+ audio = ffmpeg_read(inputs, sampling_rate=16000)
335
+ return {"array": audio, "sampling_rate": 16000}
336
+ elif isinstance(inputs, np.ndarray):
337
+ return {"array": inputs, "sampling_rate": 16000}
338
+
339
+ return None
340
+
341
+ def preprocess(self, inputs, **preprocess_params):
342
+ """Preprocess audio inputs for the model.
343
+
344
+ Args:
345
+ inputs: Audio input (dict with array, file path, etc.)
346
+ **preprocess_params: Additional preprocessing parameters
347
+
348
+ Yields:
349
+ Model input dicts with input_features and attention_mask
350
+ """
351
+ # Handle dict with "array" key (from datasets)
352
+ if isinstance(inputs, dict) and "array" in inputs:
353
+ inputs = {
354
+ "raw": inputs["array"],
355
+ "sampling_rate": inputs.get("sampling_rate", self.feature_extractor.sampling_rate),
356
+ }
357
+
358
+ for item in super().preprocess(inputs, **preprocess_params):
359
+ if "is_last" not in item:
360
+ item["is_last"] = True
361
+ yield item
362
+
363
+ def _forward(self, model_inputs, **generate_kwargs) -> dict[str, Any]:
364
+ """Run model forward pass to generate transcription.
365
+
366
+ Args:
367
+ model_inputs: Dict with input_features and attention_mask
368
+ **generate_kwargs: Generation parameters
369
+
370
+ Returns:
371
+ Dict with generated token IDs
372
+ """
373
+ # Extract audio features and is_last flag
374
+ is_last = model_inputs.pop("is_last", True) if isinstance(model_inputs, dict) else True
375
+
376
+ input_features = model_inputs["input_features"].to(self.model.device)
377
+ audio_attention_mask = model_inputs["attention_mask"].to(self.model.device)
378
+
379
+ generated_ids = self.model.generate(
380
+ input_features=input_features,
381
+ audio_attention_mask=audio_attention_mask,
382
+ **generate_kwargs,
383
+ )
384
+
385
+ return {"tokens": generated_ids, "is_last": is_last}
386
+
387
+ def postprocess(self, model_outputs, **kwargs) -> dict[str, str]:
388
+ """Convert model output tokens to text.
389
+
390
+ Args:
391
+ model_outputs: Dict with 'tokens' key containing generated IDs
392
+ **kwargs: Additional postprocessing parameters
393
+
394
+ Returns:
395
+ Dict with 'text' key containing transcription
396
+ """
397
+ # Handle list of outputs (from chunking)
398
+ if isinstance(model_outputs, list):
399
+ model_outputs = model_outputs[0] if model_outputs else {}
400
+
401
+ tokens = model_outputs.get("tokens")
402
+ if tokens is None:
403
+ return super().postprocess(model_outputs, **kwargs)
404
+
405
+ if torch.is_tensor(tokens):
406
+ tokens = tokens.cpu()
407
+ if tokens.dim() > 1:
408
+ tokens = tokens[0]
409
+
410
+ # Filter out eos tokens that the tokenizer doesn't recognize as special
411
+ # (generation_config.eos_token_id may differ from tokenizer.eos_token_id)
412
+ if hasattr(self, "model") and hasattr(self.model, "generation_config"):
413
+ eos_ids = self.model.generation_config.eos_token_id
414
+ if eos_ids is not None:
415
+ eos_set = set(eos_ids) if isinstance(eos_ids, list) else {eos_ids}
416
+ tokens = [t for t in tokens.tolist() if t not in eos_set]
417
+
418
+ text = self.tokenizer.decode(tokens, skip_special_tokens=True).strip()
419
+ # Strip <think>...</think> tags (Qwen3 doesn't respect /no_think prompt)
420
+ text = re.sub(r"<think>.*?</think>\s*", "", text, flags=re.DOTALL).strip()
421
+ # Truncate repetitions at end of text
422
+ text = _truncate_repetitions(text)
423
+ return {"text": text}
424
+
425
+
426
+ def _truncate_repetitions(text: str, min_repeats: int = 3) -> str:
427
+ """Truncate repeated words/phrases/characters at end of text.
428
+
429
+ Detects patterns like:
430
+ - Repeated words: "the the the the" -> "the"
431
+ - Repeated phrases: "i am sorry i am sorry i am sorry" -> "i am sorry"
432
+ - Repeated characters: "444444" -> "4"
433
+
434
+ Args:
435
+ text: Input text to process
436
+ min_repeats: Minimum repetitions to trigger truncation (default 3)
437
+
438
+ Returns:
439
+ Text with trailing repetitions removed
440
+ """
441
+ if not text:
442
+ return text
443
+
444
+ # 1. Truncate repeated characters at end (e.g., "444444" -> "4")
445
+ char_pattern = re.compile(r"(.)\1{" + str(min_repeats - 1) + r",}$")
446
+ text = char_pattern.sub(r"\1", text)
447
+
448
+ # 2. Truncate repeated words at end (e.g., "the the the" -> "the")
449
+ word_pattern = re.compile(
450
+ r"\b(\w+)(?:\s+\1){" + str(min_repeats - 1) + r",}\s*$", re.IGNORECASE
451
+ )
452
+ while word_pattern.search(text):
453
+ text = word_pattern.sub(r"\1", text)
454
+
455
+ # 3. Truncate repeated phrases (2-20 words) at end
456
+ # e.g., "i am sorry i am sorry i am sorry" -> "i am sorry"
457
+ words = text.split()
458
+ if len(words) >= min_repeats * 2:
459
+ # Try phrase lengths from 2 to 20 words
460
+ for phrase_len in range(2, min(21, len(words) // min_repeats + 1)):
461
+ # Check if the last phrase_len words repeat
462
+ phrase = " ".join(words[-phrase_len:])
463
+ # Build pattern to match repeated phrases at end
464
+ phrase_escaped = re.escape(phrase)
465
+ phrase_pattern = re.compile(
466
+ r"(^|.*?\s)("
467
+ + phrase_escaped
468
+ + r")(?:\s+"
469
+ + phrase_escaped
470
+ + r"){"
471
+ + str(min_repeats - 1)
472
+ + r",}\s*$",
473
+ re.IGNORECASE,
474
+ )
475
+ match = phrase_pattern.match(text)
476
+ if match:
477
+ # Keep prefix + one instance of the phrase
478
+ text = (match.group(1) + match.group(2)).strip()
479
+ words = text.split()
480
+ break
481
+
482
+ return text
asr_processing.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import torch
4
+ import transformers
5
+ from transformers import ProcessorMixin
6
+
7
+ try:
8
+ from .asr_config import ASRConfig
9
+ except ImportError:
10
+ from asr_config import ASRConfig # type: ignore[no-redef]
11
+
12
+
13
+ class ASRProcessor(ProcessorMixin):
14
+ """Processor for Whisper-based ASR models."""
15
+
16
+ attributes = ["feature_extractor", "tokenizer"]
17
+ feature_extractor_class = "AutoFeatureExtractor"
18
+ tokenizer_class = "AutoTokenizer"
19
+ AUDIO_TOKEN = "<audio>"
20
+ TRANSCRIBE_PROMPT = "Transcribe speech to text"
21
+ # Default conv layers for Whisper/GLM-ASR: [(pad, kernel, stride), ...]
22
+ DEFAULT_ENCODER_CONV_LAYERS = [(1, 3, 1), (1, 3, 2)]
23
+
24
+ def __init__(
25
+ self,
26
+ feature_extractor,
27
+ tokenizer,
28
+ projector=None,
29
+ encoder_conv_layers: Optional[list] = None,
30
+ ):
31
+ """Initialize the ASR processor.
32
+
33
+ Args:
34
+ feature_extractor: Audio feature extractor (WhisperFeatureExtractor)
35
+ tokenizer: Text tokenizer for the language model
36
+ projector: Audio projector module (for computing output lengths)
37
+ encoder_conv_layers: Conv layer specs [(pad, kernel, stride), ...]
38
+ """
39
+ self.feature_extractor = feature_extractor
40
+ self.tokenizer = tokenizer
41
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.AUDIO_TOKEN)
42
+ self.projector = projector
43
+ self.encoder_conv_layers = encoder_conv_layers or self.DEFAULT_ENCODER_CONV_LAYERS
44
+
45
+ def _compute_encoder_output_length(self, mel_length: int) -> int:
46
+ """Compute encoder output length using conv layer formulas."""
47
+ length = mel_length
48
+ for padding, kernel_size, stride in self.encoder_conv_layers:
49
+ length = (length + 2 * padding - (kernel_size - 1) - 1) // stride + 1
50
+ return length
51
+
52
+ def __call__(
53
+ self,
54
+ audio: Optional[Union[list, "torch.Tensor"]] = None,
55
+ text: Optional[str] = None,
56
+ system_prompt: Optional[str] = None,
57
+ return_tensors: str = "pt",
58
+ **kwargs,
59
+ ) -> dict:
60
+ """Process audio and text inputs for inference.
61
+
62
+ Args:
63
+ audio: Raw audio waveform(s)
64
+ text: Target transcription (optional, for training - but use DataCollator instead)
65
+ system_prompt: Optional system prompt
66
+ return_tensors: Return format ("pt" for PyTorch)
67
+
68
+ Returns:
69
+ Dict with input_features, input_ids, attention_mask
70
+ """
71
+ result = {}
72
+
73
+ # Process audio
74
+ if audio is not None:
75
+ audio_inputs = self.feature_extractor(
76
+ audio,
77
+ sampling_rate=getattr(self.feature_extractor, "sampling_rate", 16000),
78
+ return_attention_mask=True,
79
+ return_tensors=return_tensors,
80
+ **kwargs,
81
+ )
82
+ result["input_features"] = audio_inputs["input_features"]
83
+ result["audio_attention_mask"] = audio_inputs["attention_mask"]
84
+
85
+ # Use actual audio length (from attention mask) for token count
86
+ real_mel_len = int(audio_inputs["attention_mask"].sum(dim=-1).max().item())
87
+ encoder_output_len = self._compute_encoder_output_length(real_mel_len)
88
+ num_audio_tokens = self.projector.get_output_length(encoder_output_len)
89
+ else:
90
+ num_audio_tokens = 0
91
+
92
+ # Build prompt with audio token placeholders (audio BEFORE prompt)
93
+ if num_audio_tokens > 0:
94
+ user_content = self.AUDIO_TOKEN * num_audio_tokens + " " + self.TRANSCRIBE_PROMPT
95
+ else:
96
+ user_content = self.TRANSCRIBE_PROMPT
97
+
98
+ messages = []
99
+ if system_prompt:
100
+ messages.append({"role": "system", "content": system_prompt})
101
+ messages.append({"role": "user", "content": user_content})
102
+ if text is not None:
103
+ messages.append({"role": "assistant", "content": text})
104
+
105
+ # Tokenize
106
+ tokenized = self.tokenizer.apply_chat_template(
107
+ messages,
108
+ tokenize=True,
109
+ add_generation_prompt=(text is None),
110
+ return_tensors=return_tensors,
111
+ enable_thinking=False, # Disable Qwen3 thinking mode for ASR
112
+ )
113
+
114
+ # Handle both tensor and BatchEncoding returns
115
+ if isinstance(tokenized, torch.Tensor):
116
+ input_ids = tokenized
117
+ else:
118
+ # BatchEncoding or dict-like object
119
+ input_ids = tokenized.get("input_ids", tokenized.input_ids)
120
+
121
+ if input_ids.dim() == 1:
122
+ input_ids = input_ids.unsqueeze(0)
123
+
124
+ result["input_ids"] = input_ids
125
+ result["attention_mask"] = torch.ones_like(input_ids)
126
+
127
+ return result
128
+
129
+
130
+ ASRProcessor.register_for_auto_class()
131
+ transformers.AutoProcessor.register(ASRConfig, ASRProcessor)
chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if true %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
diarization.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Speaker diarization with support for pyannote and local (tiny-audio) backends.
2
+
3
+ Provides two diarization backends:
4
+ - pyannote: Uses pyannote-audio pipeline (requires HF token with model access)
5
+ - local: Uses TEN-VAD + ERes2NetV2 + spectral clustering (no token required)
6
+
7
+ Spectral clustering implementation adapted from FunASR/3D-Speaker:
8
+ https://github.com/alibaba-damo-academy/FunASR
9
+ MIT License (https://opensource.org/licenses/MIT)
10
+ """
11
+
12
+ import numpy as np
13
+ import scipy
14
+ import sklearn.metrics.pairwise
15
+ import torch
16
+ from sklearn.cluster._kmeans import k_means
17
+
18
+
19
+ def _get_device() -> torch.device:
20
+ """Get best available device for inference."""
21
+ if torch.cuda.is_available():
22
+ return torch.device("cuda")
23
+ if torch.backends.mps.is_available():
24
+ return torch.device("mps")
25
+ return torch.device("cpu")
26
+
27
+
28
+ class SpectralCluster:
29
+ """Spectral clustering using unnormalized Laplacian of affinity matrix.
30
+
31
+ Adapted from FunASR/3D-Speaker and SpeechBrain implementations.
32
+ Uses eigenvalue gap to automatically determine number of speakers.
33
+ """
34
+
35
+ def __init__(self, min_num_spks: int = 1, max_num_spks: int = 15, pval: float = 0.06):
36
+ self.min_num_spks = min_num_spks
37
+ self.max_num_spks = max_num_spks
38
+ self.pval = pval
39
+
40
+ def __call__(self, embeddings: np.ndarray, oracle_num: int | None = None) -> np.ndarray:
41
+ """Run spectral clustering on embeddings.
42
+
43
+ Args:
44
+ embeddings: Speaker embeddings of shape [N, D]
45
+ oracle_num: Optional known number of speakers
46
+
47
+ Returns:
48
+ Cluster labels of shape [N]
49
+ """
50
+ # Similarity matrix computation
51
+ sim_mat = self.get_sim_mat(embeddings)
52
+
53
+ # Refining similarity matrix with pval
54
+ prunned_sim_mat = self.p_pruning(sim_mat)
55
+
56
+ # Symmetrization
57
+ sym_prund_sim_mat = 0.5 * (prunned_sim_mat + prunned_sim_mat.T)
58
+
59
+ # Laplacian calculation
60
+ laplacian = self.get_laplacian(sym_prund_sim_mat)
61
+
62
+ # Get Spectral Embeddings
63
+ emb, num_of_spk = self.get_spec_embs(laplacian, oracle_num)
64
+
65
+ # Perform clustering
66
+ return self.cluster_embs(emb, num_of_spk)
67
+
68
+ def get_sim_mat(self, embeddings: np.ndarray) -> np.ndarray:
69
+ """Compute cosine similarity matrix."""
70
+ return sklearn.metrics.pairwise.cosine_similarity(embeddings, embeddings)
71
+
72
+ def p_pruning(self, affinity: np.ndarray) -> np.ndarray:
73
+ """Prune low similarity values in affinity matrix."""
74
+ pval = 6.0 / affinity.shape[0] if affinity.shape[0] * self.pval < 6 else self.pval
75
+ n_elems = int((1 - pval) * affinity.shape[0])
76
+
77
+ # For each row in affinity matrix, zero out low similarities
78
+ for i in range(affinity.shape[0]):
79
+ low_indexes = np.argsort(affinity[i, :])
80
+ low_indexes = low_indexes[0:n_elems]
81
+ affinity[i, low_indexes] = 0
82
+ return affinity
83
+
84
+ def get_laplacian(self, sim_mat: np.ndarray) -> np.ndarray:
85
+ """Compute unnormalized Laplacian matrix."""
86
+ sim_mat[np.diag_indices(sim_mat.shape[0])] = 0
87
+ degree = np.sum(np.abs(sim_mat), axis=1)
88
+ degree_mat = np.diag(degree)
89
+ return degree_mat - sim_mat
90
+
91
+ def get_spec_embs(
92
+ self, laplacian: np.ndarray, k_oracle: int | None = None
93
+ ) -> tuple[np.ndarray, int]:
94
+ """Extract spectral embeddings from Laplacian."""
95
+ lambdas, eig_vecs = scipy.linalg.eigh(laplacian)
96
+
97
+ if k_oracle is not None:
98
+ num_of_spk = k_oracle
99
+ else:
100
+ lambda_gap_list = self.get_eigen_gaps(
101
+ lambdas[self.min_num_spks - 1 : self.max_num_spks + 1]
102
+ )
103
+ num_of_spk = np.argmax(lambda_gap_list) + self.min_num_spks
104
+
105
+ emb = eig_vecs[:, :num_of_spk]
106
+ return emb, num_of_spk
107
+
108
+ def cluster_embs(self, emb: np.ndarray, k: int) -> np.ndarray:
109
+ """Cluster spectral embeddings using k-means."""
110
+ _, labels, _ = k_means(emb, k, n_init=10)
111
+ return labels
112
+
113
+ def get_eigen_gaps(self, eig_vals: np.ndarray) -> list[float]:
114
+ """Compute gaps between consecutive eigenvalues."""
115
+ eig_vals_gap_list = []
116
+ for i in range(len(eig_vals) - 1):
117
+ gap = float(eig_vals[i + 1]) - float(eig_vals[i])
118
+ eig_vals_gap_list.append(gap)
119
+ return eig_vals_gap_list
120
+
121
+
122
+ class SpeakerClusterer:
123
+ """Speaker clustering backend using spectral clustering with speaker merging.
124
+
125
+ Features:
126
+ - Spectral clustering with eigenvalue gap for auto speaker count detection
127
+ - P-pruning for affinity matrix refinement
128
+ - Post-clustering speaker merging by cosine similarity
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ min_num_spks: int = 2,
134
+ max_num_spks: int = 10,
135
+ merge_thr: float = 0.90, # Moderate merging
136
+ ):
137
+ self.min_num_spks = min_num_spks
138
+ self.max_num_spks = max_num_spks
139
+ self.merge_thr = merge_thr
140
+ self._spectral_cluster: SpectralCluster | None = None
141
+
142
+ def _get_spectral_cluster(self) -> SpectralCluster:
143
+ """Lazy-load spectral clusterer."""
144
+ if self._spectral_cluster is None:
145
+ self._spectral_cluster = SpectralCluster(
146
+ min_num_spks=self.min_num_spks,
147
+ max_num_spks=self.max_num_spks,
148
+ )
149
+ return self._spectral_cluster
150
+
151
+ def __call__(self, embeddings: np.ndarray, num_speakers: int | None = None) -> np.ndarray:
152
+ """Cluster speaker embeddings and return labels.
153
+
154
+ Args:
155
+ embeddings: Speaker embeddings of shape [N, D]
156
+ num_speakers: Optional oracle number of speakers
157
+
158
+ Returns:
159
+ Cluster labels of shape [N]
160
+ """
161
+ import warnings
162
+
163
+ if len(embeddings.shape) != 2:
164
+ raise ValueError(f"Expected 2D array, got shape {embeddings.shape}")
165
+
166
+ # Handle edge cases
167
+ if embeddings.shape[0] == 0:
168
+ return np.array([], dtype=int)
169
+ if embeddings.shape[0] == 1:
170
+ return np.array([0], dtype=int)
171
+ if embeddings.shape[0] < 6:
172
+ return np.zeros(embeddings.shape[0], dtype=int)
173
+
174
+ # Normalize embeddings
175
+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
176
+ norms = np.maximum(norms, 1e-10)
177
+ embeddings = embeddings / norms
178
+
179
+ # Replace NaN/inf with zeros
180
+ embeddings = np.nan_to_num(embeddings, nan=0.0, posinf=0.0, neginf=0.0)
181
+
182
+ # Run spectral clustering (suppress numerical warnings)
183
+ spectral = self._get_spectral_cluster()
184
+
185
+ # Update min/max for oracle case
186
+ if num_speakers is not None:
187
+ spectral.min_num_spks = num_speakers
188
+ spectral.max_num_spks = num_speakers
189
+
190
+ with warnings.catch_warnings():
191
+ warnings.filterwarnings("ignore", category=RuntimeWarning)
192
+ labels = spectral(embeddings, oracle_num=num_speakers)
193
+
194
+ # Reset min/max
195
+ if num_speakers is not None:
196
+ spectral.min_num_spks = self.min_num_spks
197
+ spectral.max_num_spks = self.max_num_spks
198
+
199
+ # Merge similar speakers if no oracle
200
+ if num_speakers is None:
201
+ labels = self._merge_by_cos(labels, embeddings, self.merge_thr)
202
+
203
+ # Re-index labels sequentially
204
+ _, labels = np.unique(labels, return_inverse=True)
205
+
206
+ return labels
207
+
208
+ def _merge_by_cos(self, labels: np.ndarray, embs: np.ndarray, cos_thr: float) -> np.ndarray:
209
+ """Merge similar speakers by cosine similarity of centroids."""
210
+ labels = labels.copy()
211
+
212
+ while True:
213
+ spk_num = labels.max() + 1
214
+ if spk_num == 1:
215
+ break
216
+
217
+ # Compute speaker centroids
218
+ spk_center = []
219
+ for i in range(spk_num):
220
+ spk_emb = embs[labels == i].mean(0)
221
+ spk_center.append(spk_emb)
222
+
223
+ if len(spk_center) == 0:
224
+ break
225
+
226
+ spk_center = np.stack(spk_center, axis=0)
227
+ norm_spk_center = spk_center / np.linalg.norm(spk_center, axis=1, keepdims=True)
228
+ affinity = np.matmul(norm_spk_center, norm_spk_center.T)
229
+ affinity = np.triu(affinity, 1)
230
+
231
+ # Find most similar pair
232
+ spks = np.unravel_index(np.argmax(affinity), affinity.shape)
233
+ if affinity[spks] < cos_thr:
234
+ break
235
+
236
+ # Merge speakers
237
+ for i in range(len(labels)):
238
+ if labels[i] == spks[1]:
239
+ labels[i] = spks[0]
240
+ elif labels[i] > spks[1]:
241
+ labels[i] -= 1
242
+
243
+ return labels
244
+
245
+
246
+ class LocalSpeakerDiarizer:
247
+ """Local speaker diarization using TEN-VAD + ERes2NetV2 + spectral clustering.
248
+
249
+ Pipeline:
250
+ 1. TEN-VAD detects speech segments
251
+ 2. Sliding window (1.0s, 75% overlap) for uniform embedding extraction
252
+ 3. ERes2NetV2 extracts speaker embeddings per window
253
+ 4. Spectral clustering with eigenvalue gap for auto speaker detection
254
+ 5. Frame-level consensus voting for segment reconstruction
255
+ 6. Post-processing merges short segments to reduce flicker
256
+
257
+ Tunable Parameters (class attributes):
258
+ - WINDOW_SIZE: Embedding extraction window size in seconds
259
+ - STEP_SIZE: Sliding window step size (overlap = WINDOW_SIZE - STEP_SIZE)
260
+ - VAD_THRESHOLD: Speech detection threshold (lower = more sensitive)
261
+ - VAD_MIN_DURATION: Minimum speech segment duration
262
+ - VAD_MAX_GAP: Maximum gap to bridge between segments
263
+ - VAD_PAD_ONSET/OFFSET: Padding added to speech segments
264
+ - VOTING_RATE: Frame resolution for consensus voting
265
+ - MIN_SEGMENT_DURATION: Minimum final segment duration
266
+ - SAME_SPEAKER_GAP: Maximum gap to merge same-speaker segments
267
+ - TAIL_COVERAGE_RATIO: Minimum tail coverage to add extra window
268
+ """
269
+
270
+ _ten_vad_model = None
271
+ _eres2netv2_model = None
272
+ _device = None
273
+
274
+ # ==================== TUNABLE PARAMETERS ====================
275
+
276
+ # Sliding window for embedding extraction
277
+ WINDOW_SIZE = 0.75 # seconds - shorter window for finer resolution
278
+ STEP_SIZE = 0.15 # seconds (80% overlap for more votes)
279
+ TAIL_COVERAGE_RATIO = 0.1 # Add extra window if tail > this ratio of window
280
+
281
+ # VAD hysteresis parameters
282
+ VAD_THRESHOLD = 0.25 # Balanced threshold
283
+ VAD_MIN_DURATION = 0.05 # Minimum speech segment duration (seconds)
284
+ VAD_MAX_GAP = 0.50 # Bridge gaps shorter than this (seconds)
285
+ VAD_PAD_ONSET = 0.05 # Padding at segment start (seconds)
286
+ VAD_PAD_OFFSET = 0.05 # Padding at segment end (seconds)
287
+
288
+ # Frame-level voting
289
+ VOTING_RATE = 0.01 # 10ms resolution for consensus voting
290
+
291
+ # Post-processing
292
+ MIN_SEGMENT_DURATION = 0.15 # Minimum final segment duration (seconds)
293
+ SHORT_SEGMENT_GAP = 0.1 # Gap threshold for merging short segments
294
+ SAME_SPEAKER_GAP = 0.5 # Gap threshold for merging same-speaker segments
295
+
296
+ # ===========================================================
297
+
298
+ @classmethod
299
+ def _get_ten_vad_model(cls):
300
+ """Lazy-load TEN-VAD model (singleton)."""
301
+ if cls._ten_vad_model is None:
302
+ from ten_vad import TenVad
303
+
304
+ cls._ten_vad_model = TenVad(hop_size=256, threshold=cls.VAD_THRESHOLD)
305
+ return cls._ten_vad_model
306
+
307
+ @classmethod
308
+ def _get_device(cls) -> torch.device:
309
+ """Get the best available device."""
310
+ if cls._device is None:
311
+ cls._device = _get_device()
312
+ return cls._device
313
+
314
+ @classmethod
315
+ def _get_eres2netv2_model(cls):
316
+ """Lazy-load ERes2NetV2 speaker embedding model (singleton)."""
317
+ if cls._eres2netv2_model is None:
318
+ from modelscope.pipelines import pipeline
319
+ from modelscope.utils.constant import Tasks
320
+
321
+ sv_pipeline = pipeline(
322
+ task=Tasks.speaker_verification,
323
+ model="iic/speech_eres2netv2_sv_zh-cn_16k-common",
324
+ )
325
+ cls._eres2netv2_model = sv_pipeline.model
326
+
327
+ # Move model to GPU if available
328
+ device = cls._get_device()
329
+ cls._eres2netv2_model = cls._eres2netv2_model.to(device)
330
+ cls._eres2netv2_model.device = device
331
+ cls._eres2netv2_model.eval()
332
+
333
+ return cls._eres2netv2_model
334
+
335
+ @classmethod
336
+ def diarize(
337
+ cls,
338
+ audio: np.ndarray | str,
339
+ sample_rate: int = 16000,
340
+ num_speakers: int | None = None,
341
+ min_speakers: int = 2,
342
+ max_speakers: int = 10,
343
+ **_kwargs,
344
+ ) -> list[dict]:
345
+ """Run speaker diarization on audio.
346
+
347
+ Args:
348
+ audio: Audio waveform as numpy array or path to audio file
349
+ sample_rate: Audio sample rate (default 16000)
350
+ num_speakers: Exact number of speakers (if known)
351
+ min_speakers: Minimum number of speakers
352
+ max_speakers: Maximum number of speakers
353
+
354
+ Returns:
355
+ List of dicts with 'speaker', 'start', 'end' keys
356
+ """
357
+ # Handle file path input
358
+ if isinstance(audio, str):
359
+ import librosa
360
+
361
+ audio, sample_rate = librosa.load(audio, sr=16000)
362
+
363
+ # Ensure correct sample rate
364
+ if sample_rate != 16000:
365
+ import librosa
366
+
367
+ audio = librosa.resample(audio, orig_sr=sample_rate, target_sr=16000)
368
+ sample_rate = 16000
369
+
370
+ audio = audio.astype(np.float32)
371
+ total_duration = len(audio) / sample_rate
372
+
373
+ # Step 1: VAD (returns segments and raw frame-level decisions)
374
+ segments, vad_frames = cls._get_speech_segments(audio, sample_rate)
375
+ if not segments:
376
+ return []
377
+
378
+ # Step 2: Extract embeddings
379
+ embeddings, window_segments = cls._extract_embeddings(audio, segments, sample_rate)
380
+ if len(embeddings) == 0:
381
+ return []
382
+
383
+ # Step 3: Cluster
384
+ clusterer = SpeakerClusterer(min_num_spks=min_speakers, max_num_spks=max_speakers)
385
+ labels = clusterer(embeddings, num_speakers)
386
+
387
+ # Step 4: Post-process with consensus voting (VAD-aware)
388
+ return cls._postprocess_segments(window_segments, labels, total_duration, vad_frames)
389
+
390
+ @classmethod
391
+ def _get_speech_segments(
392
+ cls, audio_array: np.ndarray, sample_rate: int = 16000
393
+ ) -> tuple[list[dict], list[bool]]:
394
+ """Get speech segments using TEN-VAD.
395
+
396
+ Returns:
397
+ Tuple of (segments list, vad_frames list of per-frame speech decisions)
398
+ """
399
+ vad_model = cls._get_ten_vad_model()
400
+
401
+ # Convert to int16 as required by TEN-VAD
402
+ # Clip to prevent integer overflow
403
+ if audio_array.dtype != np.int16:
404
+ audio_int16 = (np.clip(audio_array, -1.0, 1.0) * 32767).astype(np.int16)
405
+ else:
406
+ audio_int16 = audio_array
407
+
408
+ # Process frame by frame
409
+ hop_size = 256
410
+ frame_duration = hop_size / sample_rate
411
+ speech_frames: list[bool] = []
412
+
413
+ for i in range(0, len(audio_int16) - hop_size, hop_size):
414
+ frame = audio_int16[i : i + hop_size]
415
+ _, is_speech = vad_model.process(frame)
416
+ speech_frames.append(is_speech)
417
+
418
+ # Convert frame-level decisions to segments
419
+ segments = []
420
+ in_speech = False
421
+ start_idx = 0
422
+
423
+ for i, is_speech in enumerate(speech_frames):
424
+ if is_speech and not in_speech:
425
+ start_idx = i
426
+ in_speech = True
427
+ elif not is_speech and in_speech:
428
+ start_time = start_idx * frame_duration
429
+ end_time = i * frame_duration
430
+ segments.append(
431
+ {
432
+ "start": start_time,
433
+ "end": end_time,
434
+ "start_sample": int(start_time * sample_rate),
435
+ "end_sample": int(end_time * sample_rate),
436
+ }
437
+ )
438
+ in_speech = False
439
+
440
+ # Handle trailing speech
441
+ if in_speech:
442
+ start_time = start_idx * frame_duration
443
+ end_time = len(speech_frames) * frame_duration
444
+ segments.append(
445
+ {
446
+ "start": start_time,
447
+ "end": end_time,
448
+ "start_sample": int(start_time * sample_rate),
449
+ "end_sample": int(end_time * sample_rate),
450
+ }
451
+ )
452
+
453
+ return cls._apply_vad_hysteresis(segments, sample_rate), speech_frames
454
+
455
+ @classmethod
456
+ def _apply_vad_hysteresis(cls, segments: list[dict], sample_rate: int = 16000) -> list[dict]:
457
+ """Apply hysteresis-like post-processing to VAD segments."""
458
+ if not segments:
459
+ return segments
460
+
461
+ segments = sorted(segments, key=lambda x: x["start"])
462
+
463
+ # Fill short gaps
464
+ merged = [segments[0].copy()]
465
+ for seg in segments[1:]:
466
+ gap = seg["start"] - merged[-1]["end"]
467
+ if gap <= cls.VAD_MAX_GAP:
468
+ merged[-1]["end"] = seg["end"]
469
+ merged[-1]["end_sample"] = seg["end_sample"]
470
+ else:
471
+ merged.append(seg.copy())
472
+
473
+ # Remove short segments
474
+ filtered = [seg for seg in merged if (seg["end"] - seg["start"]) >= cls.VAD_MIN_DURATION]
475
+
476
+ # Dilate segments (add padding)
477
+ for seg in filtered:
478
+ seg["start"] = max(0.0, seg["start"] - cls.VAD_PAD_ONSET)
479
+ seg["end"] = seg["end"] + cls.VAD_PAD_OFFSET
480
+ seg["start_sample"] = int(seg["start"] * sample_rate)
481
+ seg["end_sample"] = int(seg["end"] * sample_rate)
482
+
483
+ return filtered
484
+
485
+ @classmethod
486
+ def _extract_embeddings(
487
+ cls, audio_array: np.ndarray, segments: list[dict], sample_rate: int
488
+ ) -> tuple[np.ndarray, list[dict]]:
489
+ """Extract speaker embeddings using sliding windows."""
490
+ speaker_model = cls._get_eres2netv2_model()
491
+ device = cls._get_device()
492
+
493
+ window_samples = int(cls.WINDOW_SIZE * sample_rate)
494
+ step_samples = int(cls.STEP_SIZE * sample_rate)
495
+
496
+ embeddings = []
497
+ window_segments = []
498
+
499
+ with torch.no_grad():
500
+ for seg in segments:
501
+ seg_start = seg["start_sample"]
502
+ seg_end = seg["end_sample"]
503
+ seg_len = seg_end - seg_start
504
+
505
+ # Generate window positions
506
+ if seg_len <= window_samples:
507
+ starts = [seg_start]
508
+ ends = [seg_end]
509
+ else:
510
+ starts = list(range(seg_start, seg_end - window_samples + 1, step_samples))
511
+ ends = [s + window_samples for s in starts]
512
+
513
+ # Cover tail if > TAIL_COVERAGE_RATIO of window remains
514
+ if ends and ends[-1] < seg_end:
515
+ remainder = seg_end - ends[-1]
516
+ if remainder > (window_samples * cls.TAIL_COVERAGE_RATIO):
517
+ starts.append(seg_end - window_samples)
518
+ ends.append(seg_end)
519
+
520
+ for c_start, c_end in zip(starts, ends):
521
+ chunk = audio_array[c_start:c_end]
522
+
523
+ # Pad short chunks with reflection
524
+ if len(chunk) < window_samples:
525
+ pad_width = window_samples - len(chunk)
526
+ chunk = np.pad(chunk, (0, pad_width), mode="reflect")
527
+
528
+ # Extract embedding
529
+ chunk_tensor = torch.from_numpy(chunk).float().unsqueeze(0).to(device)
530
+ embedding = speaker_model.forward(chunk_tensor).squeeze(0).cpu().numpy()
531
+
532
+ # Validate and normalize
533
+ if not np.isfinite(embedding).all():
534
+ continue
535
+ norm = np.linalg.norm(embedding)
536
+ if norm > 1e-8:
537
+ embeddings.append(embedding / norm)
538
+ window_segments.append(
539
+ {
540
+ "start": c_start / sample_rate,
541
+ "end": c_end / sample_rate,
542
+ }
543
+ )
544
+
545
+ if embeddings:
546
+ return np.array(embeddings), window_segments
547
+ return np.array([]), []
548
+
549
+ @classmethod
550
+ def _resample_vad(cls, vad_frames: list[bool], num_frames: int) -> np.ndarray:
551
+ """Resample VAD frame decisions to match voting grid resolution.
552
+
553
+ VAD operates at 256 samples / 16000 Hz = 16ms per frame.
554
+ Voting operates at VOTING_RATE (default 10ms) per frame.
555
+ This maps VAD decisions to the finer voting grid.
556
+ """
557
+ if not vad_frames:
558
+ return np.zeros(num_frames, dtype=bool)
559
+
560
+ vad_rate = 256 / 16000 # 16ms per VAD frame
561
+ result = np.zeros(num_frames, dtype=bool)
562
+
563
+ for i in range(num_frames):
564
+ voting_time = i * cls.VOTING_RATE
565
+ vad_frame = int(voting_time / vad_rate)
566
+ if vad_frame < len(vad_frames):
567
+ result[i] = vad_frames[vad_frame]
568
+
569
+ return result
570
+
571
+ @classmethod
572
+ def _postprocess_segments(
573
+ cls,
574
+ window_segments: list[dict],
575
+ labels: np.ndarray,
576
+ total_duration: float,
577
+ vad_frames: list[bool],
578
+ ) -> list[dict]:
579
+ """Post-process using frame-level consensus voting with VAD-aware silence."""
580
+ if not window_segments or len(labels) == 0:
581
+ return []
582
+
583
+ # Correct labels to be contiguous
584
+ unique_labels = np.unique(labels)
585
+ label_map = {old: new for new, old in enumerate(unique_labels)}
586
+ clean_labels = np.array([label_map[lbl] for lbl in labels])
587
+ num_speakers = len(unique_labels)
588
+
589
+ if num_speakers == 0:
590
+ return []
591
+
592
+ # Create voting grid
593
+ num_frames = int(np.ceil(total_duration / cls.VOTING_RATE)) + 1
594
+ votes = np.zeros((num_frames, num_speakers), dtype=np.float32)
595
+
596
+ # Accumulate votes
597
+ for win, label in zip(window_segments, clean_labels):
598
+ start_frame = int(win["start"] / cls.VOTING_RATE)
599
+ end_frame = int(win["end"] / cls.VOTING_RATE)
600
+ end_frame = min(end_frame, num_frames)
601
+ if start_frame < end_frame:
602
+ votes[start_frame:end_frame, label] += 1.0
603
+
604
+ # Determine winner per frame
605
+ frame_speakers = np.argmax(votes, axis=1)
606
+ max_votes = np.max(votes, axis=1)
607
+
608
+ # Resample VAD to voting grid resolution for silence-aware voting
609
+ vad_resampled = cls._resample_vad(vad_frames, num_frames)
610
+
611
+ # Convert frames to segments
612
+ final_segments = []
613
+ current_speaker = -1
614
+ seg_start = 0.0
615
+
616
+ for f in range(num_frames):
617
+ speaker = int(frame_speakers[f])
618
+ score = max_votes[f]
619
+
620
+ # Force silence if VAD says no speech OR no votes
621
+ if score == 0 or not vad_resampled[f]:
622
+ speaker = -1
623
+
624
+ if speaker != current_speaker:
625
+ if current_speaker != -1:
626
+ final_segments.append(
627
+ {
628
+ "speaker": f"SPEAKER_{current_speaker}",
629
+ "start": seg_start,
630
+ "end": f * cls.VOTING_RATE,
631
+ }
632
+ )
633
+ current_speaker = speaker
634
+ seg_start = f * cls.VOTING_RATE
635
+
636
+ # Close last segment
637
+ if current_speaker != -1:
638
+ final_segments.append(
639
+ {
640
+ "speaker": f"SPEAKER_{current_speaker}",
641
+ "start": seg_start,
642
+ "end": num_frames * cls.VOTING_RATE,
643
+ }
644
+ )
645
+
646
+ return cls._merge_short_segments(final_segments)
647
+
648
+ @classmethod
649
+ def _merge_short_segments(cls, segments: list[dict]) -> list[dict]:
650
+ """Merge short segments to reduce flicker."""
651
+ if not segments:
652
+ return []
653
+
654
+ clean: list[dict] = []
655
+ for seg in segments:
656
+ dur = seg["end"] - seg["start"]
657
+ if dur < cls.MIN_SEGMENT_DURATION:
658
+ if (
659
+ clean
660
+ and clean[-1]["speaker"] == seg["speaker"]
661
+ and seg["start"] - clean[-1]["end"] < cls.SHORT_SEGMENT_GAP
662
+ ):
663
+ clean[-1]["end"] = seg["end"]
664
+ continue
665
+
666
+ if (
667
+ clean
668
+ and clean[-1]["speaker"] == seg["speaker"]
669
+ and seg["start"] - clean[-1]["end"] < cls.SAME_SPEAKER_GAP
670
+ ):
671
+ clean[-1]["end"] = seg["end"]
672
+ else:
673
+ clean.append(seg)
674
+
675
+ return clean
676
+
677
+ @classmethod
678
+ def assign_speakers_to_words(
679
+ cls,
680
+ words: list[dict],
681
+ speaker_segments: list[dict],
682
+ ) -> list[dict]:
683
+ """Assign speaker labels to words based on timestamp overlap.
684
+
685
+ Args:
686
+ words: List of word dicts with 'word', 'start', 'end' keys
687
+ speaker_segments: List of speaker dicts with 'speaker', 'start', 'end' keys
688
+
689
+ Returns:
690
+ Words list with 'speaker' key added to each word
691
+ """
692
+ for word in words:
693
+ word_mid = (word["start"] + word["end"]) / 2
694
+
695
+ # Find the speaker segment that contains this word's midpoint
696
+ best_speaker = None
697
+ for seg in speaker_segments:
698
+ if seg["start"] <= word_mid <= seg["end"]:
699
+ best_speaker = seg["speaker"]
700
+ break
701
+
702
+ # If no exact match, find closest segment
703
+ if best_speaker is None and speaker_segments:
704
+ min_dist = float("inf")
705
+ for seg in speaker_segments:
706
+ seg_mid = (seg["start"] + seg["end"]) / 2
707
+ dist = abs(word_mid - seg_mid)
708
+ if dist < min_dist:
709
+ min_dist = dist
710
+ best_speaker = seg["speaker"]
711
+
712
+ word["speaker"] = best_speaker
713
+
714
+ return words
715
+
716
+
717
+ class SpeakerDiarizer:
718
+ """Unified speaker diarization interface supporting multiple backends.
719
+
720
+ Backends:
721
+ - 'pyannote': Uses pyannote-audio pipeline (requires HF token)
722
+ - 'local': Uses TEN-VAD + ERes2NetV2 + spectral clustering
723
+
724
+ Example:
725
+ >>> segments = SpeakerDiarizer.diarize(audio_array, backend="local")
726
+ >>> for seg in segments:
727
+ ... print(f"{seg['speaker']}: {seg['start']:.2f} - {seg['end']:.2f}")
728
+ """
729
+
730
+ _pyannote_pipeline = None
731
+
732
+ @classmethod
733
+ def _get_pyannote_pipeline(cls, hf_token: str | None = None):
734
+ """Get or create the pyannote diarization pipeline."""
735
+ if cls._pyannote_pipeline is None:
736
+ from pyannote.audio import Pipeline
737
+
738
+ cls._pyannote_pipeline = Pipeline.from_pretrained(
739
+ "pyannote/speaker-diarization-3.1",
740
+ use_auth_token=hf_token,
741
+ )
742
+ cls._pyannote_pipeline.to(torch.device(_get_device()))
743
+
744
+ return cls._pyannote_pipeline
745
+
746
+ @classmethod
747
+ def diarize(
748
+ cls,
749
+ audio: np.ndarray | str,
750
+ sample_rate: int = 16000,
751
+ num_speakers: int | None = None,
752
+ min_speakers: int | None = None,
753
+ max_speakers: int | None = None,
754
+ hf_token: str | None = None,
755
+ backend: str = "pyannote",
756
+ ) -> list[dict]:
757
+ """Run speaker diarization on audio.
758
+
759
+ Args:
760
+ audio: Audio waveform as numpy array or path to audio file
761
+ sample_rate: Audio sample rate (default 16000)
762
+ num_speakers: Exact number of speakers (if known)
763
+ min_speakers: Minimum number of speakers
764
+ max_speakers: Maximum number of speakers
765
+ hf_token: HuggingFace token for pyannote models
766
+ backend: Diarization backend ("pyannote" or "local")
767
+
768
+ Returns:
769
+ List of dicts with 'speaker', 'start', 'end' keys
770
+ """
771
+ if backend == "local":
772
+ return LocalSpeakerDiarizer.diarize(
773
+ audio,
774
+ sample_rate=sample_rate,
775
+ num_speakers=num_speakers,
776
+ min_speakers=min_speakers or 2,
777
+ max_speakers=max_speakers or 10,
778
+ )
779
+
780
+ # Default to pyannote
781
+ return cls._diarize_pyannote(
782
+ audio,
783
+ sample_rate=sample_rate,
784
+ num_speakers=num_speakers,
785
+ min_speakers=min_speakers,
786
+ max_speakers=max_speakers,
787
+ hf_token=hf_token,
788
+ )
789
+
790
+ @classmethod
791
+ def _diarize_pyannote(
792
+ cls,
793
+ audio: np.ndarray | str,
794
+ sample_rate: int = 16000,
795
+ num_speakers: int | None = None,
796
+ min_speakers: int | None = None,
797
+ max_speakers: int | None = None,
798
+ hf_token: str | None = None,
799
+ ) -> list[dict]:
800
+ """Run pyannote diarization."""
801
+ pipeline = cls._get_pyannote_pipeline(hf_token)
802
+
803
+ # Prepare audio input
804
+ if isinstance(audio, np.ndarray):
805
+ waveform = torch.from_numpy(audio.copy()).unsqueeze(0)
806
+ if waveform.dim() == 1:
807
+ waveform = waveform.unsqueeze(0)
808
+ audio_input = {"waveform": waveform, "sample_rate": sample_rate}
809
+ else:
810
+ audio_input = audio
811
+
812
+ # Run diarization
813
+ diarization_args = {}
814
+ if num_speakers is not None:
815
+ diarization_args["num_speakers"] = num_speakers
816
+ if min_speakers is not None:
817
+ diarization_args["min_speakers"] = min_speakers
818
+ if max_speakers is not None:
819
+ diarization_args["max_speakers"] = max_speakers
820
+
821
+ diarization = pipeline(audio_input, **diarization_args)
822
+
823
+ # Handle different pyannote return types
824
+ if hasattr(diarization, "itertracks"):
825
+ annotation = diarization
826
+ elif hasattr(diarization, "speaker_diarization"):
827
+ annotation = diarization.speaker_diarization
828
+ elif isinstance(diarization, tuple):
829
+ annotation = diarization[0]
830
+ else:
831
+ raise TypeError(f"Unexpected diarization output type: {type(diarization)}")
832
+
833
+ # Convert to simple format
834
+ segments = []
835
+ for turn, _, speaker in annotation.itertracks(yield_label=True):
836
+ segments.append(
837
+ {
838
+ "speaker": speaker,
839
+ "start": turn.start,
840
+ "end": turn.end,
841
+ }
842
+ )
843
+
844
+ return segments
845
+
846
+ @classmethod
847
+ def assign_speakers_to_words(
848
+ cls,
849
+ words: list[dict],
850
+ speaker_segments: list[dict],
851
+ ) -> list[dict]:
852
+ """Assign speaker labels to words based on timestamp overlap."""
853
+ return LocalSpeakerDiarizer.assign_speakers_to_words(words, speaker_segments)
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chunk_length": 30,
3
+ "dither": 0.0,
4
+ "feature_extractor_type": "WhisperFeatureExtractor",
5
+ "feature_size": 128,
6
+ "hop_length": 160,
7
+ "n_fft": 400,
8
+ "n_samples": 480000,
9
+ "nb_max_frames": 3000,
10
+ "padding": false,
11
+ "padding_side": "right",
12
+ "padding_value": 0.0,
13
+ "return_attention_mask": false,
14
+ "sampling_rate": 16000,
15
+ "processor_class": "ASRProcessor",
16
+ "auto_map": {
17
+ "AutoProcessor": "asr_processing.ASRProcessor"
18
+ }
19
+ }
projectors.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audio projector modules for bridging encoder and decoder embeddings.
2
+
3
+ This module contains all projector architectures:
4
+ - MLPAudioProjector: Simple 2-layer MLP with frame stacking downsampling
5
+ - MOSAProjector: MOSA-style dense mixture of experts
6
+ - SharedMoEAudioProjector: Shared expert + sparse routed experts
7
+ - QFormerAudioProjector: BLIP-2 QFormer with learnable queries (Granite-style)
8
+ """
9
+
10
+ import math
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F # noqa: N812
15
+ from transformers import AutoModel, Blip2QFormerConfig
16
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
17
+
18
+ # =============================================================================
19
+ # MLP Projector
20
+ # =============================================================================
21
+
22
+
23
+ class MLPAudioProjector(nn.Module):
24
+ """2-layer MLP projector with frame-stacking downsampling (matches GLM-ASR)."""
25
+
26
+ def __init__(self, config):
27
+ """Initialize MLP projector.
28
+
29
+ Args:
30
+ config: ASRConfig with encoder_dim, llm_dim, projector_pool_stride
31
+ """
32
+ super().__init__()
33
+
34
+ encoder_dim = getattr(config, "encoder_dim", 768)
35
+ llm_dim = getattr(config, "llm_dim", 2048)
36
+ self.k = getattr(config, "projector_pool_stride", 4)
37
+
38
+ # Frame stacking: concat k adjacent frames then project
39
+ # Hidden dim uses 2x expansion like GLM-ASR's GlmAsrMultiModalProjector
40
+ in_dim = encoder_dim * self.k
41
+ hidden_dim = llm_dim * 2
42
+ self.linear_1 = nn.Linear(in_dim, hidden_dim)
43
+ self.act = nn.GELU()
44
+ self.linear_2 = nn.Linear(hidden_dim, llm_dim)
45
+
46
+ def get_output_length(self, input_length: int) -> int:
47
+ """Calculate output sequence length given input length (matches GLM-ASR)."""
48
+ # GLM-ASR formula: (L - merge_factor) // merge_factor + 1
49
+ return (input_length - self.k) // self.k + 1
50
+
51
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
52
+ """Project audio features to LLM embedding space.
53
+
54
+ Args:
55
+ x: Audio encoder output of shape [batch, seq_len, encoder_dim]
56
+
57
+ Returns:
58
+ Projected features of shape [batch, (seq_len - k) // k + 1, llm_dim]
59
+ """
60
+ batch, seq, dim = x.shape
61
+ # Truncate to match GLM-ASR: use (seq - k) // k + 1 frames
62
+ # This drops trailing frames that don't fill a complete k-frame window
63
+ out_len = (seq - self.k) // self.k + 1
64
+ x = x[:, : out_len * self.k, :] # Truncate to exact multiple
65
+ x = x.reshape(batch, out_len, dim * self.k)
66
+
67
+ x = self.linear_1(x)
68
+ x = self.act(x)
69
+ return self.linear_2(x)
70
+
71
+
72
+ # =============================================================================
73
+ # MoE Projector (MOSA-style)
74
+ # =============================================================================
75
+
76
+
77
+ class SimpleAdapter(nn.Module):
78
+ """Simple 2-layer GELU adapter (from MOSA paper)."""
79
+
80
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int):
81
+ super().__init__()
82
+ self.fc1 = nn.Linear(input_dim, hidden_dim)
83
+ self.act = nn.GELU()
84
+ self.fc2 = nn.Linear(hidden_dim, output_dim)
85
+
86
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
87
+ return self.fc2(self.act(self.fc1(x)))
88
+
89
+
90
+ class MOSAProjector(nn.Module):
91
+ """MOSA-Base projector: simple 2-layer ReLU router with 4 simple adapters.
92
+
93
+ Based on "MOSA: Mixtures of Simple Adapters" (arXiv:2508.18998).
94
+ Uses softmax gating over all experts (dense MoE) with only cross-entropy loss.
95
+ Uses Conv1d for downsampling (2 layers, stride 2 each = 4x total).
96
+ """
97
+
98
+ def __init__(self, config):
99
+ """Initialize MOSA projector.
100
+
101
+ Args:
102
+ config: ASRConfig with encoder_dim, llm_dim, num_experts
103
+ """
104
+ super().__init__()
105
+ self.encoder_dim = getattr(config, "encoder_dim", None) or 1280
106
+ self.llm_dim = getattr(config, "llm_dim", None) or 2048
107
+ self.num_experts = getattr(config, "num_experts", None) or 4 # MOSA-Base uses 4
108
+ adapter_hidden = getattr(config, "adapter_hidden_dim", None) or 4096
109
+ router_hidden = getattr(config, "router_hidden_dim", None) or 512
110
+
111
+ # --- 1. Conv1d Downsampler (4x reduction) ---
112
+ # 2 layers of stride-2 convolution
113
+ self.downsampler = nn.Sequential(
114
+ nn.Conv1d(self.encoder_dim, self.encoder_dim, kernel_size=3, stride=2, padding=1),
115
+ nn.GELU(),
116
+ nn.Conv1d(self.encoder_dim, self.llm_dim, kernel_size=3, stride=2, padding=1),
117
+ nn.GELU(),
118
+ )
119
+
120
+ # --- 2. Simple Router (MOSA-Base: 2 layers with ReLU) ---
121
+ # Takes downsampled features (llm_dim) -> 512 -> num_experts
122
+ self.router = nn.Sequential(
123
+ nn.Linear(self.llm_dim, router_hidden),
124
+ nn.ReLU(),
125
+ nn.Linear(router_hidden, self.num_experts),
126
+ )
127
+
128
+ # --- 3. Experts (Simple 2-layer GELU adapters) ---
129
+ # Each expert: llm_dim -> hidden -> llm_dim (much smaller than frame-stacking)
130
+ self.experts = nn.ModuleList(
131
+ [
132
+ SimpleAdapter(self.llm_dim, adapter_hidden, self.llm_dim)
133
+ for _ in range(self.num_experts)
134
+ ]
135
+ )
136
+
137
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
138
+ """Project audio features using mixture of experts.
139
+
140
+ Args:
141
+ x: Audio encoder output of shape [batch, seq_len, encoder_dim]
142
+
143
+ Returns:
144
+ Projected features of shape [batch, out_len, llm_dim]
145
+ """
146
+ # --- 1. Conv1d Downsampling ---
147
+ # Permute for Conv1d: [B, S, D] -> [B, D, S]
148
+ x = x.transpose(1, 2)
149
+ x = self.downsampler(x)
150
+ # Permute back: [B, D, S] -> [B, S, D]
151
+ x = x.transpose(1, 2)
152
+
153
+ # --- 2. Routing ---
154
+ routing_weights = F.softmax(self.router(x), dim=-1) # (B, out_len, num_experts)
155
+
156
+ # --- 3. Expert Mixture (Dense Execution) ---
157
+ expert_outputs = torch.stack([expert(x) for expert in self.experts]) # (E, B, out_len, D)
158
+ return torch.einsum("ebsd, bse -> bsd", expert_outputs, routing_weights)
159
+
160
+ def get_output_length(self, input_length: int) -> int:
161
+ """Calculate output sequence length after Conv1d downsampling (4x reduction)."""
162
+ # Conv1d with stride 2, kernel 3, padding 1: out = (in + 2*1 - 3) // 2 + 1 = (in - 1) // 2 + 1
163
+ # Applied twice for 4x total reduction
164
+ after_conv1 = (input_length + 2 * 1 - 3) // 2 + 1
165
+ return (after_conv1 + 2 * 1 - 3) // 2 + 1
166
+
167
+
168
+ # =============================================================================
169
+ # MoE Projector (Shared Expert + Sparse Routed Experts)
170
+ # =============================================================================
171
+
172
+
173
+ class SharedMoEBlock(nn.Module):
174
+ """MoE block with Shared + Sigmoid-Routed Experts."""
175
+
176
+ def __init__(
177
+ self,
178
+ input_dim: int,
179
+ hidden_dim: int,
180
+ output_dim: int,
181
+ num_experts: int = 4,
182
+ top_k: int = 2,
183
+ ):
184
+ super().__init__()
185
+ self.num_experts = num_experts
186
+ self.top_k = top_k
187
+ self.output_dim = output_dim
188
+
189
+ # RMSNorm before routing
190
+ self.norm = LlamaRMSNorm(input_dim, eps=1e-8)
191
+
192
+ self.router = nn.Linear(input_dim, num_experts, bias=False)
193
+ nn.init.normal_(self.router.weight, mean=0.0, std=0.02)
194
+
195
+ self.shared_expert = SimpleAdapter(input_dim, hidden_dim, output_dim)
196
+ self.experts = nn.ModuleList(
197
+ [SimpleAdapter(input_dim, hidden_dim, output_dim) for _ in range(num_experts)]
198
+ )
199
+
200
+ self.last_router_logits = None
201
+ self.last_router_probs = None
202
+
203
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
204
+ batch_size, seq_len, dim = hidden_states.shape
205
+
206
+ # 1. Apply Shared Expert
207
+ normed_states = self.norm(hidden_states)
208
+ shared_out = self.shared_expert(normed_states)
209
+
210
+ # 2. Router Logic (Sigmoid Style)
211
+ flat_hidden = normed_states.view(-1, dim)
212
+ router_logits = self.router(flat_hidden)
213
+
214
+ # Sigmoid routing
215
+ router_probs = torch.sigmoid(router_logits)
216
+
217
+ self.last_router_logits = router_logits
218
+ self.last_router_probs = router_probs
219
+
220
+ # 3. Top-K Selection
221
+ top_k_scores, top_k_indices = torch.topk(router_probs, self.top_k, dim=-1)
222
+
223
+ # Normalize weights
224
+ top_k_weights = top_k_scores / (top_k_scores.sum(dim=-1, keepdim=True) + 1e-6)
225
+ top_k_weights = top_k_weights.to(hidden_states.dtype)
226
+
227
+ # 4. Dispatch
228
+ routed_out = self._dispatch_experts(flat_hidden, top_k_indices, top_k_weights)
229
+ routed_out = routed_out.view(batch_size, seq_len, -1)
230
+
231
+ return shared_out + routed_out
232
+
233
+ def _dispatch_experts(
234
+ self,
235
+ hidden_states: torch.Tensor,
236
+ top_k_indices: torch.Tensor,
237
+ top_k_weights: torch.Tensor,
238
+ ) -> torch.Tensor:
239
+ num_tokens = hidden_states.shape[0]
240
+ output = torch.zeros(
241
+ num_tokens, self.output_dim, device=hidden_states.device, dtype=hidden_states.dtype
242
+ )
243
+
244
+ for expert_idx, expert in enumerate(self.experts):
245
+ expert_mask = top_k_indices == expert_idx
246
+ if not expert_mask.any():
247
+ continue
248
+
249
+ token_indices, slot_indices = torch.where(expert_mask)
250
+ expert_input = hidden_states[token_indices]
251
+ expert_output = expert(expert_input).to(output.dtype)
252
+ weights = top_k_weights[token_indices, slot_indices].unsqueeze(-1)
253
+ output.index_add_(0, token_indices, expert_output * weights)
254
+
255
+ return output
256
+
257
+
258
+ def load_balancing_loss(router_probs: torch.Tensor, num_experts: int, top_k: int) -> torch.Tensor:
259
+ """Auxiliary loss to encourage balanced expert usage."""
260
+ prob_per_expert = router_probs.mean(dim=0)
261
+ target_mean = prob_per_expert.mean()
262
+ return (prob_per_expert - target_mean).square().sum() * num_experts
263
+
264
+
265
+ def z_loss(router_logits: torch.Tensor) -> torch.Tensor:
266
+ """Z-loss to prevent router logits from growing too large."""
267
+ return torch.logsumexp(router_logits.float(), dim=-1).square().mean()
268
+
269
+
270
+ class MoEAudioProjector(nn.Module):
271
+ """MoE projector with shared expert + sparse routed experts."""
272
+
273
+ def __init__(self, config):
274
+ """Initialize MoE projector.
275
+
276
+ Args:
277
+ config: ASRConfig with encoder_dim, llm_dim, num_experts, num_experts_per_tok
278
+ """
279
+ super().__init__()
280
+
281
+ self.k = getattr(config, "projector_pool_stride", 4)
282
+ encoder_dim = config.encoder_dim
283
+
284
+ # Depthwise Conv for temporal mixing
285
+ self.temporal_conv = nn.Conv1d(
286
+ encoder_dim, encoder_dim, kernel_size=3, padding=1, groups=encoder_dim
287
+ )
288
+
289
+ in_dim = encoder_dim * self.k
290
+ out_dim = config.llm_dim
291
+ hidden_dim = getattr(config, "projector_hidden_dim", None) or in_dim
292
+
293
+ self.num_experts = getattr(config, "num_experts", 4)
294
+ self.top_k = getattr(config, "num_experts_per_tok", 2)
295
+ self.aux_loss_coef = getattr(config, "router_aux_loss_coef", 0.02)
296
+ self.z_loss_coef = getattr(config, "router_z_loss_coef", 0.001)
297
+
298
+ self.moe = SharedMoEBlock(in_dim, hidden_dim, out_dim, self.num_experts, self.top_k)
299
+ self._init_weights()
300
+
301
+ def _init_weights(self):
302
+ with torch.no_grad():
303
+ nn.init.orthogonal_(self.moe.shared_expert.fc1.weight)
304
+ nn.init.orthogonal_(self.moe.shared_expert.fc2.weight, gain=0.5)
305
+
306
+ for expert in self.moe.experts:
307
+ nn.init.orthogonal_(expert.fc1.weight)
308
+ nn.init.orthogonal_(expert.fc2.weight, gain=0.01)
309
+
310
+ def get_output_length(self, input_length: int) -> int:
311
+ """Calculate output sequence length given input length."""
312
+ # Temporal pooling with stride k
313
+ if input_length % self.k:
314
+ input_length += self.k - input_length % self.k
315
+ return input_length // self.k
316
+
317
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
318
+ """Project audio features using shared + sparse MoE.
319
+
320
+ Args:
321
+ x: Audio encoder output of shape [batch, seq_len, encoder_dim]
322
+
323
+ Returns:
324
+ Projected features of shape [batch, out_len, llm_dim]
325
+ """
326
+ batch_size, seq_len, dim = x.size()
327
+
328
+ target_dtype = self.moe.shared_expert.fc1.weight.dtype
329
+ if x.dtype != target_dtype:
330
+ x = x.to(target_dtype)
331
+
332
+ # Temporal Context Injection
333
+ x_ctx = x.transpose(1, 2)
334
+ x_ctx = self.temporal_conv(x_ctx)
335
+ x = x + x_ctx.transpose(1, 2)
336
+
337
+ if seq_len % self.k:
338
+ x = F.pad(x, (0, 0, 0, self.k - seq_len % self.k))
339
+
340
+ x = x.view(batch_size, -1, dim * self.k)
341
+
342
+ return self.moe(x)
343
+
344
+ def get_aux_loss(self) -> torch.Tensor:
345
+ if self.moe.last_router_logits is None:
346
+ return torch.tensor(0.0, device=self.moe.router.weight.device)
347
+
348
+ balance = load_balancing_loss(self.moe.last_router_probs, self.num_experts, self.top_k)
349
+ z = z_loss(self.moe.last_router_logits)
350
+
351
+ return self.aux_loss_coef * balance + self.z_loss_coef * z
352
+
353
+
354
+ # =============================================================================
355
+ # QFormer Projector (Granite-style)
356
+ # =============================================================================
357
+
358
+
359
+ class QFormerAudioProjector(nn.Module):
360
+ """
361
+ BLIP-2 QFormer projector with learnable queries.
362
+
363
+ Based on GraniteSpeechEncoderProjector - uses a QFormer model with learnable
364
+ query embeddings to compress and project audio encoder outputs. The audio
365
+ sequence is processed in windows and downsampled via cross-attention.
366
+ """
367
+
368
+ def __init__(self, config):
369
+ """Initialize QFormer projector.
370
+
371
+ Args:
372
+ config: ASRConfig with encoder_dim, llm_dim, qformer_* settings
373
+ """
374
+ super().__init__()
375
+
376
+ encoder_dim = config.encoder_dim
377
+ llm_dim = config.llm_dim
378
+
379
+ # Window and downsampling parameters (Granite defaults: window=15, downsample=5)
380
+ self.window_size = getattr(config, "qformer_window_size", 15)
381
+ self.downsample_rate = getattr(config, "downsample_rate", 5)
382
+ self.num_queries = self.window_size // self.downsample_rate
383
+
384
+ # QFormer hidden size (matches encoder for cross-attention)
385
+ qformer_hidden = getattr(config, "qformer_hidden_size", None) or encoder_dim
386
+ qformer_num_layers = getattr(config, "qformer_num_layers", 2)
387
+ qformer_num_heads = getattr(config, "qformer_num_heads", 16)
388
+ qformer_intermediate = getattr(config, "qformer_intermediate_size", None) or (
389
+ qformer_hidden * 4
390
+ )
391
+
392
+ # Learnable query embeddings (Granite uses std=1.0)
393
+ self.query = nn.Parameter(torch.zeros(1, self.num_queries, qformer_hidden))
394
+ self.query.data.normal_(mean=0.0, std=1.0)
395
+
396
+ # Optional projection if encoder dim != qformer hidden
397
+ if encoder_dim != qformer_hidden:
398
+ self.encoder_proj = nn.Linear(encoder_dim, qformer_hidden, bias=False)
399
+ else:
400
+ self.encoder_proj = None
401
+
402
+ # Configure QFormer to match Granite's exact config
403
+ qformer_config = Blip2QFormerConfig(
404
+ hidden_size=qformer_hidden,
405
+ num_hidden_layers=qformer_num_layers,
406
+ num_attention_heads=qformer_num_heads,
407
+ intermediate_size=qformer_intermediate,
408
+ encoder_hidden_size=qformer_hidden,
409
+ cross_attention_frequency=1,
410
+ # Granite-specific settings
411
+ hidden_act="gelu",
412
+ attention_probs_dropout_prob=0.1,
413
+ hidden_dropout_prob=0.1,
414
+ layer_norm_eps=1e-12,
415
+ initializer_range=0.02,
416
+ )
417
+ self.qformer = AutoModel.from_config(qformer_config)
418
+
419
+ # Final projection to LLM dimension (Granite uses bias=True)
420
+ self.linear = nn.Linear(qformer_hidden, llm_dim)
421
+
422
+ def get_output_length(self, input_length: int) -> int:
423
+ """Calculate output sequence length given input length."""
424
+ # QFormer uses window-based processing with num_queries per window
425
+ nblocks = math.ceil(input_length / self.window_size)
426
+ return nblocks * self.num_queries
427
+
428
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
429
+ """
430
+ Args:
431
+ hidden_states: [batch_size, seq_len, encoder_dim]
432
+
433
+ Returns:
434
+ projected: [batch_size, num_output_tokens, llm_dim]
435
+ """
436
+ batch_size, seq_len, dim = hidden_states.size()
437
+
438
+ # Ensure float dtype for QFormer
439
+ target_dtype = self.query.dtype
440
+ if hidden_states.dtype != target_dtype:
441
+ hidden_states = hidden_states.to(target_dtype)
442
+
443
+ # Optional encoder projection
444
+ if self.encoder_proj is not None:
445
+ hidden_states = self.encoder_proj(hidden_states)
446
+
447
+ # Compute number of windows and pad to fit
448
+ nblocks = math.ceil(seq_len / self.window_size)
449
+ pad = nblocks * self.window_size - seq_len
450
+ if pad > 0:
451
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad), "constant", 0)
452
+
453
+ # Reshape to process each window: [batch*nblocks, window_size, dim]
454
+ effective_batch = batch_size * nblocks
455
+ hidden_states = hidden_states.view(effective_batch, self.window_size, -1)
456
+
457
+ # Expand queries to match batch size
458
+ query_embeds = self.query.expand(effective_batch, -1, -1)
459
+
460
+ # QFormer cross-attention
461
+ query_output = self.qformer(
462
+ query_embeds=query_embeds,
463
+ encoder_hidden_states=hidden_states,
464
+ return_dict=True,
465
+ )
466
+
467
+ # Reshape back: [batch, nblocks * num_queries, hidden]
468
+ output_tokens = nblocks * self.num_queries
469
+ query_proj = query_output.last_hidden_state.view(batch_size, output_tokens, -1)
470
+
471
+ # Project to LLM dimension
472
+ return self.linear(query_proj)
473
+
474
+
475
+ # =============================================================================
476
+ # Projector Registry
477
+ # =============================================================================
478
+
479
+ PROJECTOR_CLASSES = {
480
+ "mlp": MLPAudioProjector,
481
+ "mosa": MOSAProjector,
482
+ "moe": MoEAudioProjector,
483
+ "qformer": QFormerAudioProjector,
484
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33b674fb8444e2553eae8f1b261093371920a28ef75b5c18f4deb3f9217ed0ba
3
+ size 11422834
tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<audio>"
10
+ ],
11
+ "is_local": false,
12
+ "model_max_length": 131072,
13
+ "pad_token": "<|endoftext|>",
14
+ "split_special_tokens": false,
15
+ "tokenizer_class": "Qwen2Tokenizer",
16
+ "unk_token": null
17
+ }