Changelog
All notable changes to this project are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
UnreleasedLink to this section
0.7.3 - 2026-11-26Link to this section
export-gguf writes Qwen2 checkpoints, tokenizers that store their BPE merges as pairs (Qwen3) load, and F::nll_loss runs on the GPU. Nikhil Gogu contributed the GGUF export, the nll_loss kernels and the fusion change (#234, #235, #236).
AddedLink to this section
ferrotensor export-ggufandferrotensor_trainer::gguf::export_ggufwritemodel_typeqwen2checkpoints such as Qwen2.5-0.5B-Instruct, as llama.cpp'sqwen2architecture: theqwen2.*keys, the query, key and value biases asblk.N.attn_{q,k,v}.bias, the query and key rows in the Hugging Face order (the order llama.cpp rotates forqwen2), theqwen2pre-tokenizer name, andtokenizer.ggml.normalizer.nfcwhen the tokenizer normalizes to NFC. Any other bias and any othermodel_typeare still refused with exit code 2. The f16 file of Qwen2.5-0.5B-Instruct has the 290 tensors of the file llama.cpp'sconvert_hf_to_gguf.py(commit244640b) writes from the same checkpoint, with the same names, types, shapes and bytes, and llama.cpp completes three prompts with the same 16 tokens from both; withferrotensor generateon an NVIDIA H100 NVL,scripts/check_gguf.shprintsmatchfor the same three prompts. (#216)
ChangedLink to this section
ferrotensor:F::nll_lossruns on the device, ascross_entropywith class ids does. The newnll_rowskernel reads each row's target log-probability andnll_gradwrites the gradient, so only the ids are uploaded: the[rows, classes]weight tensor that was built on the host is gone, and an id tensor is not read back. Withlog_probson a GPU, an id tensor holding an id that is not below the number of classes now gives a NaN loss instead of a panic, as incross_entropy. The mean is a sum divided by the count, so a loss can differ from the old one in its last bits.ferrotensor: withFERROTENSOR_FUSION=1, a fused group passes values between its steps in registers and writes only the results a tensor still holds. An intermediate that no tensor holds any more, as in code without autograd, is not written, needs no binding and goes back to the buffer pool at the next step, so the tensor-api benchmark's 100-op chain runs as one dispatch where it ran as 20. On an NVIDIA H100 NVL that chain on[64]went from 0.241 ms to 0.107 ms with fusion on. Results are unchanged bit for bit. Seedocs/design/op-fusion.md.- The nine crates, the Python package and
CITATION.cffgive https://ferrotensor.dev as the project's homepage. (#232) - The PyTorch baseline in
benchmarks/baselines/pytorch_lora.pycomputes its loss on flat[rows, vocab]logits, so PyTorch no longer runs its spatial softmax kernels, which took 22% of a SmolLM2-1.7B step on an A10G. The loss is the same. (#170)
FixedLink to this section
ferrotensor:F::nll_lossreturned NaN when a log-probability away from the target was-inf(a class of probability 0), because it multiplied that value by a zero weight. It now reads only the target's log-probability.- The f16 copy of each LoRA A matrix (
lora_mirror_f16) rounds f32 to f16 with integer operations, so it equalsUnifiedTensor::from_f32_as_f16bit for bit on every device. WGSL leaves the rounding ofpack2x16floatto the device, and WARP on DX12 rounded some values down instead of to nearest even. Values past the f16 range now become infinities. ferrotensor-loader: atokenizer.jsonthat stores each BPE merge as a["left", "right"]pair, as Qwen3's does, now loads. The pinnedtokenizers0.19.1 reads merges only as"left right"strings, so the loader rewrites the pairs and reads the file again. (#161)
0.7.2 - 2026-11-24Link to this section
Mostly GPU work on LoRA training: matmul, attention, the buffer pool, the optimizer and the memory planner. Read before upgrading: the readback functions of the backend now return a Result (under Changed), and a batch of up to two sequences is padded to 32 tokens by default (under Changed). The cooperative-matrix kernels, the fused projections and the autotuner are opt-in (under Added).
AddedLink to this section
- Opt in with
FERROTENSOR_EXPERIMENTAL=1: f16-weight matmuls on cooperative matrices (a tiled kernel with split-K, register-prefetch tiles, and fused loaders and epilogues), tensor-core flash attention forward and backward for head size 64, and fused q/k/v and gate/up projections in LoRA training with grouped LoRA kernels and an f16 copy of each A matrix. Inputs past the f16 range are clamped and counted.FERROTENSOR_FLASH_COOP=0keeps the scalar attention kernels andFERROTENSOR_FLASH_ROWSforces the rows per workgroup. A wide forward product against a transposed weight walks the cooperative grid in groups of row tiles so a wave shares its weight columns. FERROTENSOR_AUTOTUNE=1times up to eight tile and split-K candidates for each product inside the training step and keeps the fastest in a cache file keyed by adapter, driver and Ferrotensor version. A missing, corrupt or mismatched file is ignored with a warning.train --jsonreports anautotuneobject. With the variable unset, the router's choice is unchanged.train --length-bucket Npads every micro-batch to a multiple of N tokens, and the step profile counts pool buffers.FERROTENSOR_SHADER_CHECKS(noloop,nobounds,nodiv,nozeroinit,noneor a comma list) builds the kernels without some of wgpu's runtime checks. Unset meansnoloop;defaultkeeps every check.FERROTENSOR_UNIFORM_PARAMS=1andWgpuContext::with_uniform_paramskeep uniform buffers for kernel parameters.- Benchmark tools:
matmul-tunetimes every cooperative and thin-matmul configuration on model shapes,matmul_benchtakes--tilesand a plain qkv dX case, andfused_benchis a new example.
ChangedLink to this section
- Matmuls with up to 256 rows run on a tuned tile and split-K choice, and 32 to 63 row products against f16 weights go to the cooperative kernel. The router has new rows for up to 2,048 rows of SmolLM2-360M and 1.7B and finds its rows through an index. Thin f32 products (the LoRA
x @ Aand its gradients) run on a new skinny kernel with a fixed-order reduction. The coop matmul is built without shader bounds checks at 256 rows or more. - Attention: 32-row workgroups, RoPE applied inside the kernels, and dK and dV computed for each query head and summed over the head group in head order.
- The buffer pool rounds a request up to a size class and serves it from a larger idle buffer before it creates one. Bind groups are cached by buffers instead of tensor length, 32,768 are kept, and only those of freed buffers are evicted. Up to 128 dispatches share a compute pass, up from 8. The memory report counts the extra bytes of a larger pooled buffer as
pool slack(pool_slack_bytesinmemory_report.json,MemorySnapshotandBufferRecord). Results are unchanged. - Kernel parameters are passed as immediates when the device has them, with a uniform-buffer fallback. DX12 keeps uniform buffers.
- The optimizer steps over one gradient arena: gradients are packed into one flat buffer, the clip norm matches the per-tensor path bit for bit, and the arena is cleared on the GPU.
- A micro-batch of up to two sequences is padded to 32 tokens by default; larger batches pad to the longest sequence.
--length-bucketorTrainer::with_length_bucketforces one bucket.lm_headruns only on supervised rows. finetuneandplanplan memory for the dataset's real padded length and require the longest batch to fit the budget. Gate and up are fused underautoup to a summed width of 8,192.- Smaller kernel work: RoPE rotates out of place, the RMSNorm weight gradient is skipped when the weight is frozen, the residual gradient is added inside the RMSNorm backward kernel, an add passes its gradient on without a copy, a window's losses are read back once with the loss gradient seeded in the kernel, and a training embedding table is gathered on the GPU.
- The backend moves to wgpu 30.0.2.
UnifiedTensor::to_vec,read_manyandadapters::self_checkreturnReadbackErrorwhen wgpu cannot map the staging buffer instead of panicking, and device loss is named in readback errors.info --jsonlists each adapter's cooperative-matrix shapes.
0.7.1 - 2026-11-21Link to this section
Five GPU kernel changes to LoRA training, in attention, matmul and the LoRA scale. One library change can break code: FlashAttentionNode has two new public fields, so code that builds it with a struct literal must set them (under Changed).
AddedLink to this section
- Library:
ComputeEngine::flash_attention_v2_with_statsandflash_attention_v2_backward_with_statsrun attention with the per-row log-sum-exp saved in the forward pass and read back in backward. (#168)
ChangedLink to this section
- LoRA layers scale the rank-sized
x @ Ainstead of the full-size product, and skip the scale when alpha equals rank. (#165) - The tile matmul reads a transposed weight along k, so the frozen forward
x @ W^Tloads it coalesced. (#166) - Training attention saves the forward output and log-sum-exp and no longer reruns the forward kernel inside backward.
FlashAttentionNodegains the public fieldsoutandstats. (#168) - Attention forward and backward run in 16-row blocks with eight threads per row, so short sequences use many more workgroups. (#169)
- Matmuls with 16 to 256 rows against a weight at least 256 wide and deep run through a new split-K kernel with a deterministic reduction. (#172)
- The README and the LoRA SFT example compare this code with PyTorch + PEFT on one A10G (19 November 2026): 1.87×, 1.83× and 1.13× as fast as eager PyTorch at SmolLM2-135M, 360M and 1.7B, and 0.26× of PyTorch with
torch.compileand graph capture at 135M. This replaces the comparison measured on a 0.6 development build.
0.7.0 - 2026-11-19Link to this section
Two behaviour changes to know before upgrading: --train-modules layers.N now matches layer N exactly, and train --resume with --max-steps at or below the saved step now trains nothing (both under Changed). --q4-weights is experimental and still fails its quality gate (under Added).
AddedLink to this section
- GPU time by kernel from timestamp queries.
train --profileadds to its median-step report a table of kernel name, dispatches, GPU milliseconds and share, sorted by GPU time, and toprofile.jsonkernel_timing,kernel_gpu_seconds_per_stepandkernels(name,dispatches_per_step,gpu_seconds_per_step). Newgenerate --profileprints the totals and the table for the prefill and per decode token, and--jsonadds them underprofile. Matmul is split by kernel (f32, f16 or 4-bit weights), layout and a size class. Timestamps go before and after each dispatch inside the usual passes when the adapter allows it (inside_passes), else at the start and end of one-dispatch passes (pass_boundaries); without timestamp queries one line says so and the totals print as before. They are read back at the waits the step already makes, and without--profilethe device and the recorded work are unchanged.infoshows each adapter'skernel_timing. Library:KernelTiming,KernelTimingMode,KernelTime,KernelTimes,WgpuContext::try_new_with_timing,kernel_timing_modeandkernel_times, andAdapterReport::kernel_timing. - CI runs the GPU test suites through Metal on GitHub's Apple silicon runners (a virtualised GPU,
Apple Paravirtual device) and through DX12 on WARP, Microsoft's software adapter; on WARP without theferrotensor-cliend-to-end tests, which take too long there, and on pull requests only the backend kernel tests and the Tensor API parity tests (the full DX12 run, 2 h 22 min, is onmain, weekly and byworkflow_dispatch). Neither is a real-hardware result.WGPU_DX12_COMPILER(dxcorfxc) picks the DX12 shader compiler forWgpuContextandDevice::gpu; CI uses DXC on WARP, where FXC took about 9 minutes to open the GPU. (#141) - Experimental: tools to find where the 4-bit loss comes from;
--q4-weightsstill fails its quality gate (A10G run).--q4-modules KEYSand--q4-skip KEYS(on every command with--q4-weights, which they need) choose the linear weights stored at 4 bits with the--train-moduleskeys; the defaultlayerskeeps what--q4-weightsstored before, every decoder-block projection, andheadquantiseslm_head, also when tied to the embedding.--q4-group 16|32|64|128(default 64) sets the weights per scale; the tensor carries the size and the matmul kernel reads it from the params word.trainrecords the selection, group size and number of 4-bit tensors intraining_state.json, the adapter's.state.jsonandtrain --json(q4_weights, absent without--q4-weights).ferrotensor q4-report --model DIR [--q4-group N] [--json]reads a checkpoint one tensor at a time on the host and prints, for every 2-D weight, the relative and largest error of the 4-bit round trip and the share of groups whose range one outlier sets. Library:q4::Q4Group,q4::round_trip_error,UnifiedTensor::q4_group,model_builder::{Q4Selection, module_matches}andLfm2ModelBuilder::with_q4_selection;q4::quantize,dequantize,packed_wordsandUnifiedTensor::from_f32_as_q4take the group size. A 4-bit selection that matches no weight is a build error (exit code 2). ferrotensor pretrain --tokenizer bpe --vocab-size N(default 4096) learns a byte-level BPE tokenizer from--databefore training: the 259 byte-level tokens at their ids, then one token per merge of the most frequent adjacent pair within theByteLevelpre-tokenizer's words, a tie going to the lowest ids, so the same corpus and size give the sametokenizer.jsonand every text decodes back exactly.--tokenizer bytestays the default. A--vocab-sizeof 259 or less or above what the corpus can fill,--vocab-sizewithbyte, a corpus that is not UTF-8, and a--resumewhose saved tokenizer has another size than the flags ask for exit with 2;--resumereuses the saved tokenizer.pretrain --jsonaddstokenizer. Library:ferrotensor_loader::tokenizer::train_byte_level_bpe.ferrotensor export-gguf --model DIR --out FILE.ggufandferrotensor_trainer::gguf::export_ggufwrite a Llama-style model as one GGUF version 3 file for llama.cpp and Ollama: 2-D weights in f16 and 1-D tensors and norms in f32 (--f32for all f32), llama.cpp tensor names, query and key rows reordered to llama.cpp's rotary layout, thegeneral.*andllama.*metadata fromconfig.json, and a byte-level BPE tokenizer (gpt2model,gpt-2orsmollmpre-tokenizer) with its merges, special token ids and chat template.--loraadds an adapter while writing, withmerge's maths. It streams one row at a time, and refuses with exit code 2 an existing output, a non-Llama model, a configcheck_supportedrefuses (scaled RoPE among others), projection biases (Qwen2), a quantized base and other tokenizers. Written to the GGUF v3 specification; on one A10G run llama.cpp loaded the SmolLM2-1.7B file and matched the greedy completion of one prompt, two tokens (scripts/check_gguf.sh). The temporary file of the streaming writers is now<file>.tmp, the same name as before for.safetensorsfiles.- Qwen2 checkpoints load: a projection with a
<name>.biastensor gets that bias (Linear::bias, added on the GPU asones @ bias, so its gradient flows when the base trains and it stays frozen under LoRA), and the RoPE base is read fromrope_parameterswhenrope_thetais absent (thetransformers5 layout). CI generates a tiny randomQwen2ForCausalLMwithscripts/gen_qwen2_fixture.pyand checks its logits (full forward, KV-cache decoding, batched) and LoRA gradients against Hugging Face transformers (ferrotensor-trainer/tests/qwen2_family.rs). Qwen2.5-0.5B-Instruct loads on one A10G (held-out loss 1.3359). ferrotensor pretrain --data corpus.txt --out DIRtrains a small byte-level Llama-style model from random weights and leavesDIRas a model directory thatgenerate --rawloads: a 259-token byte-leveltokenizer.json(<pad>0,<s>1,</s>2, bytebasb + 3), an untied f32 model initialised from N(0, 0.02²) with a seeded generator, the corpus astokens.bin,train --task pretrain --train-modules full, then the trained weights written asmodel.safetensorsin the Hugging Face layout (the initial model lives inDIR/init; see Fixed). The training defaults are not tuned.--resumecontinues a run in the same directory. CI loads the result in Transformers and checks its loss againsteval's. Library:ferrotensor_loader::tokenizer::byte_level_tokenizer_jsonandferrotensor_trainer::pretrain(LlamaSize,write_random_llama,write_hf_weights). (#126)- The token embedding can train:
train --train-modules embedtrains only the embedding andfulltrains it with every base weightallselects (allis unchanged).Tensor::embeddinggathers rows on the host and, when the table requires a gradient, records anEmbeddingNodewhose backward scatter-adds each position's gradient into its row.Lfm2Model::with_trainable_embeddingmakes the table trainable (it is frozen otherwise, also when the other base weights train), and the lookup then reads the table back from the GPU each time;Lfm2Model::clear_host_embeddingsdrops the host copy after new values are loaded into a frozen table, aseval --loraandgenerate --lorado for trained weights that include it. A tiedlm_headstays a separate copy. A--train-modulesvalue that names the embedding by substring, such asembed_tokens, now trains it too; before, the optimizer received the table but it never got a gradient. (#124) --modelof every command takes a Hugging Face model id such asHuggingFaceTB/SmolLM2-135Mthat is already in the local Hugging Face cache, as well as a directory; an existing directory wins. stderr showsmodel: <id> (<snapshot>)once, and an id that is not cached exits with 2 and names the cache andhf download <id>, as does a snapshot withoutconfig.json(an incomplete download). Nothing is downloaded. After a LoRAtrainorfinetune, stderr ends with thechatandmergecommands for the run.FerrotensorHub::newnow follows Hugging Face's cache order (HF_HUB_CACHE,HF_HOME,XDG_CACHE_HOME, thenHOMEorUSERPROFILE) instead ofHOMEalone,find_latest_snapshotreturns the snapshotrefs/mainpoints to (else the smallest snapshot name, not an arbitrary one), andFerrotensorHub::cache_dirreturns the cache directory. (#121)ferrotensor chatholds a multi-turn conversation with a base model or a LoRA adapter, one user message per line of stdin, with the sampling flags ofgenerate(now shared through one flattened set). Each turn re-encodes the whole conversation in ChatML (Tokenizer::encode_conversation;encode_chatis its one-turn case). When the conversation no longer fitsmax_position_embeddings(now read intoLfm2Config) the oldest exchanges are dropped and the system message is kept; a message that does not fit alone, or a tokenizer without ChatML tokens, exits with 2.--jsonprints one object per reply, each on its own line. (#118)ferrotensor mergeandferrotensor_trainer::merge::merge_adapterwrite a standalone model directory with a LoRA adapter folded into the base weights (W + alpha / rank * (A B)^T, each weight in its own dtype), streaming one tensor at a time so host memory stays near one row plus the adapter. It accepts a Ferrotensor adapter file or a PEFT directory, refuses quantized bases and mismatched adapters, and gives a tiedlm_headits own weight.--jsonprints the output directory and the tensor counts. CI loads the merged model in Transformers and checks its logits against Ferrotensor's within 1e-3.WeightsContext::tensor_nameslists a checkpoint's tensors. (#117)--jsononfinetune,train,evalandgenerate: stdout carries one JSON object when the command ends (the training summary with the measured GPU peak, and forfinetunethe plan; the loss and perplexity; the generated text and token counts) and every other line goes to stderr. With--json, errors print{"error": "..."}on stdout.AGENTS.mddocuments each object, the exit codes and the one-command path for coding agents, andllms.txtindexes the docs.plan,chat,mergeandpretrainhave--jsonfrom their own entries. (#115)ferrotensor finetunerunstrainwith the batch size, sequence length, gradient accumulation and block checkpointing thatplanpicks for this machine, except those given on the command line, and prints the plan to stderr first. It takes everytrainflag plus--memory-mib,--vram-miband--force. A plan that does not fit exits with 2 and does not train unless--forcetrains the smallest configuration anyway;--liteis refused. (#111)ferrotensor planestimates the peak GPU memory of LoRA training from a model'sconfig.jsonand prints the largest configuration that fits the memory budget with 15% left free, with thetrainline to run it: the longer sequence first (256, then 128), then no checkpointing before--checkpoint-blocks, then the larger batch size (8, 4, 2, 1). The budget is--memory-mib,--vram-mib, 60% of system RAM on a GPU that shares it, thenvidia-smitotal on an NVIDIA GPU, or an assumed 4,096 MiB. The estimate is fitted to measured A10G peaks (see Changed).--jsonprints one object, and without--modelthe documented SmolLM2 sizes are listed. (#107)train --profilecounts the GPU work of every optimizer step (dispatches, bind groups, uniform buffers, submits, synchronizes, uploads and readbacks) and, after the run, prints the step with the median wall time and writesprofile.json. (#106)ferrotensor export-adapter --format peftandferrotensor_trainer::peft(export_peft_adapter,save_peft_adapter,load_peft_adapter) write and read Hugging Face PEFT adapter directories for Llama-style models.eval --lora,generate --loraandtrain --resumeaccept a PEFT directory. CI loads the exported adapter in PyTorch + PEFT and checks its logits against Ferrotensor's within 1e-3. (#74)- Tests: the loss and per-parameter gradients of LoRA training (one sequence, batched, masked, trainable base) are checked against PyTorch autograd on a tiny model (
ferrotensor-trainer/tests/gradient_parity.rs). (#86) train --memory-report[=N]: a GPU memory breakdown by category (weights, adapters, optimizer state, activations, gradients, loss) after model load and the first N optimizer steps, with JSON output;WgpuContext::memory()exposes the counters. (#90)- Opt-in per-block activation checkpointing (
Lfm2Model::with_block_checkpointing,ferrotensor train --checkpoint-blocks). (#94) - Experimental: a 4-bit (affine, groups of 64) weight format and a matmul that decodes it in
ferrotensor-backend(#95), and--q4-weights, which stores frozen decoder-block weights at 4 bits; this changes the model's outputs.--q4-weightsis experimental and still fails its quality gate: the untouched base model has a higher held-out loss with it than with f16. Use it only when nothing else fits. (#96) ferrotensor classify-trainandclassify-predict: LoRA fine-tuning of a decoder as a text classifier from JSONL, with per-line class probabilities.ClassifierTrainerand theferrotensor_trainer::classifymodule (two learning rates, gradient accumulation, clipping, schedule, head save/load, batch planning, balanced accuracy).ClassifierHead::with_skip_firstleaves the first token out of the mean pooling. (#73)- A sequence classification head over decoder hidden states. (#71)
- Qwen3-style attention, with per-head
q_norm/k_normRMSNorm before RoPE, loaded fromself_attn.q_norm/k_normwhen present. Checked on a synthetic model against a CPU reference; real checkpoints are not measured yet. (#72) scripts/bench_mac.sh, a reproducible comparison of Ferrotensor, mlx-lm and PyTorch + PEFT (MPS) LoRA training on Apple silicon, and--device mpsforbenchmarks/baselines/pytorch_lora.py. (#87)- Examples: LoRA fine-tune, resume and KV-cache generation on a tiny model, run in CI. (#81)
- Tests: whole-model forward checks against a CPU reference. (#83)
- CI: every example is executed, on CPU or software Vulkan (#82); the flash attention and reference tests run in the GPU job (#77); the CLI runs end to end on a tiny model (#79); the Python GPU parity tests run, and
FERROTENSOR_RUN_GPU_TESTSis the one switch (#80).
ChangedLink to this section
- Matmuls with a short output side run a thin kernel (
matmul_thin, andmatmul_thin_hfor f16b) instead of the 64x64-tile kernel: when the output has at most 64 rows (a short training pass against a weight, forward and input gradient, and LoRA products with few rows) or, for f32b, at most 64 columns (LoRA products of rank up to 64, such asx @ A, run as the transposed product). A workgroup covers 8 rows by 32 columns and its threads split the inner dimension, reading f16 weights a word at a time. One-rowa @ bkeeps the matrix-vector kernel and 4-bitbkeeps the tile kernel. Same maths with a different summation order.--profilenames the new kernels with the size classm<=64orn<=64. On one NVIDIA A10G (Vulkan, builds interleaved, three runs each), a training step at sequence length 256 with batch 1 × 8 accumulation went from 1.193 to 0.961 s on SmolLM2-135M, 1.571 to 1.203 s on 360M and 2.233 to 1.697 s on 1.7B, and with batch 4 × 2 on 1.7B from 1.348 to 1.261 s. The training loss at step 30 is the same on both builds (135M 2.5320, 360M 1.8838, 1.7B 1.4793, also 1.4793 at batch 4 × 2), and the gradient norm at step 30 printed the same. A 250-stepfinetuneof 1.7B (batch 4 × 2) went from 328.0 to 320.0 s with held-out loss 1.0612 onmainand 1.0607 here (the summation order differs) and the same tracked peak, 14,061 MiB. Generation is unchanged. See benchmarks/RESULTS.md. - Decoding one token no longer runs the training kernels. A one-row
matmul,matmul_f16bormatmul_q4b(every linear layer,lm_headand an unmerged LoRA adapter while decoding) runs a matrix-vector kernel whose workgroup threads split the inner dimension and read whole weight words (matvec,matvec_h,matvec_q4), andflash_attention_v2_withwith one query runsflash_attention_decode, whose threads split the cached keys; same maths and options, with a different summation order. Greedygenerate,chatand the training sample pick the token withComputeEngine::argmax_rowson the GPU and read back token ids instead of the logits: per decode step, 4 bytes instead of 4 × vocabulary. Its tie rule is the host's: the largest value inf32::total_cmporder, the last index of equal maxima. Other sampling is unchanged.Sampler::is_greedynames the greedy case. On one NVIDIA A10G (Vulkan, builds interleaved, three runs each), greedygenerateof 120 tokens went from 58.4 to 110.1 tokens per second on SmolLM2-135M, 39.8 to 96.7 on 360M and 18.9 to 56.9 on 1.7B, and sampled generation (--temperature 0.7 --seed 7) from 52.6 to 91.5 on 135M and 18.3 to 51.2 on 1.7B, and three-turn greedychaton 1.7B from 18.9 / 17.1 / 15.7 to 56.7 / 55.0 / 53.4 per turn, with byte-identical greedy output; see benchmarks/RESULTS.md. - The monitor shows its clock in UTC (
HH:MM UTC) and no longer depends onchrono, which RustSec marks unmaintained (RUSTSEC-2026-0543). ferrotensor-backendencodes up to 8 consecutive kernel dispatches into one compute pass instead of one pass per dispatch; a copy or a submission ends a pass early. wgpu-core 0.19 builds and drops usage trackers sized by the highest live buffer id for every pass, and longer passes delayed GPU work. On one NVIDIA A10G (same machine, builds interleaved), a training step with batch 1 × 8 accumulation at sequence length 256 went from 1.166 to 0.989 s on SmolLM2-135M, 1.547 to 1.334 s on 360M and 2.216 to 2.169 s on 1.7B. Greedy generation went from 40.6 to 59.5 tokens per second on 135M and from 16.1 to 17.5 on 1.7B. Loss and gradient norm are unchanged; on a 250-step 1.7Bfinetunewith passes of up to 16 the tracked peak rose by 168 MiB.GpuCounterSnapshotandtrain --profileaddcompute_passesanddevice_polls. See benchmarks/RESULTS.md.- Internal: the crates are published to crates.io from CI when a
v*tag is pushed, with trusted publishing (no stored token), and aPackageCI job runscargo publish --workspace --dry-runon every pull request. - The
planandfinetunememory estimate is refitted on 9 peaks from a second card, an NVIDIA Tesla T4 (16 GB), with the 15 A10G peaks. The old one was 12.6% below SmolLM2-1.7B at batch 2 x 4 over 250 steps (11,138 MiB) and 13.1% below it at batch 8, sequence length 128, which filled the card. Accumulating runs keep growing past 30 steps (1.7B at 2 x 4: 9,541 MiB at 30 steps), so the estimate now targets the 250-step peak and adds 20% to activations when a step accumulates passes; activations count 0.92 times their f32 size plus 13 values per token and block per unit of key/value width; the fixed overhead is 1,600 MiB. It is at most 4.6% below all 24 peaks, at most 12% above the 250-step and single-pass peaks, and up to 35% above 30-step accumulating runs. Theplannote says so. - The docs record the T4 run of 16 November 2026 (main at
c7a0131) inbenchmarks/RESULTS.md. - Behaviour change:
--train-modules layers.Nnow trains layerNalone (an exact layer match) andlayers.A-BlayersAtoB; before,layers.1also matched layers 10 to 19 as a substring. The keys are matched bymodel_builder::module_matches, shared with--q4-modules. - Behaviour change:
train --resumewith--max-stepsat or below the saved step now trains nothing and only saves, where it took one more step. Forpretrainthis exports the weights of an interrupted run. (#128) - The docs record one run on a single NVIDIA A10G (24 GB) of 16 November 2026, a release build of
mainat8b814c1:plan,finetunewith no memory flags for SmolLM2-135M, 360M and 1.7B and Qwen2.5-0.5B-Instruct, a 250-step SmolLM2-1.7B run (held-out loss 2.6474 to 1.0612) followed byeval,merge,chatandexport-gguf, 4-bit losses of the untouched base models,train --profile, and byte-levelpretrain. They replace the statements that these commands were only tested on software Vulkan, and keep the limits: one GPU, one run, and a two-token llama.cpp check. The tables are inbenchmarks/RESULTS.md. - The
planandfinetunememory estimate counts the activations a decoder block keeps for backward from the autograd graph (every op output; flash attention keeps no scores, so the attention term is gone).TrainConfiggainsgrad_accum. The constants and the error bounds are in the refit above. tokens_per_secondofgenerate --json,chat --jsonand the stats line on stderr is now the decode speed: one-token forward passes after the prompt, per second, with the prompt left out (null when none ran). It used to divide the new tokens by the prompt and decode time together, which understated decoding and, with the kept chat cache, changed with how much of each turn's prompt the cache held. The new keyprefill_secondsgives the time to run the prompt, and the stats line shows both. After the last token--max-new-tokensallows, decoding no longer runs a forward pass whose logits nothing samples, so that token is not in the kept chat cache and the next turn runs it with the new message.Lfm2Config::eos_token_id: Option<u32>is noweos_token_ids: Vec<u32>, read fromeos_token_idas one id or a list.ferrotensor chatkeeps the KV cache across turns, so each turn processes only the new tokens: the new user message in the ChatML template, then the reply. The cache keeps the ids it holds; when a turn's encoding of the whole conversation does not start with them (old turns were dropped to fit the context,/reset, or the reply re-encodes to other ids) it keeps the longest common prefix and runs the rest, and it grows by copying when the conversation outgrows it. Greedy replies are the same as a full run of the conversation every turn (checked by a test).--jsonaddscached_tokens, the prompt tokens taken from the cache;prompt_tokensis still the whole conversation.model_builder::check_supportedrefuses a config whosehidden_actis not SiLU, whoserope_scalingorrope_parameterstype is notdefault(an object with neither a type nor afactorcounts asdefault), or that setsuse_sliding_window: true, and the builder refuses an odd head size; before, such a model loaded and gave wrong logits. Asliding_windowwithoutuse_sliding_window(Mistral-7B-v0.1) still loads, as Hugging Face applies no window there either. This refuses Llama 3.1 and later (llama3RoPE scaling). The CLI checks it right after readingconfig.json, and every model build error now exits with 2 instead of 1.Lfm2Configgainshidden_act,rope_scaling,rope_parameters,sliding_windowanduse_sliding_window.- Every crate enables the workspace lints:
unsafe_codeis denied, andmissing_docs,unwrap_used,expect_usedandpanicwarn; CI runs clippy with-D warnings. (#108, #109, #110, #112, #114, #116) - Inference no longer records an autograd graph:
generate,chat,eval, the evaluation duringtrainand classification predictions run their forward passes inside the newferrotensor_autograd::no_grad, under which ops return tensors with no creator node, so intermediate activations are released as soon as the next op has been recorded. Training is unchanged. (#120) ferrotensorexit codes are the same for every command: 0 success, 1 runtime error, 2 invalid input or a request this machine cannot meet. Invalid input (a missing model,config.jsonor data file, a flag out of range, a dataset with no usable examples) and a missing GPU adapter (ininfoand in the commands that open the GPU) now exit with 2 instead of 1.finetunereports a plan that does not fit aserror: ...instead offinetune: ...; the exit code stays 2. (#115)- Backward keeps the first gradient each tensor receives instead of copying it into a new buffer. (#91)
- Backward releases each intermediate gradient once it has been used; after
backwardonly leaves hold gradients, and a repeatedbackwardadds exactly one more gradient per leaf. (#92) - The buffer pool keeps buffers freed beyond its cap reusable until the GPU has finished the work recorded before them, then drops them and polls so wgpu destroys them at once (
FERROTENSOR_POOL_OVERFLOW=0restores the old behaviour); the memory report's awaiting-GPU count now drops as submitted work finishes. (#93) - Llama-style models name their block parameters as Hugging Face does (
input_layernorm,post_attention_layernorm,mlp.*instead ofoperator_norm,ffn_norm,feed_forward.*); LFM2 models are unchanged. Adapter files and optimizer state with the old names still load. (#74) apply_checkpointrejects adapter tensors the model does not have, instead of ignoring them. (#74)Attentionhas two new public fields,q_normandk_norm(Nonefor Llama), so struct literals need them. (#72)mean_pool_matrixtakes askip_firstargument. (#73)Optimizer::load_statereturnsResult<OptimizerLoad, String>instead ofbool(new public typeOptimizerLoad), andLoraMetadatahas a new public fieldtrained_modules: Option<String>. (#76)- A pretraining text line longer than
--seq-lenis now split into windows of at most--seq-lentokens instead of becoming one oversized example. (#78) - The README, the LoRA walkthrough, the CLI README, the website and
CITATION.cffstate only measured results, with their conditions: the GPUs tested, the PyTorch comparison with its speed ratios, the gradient parity test and the GPU memory by stage. (#97) - Loading a model uses less host memory: a tied
lm_headis built without host copies of the transpose, checkpoint file pages are released as each tensor is read, and the host embedding table is filled from the checkpoint. Peak host memory for SmolLM2-1.7B LoRA training on an NVIDIA A10G went from 5,087 MiB to 1,575 MiB (5.33 GB to 1.65 GB), 360M from 1,762 to 1,200 MiB and 135M from 1,253 to 1,138 MiB, with identical losses. (#98) - The docs and the website quote one confirmation run of merged
mainagainst the released v0.6.0 on one NVIDIA A10G: peak GPU memory for SmolLM2-1.7B LoRA is 11,671 MiB in 0.6.0, 8,142 MiB in 0.7 and 5,313 MiB with--checkpoint-blocks(+19% to +39% median time per step across the four measured settings). Within 0.7 the losses are identical with and without--checkpoint-blocks; against 0.6.0 they differ slightly because of the LoRA initialization fix below. The largest gradient difference against PyTorch autograd is below 1e-6 (9.5e-7 in that run). (#100, #101)
FixedLink to this section
ComputeEngine::top_kreturned the top index twice on Metal (seen on Apple's paravirtual GPU in CI): the kernel read back the indices it had just written. It now keeps the previous pick in registers. (#141)ComputeEngine::newpanicked withmatmul.wgsl changedwhen built from a Windows checkout with CRLF line ends. (#141)- The Tensor API's
tanhand GELU kernels compute tanh fromexp. With WGSL's built-intanh, which DX12 compiles to HLSLtanh, the GELU and Tanh gradients on WARP were about 1e-3 off the CPU. The Tensor API tests share one GPU device per process; on WARP, creating one per test failed withOutOfMemoryafter about 20 devices. (#141) - The four tests in
ferrotensor-trainer/tests/qwen2_family.rsskip with a message whenFERROTENSOR_QWEN2_FIXTUREis unset instead of failing, socargo test --release --workspace -- --ignoredruns to the end on a machine without PyTorch; a set but wrong path still fails, and CI sets the variable.docs/testing-on-your-gpu.mdsays how to generate the fixture. - A
config.jsonwhoseeos_token_idis a list (the formgeneration_config.jsonoften uses) no longer fails to load; every id in it ends generation. A prompt in the ChatML template (chat,generatewithout--raw, thetrain --sample-promptsample) also stops at<|im_end|>when the tokenizer has it, whatever EOS the config names;--rawkeeps its stop set. - The loader no longer hides errors behind a fallback. A Hugging Face tokenizer that fails to encode or decode returns the error instead of switching to the whitespace and character reader, and the CLI exits with 1 and names it; the plain reader is kept only for a
tokenizer.jsonthat is a baremodel.vocabmap with no modeltype, and a typedtokenizer.jsonthe Hugging Face reader refuses is now an error. Probing for an optional tensor (<name>.bias,q_norm, a tiedlm_head) reports a checkpoint file that no longer parses as an error instead of "absent". A refusedmadviseafter reading a tensor is an error instead of being dropped.FerrotensorHub::list_cachedreports an unreadable cache directory instead of listing nothing, and a cache path in an environment variable that is not UTF-8 is used instead of skipped. Public signatures that change:Tokenizer::encode,encode_continuation,encode_chatandencode_conversationreturnResult<Vec<u32>, String>andTokenizer::decodereturnsResult<String, String>;WeightsContext::get_tensor_inforeturnsResult<Option<TensorMetadata>, LoaderError>(wasOption<(Vec<usize>, String)>);ferrotensor_trainer::build_sft_examplereturnsResult<Option<TrainingExample>, String>;FerrotensorHub::list_cachedreturnsHubResult<Vec<String>>. - An interrupted
pretrainno longer leaves a random model that loads as if trained: the initial model is written toDIR/initand training starts from it, soDIR/model.safetensorsexists only once the trained weights are exported, and loadingDIRbefore that fails with a message that namespretrain --resume. (#128) --train-modulesvalues that select part of the base weights (attn,mlp,head,embed, a substring) now freeze the others (Lfm2Model::with_trainable_base_weights). Backward computed a gradient for every unselected weight and kept summing it across steps, one f32 buffer per weight that the optimizer never read. Gradient clipping summed only the selected gradients before and after, so losses, gradient norms and updated weights do not change; LoRA training is untouched. (#128)generateexits with 2 and a message when the prompt encodes to no tokens (--raw --prompt ""with a tokenizer that adds no BOS), where the forward pass got a zero-length sequence;generate_tokensnow returns aResult, sochatandtrain --sample-promptshare the check.generatealso readsmax_position_embeddings: a prompt longer than it exits with 2, and a prompt plus--max-new-tokensbeyond it lowers the new tokens to what fits and says so on stderr, instead of sampling past the trained context. (#123)Tokenizer::bos_token_idis thebos_tokendeclared in thetokenizer_config.jsonbesidetokenizer.jsonwhen it names a token, instead of always guessing<|im_start|>; the guess stays the fallback, and token ids from the Hugging Face tokenizer are unchanged because it never reads the field. A malformedtokenizer_config.jsonis now an error. The KV-cache attention output andEmbedding::forwardreturn frozen tensors, so cached logits of a frozen model no longer report that they require a gradient that could never arrive. (#122)- The LFM2 conv block wrapped its output in a fresh leaf, so no gradient reached the conv weight, its bias or the input projection.
Tensor::conv1dis differentiable now, with a WGSL backward kernel. (#105) - The MLP example and the Python tests that depend on random values are seeded, so CI no longer fails on an unlucky initialisation. (#125, #127)
Architecture::detecttreated any config withlayer_types, which recenttransformersversions write for Qwen3, as LFM2. Llama-style layers other than full attention are now rejected. (#72)- LoRA adapters of the same shape in one layer (for example
q_projando_proj) no longer start from the same A matrix; every adapter's seed now depends on its layer and projection name. Initial adapters, and so LoRA runs, differ from earlier releases. (#75) ferrotensor-cli trainwith--train-modulesother thanloranow saves the trained base weights (f32, only the tensors that trained) totrained_weights.safetensors; before, it wrote an empty adapter file.eval --lora,generate --loraandtrain --resumeload that file; an empty file from an older run is reported as such. (#76)Optimizer::load_statereports how many parameters got their saved state back and how many saved entries went unused.train --resumenow fails when the saved optimizer state matches none of the trainable parameters and warns when it matches only some. A saved moment of the wrong shape is rejected. (#76)save_lora_checkpointandapply_checkpointreport a tensor stored as f16 instead of writing or reading it wrongly. (#76)- Model loading returns an error instead of panicking or accepting bad input: invalid config sizes, shard paths that leave the model directory, empty shard indexes, odd-sized quantization scales, empty or duplicate-id tokenizer vocabularies, and non-file or oversized JSON files. Error messages name the file. (#84)
- Attention dropout (
attention_dropout > 0inconfig.json) now draws a different mask per training step, micro-batch, rank and layer from the trainer's run seed (Trainer::with_dropout_seed,--seedinferrotensor-cli train) instead of one fixed mask, and evaluation and generation no longer apply it. Newforward_with_dropout/forward_batch_with_dropoutonAttention,Lfm2BlockandLfm2Model, andferrotensor_graph::dropout. No change with dropout 0. (#89) - Pre-quantized (MLX
.scales) checkpoints are rejected instead of loaded wrongly. (#96) - A machine with no usable GPU adapter, or a driver that refuses the device, no longer makes the CLI panic: it prints the reason and exits with code 1 (code 2 for a missing adapter since #115, see Changed). New
WgpuContext::try_newandtry_new_with_optionsreturn aContextError;newandnew_with_optionsstill panic, now with the same message. (#113) merge_adapterremoves the partly writtenmodel.safetensors.tmpwhen writing the merged weights fails, and returns the write error. (#119)
0.6.0 - 2026-11-12Link to this section
AddedLink to this section
benchmarks/baselines/pytorch_lora.py: the LoRA walkthrough's recipe in PyTorch + PEFT (same split, chat template, response-only loss, truncation, LoRA init, optimizer, schedule, clipping and held-out metric), as a reference point for Ferrotensor's numbers on the same GPU.scripts/lora-run.shtakes--batch-size,--grad-accum,--f32-weightsand--name(a suffix for the run directory), and records them insummary.json.--help, or an option given where the model belongs, now prints the usage instead of starting a run.- Batched LoRA training: with
--batch-size N, a Llama-style model now runs N sequences through the GPU in one forward and backward pass, right-padded to the longest, instead of one at a time. Each sequence still contributes its own mean-loss gradient (per-row weights in the newComputeEngine::masked_cross_entropy_weighted) and optimizer steps fall after the same sequences, so the result matches the sequential path. NewLfm2Model::forward_batch,Lfm2Model::supports_batchingandmasked_cross_entropy_batch; LFM2 models with conv blocks keep training one sequence at a time. --f16-weightsforferrotensor train,evalandgenerate, andLfm2ModelBuilder::with_f16_weights: frozen linear-layer weights (attention, MLP andlm_head) are stored as f16, half their memory, while activations, products, norms, embeddings and LoRA adapters stay f32. On by default: on an NVIDIA A10G, LoRA on SmolLM2-1.7B reached a held-out loss of 1.0640 with f16 base weights against 1.0657 with f32, using 11.9 GiB of GPU memory instead of 14.7 GiB and 2.38 s per step instead of 2.49.--f32-weightskeeps them f32 (--f16-weightsis still accepted).Tensor::matmuluses the f16 kernels when its right operand is an f16 tensor that needs no gradient.ferrotensor-backend:UnifiedTensor::from_f32_as_f16stores a tensor as f16 (two values per 32-bit word, half the memory), andComputeEngine::matmul_f16bandmatmul_bt_f16bmultiply by such a weight matrix with f32 products and sums. The kernel unpacks with WGSL'sunpack2x16float, so it needs no f16 shader extension and runs on every adapter.ferrotensor-trainer:TrainingCheckpoint::savewrites the optimizer moments to an F32 safetensors file next to the JSON (moments_path), with the step in its header, instead of as JSON numbers. A SmolLM2-135M LoRA resume state goes from 50 MB to about 7.4 MB.loadreads both layouts, and rejects a moments file from a different step (a crash between the two writes).- A how-to guide on the website (
/guide/): 19 step-by-step guides, from installing and checking your GPU to LoRA fine-tuning, training in Rust or Python, performance and troubleshooting. Each has the real output to expect, annotated, with the machine it came from. - The LoRA walkthrough compares Ferrotensor with PyTorch + PEFT on the same NVIDIA A10G and recipe: identical held-out loss before training, within 0.005 after 250 steps, at 84% of PyTorch's speed for SmolLM2-135M and 37% for SmolLM2-1.7B.
ChangedLink to this section
ferrotensor-backend: uploading tensors no longer keeps a host-side staging copy of every upload until the next GPU submission.WgpuContext::note_uploadcounts uploaded bytes and every 256 MiB (UPLOAD_RELEASE_BYTES) waits for the copies so wgpu frees them;synchronizenow also submits pending uploads. Loading a model held a staging copy of all its weights (6.8 GB for SmolLM2-1.7B in fp32); in the CI test, uploading 768 MiB grew peak memory by 1536 MiB before and is bounded at under 1.6x now.- The README, CONTRIBUTING, the GPU testing guide, the architecture notes and the website's benchmarks and LoRA pages describe the NVIDIA results, the software-Vulkan CI job and op fusion; the README no longer says the Python package is missing from PyPI.
- The LoRA walkthrough, the README and the how-to guide show the 0.6 results on an NVIDIA A10G: SmolLM2-135M with
--batch-size 8at 0.57 s per step against 1.28 s one sequence at a time, the same held-out loss 1.6521; SmolLM2-1.7B with f16 base weights at held-out loss 1.0640, 2.38 s per step, 11.9 GiB of GPU memory and 5.33 GB of host memory (20.01 GB in 0.5).
FixedLink to this section
ferrotensorCLI: when the GPU runs out of memory, wgpu panics with "Parent device is lost" and no mention of memory. The CLI now adds a hint after such a panic: lower--batch-size(raising--grad-accum), shorten--seq-len, use--lite, keep the default f16 base weights.
0.5.0 - 2026-11-02Link to this section
AddedLink to this section
- LoRA results on an NVIDIA A10G for SmolLM2-135M, 360M and 1.7B in the LoRA walkthrough (
docs/examples/lora-sft.md): held-out loss 1.6521, 1.3228 and 1.0667 after 250 steps, at 1.33, 1.69 and 2.47 s per step. With the GPU changes below, SmolLM2-135M on the A10G went from 20.2 s to 1.33 s per step; its held-out loss is 1.6521 (1.6519 before, as on an Apple M2). - Kernel and Tensor API benchmark results on an NVIDIA A10G and a Tesla T4 through Vulkan in
benchmarks/RESULTS.md, with op fusion off and on. scripts/lora-run.sh MODELruns the LoRA SFT walkthrough on any Llama-style Hugging Face model with the walkthrough's data and settings and writes a JSON summary (held-out loss before and after, loss curve, seconds per step, peak memory, greedy generations).- Op fusion, off by default: with
FERROTENSOR_FUSION=1, consecutive same-size element-wise ops on the GPU run as onefuseddispatch of up to six steps instead of one dispatch each, still writing every intermediate. Results are checked bit-identical to unfused runs. Seedocs/design/op-fusion.md. - The
WGPU_BACKENDenvironment variable (vulkan,metal,dx12,glor a comma list) restricts which backendsDevice::new/gpu/best,WgpuContext::newandferrotensor infotry. - CI runs the GPU test suites and the autograd finite-difference checks on Mesa lavapipe (Vulkan on the CPU) for every PR, so the Vulkan path is checked without a GPU.
scripts/hardware-report.shrunsferrotensor info --check, the kernel benchmarks and the Tensor API benchmarks and writes one JSON report, so every machine is measured the same way. CI runs it in quick mode on software Vulkan.
ChangedLink to this section
ferrotensor-autograd: the backward passes of RMSNorm and RoPE run on the GPU (ComputeEngine::rms_norm_backward,ComputeEngine::rope_theta_inverse) instead of reading the input, weight and gradient back to the host. LoRA training made about 2,000 blocking GPU-to-host reads per step through these two ops.- Breaking,
ferrotensor-trainer:masked_cross_entropycomputes the loss and its gradient on the GPU (ComputeEngine::masked_cross_entropy) and reads back only one loss per position. Before, it read the whole[seq, vocab]logits to the host and uploaded a gradient of the same size, about 50 MB each way per SmolLM2 sequence. It now takes the&ComputeEngineas a fourth argument. ferrotensor-backend:ComputeEnginerecords kernel dispatches and copies into one pending command encoder on theWgpuContextand submits them together (every 128 ops, and when a tensor is read or written) instead of one queue submission per op.WgpuContext::flushsubmits the pending work; call it before submitting your own commands onqueue.WgpuContext::synchronizewaits for the GPU to finish.ferrotensor-backend: reading a tensor no longer blocks in wgpu'sMaintain::Wait, which in wgpu-core 0.19 gives up after 5 s and frees the still-running submission's resources; it polls until the GPU is done.ferrotensor-trainer: the global gradient norm sums squares on the GPU (ComputeEngine::sum_squares_partial) and reads back once per optimizer step instead of once per gradient tensor.
FixedLink to this section
ferrotensor: waiting for the GPU no longer falls back to wgpu's blockingMaintain::Wait, which in wgpu-core 0.19 gives up after 5 s and frees the still-running submission's resources. A batch of more than 5 s of GPU work could crash the driver.- The LoRA walkthrough called
target/release/ferrotensor-cli; the binary has beenferrotensorsince the rename.
0.4.0 - 2026-11-01Link to this section
AddedLink to this section
ferrotensor infolists every GPU adapter wgpu can open (name, vendor, backend, driver, the limits the kernels depend on) and marks the one Ferrotensor uses.--checkruns matmul, softmax and RMSNorm on it against an f64 CPU reference and exits non-zero if one is out of tolerance;--jsonprints the same for bug reports.ferrotensor-backend:adapters::list_adaptersandadapters::self_check, the library side offerrotensor info.- A guide to testing Ferrotensor on other GPUs (
docs/testing-on-your-gpu.md), and a field forferrotensor info --check --jsonoutput in the bug report template.
ChangedLink to this section
ferrotensor: the backward passes ofindex_selectandnn::Embeddingscatter-add their gradients on the GPU instead of reading ids and gradients back to the host. The sums run in a fixed order, so the gradients are deterministic and match the CPU bit for bit.ferrotensor:catconcatenates on the GPU, andcross_entropywith class-id targets runs forward and backward on the GPU. On an Apple M2,cross_entropyover[4096, 32000]went from 749.6 ms to 64.6 ms on the GPU and from 4226.9 ms to 517.2 ms on the CPU, and an MLP training step from 3.69 ms to 2.13 ms on the GPU.cross_entropywith class ids computes the loss per row (log-sum-exp minus the target logit), so its last bits can differ from 0.3.0.- The README feature matrix and the website list what is measured and what is not: the LoRA row now names SmolLM2-135M, the one model measured.
0.3.0 - 2026-10-26Link to this section
AddedLink to this section
ferrotensor:manual_seed(seed)(also in the prelude) seeds the generator behindTensor::randn,rand,uniform, everynnlayer's initialisation andfunctional::dropout, so a program gives the same numbers on every run. Unseeded behaviour is unchanged. Python:ferrotensor.manual_seed(seed).
ChangedLink to this section
ferrotensor: reducing a whole tensor on the GPU (sum()and the other full reductions) uses a two-pass workgroup tree instead of one thread for every element. On an Apple M2,sum()of[4096, 4096]went from 2169 ms to 1.19 ms.ferrotensor:argmaxandargminrun entirely on the GPU, so they no longer split the batched dispatch.argmax_dim(-1)of[1024, 4096]went from 8.40 ms to 0.99 ms on an M2. Ties resolve to the same index as on the CPU.- The website takes its version from the workspace
Cargo.tomland shows the newest CHANGELOG release.
RemovedLink to this section
ferrotensor-graph:FlashAttention::forward_multi_headandFlashAttention::multi_head_forward, deprecated in 0.2.1. Useforward(it already splits heads), projecting the input yourself.
FixedLink to this section
- The Python MLP training test seeds its weight initialisation, so it no longer fails on a rare unlucky start.
0.2.1 - 2026-10-25Link to this section
FixedLink to this section
ferrotensor-graph:FlashAttention::memory_savingsprinted0MBfor short sequences because sizes were divided by 1,000,000 as integers. Sizes now print in binary units and are labelled per head, e.g.8.0x less memory (128.0 KiB vs 1.0 MiB per head for seq=512).ferrotensor:optim::clip_grad_normreads the gradient norm back once instead of once per parameter, so a GPU run syncs once. The returned norm and the clipping are unchanged.
SecurityLink to this section
- Updated tokio from 1.51.0 to 1.54.1 for RUSTSEC-2026-0386 (unsound
AsyncFdconstructors). Onlyferrotensor-monitoruses tokio.
DeprecatedLink to this section
ferrotensor-graph:FlashAttention::forward_multi_head(same asforward) andFlashAttention::multi_head_forward(applies no projections). Both will be removed in 0.3.
0.2.0 - 2026-10-22Link to this section
AddedLink to this section
- Python bindings (
ferrotensor-py, published to PyPI asferrotensor):Device,Tensorwith autograd and operators (@for matmul),nnlayers (Linear, Embedding, LayerNorm, RMSNorm, Dropout, activations, Sequential), losses, SGD and AdamW with LR schedules, and safetensors state dicts. abi3 wheels for CPython 3.10+ on macOS arm64 and Linux x86_64, type stubs, a pytest suite and an MLP example. ferrotensor:Tensor::trilandTensor::triu; the causal mask is built withtriu.ferrotensor: a KV cache fornn::MultiHeadAttention(forward_cachedwithnn::KvCache). Decoding one token at a time matches the full causal forward within 1e-5 on CPU and GPU;char_transformersamples with it.ferrotensor:DataLoader::epoch_prefetchedgathers batches on a background thread, in the same order asepoch.- GPU parity tests for every
nnlayer and for safetensors round trips; a Tensor API benchmark (benchmarks,tensor-apibinary) for CPU and GPU devices. - CI builds and tests the Python wheels on every push and publishes them to PyPI from
v*tags through trusted publishing.
ChangedLink to this section
ferrotensor: GPU ops are batched into one submission and one compute pass per sync point, reuse freed buffers, and read back without wgpu's 1 ms sleep on Metal. On an M2, 100 small element-wise ops go from 10.6 ms to 0.82 ms and an MLP training step (784-256-10, batch 64) from 10.8 ms to 3.98 ms;char_transformertrains 600 steps in 31.9 s (was 105.0 s). Results are bit for bit unchanged.ferrotensor:Embedding::forwardgathers on the GPU without reading the ids back. Ids outside[0, vocab)now give zero rows and no gradient on both devices (before: a panic, or row 0 for negative ids).ferrotensor:cross_entropy,nll_loss,accuracyandone_hottakeimpl Into<Targets>: an f32 tensor of class ids or a slice, array orVecofi64,i32orusize. Negative ids are skipped everywhere, soaccuracynow ignores-100rows like the losses. Existing call forms still compile.ferrotensor:DataLoaderstacks batches into one preallocated buffer instead of cloning each sample (Dataset::with_sample). An epoch of 20k × 784 floats at batch 128 goes from 63,923 allocations (251 MB) and 11.3 ms to 2,043 allocations (63 MB) and 6.4 ms on an M2.- The
ferrotensor-backendexamples are ported to the current API and check their results against a CPU reference. - Docs: install lines, a Python quickstart, batched dispatch in the architecture guide, refreshed timings, and new good first issues.
RemovedLink to this section
ferrotensor: themetalandvulkanCargo features (no code read them) and the unused dependencies on the internal LLM crates, serde, serde_json, memmap2, log, env_logger and criterion.
0.1.0 - 2026-10-21Link to this section
First public version.
AddedLink to this section
ferrotensor: tensor API with a CPU device and a wgpu GPU device, reverse-mode autograd checked against finite differences, differentiablennlayers (Linear, Embedding, LayerNorm, RMSNorm, Dropout, activations), SGD/Adam/AdamW, gradient clipping, LR schedules (cosine with warmup),Dataset/DataLoader, and safetensors save/load of module state dicts.ferrotensor-backend: wgpu compute backend (Metal / Vulkan / DX12) with hand-written WGSL kernels: register-blocked vec4 matmul, Flash Attention v2 forward and backward with causal offset, sliding window, masks and dropout, softmax, RMSNorm, RoPE, int8 dequantization, and a capped buffer pool. Every kernel is tested against a CPU reference.ferrotensor-autograd: GPU autograd tape used by the trainer.ferrotensor-graph: Llama / LFM2-style blocks (attention with RoPE, SwiGLU MLP, RMSNorm, KV cache, LoRA linear layers).ferrotensor-loader: safetensors and tokenizer loading for Llama-style Hugging Face checkpoints.ferrotensor-trainer: LoRA SFT with response-only loss and chat template, next-token pretraining, AdamW, FP16 loss scaling, gradient accumulation, checkpoint save and resume.ferrotensorcommand-line tool (ferrotensor-clicrate):train,evalandgeneratewith temperature, top-k and top-p sampling and a KV cache.ferrotensor-hub(Hugging Face Hub downloads) andferrotensor-monitor(terminal dashboard).- Benchmark suite with recorded results (
benchmarks/RESULTS.md) and an end-to-end LoRA walkthrough on SmolLM2-135M (docs/examples/lora-sft.md). - CI (rustfmt, clippy with
-D warnings, tests on Linux and macOS, rustdoc, MSRV, cargo-deny), release workflow forv*tags, issue and PR templates,SECURITY.md,CODE_OF_CONDUCT.md,CONTRIBUTING.md, architecture and kernel-writing guides.
ChangedLink to this section
- Renamed the project from Rusty to Ferrotensor; crates are now
ferrotensor-*and the CLI binary isferrotensor. - Licensed under MIT OR Apache-2.0 (previously MIT only).