from redwood.rdl import *

W = Model("checkpoint")

processing = {}

# January 2026 English kyutai/pocket-tts with voice-cloning weights.
# Supply mono FP32 audio[1,S] at 24 kHz, padded to a positive multiple of 1920.
MAX_SAMPLES = 240000


def transformer_layer(
    x: Tensor,
    positions: Tensor,
    prefix: str,
    heads: int,
    *,
    window: int | None = None,
    layer_scale: bool = False,
) -> Tensor:
    def linear(x: Tensor, name: str) -> Tensor:
        return Linear(x, W[f"{prefix}.{name}.weight"])

    def norm(x: Tensor, name: str) -> Tensor:
        return LayerNorm(
            x,
            weight=W[f"{prefix}.{name}.weight"],
            bias=W[f"{prefix}.{name}.bias"],
        )

    width = Dim(x, -1)
    packed = linear(norm(x, "norm1"), "self_attn.in_proj")
    q, k, v = (
        SplitHeads(
            Slice(packed, axis=1, start=Mul(width, i), stop=Mul(width, i + 1), rank=2),
            heads=heads,
        )
        for i in range(3)
    )
    q = Rotary(q, positions, dim=64, interleaved=True)
    k = Rotary(k, positions, dim=64, interleaved=True)
    update = linear(MergeHeads(Attention(q, k, v, window=window)), "self_attn.out_proj")
    if layer_scale:
        update = Mul(update, Constant(W[f"{prefix}.layer_scale_1.scale"]))
    x = Add(x, update)
    update = FFN(
        norm(x, "norm2"),
        up=W[f"{prefix}.linear1.weight"],
        down=W[f"{prefix}.linear2.weight"],
        activation=lambda x: Gelu(x, approximate="none"),
    )
    if layer_scale:
        update = Mul(update, Constant(W[f"{prefix}.layer_scale_2.scale"]))
    return Add(x, update)


with Graph() as graph:
    audio = Input(
        name="audio", shape=(1, None), dtype="fp32", maximum_shape=(1, MAX_SAMPLES)
    )

    def conv(x: Tensor, name: str, kernel: int, stride: int = 1) -> Tensor:
        return Conv(
            Pad(x, padding=((0, 0), (kernel - stride, 0))),
            W[f"mimi.{name}.conv.weight"],
            bias=W[f"mimi.{name}.conv.bias"],
            kernel=(kernel,),
            stride=stride,
        )

    x = conv(audio, "encoder.model.0", 7)
    for stage, ratio in enumerate((4, 5, 6)):
        index = 1 + 3 * stage
        residual = conv(Elu(x), f"encoder.model.{index}.block.1", 3)
        residual = conv(Elu(residual), f"encoder.model.{index}.block.3", 1)
        x = Add(x, residual)
        x = conv(Elu(x), f"encoder.model.{index + 2}", 2 * ratio, ratio)
    x = conv(Elu(x), "encoder.model.11", 3)
    x = Permute(x, (1, 0))
    for i in range(2):
        x = transformer_layer(
            x,
            Iota(Dim(x, 0)),
            prefix=f"mimi.encoder_transformer.transformer.layers.{i}",
            heads=8,
            window=250,
            layer_scale=True,
        )
    x = Permute(x, (1, 0))
    prefix = Permute(
        Gather(Permute(x, (1, 0)), indices=Reshape(Mul(Iota(16), 0), (16, 1))), (1, 0)
    )
    x = Concat((prefix, x), axis=1, rank=2)
    x = Conv(x, W["mimi.downsample.conv.conv.weight"], kernel=(32,), stride=16)
    x = Linear(Permute(x, (1, 0)), W["flow_lm.speaker_proj_weight"])
    Output(x, name="voice")
