Ferrotensor
ContentsUse cases

Use cases

Small programs that show where Ferrotensor fits today. Sections 1 to 4 use the ferrotensor crate. Each of those lives in ferrotensor/examples/, runs with one command, and the output below was captured from a real run on an Apple M2 (Metal) with Rust 1.99.1. Numbers that depend on random initialisation vary from run to run; timings are single-machine snapshots.

Sections 5 to 7 use the LLM training stack (ferrotensor-graph and ferrotensor-trainer). They live in ferrotensor-trainer/examples/, build a tiny random model in a temporary directory so nothing is downloaded, and check their own results: a wrong result makes the program exit non-zero. CI runs all three on every pull request, and their output below is copied from that CI job (Mesa lavapipe, a Vulkan driver that runs on the CPU).

All commands assume you are in the repository root.

ExampleShowsDevice
mlp_two_moonsDataLoader, Sequential, AdamW, LR scheduleCPU (GPU optional)
char_transformerattention, LayerNorm, a custom Module-style model, samplingCPU (GPU optional)
gpu_matmul_attentionCPU/GPU parity and where the GPU winsGPU
similarity_searchembeddings + batched dot-product searchGPU if present
lora_finetune_tinyLoRA training, saving and reloading an adapterGPU
resume_trainingsaving and restoring adapter and optimizer stateGPU
generate_with_kv_cachegreedy decoding with and without the KV cacheGPU

1. Train an MLP with a DataLoaderLink to this section

Where it fits: classic small-model training with no Python and no GPU required. Everything here is the public ferrotensor API: Dataset / TensorDataset / DataLoader, nn::Sequential, F::cross_entropy, optim::AdamW and a WarmupCosineLr schedule.

cargo run --release -p ferrotensor --example mlp_two_moons
device: CPU (Cpu)
train: 800 points, test: 400 points
model: 2-32-32-2 MLP, 1218 parameters
epoch  0  train loss 0.4292  test accuracy 85.8%
epoch 10  train loss 0.0319  test accuracy 98.5%
epoch 20  train loss 0.0150  test accuracy 97.5%
epoch 30  train loss 0.0146  test accuracy 99.2%
epoch 40  train loss 0.0187  test accuracy 99.5%
epoch 50  train loss 0.0101  test accuracy 99.5%
epoch 59  train loss 0.0081  test accuracy 99.5%

The data are two noisy interleaved half-circles generated in the example, so this is a smoke test of the training stack. The whole run takes about half a second on the CPU.

FERROTENSOR_DEVICE=gpu trains the same model on the GPU. It works (final test accuracy 99.5% in one run) and takes about 2 s against about 0.2 s on the CPU (1.8-2.2 s in the benchmark runs; it was 12-17 s before ops were batched): a 1,218-parameter model gives the GPU too little work to amortise the cost of each dispatch. Use the CPU device for models this small.

2. A character-level transformer from scratchLink to this section

Where it fits: understanding or prototyping a transformer end to end in Rust. The example builds a two-layer pre-norm GPT-style model out of nn::Embedding, nn::LayerNorm, nn::MultiHeadAttention (causal) and nn::Linear, trains it with AdamW, gradient clipping and warmup+cosine LR on a few Shakespeare sonnets (public domain, 3.7 KB), then samples text.

cargo run --release -p ferrotensor --example char_transformer
device: CPU (Cpu)
corpus: 3700 characters, vocabulary 54
model: 2 layers, dim 64, 4 heads, 109622 parameters
step   0  loss 4.577
step 100  loss 2.280
step 200  loss 1.971
step 300  loss 1.588
step 400  loss 1.037
step 500  loss 0.722
step 599  loss 0.603
trained 600 steps in 47.6s

--- sample (prompt: "Shall I compare") ---
Shall I comparestemaf look con.
Lovet ive
Which to not me man's boyesh'd doth gloks ote tand warith crief worinng.
Lot not love t, no bnce with thi by thou ven merovem! it everWh wok d.


Then imowf  iforth suow f h

What this does and does not show:

  • The loss falls from 4.6 (about ln 54 = 4.0 plus init noise) to 0.6 on training windows. With 3.7 KB of text and 110k parameters the model is starting to memorise the corpus; there is no held-out set, so this says nothing about generalisation.
  • The samples are partly English-shaped, partly garbage. They show a working training loop.
  • On this machine the GPU path (FERROTENSOR_DEVICE=gpu) trains the same 600 steps in 31.9 s versus 42.5 s on the CPU (it took 105 s before GPU ops were batched; method and numbers in benchmarks/RESULTS.md). The timings are single-machine and the weights are not seeded.

3. GPU matmul and attentionLink to this section

Where it fits: this is where the GPU backend earns its keep: large dense ops. The example runs the same matmul and causal attention on a CPU tensor and a GPU tensor, checks they agree, and times both (best of several runs, including readback).

cargo run --release -p ferrotensor --example gpu_matmul_attention
gpu: Apple M2 (Metal)

matmul [n, n] @ [n, n]
     n     cpu ms     gpu ms   speedup   max |diff|
   256        1.3        1.4      0.9x      2.29e-5
   512       10.3        3.7      2.8x      3.05e-5
  1024       90.2       19.3      4.7x      5.34e-5
  2048      682.4      145.5      4.7x      1.07e-4

causal scaled-dot-product attention, [1, 8 heads, seq, 64]
   seq     cpu ms     gpu ms   speedup   max |diff|
   128        3.3        0.9      3.5x      3.58e-7
   512       53.0        7.9      6.7x      5.96e-7

The GPU is up to about 5x faster on large matmuls here, and no faster at small sizes. The 2048x2048 matmul is about 118 GFLOPS on the GPU (2 n^3 flops / 0.1455 s; the tuned kernels in ferrotensor-backend reach 611 GFLOPS at 4096). This is one run on a machine that may be doing other work, so expect noise. The agreement column (differences of 1e-5 to 1e-4 for matmul, ~1e-7 for attention) is the number the test suite enforces. For the project's benchmark harness see benchmarks/RESULTS.md.

Where it fits: retrieval over embeddings. The search is one [queries, dim] @ [dim, docs] matmul on the device followed by a top-k on the host. The example embeds text with hashed character trigrams into 512 dimensions, so it needs no model weights, but it is a lexical embedding: shared words and typos match, synonyms do not. Swap in embeddings from a real model and the search code is unchanged.

cargo run --release -p ferrotensor --example similarity_search
device: Apple M2 (Metal)

query: "forgot my password"
  0.545  How do I reset my password?
  0.380  Steps to change your account password
query: "revenue growth this quarter"
  0.584  Revenue increased 12% quarter over quarter
  0.513  Quarterly revenue grew by twelve percent
query: "kittens on a ledge"
  0.511  A kitten is sleeping on the window ledge
  0.154  Where to find scenic walking routes by the lake
query: "how to install with cargo"
  0.564  Install the package with cargo add
  0.458  Run cargo install to get the command line tool
query: "lake hiking trails"
  0.643  Best hiking trails near the mountain lake
  0.260  Where to find scenic walking routes by the lake

Top results are right for all five queries. Second results are sometimes weak (the second hit for "kittens on a ledge" is unrelated: the score 0.154 shows it), which is what a lexical embedding gives you.

5. LoRA fine-tuning on a tiny modelLink to this section

Where it fits: the whole LoRA path of the training stack, with no model to download. The example writes a tiny random Llama-style model (64-token vocabulary, 2 layers, hidden size 32) to a temporary directory, attaches rank-4 LoRA adapters to q_proj, k_proj, v_proj and o_proj, and trains them for 40 steps on one fixed 16-token pattern. Then it saves the adapter, loads it into a fresh copy of the model and scores that copy.

cargo run --release -p ferrotensor-trainer --example lora_finetune_tiny
device: llvmpipe (LLVM 20.1.2, 256 bits) (Vulkan)
task: continue the pattern [3, 10, 17, 24, 31, 38, 45, 52, 59, 2, 9, 16, 23, 30, 37, 44]
model: 2 layers, vocabulary 64; LoRA rank 4 on q/k/v/o, 1792 trainable values
loss before training: 5.9385
step  0  loss 5.9385
step 10  loss 2.5799
step 20  loss 0.9200
step 30  loss 0.4844
step 39  loss 0.2989
loss after 40 steps: 0.2841
saved 16 adapter tensors (8984 bytes)
fresh copy, no adapter: loss 5.9385
fresh copy, adapter loaded (16 tensors): loss 0.2841
|reloaded - trained| = 0.00e0

The key lines:

let model = Lfm2ModelBuilder::new(ctx.clone(), engine.clone(), &weights, config)
    .with_lora(LoRaConfig { rank: 4, alpha: 8.0, target_modules })
    .build()?;
let params = model.named_lora_params(); // only these are trained
let mut trainer = Trainer::new(model, Box::new(AdamW::new(engine.clone(), 1e-2)), ctx, engine);
trainer.train_step(&seq[..15], &seq[1..], &params)?;

save_lora_checkpoint(&ctx, "adapter.safetensors", &trainer.model.named_lora_params(), Some(&meta)).await?;
let checkpoint = load_lora_checkpoint("adapter.safetensors")?;
apply_checkpoint(&ctx, &checkpoint, &fresh.named_lora_params())?;

(Simplified: the example sorts the parameters by name and passes them as a list.) The program asserts that the loss at least halves and that the reloaded model gives the trained loss within 1e-4. The model memorises one fixed pattern, which checks that the training stack works and says nothing about model quality. For a real model and dataset, see the LoRA walkthrough.

6. Stop and resume a training runLink to this section

Where it fits: long runs that must survive a stop. The example trains the same tiny model 12 steps straight; then, separately, 6 steps, saves the adapter and the AdamW state, builds a fresh model, loads both and trains 6 more. For contrast it also resumes from the same adapter with a new, empty optimizer.

cargo run --release -p ferrotensor-trainer --example resume_training
device: llvmpipe (LLVM 20.1.2, 256 bits) (Vulkan)
12 steps straight:           5.9385 5.7171 5.4485 5.1535 4.8705 4.6353 4.4604 4.3264 4.2083 4.0905 3.9635 3.8199
saved adapter and optimizer state after 6 steps
6 + 6 steps, resumed:        5.9385 5.7171 5.4485 5.1535 4.8705 4.6353 4.4604 4.3264 4.2083 4.0905 3.9635 3.8199
6 + 6, new optimizer:        5.9385 5.7171 5.4485 5.1535 4.8705 4.6353 4.4604 4.2503 4.0582 3.8699 3.6729 3.4597
largest relative difference, resumed vs straight: 0.00e0 (allowed 1e-5)
final loss without the optimizer state differs by 0.3602

The key lines:

// Save: the adapter, plus the optimizer moments and step count.
save_lora_checkpoint(&ctx, &adapter, &named, Some(&meta)).await?;
let mut state = TrainingState::new(12);
state.step = trainer.optimizer_steps();
TrainingCheckpoint {
    training_state: state,
    optimizer_state: trainer.optimizer.save_state(&ctx, &named),
    grad_scaler_state: None,
}
.save(&state_path)?;

// Resume: a fresh model, the adapter, then the optimizer state.
apply_checkpoint(&ctx, &load_lora_checkpoint(&adapter)?, &model.named_lora_params())?;
let saved = TrainingCheckpoint::load(&state_path)?;
let mut optimizer = AdamW::new(engine.clone(), 5e-3);
optimizer.load_state(&ctx, &model.named_lora_params(), saved.optimizer_state.as_ref().unwrap());
let mut trainer = Trainer::new(model, Box::new(optimizer), ctx, engine);
trainer.set_optimizer_steps(saved.training_state.step);

The resumed run matches the straight run at every step (the program fails if any resumed step differs by more than 1e-5, relative). Without the optimizer state the run goes on from the same weights but takes different steps. Its loss happens to fall faster here (likely because AdamW's first steps after a fresh start are large); the example shows that it is a different run from the straight one.

7. Greedy generation with the KV cacheLink to this section

Where it fits: text generation. The example trains the tiny model's LoRA adapters for 30 steps on the pattern (so each next token is a clear choice), then generates 12 tokens from a 4-token prompt twice: once running the whole sequence again at every step, once with a KV cache that keeps the keys and values of earlier tokens, so each step feeds only the new token.

cargo run --release -p ferrotensor-trainer --example generate_with_kv_cache
device: llvmpipe (LLVM 20.1.2, 256 bits) (Vulkan)
trained LoRA for 30 steps, final loss 0.5063
prompt:            [3, 10, 17, 24]
without KV cache:  [31, 38, 45, 52, 59, 2, 9, 16, 23, 30, 37, 44]
with KV cache:     [31, 38, 45, 52, 59, 2, 9, 16, 23, 30, 37, 44]
training pattern:  [31, 38, 45, 52, 59, 2, 9, 16, 23, 30, 37, 44]
largest logit difference between the two: 0.00e0
tokens that continue the pattern: 12 of 12

The key lines:

let mut cache = model.new_kv_cache(prompt.len() + n); // None if the model has conv blocks
let mut logits = model.forward(&engine, prompt, 0, cache.as_mut(), None);
// ... pick `next` from the last row of `logits`, push it to `tokens` ...
logits = model.forward(&engine, &[next], tokens.len() - 1, cache.as_mut(), None);

The program asserts that both runs give the same tokens. The model continues the pattern it was trained on; on a model this small that is memorisation, not language.

What does not fit (yet)Link to this section

  • Large-model training or multi-GPU. Not supported. The LoRA fine-tuning path for small Llama-style models is experimental; see the README.
  • Big training jobs on the ferrotensor tensor API. Tensors are f32 only, there are no convolutions, and each tiny op still costs the GPU about 9-13 µs, so chains of small ops run slower than on the CPU.