PyTorch's API, rebuilt in Rust0.1, in development
Gradients that show their work.
FrankenTorch is a clean-room Rust reimplementation of PyTorch: tensors, autograd, nn, optim and data loading, with no Python and no C++ underneath. Every backward pass runs in an order fixed by the graph, reports each step and the rule it applied, and is checked against PyTorch itself.
- 3,202 session methods
- 122 nn modules
- 7,009 tests
Train a network in this tab
Runs in your browserData
Optimizer
- Loss
- 0.0437
- Accuracy
- 100%
- Weights fingerprint
- 572314f7aeddaad7
Recorded when this site was built, by the same engine. Train again with the same settings and the fingerprint comes back identical.
bce_with_logits_loss: 300 full-batch steps on 200 points, a frame every 15. The engine is the FrankenTorch crates compiled to WebAssembly (4.0 MB) and run in a Web Worker. The fingerprint is a hash of every weight's bits.- 3,202session methods1,120 of them tensor ops, plus functional, linalg, FFT and special functions
- 122nn modulesFrom Linear and Conv3d to LSTM, Transformer and MultiheadAttention
- 15 + 15optimizers and schedulersAdam, AdamW, SGD, LBFGS, Muon and Adafactor; StepLR to OneCycleLR
- 7,009testsPlus 56 fuzz targets and a live PyTorch oracle
- 11 of 14crates forbid unsafeThe other three: SIMD kernels, Metal, and a CUDA probe
01The API
Your PyTorch, in Rust.
Modules, losses, optimizers and schedulers keep PyTorch's names and argument order, so a training loop moves across line by line. The differences are the ones Rust asks for: an explicit session, a ? on every call that can fail, and a graph you trim between steps.
Side by side
The same program, line for line.
Four PyTorch programs and the FrankenTorch code that does the same work. Point at or tap a line, or arrow through one with the keyboard, and its counterpart lights up.
Find each line's twin
Worked exampleimport torchfrom torch import nnfrom torch.utils.data import DataLoader l1 = nn.Linear(2, 8)l2 = nn.Linear(8, 1)params = list(l1.parameters())params += list(l2.parameters())optimizer = torch.optim.Adam(params, lr=0.01)scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 40) for epoch in range(100): loader = DataLoader(dataset, batch_size=16, shuffle=True) for x, y in loader: h = l1(x) h = torch.relu(h) pred = l2(h) loss = nn.functional.mse_loss(pred, y) optimizer.zero_grad() loss.backward() optimizer.step() scheduler.step()let mut session = FrankenTorchSession::new(ExecutionMode::Strict);let l1 = Linear::new(&mut session, 2, 8, true)?;let l2 = Linear::new(&mut session, 8, 1, true)?;let mut params = l1.parameters();params.extend(l2.parameters());let mut optimizer = Adam::new(params, 0.01);let mut scheduler = StepLR::new(&optimizer, 40);let keep = session.autograd_graph_node_count(); for _epoch in 0..100 { let config = DataLoaderConfig::new(16).with_shuffle(true); let mut loader = DataLoader::new(&dataset, config); while let Some(batch) = loader.next_batch(&mut session)? { let x = batch.input().ok_or("no input")?; let y = batch.target().ok_or("no target")?; let h = l1.forward(&mut session, x)?; let h = session.tensor_relu(h)?; let pred = l2.forward(&mut session, h)?; let loss = session.mse_loss(pred, y)?; optimizer.zero_grad(&mut session)?; let report = session.tensor_backward(loss)?; optimizer.step(&mut session, &report)?; session.truncate_autograd_graph(keep); } scheduler.step(&mut optimizer, None);}first batch loss 3.311389, last 0.027743
import torch x = torch.tensor([[1.0, 2.0], [-1.0, 0.5]])y = torch.tensor([[1.0], [-1.0]])w1 = torch.tensor([[0.5, -0.25], [0.25, 0.75]], requires_grad=True)b1 = torch.tensor([[0.1, -0.1]], requires_grad=True)w2 = torch.tensor([[0.6], [-0.4]], requires_grad=True) hidden = (x @ w1 + b1).relu()diff = hidden @ w2 - yloss = (diff * diff).mean()loss.backward() grad_w1 = w1.gradlet ctx = TensorContext::strict();let x = ctx.tensor(vec![1.0, 2.0, -1.0, 0.5], vec![2, 2], false)?;let y = ctx.tensor(vec![1.0, -1.0], vec![2, 1], false)?;let w1 = ctx.tensor(vec![0.5, -0.25, 0.25, 0.75], vec![2, 2], true)?;let b1 = ctx.tensor(vec![0.1, -0.1], vec![1, 2], true)?;let w2 = ctx.tensor(vec![0.6, -0.4], vec![2, 1], true)?; let hidden = (x.matmul(&w1) + &b1).relu();let diff = &hidden.matmul(&w2) - &y;let loss = (&diff * &diff).mean();loss.backward(); let grad_w1 = w1.grad().ok_or("w1 has no gradient")?;loss 0.63205 grad_w1 [-0.4799999999999999, 0.6360000000000001, -0.9599999999999999, 0.482]
import torchfrom torch.autograd.functional import hessian b = torch.tensor([1.0, 2.0]) def out(a): return torch.linalg.solve(a, b).sum() a = torch.tensor([[4.0, 1.0], [2.0, 3.0]])H = hessian(out, a) # 2 × 2 × 2 × 2let a = session.tensor_variable(vec![4.0, 1.0, 2.0, 3.0], vec![2, 2], true)?;let b = session.tensor_variable(vec![1.0, 2.0], vec![2], false)?;let x = session.tensor_linalg_solve(a, b)?;let out = session.tensor_sum(x)?;let hessian = session.tensor_functional_hessian(out, a)?; // 4 × 4, row-majorhessian [0.005999999999999997, 0.015999999999999997, 0.007999999999999998, -0.011999999999999999, 0.016, -0.023999999999999997, 0.058, -0.012000000000000014, 0.007999999999999998, 0.05800000000000002, -0.005999999999999999, -0.006000000000000004, -0.011999999999999999, -0.012000000000000007, -0.006000000000000008, 0.14400000000000004]
from torch import nnfrom safetensors.torch import save_file, load_file model = nn.Linear(4, 2)save_file(model.state_dict(), path) restored = nn.Linear(4, 2)weights = load_file(path)restored.load_state_dict(weights, strict=True)let model = Linear::new(&mut session, 4, 2, true)?;let state = model.state_dict(&session)?;ft_serialize::save_safetensors(&state, &path, None)?; let restored = Linear::new(&mut session, 4, 2, true)?;let weights = ft_serialize::load_safetensors(&path)?;restored.load_state_dict(&mut session, &weights, true)?;restored 2 tensors from frankentorch-site-example/model.safetensors
session owns every tensor and the autograd tape, so the loop trims the tape with truncate_autograd_graph once a step is done.Coverage
Look up the op you need.
Every public method on the session and every module, optimizer and scheduler, read from the source when this page was built. PyTorch names work: conv2d finds tensor_conv2d, functional_conv2d and Conv2d.
Type a PyTorch name
Runs in your browser8e33801d. A name here means the method exists; the tests say how closely it matches PyTorch.Inventory
What's in the box.
The parts of PyTorch most programs touch, by family. Names are PyTorch's.
Layers121 modules
LinearConv1dConv2dConv3dConvTranspose2dLSTMGRUTransformerMultiheadAttentionEmbeddingEmbeddingBagBilinearUpsamplePixelShuffleFoldUnfoldAnd the activations, poolings, paddings, dropouts and containers around them.
Normalizationbatch, layer, group, RMS
BatchNorm1dBatchNorm2dBatchNorm3dLayerNormGroupNormInstanceNorm2dRMSNormLocalResponseNormLosses23 losses
AdaptiveLogSoftmaxWithLossBCELossBCEWithLogitsLossCosineEmbeddingLossCrossEntropyLossCTCLossFocalLossGaussianNLLLossHingeEmbeddingLossHuberLossKLDivLossL1LossMarginRankingLossMSELossAlso MultiLabelMarginLoss, MultiLabelSoftMarginLoss, MultiMarginLoss, NLLLoss, PoissonNLLLoss, SmoothL1Loss, SoftMarginLoss, TripletMarginLoss, TripletMarginWithDistanceLoss.
Optimizers15
AdadeltaAdafactorAdagradAdamAdamaxAdamWASGDLBFGSMuonNAdamRAdamRMSpropRpropSGDSparseAdamSchedulers15
ChainedSchedulerConstantLRCosineAnnealingLRCosineAnnealingWarmRestartsCyclicLRExponentialLRLambdaLRLinearLRMultiplicativeLRMultiStepLROneCycleLRPolynomialLRReduceLROnPlateauSequentialLRStepLRDataloading and sampling
DataLoaderSubsetTensorDatasetTransformDatasetBatchSamplerDistributedSamplerRandomSamplerSequentialSamplerSubsetRandomSamplerWeightedRandomSamplerAutogradfirst and higher order
backwardjacobianhessianjvpvjphvpno_gradcustom functionsCustom functions can define their own double backward.
Numerics11 dtypes
F64F32F16BF16QInt8QUInt8I64I32BoolComplex64Complex128Sparse COO and CSR; 85 FFT, 89 linalg and 87 special-function methods; autocast and GradScaler.
Filesweights in and out
safetensorsstate dictscheckpointsONNX exportReads and writes safetensors. ONNX export covers linear layers and their activations. There is no loader for pickled
.ptfiles.
02Deterministic autograd
Same graph, same gradients.
The backward pass takes ready nodes from a queue ordered by node id, so its order depends on the graph and nothing else. Every call returns a report of the steps it took and the rule each one applied. The core sum and mean reduce over a fixed pairwise tree, so they give the same bits on one thread or many.
The tape
Step through a backward pass.
Press Step to walk the backward pass in the order the engine ran it. Each step shows the node, the rule the report names for it, and the gradient that came out.
Step through the backward pass
Runs in your browserStep 0 of 12
Press Step to start at the loss.
The report names a rule for every step.
Execution order
Queue
Fingerprint of all parameter gradients
df229ff09ab32d2c
The session's evidence ledger
Floating point
Addition has an order.
In floating point, (a + b) + c and a + (b + c) can differ in the last bits. A parallel sum that adds partial results as threads finish can return different bits from run to run. Adding them in a fixed tree, by position, returns the same bits every time.
Sum the same numbers 200 ways
Worked exampleEight workers each sum a slice of 4,096 float32 values. Then the eight partial sums are added together, either in the order the workers finish or in a fixed tree by slice.
One bar per worker. After a run, each shows where that worker finished in the last of the 200.
As workers finish
– different results
In a fixed tree
– different result
Math.fround, which rounds like a float32 add. FrankenTorch's core sum and mean use the fixed tree. A few float32 variance kernels are matched across thread counts to a stated tolerance instead of bit for bit, and their tests say so.In your code
The report is a return value.
tensor_backward returns the steps, the order and the queue counts. session.evidence() lists every dispatch, every backward pass and every change of mode. This is the whole program and everything it printed.
let mut s = FrankenTorchSession::new(ExecutionMode::Strict);let w = s.tensor_variable(vec![0.5, -1.5], vec![2], true)?;let x = s.tensor_variable(vec![2.0, 4.0], vec![2], false)?;let y = s.tensor_mul(w, x)?;let loss = s.tensor_sum(y)?;let report = s.tensor_backward(loss)?; for step in &report.steps { println!("node {:>2} {}", step.node.0, step.rule);}println!("order {:?}", report.telemetry.execution_order);for entry in s.evidence() { println!("{:?}: {}", entry.kind, entry.summary);}node 3 d(sum(a*b))/da=b*grad (single-grad fused) node 0 leaf order [TensorNodeId(3), TensorNodeId(1), TensorNodeId(0)] Policy: mode initialized to Strict Dispatch: tensor_op=Mul lhs=0 rhs=1 out=2 mode=Strict kernel=autograd_cpu::mul_tensor_contiguous_f64 key=AutogradCPU backend=CPU keyset=0x0000000000000032 fallback=false Dispatch: tensor_reduction_op=Sum input=2 out=3 mode=Strict kernel=autograd_cpu::sum_tensor_contiguous_f64 key=AutogradCPU backend=CPU keyset=0x0000000000000032 fallback=false Backward: tensor_root=3 backward_steps=2 queue_pushes=3 queue_pops=3 max_queue_len=2 reentrant_guard=false
03Parity
Checked against PyTorch itself.
A fast path that matches the slow path proves only that the two agree. FrankenTorch's conformance harness starts a real PyTorch, hands it the same case, and compares the answers. Each bug below was found that way. In two of them the fast and slow paths matched each other bit for bit, and both were wrong.
Casebook
Six bugs PyTorch caught.
Each row uses the inputs from the commit that fixed it; all six fixes landed in August 2026. The left column is what FrankenTorch used to return, the middle is PyTorch, and the right is the engine as it is now.
Compare the old shortcut, PyTorch, and the fixed engine
Runs in your browser(−2)3
(−2)2
(−8)1
(2)3
(3)2
- NaN
- NaN
- NaN
- 7.999999999999998
- 9.000000000000002
- −8
- 4
- −8
- 8
- 9
- −8
- 4
- −8
- 8
- 9
remainder
Computed a − floor(a / b) · b. The quotient can round up to a whole number, and the sign of a zero is lost.
24.352941176470587 % 0.5294117647058824
−7.5 % 2.5
−3 % 3
- 0.0
- 0.0
- 0.0
- 0.5294117647058808
- −0.0
- −0.0
- 0.5294117647058808
- −0.0
- −0.0
addcdiv
Computed input + value · (t1 / t2). PyTorch computes input + (value · t1) / t2, which rounds differently.
400 random draws, value 2.382
312 of 400 match
400 of 400 match (value · t1) / t2
400 of 400 match
max_pool1d with NaN
Kept the larger value with if v > m, starting from −∞. NaN > m is false, so a NaN never won.
[1, 1, NaN, 4, 5, NaN, NaN, NaN, −0.0, 0.0]
kernel 2, stride 2
- 1
- 4
- 5
- −∞
- −0.0
- 1
- NaN
- NaN
- NaN
- −0.0
- 1
- NaN
- NaN
- NaN
- −0.0
d/dx sum(x · −0.0)
x = [1, 2]
- 0.0
- 0.0
- −0.0
- −0.0
- −0.0
- −0.0
cdist, a point to itself
Always used ‖a‖² + ‖b‖² − 2a·b, which cancels badly when two points coincide.
cdist(x, x) diagonal
8 × 16 float32
5.96e−8 recorded before the fix
0.0 at 25 rows or fewer
0.0 largest of 8
These results were computed by the engine when the site was built. Run it again and it recomputes them in this tab, with new random draws for addcdiv and cdist.
The oracle
Self-consistency is not parity.
That sentence is from the commit that fixed pow. The conformance crate turns it into a procedure.
- 1
A case
An op, its inputs, dtype and shape. Many come from fuzzers: the remainder and cdist fixes began as inputs a fuzzer minimized.
- 2
FrankenTorch runs it
Through the same session API your code calls.
- 3
PyTorch runs it
The harness starts
python3with PyTorch as a child process, with a timeout, and sends it the same case. - 4
The answers are compared
Bit for bit where PyTorch is exact, or to a stated tolerance. A mismatch fails the test and names the case.
- 53,381 lines in the conformance crate
- 550 tests in it
- 56 fuzz targets
04Safety
A corrupted gradient stops the run.
Autograd saves some inputs for the backward pass. Change one in place after it was saved and the gradient comes out wrong, with no error. FrankenTorch counts versions the way PyTorch does and refuses that backward pass with an error that names the tensor.
Version counters
Catch an in-place write.
c = a · b saves b, because the gradient for a is b. Then b is doubled in place. Write before the backward pass and the engine refuses. Write after it and the gradient is the one you expect.
Write to a saved tensor, before and after the backward pass
Runs in your browserlet a = s.tensor_variable(vec![2.0, 3.0], vec![2], true)?;let b = s.tensor_variable(vec![4.0, 5.0], vec![2], false)?;let c = s.tensor_mul(a, b)?; // saves b for the backward passlet loss = s.tensor_sum(c)?; let two = s.tensor_variable(vec![2.0, 2.0], vec![2], false)?;s.tensor_mul_(b, two)?; // b changes after it was saved let err = s.tensor_backward(loss).unwrap_err();println!("{err}");Write, then backward
Refused
one of the tensors needed for gradient computation has been modified by an in-place operation: tensor node TensorNodeId(1) was at version 0 when the forward ran and is at version 1 now
Backward, then write
Gradient for a: [4, 5]
That is b as it was when c was computed. The write afterwards is safe: b is now [8, 10].
Two modes
Strict and hardened differ in three places.
Both modes compute the same numbers. They differ only in what happens when a call can't take its normal path. Strict refuses. Hardened carries on where it is safe to, and writes down that it did.
fallback=true into the evidence ledger.let strict = FrankenTorchSession::new(ExecutionMode::Strict);let hardened = FrankenTorchSession::new(ExecutionMode::Hardened);Memory safety
Unsafe code lives in three crates.
11 of 14 crates declare #![forbid(unsafe_code)], which the compiler enforces and no module can override. The CPU kernels deny it crate-wide and allow it in 15 marked places for SIMD. The Metal crate and the CUDA probe talk to GPU drivers.
ft-api
The session: every public op
ft-autograd
The tape and the backward engine
ft-core
Tensor metadata, storage, dtype and shape rules
ft-dispatch
Operator schemas and kernel routing
ft-kernel-cpu
CPU kernels, with SIMD
ft-nn
Modules and losses
ft-optim
Optimizers and schedulers
ft-data
Datasets, samplers, DataLoader
ft-serialize
State dicts, safetensors, checkpoints
ft-runtime
Evidence ledgers
ft-device
Device ids and guards
ft-conformance
Tests against a live PyTorch
ft-kernel-metal
Apple GPU kernels, used directly
ft-kernel-cuda
A CUDA driver probe
05Performance
Measured against PyTorch, losses included.
Speed claims in this repository follow four written rules: name the worker, name the harness, name the estimator, and replicate before quoting, then quote the conservative bound. Some ops beat PyTorch at the same thread count. Some lose. Both kinds are on the board.
The board
Faster here, slower there.
Each bar is FrankenTorch's speed against PyTorch's for one op. Where a row was replicated, the bar is the conservative bound across runs, which is lower than the median. Rows from a single run say so.
FrankenTorch against PyTorch, forward and backward
From the recordavg_pool1d
Median 2.70–2.85× across two certified runs. Opened against a scorecard row that read 24.92× slower. 25ee311d
≥ 2.5× faster8 and 8 threads · certifiedconv2d, large shape
Median 1.46–1.51×, three runs of three certified. 0ce06381
≥ 1.40× faster8 and 8 threads · certifiedconv3d
1.45× with FrankenTorch on 16 threads. One run each; a candidate, not a standing.
1.25× faster8 and 8 threads · one runprelu
Faster in 6 runs of 6, medians 1.048–1.180×. The story is below.
≥ 1.006× faster64 and 8 threads · certifiedmax_pool1d
At 8 threads the two are level. With FrankenTorch on 16 threads, at least 1.07× faster.
even8 and 8 threads · one rungroup_norm, float32
At least 1.23× faster with FrankenTorch on 16 threads.
1.13× slower8 and 8 threads · one runSVD, 512 × 512
1.77–1.84× slower on a generic matrix.
1.8× slower8 and 8 threads · one runconv2d, training route
11.5 ms against 5.3 ms for a masked training step. 31dd7cb9
2.19× slower8 and 8 threads · certified
Protocol
How a number is earned.
Six checks stand behind every ratio on the board. They come from the head-to-head harness and the quoting rules beside it.
- 1
Time the op, not the setup.
Forward and backward only, with inputs built outside the timed region on both sides.
- 2
Sample side by side.
PyTorch runs as a co-process that returns one timed sample per request, so each of its samples is taken next to FrankenTorch's for the same lane.
- 3
Measure the noise first.
Each lane runs the same library against itself. The spread of that A/A run is the floor a real difference has to clear; the target is 2%.
- 4
Agree on the answer.
Both sides must produce the same gradient checksum, to 1e-6 relative.
- 5
Watch the machine.
Load is sampled around each run, and a run where it drifts by more than 1.25× is flagged.
- 6
Name the binary.
The SHA-256 of the executable that ran is printed beside every ratio.
The harness reports these checks; it does not stop a run that fails one, so the quoting rules decide what counts. Both rule sets are in the repository: the harness is crates/ft-api/examples/gauntlet_lane_sweep_h2h.rs and the rules are at the top of docs/NEGATIVE_EVIDENCE.md.
Replication
A headline that got smaller.
prelu was, for a while, the only quotable row. Each replication lowered its floor, and the document that quotes it kept the history.
- 1.213×one run, min estimator
- 1.07×two runs, median
- 1.006×six runs, lowest bound
“This paragraph has itself been wrong twice, which is the rules working. It first read “at least 1.213x” (one run, min estimator), then “at least 1.07x” (two runs, median) … Each correction was downward and each came from one more replication, exactly as rule 4 predicts.”
06Get started
Put it in your Cargo.toml.
Tensors and autograd are on crates.io. Modules, optimizers and data loading come from the repository until they are published. It builds on stable Rust. Read the limits below before you plan around it: this is version 0.1.
Install
Two ways in.
For the whole stack, take every crate from the repository, so they all come from one commit. For tensors and autograd alone, the crates.io releases are enough.
[dependencies]ft-api = { package = "frankentorch-api", git = "https://github.com/Dicklesworthstone/frankentorch" }ft-core = { package = "frankentorch-core", git = "https://github.com/Dicklesworthstone/frankentorch" }ft-nn = { git = "https://github.com/Dicklesworthstone/frankentorch" }ft-optim = { git = "https://github.com/Dicklesworthstone/frankentorch" }ft-data = { git = "https://github.com/Dicklesworthstone/frankentorch" }ft-serialize = { git = "https://github.com/Dicklesworthstone/frankentorch" }[dependencies]ft-api = { package = "frankentorch-api", version = "0.1" }ft-core = { package = "frankentorch-core", version = "0.1" }ft-autograd = { package = "frankentorch-autograd", version = "0.1" }Limits
What it doesn't do yet.
The goal is PyTorch's full observable behaviour. Today these gaps are real, and you should know them before you start.
CPU only.
Sessions compute on the CPU. A separate Metal crate runs some kernels on Apple GPUs for projects that call it directly; CUDA support is a driver probe.
Float64 by default.
tensor_variablemakes f64 tensors. Usetensor_variable_f32, or convert withtensor_float,tensor_halfortensor_bfloat16.No
.ptfiles.There is no pickle loader. Save weights from PyTorch as safetensors and load those.
No distributed training, no compiler.
There is no counterpart to
torch.distributedortorch.compile.DistributedSamplerexists for sharding data.DataLoader runs in your thread.
There is no
num_workers.ONNX export is narrow.
It writes linear layers and sequential stacks of them with ReLU, sigmoid, tanh, GELU or SiLU between. Convolutions and attention don't export yet.
0.1 means 0.1.
Names can still change between commits. Pin a revision.
In use
Who runs it.
Projects that ship with FrankenTorch inside them today. All of them are open source.
frankensearch
Hybrid search. Its BERT cross-encoder reranker and all-MiniLM-L6-v2 embedder run on FrankenTorch 0.1 from crates.io: opt-in in the library, on by default in the fsfs command-line tool.
cass
Searches coding-agent session history through frankensearch's native path. The fastembed and ONNX Runtime stack it used before has been removed.
franken_whisper
Speech recognition: Whisper's encoder and decoder on FrankenTorch's CPU kernels, with the Metal crate on macOS.
franken_ocr
OCR on FrankenTorch kernels: int8 dynamic linear layers, GEMM, conv2d, attention, RMS and layer norm.
frankenlife
Typed tensor storage, CPU reference inference and a Metal compute gateway.
Read the code, then try it.