Caesar source guide

Source and quick start on GitHub

src/Caesar.jl

Qwen3.5-2B, explained at 18

Suppose you type “The capital of France is”. How could a program pick the next word? Qwen starts by cutting the text into pieces called tokens. Here the five pieces are "The", " capital", " of", " France" and " is". The spaces belong to the pieces too.

Each piece has a number. For example, " France" is token 9338. Qwen uses that number to look up a list of 2,048 numbers called an embedding. During training, Qwen guessed the next token in examples. Each time, the training program adjusted its numbers to make the right answer more likely. These learned numbers are the weights. A checkpoint stores them.

The decoder is the part that makes the prediction. It reads from left to right. By the time it reaches " is", its numbers carry clues from the earlier words, including which country the sentence named. It gives every possible next token a score. If " Paris" scores highest, the default setting picks it. Now the sentence ends in “Paris”, and the decoder uses that new token to predict what follows. That loop is how Caesar writes.

Start with generate below. To see how one word changes what another word means, read Inside a transformer. To see what Qwen receives when you send a chat message or attach a photo, follow the prompt builder.

module Caesar

using BFloat16s, DataStructures, JSON, LinearAlgebra, Mmap, Printf, Random, Unicode
using SpecialFunctions: erf
using FileWatching.Pidfile: mkpidlock
using SHA: sha256

export load_model, Tokenizer, generate, encode, decode, image_features, prepare_prompt

struct Model
    dir::String
    config::Dict{String, Any}
    weights::Dict{String, AbstractArray}
end

Generating an answer

There are two versions of generate. The first takes a message such as "Hello!". It prepares the input, calls the second version with token IDs, then turns the IDs in the reply back into text.

The loop in the second version picks one ID, sends it to on_token so the CLI can print it, and feeds it back to the decoder. The decoder remembers what it has already read. The loop stops when Qwen picks an end marker or the reply reaches the requested length.


function generate(m::Model, text::AbstractString; tokenizer = Tokenizer(m), media = [], chat = true, thinking = false, on_progress = Returns(nothing), kwargs...)
    prompt = prepare_prompt(m, tokenizer, text; media, chat, thinking, on_progress)
    ids = generate(m, prompt.ids; prompt.soft, prompt.positions, on_progress, kwargs...)
    return decode(tokenizer, ids)
end

const STOP_TOKENS = (248044, 248046)  # end of text, end of turn

function generate(
        m::Model, ids::AbstractVector{<:Integer}; max_new_tokens = 32, temperature = 0,
        top_k = 20, top_p = 0.95, rng = Random.default_rng(), block_size = 64, soft = Dict(),
        on_token = Returns(nothing), on_progress = Returns(nothing), positions = text_positions(0, length(ids))
    )
    isempty(ids) && throw(ArgumentError("Prompt must contain at least one token"))
    max_new_tokens >= 0 && isfinite(temperature) && temperature >= 0 && top_k >= 0 &&
        0 < top_p <= 1 && block_size > 0 || throw(ArgumentError("Invalid generation parameters"))
    limit = length(ids) + max(0, max_new_tokens - 1)
    limit <= m.config["text_config"]["max_position_embeddings"] || throw(ArgumentError("Context exceeded"))
    size(positions) == (3, length(ids)) || throw(DimensionMismatch("Invalid prompt positions"))
    max_new_tokens == 0 && return Int[]
    decoder = Decoder(m, limit)
    scores = prefill!(m, decoder, ids, positions, soft, block_size, on_progress)
    output = Int[]
    for step in 1:max_new_tokens
        id = sample_token(scores, temperature, top_k, top_p, rng)
        id in STOP_TOKENS && break
        push!(output, id)
        on_token(id)
        step < max_new_tokens && (scores = forward!(m, decoder, [id]))
    end
    return output
end

Reading the prompt

When you send a question, all its tokens are already known. Caesar can read several at once to build the decoder’s memory. This first read is called prefill. A long question is split into blocks to limit how much memory the calculation needs. Once the last block is read, the decoder has the scores for the first token of the answer.


function prefill!(m, decoder, ids, positions, soft, block_size, on_progress)
    scores = nothing
    depth = length(decoder.layers)
    work = depth * length(ids)
    on_progress(:prefill, 0, work)
    for span in Iterators.partition(eachindex(ids), block_size)
        on_layer(i) = on_progress(:prefill, (first(span) - 1) * depth + length(span) * i, work)
        scores = forward!(m, decoder, view(ids, span); positions = view(positions, :, span), soft, on_layer, logits = last(span) == length(ids))
    end
    return scores
end

Choosing the next token

At temperature zero, Caesar always takes the token with the highest score. This is called greedy decoding. A positive temperature lets it draw a token at random. Lower temperatures favor the highest scores more strongly.

Two settings narrow the draw. For example, top_k = 20 keeps the 20 highest-scoring tokens. With top_p = 0.95, Caesar goes down that shortlist until the tokens it has kept account for at least 95% of the chance of being picked. It draws from those tokens, giving more likely ones more chances.

function sample_token(scores, temperature, top_k, top_p, rng)
    temperature == 0 && return argmax(scores) - 1
    k = top_k == 0 ? length(scores) : min(top_k, length(scores))
    ids = partialsortperm(scores, 1:k; rev = true)
    candidates = scores[ids]
    weights = exp.((candidates .- first(candidates)) ./ temperature)
    cumulative = cumsum(weights)
    cutoff = searchsortedfirst(cumulative, top_p * last(cumulative))
    return ids[searchsortedfirst(cumulative, rand(rng) * cumulative[cutoff])] - 1
end

include("text.jl")
include("prompt.jl")
include("tokenizer.jl")
include("vision.jl")
include("layers.jl")
include("checkpoint.jl")
include("q4.jl")

end

src/text.jl

The hybrid language model

Qwen reads each token through 24 layers. A layer takes the token’s list of numbers, updates it, and passes it on. The layers use two ways to remember earlier text. Three layers update a fixed-size table as each token arrives (Gated DeltaNet). The fourth can look back at individual tokens (full attention). This pattern repeats six times.


const LM = "model.language_model."

Inside a transformer

Think about the word “bank” in “river bank” and “savings bank”. The token for “ bank” starts with the same embedding in both. For the model to use it differently, something from the first word has to reach the second. In a transformer, self-attention gives each token a way to gather information from other tokens in the same sequence.

Each token’s numbers go through three learned calculations. One produces a query (what would help me here?), another a key (what might someone look for here?), and the third a value (what information can I pass along?). The query at “bank” gets compared with each available key. A stronger match gives that token’s value a larger share in the updated numbers for “bank”. Training sets the weights used to make queries, keys and values. The words in this particular phrase determine the shares. Work through one head with numbers.

Attention is one part of a transformer layer. After sharing information across tokens, a small feed-forward network updates each token on its own. It can now respond to the combination of “river” and “bank”. The next layer starts with those updated numbers. Stacking layers lets later tokens draw on connections that earlier layers have already made.

Qwen uses this full attention operation in six of its 24 text layers. The other eighteen gather context through the memory table described below. Its vision encoder uses full attention in every layer. The original transformer diagram shows how attention and feed-forward layers fit together. Attention Is All You Need, figure 1

From embeddings to logits

Follow x through forward!. At the start, each column is the embedding for one token. In each layer, mix! adds information from the tokens read so far. The lines with mlp are the feed-forward network. They expand each token into more numbers, use a learned gate to control which signals pass, then bring it back to its original width. Before each part, rmsnorm rescales its input to keep the numbers in a manageable range. Each .+= adds an update to the numbers already there. This path for carrying earlier information forward is called a residual connection.

In Julia, a name ending in ! usually means the function changes something you pass in. Here forward! updates the decoder’s memory, so the next call can pick up where this one left off.

To predict the next token, Qwen takes the last column and compares it with every entry in the original embedding table. Each result is a score called a logit. A higher score makes that token a more likely continuation.

text_positions(start, n) = repeat(reshape(start:(start + n - 1), 1, :), 3, 1)

function forward!(m, decoder, ids; positions = text_positions(decoder.next_position, length(ids)), soft = Dict(), logits = true, on_layer = Returns(nothing))
    c = m.config["text_config"]
    n = length(ids)
    0 < n <= decoder.limit - decoder.seen || throw(ArgumentError("Decoder context exceeded"))
    size(positions) == (3, n) || throw(DimensionMismatch("Expected three coordinates per token"))
    all(id -> 0 <= id < c["vocab_size"], ids) || throw(ArgumentError("Invalid token ID"))
    # Qwen counts token IDs from zero. Julia counts table columns from one.
    x = Float32.(m.weights[LM * "embed_tokens.weight"][:, ids .+ 1])
    for t in 1:n
        index = decoder.seen + t
        haskey(soft, index) && (x[:, t] = soft[index])
    end
    eps = c["rms_norm_eps"]
    angles = text_angles(c, positions)
    for (i, mem) in enumerate(decoder.layers)
        p = LM * "layers.$(i - 1)."
        z = rmsnorm(m, p * "input_layernorm", x, eps)
        x .+= mix!(mem, m, p, z, angles, decoder.seen, c)
        z = rmsnorm(m, p * "post_attention_layernorm", x, eps)
        gated = silu.(linear(m, p * "mlp.gate_proj", z)) .* linear(m, p * "mlp.up_proj", z)
        x .+= linear(m, p * "mlp.down_proj", gated)
        on_layer(i)
    end
    decoder.seen += n
    decoder.next_position = max(decoder.next_position, maximum(positions) + 1)
    logits || return nothing
    z = rmsnorm(m, LM * "norm", x[:, end:end], eps)
    return vec(linear(m, LM * "embed_tokens", z))
end

Remembering earlier tokens

Once the model writes “Paris”, it needs both that token and what came before it. The Decoder keeps this information between calls. A DeltaNet layer keeps its table and the last three inputs. A full attention layer keeps two lists, called keys and values, with one entry per token.

seen counts tokens. next_position tells us where the next token belongs. These usually advance together. A picture can take several tokens arranged in rows and columns, so the two counters can then differ.


struct DeltaMemory
    history::Matrix{Float32}
    state::Array{Float32, 3}
end

struct KVMemory
    keys::Array{Float32, 3}
    values::Array{Float32, 3}
end

mutable struct Decoder
    layers::Vector{Union{DeltaMemory, KVMemory}}
    seen::Int
    next_position::Int
    limit::Int
end

function Decoder(m, limit)
    c = m.config["text_config"]
    dk, dv = c["linear_key_head_dim"], c["linear_value_head_dim"]
    nk, nv = c["linear_num_key_heads"], c["linear_num_value_heads"]
    layers = map(c["layer_types"]) do kind
        if kind == "linear_attention"
            history = zeros(Float32, 2dk * nk + dv * nv, c["linear_conv_kernel_dim"] - 1)
            DeltaMemory(history, zeros(Float32, dv, dk, nv))
        else
            dims = (c["head_dim"], limit, c["num_key_value_heads"])
            KVMemory(Array{Float32}(undef, dims), Array{Float32}(undef, dims))
        end
    end
    return Decoder(layers, 0, 0, limit)
end

Learning what to remember

Think of S as a table that can remember an association. The key is used to look something up, and the value is what the model wants to find there. For each token, first let some of the old memory fade. Then S * key asks what the table currently returns for this key.

Suppose one number in the result is 2, but the new value says 6. The gap is

  1. If beta is 0.5, the code uses half that gap, 2, as the correction.

It writes the correction using the key, so similar keys feel more of the change. Finally it reads the updated table with a query, the lookup the current token needs. The layer does this several times in parallel. Each of these parts, called a head, has its own table.

function delta_rule!(memory, q, k, v, decay, beta)
    out = similar(v)
    for h in axes(v, 2), t in axes(v, 3)
        S = view(memory, :, :, h)
        kh = cld(h, size(v, 2) ÷ size(k, 2))
        key, query = view(k, :, kh, t), view(q, :, kh, t)
        S .*= decay[h, t]
        correction = beta[h, t] .* (view(v, :, h, t) .- S * key)
        S .+= correction .* key'
        @views mul!(out[:, h, t], S, query)
    end
    return out
end

Local mixing and gates

Word order matters. Before the memory update, this layer combines the current input with the three just before it. Each of the four positions has its own learned weights. Saving the last three inputs lets this work even when a new block starts halfway through a phrase.

A gate controls how much gets through. Here decay sets how much old memory survives, beta sets how strongly to write the correction, and gate adjusts the result on its way to the next layer.

function mix!(mem::DeltaMemory, m, p, x, angles, seen, c)
    p *= "linear_attn."
    dk, dv = c["linear_key_head_dim"], c["linear_value_head_dim"]
    nk, nv = c["linear_num_key_heads"], c["linear_num_value_heads"]
    n = size(x, 2)
    joined = hcat(mem.history, linear(m, p * "in_proj_qkv", x))
    kernel = dropdims(weight(m, p * "conv1d.weight"); dims = 2)
    conv = sum(kernel[i, :] .* view(joined, :, i:(i + n - 1)) for i in axes(kernel, 1))
    mem.history .= view(joined, :, (n + 1):size(joined, 2))
    qkv = silu.(conv)
    unit(z) = z ./ sqrt.(sum(abs2, z; dims = 1) .+ 1.0f-6)
    q = unit(reshape(qkv[1:(dk * nk), :], dk, nk, n)) ./ sqrt(Float32(dk))
    k = unit(reshape(qkv[(dk * nk + 1):(2dk * nk), :], dk, nk, n))
    v = reshape(qkv[(2dk * nk + 1):end, :], dv, nv, n)
    beta = sigmoid.(linear(m, p * "in_proj_b", x))
    step = softplus.(linear(m, p * "in_proj_a", x) .+ weight(m, p * "dt_bias"))
    decay = exp.(-exp.(weight(m, p * "A_log")) .* step)
    y = delta_rule!(mem.state, q, k, v, decay, beta)
    gate = reshape(linear(m, p * "in_proj_z", x), dv, nv, n)
    y = rms(y, c["rms_norm_eps"]) .* weight(m, p * "norm.weight") .* silu.(gate)
    return linear(m, p * "out_proj", reshape(y, :, n))
end

Full attention and three-dimensional positions

The same words in a different order can mean something different. A query and key that only described the words would miss that clue. Text tokens sit on a line, so Qwen repeats the same position number three times. An image uses separate row and column numbers. text_angles turns these positions into angles. Rotating parts of the queries and keys lets their comparison depend on how far apart they are.

function text_angles(c, positions)
    r = c["rope_parameters"]
    half = round(Int, c["head_dim"] * r["partial_rotary_factor"] / 2)
    axes_for_freq = ones(Int, half)
    for axis in 2:3
        stop = min(half, 3 * r["mrope_section"][axis])
        axes_for_freq[axis:3:stop] .= axis
    end
    freq = Float32(r["rope_theta"]) .^ (-Float32.(0:(half - 1)) ./ half)
    return freq .* positions[axes_for_freq, :]
end

One attention head by hand

At “bank” in “river bank”, both tokens are available to look at. Suppose a tiny head gives “bank” a query of 1. Give “river” and “bank” keys of 1 and 0, and values of 6 and 2. These are made-up numbers so we can do the same calculation as the loop below in four lines of Julia.

scores = 1 .* [1, 0]                    # query times each key
weights = exp.(scores)
shares = weights ./ sum(weights)        # about [0.73, 0.27]
sum(shares .* [6, 2])                   # about 4.92

Turning scores into positive shares that add to one is called softmax. “River” supplies about 73% of this head’s mixture, so the result is closer to its value of 6. If both keys matched equally well, each would supply half and the result would be 4.

A real Qwen head compares lists of 256 numbers. It multiplies matching entries, adds the products (a dot product), and divides by √256 so the scores stay on a useful scale. Eight query heads do this in parallel and can learn different ways to match. They share two sets of keys and values to save space. The final o_proj mixes the heads’ outputs together.

The prefix in the loop is the causal mask. At “river” only the first token is visible. At “bank” both are. This rule also holds while reading a whole prompt in one call. When the next token arrives, its query can reuse the keys and values already saved in mem.

function mix!(mem::KVMemory, m, p, x, angles, seen, c)
    p *= "self_attn."
    d, heads, nk = c["head_dim"], c["num_attention_heads"], c["num_key_value_heads"]
    n, eps = size(x, 2), c["rms_norm_eps"]
    packed = reshape(linear(m, p * "q_proj", x), 2d, heads, n)
    q = rotate!(rmsnorm(m, p * "q_norm", view(packed, 1:d, :, :), eps), angles)
    gate = view(packed, (d + 1):2d, :, :)
    k = reshape(linear(m, p * "k_proj", x), d, nk, n)
    k = rotate!(rmsnorm(m, p * "k_norm", k, eps), angles)
    v = reshape(linear(m, p * "v_proj", x), d, nk, n)
    span = (seen + 1):(seen + n)
    mem.keys[:, span, :] .= PermutedDimsArray(k, (1, 3, 2))
    mem.values[:, span, :] .= PermutedDimsArray(v, (1, 3, 2))
    out = similar(q)
    for h in 1:heads, t in 1:n
        kh = cld(h, heads ÷ nk)
        # Token t can look back at earlier tokens and at itself.
        prefix = 1:(seen + t)
        @views scores = (mem.keys[:, prefix, kh]' * q[:, h, t]) ./ sqrt(Float32(d))
        probabilities!(scores)
        @views mul!(out[:, h, t], mem.values[:, prefix, kh], scores)
    end
    return linear(m, p * "o_proj", reshape(out .* sigmoid.(gate), :, n))
end

src/prompt.jl

Assembling a chat prompt

When you type “Hello!”, Qwen also needs to know who said it and whose turn comes next. Caesar adds the chat markers Qwen learned during training. One marks the start of your message, another marks its end, and the next says the assistant is about to speak. By default Caesar also closes the <think> section so the reply can begin.

Mixing tokens and coordinates

A picture has to fit into the same sequence as the words around it. Caesar reserves one place for each group of image patches. The token ID at each of those places says “image here”. The soft dictionary holds the actual list of numbers describing that part of the picture.

Every place also gets three position numbers for time, row and column. For an ordinary text token at position 5, all three are 5. If a picture starts at 5, its top-left group gets (5, 5, 5) and the group to its right gets (5, 5, 6). Text resumes past the largest picture coordinate. The decoder still reads the whole sequence in order.

function prepare_prompt(m, t, text; media = [], chat = true, thinking = false, on_progress = Returns(nothing))
    ids = Int[]
    coords = NTuple{3, Int}[]
    soft = Dict{Int, AbstractVector{Float32}}()
    cursor = 0
    pending = IOBuffer()
    chat && print(pending, "<|im_start|>user\n")
    function flush_text()
        tokens = encode(t, String(take!(pending)))
        append!(ids, tokens)
        append!(coords, ((i, i, i) for i in cursor:(cursor + length(tokens) - 1)))
        return cursor += length(tokens)
    end
    function insert(kind, features, w, h)
        print(pending, "<|vision_start|>")
        flush_text()
        nx, ny = w ÷ 32, h ÷ 32
        size(features, 2) == nx * ny || throw(DimensionMismatch("Visual grid and features differ"))
        for y in 0:(ny - 1), x in 0:(nx - 1)
            push!(ids, m.config[string(kind) * "_token_id"])
            push!(coords, (cursor, cursor + y, cursor + x))
            soft[length(ids)] = view(features, :, 1 + x + nx * y)
        end
        cursor += max(nx, ny)
        return print(pending, "<|vision_end|>")
    end
    for (kind, file) in media
        path = abspath(file)
        isfile(path) || throw(ArgumentError("Missing media file $path"))
        info = visual_stream(path)
        if kind == :image
            w, h = frame_size(info.width, info.height, 65536, 16777216)
            insert(kind, image_features(m, read_frame(path, w, h); on_progress), w, h)
        elseif kind == :video
            times = video_times(info)
            w, h = frame_size(info.width, info.height, 4096, 25165824 ÷ length(times))
            for pair in Iterators.partition(times, 2)
                frames = stack(read_frame(path, w, h; time) for time in pair)
                print(pending, "<", format_timestamp(sum(pair) / 2), " seconds>")
                insert(kind, image_features(m, frames; on_progress), w, h)
            end
        else
            throw(ArgumentError("Expected an image or video, got $kind"))
        end
    end
    content = chat ? (isempty(media) ? strip(text) : rstrip(text)) : text
    print(pending, content)
    if chat
        print(pending, "<|im_end|>\n<|im_start|>assistant\n<think>\n")
        thinking || print(pending, "\n</think>\n\n")
    end
    flush_text()
    positions = isempty(coords) ? zeros(Int, 3, 0) : stack(coords)
    return (; ids, soft, positions)
end

format_timestamp(t) = @sprintf("%.1f", t)

Reading images and video

FFmpeg turns a file into red, green and blue pixel values. Caesar resizes each frame so its width and height are multiples of 32. That way the vision model can cut it into 16-by-16 squares and group neighboring squares in twos along each side.

For video, Caesar samples frames along the clip and reads them in pairs. It puts the time halfway between the two frames into the prompt, so Qwen can tell when something happened. If a frame is left over, Caesar pairs it with a copy of itself.

function frame_size(w, h, min_pixels, max_pixels)
    max(w, h) <= 200min(w, h) || throw(ArgumentError("Image aspect ratio exceeds 200:1"))
    width, height = max.(32, 32 .* round.(Int, (w, h) ./ 32))
    if width * height > max_pixels
        scale = sqrt(max_pixels / (w * h))
        return max.(32, 32 .* floor.(Int, (w, h) .* (scale / 32)))
    elseif width * height < min_pixels
        scale = sqrt(min_pixels / (w * h))
        return 32 .* ceil.(Int, (w, h) .* (scale / 32))
    end
    return width, height
end

function read_frame(path, width, height; time = nothing)
    timing = isnothing(time) ? String[] : ["-ss", string(time)]
    filter = "scale=$width:$height:flags=bicubic"
    raw = read(`ffmpeg -v error -nostdin $timing -i $path -map 0:v:0 -frames:v 1 -vf $filter -f rawvideo -pix_fmt rgb24 pipe:1`)
    length(raw) == 3width * height || error("Could not decode frame from $path")
    return reshape(Float32.(raw) ./ 255.0f0, 3, width, height)
end

function video_times(info)
    s = info.stream
    duration = parse(Float64, get(s, "duration", get(info.format, "duration", "0")))
    duration > 0 || error("Video duration is unavailable")
    a, b = parse.(Int, split(s["avg_frame_rate"], '/'))
    rate = a / b
    isfinite(rate) && rate > 0 || error("Video frame rate is unavailable")
    frames = something(tryparse(Int, get(s, "nb_frames", "")), max(1, round(Int, duration * rate)))
    n = clamp(round(Int, 2duration), min(4, frames), min(32, frames))
    times = round.(Int, range(0, frames - 1; length = n)) ./ rate
    isodd(n) && push!(times, last(times))
    return times
end

function visual_stream(path)
    fields = "stream=width,height,avg_frame_rate,nb_frames,duration:stream_side_data=rotation:format=duration"
    info = JSON.parse(read(`ffprobe -v error -select_streams v:0 -show_entries $fields -of json $path`, String))
    isempty(info["streams"]) && error("No visual stream in $path")
    stream = first(info["streams"])
    width, height = stream["width"], stream["height"]
    rotation = sum(get(d, "rotation", 0) for d in get(stream, "side_data_list", []); init = 0)
    if isodd(round(Int, rotation / 90))
        width, height = height, width
    end
    return (; width, height, stream, format = info["format"])
end

src/tokenizer.jl

From text to token IDs

A tokenizer translates between text and the numbers Qwen uses. The file tokenizer.json contains its vocabulary and the rules for building tokens. There is an entry for every possible byte, so even an unfamiliar word has a starting point. Common groups of bytes also have entries of their own.

Before splitting ordinary text, Caesar gives equivalent spellings the same form. For example, an e followed by a combining accent becomes é. This step is called Unicode normalization (NFC). Qwen’s rules then split the text into pieces, and the next function works on each piece in turn.

struct Tokenizer
    vocab::Dict{String, Int}
    pieces::Dict{Int, Vector{UInt8}}
    merges::Dict{Tuple{Int, Int}, Tuple{Int, Int}}
    added::Regex
    special_ids::Set{Int}
    split_pattern::Regex
    byte_ids::Vector{Int}
end

function Tokenizer(dir::AbstractString)
    t = JSON.parsefile(joinpath(dir, "tokenizer.json"))
    model = t["model"]
    vocab = Dict{String, Int}(model["vocab"])
    visible = vcat(33:126, 161:172, 174:255)
    others = setdiff(0:255, visible)
    alphabet = Dict(zip(vcat(visible, others), Char.(vcat(visible, 256:(255 + length(others))))))
    byte_for = Dict(ch => UInt8(b) for (b, ch) in alphabet)
    pieces = Dict(id => [byte_for[ch] for ch in piece] for (piece, id) in vocab)
    merges = Dict(
        (vocab[a], vocab[b]) => (rank, vocab[a * b])
            for (rank, pair) in enumerate(model["merges"]) for (a, b) in (split(pair, ' '),)
    )
    added = t["added_tokens"]
    for token in added
        vocab[token["content"]] = token["id"]
        pieces[token["id"]] = collect(codeunits(token["content"]))
    end
    markers = sort([a["content"] for a in added]; by = length, rev = true)
    pattern = Regex(join(("\\Q" * s * "\\E" for s in markers), "|"))
    specials = Set(Int(a["id"]) for a in added if a["special"])
    splitter = t["pre_tokenizer"]["pretokenizers"][1]["pattern"]["Regex"]
    return Tokenizer(vocab, pieces, merges, pattern, specials, Regex(splitter), [vocab[string(alphabet[b])] for b in 0:255])
end
Tokenizer(m::Model) = Tokenizer(m.dir)

Merging adjacent pieces

Take the word cat. It starts as three pieces, c, a and t. Qwen’s rules give a + t priority over c + a, so the first merge leaves c and at. Those two can merge again. The result is one token, ID 4466. This repeated joining of pairs is called byte-pair encoding (BPE).

The queue remembers which allowed pair comes first in the rules. After a merge, only the pairs touching the new piece need another look.

function merge_pieces(t, text)
    ids = [t.byte_ids[Int(b) + 1] for b in codeunits(text)]
    n = length(ids)
    n < 2 && return ids
    prev, next = collect(0:(n - 1)), collect(2:(n + 1))
    queue = BinaryMinHeap{Tuple{Int, Int, Int}}()
    function candidate(i)
        return if 1 <= i <= n && next[i] <= n
            merge = get(t.merges, (ids[i], ids[next[i]]), nothing)
            isnothing(merge) || push!(queue, (first(merge), i, last(merge)))
        end
    end
    foreach(candidate, 1:(n - 1))
    while !isempty(queue)
        rank, i, combined = pop!(queue)
        j = next[i]
        # An earlier merge may have used up one of the pieces in this pair.
        (ids[i] < 0 || j > n) && continue
        get(t.merges, (ids[i], ids[j]), nothing) == (rank, combined) || continue
        ids[i], ids[j], next[i] = combined, -1, next[j]
        next[i] <= n && (prev[next[i]] = i)
        candidate(prev[i])
        candidate(i)
    end
    return filter(>=(0), ids)
end

Crossing token boundaries

A chat marker such as <|im_end|> already has its own ID. encode picks out these markers, then applies the usual rules to the text between them.

Going back to text takes care because one character can span several tokens. For example, Qwen splits 🚲 into three tokens. The first holds two bytes and the others hold one each. decode joins the four bytes before reading them as a character.

function encode(t::Tokenizer, text::AbstractString)
    ids = Int[]
    function ordinary(span)
        for part in eachmatch(t.split_pattern, Unicode.normalize(span, :NFC))
            append!(ids, merge_pieces(t, part.match))
        end
        return
    end
    cursor = firstindex(text)
    for marker in eachmatch(t.added, text)
        ordinary(SubString(text, cursor, prevind(text, marker.offset)))
        push!(ids, t.vocab[marker.match])
        cursor = marker.offset + ncodeunits(marker.match)
    end
    ordinary(SubString(text, cursor))
    return ids
end

function decode(t::Tokenizer, ids; skip_special = true)
    bytes = UInt8[]
    for id in ids
        skip_special && id in t.special_ids && continue
        haskey(t.pieces, id) && append!(bytes, t.pieces[id])
    end
    return decode_bytes(bytes)
end

function decode_bytes(bytes)
    raw = String(bytes)
    return isvalid(raw) ? raw : join(isvalid(ch) ? ch : '�' for ch in raw)
end

src/vision.jl

From pixels to vision tokens

Qwen reads a picture a little at a time. It cuts the picture into squares called patches, each 16 pixels on a side. For video, one patch covers the same square in two frames. For a still photo, Caesar feeds in the photo twice so the same code can read it.

Merging into the language model

Take a 64-by-64 image as an example. It has 16 patches in a 4-by-4 grid. Each patch starts as a list of pixel values. Over 24 layers, the model updates each patch’s numbers using information from across the picture.

At the end, it joins each 2-by-2 group of neighbors into one list of 2,048 numbers, the same length as a text token’s embedding. Our example produces four such lists. They fill four places in the decoder’s prompt.

function image_features(m, frames::AbstractArray{Float32, 4}; on_progress = Returns(nothing))
    c = m.config["vision_config"]
    patch, merge = c["patch_size"], c["spatial_merge_size"]
    channels, w, h, time = size(frames)
    channels == 3 && time == c["temporal_patch_size"] &&
        all(n -> n > 0 && n % (patch * merge) == 0, (w, h)) ||
        throw(ArgumentError("Expected two RGB frames with sides divisible by $(patch * merge)"))
    base = "model.visual."
    data = patches(2.0f0 .* frames .- 1.0f0, patch, merge)
    wpatch = m.weights[base * "patch_embed.proj.weight"]
    x = project(reshape(wpatch, :, c["hidden_size"]), data) .+ weight(m, base * "patch_embed.proj.bias")
    pos, angles = visual_positions(m, w ÷ patch, h ÷ patch, c)
    x .+= pos
    on_progress(:vision, 0, c["depth"])
    for i in 0:(c["depth"] - 1)
        p = base * "blocks.$i."
        x .+= vision_attention(m, p * "attn.", layernorm(m, p * "norm1", x), angles, c)
        z = gelu.(affine(m, p * "mlp.linear_fc1", layernorm(m, p * "norm2", x)))
        x .+= affine(m, p * "mlp.linear_fc2", z)
        on_progress(:vision, i + 1, c["depth"])
    end
    merged = reshape(layernorm(m, base * "merger.norm", x), c["hidden_size"] * merge^2, :)
    z = affine(m, base * "merger.linear_fc1", merged)
    return affine(m, base * "merger.linear_fc2", 0.5f0 .* z .* (1.0f0 .+ erf.(z ./ sqrt(2.0f0))))
end

"""Encode a resized RGB image with shape (channel, x, y) and values in [0,1]."""
image_features(m, rgb::AbstractArray{Float32, 3}; kwargs...) = image_features(m, stack((rgb, rgb)); kwargs...)

Dividing frames into patches

The input array is laid out like a picture. The next calculation wants one column per patch. patches rearranges the same pixel values into columns and puts the four patches that will later be joined next to each other. A column includes all three colors from both frames.


function patches(frames, patch, merge)
    channels, width, height, time = size(frames)
    nx, ny = width ÷ patch, height ÷ patch
    grid = reshape(frames, channels, patch, merge, nx ÷ merge, patch, merge, ny ÷ merge, time)
    packed = permutedims(grid, (2, 5, 8, 1, 3, 6, 4, 7))
    return reshape(packed, patch^2 * time * channels, :)
end

Locating each patch

A patch’s pixels tell Qwen what it contains. Two more clues tell Qwen where it belongs. First, Qwen learned a square grid of position values. To fit a wide or tall picture, the code finds each patch’s spot on that grid and blends the values of the four surrounding grid points.

Second, the row sets some rotation angles and the column sets the rest. The attention calculation below uses these angles when it compares two patches, so their distance across the picture matters too.

function visual_positions(m, nx, ny, c)
    merge = c["spatial_merge_size"]
    coords = vec(
        [
            (u + merge * bx, v + merge * by) for u in 0:(merge - 1), v in 0:(merge - 1),
                bx in 0:(nx ÷ merge - 1), by in 0:(ny ÷ merge - 1)
        ]
    )
    xs, ys = first.(coords), last.(coords)
    table = m.weights["model.visual.pos_embed.weight"]
    side = isqrt(size(table, 2))
    col = Float32.(xs) .* ((side - 1) / Float32(nx - 1))
    row = Float32.(ys) .* ((side - 1) / Float32(ny - 1))
    positions = zeros(Float32, size(table, 1), length(coords))
    for (x, wx) in ((floor.(Int, col), 1 .- mod.(col, 1)), (ceil.(Int, col), mod.(col, 1))),
            (y, wy) in ((floor.(Int, row), 1 .- mod.(row, 1)), (ceil.(Int, row), mod.(row, 1)))
        indices = clamp.(x, 0, side - 1) .+ side .* clamp.(y, 0, side - 1) .+ 1
        positions .+= Float32.(table[:, indices]) .* (wx .* wy)'
    end
    quarter = c["hidden_size"] ÷ c["num_heads"] ÷ 4
    freq = 10000.0f0 .^ (-Float32.(0:(quarter - 1)) ./ quarter)
    angles = vcat(freq * Float32.(ys)', freq * Float32.(xs)')
    return positions, angles
end

function layernorm(m, p, x)
    centered = x .- sum(x; dims = 1) ./ size(x, 1)
    return rms(centered, 1.0f-6) .* weight(m, p * ".weight") .+ weight(m, p * ".bias")
end

Looking across the frame

A patch containing a wheel may be easier to interpret when another patch contains handlebars. Each patch gets a query that it compares with a key from every patch. A good match gives the other patch’s information more weight in the result. This is attention applied to a picture.

The whole picture is available from the start. The wheel patch can use the handlebars even if their patch comes later in the grid. The code handles up to 128 queries at once to keep the score table small. Each query still compares with every patch, using the same weighted sum as the worked text example.

function vision_attention(m, p, x, angles, c)
    heads, n = c["num_heads"], size(x, 2)
    d = size(x, 1) ÷ heads
    qkv = reshape(affine(m, p * "qkv", x), d, heads, 3, n)
    q, k, v = eachslice(qkv; dims = 3)
    rotate!(q, angles)
    rotate!(k, angles)
    out = similar(q)
    for h in 1:heads, span in Iterators.partition(1:n, 128)
        @views scores = (k[:, h, :]' * q[:, h, span]) ./ sqrt(Float32(d))
        foreach(probabilities!, eachcol(scores))
        @views mul!(out[:, h, span], v[:, h, :], scores)
    end
    return affine(m, p * "proj", reshape(out, :, n))
end

src/layers.jl

The math shared by both networks

Both the text and vision models build new numbers out of the ones they already have. A linear layer multiplies each input by a learned weight and adds up the products. With inputs 2 and 3 and weights 4 and 5, one output would be 2 × 4 + 3 × 5 = 23.

A matrix is a table of numbers. In W' * x, each column of W holds the weights for one output, and each column of x holds one token’s inputs. One matrix multiplication does all those weighted sums. The small functions below also let a layer add a fixed offset (bias), control how much of a value passes through (sigmoid), or rescale a column (rms).


weight(m, name) = Float32.(m.weights[name])
function linear(m, name, x)
    w = m.weights[name * ".weight"]
    read_ahead(w)
    return project(w, x)
end
affine(m, name, x) = linear(m, name, x) .+ weight(m, name * ".bias")
sigmoid(x) = inv(1.0f0 + exp(-x))
silu(x) = x * sigmoid(x)
softplus(x) = max(x, 0.0f0) + log1p(exp(-abs(x)))
gelu(x) = 0.5f0 * x * (1.0f0 + tanh(0.79788456f0 * (x + 0.044715f0 * x^3)))
rms(x, eps) = x ./ sqrt.(sum(abs2, x; dims = 1) ./ size(x, 1) .+ Float32(eps))
rmsnorm(m, p, x, eps) = rms(x, eps) .* (1.0f0 .+ weight(m, p * ".weight"))
function probabilities!(x)
    x .= exp.(x .- maximum(x))
    return x ./= sum(x)
end

Rotary pairs

Think of two numbers as a point on a circle. Turning it a quarter turn moves (1, 0) to (0, 1). Qwen pairs up numbers from a query or key and turns each pair by an angle that depends on its position.

Why turn them? When a query and a key are compared later, the difference between their turns carries information about the distance between their positions. The sines and cosines below do the turning.

function rotate!(x, angles)
    half = size(angles, 1)
    c = reshape(cos.(angles), half, 1, :)
    s = reshape(sin.(angles), half, 1, :)
    a, b = copy(view(x, 1:half, :, :)), view(x, (half + 1):2half, :, :)
    @views x[1:half, :, :] .= c .* a .- s .* b
    b .= s .* a .+ c .* b
    return x
end

Multiplying the weights

While reading a prompt, the model applies the same weights to several tokens. Caesar copies a small block of weights into a temporary array and lets Julia’s matrix library, BLAS, use it for all those tokens. The next layer can reuse the space.

While writing an answer, there is only one new token. Each output needs just one weighted sum. Julia threads can calculate different outputs at the same time. Each thread reads the stored weights as it needs them.

const TILE_KEY = gensym(:caesar_tile)

function neuron_dot(weights, j, input)
    total = 0.0f0
    @inbounds @simd for i in eachindex(input)
        total += Float32(weights[i, j]) * input[i]
    end
    return total
end

unpack_tile!(tile, w, cols) = copyto!(tile, view(w, :, cols))

function project(w::AbstractMatrix, x::AbstractMatrix{Float32})
    input, output = size(w)
    size(x, 1) == input || throw(DimensionMismatch("Projection input width"))
    y = Matrix{Float32}(undef, output, size(x, 2))
    if size(x, 2) == 1
        token = vec(x)
        Threads.@threads for j in axes(w, 2)
            y[j] = neuron_dot(w, j, token)
        end
        return y
    end
    rows = min(output, max(1, (1 << 20) ÷ input))
    scratch = get!(Vector{Float32}, task_local_storage(), TILE_KEY)
    length(scratch) < input * rows && resize!(scratch, input * rows)
    tile = reshape(view(scratch, 1:(input * rows)), input, rows)
    for cols in Iterators.partition(axes(w, 2), rows)
        part = view(tile, :, 1:length(cols))
        unpack_tile!(part, w, cols)
        @views mul!(y[cols, :], part', x)
    end
    return y
end

Reading mapped weights on macOS

Some of the weights may still be on disk when a layer needs them. Waiting for them can take longer than doing the math. read_ahead tells macOS which block of weights comes next, so it has a chance to start reading early.

function read_ahead(w)
    if Sys.isapple() && w isa Matrix{BFloat16} && sizeof(w) >= 4096
        try
            Mmap.madvise!(w, Mmap.MADV_WILLNEED)
        catch err
            err isa SystemError || rethrow()
        end
    end
    return nothing
end

Native matrix multiplication

Apple ships a library called Accelerate for calculations such as matrix multiplication. Caesar’s command-line tools use it on a Mac. The suffix below selects the version that uses the same size of integer as Julia for row and column numbers.

function native_blas!()
    return if Sys.isapple()
        BLAS.lbt_forward(
            "/System/Library/Frameworks/Accelerate.framework/Accelerate";
            suffix_hint = "\x1a\$NEWLAPACK\$ILP64"
        )
    end
end

src/checkpoint.jl

Getting the checkpoint on first run

The first run needs three files. One describes the model’s layers, one holds the tokenizer’s vocabulary and rules, and the largest holds the learned numbers. Caesar downloads a specific version of each. It checks the size and a fingerprint of the contents (SHA-256) before using a download. An interrupted download can continue where it left off.

On later runs Caesar checks the file sizes and uses the local copies. Run fetch-model to check their fingerprints again.


const MODEL_ID = "Qwen/Qwen3.5-2B"
const REVISION = "15852e8c16360a2fea060d615a32b45270f8a8fc"
const SHARD = "model.safetensors-00001-of-00001.safetensors"
default_model_dir() = joinpath(
    get(ENV, "XDG_CACHE_HOME", joinpath(homedir(), ".cache")),
    "caesar", MODEL_ID, REVISION
)

const MODEL_FILES = [
    ("config.json", 2908, "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4"),
    ("tokenizer.json", 12807982, "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42"),
    (SHARD, 4548221488, "aa33250c4fc64891ddfaba3a314fd9542ea371843c387178b425fbcc5ed680b1"),
]

function fetch_model(dir = default_model_dir(); verify = false)
    matches(name, size) = isfile(joinpath(dir, name)) && filesize(joinpath(dir, name)) == size
    !verify && all(f -> matches(f[1], f[2]), MODEL_FILES) && return dir
    mkpath(dir)
    lock = joinpath(dir, "download.pid")
    isfile(lock) && println(stderr, "Waiting for the current Qwen download…")
    mkpidlock(lock; stale_age = 15) do
        for (name, size, digest) in MODEL_FILES
            path = joinpath(dir, name)
            if matches(name, size)
                !verify || bytes2hex(open(sha256, path)) == digest ||
                    error("Checksum mismatch in $path")
                continue
            end
            url = "https://huggingface.co/$MODEL_ID/resolve/$REVISION/$name"
            part = path * ".part"
            println(stderr, "Fetching $name ($(round(size / 1.0e6; digits = 1)) MB)")
            if !isfile(part) || filesize(part) < size
                run(`curl --fail --location --retry 3 --continue-at - --progress-bar --output $part $url`)
            end
            if filesize(part) != size || bytes2hex(open(sha256, part)) != digest
                rm(part)
                error("Incomplete or corrupt $name. Run Caesar again to retry.")
            end
            mv(part, path; force = true)
        end
    end
    return dir
end

Mapping the weights

The weights file starts with an index. For each array of numbers (a tensor), the index says where its bytes start and end, how to arrange them, and how many bytes each number takes. Most weights use two bytes each (BF16). Some use four (Float32).

Mmap.mmap lets Julia use those bytes as an array and lets the operating system bring them into memory as needed. Julia and the file list the dimensions in opposite orders, so the loader reverses the dimensions without moving the numbers.

load_model(; kwargs...) = load_model(fetch_model(); kwargs...)

function load_model(dir::AbstractString; q4 = false, on_progress = Returns(nothing))
    config = JSON.parsefile(joinpath(dir, "config.json"); dicttype = Dict{String, Any})
    config["architectures"] == ["Qwen3_5ForConditionalGeneration"] &&
        config["text_config"]["hidden_size"] == 2048 || error("Expected $MODEL_ID in $dir")
    weights = Dict{String, AbstractArray}()
    open(joinpath(dir, SHARD)) do io
        ENDIAN_BOM == 0x04030201 || error("A little-endian machine is required")
        n = read(io, UInt64)
        n <= min(100_000_000, filesize(io) - 8) || error("Invalid safetensors header length")
        header = JSON.parse(String(read(io, n)))
        start = position(io)
        for (name, entry) in header
            name == "__metadata__" && continue
            T = Dict("BF16" => BFloat16, "F32" => Float32)[entry["dtype"]]
            dims = Tuple(reverse(Int.(entry["shape"])))
            lo, hi = entry["data_offsets"]
            all(>=(0), dims) && 0 <= lo <= hi <= filesize(io) - start &&
                hi - lo == sizeof(T) * prod(big.(dims); init = big(1)) || error("Invalid tensor extent for $name")
            weights[name] = Mmap.mmap(io, Array{T, length(dims)}, dims, start + lo; grow = false)
        end
    end
    m = Model(abspath(dir), config, weights)
    return q4 ? pack_decoder!(m, on_progress) : m
end

src/q4.jl

Keeping weights in four bits

To generate each token, Qwen reads its weights again. On a laptop this can take longer than the math. The optional --q4 setting makes the decoder weights smaller by rounding them. That saves reading time and can change which token wins.

Take a group of 32 weights. They share one step size, called the scale. If the scale is 0.25, a weight of 0.72 rounds to three steps and reads back as 0.75. Each step count is an integer from −7 to 7. Two counts fit in one byte. The calculations still use 32-bit numbers.

struct Q4Matrix <: AbstractMatrix{Float32}
    scales::Matrix{Float16}
    codes::Array{UInt8, 3}
end

const Q4_GROUP = 32
const Q4_HALF = Q4_GROUP ÷ 2
Base.size(w::Q4Matrix) = (Q4_GROUP * size(w.scales, 1), size(w.scales, 2))
low(code) = Float32(Int32(code & 0x0f) - 8)
high(code) = Float32(Int32(code >> 4) - 8)

function Base.getindex(w::Q4Matrix, i::Int, j::Int)
    @boundscheck checkbounds(w, i, j)
    group, slot = divrem(i - 1, Q4_GROUP)
    code = w.codes[slot % Q4_HALF + 1, group + 1, j]
    return Float32(w.scales[group + 1, j]) * (slot < Q4_HALF ? low(code) : high(code))
end

function pack_groups(weights)
    blocks = reshape(Float32.(weights), Q4_GROUP, :, size(weights, 2))
    scales = Float16.(maximum(abs, blocks; dims = 1) ./ 7.0f0)
    divisor = ifelse.(iszero.(scales), 1.0f0, Float32.(scales))
    # Adding 8 lets us store a negative step count in four unsigned bits.
    levels = UInt8.(8 .+ clamp.(round.(Int, blocks ./ divisor), -7, 7))
    codes = levels[1:Q4_HALF, :, :] .| (levels[(Q4_HALF + 1):end, :, :] .<< 4)
    return dropdims(scales; dims = 1), codes
end

Multiplying packed weights

When several tokens need the same weights, Caesar unpacks a small block once and uses it for all of them. For a single token it can work directly from the bytes. It reads the two counts in each byte, multiplies each by its matching input, and adds the products. All 32 weights in a group share a scale, so it can multiply the group’s sum by that scale just once.

function unpack_tile!(tile, w::Q4Matrix, cols)
    blocks = reshape(tile, Q4_GROUP, size(w.scales, 1), :)
    codes = view(w.codes, :, :, cols)
    scales = reshape(view(w.scales, :, cols), 1, size(w.scales, 1), :)
    @views blocks[1:Q4_HALF, :, :] .= low.(codes) .* scales
    @views blocks[(Q4_HALF + 1):end, :, :] .= high.(codes) .* scales
    return tile
end

function neuron_dot(w::Q4Matrix, j, input)
    total = 0.0f0
    @inbounds for group in axes(w.scales, 1)
        first = (group - 1) * Q4_GROUP
        subtotal = 0.0f0
        @simd for i in 1:Q4_HALF
            code = w.codes[i, group, j]
            subtotal += low(code) * input[first + i] + high(code) * input[first + i + Q4_HALF]
        end
        total += Float32(w.scales[group, j]) * subtotal
    end
    return total
end

Building a reusable local cache

The first run with --q4 makes a second file containing the smaller weights. Caesar converts a few columns at a time so the whole conversion can fit on a laptop. It writes the scale values and packed bytes for each matrix in a fixed order so it can find them again.

Caesar uses a temporary name while it writes. Only a complete file gets the final name, so a second run can safely open and reuse it.

function pack_decoder!(m, on_progress)
    names = sort([k for (k, w) in m.weights if startswith(k, LM) && ndims(w) == 2])
    shard = realpath(joinpath(m.dir, SHARD))
    st = stat(shard)
    signature = join(("q4-v1", shard, st.device, st.inode, st.size, st.mtime, st.ctime), '\n')
    root = joinpath(get(ENV, "XDG_CACHE_HOME", joinpath(homedir(), ".cache")), "caesar", "packed")
    mkpath(root)
    file = joinpath(root, bytes2hex(sha256(signature)) * ".q4")
    expected = sum(length(m.weights[k]) ÷ Q4_GROUP * (Q4_HALF + 2) for k in names)
    ready() = isfile(file) && filesize(file) == expected
    if !ready()
        mkpidlock(file * ".pid"; stale_age = 15) do
            ready() && return
            mktemp(root) do tmp, io
                offset = 0
                on_progress(:packing, 0, expected)
                for name in names
                    w = m.weights[name]
                    input, output = size(w)
                    groups = input ÷ Q4_GROUP
                    input % Q4_GROUP == 0 || error("Unaligned Q4 matrix: $name")
                    codes_start = offset + 2groups * output
                    for cols in Iterators.partition(1:output, max(1, (1 << 19) ÷ input))
                        scales, codes = pack_groups(view(w, :, cols))
                        seek(io, offset + 2groups * (first(cols) - 1))
                        write(io, scales)
                        seek(io, codes_start + Q4_HALF * groups * (first(cols) - 1))
                        write(io, codes)
                        on_progress(:packing, offset + (Q4_HALF + 2) * groups * last(cols), expected)
                    end
                    offset += (Q4_HALF + 2) * groups * output
                end
                close(io)
                filesize(tmp) == expected || error("Incomplete Q4 cache")
                mv(tmp, file; force = true)
            end
        end
    end
    open(file) do io
        offset = 0
        for name in names
            input, output = size(m.weights[name])
            groups = input ÷ Q4_GROUP
            scales = Mmap.mmap(io, Matrix{Float16}, (groups, output), offset; grow = false)
            offset += sizeof(scales)
            codes = Mmap.mmap(io, Array{UInt8, 3}, (Q4_HALF, groups, output), offset; grow = false)
            offset += sizeof(codes)
            m.weights[name] = Q4Matrix(scales, codes)
        end
    end
    return m
end

bin/caesar

Running Caesar

Run caesar 'Hello!' to send Qwen a message. The command prints progress as the model loads and reads your prompt. The answer appears a piece at a time as Qwen chooses tokens. Progress goes to standard error, so piping the command’s output sends just the answer to the next program.

using Pkg
Pkg.activate(joinpath(@__DIR__, ".."); io = devnull)

const USAGE = """
Usage: caesar [options] [--] PROMPT

  --model DIR          Local Qwen3.5-2B checkpoint
  --tokens N           Maximum continuation length (default 32)
  --temperature T      Zero for greedy decoding (default), positive for sampling
  --image FILE         Prepend an image
  --q4                 Cache four-bit decoder weights for lower memory use
  --think              Enable the thinking prefix
  --raw                Use a raw completion prompt
  --video FILE         Prepend up to 32 time-stamped frames
  --help               Show this message

Media options can be repeated and are processed in the order supplied.
"""
if ARGS == ["--help"]
    print(USAGE)
    exit()
end

Pkg.instantiate(; allow_autoprecomp = false)
using Caesar

function main(args)
    Caesar.native_blas!()
    args = copy(args)
    dir = nothing
    media = Pair{Symbol, String}[]
    thinking, chat, q4 = false, true, false
    n, temp = 32, 0.0
    while !isempty(args) && startswith(first(args), "--")
        flag = popfirst!(args)
        flag == "--" && break
        flag == "--help" && return print(USAGE)
        if flag == "--q4"
            q4 = true
            continue
        elseif flag == "--think"
            thinking = true
            continue
        elseif flag == "--raw"
            chat = false
            continue
        end
        flag in ("--model", "--tokens", "--temperature", "--image", "--video") ||
            throw(ArgumentError("Unknown option $flag"))
        isempty(args) && throw(ArgumentError("Missing value for $flag"))
        value = popfirst!(args)
        if flag == "--model"
            dir = value
        elseif flag == "--tokens"
            n = parse(Int, value)
        elseif flag == "--temperature"
            temp = parse(Float64, value)
        else
            push!(media, Symbol(flag[3:end]) => value)
        end
    end
    length(args) == 1 || throw(ArgumentError(USAGE))
    println(stderr, "Loading Qwen3.5-2B…")
    flush(stderr)
    last_percent = -1
    function progress(stage, done, total)
        percent = 100done ÷ total
        label = (vision = "Encoding vision", prefill = "Processing prompt", packing = "Preparing four-bit cache")[stage]
        percent == last_percent && done != 0 && return
        if stderr isa Base.TTY
            print(stderr, '\r', label, "… ", percent, "%   ")
            done == total && println(stderr)
        elseif done == 0 || percent ÷ 25 > last_percent ÷ 25
            println(stderr, label, "… ", percent, "%")
        end
        flush(stderr)
        return last_percent = percent
    end
    m = isnothing(dir) ? load_model(; q4, on_progress = progress) : load_model(dir; q4, on_progress = progress)
    tokenizer = Tokenizer(m)
    bytes = UInt8[]
    function emit(id)
        id in tokenizer.special_ids && return
        haskey(tokenizer.pieces, id) || return
        append!(bytes, tokenizer.pieces[id])
        return if isvalid(String, bytes)
            write(stdout, bytes)
            flush(stdout)
            empty!(bytes)
        end
    end
    generate(m, only(args); tokenizer, media, thinking, chat, max_new_tokens = n, temperature = temp, on_token = emit, on_progress = progress)
    return println(Caesar.decode_bytes(bytes))
end
try
    main(ARGS)
catch err
    println(stderr, "caesar: ", sprint(showerror, err))
    exit(1)
end

bin/caesar-bench

Measuring token throughput

How long do you wait for an answer to start, and how fast does it appear after that? This command uses the same generation loop as caesar. The first timer runs from the start of generation until the first token is ready. Dividing the prompt length by that time gives prompt tokens per second. The second timer measures how fast the following tokens arrive.

One short run warms up Julia before the three timed trials. Loading the weights and turning the prompt into token IDs happen before the timers start.

using Pkg
Pkg.activate(joinpath(@__DIR__, ".."); io = devnull)
Pkg.instantiate(; allow_autoprecomp = false)
using Caesar, LinearAlgebra, Printf

function trial(m, ids, n)
    started = time_ns()
    first_token = nothing
    function emitted(id)
        if isnothing(first_token)
            first_token = time_ns()
            @printf(stderr, "Prompt processed in %.3f s. Decoding", (first_token - started) / 1.0e9)
        else
            print(stderr, ".")
        end
        return flush(stderr)
    end
    output = generate(m, ids; max_new_tokens = n + 1, on_token = emitted)
    finished = time_ns()
    println(stderr)
    prompt_end = something(first_token, finished)
    prompt_time = (prompt_end - started) / 1.0e9
    decode_time = (finished - prompt_end) / 1.0e9
    decoded = max(0, length(output) - 1)
    return (; prompt_time, decode_time, decoded, output)
end

function main()
    Caesar.native_blas!()
    q4 = "--q4" in ARGS
    args = filter(!=("--q4"), ARGS)
    m = haskey(ENV, "CAESAR_TEST_MODEL") ? load_model(ENV["CAESAR_TEST_MODEL"]; q4) : load_model(; q4)
    t = Tokenizer(m)
    p = prepare_prompt(m, t, "Explain how the seasons change over the course of a year, starting with the tilt of Earth's axis and its orbit around the Sun.")
    tokens = isempty(args) ? 12 : parse(Int, only(args))
    tokens > 0 || error("Expected a positive decode length")
    println("Julia ", VERSION, "; ", first(Sys.cpu_info()).model, "; ", q4 ? "Q4" : "BF16", "; ", Threads.nthreads(), " Julia threads; ", BLAS.get_num_threads(), " BLAS threads")
    println("Warming up...")
    flush(stdout)
    trial(m, p.ids, 2)
    for i in 1:3
        GC.gc()
        r = trial(m, p.ids, tokens)
        @printf(
            "Trial %d: prefill %d / %.3f s = %.2f tok/s; decode %d / %.3f s = %.2f tok/s\n",
            i, length(p.ids), r.prompt_time, length(p.ids) / r.prompt_time, r.decoded, r.decode_time, iszero(r.decoded) ? 0.0 : r.decoded / r.decode_time
        )
        i == 1 && println("Continuation: ", repr(decode(t, r.output)))
        flush(stdout)
    end
    return
end
main()

bin/fetch-model

Verifying cached weights

Caesar downloads the model the first time you use it. Run fetch-model when you also want to check every byte of the files already on disk. Give it a directory name to download or check the files there.

using Pkg
Pkg.activate(joinpath(@__DIR__, ".."); io = devnull)
Pkg.instantiate(; allow_autoprecomp = false)
using Caesar
length(ARGS) <= 1 || error("Usage: fetch-model [directory]")
println(Caesar.fetch_model(isempty(ARGS) ? Caesar.default_model_dir() : only(ARGS); verify = true))

bin/caesar-docs

Building this source guide

The page you’re reading comes from the Julia files themselves. Run caesar-docs to build it. A line starting with # at the left edge becomes ordinary text on the page. Use # # for a chapter title and # ## for a section title. An indented comment stays beside its code.

using Markdown, JuliaSyntaxHighlighting

const ROOT = dirname(@__DIR__)
escape_html(s) = replace(string(s), '&' => "&amp;", '<' => "&lt;", '>' => "&gt;", '"' => "&quot;")
slug(s) = strip(replace(lowercase(s), r"[^a-z0-9]+" => "-"), '-')

function highlight_html(code)
    io = IOBuffer()
    for (text, annotations) in Base.eachregion(JuliaSyntaxHighlighting.highlight(code))
        faces = join((a.value for a in annotations if a.label == :face), " ")
        if isempty(faces)
            print(io, escape_html(text))
        else
            print(io, "<span class=\"", escape_html(faces), "\">", escape_html(text), "</span>")
        end
    end
    return String(take!(io))
end

Reading a chapter

Read one file from top to bottom. Collect consecutive comment lines into a paragraph and consecutive Julia lines into a code block. A new heading gets its own link so a reader can jump straight to that part of the file. The code block shows exactly what was written, including strings and symbols.

function chapter(path)
    file = relpath(path, ROOT)
    id = slug(file)
    lines = readlines(path)
    title_line = findfirst(startswith("# # "), lines)
    title = isnothing(title_line) ? file : chop(lines[title_line]; head = 4, tail = 0)
    toc = Pair{String, String}[]
    io = IOBuffer()
    print(
        io, "<article id=\"$id\"><header><p class=\"path\">", escape_html(file),
        "</p><h2>", escape_html(title), "</h2></header>"
    )
    group = String[]
    prose = false
    function render()
        body = join(group, "\n")
        empty!(group)
        isempty(strip(body)) && return
        return if prose
            show(io, MIME"text/html"(), Markdown.parse(body))
        else
            print(io, "<pre><code>", highlight_html(body), "</code></pre>")
        end
    end
    for (line_number, line) in enumerate(lines)
        if line_number == title_line || startswith(line, "#!")
            continue
        elseif startswith(line, "# ## ")
            render()
            label = chop(line; head = 5, tail = 0)
            target = id * "-" * slug(label)
            push!(toc, target => label)
            print(io, "<h3 id=\"$target\"><a href=\"#$target\">", escape_html(label), "</a></h3>")
        else
            isprose = startswith(line, "# ") || line == "#"
            isprose != prose && render()
            prose = isprose
            push!(group, prose ? replace(line, r"^# ?" => "") : line)
        end
    end
    render()
    print(io, "</article>")
    return (; id, title, toc, html = String(take!(io)))
end

Linking the chapters

The include lines at the end of src/Caesar.jl give the chapters their reading order. The command-line scripts come after them. Put the contents list and the chapters into docs/layout.html and save the result as docs/index.html. That one file contains everything needed to read the guide offline.

function build()
    main = joinpath(ROOT, "src", "Caesar.jl")
    included = [joinpath(dirname(main), m[1]) for m in eachmatch(r"(?m)^include\(\"([^\"]+)\"\)", read(main, String))]
    commands = filter(readdir(@__DIR__; join = true)) do path
        path != (@__FILE__) && open(readline, path) == "#!/usr/bin/env julia"
    end
    chapters = chapter.(vcat(main, included, commands, @__FILE__))
    nav = IOBuffer()
    for c in chapters
        print(nav, "<a class=\"chapter\" href=\"#", c.id, "\">", escape_html(c.title), "</a>")
        for (target, label) in c.toc
            print(nav, "<a class=\"section\" href=\"#", target, "\">", escape_html(label), "</a>")
        end
    end
    template = read(joinpath(ROOT, "docs", "layout.html"), String)
    html = replace(
        template, "{{navigation}}" => String(take!(nav)),
        "{{chapters}}" => join(c.html for c in chapters)
    )
    return write(joinpath(ROOT, "docs", "index.html"), html)
end
build()