from redwood.rdl import *

W = Model("checkpoint")

processing = {"pre": "text", "post": "text", "assets": {"tokenizer": W.root}, "options": {"vision": True}}

# Qwen/Qwen3.5-4B
LAYERS, HIDDEN = 32, 2560
HEADS, KV_HEADS, HEAD_DIM = 16, 4, 256
KEY_HEADS, VALUE_HEADS, STATE_DIM = 16, 32, 128
VISION_WIDTH, VISION_HEADS, VISION_LAYERS = 1024, 16, 24
MAX_PROMPT, MAX_NEW = 4096, 256
CAPACITY = MAX_PROMPT + MAX_NEW
VOCAB, EOS_IDS = 248320, (248044,)
ROOT = "model.language_model"


def norm(x: Tensor, name: str) -> Tensor:
    return RMSNorm(x, weight=W[f"{name}.weight"], eps=1e-6, weight_offset=1.0, dtype="bf16")


def attention(x: Tensor, phases: Tensor, name: str, key: Cache, value: Cache) -> Tensor:
    projected = Reshape(Cast(Linear(x, W[f"{name}.q_proj.weight"]), "bf16"), (Dim(x, 0), HEADS, 2 * HEAD_DIM))
    q = Slice(projected, axis=2, stop=HEAD_DIM, rank=3)
    gate = Reshape(Slice(projected, axis=2, start=HEAD_DIM, rank=3), (Dim(x, 0), -1))
    k = SplitHeads(Cast(Linear(x, W[f"{name}.k_proj.weight"]), "bf16"), heads=KV_HEADS)
    v = SplitHeads(Cast(Linear(x, W[f"{name}.v_proj.weight"]), "bf16"), heads=KV_HEADS)
    q = MRope(norm(q, f"{name}.q_norm"), phases, dim=64, sections=(11, 11, 10), theta=10_000_000, dtype="bf16")
    k = MRope(norm(k, f"{name}.k_norm"), phases, dim=64, sections=(11, 11, 10), theta=10_000_000, dtype="bf16")
    key.append(k)
    value.append(v)
    context = MergeHeads(Attention(q, key.read(), value.read(), dtype="bf16"))
    return Cast(Linear(Mul(context, Sigmoid(gate)), W[f"{name}.o_proj.weight"]), "bf16")


def mlp(x: Tensor, name: str) -> Tensor:
    return Cast(
        FFN(
            x, gate=W[f"{name}.gate_proj.weight"], up=W[f"{name}.up_proj.weight"], down=W[f"{name}.down_proj.weight"]
        ),
        "bf16",
    )


def delta_attention(x: Tensor, name: str, convolution: Cache, recurrent: Cache) -> Tensor:
    length = Dim(x, 0)
    key_width = KEY_HEADS * STATE_DIM
    channels = 2 * key_width + VALUE_HEADS * STATE_DIM
    mixed = Cast(Linear(x, W[f"{name}.in_proj_qkv.weight"]), "bf16")
    mixed = Silu(
        Cast(
            CausalConv(
                mixed,
                W[f"{name}.conv1d.weight"],
                kernel=4,
                state=convolution,
                groups=channels,
            ),
            "bf16",
        )
    )
    q = Reshape(
        Slice(mixed, axis=1, stop=key_width, rank=2),
        (length, KEY_HEADS, STATE_DIM),
    )
    k = Reshape(
        Slice(mixed, axis=1, start=key_width, stop=2 * key_width, rank=2),
        (length, KEY_HEADS, STATE_DIM),
    )
    v = Reshape(
        Slice(mixed, axis=1, start=2 * key_width, rank=2),
        (length, VALUE_HEADS, STATE_DIM),
    )
    heads = FloorDiv(Iota(VALUE_HEADS), VALUE_HEADS // KEY_HEADS)
    q, k = Take(q, heads, axis=1, rank=3), Take(k, heads, axis=1, rank=3)
    beta = Sigmoid(Cast(Linear(x, W[f"{name}.in_proj_b.weight"]), "bf16"))
    decay = Cast(Linear(x, W[f"{name}.in_proj_a.weight"]), "bf16")
    decay = Mul(
        Mul(Exp(Constant(W[f"{name}.A_log"])), -1),
        Softplus(Add(decay, Constant(W[f"{name}.dt_bias"]))),
    )
    result = Cast(GatedDelta(q, k, v, beta=beta, log_decay=decay, state=recurrent), "bf16")
    gate = Reshape(
        Cast(Linear(x, W[f"{name}.in_proj_z.weight"]), "bf16"),
        (length, VALUE_HEADS, STATE_DIM),
    )
    result = Mul(
        RMSNorm(result, weight=W[f"{name}.norm.weight"], eps=1e-6, dtype="bf16"), Silu(gate)
    )
    return Cast(Linear(Reshape(result, (length, -1)), W[f"{name}.out_proj.weight"]), "bf16")


def vision(patches: Tensor, coordinates: Tensor, interpolation: Tensor, segments: Tensor) -> Tensor:
    def linear(x: Tensor, name: str) -> Tensor:
        return Cast(
            Linear(
                x, W[f"model.visual.{name}.weight"], bias=W[f"model.visual.{name}.bias"]
            ),
            "bf16",
        )

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

    x = Cast(
        Linear(
            Reshape(patches, (Dim(patches, 0), -1)),
            Reshape(Constant(W["model.visual.patch_embed.proj.weight"]), (VISION_WIDTH, -1)),
            bias=W["model.visual.patch_embed.proj.bias"],
        ),
        "bf16",
    )
    x = Add(
        x,
        Cast(
            InterpolatedEmbedding(
                interpolation,
                W["model.visual.pos_embed.weight"],
                grid_size=48,
            ),
            "bf16",
        ),
    )
    head = VISION_WIDTH // VISION_HEADS
    frequencies = Exp(Mul(Iota(head // 4), Mul(Log(Constant(10000.0)), -4 / head)))
    phases: list[Tensor] = []
    for axis in range(2):
        position = Take(coordinates, Constant(axis), axis=1, rank=2, index_rank=0)
        phases.append(Mul(Reshape(position, (-1, 1)), frequencies))
    angles = Reshape(Concat(tuple(phases), axis=1, rank=2), (-1, 1, head // 2))
    visible = Compare(Reshape(segments, (-1, 1)), segments, predicate="eq")
    mask = Select(visible, 0.0, float("-inf"))
    for i in range(VISION_LAYERS):
        name = f"blocks.{i}"
        packed = linear(norm(x, f"{name}.norm1"), f"{name}.attn.qkv")
        q, k, v = (
            SplitHeads(
                Slice(packed, axis=1, start=j * VISION_WIDTH, stop=(j + 1) * VISION_WIDTH, rank=2),
                heads=VISION_HEADS,
                head_dim=head,
            )
            for j in range(3)
        )
        q, k = (
            RotaryFromAngles(q, angles, dim=head),
            RotaryFromAngles(k, angles, dim=head),
        )
        update = MergeHeads(Attention(q, k, v, causal=False, mask=mask, dtype="bf16"))
        x = Add(x, linear(update, f"{name}.attn.proj"))
        update = Cast(
            FFN(
                norm(x, f"{name}.norm2"),
                up=W[f"model.visual.{name}.mlp.linear_fc1.weight"],
                down=W[f"model.visual.{name}.mlp.linear_fc2.weight"],
                up_bias=W[f"model.visual.{name}.mlp.linear_fc1.bias"],
                down_bias=W[f"model.visual.{name}.mlp.linear_fc2.bias"],
                activation=lambda x: Gelu(x, approximate="tanh"),
            ),
            "bf16",
        )
        x = Add(x, update)
    x = Reshape(norm(x, "merger.norm"), (-1, VISION_WIDTH * 4))
    return Cast(
        FFN(
            x,
            up=W["model.visual.merger.linear_fc1.weight"],
            down=W["model.visual.merger.linear_fc2.weight"],
            up_bias=W["model.visual.merger.linear_fc1.bias"],
            down_bias=W["model.visual.merger.linear_fc2.bias"],
            activation=Gelu,
        ),
        "bf16",
    )


with Graph() as graph:
    tokens = Input(name="tokens", shape=(None,), dtype="int32", maximum_shape=(MAX_PROMPT,))
    reset = Input(name="reset", shape=(), dtype="bool")
    history = Cache(name="history", shape=(CAPACITY,), dtype="int32", mode="append", axis=0)
    key_shape = (CAPACITY, KV_HEADS, HEAD_DIM)
    keys = [Cache(name=f"{i}.key", shape=key_shape, dtype="bf16", mode="append", axis=0) for i in range(LAYERS // 4)]
    values = [
        Cache(name=f"{i}.value", shape=key_shape, dtype="bf16", mode="append", axis=0) for i in range(LAYERS // 4)
    ]
    conv_shape = ((2 * KEY_HEADS + VALUE_HEADS) * STATE_DIM, 3)
    state_shape = (VALUE_HEADS, STATE_DIM, STATE_DIM)
    convolution = {i: Cache(name=f"{i}.conv", shape=conv_shape, dtype="fp32") for i in range(LAYERS) if (i + 1) % 4}
    memory = {i: Cache(name=f"{i}.state", shape=state_shape, dtype="fp32") for i in range(LAYERS) if (i + 1) % 4}
    patches = Input(name="vision.patches", shape=(None, 3, 2, 16, 16), dtype="fp32")
    coordinates = Input(name="vision.coordinates", shape=(None, 2), dtype="int32")
    interpolation = Input(name="vision.interpolation", shape=(None, 2), dtype="fp32")
    segments = Input(name="vision.segments", shape=(None,), dtype="int32")
    feature_map = Input(name="vision.token_features", shape=(None,), dtype="int32")
    positions = Input(name="positions", shape=(None, 3), dtype="int32")
    delta = Input(name="rope_delta", shape=(), dtype="int32")
    features = If(
        Compare(Dim(patches, 0), 0, predicate="gt"),
        then_branch=lambda: (
            vision(patches, coordinates, interpolation, segments),
        ),
        else_branch=lambda: (Broadcast(Constant(0.0), (0, HIDDEN)),),
    )[0]

    start = ReusePrefix(tokens, history, caches=(*keys, *values, *convolution.values(), *memory.values()), reset=reset)

    def decode(state: tuple[Tensor, ...]) -> tuple[Tensor, ...]:
        index, previous, output, _ = state
        prefill = Compare(index, 0, predicate="eq")
        position = Select(prefill, start, Add(Dim(tokens, 0), Sub(index, 1)))
        token_ids = If(
            prefill,
            then_branch=lambda: (Slice(tokens, axis=0, start=start, rank=1),),
            else_branch=lambda: (Reshape(previous, (1,)),),
        )[0]
        token_positions = Add(Iota(Dim(token_ids, 0)), position)
        history.append(token_ids)
        x = Cast(Embedding(token_ids, W[f"{ROOT}.embed_tokens.weight"]), "bf16")
        mapped = Gather(feature_map, indices=Reshape(token_positions, (-1, 1)), mask=prefill, fill=-1)
        replace = Compare(mapped, 0, predicate="ge")
        feature = Gather(features, indices=Reshape(mapped, (-1, 1)), mask=replace)
        x = Select(Reshape(replace, (-1, 1)), Reshape(feature, (-1, HIDDEN)), x)
        phases = Gather(positions, indices=Reshape(token_positions, (-1, 1)), mask=prefill)
        phases = Select(prefill, phases, Reshape(Add(token_positions, delta), (-1, 1)))
        for i in range(LAYERS):
            name = f"{ROOT}.layers.{i}"
            hidden = norm(x, f"{name}.input_layernorm")
            if (i + 1) % 4:
                update = delta_attention(hidden, f"{name}.linear_attn", convolution[i], memory[i])
            else:
                update = attention(hidden, phases, f"{name}.self_attn", keys[i // 4], values[i // 4])
            x = Add(x, update)
            x = Add(x, mlp(norm(x, f"{name}.post_attention_layernorm"), f"{name}.mlp"))
        x = Slice(x, axis=0, start=-1, rank=2)
        logits = Reshape(Linear(Cast(norm(x, f"{ROOT}.norm"), "fp32"), Cast(Constant(W[f"{ROOT}.embed_tokens.weight"]), "fp32")), (VOCAB,))
        token = Greedy(logits)
        output = Scatter(output, indices=Reshape(index, (1,)), values=token)
        done = Constant(False)
        for eos in EOS_IDS:
            done = Select(Compare(token, eos, predicate="eq"), True, done)
        return Add(index, 1), token, output, done

    output = Broadcast(Constant(0, dtype="int32"), (MAX_NEW,))
    result = While(
        (Constant(0), Constant(0, dtype="int32"), output, Constant(False)),
        condition=lambda s: Select(
            Compare(s[0], MAX_NEW, predicate="lt"), Compare(s[3], False, predicate="eq"), False
        ),
        body=decode,
    )
    Output(Slice(result[2], axis=0, stop=result[0], rank=1), name="tokens")
