Install
FrankenTorch builds on stable Rust; it needs no Python, no libtorch and no C or C++ compiler. For the whole stack, take every crate from the repository so they all come from one commit, and pin a revision with rev = "…" once you have one that works for you.
[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" }If you only need tensors and autograd, the crates.io releases are enough. Don't mix the two: a session from crates.io and a module from the repository are different types to the compiler.
[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" }A tensor and its gradient
TensorContext gives tensors operators, so the code reads like PyTorch. Every tensor belongs to one session, which holds the values and the autograd tape.
let 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]
The session API underneath is explicit: each op is a method that takes node ids and returns a Result. Everything else on this page uses it.
Train a model
Modules come from ft_nn, optimizers and schedulers from ft_optim, and batches from ft_data. tensor_backward returns a report, and the optimizer's step takes it.
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
The tape lives in the session, so it grows with every op. truncate_autograd_graph cuts it back to the length it had before the loop, once a step's gradients have been applied.
Save and load weights
A module's state_dict is a map from names to tensors. ft_serialize writes it as safetensors, the format PyTorch's safetensors package and the Hugging Face Hub use. Module parameters keep PyTorch's names, weight and bias.
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
Read the backward report
tensor_backward returns every step it took, the rule it applied at each, the order, and the queue counts. session.evidence() keeps a ledger of every op the session dispatched and every backward pass it ran.
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
Strict or hardened
A session runs in one of two modes. Both compute the same numbers. Strict refuses when an op has no kernel on its normal path; hardened falls back to a composite or another backend and records fallback=true in the ledger. Hardened also allows a backward pass to start inside another, two levels deep. Start with strict.
use ft_api::FrankenTorchSession;use ft_core::ExecutionMode; let mut session = FrankenTorchSession::new(ExecutionMode::Strict);An in-place write to a tensor that autograd saved is refused in both modes:
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}");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
Coming from PyTorch
The usual calls, side by side. Names on the right are methods on FrankenTorchSession unless they belong to a module or an optimizer.
torch.tensor(data, requires_grad=True)session.tensor_variable(data, shape, true)?torch.zeros(2, 3)session.tensor_zeros(vec![2, 3], false)?torch.randn(2, 3)session.tensor_randn(vec![2, 3], false)?torch.manual_seed(7)session.manual_seed(7)a @ bsession.tensor_matmul(a, b)?x.relu()session.tensor_relu(x)?x.float()session.tensor_float(x)?x.tolist()session.tensor_values(x)?loss.backward()let report = session.tensor_backward(loss)?;w.gradsession.tensor_gradient(&report, w)with torch.no_grad():session.with_no_grad(|s| { … })nn.Linear(2, 8)Linear::new(&mut session, 2, 8, true)?model(x)model.forward(&mut session, x)?optimizer.step()optimizer.step(&mut session, &report)?Limits
- 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.
Something missing that you need? The repository is the place to look first: the conformance tests say what matches PyTorch today.