Training in progress - step 500
Browse files- asr_config.py +4 -4
- asr_modeling.py +47 -8
- asr_pipeline.py +5 -0
- asr_processing.py +6 -3
- model.safetensors +1 -1
- projectors.py +10 -5
asr_config.py
CHANGED
|
@@ -21,7 +21,7 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 21 |
audio_sample_rate: int = 16000,
|
| 22 |
projector_init_std: float = 0.02,
|
| 23 |
projector_pool_stride: int = 4,
|
| 24 |
-
downsample_rate: int =
|
| 25 |
projector_hidden_dim: Optional[int] = None,
|
| 26 |
projector_type: str = "moe", # "moe", "swiglu", "residual", "shared_moe", "mlp", "qformer"
|
| 27 |
projector_num_layers: int = 2, # Number of layers (for residual projector)
|
|
@@ -32,11 +32,11 @@ class ASRConfig(transformers.PretrainedConfig):
|
|
| 32 |
num_experts_per_tok: int = 2, # Top-k experts per token
|
| 33 |
router_aux_loss_coef: float = 0.01, # Auxiliary loss coefficient for load balancing
|
| 34 |
use_specaugment: bool = True, # Apply SpecAugment during training
|
| 35 |
-
# QFormer-specific configuration
|
| 36 |
-
qformer_window_size: int =
|
| 37 |
qformer_hidden_size: Optional[int] = None, # QFormer hidden size (defaults to encoder_dim)
|
| 38 |
qformer_num_layers: int = 2, # Number of QFormer transformer layers
|
| 39 |
-
qformer_num_heads: int =
|
| 40 |
qformer_intermediate_size: Optional[int] = None, # FFN size (defaults to 4x hidden)
|
| 41 |
label_smoothing: float = 0.0, # Label smoothing for cross-entropy loss
|
| 42 |
inference_diversity_penalty: float = 0.0,
|
|
|
|
| 21 |
audio_sample_rate: int = 16000,
|
| 22 |
projector_init_std: float = 0.02,
|
| 23 |
projector_pool_stride: int = 4,
|
| 24 |
+
downsample_rate: int = 5, # Granite default
|
| 25 |
projector_hidden_dim: Optional[int] = None,
|
| 26 |
projector_type: str = "moe", # "moe", "swiglu", "residual", "shared_moe", "mlp", "qformer"
|
| 27 |
projector_num_layers: int = 2, # Number of layers (for residual projector)
|
|
|
|
| 32 |
num_experts_per_tok: int = 2, # Top-k experts per token
|
| 33 |
router_aux_loss_coef: float = 0.01, # Auxiliary loss coefficient for load balancing
|
| 34 |
use_specaugment: bool = True, # Apply SpecAugment during training
|
| 35 |
+
# QFormer-specific configuration (Granite defaults)
|
| 36 |
+
qformer_window_size: int = 15, # Window size for QFormer processing
|
| 37 |
qformer_hidden_size: Optional[int] = None, # QFormer hidden size (defaults to encoder_dim)
|
| 38 |
qformer_num_layers: int = 2, # Number of QFormer transformer layers
|
| 39 |
+
qformer_num_heads: int = 16, # Number of attention heads in QFormer
|
| 40 |
qformer_intermediate_size: Optional[int] = None, # FFN size (defaults to 4x hidden)
|
| 41 |
label_smoothing: float = 0.0, # Label smoothing for cross-entropy loss
|
| 42 |
inference_diversity_penalty: float = 0.0,
|
asr_modeling.py
CHANGED
|
@@ -316,10 +316,20 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 316 |
|
| 317 |
return input_features
|
| 318 |
|
| 319 |
-
def _encode_audio(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
"""Encode audio and project to LLM embedding space.
|
| 321 |
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
"""
|
| 324 |
# Apply SpecAugment during training (before encoding)
|
| 325 |
audio_features = self._apply_specaugment(audio_features)
|
|
@@ -328,6 +338,14 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 328 |
encoder_out = self.audio_tower(input_features=audio_features)
|
| 329 |
hidden_states = encoder_out.last_hidden_state
|
| 330 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
audio_embeds = self.projector(hidden_states)
|
| 332 |
|
| 333 |
# Flatten: (batch, seq, hidden) -> (batch * seq, hidden)
|
|
@@ -338,6 +356,7 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 338 |
self,
|
| 339 |
input_ids: Optional[torch.Tensor] = None,
|
| 340 |
input_features: Optional[torch.Tensor] = None,
|
|
|
|
| 341 |
attention_mask: Optional[torch.Tensor] = None,
|
| 342 |
position_ids: Optional[torch.Tensor] = None,
|
| 343 |
past_key_values: Optional[torch.Tensor] = None,
|
|
@@ -347,14 +366,19 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 347 |
cache_position: Optional[torch.Tensor] = None,
|
| 348 |
**kwargs,
|
| 349 |
) -> CausalLMOutputWithPast:
|
| 350 |
-
"""Forward pass for training and inference.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
# Get text embeddings if not provided
|
| 352 |
if inputs_embeds is None:
|
| 353 |
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 354 |
|
| 355 |
if input_features is not None and input_ids is not None:
|
| 356 |
# Encode audio -> flattened (total_audio_tokens, hidden_dim)
|
| 357 |
-
audio_embeds = self._encode_audio(input_features)
|
| 358 |
|
| 359 |
# Replace <audio> token placeholders with audio embeddings using masked_scatter
|
| 360 |
audio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)
|
|
@@ -396,14 +420,24 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 396 |
|
| 397 |
return model_inputs
|
| 398 |
|
| 399 |
-
def _get_num_audio_tokens(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
"""Calculate number of audio tokens based on input shape and projector.
|
| 401 |
|
| 402 |
Whisper: input_features shape is (batch, n_mels, mel_len)
|
| 403 |
Encoder output is mel_len // 2 due to stride-2 conv
|
| 404 |
Projector then applies its own downsampling.
|
|
|
|
|
|
|
| 405 |
"""
|
| 406 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
# Whisper encoder halves the sequence length
|
| 408 |
encoder_output_len = mel_len // 2
|
| 409 |
# Use projector's method to get final token count
|
|
@@ -414,6 +448,7 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 414 |
self,
|
| 415 |
input_ids: Optional[torch.Tensor] = None,
|
| 416 |
input_features: Optional[torch.Tensor] = None,
|
|
|
|
| 417 |
attention_mask: Optional[torch.Tensor] = None,
|
| 418 |
system_prompt: Optional[str] = None,
|
| 419 |
**generate_kwargs,
|
|
@@ -423,6 +458,10 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 423 |
Can be called in two ways:
|
| 424 |
1. With input_ids containing <audio> tokens (from processor)
|
| 425 |
2. With just audio, and we build the prompt internally
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
"""
|
| 427 |
if input_features is None:
|
| 428 |
raise ValueError("input_features required for generation")
|
|
@@ -431,11 +470,11 @@ class ASRModel(PreTrainedModel, GenerationMixin):
|
|
| 431 |
batch_size = input_features.shape[0]
|
| 432 |
|
| 433 |
# Encode audio -> flattened embeddings
|
| 434 |
-
audio_embeds = self._encode_audio(input_features)
|
| 435 |
|
| 436 |
# If input_ids not provided, build prompt with correct number of audio tokens
|
| 437 |
if input_ids is None:
|
| 438 |
-
num_audio_tokens = self._get_num_audio_tokens(input_features)
|
| 439 |
audio_placeholder = "<audio>" * num_audio_tokens
|
| 440 |
|
| 441 |
system_prompt = system_prompt or self.system_prompt
|
|
|
|
| 316 |
|
| 317 |
return input_features
|
| 318 |
|
| 319 |
+
def _encode_audio(
|
| 320 |
+
self,
|
| 321 |
+
audio_features: torch.Tensor,
|
| 322 |
+
audio_attention_mask: Optional[torch.Tensor] = None,
|
| 323 |
+
) -> torch.Tensor:
|
| 324 |
"""Encode audio and project to LLM embedding space.
|
| 325 |
|
| 326 |
+
Args:
|
| 327 |
+
audio_features: Mel spectrogram features (batch, n_mels, mel_len)
|
| 328 |
+
audio_attention_mask: Mask indicating real vs padded mel frames (batch, mel_len)
|
| 329 |
+
If provided, encoder output is truncated to actual audio length.
|
| 330 |
+
|
| 331 |
+
Returns:
|
| 332 |
+
Flattened audio embeddings of shape (total_audio_tokens, hidden_dim).
|
| 333 |
"""
|
| 334 |
# Apply SpecAugment during training (before encoding)
|
| 335 |
audio_features = self._apply_specaugment(audio_features)
|
|
|
|
| 338 |
encoder_out = self.audio_tower(input_features=audio_features)
|
| 339 |
hidden_states = encoder_out.last_hidden_state
|
| 340 |
|
| 341 |
+
# Truncate to actual audio length if attention mask provided
|
| 342 |
+
if audio_attention_mask is not None:
|
| 343 |
+
# mel_frames -> encoder_frames (stride-2 conv in Whisper encoder)
|
| 344 |
+
real_encoder_len = audio_attention_mask.sum(dim=-1) // 2
|
| 345 |
+
# For batched inputs, truncate to the max real length in the batch
|
| 346 |
+
max_real_len = real_encoder_len.max().item()
|
| 347 |
+
hidden_states = hidden_states[:, :max_real_len]
|
| 348 |
+
|
| 349 |
audio_embeds = self.projector(hidden_states)
|
| 350 |
|
| 351 |
# Flatten: (batch, seq, hidden) -> (batch * seq, hidden)
|
|
|
|
| 356 |
self,
|
| 357 |
input_ids: Optional[torch.Tensor] = None,
|
| 358 |
input_features: Optional[torch.Tensor] = None,
|
| 359 |
+
audio_attention_mask: Optional[torch.Tensor] = None,
|
| 360 |
attention_mask: Optional[torch.Tensor] = None,
|
| 361 |
position_ids: Optional[torch.Tensor] = None,
|
| 362 |
past_key_values: Optional[torch.Tensor] = None,
|
|
|
|
| 366 |
cache_position: Optional[torch.Tensor] = None,
|
| 367 |
**kwargs,
|
| 368 |
) -> CausalLMOutputWithPast:
|
| 369 |
+
"""Forward pass for training and inference.
|
| 370 |
+
|
| 371 |
+
Args:
|
| 372 |
+
audio_attention_mask: Mask for audio features indicating real vs padded frames.
|
| 373 |
+
If provided, encoder output is truncated to actual audio length.
|
| 374 |
+
"""
|
| 375 |
# Get text embeddings if not provided
|
| 376 |
if inputs_embeds is None:
|
| 377 |
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 378 |
|
| 379 |
if input_features is not None and input_ids is not None:
|
| 380 |
# Encode audio -> flattened (total_audio_tokens, hidden_dim)
|
| 381 |
+
audio_embeds = self._encode_audio(input_features, audio_attention_mask)
|
| 382 |
|
| 383 |
# Replace <audio> token placeholders with audio embeddings using masked_scatter
|
| 384 |
audio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)
|
|
|
|
| 420 |
|
| 421 |
return model_inputs
|
| 422 |
|
| 423 |
+
def _get_num_audio_tokens(
|
| 424 |
+
self,
|
| 425 |
+
input_features: torch.Tensor,
|
| 426 |
+
audio_attention_mask: Optional[torch.Tensor] = None,
|
| 427 |
+
) -> int:
|
| 428 |
"""Calculate number of audio tokens based on input shape and projector.
|
| 429 |
|
| 430 |
Whisper: input_features shape is (batch, n_mels, mel_len)
|
| 431 |
Encoder output is mel_len // 2 due to stride-2 conv
|
| 432 |
Projector then applies its own downsampling.
|
| 433 |
+
|
| 434 |
+
If audio_attention_mask is provided, uses actual audio length instead of padded length.
|
| 435 |
"""
|
| 436 |
+
if audio_attention_mask is not None:
|
| 437 |
+
# Use actual audio length (max in batch for batched inputs)
|
| 438 |
+
mel_len = audio_attention_mask.sum(dim=-1).max().item()
|
| 439 |
+
else:
|
| 440 |
+
mel_len = input_features.shape[-1]
|
| 441 |
# Whisper encoder halves the sequence length
|
| 442 |
encoder_output_len = mel_len // 2
|
| 443 |
# Use projector's method to get final token count
|
|
|
|
| 448 |
self,
|
| 449 |
input_ids: Optional[torch.Tensor] = None,
|
| 450 |
input_features: Optional[torch.Tensor] = None,
|
| 451 |
+
audio_attention_mask: Optional[torch.Tensor] = None,
|
| 452 |
attention_mask: Optional[torch.Tensor] = None,
|
| 453 |
system_prompt: Optional[str] = None,
|
| 454 |
**generate_kwargs,
|
|
|
|
| 458 |
Can be called in two ways:
|
| 459 |
1. With input_ids containing <audio> tokens (from processor)
|
| 460 |
2. With just audio, and we build the prompt internally
|
| 461 |
+
|
| 462 |
+
Args:
|
| 463 |
+
audio_attention_mask: Mask for audio features indicating real vs padded frames.
|
| 464 |
+
If provided, encoder output is truncated to actual audio length.
|
| 465 |
"""
|
| 466 |
if input_features is None:
|
| 467 |
raise ValueError("input_features required for generation")
|
|
|
|
| 470 |
batch_size = input_features.shape[0]
|
| 471 |
|
| 472 |
# Encode audio -> flattened embeddings
|
| 473 |
+
audio_embeds = self._encode_audio(input_features, audio_attention_mask)
|
| 474 |
|
| 475 |
# If input_ids not provided, build prompt with correct number of audio tokens
|
| 476 |
if input_ids is None:
|
| 477 |
+
num_audio_tokens = self._get_num_audio_tokens(input_features, audio_attention_mask)
|
| 478 |
audio_placeholder = "<audio>" * num_audio_tokens
|
| 479 |
|
| 480 |
system_prompt = system_prompt or self.system_prompt
|
asr_pipeline.py
CHANGED
|
@@ -442,13 +442,18 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
|
|
| 442 |
|
| 443 |
if isinstance(model_inputs, dict):
|
| 444 |
input_features = model_inputs.get("input_features")
|
|
|
|
| 445 |
if input_features is not None:
|
| 446 |
input_features = input_features.to(self.model.device)
|
|
|
|
|
|
|
| 447 |
else:
|
| 448 |
input_features = model_inputs.to(self.model.device)
|
|
|
|
| 449 |
|
| 450 |
generated_ids = self.model.generate(
|
| 451 |
input_features=input_features,
|
|
|
|
| 452 |
**generate_kwargs,
|
| 453 |
)
|
| 454 |
|
|
|
|
| 442 |
|
| 443 |
if isinstance(model_inputs, dict):
|
| 444 |
input_features = model_inputs.get("input_features")
|
| 445 |
+
audio_attention_mask = model_inputs.get("attention_mask")
|
| 446 |
if input_features is not None:
|
| 447 |
input_features = input_features.to(self.model.device)
|
| 448 |
+
if audio_attention_mask is not None:
|
| 449 |
+
audio_attention_mask = audio_attention_mask.to(self.model.device)
|
| 450 |
else:
|
| 451 |
input_features = model_inputs.to(self.model.device)
|
| 452 |
+
audio_attention_mask = None
|
| 453 |
|
| 454 |
generated_ids = self.model.generate(
|
| 455 |
input_features=input_features,
|
| 456 |
+
audio_attention_mask=audio_attention_mask,
|
| 457 |
**generate_kwargs,
|
| 458 |
)
|
| 459 |
|
asr_processing.py
CHANGED
|
@@ -51,13 +51,16 @@ class ASRProcessor(ProcessorMixin):
|
|
| 51 |
audio_inputs = self.feature_extractor(
|
| 52 |
audio,
|
| 53 |
sampling_rate=getattr(self.feature_extractor, "sampling_rate", 16000),
|
|
|
|
| 54 |
return_tensors=return_tensors,
|
| 55 |
**kwargs,
|
| 56 |
)
|
| 57 |
result["input_features"] = audio_inputs["input_features"]
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
num_audio_tokens = self.projector.get_output_length(encoder_output_len)
|
| 62 |
else:
|
| 63 |
num_audio_tokens = 0
|
|
|
|
| 51 |
audio_inputs = self.feature_extractor(
|
| 52 |
audio,
|
| 53 |
sampling_rate=getattr(self.feature_extractor, "sampling_rate", 16000),
|
| 54 |
+
return_attention_mask=True,
|
| 55 |
return_tensors=return_tensors,
|
| 56 |
**kwargs,
|
| 57 |
)
|
| 58 |
result["input_features"] = audio_inputs["input_features"]
|
| 59 |
+
result["audio_attention_mask"] = audio_inputs["attention_mask"]
|
| 60 |
+
|
| 61 |
+
# Use actual audio length (from attention mask) for token count
|
| 62 |
+
real_mel_len = audio_inputs["attention_mask"].sum(dim=-1).max().item()
|
| 63 |
+
encoder_output_len = real_mel_len // 2
|
| 64 |
num_audio_tokens = self.projector.get_output_length(encoder_output_len)
|
| 65 |
else:
|
| 66 |
num_audio_tokens = 0
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 110222312
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d6202489b6684a47e4df573ca7d40197cc26cd5347efccc3543770f625514f84
|
| 3 |
size 110222312
|
projectors.py
CHANGED
|
@@ -609,15 +609,14 @@ class QFormerAudioProjector(nn.Module):
|
|
| 609 |
encoder_dim = config.encoder_dim
|
| 610 |
llm_dim = config.llm_dim
|
| 611 |
|
| 612 |
-
# Window and downsampling parameters
|
| 613 |
-
self.window_size = getattr(config, "qformer_window_size",
|
| 614 |
-
self.downsample_rate = getattr(config, "downsample_rate",
|
| 615 |
self.num_queries = self.window_size // self.downsample_rate
|
| 616 |
|
| 617 |
# QFormer hidden size (matches encoder for cross-attention)
|
| 618 |
qformer_hidden = getattr(config, "qformer_hidden_size", None) or encoder_dim
|
| 619 |
qformer_num_layers = getattr(config, "qformer_num_layers", 2)
|
| 620 |
-
# Default heads must divide hidden size evenly (1280 / 16 = 80)
|
| 621 |
qformer_num_heads = getattr(config, "qformer_num_heads", 16)
|
| 622 |
qformer_intermediate = getattr(config, "qformer_intermediate_size", None) or (qformer_hidden * 4)
|
| 623 |
|
|
@@ -631,7 +630,7 @@ class QFormerAudioProjector(nn.Module):
|
|
| 631 |
else:
|
| 632 |
self.encoder_proj = None
|
| 633 |
|
| 634 |
-
# Configure QFormer
|
| 635 |
qformer_config = Blip2QFormerConfig(
|
| 636 |
hidden_size=qformer_hidden,
|
| 637 |
num_hidden_layers=qformer_num_layers,
|
|
@@ -639,6 +638,12 @@ class QFormerAudioProjector(nn.Module):
|
|
| 639 |
intermediate_size=qformer_intermediate,
|
| 640 |
encoder_hidden_size=qformer_hidden,
|
| 641 |
cross_attention_frequency=1,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
)
|
| 643 |
self.qformer = AutoModel.from_config(qformer_config)
|
| 644 |
|
|
|
|
| 609 |
encoder_dim = config.encoder_dim
|
| 610 |
llm_dim = config.llm_dim
|
| 611 |
|
| 612 |
+
# Window and downsampling parameters (Granite defaults: window=15, downsample=5)
|
| 613 |
+
self.window_size = getattr(config, "qformer_window_size", 15)
|
| 614 |
+
self.downsample_rate = getattr(config, "downsample_rate", 5)
|
| 615 |
self.num_queries = self.window_size // self.downsample_rate
|
| 616 |
|
| 617 |
# QFormer hidden size (matches encoder for cross-attention)
|
| 618 |
qformer_hidden = getattr(config, "qformer_hidden_size", None) or encoder_dim
|
| 619 |
qformer_num_layers = getattr(config, "qformer_num_layers", 2)
|
|
|
|
| 620 |
qformer_num_heads = getattr(config, "qformer_num_heads", 16)
|
| 621 |
qformer_intermediate = getattr(config, "qformer_intermediate_size", None) or (qformer_hidden * 4)
|
| 622 |
|
|
|
|
| 630 |
else:
|
| 631 |
self.encoder_proj = None
|
| 632 |
|
| 633 |
+
# Configure QFormer to match Granite's exact config
|
| 634 |
qformer_config = Blip2QFormerConfig(
|
| 635 |
hidden_size=qformer_hidden,
|
| 636 |
num_hidden_layers=qformer_num_layers,
|
|
|
|
| 638 |
intermediate_size=qformer_intermediate,
|
| 639 |
encoder_hidden_size=qformer_hidden,
|
| 640 |
cross_attention_frequency=1,
|
| 641 |
+
# Granite-specific settings
|
| 642 |
+
hidden_act="gelu",
|
| 643 |
+
attention_probs_dropout_prob=0.1,
|
| 644 |
+
hidden_dropout_prob=0.1,
|
| 645 |
+
layer_norm_eps=1e-12,
|
| 646 |
+
initializer_range=0.02,
|
| 647 |
)
|
| 648 |
self.qformer = AutoModel.from_config(qformer_config)
|
| 649 |
|