Skip to content

Open-source State-of-the-art TTS model which runs on a CPU 😻

Python
86.5 KB
Raw Blame
"""The optional quantised decoder: a distilled student flow, tokens -> mel.

KittenTTS 2 decodes in two stages β€” a flow turns codec tokens into a mel
spectrogram, then a vocoder turns that into audio. This module is an alternative
first stage: a distilled student that runs in a single step with its weights
packed to 4 or 8 bits, cutting the flow from roughly 115 MB to 37 MB. The
tokenizer, speaker encoder and vocoder are untouched and still come from
`s3gen.py`.

The trade is deliberate and worth stating plainly: quantisation shrinks storage
and memory bandwidth, not arithmetic, so this is **not faster** without a kernel
that multiplies in low precision. Quality is also below the default decoder
(measured mel L1 against the teacher: 0.250 versus 0.168 for the dense student),
and voices far from the student's 539-speaker training pool degrade more than the
default decoder's would. Choose it for footprint, not for speed or fidelity.

Weights are loaded pre-quantised. Dequantising and re-quantising a weight is not a
no-op in floating point β€” rounding at a boundary shifts about 10% of weights by
~1e-7, which accumulated over 474 layers moved the mel output by 0.365. The stored
codes are therefore used directly.

Generated by scripts/vendor_student_flow.py; edit that, not this. Derived from
ResembleAI's chatterbox (Apache 2.0), which builds on Alibaba's CosyVoice and
Matcha-TTS, plus the BitNet-style quantised layers.
"""

import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
import logging
import math
from abc import ABC
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from einops import pack, rearrange, repeat
from omegaconf import DictConfig
from torch import sin, pow
from torch.distributions.uniform import Uniform
from torch.nn import Conv1d, ConvTranspose1d, Parameter
from tqdm import tqdm
try:
    from diffusers.models.attention import (
        GEGLU,
        GELU,
        AdaLayerNorm,
        AdaLayerNormZero,
        ApproximateGELU,
    )
except ImportError:
    from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
    from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormZero
from diffusers.models.attention_processor import Attention
try:
    from diffusers.models.lora import LoRACompatibleLinear
except ImportError:
    # LoRACompatibleLinear was removed in diffusers >= 0.32; fall back to plain Linear
    LoRACompatibleLinear = nn.Linear


# ── quantised layers, from bitnet.py ────────────────────────────────────────────


__all__ = [
    "SimpleRMSNorm", "simple_rms_norm", "activation_quant",
    "weight_quant_ternary", "weight_quant_sign", "weight_quant_nbit",
    "BitLinear", "BitConv1d", "convert_to_bitnet", "count_quantised",
]


def simple_rms_norm(x: Tensor, dim: int) -> Tensor:
    """L2-normalise over the last axis and scale by ``dim ** -0.5``."""
    return F.normalize(x, dim=-1) * (dim ** -0.5)


class SimpleRMSNorm(nn.Module):
    """Parameter-free. Kept as a module for API compatibility with zeta."""

    def __init__(self, dim: int):
        super().__init__()
        self.dim = dim
        self.scale = dim ** -0.5

    def forward(self, x: Tensor) -> Tensor:
        return F.normalize(x, dim=-1) * self.scale


def activation_quant(x: Tensor, eps: float = 1e-5) -> Tensor:
    """8-bit per-token quantisation. Scale is divided back out, so this is
    near-identity in magnitude and only the precision changes."""
    scale = 127.0 / x.abs().amax(dim=-1, keepdim=True).clamp(min=eps)
    return (x * scale).round().clamp(-128, 127) / scale


def weight_quant_ternary(w: Tensor, eps: float = 1e-5) -> Tensor:
    """BitNet b1.58: three levels, {-s, 0, +s} with s = mean|w|."""
    scale = 1.0 / w.abs().mean().clamp(min=eps)
    return (w * scale).round().clamp(-1, 1) / scale


def weight_quant_sign(w: Tensor) -> Tensor:
    """BitNet 1-bit: two levels. Binary despite often being called ternary."""
    scale = w.abs().mean()
    return (w - w.mean()).sign() * scale


def weight_quant_nbit(w: Tensor, bits: int, per_channel: bool = True,
                      group_size: int = 0, eps: float = 1e-5) -> Tensor:
    """Uniform signed n-bit weight quantisation.

    Per-channel by default: one scale per output channel rather than one for the
    whole tensor. At 8 bits the difference is small, but at 4 bits a single
    outlier channel otherwise sets the scale for every weight and most of the
    range goes unused. This is the standard choice for 4-bit PTQ.
    """
    qmax = float(2 ** (bits - 1) - 1)
    if group_size:
        # One scale per contiguous run of `group_size` weights within an output
        # channel. Standard for 4-bit LLM quantisation (GPTQ, AWQ use 128) and
        # much finer than per-channel, which for a conv covers in_ch * kernel
        # weights under a single scale.
        shape = w.shape
        flat = w.reshape(shape[0], -1)
        n = flat.shape[1]
        pad = (-n) % group_size
        if pad:
            flat = torch.nn.functional.pad(flat, (0, pad))
        g = flat.reshape(-1, group_size)
        scale = qmax / g.abs().amax(dim=1, keepdim=True).clamp(min=eps)
        q = (g * scale).round().clamp(-qmax - 1, qmax) / scale
        q = q.reshape(shape[0], -1)[:, :n]
        return q.reshape(shape)
    if per_channel:
        flat = w.reshape(w.shape[0], -1)
        scale = qmax / flat.abs().amax(dim=1).clamp(min=eps)
        scale = scale.reshape(-1, *([1] * (w.dim() - 1)))
    else:
        scale = qmax / w.abs().amax().clamp(min=eps)
    return (w * scale).round().clamp(-qmax - 1, qmax) / scale


_WEIGHT_QUANT = {"ternary": weight_quant_ternary, "sign": weight_quant_sign}


_NBIT_RE = re.compile(r"^w(\d+)(_pt)?(?:g(\d+))?(a16)?$")


def _check_mode(mode: str) -> str:
    """Modes: ``ternary``, ``sign``, or ``w<bits>`` (``w4``, ``w8``).

    A ``_pt`` suffix asks for per-tensor scaling instead of per-channel, which is
    only useful for showing why per-channel is the default.
    """
    if mode in _WEIGHT_QUANT or _NBIT_RE.match(mode):
        return mode
    raise ValueError(f"unknown quantise mode {mode!r}")


def _quantise_weight(w: Tensor, mode: str) -> Tensor:
    if mode in _WEIGHT_QUANT:
        return _WEIGHT_QUANT[mode](w)
    m = _NBIT_RE.match(mode)
    return weight_quant_nbit(w, int(m.group(1)), per_channel=m.group(2) is None,
                             group_size=int(m.group(3)) if m.group(3) else 0)


def _quantise_acts(mode: str) -> bool:
    """False for an ``a16`` mode, which leaves activations in full precision."""
    m = _NBIT_RE.match(mode)
    return not (m and m.group(4))


def _ste(x: Tensor, quantised: Tensor) -> Tensor:
    """Forward the quantised value, backprop as if it were the identity."""
    return x + (quantised - x).detach()


class BitLinear(nn.Linear):
    """``nn.Linear`` with quantised weights and 8-bit activations."""

    def __init__(self, in_features, out_features, bias=True,
                 mode: str = "ternary", norm_input: bool = True,
                 prequantised: bool = False, device=None, dtype=None):
        super().__init__(in_features, out_features, bias, device=device, dtype=dtype)
        self.mode = _check_mode(mode)
        self.norm_input = norm_input
        # Set when the stored weight is already on the quantisation grid, as in an
        # exported model. Re-quantising it is *not* a no-op in floating point:
        # dequantise-then-requantise flips ~10 % of weights by ~1e-7, which is
        # enough to move the output noticeably once it accumulates over 474 layers.
        self.prequantised = prequantised

    def forward(self, x: Tensor, scale: float = 1.0) -> Tensor:
        # `scale` exists only so this is a drop-in for diffusers'
        # LoRACompatibleLinear, which some call sites pass it to. There is no LoRA
        # here, so anything other than 1.0 would be silently dropped β€” refuse instead.
        if scale != 1.0:
            raise ValueError(f"BitLinear got scale={scale}; LoRA is not supported")
        x = simple_rms_norm(x, self.in_features) if self.norm_input else x
        x_q = _ste(x, activation_quant(x)) if _quantise_acts(self.mode) else x
        w_q = (self.weight if self.prequantised else
               _ste(self.weight, _quantise_weight(self.weight, self.mode)))
        return F.linear(x_q, w_q, self.bias)

    def extra_repr(self) -> str:
        return f"{super().extra_repr()}, mode={self.mode}"


class BitConv1d(nn.Conv1d):
    """``nn.Conv1d`` with quantised weights and 8-bit activations.

    Input is ``[B, C, T]``; the norm and the activation quantiser both act over the
    channel axis, so the tensor is transposed around them.
    """

    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0,
                 dilation=1, groups=1, bias=True, padding_mode="zeros",
                 mode: str = "ternary", norm_input: bool = True,
                 causal_padding=None, prequantised: bool = False,
                 device=None, dtype=None):
        super().__init__(in_channels, out_channels, kernel_size, stride, padding,
                         dilation, groups, bias, padding_mode,
                         device=device, dtype=dtype)
        self.mode = _check_mode(mode)
        self.norm_input = norm_input
        self.prequantised = prequantised     # see BitLinear
        # Carried over from CausalConv1d, which pads in its forward rather than
        # through nn.Conv1d's padding argument. Dropping it silently shortens the
        # sequence and the model stops assembling.
        self.causal_padding = tuple(causal_padding) if causal_padding else None

    def forward(self, x: Tensor) -> Tensor:
        if self.causal_padding:
            x = F.pad(x, self.causal_padding)
        xt = x.transpose(-1, -2)
        if self.norm_input:
            xt = simple_rms_norm(xt, self.in_channels)
        xq = _ste(xt, activation_quant(xt)) if _quantise_acts(self.mode) else xt
        x_q = xq.transpose(-1, -2)
        w_q = (self.weight if self.prequantised else
               _ste(self.weight, _quantise_weight(self.weight, self.mode)))
        return self._conv_forward(x_q, w_q, self.bias)

    def extra_repr(self) -> str:
        return f"{super().extra_repr()}, mode={self.mode}"


DEFAULT_SKIP = ("final_proj", "input_embedding", "spk_embed_affine_layer")


def _is_plain_linear(m: nn.Module) -> bool:
    """An nn.Linear, or a subclass that behaves exactly like one right now.

    diffusers' LoRACompatibleLinear wraps every transformer feed-forward; with no
    LoRA attached its forward is plain F.linear, and it holds 6.9 M of the
    half-size flow's weights β€” too much to leave dense over a type check.
    """
    if type(m) is nn.Linear:
        return True
    return (isinstance(m, nn.Linear) and not isinstance(m, BitLinear)
            and type(m).__name__ == "LoRACompatibleLinear"
            and getattr(m, "lora_layer", None) is None)


def _is_causal_conv1d(m: nn.Module) -> bool:
    """A Conv1d subclass whose only extra behaviour is a causal pre-pad."""
    return (isinstance(m, nn.Conv1d) and not isinstance(m, BitConv1d)
            and type(m).__name__ == "CausalConv1d"
            and getattr(m, "causal_padding", None) is not None)


def convert_to_bitnet(module: nn.Module, mode: str = "ternary",
                      skip: tuple = DEFAULT_SKIP, norm_input: bool = True,
                      prequantised: bool = False, _prefix: str = "") -> nn.Module:
    """Replace every ``nn.Linear`` / ``nn.Conv1d`` in ``module``, in place.

    Args:
        module: model to convert.
        mode: ``ternary`` or ``sign``.
        skip: names matched against the dotted path of each layer; a layer whose
            path contains any of these substrings is left dense.
        norm_input: apply SimpleRMSNorm to layer inputs, as BitNet specifies.

    Returns the same module, converted.
    """
    for name, child in list(module.named_children()):
        path = f"{_prefix}{name}"
        if any(s in path for s in skip):
            continue
        # Exact type only. Subclasses (CausalConv1d, the tokenizer's _S3Linear /
        # _S3Conv1d) override forward, and replacing them would throw that away.
        # CausalConv1d is handled explicitly below.
        if _is_plain_linear(child):
            new = BitLinear(child.in_features, child.out_features,
                            bias=child.bias is not None, mode=mode,
                            norm_input=norm_input, prequantised=prequantised)
            new.weight.data.copy_(child.weight.data)
            if child.bias is not None:
                new.bias.data.copy_(child.bias.data)
            setattr(module, name, new)
        elif type(child) is nn.Conv1d or _is_causal_conv1d(child):
            new = BitConv1d(child.in_channels, child.out_channels, child.kernel_size,
                            stride=child.stride, padding=child.padding,
                            dilation=child.dilation, groups=child.groups,
                            bias=child.bias is not None,
                            padding_mode=child.padding_mode, mode=mode,
                            norm_input=norm_input, prequantised=prequantised,
                            causal_padding=getattr(child, "causal_padding", None))
            new.weight.data.copy_(child.weight.data)
            if child.bias is not None:
                new.bias.data.copy_(child.bias.data)
            setattr(module, name, new)
        else:
            convert_to_bitnet(child, mode=mode, skip=skip, norm_input=norm_input,
                              prequantised=prequantised, _prefix=f"{path}.")
    return module


def count_quantised(module: nn.Module) -> dict:
    """Parameters that end up quantised versus left dense, and the memory that buys."""
    q = sum(m.weight.numel() for m in module.modules()
            if isinstance(m, (BitLinear, BitConv1d)))
    total = sum(p.numel() for p in module.parameters())
    # ternary needs log2(3) bits per weight; everything else stays fp16
    bits = q * 1.58 + (total - q) * 16
    return dict(total=total, quantised=q, dense=total - q,
                quantised_frac=q / total if total else 0.0,
                mb_fp16=total * 16 / 8 / 2**20, mb_ternary=bits / 8 / 2**20)


# ── student flow architecture, from chatterbox_codec.py ─────────────────────────


logger = logging.getLogger(__name__)


class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self


CFM_PARAMS = AttrDict({
    "sigma_min": 1e-06,
    "solver": "euler",
    "t_scheduler": "cosine",
    "training_cfg_rate": 0.2,
    "inference_cfg_rate": 0.7,
    "reg_loss_type": "l1",
})


class Swish(torch.nn.Module):
    """Swish activation function."""

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x * torch.sigmoid(x)


class PositionalEncoding(torch.nn.Module):
    """Sinusoidal positional encoding."""

    def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000, reverse: bool = False):
        super().__init__()
        self.d_model = d_model
        self.xscale = math.sqrt(self.d_model)
        self.dropout = torch.nn.Dropout(p=dropout_rate)
        self.max_len = max_len

        self.pe = torch.zeros(self.max_len, self.d_model)
        position = torch.arange(0, self.max_len, dtype=torch.float32).unsqueeze(1)
        div_term = torch.exp(
            torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)
        )
        self.pe[:, 0::2] = torch.sin(position * div_term)
        self.pe[:, 1::2] = torch.cos(position * div_term)
        self.pe = self.pe.unsqueeze(0)

    def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
        self.pe = self.pe.to(x.device)
        pos_emb = self.position_encoding(offset, x.size(1), False)
        x = x * self.xscale + pos_emb
        return self.dropout(x), self.dropout(pos_emb)

    def position_encoding(self, offset: Union[int, torch.Tensor], size: int, apply_dropout: bool = True) -> torch.Tensor:
        if isinstance(offset, int):
            assert offset + size <= self.max_len
            pos_emb = self.pe[:, offset:offset + size]
        elif isinstance(offset, torch.Tensor) and offset.dim() == 0:
            assert offset + size <= self.max_len
            pos_emb = self.pe[:, offset:offset + size]
        else:
            assert torch.max(offset) + size <= self.max_len
            index = offset.unsqueeze(1) + torch.arange(0, size).to(offset.device)
            flag = index > 0
            index = index * flag
            pos_emb = F.embedding(index, self.pe[0])
        if apply_dropout:
            pos_emb = self.dropout(pos_emb)
        return pos_emb


class RelPositionalEncoding(PositionalEncoding):
    def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
        super().__init__(d_model, dropout_rate, max_len, reverse=True)

    def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
        self.pe = self.pe.to(x.device)
        x = x * self.xscale
        pos_emb = self.position_encoding(offset, x.size(1), False)
        return self.dropout(x), self.dropout(pos_emb)


class EspnetRelPositionalEncoding(torch.nn.Module):
    """Relative positional encoding (ESPnet style)."""

    def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
        super(EspnetRelPositionalEncoding, self).__init__()
        self.d_model = d_model
        self.xscale = math.sqrt(self.d_model)
        self.dropout = torch.nn.Dropout(p=dropout_rate)
        self.pe = None
        self.extend_pe(torch.tensor(0.0).expand(1, max_len))

    def extend_pe(self, x: torch.Tensor):
        if self.pe is not None:
            if self.pe.size(1) >= x.size(1) * 2 - 1:
                if self.pe.dtype != x.dtype or self.pe.device != x.device:
                    self.pe = self.pe.to(dtype=x.dtype, device=x.device)
                return
        pe_positive = torch.zeros(x.size(1), self.d_model)
        pe_negative = torch.zeros(x.size(1), self.d_model)
        position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
        div_term = torch.exp(
            torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)
        )
        pe_positive[:, 0::2] = torch.sin(position * div_term)
        pe_positive[:, 1::2] = torch.cos(position * div_term)
        pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
        pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
        pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
        pe_negative = pe_negative[1:].unsqueeze(0)
        pe = torch.cat([pe_positive, pe_negative], dim=1)
        self.pe = pe.to(device=x.device, dtype=x.dtype)

    def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
        self.extend_pe(x)
        x = x * self.xscale
        pos_emb = self.position_encoding(size=x.size(1), offset=offset)
        return self.dropout(x), self.dropout(pos_emb)

    def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
        pos_emb = self.pe[
            :,
            self.pe.size(1) // 2 - size + 1: self.pe.size(1) // 2 + size,
        ]
        return pos_emb


class WhisperPositionalEncoding(PositionalEncoding):
    def __init__(self, d_model: int, dropout_rate: float, max_len: int = 1500):
        super().__init__(d_model, dropout_rate, max_len)
        self.xscale = 1.0
        log_timescale_increment = np.log(10000) / (d_model // 2 - 1)
        inv_timescales = torch.exp(-log_timescale_increment * torch.arange(d_model // 2))
        scaled_time = torch.arange(max_len)[:, np.newaxis] * inv_timescales[np.newaxis, :]
        pe = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
        delattr(self, "pe")
        self.register_buffer("pe", pe.unsqueeze(0))


class LearnablePositionalEncoding(PositionalEncoding):
    def __init__(self, d_model: int, dropout_rate: float, max_len: int = 448):
        super().__init__(d_model, dropout_rate, max_len)
        self.pe = torch.nn.Parameter(torch.empty(1, max_len, d_model))
        self.xscale = 1.0


class NoPositionalEncoding(torch.nn.Module):
    def __init__(self, d_model: int, dropout_rate: float):
        super().__init__()
        self.d_model = d_model
        self.dropout = torch.nn.Dropout(p=dropout_rate)

    def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
        pos_emb = torch.zeros(1, x.size(1), self.d_model).to(x.device)
        return self.dropout(x), pos_emb

    def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
        return torch.zeros(1, size, self.d_model)


class BaseSubsampling(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.right_context = 0
        self.subsampling_rate = 1

    def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
        return self.pos_enc.position_encoding(offset, size)


class EmbedinigNoSubsampling(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.embed = torch.nn.Embedding(idim, odim)
        self.pos_enc = pos_enc_class

    def forward(self, x, x_mask, offset=0):
        x = self.embed(x)
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask


class LinearNoSubsampling(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.out = torch.nn.Sequential(
            torch.nn.Linear(idim, odim),
            torch.nn.LayerNorm(odim, eps=1e-5),
            torch.nn.Dropout(dropout_rate),
        )
        self.pos_enc = pos_enc_class
        self.right_context = 0
        self.subsampling_rate = 1

    def forward(self, x, x_mask, offset=0):
        x = self.out(x)
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask


class LegacyLinearNoSubsampling(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.out = torch.nn.Sequential(
            torch.nn.Linear(idim, odim),
            torch.nn.LayerNorm(odim, eps=1e-5),
            torch.nn.Dropout(dropout_rate),
            torch.nn.ReLU(),
        )
        self.pos_enc = pos_enc_class
        self.right_context = 0
        self.subsampling_rate = 1

    def forward(self, x, x_mask, offset=0):
        x = self.out(x)
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask


class Conv1dSubsampling2(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv1d(idim, odim, kernel_size=3, padding=1),
            torch.nn.GELU(),
            torch.nn.Conv1d(odim, odim, kernel_size=3, stride=2, padding=1),
            torch.nn.GELU(),
        )
        self.pos_enc = pos_enc_class
        self.subsampling_rate = 2
        self.right_context = 4

    def forward(self, x, x_mask, offset=0):
        time = x.size(1)
        x = x.transpose(1, 2)
        x = self.conv(x)
        x = x.transpose(1, 2)
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask[:, :, (time + 1) % 2::2]


class Conv2dSubsampling4(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(1, odim, 3, 2),
            torch.nn.ReLU(),
            torch.nn.Conv2d(odim, odim, 3, 2),
            torch.nn.ReLU(),
        )
        self.out = torch.nn.Sequential(
            torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim)
        )
        self.pos_enc = pos_enc_class
        self.subsampling_rate = 4
        self.right_context = 6

    def forward(self, x, x_mask, offset=0):
        x = x.unsqueeze(1)
        x = self.conv(x)
        b, c, t, f = x.size()
        x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2]


class Conv2dSubsampling6(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(1, odim, 3, 2),
            torch.nn.ReLU(),
            torch.nn.Conv2d(odim, odim, 5, 3),
            torch.nn.ReLU(),
        )
        self.linear = torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim)
        self.pos_enc = pos_enc_class
        self.subsampling_rate = 6
        self.right_context = 10

    def forward(self, x, x_mask, offset=0):
        x = x.unsqueeze(1)
        x = self.conv(x)
        b, c, t, f = x.size()
        x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f))
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask[:, :, 2::2][:, :, 4::3]


class Conv2dSubsampling8(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
        super().__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(1, odim, 3, 2),
            torch.nn.ReLU(),
            torch.nn.Conv2d(odim, odim, 3, 2),
            torch.nn.ReLU(),
            torch.nn.Conv2d(odim, odim, 3, 2),
            torch.nn.ReLU(),
        )
        self.linear = torch.nn.Linear(odim * ((((idim - 1) // 2 - 1) // 2 - 1) // 2), odim)
        self.pos_enc = pos_enc_class
        self.subsampling_rate = 8
        self.right_context = 14

    def forward(self, x, x_mask, offset=0):
        x = x.unsqueeze(1)
        x = self.conv(x)
        b, c, t, f = x.size()
        x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f))
        x, pos_emb = self.pos_enc(x, offset)
        return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2][:, :, 2::2]


_ACTIVATION_CLASSES = {
    "hardtanh": torch.nn.Hardtanh,
    "tanh": torch.nn.Tanh,
    "relu": torch.nn.ReLU,
    "selu": torch.nn.SELU,
    "swish": getattr(torch.nn, "SiLU", Swish),
    "gelu": torch.nn.GELU,
}


_SUBSAMPLE_CLASSES = {
    "linear": LinearNoSubsampling,
    "linear_legacy": LegacyLinearNoSubsampling,
    "embed": EmbedinigNoSubsampling,
    "conv1d2": Conv1dSubsampling2,
    "conv2d": Conv2dSubsampling4,
    "conv2d6": Conv2dSubsampling6,
    "conv2d8": Conv2dSubsampling8,
    "paraformer_dummy": torch.nn.Identity,
}


_EMB_CLASSES = {
    "embed": PositionalEncoding,
    "abs_pos": PositionalEncoding,
    "rel_pos": RelPositionalEncoding,
    "rel_pos_espnet": EspnetRelPositionalEncoding,
    "no_pos": NoPositionalEncoding,
    "abs_pos_whisper": WhisperPositionalEncoding,
    "embed_learnable_pe": LearnablePositionalEncoding,
}


_ATTENTION_CLASSES = {
    "selfattn": None,      # filled below after class definition
    "rel_selfattn": None,  # filled below
}


def subsequent_chunk_mask(
    size: int,
    chunk_size: int,
    num_left_chunks: int = -1,
    device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
    pos_idx = torch.arange(size, device=device)
    block_value = (torch.div(pos_idx, chunk_size, rounding_mode='trunc') + 1) * chunk_size
    ret = pos_idx.unsqueeze(0) < block_value.unsqueeze(1)
    return ret


def add_optional_chunk_mask(
    xs: torch.Tensor,
    masks: torch.Tensor,
    use_dynamic_chunk: bool,
    use_dynamic_left_chunk: bool,
    decoding_chunk_size: int,
    static_chunk_size: int,
    num_decoding_left_chunks: int,
    enable_full_context: bool = True,
):
    if use_dynamic_chunk:
        max_len = xs.size(1)
        if decoding_chunk_size < 0:
            chunk_size = max_len
            num_left_chunks = -1
        elif decoding_chunk_size > 0:
            chunk_size = decoding_chunk_size
            num_left_chunks = num_decoding_left_chunks
        else:
            chunk_size = torch.randint(1, max_len, (1,)).item()
            num_left_chunks = -1
            if chunk_size > max_len // 2 and enable_full_context:
                chunk_size = max_len
            else:
                chunk_size = chunk_size % 25 + 1
                if use_dynamic_left_chunk:
                    max_left_chunks = (max_len - 1) // chunk_size
                    num_left_chunks = torch.randint(0, max_left_chunks, (1,)).item()
        chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size, num_left_chunks, xs.device)
        chunk_masks = chunk_masks.unsqueeze(0)
        chunk_masks = masks & chunk_masks
    elif static_chunk_size > 0:
        num_left_chunks = num_decoding_left_chunks
        chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size, num_left_chunks, xs.device)
        chunk_masks = chunk_masks.unsqueeze(0)
        chunk_masks = masks & chunk_masks
    else:
        chunk_masks = masks
    assert chunk_masks.dtype == torch.bool
    if (chunk_masks.sum(dim=-1) == 0).sum().item() != 0:
        logger.warning(
            "get chunk_masks all false at some timestep, force set to true, "
            "make sure they are masked in future computation!"
        )
        chunk_masks[chunk_masks.sum(dim=-1) == 0] = True
    return chunk_masks


def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
    lengths = lengths.long()
    batch_size = lengths.size(0)
    max_len = max_len if max_len > 0 else lengths.max().item()
    seq_range = torch.arange(0, max_len, dtype=torch.int64, device=lengths.device)
    seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
    seq_length_expand = lengths.unsqueeze(-1)
    mask = seq_range_expand >= seq_length_expand
    return mask


def get_intmeanflow_time_mixer(dims: int) -> nn.Linear:
    """Diagonal init as described in 3.3 https://arxiv.org/pdf/2510.07979"""
    layer = nn.Linear(dims * 2, dims, bias=False)
    with torch.no_grad():
        target_weight = torch.zeros(dims, 2 * dims)
        target_weight[:, 0:dims] = torch.eye(dims)
        layer.weight.data = target_weight
    return layer


class MultiHeadedAttention(nn.Module):
    def __init__(self, n_head: int, n_feat: int, dropout_rate: float, key_bias: bool = True):
        super().__init__()
        assert n_feat % n_head == 0
        self.d_k = n_feat // n_head
        self.h = n_head
        self.linear_q = nn.Linear(n_feat, n_feat)
        self.linear_k = nn.Linear(n_feat, n_feat, bias=key_bias)
        self.linear_v = nn.Linear(n_feat, n_feat)
        self.linear_out = nn.Linear(n_feat, n_feat)
        self.dropout = nn.Dropout(p=dropout_rate)

    def forward_qkv(self, query, key, value):
        n_batch = query.size(0)
        q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)
        k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)
        v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)
        q = q.transpose(1, 2)
        k = k.transpose(1, 2)
        v = v.transpose(1, 2)
        return q, k, v

    def forward_attention(self, value, scores, mask=torch.ones((0, 0, 0), dtype=torch.bool)):
        n_batch = value.size(0)
        if mask.size(2) > 0:
            mask = mask.unsqueeze(1).eq(0)
            mask = mask[:, :, :, :scores.size(-1)]
            scores = scores.masked_fill(mask, -float('inf'))
            attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0)
        else:
            attn = torch.softmax(scores, dim=-1)
        p_attn = self.dropout(attn)
        x = torch.matmul(p_attn, value)
        x = x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)
        return self.linear_out(x)

    def forward(
        self,
        query,
        key,
        value,
        mask=torch.ones((0, 0, 0), dtype=torch.bool),
        pos_emb=torch.empty(0),
        cache=torch.zeros((0, 0, 0, 0)),
    ):
        q, k, v = self.forward_qkv(query, key, value)
        if cache.size(0) > 0:
            key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1)
            k = torch.cat([key_cache, k], dim=2)
            v = torch.cat([value_cache, v], dim=2)
        new_cache = torch.cat((k, v), dim=-1)
        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
        return self.forward_attention(v, scores, mask), new_cache


class RelPositionMultiHeadedAttention(MultiHeadedAttention):
    def __init__(self, n_head: int, n_feat: int, dropout_rate: float, key_bias: bool = True):
        super().__init__(n_head, n_feat, dropout_rate, key_bias)
        self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
        self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
        self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
        torch.nn.init.xavier_uniform_(self.pos_bias_u)
        torch.nn.init.xavier_uniform_(self.pos_bias_v)

    def rel_shift(self, x: torch.Tensor) -> torch.Tensor:
        zero_pad = torch.zeros((x.size()[0], x.size()[1], x.size()[2], 1), device=x.device, dtype=x.dtype)
        x_padded = torch.cat([zero_pad, x], dim=-1)
        x_padded = x_padded.view(x.size()[0], x.size()[1], x.size(3) + 1, x.size(2))
        x = x_padded[:, :, 1:].view_as(x)[:, :, :, :x.size(-1) // 2 + 1]
        return x

    def forward(
        self,
        query,
        key,
        value,
        mask=torch.ones((0, 0, 0), dtype=torch.bool),
        pos_emb=torch.empty(0),
        cache=torch.zeros((0, 0, 0, 0)),
    ):
        q, k, v = self.forward_qkv(query, key, value)
        q = q.transpose(1, 2)
        if cache.size(0) > 0:
            key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1)
            k = torch.cat([key_cache, k], dim=2)
            v = torch.cat([value_cache, v], dim=2)
        new_cache = torch.cat((k, v), dim=-1)
        n_batch_pos = pos_emb.size(0)
        p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
        p = p.transpose(1, 2)
        q_with_bias_u = (q + self.pos_bias_u.to(q.device)).transpose(1, 2)
        q_with_bias_v = (q + self.pos_bias_v.to(q.device)).transpose(1, 2)
        matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
        matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
        if matrix_ac.shape != matrix_bd.shape:
            matrix_bd = self.rel_shift(matrix_bd)
        scores = (matrix_ac + matrix_bd) / math.sqrt(self.d_k)
        return self.forward_attention(v, scores, mask), new_cache


class ConvolutionModule(nn.Module):
    def __init__(self, channels: int, kernel_size: int = 15, activation: nn.Module = nn.ReLU(),
                 norm: str = "batch_norm", causal: bool = False, bias: bool = True):
        super().__init__()
        self.pointwise_conv1 = nn.Conv1d(channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)
        if causal:
            padding = 0
            self.lorder = kernel_size - 1
        else:
            assert (kernel_size - 1) % 2 == 0
            padding = (kernel_size - 1) // 2
            self.lorder = 0
        self.depthwise_conv = nn.Conv1d(
            channels, channels, kernel_size, stride=1, padding=padding, groups=channels, bias=bias
        )
        assert norm in ['batch_norm', 'layer_norm']
        if norm == "batch_norm":
            self.use_layer_norm = False
            self.norm = nn.BatchNorm1d(channels)
        else:
            self.use_layer_norm = True
            self.norm = nn.LayerNorm(channels)
        self.pointwise_conv2 = nn.Conv1d(channels, channels, kernel_size=1, stride=1, padding=0, bias=bias)
        self.activation = activation

    def forward(
        self,
        x: torch.Tensor,
        mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
        cache: torch.Tensor = torch.zeros((0, 0, 0)),
    ):
        x = x.transpose(1, 2)
        if mask_pad.size(2) > 0:
            x.masked_fill_(~mask_pad, 0.0)
        if self.lorder > 0:
            if cache.size(2) == 0:
                x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
            else:
                assert cache.size(0) == x.size(0)
                assert cache.size(1) == x.size(1)
                x = torch.cat((cache, x), dim=2)
            assert (x.size(2) > self.lorder)
            new_cache = x[:, :, -self.lorder:]
        else:
            new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
        x = self.pointwise_conv1(x)
        x = nn.functional.glu(x, dim=1)
        x = self.depthwise_conv(x)
        if self.use_layer_norm:
            x = x.transpose(1, 2)
        x = self.activation(self.norm(x))
        if self.use_layer_norm:
            x = x.transpose(1, 2)
        x = self.pointwise_conv2(x)
        if mask_pad.size(2) > 0:
            x.masked_fill_(~mask_pad, 0.0)
        return x.transpose(1, 2), new_cache


class PositionwiseFeedForward(torch.nn.Module):
    def __init__(self, idim: int, hidden_units: int, dropout_rate: float,
                 activation: torch.nn.Module = torch.nn.ReLU()):
        super(PositionwiseFeedForward, self).__init__()
        self.w_1 = torch.nn.Linear(idim, hidden_units)
        self.activation = activation
        self.dropout = torch.nn.Dropout(dropout_rate)
        self.w_2 = torch.nn.Linear(hidden_units, idim)

    def forward(self, xs: torch.Tensor) -> torch.Tensor:
        return self.w_2(self.dropout(self.activation(self.w_1(xs))))


class ConformerEncoderLayer(nn.Module):
    def __init__(self, size, self_attn, feed_forward=None, feed_forward_macaron=None,
                 conv_module=None, dropout_rate=0.1, normalize_before=True):
        super().__init__()
        self.self_attn = self_attn
        self.feed_forward = feed_forward
        self.feed_forward_macaron = feed_forward_macaron
        self.conv_module = conv_module
        self.norm_ff = nn.LayerNorm(size, eps=1e-12)
        self.norm_mha = nn.LayerNorm(size, eps=1e-12)
        if feed_forward_macaron is not None:
            self.norm_ff_macaron = nn.LayerNorm(size, eps=1e-12)
            self.ff_scale = 0.5
        else:
            self.ff_scale = 1.0
        if self.conv_module is not None:
            self.norm_conv = nn.LayerNorm(size, eps=1e-12)
            self.norm_final = nn.LayerNorm(size, eps=1e-12)
        self.dropout = nn.Dropout(dropout_rate)
        self.size = size
        self.normalize_before = normalize_before

    def forward(self, x, mask, pos_emb, mask_pad=torch.ones((0, 0, 0), dtype=torch.bool),
                att_cache=torch.zeros((0, 0, 0, 0)), cnn_cache=torch.zeros((0, 0, 0, 0))):
        if self.feed_forward_macaron is not None:
            residual = x
            if self.normalize_before:
                x = self.norm_ff_macaron(x)
            x = residual + self.ff_scale * self.dropout(self.feed_forward_macaron(x))
            if not self.normalize_before:
                x = self.norm_ff_macaron(x)
        residual = x
        if self.normalize_before:
            x = self.norm_mha(x)
        x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb, att_cache)
        x = residual + self.dropout(x_att)
        if not self.normalize_before:
            x = self.norm_mha(x)
        new_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
        if self.conv_module is not None:
            residual = x
            if self.normalize_before:
                x = self.norm_conv(x)
            x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
            x = residual + self.dropout(x)
            if not self.normalize_before:
                x = self.norm_conv(x)
        residual = x
        if self.normalize_before:
            x = self.norm_ff(x)
        x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
        if not self.normalize_before:
            x = self.norm_ff(x)
        if self.conv_module is not None:
            x = self.norm_final(x)
        return x, mask, new_att_cache, new_cnn_cache


class _EncoderUpsample1D(nn.Module):
    def __init__(self, channels: int, out_channels: int, stride: int = 2):
        super().__init__()
        self.channels = channels
        self.out_channels = out_channels
        self.stride = stride
        self.conv = nn.Conv1d(self.channels, self.out_channels, stride * 2 + 1, stride=1, padding=0)

    def forward(self, inputs: torch.Tensor, input_lengths: torch.Tensor):
        outputs = F.interpolate(inputs, scale_factor=float(self.stride), mode="nearest")
        outputs = F.pad(outputs, (self.stride * 2, 0), value=0.0)
        outputs = self.conv(outputs)
        return outputs, input_lengths * self.stride


class PreLookaheadLayer(nn.Module):
    def __init__(self, channels: int, pre_lookahead_len: int = 1):
        super().__init__()
        self.channels = channels
        self.pre_lookahead_len = pre_lookahead_len
        self.conv1 = nn.Conv1d(channels, channels, kernel_size=pre_lookahead_len + 1, stride=1, padding=0)
        self.conv2 = nn.Conv1d(channels, channels, kernel_size=3, stride=1, padding=0)

    def forward(self, inputs: torch.Tensor) -> torch.Tensor:
        outputs = inputs.transpose(1, 2).contiguous()
        outputs = F.pad(outputs, (0, self.pre_lookahead_len), mode='constant', value=0.0)
        outputs = F.leaky_relu(self.conv1(outputs))
        outputs = F.pad(outputs, (2, 0), mode='constant', value=0.0)
        outputs = self.conv2(outputs)
        outputs = outputs.transpose(1, 2).contiguous()
        outputs = outputs + inputs
        return outputs


class UpsampleConformerEncoder(torch.nn.Module):
    def __init__(
        self,
        input_size: int = 512,
        output_size: int = 512,
        attention_heads: int = 8,
        linear_units: int = 2048,
        num_blocks: int = 6,
        dropout_rate: float = 0.1,
        positional_dropout_rate: float = 0.1,
        attention_dropout_rate: float = 0.1,
        input_layer: str = "linear",
        pos_enc_layer_type: str = "rel_pos_espnet",
        normalize_before: bool = True,
        static_chunk_size: int = 0,
        use_dynamic_chunk: bool = False,
        global_cmvn: torch.nn.Module = None,
        use_dynamic_left_chunk: bool = False,
        positionwise_conv_kernel_size: int = 1,
        macaron_style: bool = False,
        selfattention_layer_type: str = "rel_selfattn",
        activation_type: str = "swish",
        use_cnn_module: bool = False,
        cnn_module_kernel: int = 15,
        causal: bool = False,
        cnn_module_norm: str = "batch_norm",
        key_bias: bool = True,
        gradient_checkpointing: bool = False,
        num_up_blocks: int = 4,
    ):
        super().__init__()
        self._output_size = output_size
        self.global_cmvn = global_cmvn
        self.embed = _SUBSAMPLE_CLASSES[input_layer](
            input_size,
            output_size,
            dropout_rate,
            _EMB_CLASSES[pos_enc_layer_type](output_size, positional_dropout_rate),
        )
        self.normalize_before = normalize_before
        self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5)
        self.static_chunk_size = static_chunk_size
        self.use_dynamic_chunk = use_dynamic_chunk
        self.use_dynamic_left_chunk = use_dynamic_left_chunk
        self.gradient_checkpointing = gradient_checkpointing
        activation = _ACTIVATION_CLASSES[activation_type]()
        encoder_selfattn_layer_args = (attention_heads, output_size, attention_dropout_rate, key_bias)
        positionwise_layer_args = (output_size, linear_units, dropout_rate, activation)
        convolution_layer_args = (output_size, cnn_module_kernel, activation, cnn_module_norm, causal)
        self.pre_lookahead_layer = PreLookaheadLayer(channels=output_size, pre_lookahead_len=3)
        self.encoders = torch.nn.ModuleList([
            ConformerEncoderLayer(
                output_size,
                _ATTENTION_CLASSES[selfattention_layer_type](*encoder_selfattn_layer_args),
                PositionwiseFeedForward(*positionwise_layer_args),
                PositionwiseFeedForward(*positionwise_layer_args) if macaron_style else None,
                ConvolutionModule(*convolution_layer_args) if use_cnn_module else None,
                dropout_rate,
                normalize_before,
            ) for _ in range(num_blocks)
        ])
        self.up_layer = _EncoderUpsample1D(channels=output_size, out_channels=output_size, stride=2)
        self.up_embed = _SUBSAMPLE_CLASSES[input_layer](
            input_size,
            output_size,
            dropout_rate,
            _EMB_CLASSES[pos_enc_layer_type](output_size, positional_dropout_rate),
        )
        self.up_encoders = torch.nn.ModuleList([
            ConformerEncoderLayer(
                output_size,
                _ATTENTION_CLASSES[selfattention_layer_type](*encoder_selfattn_layer_args),
                PositionwiseFeedForward(*positionwise_layer_args),
                PositionwiseFeedForward(*positionwise_layer_args) if macaron_style else None,
                ConvolutionModule(*convolution_layer_args) if use_cnn_module else None,
                dropout_rate,
                normalize_before,
            ) for _ in range(num_up_blocks)
        ])

    def output_size(self) -> int:
        return self._output_size

    def forward(self, xs: torch.Tensor, xs_lens: torch.Tensor,
                decoding_chunk_size: int = 0, num_decoding_left_chunks: int = -1):
        T = xs.size(1)
        masks = ~make_pad_mask(xs_lens, T).unsqueeze(1)
        if self.global_cmvn is not None:
            xs = self.global_cmvn(xs)
        xs, pos_emb, masks = self.embed(xs, masks)
        mask_pad = masks
        chunk_masks = add_optional_chunk_mask(
            xs, masks, self.use_dynamic_chunk, self.use_dynamic_left_chunk,
            decoding_chunk_size, self.static_chunk_size, num_decoding_left_chunks
        )
        xs = self.pre_lookahead_layer(xs)
        xs = self._forward_layers(xs, chunk_masks, pos_emb, mask_pad)
        xs = xs.transpose(1, 2).contiguous()
        xs, xs_lens = self.up_layer(xs, xs_lens)
        xs = xs.transpose(1, 2).contiguous()
        T = xs.size(1)
        masks = ~make_pad_mask(xs_lens, T).unsqueeze(1)
        xs, pos_emb, masks = self.up_embed(xs, masks)
        mask_pad = masks
        chunk_masks = add_optional_chunk_mask(
            xs, masks, self.use_dynamic_chunk, self.use_dynamic_left_chunk,
            decoding_chunk_size, self.static_chunk_size * self.up_layer.stride, num_decoding_left_chunks
        )
        xs = self._forward_up_layers(xs, chunk_masks, pos_emb, mask_pad)
        if self.normalize_before:
            xs = self.after_norm(xs)
        return xs, masks

    def _forward_layers(self, xs, chunk_masks, pos_emb, mask_pad):
        for layer in self.encoders:
            xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
        return xs

    def _forward_up_layers(self, xs, chunk_masks, pos_emb, mask_pad):
        for layer in self.up_encoders:
            xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
        return xs


class SnakeBeta(nn.Module):
    def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
        super().__init__()
        self.in_features = out_features if isinstance(out_features, list) else [out_features]
        self.proj = LoRACompatibleLinear(in_features, out_features)
        self.alpha_logscale = alpha_logscale
        if self.alpha_logscale:
            self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
            self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
        else:
            self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
            self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
        self.alpha.requires_grad = alpha_trainable
        self.beta.requires_grad = alpha_trainable
        self.no_div_by_zero = 0.000000001

    def forward(self, x):
        x = self.proj(x)
        if self.alpha_logscale:
            alpha = torch.exp(self.alpha)
            beta = torch.exp(self.beta)
        else:
            alpha = self.alpha
            beta = self.beta
        x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
        return x


class _MatchaFeedForward(nn.Module):
    def __init__(self, dim: int, dim_out: Optional[int] = None, mult: int = 4,
                 dropout: float = 0.0, activation_fn: str = "geglu", final_dropout: bool = False):
        super().__init__()
        inner_dim = int(dim * mult)
        dim_out = dim_out if dim_out is not None else dim
        if activation_fn == "gelu":
            act_fn = GELU(dim, inner_dim)
        if activation_fn == "gelu-approximate":
            act_fn = GELU(dim, inner_dim, approximate="tanh")
        elif activation_fn == "geglu":
            act_fn = GEGLU(dim, inner_dim)
        elif activation_fn == "geglu-approximate":
            act_fn = ApproximateGELU(dim, inner_dim)
        elif activation_fn == "snakebeta":
            act_fn = SnakeBeta(dim, inner_dim)
        self.net = nn.ModuleList([])
        self.net.append(act_fn)
        self.net.append(nn.Dropout(dropout))
        self.net.append(LoRACompatibleLinear(inner_dim, dim_out))
        if final_dropout:
            self.net.append(nn.Dropout(dropout))

    def forward(self, hidden_states):
        for module in self.net:
            hidden_states = module(hidden_states)
        return hidden_states


class BasicTransformerBlock(nn.Module):
    def __init__(
        self,
        dim: int,
        num_attention_heads: int,
        attention_head_dim: int,
        dropout=0.0,
        cross_attention_dim: Optional[int] = None,
        activation_fn: str = "geglu",
        num_embeds_ada_norm: Optional[int] = None,
        attention_bias: bool = False,
        only_cross_attention: bool = False,
        double_self_attention: bool = False,
        upcast_attention: bool = False,
        norm_elementwise_affine: bool = True,
        norm_type: str = "layer_norm",
        final_dropout: bool = False,
    ):
        super().__init__()
        self.only_cross_attention = only_cross_attention
        self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
        self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"

        if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
            raise ValueError(
                f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined."
            )
        if self.use_ada_layer_norm:
            self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
        elif self.use_ada_layer_norm_zero:
            self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
        else:
            self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
        self.attn1 = Attention(
            query_dim=dim,
            heads=num_attention_heads,
            dim_head=attention_head_dim,
            dropout=dropout,
            bias=attention_bias,
            cross_attention_dim=cross_attention_dim if only_cross_attention else None,
            upcast_attention=upcast_attention,
        )
        if cross_attention_dim is not None or double_self_attention:
            self.norm2 = (
                AdaLayerNorm(dim, num_embeds_ada_norm)
                if self.use_ada_layer_norm
                else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
            )
            self.attn2 = Attention(
                query_dim=dim,
                cross_attention_dim=cross_attention_dim if not double_self_attention else None,
                heads=num_attention_heads,
                dim_head=attention_head_dim,
                dropout=dropout,
                bias=attention_bias,
                upcast_attention=upcast_attention,
            )
        else:
            self.norm2 = None
            self.attn2 = None
        self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
        self.ff = _MatchaFeedForward(dim, dropout=dropout, activation_fn=activation_fn,
                                     final_dropout=final_dropout)
        self._chunk_size = None
        self._chunk_dim = 0

    def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
        self._chunk_size = chunk_size
        self._chunk_dim = dim

    def forward(
        self,
        hidden_states: torch.FloatTensor,
        attention_mask: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
        timestep: Optional[torch.LongTensor] = None,
        cross_attention_kwargs: Dict[str, Any] = None,
        class_labels: Optional[torch.LongTensor] = None,
    ):
        if self.use_ada_layer_norm:
            norm_hidden_states = self.norm1(hidden_states, timestep)
        elif self.use_ada_layer_norm_zero:
            norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
                hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
            )
        else:
            norm_hidden_states = self.norm1(hidden_states)

        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
        attn_output = self.attn1(
            norm_hidden_states,
            encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
            attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
            **cross_attention_kwargs,
        )
        if self.use_ada_layer_norm_zero:
            attn_output = gate_msa.unsqueeze(1) * attn_output
        hidden_states = attn_output + hidden_states

        if self.attn2 is not None:
            norm_hidden_states = (
                self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
            )
            attn_output = self.attn2(
                norm_hidden_states,
                encoder_hidden_states=encoder_hidden_states,
                attention_mask=encoder_attention_mask,
                **cross_attention_kwargs,
            )
            hidden_states = attn_output + hidden_states

        norm_hidden_states = self.norm3(hidden_states)
        if self.use_ada_layer_norm_zero:
            norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

        if self._chunk_size is not None:
            if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
                raise ValueError(
                    f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} "
                    f"has to be divisible by chunk size: {self._chunk_size}."
                )
            num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
            ff_output = torch.cat(
                [self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
                dim=self._chunk_dim,
            )
        else:
            ff_output = self.ff(norm_hidden_states)

        if self.use_ada_layer_norm_zero:
            ff_output = gate_mlp.unsqueeze(1) * ff_output
        hidden_states = ff_output + hidden_states
        return hidden_states


class SinusoidalPosEmb(torch.nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim
        assert self.dim % 2 == 0

    def forward(self, x, scale=1000):
        if x.ndim < 1:
            x = x.unsqueeze(0)
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
        emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb


class Block1D(torch.nn.Module):
    def __init__(self, dim: int, dim_out: int, groups: int = 8):
        super().__init__()
        self.block = torch.nn.Sequential(
            torch.nn.Conv1d(dim, dim_out, 3, padding=1),
            torch.nn.GroupNorm(groups, dim_out),
            nn.Mish(),
        )

    def forward(self, x: torch.Tensor, mask: torch.Tensor):
        output = self.block(x * mask)
        return output * mask


class ResnetBlock1D(torch.nn.Module):
    def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
        super().__init__()
        self.mlp = torch.nn.Sequential(nn.Mish(), torch.nn.Linear(time_emb_dim, dim_out))
        self.block1 = Block1D(dim, dim_out, groups=groups)
        self.block2 = Block1D(dim_out, dim_out, groups=groups)
        self.res_conv = torch.nn.Conv1d(dim, dim_out, 1)

    def forward(self, x, mask, time_emb):
        h = self.block1(x, mask)
        h += self.mlp(time_emb).unsqueeze(-1)
        h = self.block2(h, mask)
        output = h + self.res_conv(x * mask)
        return output


class Downsample1D(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.conv = torch.nn.Conv1d(dim, dim, 3, 2, 1)

    def forward(self, x):
        return self.conv(x)


class TimestepEmbedding(nn.Module):
    def __init__(self, in_channels: int, time_embed_dim: int, act_fn: str = "silu",
                 out_dim: int = None, post_act_fn: Optional[str] = None, cond_proj_dim=None):
        super().__init__()
        from diffusers.models.activations import get_activation
        self.linear_1 = nn.Linear(in_channels, time_embed_dim)
        if cond_proj_dim is not None:
            self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
        else:
            self.cond_proj = None
        self.act = get_activation(act_fn)
        time_embed_dim_out = out_dim if out_dim is not None else time_embed_dim
        self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out)
        self.post_act = get_activation(post_act_fn) if post_act_fn is not None else None

    def forward(self, sample, condition=None):
        if condition is not None:
            sample = sample + self.cond_proj(condition)
        sample = self.linear_1(sample)
        if self.act is not None:
            sample = self.act(sample)
        sample = self.linear_2(sample)
        if self.post_act is not None:
            sample = self.post_act(sample)
        return sample


class Upsample1D(nn.Module):
    """Matcha 1D upsample layer (ConvTranspose1d-based)."""

    def __init__(self, channels, use_conv=False, use_conv_transpose=True, out_channels=None, name="conv"):
        super().__init__()
        self.channels = channels
        self.out_channels = out_channels or channels
        self.use_conv = use_conv
        self.use_conv_transpose = use_conv_transpose
        self.name = name
        self.conv = None
        if use_conv_transpose:
            self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
        elif use_conv:
            self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)

    def forward(self, inputs):
        assert inputs.shape[1] == self.channels
        if self.use_conv_transpose:
            return self.conv(inputs)
        outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
        if self.use_conv:
            outputs = self.conv(outputs)
        return outputs


class BASECFM(torch.nn.Module, ABC):
    def __init__(self, n_feats, cfm_params, n_spks=1, spk_emb_dim=128):
        super().__init__()
        self.n_feats = n_feats
        self.n_spks = n_spks
        self.spk_emb_dim = spk_emb_dim
        self.solver = cfm_params.solver
        self.sigma_min = cfm_params.sigma_min if hasattr(cfm_params, "sigma_min") else 1e-4
        self.estimator = None

    @torch.inference_mode()
    def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
        z = torch.randn_like(mu) * temperature
        t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
        return self._solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)

    def _solve_euler(self, x, t_span, mu, mask, spks, cond):
        t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
        sol = []
        for step in range(1, len(t_span)):
            dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
            x = x + dt * dphi_dt
            t = t + dt
            sol.append(x)
            if step < len(t_span) - 1:
                dt = t_span[step + 1] - t
        return sol[-1]

    def compute_loss(self, x1, mask, mu, spks=None, cond=None):
        b, _, t = mu.shape
        t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
        z = torch.randn_like(x1)
        y = (1 - (1 - self.sigma_min) * t) * z + t * x1
        u = x1 - (1 - self.sigma_min) * z
        loss = F.mse_loss(self.estimator(y, mask, mu, t.squeeze(), spks), u, reduction="sum") / (
            torch.sum(mask) * u.shape[1]
        )
        return loss, y


def _mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
    assert mask.dtype == torch.bool
    assert dtype in [torch.float32, torch.bfloat16, torch.float16]
    mask = mask.to(dtype)
    mask = (1.0 - mask) * -1.0e+10
    return mask


class _Transpose(torch.nn.Module):
    def __init__(self, dim0: int, dim1: int):
        super().__init__()
        self.dim0 = dim0
        self.dim1 = dim1

    def forward(self, x: torch.Tensor):
        return torch.transpose(x, self.dim0, self.dim1)


class CausalConv1d(torch.nn.Conv1d):
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1,
                 groups=1, bias=True, padding_mode='zeros', device=None, dtype=None):
        super(CausalConv1d, self).__init__(
            in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation,
            groups=groups, bias=bias, padding_mode=padding_mode, device=device, dtype=dtype
        )
        assert stride == 1
        self.causal_padding = (kernel_size - 1, 0)

    def forward(self, x: torch.Tensor):
        x = F.pad(x, self.causal_padding)
        return super(CausalConv1d, self).forward(x)


class CausalBlock1D(Block1D):
    def __init__(self, dim: int, dim_out: int):
        super(CausalBlock1D, self).__init__(dim, dim_out)
        self.block = torch.nn.Sequential(
            CausalConv1d(dim, dim_out, 3),
            _Transpose(1, 2),
            nn.LayerNorm(dim_out),
            _Transpose(1, 2),
            nn.Mish(),
        )

    def forward(self, x: torch.Tensor, mask: torch.Tensor):
        output = self.block(x * mask)
        return output * mask


class CausalResnetBlock1D(ResnetBlock1D):
    def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
        super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
        self.block1 = CausalBlock1D(dim, dim_out)
        self.block2 = CausalBlock1D(dim_out, dim_out)


class ConditionalDecoder(nn.Module):
    def __init__(
        self,
        in_channels=320,
        out_channels=80,
        causal=True,
        channels=[256],
        dropout=0.0,
        attention_head_dim=64,
        n_blocks=4,
        num_mid_blocks=12,
        num_heads=8,
        act_fn="gelu",
        meanflow=False,
    ):
        super().__init__()
        channels = tuple(channels)
        self.meanflow = meanflow
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.causal = causal
        self.time_embeddings = SinusoidalPosEmb(in_channels)
        time_embed_dim = channels[0] * 4
        self.time_mlp = TimestepEmbedding(in_channels=in_channels, time_embed_dim=time_embed_dim, act_fn="silu")
        self.down_blocks = nn.ModuleList([])
        self.mid_blocks = nn.ModuleList([])
        self.up_blocks = nn.ModuleList([])
        self.static_chunk_size = 0

        output_channel = in_channels
        for i in range(len(channels)):
            input_channel = output_channel
            output_channel = channels[i]
            is_last = i == len(channels) - 1
            resnet = (
                CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
                if self.causal
                else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
            )
            transformer_blocks = nn.ModuleList([
                BasicTransformerBlock(
                    dim=output_channel, num_attention_heads=num_heads,
                    attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
                ) for _ in range(n_blocks)
            ])
            downsample = (
                Downsample1D(output_channel) if not is_last else
                CausalConv1d(output_channel, output_channel, 3) if self.causal
                else nn.Conv1d(output_channel, output_channel, 3, padding=1)
            )
            self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))

        for _ in range(num_mid_blocks):
            input_channel = channels[-1]
            resnet = (
                CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
                if self.causal
                else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
            )
            transformer_blocks = nn.ModuleList([
                BasicTransformerBlock(
                    dim=output_channel, num_attention_heads=num_heads,
                    attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
                ) for _ in range(n_blocks)
            ])
            self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))

        channels = channels[::-1] + (channels[0],)
        for i in range(len(channels) - 1):
            input_channel = channels[i] * 2
            output_channel = channels[i + 1]
            is_last = i == len(channels) - 2
            resnet = (
                CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
                if self.causal
                else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
            )
            transformer_blocks = nn.ModuleList([
                BasicTransformerBlock(
                    dim=output_channel, num_attention_heads=num_heads,
                    attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
                ) for _ in range(n_blocks)
            ])
            upsample = (
                Upsample1D(output_channel, use_conv_transpose=True) if not is_last else
                CausalConv1d(output_channel, output_channel, 3) if self.causal
                else nn.Conv1d(output_channel, output_channel, 3, padding=1)
            )
            self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))

        self.final_block = (
            CausalBlock1D(channels[-1], channels[-1]) if self.causal else Block1D(channels[-1], channels[-1])
        )
        self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
        self.initialize_weights()
        self.time_embed_mixer = None
        if self.meanflow:
            self.time_embed_mixer = get_intmeanflow_time_mixer(time_embed_dim)

    @property
    def dtype(self):
        return self.final_proj.weight.dtype

    def initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv1d):
                nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.GroupNorm):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    def forward(self, x, mask, mu, t, spks=None, cond=None, r=None):
        t = self.time_embeddings(t).to(t.dtype)
        t = self.time_mlp(t)
        if self.meanflow:
            r = self.time_embeddings(r).to(t.dtype)
            r = self.time_mlp(r)
            concat_embed = torch.cat([t, r], dim=1)
            t = self.time_embed_mixer(concat_embed)
        x = pack([x, mu], "b * t")[0]
        if spks is not None:
            spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
            x = pack([x, spks], "b * t")[0]
        if cond is not None:
            x = pack([x, cond], "b * t")[0]
        hiddens = []
        masks = [mask]
        for resnet, transformer_blocks, downsample in self.down_blocks:
            mask_down = masks[-1]
            x = resnet(x, mask_down, t)
            x = rearrange(x, "b c t -> b t c").contiguous()
            attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, -1)
            attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
            for transformer_block in transformer_blocks:
                x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
            x = rearrange(x, "b t c -> b c t").contiguous()
            hiddens.append(x)
            x = downsample(x * mask_down)
            masks.append(mask_down[:, :, ::2])
        masks = masks[:-1]
        mask_mid = masks[-1]
        for resnet, transformer_blocks in self.mid_blocks:
            x = resnet(x, mask_mid, t)
            x = rearrange(x, "b c t -> b t c").contiguous()
            attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, -1)
            attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
            for transformer_block in transformer_blocks:
                x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
            x = rearrange(x, "b t c -> b c t").contiguous()
        for resnet, transformer_blocks, upsample in self.up_blocks:
            mask_up = masks.pop()
            skip = hiddens.pop()
            x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
            x = resnet(x, mask_up, t)
            x = rearrange(x, "b c t -> b t c").contiguous()
            attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, -1)
            attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
            for transformer_block in transformer_blocks:
                x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
            x = rearrange(x, "b t c -> b c t").contiguous()
            x = upsample(x * mask_up)
        x = self.final_block(x, mask_up)
        output = self.final_proj(x * mask_up)
        return output * mask


def _cast_all(*args, dtype):
    return [a if (not a.dtype.is_floating_point) or a.dtype == dtype else a.to(dtype) for a in args]


class ConditionalCFM(BASECFM):
    def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator=None):
        super().__init__(n_feats=in_channels, cfm_params=cfm_params, n_spks=n_spks, spk_emb_dim=spk_emb_dim)
        self.t_scheduler = cfm_params.t_scheduler
        self.training_cfg_rate = cfm_params.training_cfg_rate
        self.inference_cfg_rate = cfm_params.inference_cfg_rate
        self.estimator = estimator

    def solve_euler(self, x, t_span, mu, mask, spks, cond, meanflow=False):
        in_dtype = x.dtype
        x, t_span, mu, mask, spks, cond = _cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
        B, T = mu.size(0), x.size(2)
        x_in    = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
        mask_in = torch.zeros([2 * B,  1, T], device=x.device, dtype=x.dtype)
        mu_in   = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
        t_in    = torch.zeros([2 * B       ], device=x.device, dtype=x.dtype)
        spks_in = torch.zeros([2 * B, 80   ], device=x.device, dtype=x.dtype)
        cond_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
        r_in    = torch.zeros([2 * B       ], device=x.device, dtype=x.dtype)

        for t, r in zip(t_span[:-1], t_span[1:]):
            t = t.unsqueeze(dim=0)
            r = r.unsqueeze(dim=0)
            x_in[:B] = x_in[B:] = x
            mask_in[:B] = mask_in[B:] = mask
            mu_in[:B] = mu
            t_in[:B] = t_in[B:] = t
            spks_in[:B] = spks
            cond_in[:B] = cond
            r_in[:B] = r_in[B:] = r
            dxdt = self.estimator.forward(
                x=x_in, mask=mask_in, mu=mu_in, t=t_in, spks=spks_in, cond=cond_in,
                r=r_in if meanflow else None,
            )
            dxdt, cfg_dxdt = torch.split(dxdt, [B, B], dim=0)
            dxdt = ((1.0 + self.inference_cfg_rate) * dxdt - self.inference_cfg_rate * cfg_dxdt)
            dt = r - t
            x = x + dt * dxdt

        return x.to(in_dtype)

    def compute_loss(self, x1, mask, mu, spks=None, cond=None):
        b, _, t = mu.shape
        t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
        if self.t_scheduler == 'cosine':
            t = 1 - torch.cos(t * 0.5 * torch.pi)
        z = torch.randn_like(x1)
        y = (1 - (1 - self.sigma_min) * t) * z + t * x1
        u = x1 - (1 - self.sigma_min) * z
        if self.training_cfg_rate > 0:
            cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
            mu = mu * cfg_mask.view(-1, 1, 1)
            spks = spks * cfg_mask.view(-1, 1)
            cond = cond * cfg_mask.view(-1, 1, 1)
        pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
        loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
        return loss, y


class CausalConditionalCFM(ConditionalCFM):
    def __init__(self, in_channels=240, cfm_params=CFM_PARAMS, n_spks=1, spk_emb_dim=80, estimator=None):
        super().__init__(in_channels, cfm_params, n_spks, spk_emb_dim, estimator)
        self.rand_noise = None

    @torch.inference_mode()
    def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None,
                noised_mels=None, meanflow=False):
        B = mu.size(0)
        z = torch.randn_like(mu)
        if noised_mels is not None:
            prompt_len = mu.size(2) - noised_mels.size(2)
            z[..., prompt_len:] = noised_mels
        t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
        if (not meanflow) and (self.t_scheduler == 'cosine'):
            t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
        if meanflow:
            return self.basic_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), None
        return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond, meanflow=meanflow), None

    def basic_euler(self, x, t_span, mu, mask, spks, cond):
        in_dtype = x.dtype
        x, t_span, mu, mask, spks, cond = _cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
        print("S3 Token -> Mel Inference...")
        for t, r in tqdm(zip(t_span[..., :-1], t_span[..., 1:]), total=t_span.shape[-1] - 1):
            t, r = t[None], r[None]
            dxdt = self.estimator.forward(x, mask=mask, mu=mu, t=t, spks=spks, cond=cond, r=r)
            dt = r - t
            x = x + dt * dxdt
        return x.to(in_dtype)


def _repeat_batch_dim(tnsr, B, ndim):
    if tnsr is not None:
        while tnsr.ndim < ndim:
            tnsr = tnsr[None]
        if B > 1 and tnsr.size(0) == 1:
            tnsr = tnsr.repeat(B, *([1] * (ndim - 1)))
        assert tnsr.ndim == ndim
    return tnsr


class CausalMaskedDiffWithXvec(torch.nn.Module):
    def __init__(
        self,
        input_size: int = 512,
        output_size: int = 80,
        spk_embed_dim: int = 192,
        output_type: str = "mel",
        vocab_size: int = 6561,
        input_frame_rate: int = 25,
        only_mask_loss: bool = True,
        token_mel_ratio: int = 2,
        pre_lookahead_len: int = 3,
        encoder: torch.nn.Module = None,
        decoder: torch.nn.Module = None,
        decoder_conf: Dict = {
            'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,
            'cfm_params': DictConfig({
                'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine',
                'training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7, 'reg_loss_type': 'l1',
            }),
            'decoder_params': {
                'channels': [256, 256], 'dropout': 0.0, 'attention_head_dim': 64,
                'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8, 'act_fn': 'gelu',
            },
        },
        mel_feat_conf: Dict = {
            'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,
            'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000,
        },
    ):
        super().__init__()
        self.input_size = input_size
        self.output_size = output_size
        self.decoder_conf = decoder_conf
        self.mel_feat_conf = mel_feat_conf
        self.vocab_size = vocab_size
        self.output_type = output_type
        self.input_frame_rate = input_frame_rate
        self.input_embedding = nn.Embedding(vocab_size, input_size)
        self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, output_size)
        self.encoder = encoder
        self.encoder_proj = torch.nn.Linear(self.encoder.output_size(), output_size)
        self.decoder = decoder
        self.only_mask_loss = only_mask_loss
        self.token_mel_ratio = token_mel_ratio
        self.pre_lookahead_len = pre_lookahead_len

    @torch.inference_mode()
    def inference(self, token, token_len, prompt_token, prompt_token_len, prompt_feat,
                  prompt_feat_len, embedding, finalize, n_timesteps=10, noised_mels=None, meanflow=False):
        B = token.size(0)
        embedding = torch.atleast_2d(embedding)
        embedding = F.normalize(embedding, dim=1)
        embedding = self.spk_embed_affine_layer(embedding)
        prompt_token = _repeat_batch_dim(prompt_token, B, ndim=2)
        prompt_token_len = _repeat_batch_dim(prompt_token_len, B, ndim=1)
        prompt_feat = _repeat_batch_dim(prompt_feat, B, ndim=3)
        prompt_feat_len = _repeat_batch_dim(prompt_feat_len, B, ndim=1)
        embedding = _repeat_batch_dim(embedding, B, ndim=2)
        token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
        mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
        if (token >= self.vocab_size).any():
            logger.error(f"{token.max()}>{self.vocab_size}\n out-of-range special tokens found in flow!")
        token = self.input_embedding(token.long()) * mask
        h, h_masks = self.encoder(token, token_len)
        if finalize is False:
            h = h[:, :-self.pre_lookahead_len * self.token_mel_ratio]
        h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
        mel_len1, mel_len2 = prompt_feat.shape[1], h.shape[1] - prompt_feat.shape[1]
        h = self.encoder_proj(h)
        conds = torch.zeros([B, mel_len1 + mel_len2, self.output_size], device=token.device).to(h.dtype)
        conds[:, :mel_len1] = prompt_feat
        conds = conds.transpose(1, 2)
        mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
        if mask.shape[0] != B:
            mask = mask.repeat(B, 1, 1)
        feat, _ = self.decoder(
            mu=h.transpose(1, 2).contiguous(),
            mask=mask,
            spks=embedding,
            cond=conds,
            n_timesteps=n_timesteps,
            noised_mels=noised_mels,
            meanflow=meanflow,
        )
        feat = feat[:, :, mel_len1:]
        assert feat.shape[2] == mel_len2
        return feat, None


_SUBSAMPLE_CLASSES = {"linear": LinearNoSubsampling}
_EMB_CLASSES = {"rel_pos_espnet": EspnetRelPositionalEncoding}
_ATTENTION_CLASSES = {"rel_selfattn": RelPositionMultiHeadedAttention}
_ACTIVATION_CLASSES = {"swish": torch.nn.SiLU}


# ── construction and the single-step sampler, from s3gen_flow_distill.py ────────


N_SILENCE_TOKENS = 3


N_MELS = 80


ARCH_PRESETS = {
    # 56.90 M Β· 501 ms Β· 8.3x real time
    "half_params": dict(
        encoder_output_size=368, encoder_linear_units=1472,
        encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
        estimator_channels=176, estimator_n_blocks=4,
        estimator_num_mid_blocks=12, estimator_num_heads=8,
        estimator_attention_head_dim=44,
    ),
    # 114.65 M Β· the teacher's own shape.  Same capacity, not a smaller model β€”
    # only useful paired with quantisation, where the win is bits per weight.
    "full_params": dict(
        encoder_output_size=512, encoder_linear_units=2048,
        encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
        estimator_channels=256, estimator_n_blocks=4,
        estimator_num_mid_blocks=12, estimator_num_heads=8,
        estimator_attention_head_dim=64,
    ),
    # 14.40 M Β· 12.6 % of teacher.  exp43's shape, width-tuned to one eighth.
    "eighth_params": dict(
        encoder_output_size=168, encoder_linear_units=672,
        encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
        estimator_channels=88, estimator_n_blocks=4,
        estimator_num_mid_blocks=12, estimator_num_heads=8,
        estimator_attention_head_dim=24,
    ),
    # 7.10 M Β· 6.2 % of teacher.  Same again at one sixteenth.
    "sixteenth_params": dict(
        encoder_output_size=128, encoder_linear_units=512,
        encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
        estimator_channels=56, estimator_n_blocks=4,
        estimator_num_mid_blocks=12, estimator_num_heads=8,
        estimator_attention_head_dim=16,
    ),
    # 57.14 M Β· 242 ms Β· 17.2x real time
    "f1": dict(
        encoder_output_size=368, encoder_linear_units=1472,
        encoder_num_blocks=8, encoder_num_up_blocks=2, encoder_attention_heads=8,
        estimator_channels=[160, 200, 256], estimator_n_blocks=2,
        estimator_num_mid_blocks=8, estimator_num_heads=8,
        estimator_attention_head_dim=64,
    ),
    # 57.69 M Β· 148 ms Β· 28.1x real time.  Five widening stages put the mid
    # blocks on 27 frames instead of 432; no conformer layer runs at the mel
    # rate; four heads rather than eight, which CPU BLAS prefers.
    "fast": dict(
        encoder_output_size=336, encoder_linear_units=1344,
        encoder_num_blocks=10, encoder_num_up_blocks=0, encoder_attention_heads=4,
        estimator_channels=[104, 120, 160, 200, 264], estimator_n_blocks=2,
        estimator_num_mid_blocks=12, estimator_num_heads=4,
        estimator_attention_head_dim=64,
    ),
}


def build_flow(
    encoder_output_size: int = 512,
    encoder_linear_units: int = 2048,
    encoder_num_blocks: int = 6,
    encoder_num_up_blocks: int = 4,
    encoder_attention_heads: int = 8,
    estimator_channels: int = 256,
    estimator_n_blocks: int = 4,
    estimator_num_mid_blocks: int = 12,
    estimator_num_heads: int = 8,
    estimator_attention_head_dim: int = 64,
) -> CausalMaskedDiffWithXvec:
    """Build a meanflow S3Gen flow.  Defaults reproduce the released architecture.

    Halving every width argument yields the pruned student.  The mel dimension
    (80) and the x-vector dimension (192) are interfaces to frozen components and
    stay fixed.

    ``estimator_channels`` takes an int for the released single-stage shape, or a
    list for a genuinely hierarchical UNet: every entry past the first adds a
    stride-2 stage, so the mid blocks then run at a fraction of the mel rate.
    That is the single biggest CPU lever, since mid-block attention is quadratic
    in sequence length.
    """
    encoder = UpsampleConformerEncoder(
        input_size=encoder_output_size,
        output_size=encoder_output_size,
        attention_heads=encoder_attention_heads,
        linear_units=encoder_linear_units,
        num_blocks=encoder_num_blocks,
        num_up_blocks=encoder_num_up_blocks,
        dropout_rate=0.1,
        positional_dropout_rate=0.1,
        attention_dropout_rate=0.1,
        normalize_before=True,
        input_layer="linear",
        pos_enc_layer_type="rel_pos_espnet",
        selfattention_layer_type="rel_selfattn",
        use_cnn_module=False,
        macaron_style=False,
    )
    est_channels = (
        [estimator_channels] if isinstance(estimator_channels, int)
        else list(estimator_channels)
    )
    estimator = ConditionalDecoder(
        in_channels=4 * N_MELS,
        out_channels=N_MELS,
        causal=True,
        channels=est_channels,
        dropout=0.0,
        attention_head_dim=estimator_attention_head_dim,
        n_blocks=estimator_n_blocks,
        num_mid_blocks=estimator_num_mid_blocks,
        num_heads=estimator_num_heads,
        act_fn="gelu",
        meanflow=True,
    )
    decoder = CausalConditionalCFM(
        spk_emb_dim=N_MELS, cfm_params=CFM_PARAMS, estimator=estimator
    )
    return CausalMaskedDiffWithXvec(
        input_size=encoder_output_size, encoder=encoder, decoder=decoder
    )


def meanflow_forward(
    flow: CausalMaskedDiffWithXvec,
    token,
    token_len,
    prompt_token,
    prompt_token_len,
    prompt_feat,
    embedding,
    z=None,
    n_steps: int = 1,
):
    """Run ``flow`` from noise to mel with ``n_steps`` meanflow Euler steps.

    Mirrors ``CausalMaskedDiffWithXvec.inference`` with ``finalize=True``, minus
    the ``inference_mode`` decorator, so gradients reach the student's weights.
    Classifier-free guidance is skipped, matching ``basic_euler``: the meanflow
    weights are trained without it.

    Args:
        z: starting noise over prompt *and* speech frames,
           ``[B, 80, 2 * (prompt_tokens + tokens)]``.  Drawn internally when
           ``None``, which is how the teacher creates the noise it then hands to
           the student.

    Returns:
        ``(mel, mask, z)`` β€” mel ``[B, 80, T_speech]`` and its validity mask
        ``[B, 80, T_speech]``, both already stripped of the prompt region, plus
        the noise actually integrated.
    """
    B = token.size(0)

    embedding = F.normalize(torch.atleast_2d(embedding), dim=1)
    embedding = flow.spk_embed_affine_layer(embedding)

    token = torch.cat([prompt_token, token], dim=1)
    token_len = prompt_token_len + token_len
    token_mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
    token = flow.input_embedding(token.long()) * token_mask

    h, h_masks = flow.encoder(token, token_len)
    h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
    mel_len1 = prompt_feat.shape[1]
    h = flow.encoder_proj(h)

    conds = torch.zeros(B, h.shape[1], flow.output_size, device=h.device, dtype=h.dtype)
    conds[:, :mel_len1] = prompt_feat
    conds = conds.transpose(1, 2)

    mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
    if mask.shape[0] != B:
        mask = mask.repeat(B, 1, 1)

    mu = h.transpose(1, 2).contiguous()
    if z is None:
        z = torch.randn_like(mu)  # encoder_proj makes mu [B, 80, T], same shape as x
    x = z.to(dtype=mu.dtype)

    estimator = flow.decoder.estimator
    t_span = torch.linspace(0, 1, n_steps + 1, device=mu.device, dtype=mu.dtype)
    for t, r in zip(t_span[:-1], t_span[1:]):
        dxdt = estimator(
            x, mask=mask, mu=mu, t=t[None], spks=embedding, cond=conds, r=r[None]
        )
        x = x + (r - t) * dxdt

    mel = x[:, :, mel_len1:]
    mel_mask = mask[:, :, mel_len1:].expand(-1, N_MELS, -1)
    return mel, mel_mask, z