from redwood.rdl import *

W = Model("checkpoint")

processing = {"post": "audio", "assets": {"tokenizer": W.root}, "options": {"sample_rate": 24000}}

# January 2026 English PocketTTS; stock or custom voice embeddings.
# Supply nonempty tokens[P] and a precomputed FP32 voice[V,1024].
LAYERS, WIDTH, HEADS = 6, 1024, 16
MAX_TEXT, MAX_FRAMES = 512, 512
CAPACITY = MAX_TEXT + MAX_FRAMES + 512


def transformer_layer(
    x: Tensor,
    positions: Tensor,
    prefix: str,
    heads: int,
    *,
    cache: tuple[Cache, Cache] | None = None,
    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)
    if cache is not None:
        key, value = cache
        key.append(k)
        value.append(v)
        k, v = key.read(), value.read()
    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="tanh"),
    )
    if layer_scale:
        update = Mul(update, Constant(W[f"{prefix}.layer_scale_2.scale"]))
    return Add(x, update)


def flow(condition: Tensor, sample: Tensor, start: Tensor, end: Tensor) -> Tensor:
    def linear(x: Tensor, name: str) -> Tensor:
        return Linear(x, W[f"{name}.weight"], bias=W[f"{name}.bias"])

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

    def modulation(
        x: Tensor, condition: Tensor, name: str, sets: int
    ) -> tuple[Tensor, ...]:
        parameters = linear(Silu(condition), f"{name}.1")
        width = Dim(x, -1)
        return tuple(
            Slice(
                parameters, axis=0, start=Mul(width, i), stop=Mul(width, i + 1), rank=1
            )
            for i in range(sets)
        )

    name = "flow_lm.flow_net"
    hidden = linear(sample, f"{name}.input_proj")
    y = linear(condition, f"{name}.cond_embed")
    for i, time in enumerate((start, end)):
        embedded = Sinusoidal(time, dim=256, rank=0)
        embedded = FFN(
            embedded,
            up=W[f"{name}.time_embed.{i}.mlp.0.weight"],
            down=W[f"{name}.time_embed.{i}.mlp.2.weight"],
            up_bias=W[f"{name}.time_embed.{i}.mlp.0.bias"],
            down_bias=W[f"{name}.time_embed.{i}.mlp.2.bias"],
        )
        embedded = VarianceNorm(
            embedded, weight=W[f"{name}.time_embed.{i}.mlp.3.alpha"]
        )
        y = Add(y, Mul(embedded, 0.5))
    for i in range(6):
        block = f"{name}.res_blocks.{i}"
        shift, scale, gate = modulation(hidden, y, f"{block}.adaLN_modulation", 3)
        update = Add(Mul(norm(hidden, f"{block}.in_ln"), Add(scale, 1)), shift)
        update = FFN(
            update,
            up=W[f"{block}.mlp.0.weight"],
            down=W[f"{block}.mlp.2.weight"],
            up_bias=W[f"{block}.mlp.0.bias"],
            down_bias=W[f"{block}.mlp.2.bias"],
        )
        hidden = Add(hidden, Mul(update, gate))
    shift, scale = modulation(hidden, y, f"{name}.final_layer.adaLN_modulation", 2)
    hidden = AdaptiveLayerNorm(hidden, shift=shift, scale=scale)
    return linear(hidden, f"{name}.final_layer.linear")


def mimi_decode(latent: Tensor) -> Tensor:
    prefix = "mimi"

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

    x = Conv(
        Permute(latent, (1, 0)),
        W[f"{prefix}.quantizer.output_proj.weight"],
        kernel=(1,),
    )
    x = ConvTranspose(
        x,
        W[f"{prefix}.upsample.convtr.convtr.weight"],
        kernel=(32,),
        stride=16,
        groups=512,
    )
    x = Permute(Slice(x, axis=1, stop=Sub(Dim(x, 1), 16), rank=2), (1, 0))
    positions = Iota(Dim(x, 0))
    for i in range(2):
        x = transformer_layer(
            x,
            positions,
            prefix=f"{prefix}.decoder_transformer.transformer.layers.{i}",
            heads=8,
            window=251,
            layer_scale=True,
        )
    x = conv(Permute(x, (1, 0)), "decoder.model.0", 7)
    for stage, ratio in enumerate((6, 5, 4)):
        index = 2 + 3 * stage
        x = ConvTranspose(
            Elu(x),
            W[f"{prefix}.decoder.model.{index}.convtr.weight"],
            bias=W[f"{prefix}.decoder.model.{index}.convtr.bias"],
            kernel=(2 * ratio,),
            stride=ratio,
        )
        x = Slice(x, axis=1, stop=Sub(Dim(x, 1), ratio), rank=2)
        update = conv(Elu(x), f"decoder.model.{index + 1}.block.1", 3)
        update = conv(Elu(update), f"decoder.model.{index + 1}.block.3", 1)
        x = Add(x, update)
    return conv(Elu(x), "decoder.model.11", 3)


with Graph() as graph:
    tokens = Input(name="tokens", shape=(None,), dtype="int32", maximum_shape=(MAX_TEXT,))
    voice = Input(name="voice", shape=(None, WIDTH), dtype="fp32", maximum_shape=(512, WIDTH))
    key_shape = (CAPACITY, HEADS, WIDTH // HEADS)
    keys = [Cache(name=f"{i}.key", shape=key_shape, dtype="fp32", mode="append", axis=0) for i in range(LAYERS)]
    values = [Cache(name=f"{i}.value", shape=key_shape, dtype="fp32", mode="append", axis=0) for i in range(LAYERS)]

    for cache in (*keys, *values):
        cache.assign(Slice(cache.read(), axis=0, stop=0, rank=3))

    def transformer(x: Tensor, positions: Tensor) -> Tensor:
        for i in range(LAYERS):
            x = transformer_layer(x, positions, f"flow_lm.transformer.layers.{i}", HEADS, cache=(keys[i], values[i]))
        return x

    transformer(voice, Iota(Dim(voice, 0)))
    text = Embedding(tokens, W["flow_lm.conditioner.embed.weight"])
    transformer(text, Add(Iota(Dim(tokens, 0)), Dim(voice, 0)))
    bos = Reshape(Constant(W["flow_lm.bos_emb"]), (32,))

    def generate_frame(state: tuple[Tensor, ...]) -> tuple[Tensor, ...]:
        index, previous, output, counter = state
        x = Reshape(Linear(previous, W["flow_lm.input_linear.weight"]), (1, WIDTH))
        x = transformer(x, Reshape(Add(Add(Dim(voice, 0), Dim(tokens, 0)), index), (1,)))
        x = LayerNorm(x, weight=W["flow_lm.out_norm.weight"], bias=W["flow_lm.out_norm.bias"])
        condition = Reshape(x, (WIDTH,))
        eos = Linear(condition, W["flow_lm.out_eos.weight"], bias=W["flow_lm.out_eos.bias"])
        noise = Mul(Random((32,), seed=0, offset=Mul(index, 32), distribution="normal"), 0.7**0.5)
        frame = Add(noise, flow(condition, noise, Constant(0.0), Constant(1.0)))
        output = Scatter(output, indices=Reshape(index, (1,)), values=frame)
        eos = Compare(Reshape(eos, ()), -4.0, predicate="gt")
        counter = Select(Compare(counter, 0, predicate="ge"), Add(counter, 1), Select(eos, 0, -1))
        return Add(index, 1), frame, output, counter

    result = While(
        (Constant(0), bos, FullLike(bos, shape=(MAX_FRAMES, 32)), Constant(-1)),
        condition=lambda s: Select(
            Compare(s[0], MAX_FRAMES, predicate="lt"), Compare(s[3], 3, predicate="lt"), False
        ),
        body=generate_frame,
    )
    latents = Slice(result[2], axis=0, stop=result[0], rank=2)
    truncated = Compare(result[3], 3, predicate="lt")
    latents = Add(
        Mul(latents, Reshape(Constant(W["flow_lm.emb_std"]), (32,))), Reshape(Constant(W["flow_lm.emb_mean"]), (32,))
    )
    audio = mimi_decode(latents)
    Output(audio, name="audio")
    Output(truncated, name="truncated")
