"""Muaalem mini, made to stream: the same weights and layers, but each frame only sees its own chunk and `left` frames before it. Two ways to run it, which must give the same numbers: - `forward`: a whole batch of clips at once, every chunk in parallel. Used for training and evaluation. - `step`: one chunk at a time, carrying a `State` from chunk to chunk. Used by the app (exported to ONNX). What differs from the original model (docs: "What we change in the model"): - Attention in the 24 layers and in the adapter: limited to the chunk and `left` frames before it. - Position tags: this model rotates each frame's *input* to attention by its position before projecting it, so keys can't be cached with old positions. Each step recomputes keys over its window, with positions 0 .. left-1 for the remembered frames and left .. left+chunk-1 for the chunk. Slots before the start of the audio are masked out. - The rest (feed-forward steps, the causal convolutions, the adapter's two stride-2 convolutions, the head) is unchanged; the convolutions keep the frames they need from earlier chunks. """ from __future__ import annotations import json import math from dataclasses import dataclass from pathlib import Path import torch import torch.nn.functional as F import torch.utils.checkpoint from huggingface_hub import snapshot_download from safetensors.torch import load_file from torch import nn from transformers import Wav2Vec2BertConfig, Wav2Vec2BertModel REPO = "sysofwan/hifzguide-muaalem-mini" FILES = [ "config.json", "model.safetensors", "phoneme_vocab.json", "preprocessor_config.json", "LICENSE", "NOTICE.md", ] class MuaalemMini(nn.Module): """Wav2Vec2-BERT encoder + the `phonemes` CTC head (stock transformers classes; the repo's custom code is never run).""" def __init__(self, config: dict): super().__init__() self.encoder = Wav2Vec2BertModel(Wav2Vec2BertConfig(**config)) self.head = nn.Linear( config["output_hidden_size"], config["level_to_vocab_size"]["phonemes"] ) def forward(self, input_features: torch.Tensor) -> torch.Tensor: return self.head(self.encoder(input_features).last_hidden_state) def download() -> Path: return Path(snapshot_download(REPO, allow_patterns=FILES)) def load_muaalem(snapshot: Path) -> MuaalemMini: config = json.loads((snapshot / "config.json").read_text()) for key in ("architectures", "auto_map", "model_type"): config.pop(key, None) model = MuaalemMini(config).eval() renamed = {} for key, value in load_file(snapshot / "model.safetensors").items(): if key.startswith("wav2vec2_bert."): renamed["encoder." + key.removeprefix("wav2vec2_bert.")] = value elif key.startswith("level_to_lm_head.phonemes."): renamed["head." + key.removeprefix("level_to_lm_head.phonemes.")] = value else: raise SystemExit(f"unexpected weight {key}") missing, unexpected = model.load_state_dict(renamed, strict=False) missing = [k for k in missing if not k.endswith("inv_freq")] if missing or unexpected: raise SystemExit(f"missing {missing}, unexpected {unexpected}") return model def vocab(snapshot: Path) -> list[str]: return json.loads((snapshot / "phoneme_vocab.json").read_text())["id_to_char"] @dataclass class State: """What one streaming step hands to the next. attn: (L, B, left, D) each layer's attention input (before rotation) conv: (L, B, K-1, D) each layer's depthwise-conv input a_res, a_att: (B, 1, D) the adapter's two conv inputs, last frame a_attn: (B, left/2, D) the adapter's attention input seen: () frames (50/s) processed so far """ attn: torch.Tensor conv: torch.Tensor a_res: torch.Tensor a_att: torch.Tensor a_attn: torch.Tensor seen: torch.Tensor def tensors(self) -> tuple[torch.Tensor, ...]: return (self.attn, self.conv, self.a_res, self.a_att, self.a_attn, self.seen) def _rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, heads: int) -> torch.Tensor: """Rotary position tags on (..., S, D) with cos/sin (S, d), per head, as Wav2Vec2BertSelfAttention._apply_rotary_embedding does.""" shape = x.shape x = x.reshape(*shape[:-1], heads, shape[-1] // heads) half = x.shape[-1] // 2 turned = torch.cat((-x[..., half:], x[..., :half]), dim=-1) x = x * cos[:, None, :] + turned * sin[:, None, :] return x.reshape(shape) class StreamingMuaalem(nn.Module): def __init__(self, base: MuaalemMini, chunk: int = 32, left: int = 192): super().__init__() if chunk % 2 or left % 2: raise ValueError("chunk and left must be even (the adapter halves the rate)") model = base.encoder self.projection = model.feature_projection self.layers = model.encoder.layers self.adapter = model.adapter.layers[0] self.head = base.head self.chunk = chunk self.left = left config = model.config self.heads = config.num_attention_heads self.dim = config.hidden_size self.kernel = config.conv_depthwise_kernel_size self.register_buffer( "inv_freq", model.encoder.embed_positions.inv_freq.clone(), persistent=False ) self.checkpointing = False # -- position tags --------------------------------------------------- def _cos_sin(self, length: int, device, dtype): t = torch.arange(length, device=device, dtype=torch.float32) freqs = t[:, None] * self.inv_freq[None, :] emb = torch.cat((freqs, freqs), dim=-1) return emb.cos().to(dtype), emb.sin().to(dtype) # -- attention over a chunk and the frames before it ------------------- def _attend(self, attn, query_in, window_in, key_index, query_index, rotary, valid_len): """query_in: (..., C, D) chunk frames; window_in: (..., W, D) the remembered frames then the chunk. key_index (..., W) / query_index (..., C): absolute frame numbers (negative = before the audio). Returns (..., C, D) after the output projection.""" C, W = query_in.shape[-2], window_in.shape[-2] if rotary: cos, sin = self._cos_sin(W, window_in.device, window_in.dtype) keys_in = _rotate(window_in, cos, sin, self.heads) query_in = _rotate(query_in, cos[W - C :], sin[W - C :], self.heads) else: keys_in = window_in lead = query_in.shape[:-2] d = self.dim // self.heads q = attn.linear_q(query_in).reshape(*lead, C, self.heads, d).transpose(-2, -3) k = attn.linear_k(keys_in).reshape(*lead, W, self.heads, d).transpose(-2, -3) v = attn.linear_v(window_in).reshape(*lead, W, self.heads, d).transpose(-2, -3) # Every frame of the window, except slots before the audio began. allowed = (key_index >= 0)[..., None, :].expand(*key_index.shape[:-1], C, W) if valid_len is not None: allowed = allowed & (key_index[..., None, :] < valid_len) # A frame may always see itself (keeps fully padded rows finite). allowed = allowed | (key_index[..., None, :] == query_index[..., :, None]) out = F.scaled_dot_product_attention( q, k, v, attn_mask=allowed.unsqueeze(-3), scale=attn.scaling ) out = out.transpose(-2, -3).reshape(*lead, C, self.dim) return attn.linear_out(out) def _windowed(self, attn, x, chunk, left, lengths, rotary): """All chunks of x (B, T, D) at once: chunk i sees frames [i*chunk - left, (i+1)*chunk).""" B, T, D = x.shape n = math.ceil(T / chunk) padded = F.pad(x, (0, 0, left, n * chunk - T)) windows = padded.unfold(1, left + chunk, chunk).transpose(-1, -2) # (B, n, W, D) queries = padded[:, left:].reshape(B, n, chunk, D) starts = torch.arange(n, device=x.device) * chunk key_index = (starts[:, None] - left + torch.arange(left + chunk, device=x.device)).expand(B, -1, -1) query_index = (starts[:, None] + torch.arange(chunk, device=x.device)).expand(B, -1, -1) valid = lengths.view(B, 1, 1, 1) out = self._attend(attn, queries, windows, key_index, query_index, rotary, valid) return out.reshape(B, n * chunk, D)[:, :T] # -- one conformer layer ----------------------------------------------- def _layer(self, layer, h, attend): residual = h h = layer.ffn1(layer.ffn1_layer_norm(h)) * 0.5 + residual residual = h h = attend(layer.self_attn_layer_norm(h)) + residual residual = h h = residual + self._conv_full(layer.conv_module, h) residual = h h = layer.ffn2(layer.ffn2_layer_norm(h)) * 0.5 + residual return layer.final_layer_norm(h) @staticmethod def _conv_full(conv, h): return conv(h) # -- whole clips, all chunks in parallel (training) -------------------- def forward(self, features: torch.Tensor, lengths: torch.Tensor, chunk: int | None = None, left: int | None = None): """features: (B, T, 160) rescaled frames at 50/s; lengths: (B,) valid frames. Returns logits (B, ceil(T/2), 43) at 25/s and their valid lengths.""" chunk = chunk or self.chunk left = self.left if left is None else left h = self.projection(features)[0] for layer in self.layers: attend = lambda x, layer=layer: self._windowed(layer.self_attn, x, chunk, left, lengths, True) # noqa: E731 if self.checkpointing and self.training: h = torch.utils.checkpoint.checkpoint(self._layer, layer, h, attend, use_reentrant=False) else: h = self._layer(layer, h, attend) out_lengths = (lengths + 1) // 2 h = self._adapter_full(h, lengths, out_lengths, chunk // 2, left // 2) return self.head(h), out_lengths def _adapter_full(self, h, lengths, out_lengths, chunk, left): a = self.adapter B, T, _ = h.shape mask = (torch.arange(T, device=h.device)[None, :] < lengths[:, None]).unsqueeze(-1) residual = a.activation(a.residual_conv((a.residual_layer_norm(h) * mask).transpose(1, 2))).transpose(1, 2) x = a.activation(a.self_attn_conv((a.self_attn_layer_norm(h) * mask).transpose(1, 2))).transpose(1, 2) x = self._windowed(a.self_attn, x, chunk, left, out_lengths, False) + residual return a.ffn(a.ffn_layer_norm(x)) + x # -- one chunk at a time (the app) ------------------------------------- def initial_state(self, batch: int = 1, device=None, dtype=torch.float32) -> State: L, D = len(self.layers), self.dim z = lambda *s: torch.zeros(*s, device=device, dtype=dtype) # noqa: E731 return State( attn=z(L, batch, self.left, D), conv=z(L, batch, self.kernel - 1, D), a_res=z(batch, 1, D), a_att=z(batch, 1, D), a_attn=z(batch, self.left // 2, D), seen=torch.zeros((), dtype=torch.int64, device=device), ) def step(self, features: torch.Tensor, state: State) -> tuple[torch.Tensor, State]: """features: (B, chunk, 160). Returns logits (B, chunk/2, 43).""" C = features.shape[1] left = self.left dev = features.device key_index = state.seen - left + torch.arange(left + C, device=dev) query_index = state.seen + torch.arange(C, device=dev) h = self.projection(features)[0] new_attn, new_conv = [], [] for i, layer in enumerate(self.layers): residual = h h = layer.ffn1(layer.ffn1_layer_norm(h)) * 0.5 + residual residual = h x = layer.self_attn_layer_norm(h) window = torch.cat([state.attn[i], x], dim=1) h = self._attend(layer.self_attn, x, window, key_index, query_index, True, None) + residual new_attn.append(window[:, -left:]) residual = h out, cache = self._conv_step(layer.conv_module, h, state.conv[i]) new_conv.append(cache) h = residual + out residual = h h = layer.ffn2(layer.ffn2_layer_norm(h)) * 0.5 + residual h = layer.final_layer_norm(h) a = self.adapter r_in = torch.cat([state.a_res, a.residual_layer_norm(h)], dim=1) s_in = torch.cat([state.a_att, a.self_attn_layer_norm(h)], dim=1) residual = a.activation(F.conv1d(r_in.transpose(1, 2), a.residual_conv.weight, a.residual_conv.bias, stride=2)).transpose(1, 2) x = a.activation(F.conv1d(s_in.transpose(1, 2), a.self_attn_conv.weight, a.self_attn_conv.bias, stride=2)).transpose(1, 2) half, seen2 = C // 2, state.seen // 2 window = torch.cat([state.a_attn, x], dim=1) k2 = seen2 - left // 2 + torch.arange(left // 2 + half, device=dev) q2 = seen2 + torch.arange(half, device=dev) x = self._attend(a.self_attn, x, window, k2, q2, False, None) + residual x = a.ffn(a.ffn_layer_norm(x)) + x state = State( attn=torch.stack(new_attn), conv=torch.stack(new_conv), a_res=r_in[:, -1:], a_att=s_in[:, -1:], a_attn=window[:, -(left // 2):], seen=state.seen + C, ) return self.head(x), state @staticmethod def _conv_step(conv, h, cache): """The conformer convolution on one chunk, with the K-1 frames of depthwise input carried over from before.""" x = conv.glu(conv.pointwise_conv1(conv.layer_norm(h).transpose(1, 2))) # (B, D, C) x = torch.cat([cache.transpose(1, 2), x], dim=2) new_cache = x[:, :, -cache.shape[1]:].transpose(1, 2) x = conv.depthwise_conv(x) x = conv.depthwise_layer_norm(x.transpose(1, 2)).transpose(1, 2) x = conv.pointwise_conv2(conv.activation(x)) return x.transpose(1, 2), new_cache def greedy(ids, blank: int = 0, previous: int | None = None) -> tuple[list[int], int | None]: """Collapse repeats and drop blanks; `previous` carries the last id across chunks so a letter split over two chunks counts once.""" out = [] for i in ids: i = int(i) if i != previous and i != blank: out.append(i) previous = i return out, previous