Skip to content

Pretrained Qwen2.5 (Hugging Face)

Full source in examples/qwen.rs. Run it with cargo run --release --example qwen.

What This Shows

  • Downloading config.json, tokenizer.json, and model.safetensors directly from Hugging Face (Qwen/Qwen2.5-0.5B)
  • Mapping pretrained weights into a 24-layer #[module] using RmsNorm, RoPE, 7x grouped-query MultiheadAttention, nn::swiglu, and tied Embedding output weights
  • Compiling one fixed-shape decode step with KvCache::update_dynamic, in-place tf.aliasing_output buffer donation, and zero-copy device-resident weights
  • Exporting the decode step as a compact external-weight StableHLO .mlir graph (JACOBI_EXPORT_MLIR=1)

Loading Pretrained Weights

hub::load_safetensors memory-maps the downloaded .safetensors file directly onto device memory. Because PyTorch stores linear weights as [out_features, in_features] while Jacobi multiplies x @ w, linear weights are transposed once at load time.

let tok = Tokenizer::from_pretrained("Qwen/Qwen2.5-0.5B")?;
let cfg = hub::load_config("Qwen/Qwen2.5-0.5B")?;
let weights = hub::load_safetensors("Qwen/Qwen2.5-0.5B")?;

let embed_w = weights["model.embed_tokens.weight"].to_dtype(compute_dtype);
let q_w = eval(|| weights["model.layers.0.self_attn.q_proj.weight"].to_dtype(compute_dtype).transpose())?;

Single-Graph Fixed-Shape Decode

Each decode step writes one token into the pre-allocated [1, 2, max_seq_len, 64] KvCache via stablehlo.dynamic_update_slice and increments pos on device. XLA compiles the decode step once and keeps all 494M weights resident on the accelerator with zero per-token copies.

let decode_fn = jit(move |(tok_id, mut caches, pos): (Tensor, Vec<KvCache>, Tensor)| {
    let next_tok = decode_model
        .forward_next_token(&tok_id, &mut caches, &pos)
        .reshape(&[1, 1]);
    let next_pos = &pos + 1.0;
    (caches, next_tok, next_pos)
});

for _ in 0..max_new_tokens {
    (caches, cur_tok, cur_pos) = decode_fn.call((cur_tok, caches, cur_pos))?;
}

Configuration and Measured Throughput

Override the model, prompt, precision, or backend through environment variables.

JACOBI_PROMPT="Rust is a systems language that" JACOBI_MAX_TOKENS=64 cargo run --release --example qwen
JACOBI_BACKEND=cpu JACOBI_DTYPE=f32 cargo run --release --example qwen
JACOBI_EXPORT_MLIR=1 cargo run --release --example qwen

Measured on Qwen/Qwen2.5-0.5B (494.1M parameters, 64 generated tokens) on an Apple M5 Max.

Backend and dtype Load time Steady-state decode
Apple M5 Max Metal (f16) 0.48 s 200.5 tok/s (5.0 ms/tok)
Apple M5 Max Metal (f32) 0.44 s 103.5 tok/s (9.7 ms/tok)
Apple M5 Max CPU (f32) 0.30 s 55.6 tok/s (18.0 ms/tok)