FrankenTorch

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 browser

Data

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.

A 2 → 16 → 16 → 1 tanh network trained with 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.

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 example
PyTorch
import 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()
FrankenTorch · examples/train.rs
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);}
It printed
first batch loss 3.311389, last 0.027743
The Rust on the right is compiled and run each time this site is built; under it is what it printed. 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 browser

    3,202 session methods, 122 modules, 15 optimizers and 15 schedulers, read from the source at commit 8e33801d. 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

      LinearConv1dConv2dConv3dConvTranspose2dLSTMGRUTransformerMultiheadAttentionEmbeddingEmbeddingBagBilinearUpsamplePixelShuffleFoldUnfold

      And the activations, poolings, paddings, dropouts and containers around them.

    • Normalizationbatch, layer, group, RMS

      BatchNorm1dBatchNorm2dBatchNorm3dLayerNormGroupNormInstanceNorm2dRMSNormLocalResponseNorm

    • Losses23 losses

      AdaptiveLogSoftmaxWithLossBCELossBCEWithLogitsLossCosineEmbeddingLossCrossEntropyLossCTCLossFocalLossGaussianNLLLossHingeEmbeddingLossHuberLossKLDivLossL1LossMarginRankingLossMSELoss

      Also MultiLabelMarginLoss, MultiLabelSoftMarginLoss, MultiMarginLoss, NLLLoss, PoissonNLLLoss, SmoothL1Loss, SoftMarginLoss, TripletMarginLoss, TripletMarginWithDistanceLoss.

    • Optimizers15

      AdadeltaAdafactorAdagradAdamAdamaxAdamWASGDLBFGSMuonNAdamRAdamRMSpropRpropSGDSparseAdam

    • Schedulers15

      ChainedSchedulerConstantLRCosineAnnealingLRCosineAnnealingWarmRestartsCyclicLRExponentialLRLambdaLRLinearLRMultiplicativeLRMultiStepLROneCycleLRPolynomialLRReduceLROnPlateauSequentialLRStepLR

    • Dataloading and sampling

      DataLoaderSubsetTensorDatasetTransformDatasetBatchSamplerDistributedSamplerRandomSamplerSequentialSamplerSubsetRandomSamplerWeightedRandomSampler

    • Autogradfirst and higher order

      backwardjacobianhessianjvpvjphvpno_gradcustom functions

      Custom functions can define their own double backward.

    • Numerics11 dtypes

      F64F32F16BF16QInt8QUInt8I64I32BoolComplex64Complex128

      Sparse COO and CSR; 85 FFT, 89 linalg and 87 special-function methods; autocast and GradScaler.

    • Filesweights in and out

      safetensorsstate dictscheckpointsONNX export

      Reads and writes safetensors. ONNX export covers linear layers and their activations. There is no loader for pickled .pt files.

    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 browser
    x0W11b12W23b24y5x·W16+ b17relu8·W29+ b210ŷ − y11square12loss13x0W11b12W23b24y5x·W16+ b17relu8·W29+ b210ŷ − y11square12loss13

    Step 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
        One training example through a 2 → 3 → 1 ReLU network with a squared-error loss, computed by the engine in this tab. Switch to hardened mode: the gradients and their fingerprint don't move, because hardened mode only changes what happens when a call would fail.

        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 example

        Eight 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

            Computed in this tab with 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.

            examples/evidence.rs
            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);}
            It printed
            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
            CaseInputThe old shortcutPyTorch 2.12FrankenTorch now

            pow, tensor exponent

            Computed x^e as exp(e · ln x). ln of a negative number is NaN.

            bd2696de
            Input

            (−2)3
            (−2)2
            (−8)1
            (2)3
            (3)2

            The old shortcut
            1. NaN
            2. NaN
            3. NaN
            4. 7.999999999999998
            5. 9.000000000000002
            PyTorch 2.12
            1. −8
            2. 4
            3. −8
            4. 8
            5. 9
            FrankenTorch now
            1. −8
            2. 4
            3. −8
            4. 8
            5. 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.

            bd02f26b
            Input

            24.352941176470587 % 0.5294117647058824
            −7.5 % 2.5
            −3 % 3

            The old shortcut
            1. 0.0
            2. 0.0
            3. 0.0
            PyTorch 2.12
            1. 0.5294117647058808
            2. −0.0
            3. −0.0
            FrankenTorch now
            1. 0.5294117647058808
            2. −0.0
            3. −0.0

            addcdiv

            Computed input + value · (t1 / t2). PyTorch computes input + (value · t1) / t2, which rounds differently.

            72dec3b7
            Input

            400 random draws, value 2.382

            The old shortcut

            312 of 400 match

            PyTorch 2.12

            400 of 400 match (value · t1) / t2

            FrankenTorch now

            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.

            c891ba2e
            Input

            [1, 1, NaN, 4, 5, NaN, NaN, NaN, −0.0, 0.0]
            kernel 2, stride 2

            The old shortcut
            1. 1
            2. 4
            3. 5
            4. −∞
            5. −0.0
            PyTorch 2.12
            1. 1
            2. NaN
            3. NaN
            4. NaN
            5. −0.0
            FrankenTorch now
            1. 1
            2. NaN
            3. NaN
            4. NaN
            5. −0.0

            Sign of a zero gradient

            Started each gradient slot from 0.0 + g, and 0.0 + (−0.0) is +0.0.

            2e0bceac
            Input

            d/dx sum(x · −0.0)
            x = [1, 2]

            The old shortcut
            1. 0.0
            2. 0.0
            PyTorch 2.12
            1. −0.0
            2. −0.0
            FrankenTorch now
            1. −0.0
            2. −0.0

            cdist, a point to itself

            Always used ‖a‖² + ‖b‖² − 2a·b, which cancels badly when two points coincide.

            7eea3021
            Input

            cdist(x, x) diagonal
            8 × 16 float32

            The old shortcut

            5.96e−8 recorded before the fix

            PyTorch 2.12

            0.0 at 25 rows or fewer

            FrankenTorch now

            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.

            PyTorch values and the cdist “before” value are copied from each fix's commit message, measured with PyTorch 2.12.0 or 2.12.1 on CPU. The shortcut columns for pow, remainder, max_pool1d and the zero gradient are recomputed in this tab with the old formula.

            The oracle

            Self-consistency is not parity.

            That sentence is from the commit that fixed pow. The conformance crate turns it into a procedure.

            Read the conformance crate
            1. 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. 2

              FrankenTorch runs it

              Through the same session API your code calls.

            3. 3

              PyTorch runs it

              The harness starts python3 with PyTorch as a child process, with a timeout, and sends it the same case.

            4. 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 browser
            examples/inplace.rs
            let 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].

            PyTorch refuses the same program with “one of the variables needed for gradient computation has been modified by an inplace operation”. Each tensor carries a version number that every in-place op increments; the backward pass compares it with the version it saved.

            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.

            WhenStrictHardened
            An op has no kernel on this pathStrictRefuses with an error.HardenedFalls back to a composite or another backend, and writes fallback=true into the evidence ledger.
            A backward pass starts inside anotherStrictRefused: reentrant depth 0.HardenedAllowed two levels deep, and flagged in the telemetry.
            A checkpoint is decodedStrictThe parser rejects unknown fields.HardenedFields are checked against an allowlist before parsing. Unknown fields are rejected here too.
            Pick one per session
            let strict = FrankenTorchSession::new(ExecutionMode::Strict);let hardened = FrankenTorchSession::new(ExecutionMode::Hardened);

            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 record
            • avg_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 · certified
            • conv2d, large shape

              Median 1.46–1.51×, three runs of three certified. 0ce06381

              ≥ 1.40× faster8 and 8 threads · certified
            • conv3d

              1.45× with FrankenTorch on 16 threads. One run each; a candidate, not a standing.

              1.25× faster8 and 8 threads · one run
            • prelu

              Faster in 6 runs of 6, medians 1.048–1.180×. The story is below.

              ≥ 1.006× faster64 and 8 threads · certified
            • max_pool1d

              At 8 threads the two are level. With FrankenTorch on 16 threads, at least 1.07× faster.

              even8 and 8 threads · one run
            • group_norm, float32

              At least 1.23× faster with FrankenTorch on 16 threads.

              1.13× slower8 and 8 threads · one run
            • SVD, 512 × 512

              1.77–1.84× slower on a generic matrix.

              1.8× slower8 and 8 threads · one run
            • conv2d, training route

              11.5 ms against 5.3 ms for a masked training step. 31dd7cb9

              2.19× slower8 and 8 threads · certified
            One machine: an AMD Threadripper PRO 5975WX (32 cores) on the powersave governor, PyTorch 2.12 on CPU with 8 threads in every row. Thread counts are FrankenTorch's, then PyTorch's; FrankenTorch's count is set by an environment variable, not chosen by default. “Certified” means the run passed its A/A controls and drift gate; rows that didn't are labelled as single runs.

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

              Time the op, not the setup.

              Forward and backward only, with inputs built outside the timed region on both sides.

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

              Agree on the answer.

              Both sides must produce the same gradient checksum, to 1e-6 relative.

            5. 5

              Watch the machine.

              Load is sampled around each run, and a run where it drifts by more than 1.25× is flagged.

            6. 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. 1.213×one run, min estimator
            2. 1.07×two runs, median
            3. 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.

            Cargo.toml · the whole stack
            [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" }
            Cargo.toml · tensors and autograd from crates.io
            [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_variable makes f64 tensors. Use tensor_variable_f32, or convert with tensor_float, tensor_half or tensor_bfloat16.

            • No .pt files.

              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.distributed or torch.compile. DistributedSampler exists 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.