from redwood.rdl import *

TEXT = Model("textencoder")
DENOISER = Model("transformer")
VAE = Model("vae")

processing = {"pre": "image", "post": "image", "assets": {"tokenizer": TEXT.root}}

# prism-ml/bonsai-image-ternary-4B-unpacked
MAX_IMAGE_SIZE, MAX_TEXT_TOKENS = 1920, 512
DENOISER_WIDTH = 24 * 128


def concat_rows(tensors: tuple[Tensor, ...], *, rank: int) -> Tensor:
    length = Constant(0)
    for value in tensors:
        length = Add(length, Dim(value, 0))
    output = FullLike(tensors[0], shape=(length, *(Dim(tensors[0], i) for i in range(1, rank))))
    offset = Constant(0)
    for value in tensors:
        # Keep the index count equal to this input's length during bounds inference.
        indices = Reshape(Add(Iota(Dim(value, 0)), offset), (-1, 1))
        output = Scatter(output, indices=indices, values=value)
        offset = Add(offset, Dim(value, 0))
    return output


def encode_text(tokens: Tensor) -> Tensor:
    x = Embedding(tokens, TEXT["model.embed_tokens.weight"])
    position = Iota(Dim(tokens, 0))
    snapshots: list[Tensor] = []
    for i in range(36):
        name = f"model.layers.{i}"
        hidden = RMSNorm(x, weight=TEXT[f"{name}.input_layernorm.weight"], eps=1e-6)
        q = SplitHeads(Linear(hidden, TEXT[f"{name}.self_attn.q_proj.weight"]), heads=32)
        k = SplitHeads(Linear(hidden, TEXT[f"{name}.self_attn.k_proj.weight"]), heads=8)
        v = SplitHeads(Linear(hidden, TEXT[f"{name}.self_attn.v_proj.weight"]), heads=8)
        q = RMSNorm(q, weight=TEXT[f"{name}.self_attn.q_norm.weight"], eps=1e-6)
        k = RMSNorm(k, weight=TEXT[f"{name}.self_attn.k_norm.weight"], eps=1e-6)
        q, k = Rotary(q, position, dim=128, theta=1_000_000), Rotary(k, position, dim=128, theta=1_000_000)
        x = Add(x, Linear(MergeHeads(Attention(q, k, v)), TEXT[f"{name}.self_attn.o_proj.weight"]))
        hidden = RMSNorm(x, weight=TEXT[f"{name}.post_attention_layernorm.weight"], eps=1e-6)
        x = Add(
            x,
            FFN(
                hidden,
                gate=TEXT[f"{name}.mlp.gate_proj.weight"],
                up=TEXT[f"{name}.mlp.up_proj.weight"],
                down=TEXT[f"{name}.mlp.down_proj.weight"],
            ),
        )
        if i + 1 in (9, 18, 27):
            snapshots.append(x)
    return Concat(tuple(snapshots), axis=1, rank=2)


def denoiser_linear(x: Tensor, name: str) -> Tensor:
    return Linear(x, Weight(f"{DENOISER.root}.{name}.weight", dtype="grp_ternary"))


def modulation(parameters: Tensor, part: int = 0) -> tuple[Tensor, Tensor, Tensor]:
    parameters = Reshape(parameters, (-1, DENOISER_WIDTH))
    shift, scale, gate = (
        Take(parameters, Constant(3 * part + i), rank=2, index_rank=0) for i in range(3)
    )
    return shift, scale, gate


def attend(q: Tensor, k: Tensor, v: Tensor, coordinates: Tensor) -> Tensor:
    q = AxialRotary(q, coordinates, sections=(32, 32, 32, 32), theta=2000.0)
    k = AxialRotary(k, coordinates, sections=(32, 32, 32, 32), theta=2000.0)
    return MergeHeads(Attention(q, k, v, causal=False))


def joint_block(
    image: Tensor, text: Tensor, image_mod: Tensor, text_mod: Tensor, coordinates: Tensor, name: str
) -> tuple[Tensor, Tensor]:
    def qkv(x: Tensor, prefix: str, norm_prefix: str) -> tuple[Tensor, Tensor, Tensor]:
        suffix = "_proj" if prefix == "add_" else ""
        q, k, v = (
            SplitHeads(denoiser_linear(x, f"{name}.attn.{prefix}{part}{suffix}"), heads=24)
            for part in ("q", "k", "v")
        )
        q = RMSNorm(q, weight=DENOISER[f"{name}.attn.{norm_prefix}q.weight"], eps=1e-6)
        k = RMSNorm(k, weight=DENOISER[f"{name}.attn.{norm_prefix}k.weight"], eps=1e-6)
        return q, k, v

    def feedforward(x: Tensor, parameters: Tensor, prefix: str) -> Tensor:
        shift, scale, gate = modulation(parameters, 1)
        update = FFN(
            AdaptiveLayerNorm(x, shift=shift, scale=scale, eps=1e-6),
            up=Weight(f"{DENOISER.root}.{prefix}.linear_in.weight", dtype="grp_ternary"),
            down=Weight(f"{DENOISER.root}.{prefix}.linear_out.weight", dtype="grp_ternary"),
            activation=SwiGLU,
        )
        return Add(x, Mul(update, gate))

    shift, scale, gate = modulation(image_mod)
    t_shift, t_scale, t_gate = modulation(text_mod)
    qi, ki, vi = qkv(AdaptiveLayerNorm(image, shift=shift, scale=scale, eps=1e-6), "to_", "norm_")
    qt, kt, vt = qkv(AdaptiveLayerNorm(text, shift=t_shift, scale=t_scale, eps=1e-6), "add_", "norm_added_")
    combined = attend(
        concat_rows((qt, qi), rank=3), concat_rows((kt, ki), rank=3),
        concat_rows((vt, vi), rank=3), coordinates,
    )
    update = denoiser_linear(
        Reshape(Slice(combined, axis=0, start=Dim(text, 0), rank=2), (Dim(image, 0), DENOISER_WIDTH)),
        f"{name}.attn.to_out.0",
    )
    image = Add(image, Mul(update, gate))
    update = denoiser_linear(Slice(combined, axis=0, stop=Dim(text, 0), rank=2), f"{name}.attn.to_add_out")
    text = Add(text, Mul(update, t_gate))
    return feedforward(image, image_mod, f"{name}.ff"), feedforward(text, text_mod, f"{name}.ff_context")


def parallel_block(hidden: Tensor, single_mod: Tensor, coordinates: Tensor, name: str) -> Tensor:
    width = DENOISER_WIDTH

    shift, scale, gate = modulation(single_mod)
    x = AdaptiveLayerNorm(hidden, shift=shift, scale=scale, eps=1e-6)
    projected = denoiser_linear(x, f"{name}.attn.to_qkv_mlp_proj")
    q, k, v = (
        SplitHeads(
            Slice(projected, axis=1, start=j * width, stop=(j + 1) * width, rank=2),
            heads=24,
            head_dim=128,
        )
        for j in range(3)
    )
    q = RMSNorm(q, weight=DENOISER[f"{name}.attn.norm_q.weight"], eps=1e-6)
    k = RMSNorm(k, weight=DENOISER[f"{name}.attn.norm_k.weight"], eps=1e-6)
    attention = attend(q, k, v, coordinates)
    mlp = SwiGLU(Slice(projected, axis=1, start=3 * width, rank=2))
    joined = Concat((attention, mlp), axis=1, rank=2)
    # Flattening materializes the column-strided concatenation for linear kernels.
    joined = Reshape(Reshape(joined, (-1,)), (Dim(hidden, 0), 4 * width))
    update = denoiser_linear(joined, f"{name}.attn.to_out")
    return Add(hidden, Mul(update, gate))


def decode_vae(latent: Tensor) -> Tensor:
    def conv(x: Tensor, name: str, kernel: int = 3) -> Tensor:
        return Conv(
            x, VAE[f"{name}.weight"], bias=VAE[f"{name}.bias"],
            kernel=(kernel, kernel), padding=kernel // 2,
        )

    def norm(x: Tensor, name: str) -> Tensor:
        return GroupNorm(
            x, groups=32, weight=VAE[f"{name}.weight"], bias=VAE[f"{name}.bias"], eps=1e-6, rank=3,
        )

    def residual(x: Tensor, name: str, shortcut: bool = False) -> Tensor:
        update = conv(Silu(norm(x, f"{name}.norm1")), f"{name}.conv1")
        update = conv(Silu(norm(update, f"{name}.norm2")), f"{name}.conv2")
        return Add(conv(x, f"{name}.conv_shortcut", 1) if shortcut else x, update)

    x = conv(latent, "post_quant_conv", 1)
    x = conv(x, "decoder.conv_in")
    x = residual(x, "decoder.mid_block.resnets.0")
    name = "decoder.mid_block.attentions.0"
    hidden = Permute(Reshape(norm(x, f"{name}.group_norm"), (Dim(x, 0), -1)), (1, 0))
    q, k, v = (
        SplitHeads(
            Linear(
                hidden,
                VAE[f"{name}.to_{suffix}.weight"],
                bias=VAE[f"{name}.to_{suffix}.bias"],
            ),
            heads=1,
        )
        for suffix in ("q", "k", "v")
    )
    hidden = MergeHeads(Attention(q, k, v, causal=False))
    hidden = Linear(
        hidden, VAE[f"{name}.to_out.0.weight"], bias=VAE[f"{name}.to_out.0.bias"]
    )
    x = Add(x, Reshape(Permute(hidden, (1, 0)), (Dim(x, 0), Dim(x, 1), Dim(x, 2))))
    x = residual(x, "decoder.mid_block.resnets.1")
    channels = (512, 512, 256, 128)
    previous = channels[0]
    for stage, width in enumerate(channels):
        for block in range(3):
            x = residual(
                x,
                f"decoder.up_blocks.{stage}.resnets.{block}",
                shortcut=previous != width,
            )
            previous = width
        if stage < len(channels) - 1:
            x = Resize(x, sizes=(Mul(Dim(x, 1), 2), Mul(Dim(x, 2), 2)))
            x = conv(x, f"decoder.up_blocks.{stage}.upsamplers.0.conv")
    return conv(Silu(norm(x, "decoder.conv_norm_out")), "decoder.conv_out")


with Graph() as graph:
    tokens = Input(name="tokens", shape=(None,), dtype="int32", maximum_shape=(MAX_TEXT_TOKENS,))
    sigmas = Input(name="sigmas", shape=(None,), dtype="fp32", maximum_shape=(1001,))
    coordinates = Input(name="coordinates", shape=(None, 4), dtype="int32", maximum_shape=((MAX_IMAGE_SIZE // 16) ** 2 + MAX_TEXT_TOKENS, 4))
    height = Input(name="height", shape=(), dtype="int32", minimum=16, maximum=MAX_IMAGE_SIZE, multiple_of=16)
    width = Input(name="width", shape=(), dtype="int32", minimum=16, maximum=MAX_IMAGE_SIZE, multiple_of=16)
    seed = Input(name="seed", shape=(), dtype="uint64")
    latent_h, latent_w = FloorDiv(height, 16), FloorDiv(width, 16)
    context = encode_text(tokens)
    noise = Random((Mul(latent_h, latent_w), 128), seed=seed, distribution="normal")

    def denoise(state: tuple[Tensor, ...]) -> tuple[Tensor, ...]:
        index, sample = state
        current = Take(sigmas, index, index_rank=0)
        following = Take(sigmas, Add(index, 1), index_rank=0)
        time = Sinusoidal(Mul(current, 1000), dim=256, rank=0)
        time = FFN(
            time, up=DENOISER["time_guidance_embed.timestep_embedder.linear_1.weight"],
            down=DENOISER["time_guidance_embed.timestep_embedder.linear_2.weight"],
        )
        image = Linear(sample, DENOISER["x_embedder.weight"])
        text = Linear(context, DENOISER["context_embedder.weight"])
        image_mod = Linear(Silu(time), DENOISER["double_stream_modulation_img.linear.weight"])
        text_mod = Linear(Silu(time), DENOISER["double_stream_modulation_txt.linear.weight"])
        single_mod = Linear(Silu(time), DENOISER["single_stream_modulation.linear.weight"])
        for i in range(5):
            image, text = joint_block(image, text, image_mod, text_mod, coordinates, f"transformer_blocks.{i}")
        x = concat_rows((text, image), rank=2)
        for i in range(20):
            x = parallel_block(x, single_mod, coordinates, f"single_transformer_blocks.{i}")
        x = Reshape(Slice(x, axis=0, start=Dim(text, 0), rank=2), (Dim(sample, 0), DENOISER_WIDTH))
        parameters = Linear(Silu(time), DENOISER["norm_out.linear.weight"])
        scale = Reshape(Slice(parameters, axis=0, stop=3072, rank=1), (1, 3072))
        shift = Reshape(Slice(parameters, axis=0, start=3072, rank=1), (1, 3072))
        velocity = Reshape(
            Linear(AdaptiveLayerNorm(x, shift=shift, scale=scale), DENOISER["proj_out.weight"]),
            (Dim(sample, 0), 128),
        )
        return Add(index, 1), Add(sample, Mul(velocity, Sub(following, current)))

    latent = While(
        (Constant(0), noise),
        condition=lambda s: Compare(s[0], Sub(Dim(sigmas, 0), 1), predicate="lt"),
        body=denoise,
    )[1]
    latent = Permute(Reshape(latent, (latent_h, latent_w, 128)), (2, 0, 1))
    mean = Reshape(Constant(VAE["bn.running_mean"]), (-1, 1, 1))
    std = Sqrt(Add(Reshape(Constant(VAE["bn.running_var"]), (-1, 1, 1)), 1e-4))
    latent = Add(Mul(latent, std), mean)
    latent = Permute(Reshape(latent, (32, 2, 2, latent_h, latent_w)), (0, 3, 1, 4, 2))
    latent = Reshape(latent, (32, Mul(latent_h, 2), Mul(latent_w, 2)))
    image = decode_vae(latent)
    Output(Reshape(image, (3, height, width)), name="image")
