Ferrotensor

Guide

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.

New to Ferrotensor? Start with Install Ferrotensor, then Check your GPU. The architecture and the reference are in the docs; the Rust API is on docs.rs.

01 Start here

Install Ferrotensor

Add the Rust crate, install the ferrotensor command, or install the Python package.

1cargo add ferrotensor
2cargo install ferrotensor-cli
3pip install ferrotensor
Three ways in: the Rust library, the command line tool and the Python package.
  1. The tensor API, autograd, nn and optimizers, as a library in your Rust project.
  2. The ferrotensor command: LoRA train, eval, generate and info.
  3. The Python bindings. Wheels exist for macOS arm64 and Linux x86_64.

Steps

  1. Install Rust 1.88 or newer with rustup. On macOS nothing else is needed: Ferrotensor uses Metal.

  2. On Linux, make sure a Vulkan driver is installed. NVIDIA's driver includes one; for AMD and Intel GPUs install Mesa (mesa-vulkan-drivers on Ubuntu).

  3. To use the tensor API in a Rust project, add the crate:

    cargo add ferrotensor
  4. To fine-tune and run language models from the terminal, install the command line tool. The binary is called ferrotensor:

    cargo install ferrotensor-cli
  5. For Python 3.10 or newer:

    pip install ferrotensor

Details

On platforms without a wheel, pip builds the package from its source distribution, which needs Rust.

To work from a checkout instead:

git clone https://github.com/puranikyashaswin/ferrotensor.git
cd ferrotensor
cargo build --release -p ferrotensor-cli   # ./target/release/ferrotensor
pip install ./ferrotensor-py

Limits

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 --check
1ferrotensor 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.
  1. The version and platform you are running.
  2. Every adapter wgpu can open. The one marked * is the one Ferrotensor uses: name, vendor, device type and backend.
  3. The limits the kernels depend on. Large models need a large max buffer and storage binding.
  4. Each kernel is run on the GPU and compared with an f64 CPU reference. A line says ok or FAIL.

Steps

  1. List the adapters:

    ferrotensor info
  2. Run the kernel check. Odd sizes are used on purpose, so tiling bugs show up:

    ferrotensor info --check
  3. 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.

1device: Apple M2 (Metal)
2x @ w = [7.5, 2.0, 18.0, 2.0] (shape [2, 2])
3dL/dw = [5.0, 5.0, 7.0, 7.0, 9.0, 9.0]
cargo run --release -p ferrotensor --example quickstart on a MacBook Air (Apple M2, 8 GB).
  1. Device::best() picked the GPU. Without one, the same code runs on the CPU.
  2. The forward result of the matmul.
  3. The gradient of the loss with respect to w, from loss.backward().

Steps

  1. Clone the repository and run the example:

    git clone https://github.com/puranikyashaswin/ferrotensor.git
    cd ferrotensor
    cargo run --release -p ferrotensor --example quickstart
  2. In your own project (after cargo add ferrotensor), this trains a small network on XOR:

use ferrotensor::prelude::*;
let device = Device::cpu(); // or Device::best() for a GPU when present
let model = nn::Sequential::new(&device)
    .add(nn::Linear::new(2, 16, &device))
    .add(nn::Tanh)
    .add(nn::Linear::new(16, 2, &device));
let mut opt = optim::AdamW::new(model.parameters(), 0.05).weight_decay(0.0);
// XOR
let x = Tensor::from_data(&[0., 0., 0., 1., 1., 0., 1., 1.], &[4, 2], &device);
let y = Tensor::from_data(&[0., 1., 1., 0.], &[4], &device);
for _ in 0..200 {
    opt.zero_grad();
    let loss = F::cross_entropy(&model.forward(&x), &y);
    loss.backward();
    opt.step();
}

Details

The example's source is ferrotensor/examples/quickstart.rs. The API reference is on docs.rs.

Limits

Tensors are f32. Small models like this one run faster on the CPU than on a GPU; see Training is slow or uses too much memory.

01 Start here

Train a model from Python

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.
  1. The network's predictions for the four XOR inputs: all four are right.

Steps

  1. Install the package:

    pip install ferrotensor
  2. 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.

1{"prompt": "<instruction and input>", "response": "<the answer>"}
2{"prompt": "...", "response": "...", "system": "<optional>"}
data/alpaca/train.jsonl in the format ferrotensor train --task sft reads: one JSON object per line.
  1. Each line is one example. The loss counts the response tokens.
  2. An optional system message is used too. Prompts are wrapped in the ChatML template unless you pass --no-chat-template.

Steps

  1. Install the Hugging Face command line tool:

    pip install huggingface_hub
  2. Download the model's weights, config and tokenizer:

    hf download HuggingFaceTB/SmolLM2-135M \
      model.safetensors config.json tokenizer.json tokenizer_config.json \
      --local-dir data/models/SmolLM2-135M
  3. Download the dataset:

    hf download yahma/alpaca-cleaned alpaca_data_cleaned.json \
      --repo-type dataset --local-dir data/alpaca-cleaned
  4. 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.

1device: NVIDIA A10G (Vulkan)
model:  data/models/SmolLM2-135M (30 layers, hidden 576, vocab 49152)
data:   2000 examples (sft task), 66890 supervised tokens, seq-len 256
2train:  lora (921600 trainable params), lr 0.0005 warmup 20 cosine, 250 steps x 8 sequences
3eval before: loss 2.4250 ppl 11.302 (2744 tokens)
  step |   loss | grad norm |       lr | tok/s | s/step
4    10 | 2.6204 |     0.834 |  2.50e-4 |   182 |   1.27
    50 | 2.0939 |     1.927 |  4.81e-4 |   176 |   1.31
eval @ 50: loss 1.8146 ppl 6.139
   250 | 1.6318 |     0.907 |  5.00e-5 |   193 |   1.32
done:   250 steps in 351.3s; train loss 2.6204 -> 1.6318
5saved:  data/runs/SmolLM2-135M/lora_adapters.safetensors (+ ...state.json)
6eval after: loss 1.6521 ppl 5.218 (2744 tokens)
ferrotensor train with the command below, on an NVIDIA A10G through Vulkan with a 0.5 build. Rows 70 to 240 are left out.
  1. The GPU in use. On a Mac this says Apple M2 (Metal).
  2. The trainable parameters are the LoRA adapters: 921,600 of them, rank 8 on q/k/v/o of every layer.
  3. Held-out loss of the base model, before any training.
  4. Seconds per optimizer step (8 sequences). tok/s counts response tokens.
  5. The adapter, with its rank, alpha and targets in the file metadata, plus optimizer state for resuming.
  6. Held-out loss after 250 steps: 2.43 to 1.65.

Steps

  1. Prepare a model and data as in Download a model and prepare data.

  2. Train. These are the settings of the measured run:

    ferrotensor train \
      --model data/models/SmolLM2-135M \
      --data data/alpaca/train.jsonl --eval-data data/alpaca/val.jsonl \
      --out data/runs/sft --seq-len 256 \
      --lr 5e-4 --warmup-steps 20 --grad-accum 8 --max-steps 250 \
      --log-every 10 --eval-every 50 --save-every 50 \
      --sample-prompt "Give three tips for staying healthy."
  3. 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):

ModelHeld-out loss
SmolLM2-135M2.4250 → 1.6521
SmolLM2-360M2.0852 → 1.3228
SmolLM2-1.7B, f16 base weights2.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.

$ ferrotensor eval ... --lora data/runs/sft/lora_adapters.safetensors
1lora:   data/runs/SmolLM2-135M/lora_adapters.safetensors (240 tensors)
2eval: 64 examples, 2744 tokens, loss 1.6521, perplexity 5.218 (4.5s)

$ ferrotensor generate ... --prompt "Translate 'good morning' into French." --temperature 0
3Bonjour, bonne journe!
4[18 prompt + 8 new tokens, 14.3 tok/s, kv cache on]
ferrotensor eval and ferrotensor generate on an NVIDIA A10G through Vulkan with a 0.5 build.
  1. The adapter is applied on top of the frozen base model: 240 LoRA tensors.
  2. Reloading the adapter reproduces the held-out loss from training.
  3. Greedy output with the adapter. The base model repeats the prompt instead.
  4. Generation speed, with the KV cache.

Steps

  1. Measure the held-out loss with the adapter:

    ferrotensor eval --model data/models/SmolLM2-135M \
      --data data/alpaca/val.jsonl \
      --lora data/runs/sft/lora_adapters.safetensors
  2. Generate, greedily:

    ferrotensor generate --model data/models/SmolLM2-135M \
      --lora data/runs/sft/lora_adapters.safetensors \
      --prompt "Translate 'good morning' into French." --temperature 0
  3. 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.

PromptBase SmolLM2-1.7BWith the adapter
Translate 'good morning' into French.Repeats the prompt until the 60-token limitBonjour
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.

1$ ferrotensor train ... --max-steps 300 --resume data/runs/sft/lora_adapters.safetensors
2continuing at step 250
ferrotensor train --resume in the measured walkthrough run.
  1. Point --resume at an adapter a previous run saved; raise --max-steps to train further.
  2. The adapter, the AdamW moments and the step counter are restored. Batches already seen are skipped, in the same seeded order.

Steps

  1. Keep the .state.json and .state.safetensors files next to the adapter. They hold the step and the optimizer state.

  2. Run the same command with a higher --max-steps and --resume:

    ferrotensor train --model data/models/SmolLM2-135M \
      --data data/alpaca/train.jsonl --out data/runs/sft --seq-len 256 \
      --lr 5e-4 --warmup-steps 20 --grad-accum 8 --max-steps 300 \
      --resume data/runs/sft/lora_adapters.safetensors

Details

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.

"model": "HuggingFaceTB/SmolLM2-135M",
1"device": "NVIDIA A10G (Vulkan)",
2"heldout_loss_before": 2.425,
"heldout_loss_after": 1.6521,
"heldout_ppl_after": 5.218,
3"seconds_per_step_median": 1.328196144104004,
4"peak_memory_gb": 2.06,
"adapter_mb": 3.7,
data/runs/SmolLM2-135M/summary.json from an NVIDIA A10G run with a 0.5 build. The loss curve and generations are left out.
  1. Where it ran.
  2. Held-out loss before and after, on the same 64 examples as the walkthrough.
  3. Median seconds per optimizer step.
  4. Peak host memory of the training process.

Steps

  1. From a checkout of the repository, install the Hugging Face tool:

    pip install huggingface_hub
  2. Run the script with a Llama-style model:

    scripts/lora-run.sh HuggingFaceTB/SmolLM2-360M
  3. 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.
  1. The examples default to the CPU. Set FERROTENSOR_DEVICE=gpu to use the GPU.
  2. 99.5% test accuracy on two noisy interleaved half-circles.

Steps

  1. From a checkout:

    cargo run --release -p ferrotensor --example mlp_two_moons
  2. 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.
  1. nn::Embedding, nn::LayerNorm, causal nn::MultiHeadAttention and nn::Linear.
  2. The loss falls from 4.6 to 0.6 on training windows.
  3. The same 600 steps also run on the M2's GPU with FERROTENSOR_DEVICE=gpu.
  4. Partly English-shaped, partly not: a working training loop on 3.7 KB of text, not a language model.

Steps

  1. 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.

1ferrotensor::manual_seed(42);
2ferrotensor::serialize::save_module(&model, "model.safetensors")?;
3ferrotensor::serialize::load_module(&model, "model.safetensors")?;
Save and load a module's parameters, and seed every random source.
  1. Seeds random tensors, layer initialisation and dropout, so a program gives the same numbers on every run.
  2. Writes every named parameter to a safetensors file.
  3. Loads them back in place. Loading is strict: missing or extra names are errors.

Steps

  1. In Rust, use the three calls above. serialize::state_dict and load_state_dict give you the named tensors directly.

  2. In Python:

import ferrotensor as ft
ft.manual_seed(42)
model.save("xor.safetensors")
model.load("xor.safetensors")

Details

Safetensors files load as F32, F16, BF16 or F64 (F32, F16 or BF16 in Python) and are converted to f32.

04 Performance

Choose a GPU and backend

Pick between the GPU and CPU, and between Metal, Vulkan, DX12 and GL.

1WGPU_BACKEND=vulkan ferrotensor info --check
2ferrotensor train --device cpu ...
3let device = Device::best();   // or Device::gpu(), Device::cpu()
4FERROTENSOR_DEVICE=gpu cargo run --release -p ferrotensor --example mlp_two_moons
The switches Ferrotensor reads.
  1. Restricts which backends are tried: vulkan, metal, dx12, gl or a comma list. Applies to the library, the CLI and the tests.
  2. The CLI's --device: auto and gpu use the high-performance GPU; cpu uses wgpu's software adapter, which is slow.
  3. In Rust, Device::best() falls back to the CPU device; Device::gpu() returns None without a GPU.
  4. The examples read FERROTENSOR_DEVICE and default to the CPU.

Steps

  1. Check what is available with ferrotensor info.

  2. On Windows, compare backends on the same GPU:

    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.
  1. Results are bit-identical with fusion on and off; speed has not been measured for this release.

Steps

  1. 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
  2. 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).
  1. One JSON file per machine, backend and commit, under reports/.
  2. A summary line: the GPU, whether the kernel check passed and how many results were recorded.

Steps

  1. From a checkout, run the full report (or add --quick for a short one):

    scripts/hardware-report.sh
  2. 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.
  1. 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.
  2. The Tensor API: forward values and gradients on the GPU must match the CPU.
  3. Finite-difference gradient checks of every autograd op on the GPU.

Steps

  1. Clone the repository, then run the suites above. Without the variable, GPU tests skip themselves.

  2. 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.
  1. Adapters, limits and the kernel check, as JSON. Paste it into the bug report's field for it.
  2. Optional: the full benchmark report, the same measurement every published number comes from.

Steps

  1. Run the commands above.

  2. Open an issue on GitHub and attach the output, whether the checks passed or failed.

Details

The full checklist is in Testing on your GPU.

06 Troubleshooting

No GPU found, or the wrong one

What to do when Ferrotensor runs on the CPU or picks an unexpected adapter.

1No GPU adapter found. Ferrotensor's CPU device still works.
ferrotensor info when wgpu finds no adapter.
  1. wgpu could not open a GPU. Programs that use Device::best() or ft.Device("best") keep working on the CPU.

Steps

  1. On Linux, install a Vulkan driver (NVIDIA's driver, or Mesa for AMD and Intel) and check with vulkaninfo --summary.

  2. If several adapters are listed, restrict the backend with WGPU_BACKEND, for example WGPU_BACKEND=vulkan.

  3. In a container or VM without GPU access, use the CPU device: Device::cpu(), ft.Device("cpu"), or --device cpu for the CLI.

06 Troubleshooting

Training is slow or uses too much memory

Why tiny models are faster on the CPU, and how to lower GPU memory.

10.6                         11,671 MiB
20.7                          8,142 MiB
30.7, --checkpoint-blocks     5,313 MiB
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.
  1. The released 0.6.0.
  2. 0.7 hands each intermediate gradient back once it is used and reuses freed buffers; on by default.
  3. --checkpoint-blocks recomputes each decoder block during backward: 19 to 39% more time per step (medians over 30 steps).

Steps

  1. Use the latest release: cargo install ferrotensor-cli --force.

  2. Small models train faster on the CPU, because every GPU dispatch has a fixed overhead.

  3. 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.

  4. 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.

Something missing or wrong? Open an issue.