Whisper Small

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")

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

# openai/whisper-small
WIDTH, LAYERS, HEADS = 768, 12, 12
MAX_PROMPT, MAX_NEW = 64, 384
CAPACITY = MAX_PROMPT + MAX_NEW
VOCAB, EOS_IDS = 51865, (50257,)


def linear(x: Tensor, name: str, bias: bool = True) -> Tensor:
    return Cast(Linear(x, W[f"{name}.weight"], bias=W[f"{name}.bias"] if bias else None), "bf16")


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


def qkv(x: Tensor, name: str) -> tuple[Tensor, ...]:
    return (
        SplitHeads(linear(x, f"{name}.q_proj"), heads=HEADS),
        SplitHeads(linear(x, f"{name}.k_proj", False), heads=HEADS),
        SplitHeads(linear(x, f"{name}.v_proj"), heads=HEADS),
    )


def mlp(x: Tensor, name: str) -> Tensor:
    return Cast(
        FFN(
            x, up=W[f"{name}.fc1.weight"], down=W[f"{name}.fc2.weight"],
            up_bias=W[f"{name}.fc1.bias"], down_bias=W[f"{name}.fc2.bias"], activation=Gelu,
        ),
        "bf16",
    )


with Graph() as graph:
    mel = Input(name="mel", shape=(80, 3000), dtype="fp32")
    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)
    x = Gelu(Cast(Conv(mel, W["model.encoder.conv1.weight"], bias=W["model.encoder.conv1.bias"], kernel=(3,), padding=1), "bf16"))
    x = Gelu(
        Cast(Conv(x, W["model.encoder.conv2.weight"], bias=W["model.encoder.conv2.bias"], kernel=(3,), stride=2, padding=1), "bf16")
    )
    x = Add(Permute(x, (1, 0)), Cast(Embedding(Iota(1500), W["model.encoder.embed_positions.weight"], token_rank=1), "bf16"))
    for i in range(LAYERS):
        name = f"model.encoder.layers.{i}"
        q, k, v = qkv(norm(x, f"{name}.self_attn_layer_norm"), f"{name}.self_attn")
        x = Add(x, linear(MergeHeads(Attention(q, k, v, causal=False, dtype="bf16")), f"{name}.self_attn.out_proj"))
        x = Add(x, mlp(norm(x, f"{name}.final_layer_norm"), name))
    encoded = norm(x, "model.encoder.layer_norm")
    key_shape = (CAPACITY, HEADS, WIDTH // HEADS)
    keys = [Cache(name=f"{i}.key", shape=key_shape, dtype="bf16", mode="append", axis=0) for i in range(LAYERS)]
    values = [Cache(name=f"{i}.value", shape=key_shape, dtype="bf16", mode="append", axis=0) for i in range(LAYERS)]
    cross_keys = [
        SplitHeads(linear(encoded, f"model.decoder.layers.{i}.encoder_attn.k_proj", False), heads=HEADS)
        for i in range(LAYERS)
    ]
    cross_values = [
        SplitHeads(linear(encoded, f"model.decoder.layers.{i}.encoder_attn.v_proj"), heads=HEADS) for i in range(LAYERS)
    ]

    start = ReusePrefix(tokens, history, caches=(*keys, *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["model.decoder.embed_tokens.weight"]), "bf16")
        x = Add(x, Cast(Embedding(token_positions, W["model.decoder.embed_positions.weight"]), "bf16"))
        for i in range(LAYERS):
            name = f"model.decoder.layers.{i}"
            q, k, v = qkv(norm(x, f"{name}.self_attn_layer_norm"), f"{name}.self_attn")
            keys[i].append(k)
            values[i].append(v)
            x = Add(
                x,
                linear(MergeHeads(Attention(q, keys[i].read(), values[i].read(), dtype="bf16")), f"{name}.self_attn.out_proj"),
            )
            q = SplitHeads(
                linear(norm(x, f"{name}.encoder_attn_layer_norm"), f"{name}.encoder_attn.q_proj"), heads=HEADS
            )
            context = Attention(q, cross_keys[i], cross_values[i], causal=False, dtype="bf16")
            x = Add(x, linear(MergeHeads(context), f"{name}.encoder_attn.out_proj"))
            x = Add(x, mlp(norm(x, f"{name}.final_layer_norm"), name))
        x = Slice(x, axis=0, start=-1, rank=2)
        logits = Linear(Cast(norm(x, "model.decoder.layer_norm"), "fp32"), Cast(Constant(W["model.decoder.embed_tokens.weight"]), "fp32"))
        logits = Reshape(logits, (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")