Zero Labs
Industry News / AI

Will Rust Replace Python in AI? The Real Battle Is Happening Underneath

Source · Towards AI By Safal Narshing Shrestha

From the publisher’s feed, collected in the ZeroLabs newsroom.

Rust isn’t coming for your Jupyter notebook. It’s coming for everything around it.If you write AI code, you write Python. Training loops, fine-tuning scripts, eval harnesses, the FastAPI wrapper around your model: it’s Python almost all the way down. Or at least it looks that way.Open up the tools you pip install every day and a different picture shows up. The tokenizer behind most Hugging Face models is written in Rust. So is safetensors, the format most open model weights now ship in. So is Polars, the DataFrame library that keeps eating into pandas' benchmarks. Even Python's own tooling is shifting: uv and ruff, two of the fastest-growing Python dev tools, are Rust binaries.That raises a fair question. Is Rust going to replace Python in AI? And if it’s already sitting under Python, could it push further down and take over from C and C++ inside the frameworks themselves?The short answer is no, and also yes, depending on which layer of the stack you’re looking at. To see why, you have to stop thinking of an “AI app” as a model and start thinking of it as a system.1. Python was never doing the heavy liftingThe usual complaint goes like this: Python is slow, so AI written in Python must be slow. It’s half right, and the wrong half matters.Here’s a tiny PyTorch model:import torchimport torch.nn as nnmodel = nn.Sequential( nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, 10),)x = torch.randn(1, 128)output = model(x)Python describes the layers and kicks off the forward pass. That’s about all it does. The actual matrix multiplications get dispatched to native code: ATen and C++ on the framework side, then libraries like oneDNN or MKL on CPU, or cuBLAS, cuDNN and hand-written CUDA kernels on an NVIDIA GPU.Python is the steering wheel, not the engine. That split is exactly why it won machine learning. Researchers get a readable, interactive language for describing ideas, and the expensive math still runs at native speed.So if Python already sits on top of fast native code, why would anyone bother with Rust? Because in a real product, the model is only one piece of the software.2. An AI product is more than a modelPicture an AI assistant that can read your files, search the web, run shell commands and talk to other apps. The model decides what to do: which tool to call, with which arguments. Something else has to actually do it.That something is the agent runtime, sometimes called the harness. It’s responsible for:Reading and writing filesMaking network requests and calling external APIsSpawning and supervising subprocessesHolding conversation state and memoryHandling errors, retries and timeoutsRunning many tasks concurrentlyEnforcing permissions and sandboxingThe user talks to the runtime, the runtime talks to the model, and only the runtime touches files, the network and the shell.If the model is the brain, the runtime is the nervous system. And nothing says the two have to be written in the same language. The model can live on a GPU cluster behind an API while the runtime runs as a Rust binary on your laptop.One caveat worth stating plainly: rewriting the runtime in Rust won’t make your agent feel faster if 95% of each turn is spent waiting on a remote model. Rust earns its keep when the runtime itself is busy: lots of concurrent tool calls, heavy local data processing, long-running processes where memory leaks and crashes actually hurt.3. Why Rust keeps showing up in AI infrastructureThe most telling data point isn’t a benchmark. It’s who is rewriting what. In mid-2025, OpenAI rewrote its Codex CLI from TypeScript and Node.js to Rust. The reasons they gave are a good summary of Rust’s pitch: no Node.js install to fight with, native bindings for Linux sandboxing via Landlock, no garbage collector eating memory, and an existing Rust implementation of MCP. Hugging Face’s Text Generation Inference took a similar split years earlier: a Rust web server handles HTTP, batching and streaming, while Python shards run the model.Here’s what’s actually pulling teams toward Rust.Performance where it countsRust compiles to native code with no garbage collector, and in suitable workloads it lands in the same range as C++. That pays off in the CPU-bound work around a model: tokenization, serialization, parsing, data transforms, request routing. It’s no coincidence that Hugging Face’s tokenizers and the Polars DataFrame engine are both Rust under a Python API.But don’t oversell it. A Rust service and a tidy Python service that both spend most of their time waiting on the same remote API will feel about the same.Memory safetyRust’s ownership and borrow checker reject whole categories of bugs at compile time: use-after-free, double-free, data races. For infrastructure, that matters more than it does in a notebook, because one memory bug can take down a service rather than one prediction.The best large-scale evidence comes from outside AI. Google reported that memory-safety bugs fell from 76% of Android vulnerabilities in 2019 to 24% in 2024, mostly by writing new code in memory-safe languages like Rust rather than rewriting old C++. Rust won’t stop logic bugs or prompt injection, but it removes a class of problems you’d otherwise be chasing.Concurrency you can trustAn agent might fetch five documents, call three APIs and stream a model response at the same time. Async Rust, usually on Tokio, handles that kind of fan-out well, and the compiler refuses to build code that shares mutable state unsafely. You find the race condition at cargo build, not at 3 a.m. in production.Single-binary deploymentcargo build --release gives you one executable. No interpreter, no virtualenv, no "works on my machine" dependency tree. For CLIs, local assistants, desktop apps and self-hosted tools, that's a real advantage. It's a big part of why uv and ruff spread so fast.The fine print: model weights, GPU drivers, CUDA runtimes and other native libraries still have to get onto the machine somehow.AI coding assistants are getting good at RustThis one is newer. Rust’s compiler gives unusually precise errors about types, lifetimes and borrowing. Coding agents can read those errors, fix the code and try again, so the compiler effectively acts as a strict reviewer in the loop. It doesn’t remove the need to understand Rust, but it flattens the learning curve and makes it cheaper to write serious systems code.4. The real shift: from AI tools to AI systemsSwapping a Python script for a faster binary is the least interesting part of this story. The bigger change is that AI products have turned into real software systems.Take an AI coding assistant. The model reads the request and writes code. Everything else is plain old systems engineering: watching the file system, running commands in a sandbox, keeping context under a token budget, streaming output, talking to language servers, deciding what the model is and isn’t allowed to touch.Scale that up and you get multiple agents running in parallel, recovering from failed tool calls, managing subprocess lifecycles and enforcing security boundaries. That’s the kind of software Rust was built for, and it’s why so many agent harnesses, inference routers and local AI apps are being written in it.Once you see it that way, the question changes. It’s no longer “which language should define the neural network?” It’s “which language should run the machinery around it?” And that naturally leads to the next question: if Rust is taking over the machinery around the model, could it take over the machinery underneath it too?5. Could Rust replace C and C++ inside the frameworks?First, a point that gets lost in language wars: a neural network is math, not code. This layer, for example:y = ReLU(Wx + b)is a linear transform followed by an activation. You can implement it in Python, C++, Rust, Julia or Fortran. What decides performance isn’t the language you wrote it in. It’s how the implementation lays out memory, multiplies matrices, computes gradients and uses the hardware.A simplified ML stack has roughly five layers, from the Python you write down to the silicon (diagram below). Python model code already sits on top of heavily optimized native layers. So the real question is whether Rust can take over some of those middle layers.The exact split varies by framework and operation, but the middle three layers are where Rust projects like Burn, Candle and CubeCL are already working.Technically, yes. Rust can call C and CUDA libraries through FFI, target GPUs through backends like wgpu and CubeCL, implement tensor ops and autodiff, and train models. There’s no mathematical reason it can’t.The hard part isn’t can Rust do it. It’s whether the Rust ecosystem can make training and serving big modern models as fast and as convenient as what people already use.6. Rust ML is already here, at every layerRust isn’t limited to apps that call an LLM API. There are serious projects at almost every level of the stack:The bridge that lets you write a Rust extension and import it from Python.These projects work at very different depths. Rig helps you build around a model. Burn and Candle go into the model’s execution. That distinction matters: building an agent in Rust means HTTP clients, JSON and async tasks. Training a model from scratch in Rust means matrix multiplication, autodiff and GPU kernels. Those are completely different difficulty levels.7. So why hasn’t Rust taken over already?One word: ecosystem.GPU work is brutally specializedTraining a modern model takes far more than a correct matmul. You need fused attention kernels in the style of FlashAttention, mixed-precision training (FP16, BF16, FP8), activation checkpointing, careful GPU memory management and fast multi-GPU communication through NCCL. Each of those took the PyTorch and CUDA world years to get right. A framework that is mathematically correct but leaves half the GPU idle won’t replace anything.PyTorch has a massive head startPyTorch brings years of kernels, optimizers and tooling, plus the Hugging Face Hub, torch.compile, DeepSpeed, FSDP and a huge stack of reference implementations. When a new paper drops, the code is almost always PyTorch. A Rust framework isn't competing with Python's syntax. It's competing with all of that.Research rewards iteration speedML research moves fast. Someone publishes a new attention variant on Tuesday, and people want to try it on Wednesday. Python’s REPL, notebooks and loose typing make that easy. Rust’s compile-time checks are great for production code, but they add friction when you’re hacking on an idea that may be gone by Friday.For a researcher, how fast you can try an idea usually matters more than how fast the language runs. That’s why Python isn’t going anywhere in the lab.8. What about training from scratch in Rust?You can do it today. A training loop is the same seven steps in any language:Load the datasetInitialize the parametersRun the forward passCompute the lossBackpropagate to get gradientsUpdate the parametersRepeat across batches and epochsNone of that needs Python. For a small network or a CPU-sized experiment, Burn or a hand-rolled implementation works fine, and writing backprop yourself in Rust is a great way to really understand it.Scale up to a multi-billion-parameter LLM across a GPU cluster and things change. Now you need efficient kernels for every op, sharded optimizer state, mixed precision, gradient accumulation, fault-tolerant checkpointing and fast collective communication. Rust frameworks support some of this, and the list grows every release. But you’d need to benchmark carefully against your actual workload before betting a training run on it.That’s why the most common pattern today is a split:Train in PyTorch → Export (safetensors / ONNX) → Serve from RustYou keep the research ecosystem where it’s strongest and use Rust where its strengths actually show up: latency, memory footprint and deployment.9. Rust doesn’t have to “win” to matterRust doesn’t need to replace Python to become a major AI language. If it ends up as the default choice for agent runtimes, local AI apps, inference servers and the performance-critical pieces of data pipelines, that’s already a huge share of the AI software being written.Python can stay on top in research while Rust takes over production infrastructure. Those two outcomes don’t conflict. They’re already happening at the same time.10. What should AI developers actually learn?Don’t drop Python and start rewriting everything in Rust. Pick the layer you want to work on, then pick the language.Try it yourselfThe best way to settle the Rust-vs-Python argument for your own work is to measure it. Take a small pretrained model, say a sentence-embedding model exported to ONNX, and build two versions of the same service: one in Python with FastAPI, one in Rust with Axum and ort.Time each stage separately: request parsing, tokenization and preprocessing, model execution, and post-processing. You’ll probably find that Rust makes a big difference in some stages and almost none in others, since model execution runs on the same native runtime either way.That result teaches more than any “Rust is X times faster” headline.11. I ran it: PyTorch vs Candle on a laptop GPUTo put real numbers behind all this, I ran the same LLM through PyTorch and through Candle, Hugging Face’s Rust framework, on my own laptop. Both sides used Qwen2.5–1.5B-Instruct in BF16 with the same weights, tokenizer, chat template and 20 prompts. Each prompt generated exactly 256 tokens with greedy decoding, so both did identical work.The hardware was an ASUS ROG Zephyrus G16 (2024) with an RTX 4070 Laptop GPU (8 GB), an Intel Core Ultra 9 185H, Arch Linux, NVIDIA driver 615.78 and CUDA 13.4. The versions were PyTorch 2.11.0 (cu128) and Candle 0.11. One caveat: the laptop held the GPU at a 55 W power limit for the whole test (its maximum is 115 W). That applied equally to both sides, but it means absolute speeds are lower than this GPU can reach.The rest of the numbers, also medians of three runs:Check it out on github:https://github.com/SafalNarshing/rust-vs-python/Inside the model: a tieDecode speed differed by under 1%, and time to first token by 0.2 ms. That’s the expected result. Both frameworks hand the heavy math to NVIDIA’s own GPU libraries, and at batch size 1, generating text one token at a time is limited by how fast the GPU can read the model’s weights from memory. At about 3.1 GB of weights and 61 tokens/s, both are reading roughly 190 GB/s, around three quarters of this GPU’s peak memory bandwidth. Neither language has much room to pull ahead.Around the model: Rust winsCandle had the model loaded and ready in 0.73 s versus 2.96 s for PyTorch, about 4× faster. Most of that gap is Python importing torch and transformers before it touches the GPU. Candle also used about 180 MB less VRAM and about 260 MB less system RAM. For a CLI tool, a serverless function or anything that starts often, that startup gap matters more than a fraction of a token per second.ConclusionRust’s rise in AI isn’t really a “which language is faster” story. It’s a sign that AI software has grown up. Once a model becomes one component in a system that reads files, runs commands, juggles concurrent tasks and has to stay up, you need reliable runtimes, safe tool execution and simple deployment. That’s Rust’s home turf.Replacing Python and C++ across the whole ML stack is a different challenge. It takes mature frameworks, broad hardware support, tuned kernels and an ecosystem researchers trust with a six-figure training run. Burn, Candle and friends are moving fast, but they’re not there yet for frontier-scale training.So the honest answer to “Will Rust replace Python in AI?” is: it doesn’t have to. The future probably isn’t one language. It belongs to developers who know which language belongs at which layer, and can move comfortably between them.Further reading and referencesCase studies and evidenceAnother Rust Rewrite: OpenAI’s Codex CLI Goes Native (InfoQ, June 2025): why OpenAI moved its coding agent from Node.js to RustOpenAI rewrites AI coding tool in Rust (DevClass): sandboxing with Landlock and Seatbelt, MCP in Rustcodex on GitHub: the codex-rs source, a real-world Rust agent harness you can readEliminating Memory Safety Vulnerabilities at the Source (Google Security Blog, Sept 2024): the Android 76% → 24% dataText Generation Inference architecture (Hugging Face): Rust router plus Python model shardsBurn 0.20 released (Phoronix, Jan 2026): CubeK and multi-vendor GPU kernels in RustFrameworks and librariesPyTorch documentationBurn and The Burn BookCubeCL: writing GPU kernels in RustCandle: Hugging Face’s minimalist ML framework for Rustmistral.rs: LLM inference engine in Rustort: ONNX Runtime for RustRig: LLM application framework for RustHugging Face tokenizers and safetensorsPolars: DataFrames in RustPyO3 and maturin: building Python extensions in RustTokio: async runtime for RustLearning resourcesThe Rust Programming Language (“the Book”)Async Rust bookAre We Learning Yet?: a running catalogue of Rust ML cratesuv and ruff: Rust tools that already changed everyday Python workWill Rust Replace Python in AI? The Real Battle Is Happening Underneath was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.