Ternary Bonsai 2 27B

Hugging Face checkpoints

Download the configuration, tokenizer or processor assets, and all weight shards with their index files. Some publishers require accepting their terms on Hugging Face.

Use the names in Model(...) to bind the checkpoints when you compile the RDL.

from redwood.rdl import *

W = Model("checkpoint")

import numpy as np

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

# prism-ml/Ternary-Bonsai-2-27B-mlx-2bit
LAYERS, HIDDEN = 64, 5120
HEADS, KV_HEADS, HEAD_DIM = 24, 4, 256
KEY_HEADS, VALUE_HEADS, STATE_DIM = 16, 48, 128
MAX_PROMPT, MAX_NEW = 4096, 256
CAPACITY = MAX_PROMPT + MAX_NEW
VOCAB, EOS_IDS = 248320, (248044, 248046)
ROOT = "language_model.model"


_H = np.ones((1, 1), dtype=np.float32)
while _H.shape[0] < 1024:
    _H = np.block([[_H, _H], [_H, -_H]])
SIGNS = {
    HIDDEN: W["language_model.lm_head.signs"],
    VALUE_HEADS * STATE_DIM: W[f"{ROOT}.layers.0.linear_attn.out_proj.signs"],
    17408: W[f"{ROOT}.layers.0.mlp.down_proj.signs"],
}


def rotate(x: Tensor, width: int, *, inverse: bool = False) -> Tensor:
    value = Cast(x, "fp32")
    signs = SIGN_TENSORS[width]
    if not inverse:
        value = Mul(value, signs)
    value = Reshape(Mul(Matmul(Reshape(value, (-1, 1024)), HADAMARD), 1.0 / 32), (Dim(x, 0), width))
    return Cast(Mul(value, signs) if inverse else value, "fp16")


def rotated_linear(x: Tensor, name: str, width: int = HIDDEN) -> Tensor:
    return Cast(Linear(rotate(x, width), W[f"{name}.weight"]), "fp16")


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


def attention(x: Tensor, phases: Tensor, name: str, key: Cache, value: Cache) -> Tensor:
    projected = Reshape(rotated_linear(x, f"{name}.q_proj"), (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(rotated_linear(x, f"{name}.k_proj"), heads=KV_HEADS)
    v = SplitHeads(rotated_linear(x, f"{name}.v_proj"), heads=KV_HEADS)
    q = MRope(norm(q, f"{name}.q_norm"), phases, dim=64, sections=(11, 11, 10), theta=10_000_000, dtype="fp16")
    k = MRope(norm(k, f"{name}.k_norm"), phases, dim=64, sections=(11, 11, 10), theta=10_000_000, dtype="fp16")
    key.append(k)
    value.append(v)
    context = MergeHeads(Attention(q, key.read(), value.read(), dtype="fp16"))
    return Cast(rotated_linear(Mul(context, Sigmoid(gate)), f"{name}.o_proj", HEADS * HEAD_DIM), "fp16")


def mlp(x: Tensor, name: str) -> Tensor:
    gate = rotated_linear(x, f"{name}.gate_proj")
    up = rotated_linear(x, f"{name}.up_proj")
    return rotated_linear(Mul(Silu(gate), up), f"{name}.down_proj", 17408)


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 = rotated_linear(x, f"{name}.in_proj_qkv")
    mixed = Silu(
        Cast(
            CausalConv(
                mixed,
                Permute(Constant(W[f"{name}.conv1d.weight"]), (0, 2, 1)),
                kernel=4,
                state=convolution,
                groups=channels,
            ),
            "fp16",
        )
    )
    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"]), "fp16"))
    decay = Cast(Linear(x, W[f"{name}.in_proj_a.weight"]), "fp16")
    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), "fp16")
    gate = Reshape(
        rotated_linear(x, f"{name}.in_proj_z"),
        (length, VALUE_HEADS, STATE_DIM),
    )
    result = Mul(
        RMSNorm(result, weight=W[f"{name}.norm.weight"], eps=1e-6, dtype="fp16"), Silu(gate)
    )
    return Cast(rotated_linear(Reshape(result, (length, VALUE_HEADS * STATE_DIM)), f"{name}.out_proj", VALUE_HEADS * STATE_DIM), "fp16")


with Graph() as graph:
    HADAMARD = Constant(_H)
    SIGN_TENSORS = {width: Constant(weight) for width, weight in SIGNS.items()}
    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="fp16", mode="append", axis=0) for i in range(LAYERS // 4)]
    values = [
        Cache(name=f"{i}.value", shape=key_shape, dtype="fp16", 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}

    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 = rotate(Cast(Embedding(token_ids, W[f"{ROOT}.embed_tokens.weight"]), "fp16"), HIDDEN, inverse=True)
        phases = Broadcast(Reshape(token_positions, (-1, 1)), (Dim(token_ids, 0), 3))
        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(rotate(norm(x, f"{ROOT}.norm"), HIDDEN), W["language_model.lm_head.weight"]), (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")