Download code/tt_raon/reference/mimi.py from changh95/Raon-Speech-9B: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/reference/mimi.py
- Command line
-
hf download hf://changh95/Raon-Speech-9B/code/tt_raon/reference/mimi.py
-
curl -L -o mimi.py https://huggingface.co/changh95/Raon-Speech-9B/resolve/main/code/tt_raon/reference/mimi.py
18.7 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Clean-room fp32 Mimi codec of Raon (ARCH section 9; transformers 4.57.3 ``MimiModel`` read as a specification): | |
| dec = MimiDecoder(ck, window=250) # 250 keys incl. self; None = full causal (official CPU/sdpa path) | |
| pcm = dec.decode(codes [T, 16]) # offline: [T * 1920] at 24 kHz | |
| st = dec.stream(); pcm_k = st.decode(codes_k) # exact causal streaming (any packet size == offline) | |
| enc = MimiEncoder(ck); codes = enc(wav24) # [ceil(N / 1920), 16] (fp32 required: bf16 flips 21 % of codes) | |
| enc.silence_codes() # encode(1920 zeros)[0] | |
| Decoder per frame: RVQ decode (semantic codebook + 15 acoustic codebooks, each RVQ: sum of codebook rows then its | |
| 1x1 ``output_proj``) -> ``upsample`` depthwise ConvTranspose1d (k4, s2, causal: trim 2 right) -> 8-layer transformer | |
| (LayerNorm eps 1e-5, 8 heads x 64, RoPE 1e4 at 25 Hz positions, causal, optional window: keys j in | |
| (i - window, i], i.e. ``window`` keys incl. the query's own (the official flash path), GELU MLP 512 -> 2048 -> 512 | |
| without biases, LayerScale on both branches) -> | |
| SEANet decoder: causal conv k7 512 -> 1024, then for r in 8, 6, 5, 4: ELU, ConvTranspose1d (C -> C/2, k 2r, s r, | |
| trim r right), residual block (ELU, conv k3 C/2 -> C/4, ELU, conv k1 -> C/2, + x); ELU, conv k3 64 -> 1. | |
| The streaming decoder keeps, per causal conv, the last ``k_eff - 1`` input samples (zeros at the start = the causal | |
| zero padding), per transposed conv the overlap tail of the previous call, and the transformer KV (positions | |
| continue; the window drops keys older than ``window``). This is the true causal streaming DEC must match (the | |
| official ``use_streaming`` path loses history for packets < 3 frames, ARCH section 9). | |
| The encoder (continuation references, silence codes) is the Qwen3-TTS bundle's clean-room Mimi encoder | |
| (``reference/encoders.py`` ``CodecEncoder``, same author, Apache-2.0) with Raon's weights: SEANet (strides 4, 5, | |
| 6, 8), 8-layer transformer (full causal, as the official non-streaming encode), downsample k4 s2 (replicate pad), | |
| split RVQ (semantic + 15 acoustic, nearest code by ``cdist``). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from typing import Dict, List, Optional, Tuple | |
| import torch | |
| import torch.nn.functional as F | |
| from ..config import NUM_CODEBOOKS, SAMPLES_PER_FRAME | |
| from ..weights import stages as ST | |
| from ..weights.source import Checkpoint | |
| D, HEADS, HD, LAYERS = 512, 8, 64, 8 | |
| EPS = 1e-5 | |
| THETA = 1e4 | |
| RATIOS = (8, 6, 5, 4) | |
| SEANET_CONVT = {2: 8, 5: 6, 8: 5, 11: 4} # decoder layer index of each ConvTranspose -> ratio | |
| SEANET_RES = (3, 6, 9, 12) | |
| # ============================================================================================ shared helpers | |
| def _mimi_pad(x: torch.Tensor, left: int, right: int, mode: str) -> torch.Tensor: | |
| if mode in ("constant", "zero", "zeros"): | |
| return F.pad(x, (left, right)) | |
| if mode == "reflect": | |
| length = x.shape[-1] | |
| extra = max(left, right) - length + 1 if length <= max(left, right) else 0 | |
| if extra: | |
| x = F.pad(x, (0, extra)) | |
| y = F.pad(x, (left, right), mode="reflect") | |
| return y[..., : y.shape[-1] - extra] | |
| return F.pad(x, (left, right), mode=mode) | |
| def _mimi_conv(x, w, b, *, stride: int = 1, dilation: int = 1, causal: bool = True, pad_mode: str = "constant"): | |
| """``MimiConv1d.forward`` without a streaming cache (causal: ``k_eff - stride`` left + the extra right padding).""" | |
| k_eff = (w.shape[-1] - 1) * dilation + 1 | |
| pad_total = k_eff - stride | |
| length = x.shape[-1] | |
| n_frames = -(-(length - k_eff + pad_total) // stride) | |
| extra = n_frames * stride + k_eff - pad_total - length | |
| if causal: | |
| left, right = pad_total, extra | |
| else: | |
| right = pad_total // 2 | |
| left, right = pad_total - right, right + extra | |
| return F.conv1d(_mimi_pad(x, left, right, pad_mode), w, b, stride=stride, dilation=dilation) | |
| def convt_full(x: torch.Tensor, w: torch.Tensor, stride: int, groups: int = 1) -> torch.Tensor: | |
| """``F.conv_transpose1d(x, w, None, stride, groups=groups)`` for kernel k = 2 * stride as one matmul + overlap-add | |
| (torch's CPU transposed conv is ~10x slower at these shapes). x [B, Cin, T], w [Cin, Cout / groups, k] -> | |
| [B, Cout, (T + 1) * stride].""" | |
| B, Cin, T = x.shape | |
| k = w.shape[-1] | |
| assert k == 2 * stride, (k, stride) | |
| if groups == 1: | |
| z = torch.einsum("bct,cok->btok", x, w) # [B, T, Cout, k] | |
| else: | |
| assert groups == Cin and w.shape[1] == 1 | |
| z = (x.transpose(1, 2)[..., None] * w[:, 0][None, None]) # [B, T, C, k] | |
| Cout = z.shape[2] | |
| a, b = z[..., :stride], z[..., stride:] # first / second half of every frame's window | |
| y = torch.zeros(B, Cout, (T + 1) * stride, dtype=x.dtype) | |
| y[..., : T * stride] += a.permute(0, 2, 1, 3).reshape(B, Cout, T * stride) | |
| y[..., stride:] += b.permute(0, 2, 1, 3).reshape(B, Cout, T * stride) | |
| return y | |
| def _convt(x, w, b, stride: int, groups: int = 1): | |
| """Causal ``MimiConvTranspose1d``: trim ``k - stride`` on the right.""" | |
| y = F.conv_transpose1d(x, w, b, stride=stride, groups=groups) | |
| return y[..., : y.shape[-1] - (w.shape[-1] - stride)] | |
| def _rotate_half(x: torch.Tensor) -> torch.Tensor: | |
| h = x.shape[-1] // 2 | |
| return torch.cat((-x[..., h:], x[..., :h]), dim=-1) | |
| def _rope(positions: torch.Tensor): | |
| inv = 1.0 / (THETA ** (torch.arange(0, HD, 2, dtype=torch.int64).to(torch.float32) / HD)) | |
| freqs = (inv[:, None] @ positions.to(torch.float32)[None, :]).transpose(0, 1) | |
| emb = torch.cat((freqs, freqs), dim=-1) | |
| return emb.cos()[None, None], emb.sin()[None, None] | |
| def _transformer_layer(w, p: str, h: torch.Tensor, kv: Optional[Tuple[torch.Tensor, torch.Tensor]], cos, sin, | |
| mask: Optional[torch.Tensor]): | |
| """One MimiTransformerLayer on h [1, T, D]; kv = cached (K, V) [1, H, S, hd] (post RoPE) or None.""" | |
| B, T, _ = h.shape | |
| x = F.layer_norm(h, (D,), w[p + "input_layernorm.weight"], w[p + "input_layernorm.bias"], EPS) | |
| q = F.linear(x, w[p + "self_attn.q_proj.weight"]).view(B, T, HEADS, HD).transpose(1, 2) | |
| k = F.linear(x, w[p + "self_attn.k_proj.weight"]).view(B, T, HEADS, HD).transpose(1, 2) | |
| v = F.linear(x, w[p + "self_attn.v_proj.weight"]).view(B, T, HEADS, HD).transpose(1, 2) | |
| q = q * cos + _rotate_half(q) * sin | |
| k = k * cos + _rotate_half(k) * sin | |
| if kv is not None: | |
| k, v = torch.cat([kv[0], k], 2), torch.cat([kv[1], v], 2) | |
| o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) | |
| o = F.linear(o.transpose(1, 2).contiguous().view(B, T, D), w[p + "self_attn.o_proj.weight"]) | |
| h = h + w[p + "self_attn_layer_scale.scale"] * o | |
| x = F.layer_norm(h, (D,), w[p + "post_attention_layernorm.weight"], w[p + "post_attention_layernorm.bias"], EPS) | |
| x = F.linear(F.gelu(F.linear(x, w[p + "mlp.fc1.weight"])), w[p + "mlp.fc2.weight"]) | |
| return h + w[p + "mlp_layer_scale.scale"] * x, (k, v) | |
| def _mask(q_pos: torch.Tensor, k_pos: torch.Tensor, window: Optional[int]) -> torch.Tensor: | |
| """Boolean attention mask [1, 1, Tq, Tk]: causal, and with ``window`` keys i - window < j <= i (``window`` keys | |
| INCLUDING the query's own: the pinned transformers flash path, SPEC section 9 amendment 2026-12-01).""" | |
| ok = k_pos[None, :] <= q_pos[:, None] | |
| if window is not None: | |
| ok &= k_pos[None, :] > q_pos[:, None] - int(window) | |
| return ok[None, None] | |
| # ============================================================================================ decoder | |
| class MimiDecoder: | |
| def __init__(self, ck: Optional[Checkpoint] = None, window: Optional[int] = 250, | |
| weights: Optional[Dict[str, torch.Tensor]] = None): | |
| w = weights if weights is not None else ST.mimi(ck, torch.float32, part="decoder") | |
| self.w = {k: v.float().contiguous() for k, v in w.items()} | |
| self.window = None if window is None or int(window) <= 0 else int(window) | |
| self.books = {} | |
| for q, n in (("semantic", 1), ("acoustic", NUM_CODEBOOKS - 1)): | |
| pre = f"quantizer.{q}_residual_vector_quantizer" | |
| self.books[q] = [(self.w[f"{pre}.layers.{i}.codebook.embed_sum"] | |
| / self.w[f"{pre}.layers.{i}.codebook.cluster_usage"].clamp(min=ST.RVQ_EPS)[:, None]) | |
| for i in range(n)] | |
| # ------------------------------------------------------------------ stages | |
| def rvq(self, codes: torch.Tensor) -> torch.Tensor: | |
| """codes [T, 16] -> latent [1, 512, T] (official split RVQ decode order).""" | |
| c = torch.as_tensor(codes).long().reshape(-1, NUM_CODEBOOKS) | |
| out = None | |
| for q, sl in (("semantic", slice(0, 1)), ("acoustic", slice(1, NUM_CODEBOOKS))): | |
| qs = torch.tensor(0.0) | |
| for i, idx in enumerate(c[:, sl].T): | |
| qs = qs + F.embedding(idx, self.books[q][i]) | |
| y = F.conv1d(qs.T[None], self.w[f"quantizer.{q}_residual_vector_quantizer.output_proj.weight"]) | |
| out = y if out is None else out + y | |
| return out | |
| def upsample(self, x: torch.Tensor) -> torch.Tensor: | |
| return _convt(x, self.w["upsample.conv.weight"], None, stride=2, groups=D) | |
| def transformer(self, h: torch.Tensor) -> torch.Tensor: | |
| """[1, 512, T25] -> [1, T25, 512] (offline).""" | |
| T = h.shape[-1] | |
| pos = torch.arange(T) | |
| cos, sin = _rope(pos) | |
| mask = _mask(pos, pos, self.window) | |
| x = h.transpose(1, 2) | |
| for l in range(LAYERS): | |
| x, _ = _transformer_layer(self.w, f"decoder_transformer.layers.{l}.", x, None, cos, sin, mask) | |
| return x | |
| def _conv(self, x, i, sub: str = ""): | |
| p = f"decoder.layers.{i}.{sub}conv." | |
| return _mimi_conv(x, self.w[p + "weight"], self.w[p + "bias"]) | |
| def seanet(self, x: torch.Tensor, taps: Optional[dict] = None) -> torch.Tensor: | |
| x = self._conv(x, 0) | |
| for i in range(1, 15): | |
| if i in SEANET_CONVT: | |
| p = f"decoder.layers.{i}.conv." | |
| x = _convt(x, self.w[p + "weight"], self.w[p + "bias"], stride=SEANET_CONVT[i]) | |
| elif i in SEANET_RES: | |
| h = self._conv(F.elu(x), i, "block.1.") | |
| x = x + self._conv(F.elu(h), i, "block.3.") | |
| elif i == 14: | |
| x = self._conv(x, 14) | |
| else: | |
| x = F.elu(x) | |
| if taps is not None: | |
| taps[f"seanet.{i}"] = x | |
| return x | |
| def decode(self, codes: torch.Tensor, taps: Optional[dict] = None) -> torch.Tensor: | |
| """codes [T, 16] -> pcm [T * 1920] (offline, one pass).""" | |
| z = self.rvq(codes) | |
| u = self.upsample(z) | |
| t = self.transformer(u) | |
| if taps is not None: | |
| taps.update(rvq_decode=z, upsample=u, decoder_transformer=t) | |
| return self.seanet(t.transpose(1, 2), taps).reshape(-1) | |
| def stream(self) -> "MimiStream": | |
| return MimiStream(self) | |
| class MimiStream: | |
| """Exact causal streaming decoder state (packets of any size concatenate to ``MimiDecoder.decode``).""" | |
| def __init__(self, dec: MimiDecoder): | |
| self.dec = dec | |
| self.reset() | |
| def reset(self) -> None: | |
| self.frames = 0 | |
| self.conv_state: Dict[str, torch.Tensor] = {} | |
| self.convt_tail: Dict[str, torch.Tensor] = {} | |
| self.kv: List[Optional[Tuple[torch.Tensor, torch.Tensor]]] = [None] * LAYERS | |
| def _conv(self, key: str, x: torch.Tensor, w: torch.Tensor, b: Optional[torch.Tensor], dilation: int = 1): | |
| k_eff = (w.shape[-1] - 1) * dilation + 1 | |
| st = self.conv_state.get(key) | |
| if st is None: | |
| st = torch.zeros(x.shape[0], x.shape[1], k_eff - 1) | |
| xx = torch.cat([st, x], -1) | |
| self.conv_state[key] = xx[..., xx.shape[-1] - (k_eff - 1):] if k_eff > 1 else xx[..., :0] | |
| return F.conv1d(xx, w, b, dilation=dilation) | |
| def _convt(self, key: str, x: torch.Tensor, w: torch.Tensor, b: Optional[torch.Tensor], stride: int, | |
| groups: int = 1): | |
| y = convt_full(x, w, stride, groups) # [B, C, (T + 1) * s] for k = 2 s | |
| tail = self.convt_tail.get(key) | |
| ov = w.shape[-1] - stride | |
| if tail is not None: | |
| y[..., :ov] += tail | |
| n = x.shape[-1] * stride | |
| self.convt_tail[key] = y[..., n:n + ov].clone() | |
| out = y[..., :n] | |
| return out + b[None, :, None] if b is not None else out | |
| def decode(self, codes: torch.Tensor) -> torch.Tensor: | |
| dec, w = self.dec, self.dec.w | |
| c = torch.as_tensor(codes).long().reshape(-1, NUM_CODEBOOKS) | |
| n = c.shape[0] | |
| if n == 0: | |
| return torch.zeros(0) | |
| z = dec.rvq(c) | |
| u = self._convt("up", z, w["upsample.conv.weight"], None, 2, groups=D) | |
| T = u.shape[-1] | |
| p0 = 2 * self.frames | |
| qpos = torch.arange(p0, p0 + T) | |
| cos, sin = _rope(qpos) | |
| x = u.transpose(1, 2) | |
| for l in range(LAYERS): | |
| kv = self.kv[l] | |
| S = 0 if kv is None else kv[0].shape[2] | |
| kpos = torch.arange(p0 - S, p0 + T) | |
| x, (k, v) = _transformer_layer(w, f"decoder_transformer.layers.{l}.", x, kv, cos, sin, | |
| _mask(qpos, kpos, dec.window)) | |
| if dec.window is not None and k.shape[2] > dec.window: | |
| k, v = k[:, :, -dec.window:], v[:, :, -dec.window:] | |
| self.kv[l] = (k, v) | |
| x = x.transpose(1, 2) | |
| x = self._conv("l0", x, w["decoder.layers.0.conv.weight"], w["decoder.layers.0.conv.bias"]) | |
| for i in range(1, 15): | |
| if i in SEANET_CONVT: | |
| p = f"decoder.layers.{i}.conv." | |
| x = self._convt(f"l{i}", x, w[p + "weight"], w[p + "bias"], SEANET_CONVT[i]) | |
| elif i in SEANET_RES: | |
| p = f"decoder.layers.{i}.block." | |
| h = self._conv(f"l{i}b1", F.elu(x), w[p + "1.conv.weight"], w[p + "1.conv.bias"]) | |
| x = x + self._conv(f"l{i}b3", F.elu(h), w[p + "3.conv.weight"], w[p + "3.conv.bias"]) | |
| elif i == 14: | |
| x = self._conv("l14", x, w["decoder.layers.14.conv.weight"], w["decoder.layers.14.conv.bias"]) | |
| else: | |
| x = F.elu(x) | |
| self.frames += n | |
| return x.reshape(-1) | |
| # ============================================================================================ encoder | |
| class MimiEncoder: | |
| """Mimi encoder (fp32): 24 kHz waveform -> codes [ceil(N / 1920), 16].""" | |
| def __init__(self, ck: Optional[Checkpoint] = None, weights: Optional[Dict[str, torch.Tensor]] = None): | |
| w = weights if weights is not None else ST.mimi(ck, torch.float32, part="encoder") | |
| self.w = {k: v.float().contiguous() for k, v in w.items()} | |
| self.books = {} | |
| for q, n in (("semantic", 1), ("acoustic", NUM_CODEBOOKS - 1)): | |
| pre = f"quantizer.{q}_residual_vector_quantizer" | |
| self.books[q] = [(self.w[f"{pre}.layers.{i}.codebook.embed_sum"] | |
| / self.w[f"{pre}.layers.{i}.codebook.cluster_usage"].clamp(min=ST.RVQ_EPS)[:, None]) | |
| .contiguous() for i in range(n)] | |
| plan = [(0, "conv", 1)] | |
| idx = 1 | |
| for ratio in reversed(RATIOS): | |
| plan.append((idx, "res", 1)) | |
| plan.append((idx + 2, "down", int(ratio))) | |
| idx += 3 | |
| plan.append((idx + 1, "last", 1)) | |
| self._plan = plan | |
| self._silence = None | |
| def _conv(self, x, name, stride=1, dilation=1, pad_mode="constant"): | |
| return _mimi_conv(x, self.w[f"{name}.conv.weight"], self.w.get(f"{name}.conv.bias"), stride=stride, | |
| dilation=dilation, pad_mode=pad_mode) | |
| def seanet(self, x: torch.Tensor) -> torch.Tensor: | |
| for idx, kind, arg in self._plan: | |
| p = f"encoder.layers.{idx}" | |
| if kind == "conv": | |
| x = self._conv(x, p) | |
| elif kind == "res": | |
| h = self._conv(F.elu(x), f"{p}.block.1", dilation=arg) | |
| x = x + self._conv(F.elu(h), f"{p}.block.3") | |
| else: | |
| x = self._conv(F.elu(x), p, stride=arg) | |
| return x | |
| def transformer(self, h: torch.Tensor) -> torch.Tensor: | |
| """[1, T, 512] -> [1, T, 512], full causal attention (official non-streaming encode).""" | |
| T = h.shape[1] | |
| pos = torch.arange(T) | |
| cos, sin = _rope(pos) | |
| mask = _mask(pos, pos, None) | |
| for l in range(LAYERS): | |
| h, _ = _transformer_layer(self.w, f"encoder_transformer.layers.{l}.", h, None, cos, sin, mask) | |
| return h | |
| def latents(self, wav24: torch.Tensor, taps: Optional[dict] = None) -> torch.Tensor: | |
| x = torch.as_tensor(wav24).float().reshape(1, 1, -1) | |
| z = self.seanet(x) | |
| t = self.transformer(z.transpose(1, 2)).transpose(1, 2) | |
| d = _mimi_conv(t, self.w["downsample.conv.weight"], None, stride=2, pad_mode="replicate") | |
| if taps is not None: | |
| taps.update(seanet_encoder=z, encoder_transformer=t.transpose(1, 2), downsample=d) | |
| return d | |
| def quantize(self, z: torch.Tensor) -> torch.Tensor: | |
| codes = [] | |
| for q in ("semantic", "acoustic"): | |
| pre = f"quantizer.{q}_residual_vector_quantizer" | |
| x = F.conv1d(z, self.w[f"{pre}.input_proj.weight"]) if f"{pre}.input_proj.weight" in self.w else z | |
| res = x.permute(0, 2, 1).reshape(-1, x.shape[1]) | |
| for embed in self.books[q]: | |
| ind = torch.cdist(res[None], embed[None], p=2)[0].argmin(dim=-1) | |
| res = res - F.embedding(ind, embed) | |
| codes.append(ind) | |
| return torch.stack(codes, dim=1) | |
| def __call__(self, wav24: torch.Tensor, taps: Optional[dict] = None) -> torch.Tensor: | |
| n = -(-int(torch.as_tensor(wav24).numel()) // SAMPLES_PER_FRAME) | |
| if n == 0: | |
| raise ValueError("empty waveform") | |
| return self.quantize(self.latents(wav24, taps))[:n].to(torch.int64).contiguous() | |
| def encode_chunked(self, wav24: torch.Tensor, chunk: int = 192000) -> torch.Tensor: | |
| """``tts_continuation``: references longer than ``chunk`` samples are encoded per chunk independently.""" | |
| w = torch.as_tensor(wav24).float().reshape(-1) | |
| if w.numel() <= chunk: | |
| return self(w) | |
| return torch.cat([self(w[o:o + chunk]) for o in range(0, w.numel(), chunk)]) | |
| def silence_codes(self) -> torch.Tensor: | |
| if self._silence is None: | |
| self._silence = self(torch.zeros(SAMPLES_PER_FRAME))[0] | |
| return self._silence | |