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, andmodel.safetensorsdirectly from Hugging Face (Qwen/Qwen2.5-0.5B) - Mapping pretrained weights into a 24-layer
#[module]usingRmsNorm,RoPE, 7x grouped-queryMultiheadAttention,nn::swiglu, and tiedEmbeddingoutput weights - Compiling one fixed-shape decode step with
KvCache::update_dynamic, in-placetf.aliasing_outputbuffer donation, and zero-copy device-resident weights - Exporting the decode step as a compact external-weight StableHLO
.mlirgraph (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) |