One task per section, from installing Ferrotensor to fine-tuning a language model on your GPU. Output shown under a step is copied from a real run, and the caption says which machine it ran on.
There are no results from AMD or Intel GPUs, and none from DX12 on a real GPU. CI runs the GPU tests through DX12 on WARP, a software adapter, and through Metal on a virtualised Apple GPU. If you try one of these GPUs, report what you find.
01 Start here
Check your GPU
See which GPU Ferrotensor will use and test its kernels against a CPU reference.
$ ferrotensor info --check1ferrotensor 0.5.0 on linux x86_64
2* llvmpipe (LLVM 20.1.2, 256 bits) (Mesa, Cpu, Vulkan)
driver llvmpipe Mesa 25.2.8-0ubuntu0.24.04.4 (LLVM 20.1.2)
3 max buffer 2047 MiB
max storage bind 128 MiB
workgroup 1024 threads, 32 KiB shared
shader f16 yes
* = the adapter Ferrotensor uses
Kernel check against a CPU reference:
4 ok matmul 37x53 @ 53x29 max error 3.6e-7 (tolerance 1e-4)
ok softmax 7x1031 max error 4.7e-10 (tolerance 1e-6)
ok rms_norm 5x777 max error 2.4e-7 (tolerance 1e-4)
ferrotensor info --check in Ferrotensor's CI on Mesa lavapipe (software Vulkan). On your machine the adapter lines show your GPU.
The version and platform you are running.
Every adapter wgpu can open. The one marked * is the one Ferrotensor uses: name, vendor, device type and backend.
The limits the kernels depend on. Large models need a large max buffer and storage binding.
Each kernel is run on the GPU and compared with an f64 CPU reference. A line says ok or FAIL.
Steps
List the adapters:
ferrotensor info
Run the kernel check. Odd sizes are used on purpose, so tiling bugs show up:
ferrotensor info --check
If every line says ok, your GPU computes correctly with Ferrotensor. The command exits with an error when a kernel fails.
Details
To try a single backend, set WGPU_BACKEND: vulkan, metal, dx12 or gl.
WGPU_BACKEND=vulkan ferrotensor info --check
For a bug report, ferrotensor info --check --json prints the same information as JSON. See Report results from your GPU.
Limits
The check covers matmul, softmax and RMSNorm, the kernels most likely to break on a new driver. The full GPU test suite is in Run the GPU tests.
01 Start here
Run an example program
A matmul and its gradient on the best available device, then the same idea in your own code.
PyTorch-style tensors, autograd, nn and optim from Python, on the CPU or a GPU. No NumPy needed.
1[0.0, 1.0, 1.0, 0.0]
python xor.py, the script below.
The network's predictions for the four XOR inputs: all four are right.
Steps
Install the package:
pip install ferrotensor
Save this as xor.py and run python xor.py:
import ferrotensor as ft
from ferrotensor import nn, optim
import ferrotensor.nn.functional as F
model = nn.Sequential(nn.Linear(2, 16), nn.Tanh(), nn.Linear(16, 2))
opt = optim.AdamW(model.parameters(), lr=0.05, weight_decay=0.0)
x = ft.tensor([[0, 0], [0, 1], [1, 0], [1, 1]])
for _ in range(200):
opt.zero_grad()
loss = F.cross_entropy(model(x), [0, 1, 1, 0]) # XOR
loss.backward()
opt.step()
print(model(x).argmax(dim=1).tolist())
Details
Tensors and layers take a device= argument. ft.Device("best") picks a GPU when there is one; ft.Device.gpu_available() tells you whether there is.
dev = ft.Device("best")
a = ft.randn(256, 256, device=dev)
ft.Device("gpu") raises RuntimeError when no adapter is found. Tensors on different devices cannot be mixed in one op; move them with .to(device).
What the bindings cover, and how they differ from PyTorch, is in the Python reference.
Limits
The Python API covers tensors, autograd, nn, optim and safetensors, a subset of PyTorch. LoRA fine-tuning runs from the command line; it has no Python binding.
02 Fine-tune a language model
Download a model and prepare data
Fetch a Llama-style checkpoint from Hugging Face and turn an instruction dataset into JSONL.
Convert it to {prompt, response} JSONL: keep short examples, shuffle with seed 0, and hold out 64 for evaluation.
mkdir -p data/alpaca
python3 - <<'EOF'
import json, random
rows = json.load(open("data/alpaca-cleaned/alpaca_data_cleaned.json"))
out = []
for r in rows:
p = r["instruction"].strip()
if r.get("input", "").strip():
p += "\n\n" + r["input"].strip()
resp = r["output"].strip()
if len(p) + len(resp) <= 500 and resp:
out.append({"prompt": p, "response": resp})
random.Random(0).shuffle(out)
for name, rs in (("val", out[:64]), ("train", out[64:2064])):
with open(f"data/alpaca/{name}.jsonl", "w") as f:
for x in rs:
f.write(json.dumps(x) + "\n")
EOF
Details
For plain next-token training, use --task pretrain with .txt lines, JSON text or token arrays, or packed little-endian u32.bin tokens.
Llama-architecture checkpoints have been measured: SmolLM2-135M, 360M and 1.7B. Sharded checkpoints load through model.safetensors.index.json.
Limits
Released LFM2 checkpoints are rejected because per-head q/k layernorm is not implemented yet.
02 Fine-tune a language model
Fine-tune a model with LoRA
Train a LoRA adapter with the loss on response tokens, and check the held-out loss before and after.
Watch eval before and eval after. The run writes lora_adapters.safetensors, its .state.json and .state.safetensors, metrics.jsonl and training_state.json to --out.
Details
Defaults that apply: batch size 1 (so --grad-accum 8 means 8 sequences per step), LoRA rank 8 and alpha 16 on q_proj,k_proj,v_proj,o_proj, gradient clipping at a global norm of 1.0, AdamW without weight decay, and warmup then cosine decay to lr/10.
--lora-rank, --lora-alpha and --lora-targets change the adapter.
--lite is a preset for small machines: sequence length 128, rank 4 and grad-accum 8, unless you set them.
--train-modules all|attn|mlp|norm|lm_head trains base weights instead of LoRA and saves the trained tensors, in f32, to trained_weights.safetensors. Pass that file to --lora in eval and generate, or to --resume with the same --train-modules.
ferrotensor monitor follows a run's training_state.json in a terminal dashboard.
The same recipe on three model sizes on an NVIDIA A10G (24 GB), 250 steps, with 0.6 development builds (commits 1b6709f and, for the f16 row, b319ce7):
Model
Held-out loss
SmolLM2-135M
2.4250 → 1.6521
SmolLM2-360M
2.0852 → 1.3228
SmolLM2-1.7B, f16 base weights
2.6474 → 1.0640
Frozen base weights are stored as f16 by default, which saves GPU memory; for SmolLM2-1.7B the held-out loss moves by 0.0017 against f32 weights. --f32-weights keeps them f32. --checkpoint-blocks recomputes each decoder block during backward instead of keeping its activations: in 0.7, LoRA on SmolLM2-1.7B peaks at 8,142 MiB of GPU memory by default and 5,313 MiB with the flag, with the same printed losses and 39% more time per step. --batch-size N trains N sequences in one GPU pass with the same result, faster but with more GPU memory.
On one NVIDIA A10G on 19 November 2026, main at 3deacf6 (the code in 0.7.1) ran the same recipe against PyTorch 2.15.0 with PEFT 0.21.3 and transformers 5.23.0: SmolLM2 with LoRA rank 8, batch 1 × 8, 250 steps, median of three runs. Against eager PyTorch + PEFT it takes 0.5071 s per step for SmolLM2-135M against 0.9459 s (1.87 times as fast), 0.5549 s against 1.0128 s for 360M (1.83 times) and 0.6709 s against 0.7606 s for 1.7B (1.13 times). The held-out loss is within 0.004 of PyTorch's at all three sizes. PyTorch with torch.compile, graph capture and TF32 is faster than Ferrotensor: for SmolLM2-135M at batch 1 × 8 it takes 0.1288 s per step against 0.4958 s (Ferrotensor at 0.26 of its speed), and at batch 8 × 1 it takes 0.0516 s against 0.1769 s (0.29). No memory comparison with PyTorch has been run since 0.6.
Every number, with the M2 run and the full PyTorch comparison, is in the LoRA walkthrough.
Limits
Larger batches need more GPU memory; --checkpoint-blocks lowers it and adds time per step. Activations and LoRA adapters are f32. --q4-weights (4-bit base weights) is experimental and gives a worse held-out loss than f16. Models above 1.7B have not been tested.
02 Fine-tune a language model
Evaluate and chat with your adapter
Reload the adapter, measure the held-out loss, and generate text with or without it.
Run both again without --lora to compare with the base model.
Details
generate takes --temperature (0 is greedy, default 0.7), --top-k (default 50), --top-p (default 0.9), --seed, --system, --max-new-tokens (default 128), --raw to skip the chat template, and --no-kv-cache. Greedy output is identical with and without the cache.
Prompt
Base SmolLM2-1.7B
With the adapter
Translate 'good morning' into French.
Repeats the prompt until the 60-token limit
Bonjour
Give three tips for staying healthy.
Rambles on about a "Healthy Diet"
A numbered list of three tips
Limits
Small models stay small: answers are fluent but shallow, and sampled output can wander.
02 Fine-tune a language model
Resume or extend a run
Continue training from a saved adapter with its optimizer state and step counter.
Use --save-every N during long runs so there is always a recent adapter to resume from.
Limits
The optimizer state takes 8 bytes per trainable parameter (7.4 MB for SmolLM2-135M). Versions before the next release stored it as JSON, 50 MB for the same run; those files still resume.
02 Fine-tune a language model
Run the whole recipe with one script
Download, train, evaluate and generate with a Llama-style model from Hugging Face, and get one JSON summary.
data/runs/SmolLM2-135M/summary.json from an NVIDIA A10G run with a 0.5 build. The loss curve and generations are left out.
Where it ran.
Held-out loss before and after, on the same 64 examples as the walkthrough.
Median seconds per optimizer step.
Peak host memory of the training process.
Steps
From a checkout of the repository, install the Hugging Face tool:
pip install huggingface_hub
Run the script with a Llama-style model:
scripts/lora-run.sh HuggingFaceTB/SmolLM2-360M
Read data/runs/<model>/summary.json. It also has the loss curve and greedy generations from the base model and the adapter.
Details
Options: --steps N (default 250) and --seq-len L (default 256). The other settings match the walkthrough: 2,000 Alpaca examples, 64 held out, rank 8 on q/k/v/o, lr 5e-4.
Limits
The script needs bash, Python 3 and the hf command. It builds the CLI in release mode if it is not built yet.
03 Train your own models
Train an MLP with a DataLoader
Classic small-model training: Dataset, DataLoader, nn::Sequential, AdamW and a warmup-cosine schedule.
1device: 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%
2epoch 59 train loss 0.0081 test accuracy 99.5%
cargo run --release -p ferrotensor --example mlp_two_moons on the CPU.
The examples default to the CPU. Set FERROTENSOR_DEVICE=gpu to use the GPU.
99.5% test accuracy on two noisy interleaved half-circles.
Steps
From a checkout:
cargo run --release -p ferrotensor --example mlp_two_moons
Try the GPU:
FERROTENSOR_DEVICE=gpu cargo run --release -p ferrotensor --example mlp_two_moons
Details
The GPU run reaches the same accuracy but is slower than the CPU: a 1,218-parameter model gives a GPU too little work. Source: mlp_two_moons.rs.
03 Train your own models
Train a small transformer from scratch
A two-layer GPT-style model built from nn layers, trained on Shakespeare sonnets and sampled.
corpus: 3700 characters, vocabulary 54
1model: 2 layers, dim 64, 4 heads, 109622 parameters
step 0 loss 4.577
step 300 loss 1.588
2step 599 loss 0.603
3trained 600 steps in 47.6s
--- sample (prompt: "Shall I compare") ---
4Shall I comparestemaf look con.
cargo run --release -p ferrotensor --example char_transformer on the CPU of a MacBook Air M2.
nn::Embedding, nn::LayerNorm, causal nn::MultiHeadAttention and nn::Linear.
The loss falls from 4.6 to 0.6 on training windows.
The same 600 steps also run on the M2's GPU with FERROTENSOR_DEVICE=gpu.
Partly English-shaped, partly not: a working training loop on 3.7 KB of text, not a language model.
Steps
From a checkout:
cargo run --release -p ferrotensor --example char_transformer
Details
It uses AdamW, gradient clipping and a warmup+cosine schedule. Source: char_transformer.rs. More examples, with output, are in Use cases.
Limits
There is no held-out set, so the loss says nothing about generalisation.
03 Train your own models
Save, load and seed a model
Store parameters as safetensors and make random initialisation reproducible.
WGPU_BACKEND=vulkan ferrotensor info --check
WGPU_BACKEND=dx12 ferrotensor info --check
Limits
One GPU per process. Multi-GPU training is not supported.
04 Performance
Turn on op fusion
Run chains of element-wise ops as one GPU dispatch. Results are bit-identical.
case GPU off on
100 element-wise ops, [64] A10G 0.676 ms 0.322 ms
100 element-wise ops, [64] T4 0.668 ms 0.305 ms
MLP 784-256-10 AdamW step A10G 0.855 ms 0.673 ms
matmul 512x512x512 A10G 0.528 ms 0.532 ms
Tensor API medians with FERROTENSOR_FUSION off and on, NVIDIA A10G and Tesla T4 through Vulkan at commit 165921d (benchmarks/RESULTS.md). Not measured again for 0.7.
Results are bit-identical with fusion on and off; speed has not been measured for this release.
Steps
Set the variable for any program that uses the ferrotensor Tensor API, Rust or Python:
FERROTENSOR_DEVICE=gpu FERROTENSOR_FUSION=1 \
cargo run --release -p ferrotensor --example char_transformer
Results do not change: every intermediate is still written, and CI checks fused and unfused runs bit for bit.
Details
Up to six consecutive same-size element-wise steps run as one fused dispatch. The design and its decision tree are in op fusion.
Limits
Off by default. It applies to the Tensor API, not to the LoRA command line, which uses its own kernels.
04 Performance
Benchmark your machine
Run the kernel and Tensor API benchmarks and get one JSON report.
1report: reports/runnervm48cm3-vulkan-403a069.json
2GPU: llvmpipe (LLVM 20.1.2, 256 bits) (vulkan), kernel check passed, 12 kernel and 4 Tensor API results
scripts/hardware-report.sh --quick in Ferrotensor's CI (software Vulkan).
One JSON file per machine, backend and commit, under reports/.
A summary line: the GPU, whether the kernel check passed and how many results were recorded.
Steps
From a checkout, run the full report (or add --quick for a short one):
scripts/hardware-report.sh
Or run the parts on their own:
cargo run -p ferrotensor-benchmarks --release --bin bench
cargo run -p ferrotensor-benchmarks --release --bin tensor-api
Details
The report runs ferrotensor info --check, the kernel benchmarks and the Tensor API benchmarks, and keeps the raw tables. Published results for an Apple M2, an NVIDIA A10G and a Tesla T4 are on the benchmarks page.
Limits
Close other GPU-heavy programs before a run. Timings are medians and still noisy.
05 Contribute
Run the GPU tests
Check the kernels and gradients on your GPU against the CPU.
1FERROTENSOR_RUN_GPU_TESTS=1 cargo test --workspace -- --ignored --test-threads=1
2FERROTENSOR_RUN_GPU_TESTS=1 cargo test -p ferrotensor --lib
3FERROTENSOR_RUN_GPU_TESTS=1 cargo test -p ferrotensor-autograd --test grad_check
What the GPU suites cover.
Every GPU test in the workspace, including each ferrotensor-backend kernel against a CPU reference. On merged main, one NVIDIA A10G, 15 Nov 2026: 138 passed, 0 failed, with cargo test --release --workspace -- --ignored --test-threads=1.
The Tensor API: forward values and gradients on the GPU must match the CPU.
Finite-difference gradient checks of every autograd op on the GPU.
Steps
Clone the repository, then run the suites above. Without the variable, GPU tests skip themselves.
Add FERROTENSOR_FUSION=1 to the second command to test op fusion too.
Details
Every pull request runs these suites in CI on Mesa lavapipe, a Vulkan driver that runs on the CPU, so the Vulkan path is checked without a GPU. Behaviour on real hardware still needs a local run. Adding a kernel is covered in Writing a kernel.
Limits
Use --test-threads=1: creating several GPU devices at once is unreliable on some drivers.
05 Contribute
Report results from your GPU
There are no results from AMD or Intel GPUs, and none from DX12 on a real GPU. CI runs the GPU tests through DX12 on WARP, a software adapter, and through Metal on a virtualised Apple GPU. One report from your machine fills a gap.
1ferrotensor info --check --json
2scripts/hardware-report.sh
What to attach to the issue.
Adapters, limits and the kernel check, as JSON. Paste it into the bug report's field for it.
Optional: the full benchmark report, the same measurement every published number comes from.
Steps
Run the commands above.
Open an issue on GitHub and attach the output, whether the checks passed or failed.
Peak GPU memory for SmolLM2-1.7B LoRA on an NVIDIA A10G: nvidia-smi peak over 30 steps, f16 base weights, batch 1, one session. Within 0.7, losses are identical with and without --checkpoint-blocks; against 0.6 they differ slightly because 0.7 gives every LoRA adapter its own initial A matrix.
The released 0.6.0.
0.7 hands each intermediate gradient back once it is used and reuses freed buffers; on by default.
--checkpoint-blocks recomputes each decoder block during backward: 19 to 39% more time per step (medians over 30 steps).
Steps
Use the latest release: cargo install ferrotensor-cli --force.
Small models train faster on the CPU, because every GPU dispatch has a fixed overhead.
If GPU memory allows, train several sequences per pass: --batch-size 8 --grad-accum 1 gives the same result as the default 8 steps of accumulation in fewer GPU passes.
Out of GPU memory? Add --checkpoint-blocks, lower --batch-size, and keep the default f16 base weights. train --memory-report shows where the memory goes. In 0.7, LoRA on SmolLM2-1.7B peaks at 1,575 MiB of host memory, down from 5,087 MiB before the host-memory change.
Details
Try op fusion for Tensor API programs with long element-wise chains, and --lite for LoRA on small machines.
Limits
Activations, gradients and LoRA adapters are f32. Frozen base weights are f16.