Automatic Speech Recognition
Transformers
Safetensors
English
asr_model
feature-extraction
asr
speech-recognition
speech-to-text
audio
speech-llm
word-timestamps
speaker-diarization
qwen
granite-speech
custom_code
Run this model with HF Jobs
Run mazesmazes/tiny-audio on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/mazesmazes/tiny-audio. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/mazesmazes/tiny-audio on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use mazesmazes/tiny-audio with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mazesmazes/tiny-audio with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("automatic-speech-recognition", model="mazesmazes/tiny-audio", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("mazesmazes/tiny-audio", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Training in progress - step 1000
Browse filesFiles changed (7)
- alignment.py+6-3
- asr_config.py+16-24
- asr_modeling.py+54-116
- asr_pipeline.py+19-11
- asr_processing.py+3-5
- diarization.py-2
- projectors.py+15-41
119 unmodified lines120121122123124125126127128129130131132133134135119 unmodified linesif move_score >= stay_score:# Token j-1 was emitted at frame t-1token_frames[j - 1].insert(0, t - 1)j -= 1# Always decrement time (monotonic)t -= 1# Handle any remaining tokens at the start (edge case)while j > 0:token_frames[j - 1].insert(0, 0)j -= 1# Convert to spanstoken_spans: list[tuple[int, float, float]] = []for token_idx, frames in enumerate(token_frames):119 unmodified lines120121122123124125126127128129130131132133134135136137138119 unmodified linesif move_score >= stay_score:# Token j-1 was emitted at frame t-1token_frames[j - 1].append(t - 1)j -= 1t -= 1# Handle any remaining tokens at the start (edge case)while j > 0:token_frames[j - 1].append(0)j -= 1# We appended in reverse-time order; restore monotonic orderfor frames in token_frames:frames.reverse()# Convert to spanstoken_spans: list[tuple[int, float, float]] = []for token_idx, frames in enumerate(token_frames):
1 unmodified line23456799 unmodified lines10710810911011111211311436 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781 unmodified lineimport transformersclass ASRConfig(transformers.PretrainedConfig):"""Configuration class for the ASR model.99 unmodified linesself.system_prompt = system_promptself.encoder_dim = encoder_dimself.llm_dim = llm_dim# Default conv layers for Whisper/GLM-ASR: [(pad, kernel, stride), ...]self.encoder_conv_layers = encoder_conv_layers or [(1, 3, 1), (1, 3, 2)]self.audio_sample_rate = audio_sample_rateself.projector_init_std = projector_init_stdself.projector_pool_stride = projector_pool_stride36 unmodified lines]self.freeze_projector = freeze_projector# Generation parameters (use explicit value if provided, else use default)self.num_beams = num_beams if num_beams is not None else generation_defaults["num_beams"]self.max_new_tokens = (max_new_tokens if max_new_tokens is not None else generation_defaults["max_new_tokens"])self.min_new_tokens = (min_new_tokens if min_new_tokens is not None else generation_defaults["min_new_tokens"])self.repetition_penalty = (repetition_penaltyif repetition_penalty is not Noneelse generation_defaults["repetition_penalty"])self.length_penalty = (length_penalty if length_penalty is not None else generation_defaults["length_penalty"])self.no_repeat_ngram_size = (no_repeat_ngram_sizeif no_repeat_ngram_size is not Noneelse generation_defaults["no_repeat_ngram_size"])self.use_cache = use_cache if use_cache is not None else generation_defaults["use_cache"]self.do_sample = do_sampleself.temperature = temperatureself.top_p = top_p1 unmodified line234567891099 unmodified lines11011111211311411511636 unmodified lines1531541551561571581591601611621631641651661671681691701 unmodified lineimport transformers# Default conv layers for Whisper/GLM-ASR audio encoders: [(pad, kernel, stride), ...]DEFAULT_ENCODER_CONV_LAYERS = [(1, 3, 1), (1, 3, 2)]class ASRConfig(transformers.PretrainedConfig):"""Configuration class for the ASR model.99 unmodified linesself.system_prompt = system_promptself.encoder_dim = encoder_dimself.llm_dim = llm_dimself.encoder_conv_layers = encoder_conv_layers or DEFAULT_ENCODER_CONV_LAYERSself.audio_sample_rate = audio_sample_rateself.projector_init_std = projector_init_stdself.projector_pool_stride = projector_pool_stride36 unmodified lines]self.freeze_projector = freeze_projectorexplicit_generation_args = {"num_beams": num_beams,"max_new_tokens": max_new_tokens,"min_new_tokens": min_new_tokens,"repetition_penalty": repetition_penalty,"length_penalty": length_penalty,"no_repeat_ngram_size": no_repeat_ngram_size,"use_cache": use_cache,}for key, default in generation_defaults.items():value = explicit_generation_args[key]setattr(self, key, value if value is not None else default)self.do_sample = do_sampleself.temperature = temperatureself.top_p = top_p
4 unmodified lines5678910111214 unmodified lines272829303132369 unmodified lines4024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614627 unmodified lines4704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035 unmodified lines50951051151251351451553 unmodified lines56957057157257357457577 unmodified lines65365465565665765865987 unmodified lines74774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880964 unmodified lines87487587687787887988015 unmodified lines8968978988999009019029039049059064 unmodified linesimport torchimport torch.nn as nnfrom transformers import (AutoConfig,AutoModel,AutoModelForCausalLM,AutoTokenizer,14 unmodified linesfrom torchaudio.transforms import SpecAugmentclass ASRModel(PreTrainedModel, GenerationMixin):"""Audio-to-text model combining an audio encoder, projector, and language model."""369 unmodified linesdef _encode_audio(self,audio_features: torch.Tensor,audio_attention_mask: torch.Tensor,expected_token_counts: torch.Tensor | None = None,) -> torch.Tensor:"""Encode audio and project to LLM embedding space.Args:audio_features: Mel spectrogram features (batch, n_mels, mel_len)audio_attention_mask: Mask indicating real vs padded mel frames (batch, mel_len)expected_token_counts: Expected number of audio tokens per sample from input_ids.If provided, output will match these counts exactly (padding/truncating as needed).Returns:Flattened audio embeddings of shape (total_audio_tokens, hidden_dim)."""with torch.no_grad():encoder_out = self.audio_tower(input_features=audio_features)hidden_states = encoder_out.last_hidden_state# Project to LLM spaceaudio_embeds = self.projector(hidden_states)# Use expected token counts if provided (from input_ids), otherwise compute from audioif expected_token_counts is not None:token_counts = expected_token_countselse:# Compute per-sample encoder output lengths using conv formulasencoder_lengths = self._compute_encoder_output_lengths(audio_attention_mask)token_counts = torch.tensor([self.projector.get_output_length(int(length.item()))for length in encoder_lengths],device=audio_embeds.device,)# Extract embeddings matching expected token counts per samplebatch_size = audio_embeds.shape[0]hidden_dim = audio_embeds.shape[2]result_embeds = []for i in range(batch_size):count = int(token_counts[i].item())sample_embeds = audio_embeds[i, :count, :] # Take first 'count' embeddings# Pad with zeros if we don't have enough embeddingsif sample_embeds.shape[0] < count:padding = torch.zeros(count - sample_embeds.shape[0],hidden_dim,device=audio_embeds.device,dtype=audio_embeds.dtype,)sample_embeds = torch.cat([sample_embeds, padding], dim=0)result_embeds.append(sample_embeds)return torch.cat(result_embeds, dim=0)def forward(self,7 unmodified lineslabels: Optional[torch.Tensor] = None,use_cache: Optional[bool] = None,cache_position: Optional[torch.Tensor] = None,**kwargs,) -> CausalLMOutputWithPast:"""Forward pass for training and inference."""# Get text embeddings if not providedif inputs_embeds is None:inputs_embeds = self.language_model.get_input_embeddings()(input_ids)if input_features is not None and input_ids is not None:# Apply SpecAugment during training if enabledif self.training and self.spec_augment is not None:input_features = self.spec_augment(input_features)# Count expected audio tokens from input_ids (ground truth from collator)audio_token_counts = (input_ids == self.audio_token_id).sum(dim=-1)# Encode audio -> flattened (total_audio_tokens, hidden_dim)audio_embeds = self._encode_audio(input_features, audio_attention_mask, audio_token_counts)# Replace <audio> token placeholders with audio embeddings using masked_scatteraudio_token_mask = (input_ids == self.audio_token_id).unsqueeze(-1)inputs_embeds = inputs_embeds.masked_scatter(audio_token_mask.to(inputs_embeds.device),audio_embeds.to(inputs_embeds.device, dtype=inputs_embeds.dtype),)# Run through language model (let it compute loss if labels provided)outputs = self.language_model(attention_mask=attention_mask,position_ids=position_ids,5 unmodified lines**kwargs,)# Add auxiliary loss from MoE projectors if availableif outputs.loss is not None and hasattr(self.projector, "get_aux_loss"):aux_loss = self.projector.get_aux_loss()if aux_loss is not None and aux_loss.numel() > 0:53 unmodified linesbatch_size = input_features.shape[0]# Encode audio -> flattened embeddingsaudio_embeds = self._encode_audio(input_features, audio_attention_mask)# If input_ids not provided, build prompt with correct number of audio tokensif input_ids is None:77 unmodified linesbatch_size = input_features.shape[0]# Encode audio -> flattened embeddingsaudio_embeds = self._encode_audio(input_features, audio_attention_mask)# Build prompt with correct number of audio tokensnum_audio_tokens = self._get_num_audio_tokens(audio_attention_mask)87 unmodified linesthread.join()@torch.no_grad()def generate_text_only(self,messages: list[dict[str, str]],max_new_tokens: int = 256,**generate_kwargs,) -> str:"""Generate text using only the LLM (no audio encoding).Used for SIFT-style response generation from metadata prompts.Args:messages: List of chat messages [{"role": "user", "content": "..."}]max_new_tokens: Maximum tokens to generate**generate_kwargs: Additional generation argumentsReturns:Generated text response"""device = next(self.language_model.parameters()).device# Apply chat templateinput_ids = self.tokenizer.apply_chat_template(messages,tokenize=True,add_generation_prompt=True,return_tensors="pt",enable_thinking=False, # Disable Qwen3 thinking mode for ASR).to(device)if input_ids.dim() == 1:input_ids = input_ids.unsqueeze(0)attention_mask = torch.ones_like(input_ids)# Generate using language model directlyoutput = self.language_model.generate(input_ids=input_ids,attention_mask=attention_mask,max_new_tokens=max_new_tokens,do_sample=False,pad_token_id=self.tokenizer.pad_token_id,eos_token_id=self.tokenizer.eos_token_id,**generate_kwargs,)# Decode only the new tokensnew_tokens = output[0, input_ids.shape[1] :]response = self.tokenizer.decode(new_tokens, skip_special_tokens=True)return response.strip()def save_pretrained(self, save_directory: Union[str, Path], **kwargs) -> None:"""Save model, tokenizer, and processor."""import shutilfrom pathlib import Path as PathlibPathsave_dir = PathlibPath(save_directory)save_dir.mkdir(parents=True, exist_ok=True)# Update config with actual vocab size64 unmodified linesjson.dump(processor_config, f, indent=2)# Copy source files for auto-loadingsrc_dir = PathlibPath(__file__).parentfor asr_file in src_dir.glob("asr_*.py"):shutil.copy(asr_file, save_dir / asr_file.name)# Copy projectors module15 unmodified lines# Call parent's push_to_hubreturn super().push_to_hub(repo_id, **kwargs)def create_or_update_model_card(self, output_dir: Union[str, Path]) -> None:"""No-op for model card creation - we use MODEL_CARD.md in repo instead."""pass# Register with transformers Auto classesAutoConfig.register("asr_model", ASRConfig)AutoModel.register(ASRConfig, ASRModel)4 unmodified lines5678910111214 unmodified lines2728293031323334353637383940414243444546474849505152369 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454467 unmodified lines4544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854865 unmodified lines49249349449549649753 unmodified lines55155255355455555655755855956056156256377 unmodified lines64164264364464564664764864965065165265387 unmodified lines74174274374474574674774874975075164 unmodified lines81681781881982082182215 unmodified lines8388398408418428438444 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as F # noqa: N812from transformers import (AutoModel,AutoModelForCausalLM,AutoTokenizer,14 unmodified linesfrom torchaudio.transforms import SpecAugmentdef _gather_audio_embeds(audio_embeds: torch.Tensor, token_counts: torch.Tensor) -> torch.Tensor:"""Flatten per-sample audio embeddings into a packed tensor.For each row i, takes the first ``token_counts[i]`` rows of``audio_embeds[i]`` and concatenates them. If any token count exceeds``audio_embeds.shape[1]``, the deficit is zero-padded.Equivalent to a per-sample slice/cat loop but with O(1) host-devicesyncs per call (one ``max().item()``) instead of one per sample."""_, max_len, _ = audio_embeds.shapeneeded = int(token_counts.max().item())if needed > max_len:audio_embeds = F.pad(audio_embeds, (0, 0, 0, needed - max_len))max_len = neededindices = torch.arange(max_len, device=audio_embeds.device).unsqueeze(0)mask = indices < token_counts.unsqueeze(1)return audio_embeds[mask]class ASRModel(PreTrainedModel, GenerationMixin):"""Audio-to-text model combining an audio encoder, projector, and language model."""369 unmodified linesdef _encode_audio(self,audio_features: torch.Tensor,expected_token_counts: torch.Tensor,) -> torch.Tensor:"""Encode audio features and return flattened embeddings matching expected_token_counts.Args:audio_features: Mel spectrogram features (batch, n_mels, mel_len)expected_token_counts: Per-sample audio token counts as int64 tensor (batch,).Returns:Flattened audio embeddings of shape (sum(expected_token_counts), hidden_dim)."""with torch.no_grad():encoder_out = self.audio_tower(input_features=audio_features)hidden_states = encoder_out.last_hidden_stateaudio_embeds = self.projector(hidden_states)token_counts = expected_token_counts.to(device=audio_embeds.device, dtype=torch.long)return _gather_audio_embeds(audio_embeds, token_counts)def forward(self,7 unmodified lineslabels: Optional[torch.Tensor] = None,use_cache: Optional[bool] = None,cache_position: Optional[torch.Tensor] = None,audio_token_counts: Optional[torch.Tensor] = None,**kwargs,) -> CausalLMOutputWithPast:"""Forward pass for training and inference."""if inputs_embeds is None:inputs_embeds = self.language_model.get_input_embeddings()(input_ids)if input_features is not None and input_ids is not None:if self.training and self.spec_augment is not None:input_features = self.spec_augment(input_features)is_audio_token = input_ids == self.audio_token_idif audio_token_counts is None:audio_token_counts = is_audio_token.sum(dim=-1)else:audio_token_counts = audio_token_counts.to(device=input_ids.device, dtype=torch.long)audio_embeds = self._encode_audio(input_features, audio_token_counts)audio_token_mask = is_audio_token.unsqueeze(-1)inputs_embeds = inputs_embeds.masked_scatter(audio_token_mask.to(inputs_embeds.device),audio_embeds.to(inputs_embeds.device, dtype=inputs_embeds.dtype),)outputs = self.language_model(attention_mask=attention_mask,position_ids=position_ids,5 unmodified lines**kwargs,)if outputs.loss is not None and hasattr(self.projector, "get_aux_loss"):aux_loss = self.projector.get_aux_loss()if aux_loss is not None and aux_loss.numel() > 0:53 unmodified linesbatch_size = input_features.shape[0]# Encode audio -> flattened embeddingsencoder_lengths = self._compute_encoder_output_lengths(audio_attention_mask)token_counts = torch.tensor([self.projector.get_output_length(int(length.item())) for length in encoder_lengths],device=input_features.device,dtype=torch.long,)audio_embeds = self._encode_audio(input_features, token_counts)# If input_ids not provided, build prompt with correct number of audio tokensif input_ids is None:77 unmodified linesbatch_size = input_features.shape[0]# Encode audio -> flattened embeddingsencoder_lengths = self._compute_encoder_output_lengths(audio_attention_mask)token_counts = torch.tensor([self.projector.get_output_length(int(length.item())) for length in encoder_lengths],device=input_features.device,dtype=torch.long,)audio_embeds = self._encode_audio(input_features, token_counts)# Build prompt with correct number of audio tokensnum_audio_tokens = self._get_num_audio_tokens(audio_attention_mask)87 unmodified linesthread.join()def save_pretrained(self, save_directory: Union[str, Path], **kwargs) -> None:"""Save model, tokenizer, and processor."""import shutilsave_dir = Path(save_directory)save_dir.mkdir(parents=True, exist_ok=True)# Update config with actual vocab size64 unmodified linesjson.dump(processor_config, f, indent=2)# Copy source files for auto-loadingsrc_dir = Path(__file__).parentfor asr_file in src_dir.glob("asr_*.py"):shutil.copy(asr_file, save_dir / asr_file.name)# Copy projectors module15 unmodified lines# Call parent's push_to_hubreturn super().push_to_hub(repo_id, **kwargs)# Register with transformers Auto classes# (AutoConfig.register is handled in asr_config.py at module load.)AutoModel.register(ASRConfig, ASRModel)
6 unmodified lines7891011127 unmodified lines202122232425126 unmodified lines15215315415515615715815997 unmodified lines25725825926026126226326416 unmodified lines2812822832842852862872882892902912922932946 unmodified linesimport numpy as npimport torchimport transformerstry:from .alignment import ForcedAligner7 unmodified lines# Re-export for backwards compatibility__all__ = ["ForcedAligner", "SpeakerDiarizer", "ASRPipeline"]class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):"""ASR Pipeline for audio-to-text transcription."""126 unmodified linesdef _extract_audio(self, inputs) -> dict | None:"""Extract audio array from various input formats using HF utilities."""from transformers.pipelines.audio_utils import ffmpeg_readif isinstance(inputs, dict):if "array" in inputs:return {97 unmodified linestext = self.tokenizer.decode(tokens, skip_special_tokens=True).strip()# Strip <think>...</think> tags (Qwen3 doesn't respect /no_think prompt)text = re.sub(r"<think>.*?</think>\s*", "", text, flags=re.DOTALL).strip()# Truncate repetitions at end of texttext = _truncate_repetitions(text)return {"text": text}16 unmodified linesif not text:return text# 1. Truncate repeated characters at end (e.g., "444444" -> "4")char_pattern = re.compile(r"(.)\1{" + str(min_repeats - 1) + r",}$")text = char_pattern.sub(r"\1", text)# 2. Truncate repeated words at end (e.g., "the the the" -> "the")word_pattern = re.compile(r"\b(\w+)(?:\s+\1){" + str(min_repeats - 1) + r",}\s*$", re.IGNORECASE)while word_pattern.search(text):text = word_pattern.sub(r"\1", text)6 unmodified lines789101112137 unmodified lines21222324252627282930313233126 unmodified lines16016116216316416597 unmodified lines26326426526626726826927016 unmodified lines2872882892902912922932942952962972982993003013026 unmodified linesimport numpy as npimport torchimport transformersfrom transformers.pipelines.audio_utils import ffmpeg_readtry:from .alignment import ForcedAligner7 unmodified lines# Re-export for backwards compatibility__all__ = ["ForcedAligner", "SpeakerDiarizer", "ASRPipeline"]_THINK_TAG_RE = re.compile(r"<think>.*?</think>\s*", flags=re.DOTALL)_DEFAULT_MIN_REPEATS = 3_TRAILING_CHAR_RE = re.compile(r"(.)\1{" + str(_DEFAULT_MIN_REPEATS - 1) + r",}$")_TRAILING_WORD_RE = re.compile(r"\b(\w+)(?:\s+\1){" + str(_DEFAULT_MIN_REPEATS - 1) + r",}\s*$", re.IGNORECASE)class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):"""ASR Pipeline for audio-to-text transcription."""126 unmodified linesdef _extract_audio(self, inputs) -> dict | None:"""Extract audio array from various input formats using HF utilities."""if isinstance(inputs, dict):if "array" in inputs:return {97 unmodified linestext = self.tokenizer.decode(tokens, skip_special_tokens=True).strip()# Strip <think>...</think> tags (Qwen3 doesn't respect /no_think prompt)if "<think>" in text:text = _THINK_TAG_RE.sub("", text).strip()text = _truncate_repetitions(text)return {"text": text}16 unmodified linesif not text:return textif min_repeats == _DEFAULT_MIN_REPEATS:char_pattern = _TRAILING_CHAR_REword_pattern = _TRAILING_WORD_REelse:char_pattern = re.compile(r"(.)\1{" + str(min_repeats - 1) + r",}$")word_pattern = re.compile(r"\b(\w+)(?:\s+\1){" + str(min_repeats - 1) + r",}\s*$", re.IGNORECASE)text = char_pattern.sub(r"\1", text)while word_pattern.search(text):text = word_pattern.sub(r"\1", text)
4 unmodified lines56789101112134 unmodified lines181920212223242514 unmodified lines404142434445464 unmodified linesfrom transformers import ProcessorMixintry:from .asr_config import ASRConfigexcept ImportError:from asr_config import ASRConfig # type: ignore[no-redef]class ASRProcessor(ProcessorMixin):4 unmodified linestokenizer_class = "AutoTokenizer"AUDIO_TOKEN = "<audio>"TRANSCRIBE_PROMPT = ""# Default conv layers for Whisper/GLM-ASR: [(pad, kernel, stride), ...]DEFAULT_ENCODER_CONV_LAYERS = [(1, 3, 1), (1, 3, 2)]def __init__(self,14 unmodified linesself.tokenizer = tokenizerself.audio_token_id = tokenizer.convert_tokens_to_ids(self.AUDIO_TOKEN)self.projector = projectorself.encoder_conv_layers = encoder_conv_layers or self.DEFAULT_ENCODER_CONV_LAYERSdef _compute_encoder_output_length(self, mel_length: int) -> int:"""Compute encoder output length using conv layer formulas."""4 unmodified lines56789101112134 unmodified lines18192021222314 unmodified lines383940414243444 unmodified linesfrom transformers import ProcessorMixintry:from .asr_config import DEFAULT_ENCODER_CONV_LAYERS, ASRConfigexcept ImportError:from asr_config import DEFAULT_ENCODER_CONV_LAYERS, ASRConfig # type: ignore[no-redef]class ASRProcessor(ProcessorMixin):4 unmodified linestokenizer_class = "AutoTokenizer"AUDIO_TOKEN = "<audio>"TRANSCRIBE_PROMPT = ""def __init__(self,14 unmodified linesself.tokenizer = tokenizerself.audio_token_id = tokenizer.convert_tokens_to_ids(self.AUDIO_TOKEN)self.projector = projectorself.encoder_conv_layers = encoder_conv_layers or DEFAULT_ENCODER_CONV_LAYERSdef _compute_encoder_output_length(self, mel_length: int) -> int:"""Compute encoder output length using conv layer formulas."""
153 unmodified lines154155156157158159160161153 unmodified linesReturns:Cluster labels of shape [N]"""import warningsif len(embeddings.shape) != 2:raise ValueError(f"Expected 2D array, got shape {embeddings.shape}")153 unmodified lines154155156157158159153 unmodified linesReturns:Cluster labels of shape [N]"""if len(embeddings.shape) != 2:raise ValueError(f"Expected 2D array, got shape {embeddings.shape}")
57 unmodified lines585960616263646566676869705 unmodified lines7677787980817 unmodified lines8990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122158 unmodified lines28128228328428528628728828929029129229357 unmodified linesReturns:Projected features of shape [batch, (seq_len - k) // k + 1, llm_dim]"""batch, seq, dim = x.shape# Truncate to match GLM-ASR: use (seq - k) // k + 1 frames# This drops trailing frames that don't fill a complete k-frame windowout_len = (seq - self.k) // self.k + 1x = x[:, : out_len * self.k, :] # Truncate to exact multiplex = x.reshape(batch, out_len, dim * self.k)x = self.linear_1(x)x = self.norm(x)x = self.act(x)5 unmodified lines# =============================================================================class SimpleAdapter(nn.Module):"""Simple 2-layer GELU adapter (from MOSA paper)."""7 unmodified linesreturn self.fc2(self.act(self.fc1(x)))class SwiGLU(nn.Module):"""SwiGLU activation with gated linear units (used in LLaMA, Mistral, etc.)."""def __init__(self, dim: int, hidden_dim: int, bias: bool = False):super().__init__()self.w1 = nn.Linear(dim, hidden_dim, bias=bias) # Gateself.w2 = nn.Linear(dim, hidden_dim, bias=bias) # Valueself.w3 = nn.Linear(hidden_dim, dim, bias=bias) # Outputdef forward(self, x: torch.Tensor) -> torch.Tensor:return self.w3(F.silu(self.w1(x)) * self.w2(x))class AsymmetricSwiGLU(nn.Module):"""SwiGLU that handles different input and output dimensions."""def __init__(self, in_features: int, hidden_features: int, out_features: int, bias: bool = False):super().__init__()self.w1 = nn.Linear(in_features, hidden_features, bias=bias) # Gateself.w2 = nn.Linear(in_features, hidden_features, bias=bias) # Valueself.w3 = nn.Linear(hidden_features, out_features, bias=bias) # Outputdef forward(self, x: torch.Tensor) -> torch.Tensor:return self.w3(F.silu(self.w1(x)) * self.w2(x))class MOSAProjector(nn.Module):"""MOSA-Base projector: simple 2-layer ReLU router with 4 simple adapters.158 unmodified linesReturns:Projected features of shape [batch, out_len, llm_dim]"""# 1. Frame Stackingbatch, seq, dim = x.shapeout_len = (seq - self.k) // self.k + 1x = x[:, : out_len * self.k, :]x = x.reshape(batch, out_len, dim * self.k)# 2. Normalize stacked input (like main branch SharedMoEBlock)x = self.norm(x)flat_x = x.view(-1, x.size(-1)) # [tokens, in_dim]57 unmodified lines585960616263645 unmodified lines70717273747576777879808182838485867 unmodified lines949596979899158 unmodified lines25825926026126226326426526626757 unmodified linesReturns:Projected features of shape [batch, (seq_len - k) // k + 1, llm_dim]"""x = _frame_stack(x, self.k)x = self.linear_1(x)x = self.norm(x)x = self.act(x)5 unmodified lines# =============================================================================def _frame_stack(x: torch.Tensor, k: int) -> torch.Tensor:"""Stack k adjacent frames along the feature dim.Truncates trailing frames that don't fill a complete k-frame window,matching GLM-ASR's `(seq_len - k) // k + 1` formula."""batch, seq, dim = x.shapeout_len = (seq - k) // k + 1return x[:, : out_len * k, :].reshape(batch, out_len, dim * k)class SimpleAdapter(nn.Module):"""Simple 2-layer GELU adapter (from MOSA paper)."""7 unmodified linesreturn self.fc2(self.act(self.fc1(x)))class MOSAProjector(nn.Module):"""MOSA-Base projector: simple 2-layer ReLU router with 4 simple adapters.158 unmodified linesReturns:Projected features of shape [batch, out_len, llm_dim]"""x = _frame_stack(x, self.k)batch, out_len, _ = x.shape# Normalize stacked input (like main branch SharedMoEBlock)x = self.norm(x)flat_x = x.view(-1, x.size(-1)) # [tokens, in_dim]
alignment.py+6-3
asr_config.py+16-24
asr_modeling.py+54-116
asr_pipeline.py+19-11
asr_processing.py+3-5
diarization.py-2
projectors.py+15-41