burn

tracel-aiApache-2.0活跃维护

Rust 写的张量库和深度学习框架,兼顾灵活性与效率,支持自动微分、跨平台后端和内核融合,可训练和部署神经网络。

Burn is a next generation tensor library and Deep Learning Framework that doesn't compromise on flexibility, efficiency and portability.

v0.22.1发布于 2026-10-20 17:48 UTC16,266star +16 / 7 天1,124fork同步于 2026-11-10 23:27 UTC

怎么上手

由 README 提炼,执行前请确认
cargo add burn
硬件要求按 README 说明

README 未说明具体显存要求;后端支持 CUDA、ROCm、Metal、Vulkan、WebGPU 与 CPU,另有纯 Rust 的 Flex CPU/no_std 后端(仅可组合 autodiff)。

需要 CUDA支持 ROCm / AMD
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

Rust 写的张量库与深度学习框架,训练和推理共用同一份代码,免去模型导出

Rust 写的张量库和深度学习框架,兼顾灵活性与效率,支持自动微分、跨平台后端和内核融合,可训练和部署神经网络。

核心能力

  • 用统一 API 执行多平台张量运算,训练代码即生产代码
  • JIT 编译张量运算流并自动做内核融合,兼顾动态图灵活性与性能
  • 增量编译让改模型后 release 模式重编译在 5 秒内完成
  • CubeCL 后端覆盖 CUDA、ROCm、Metal、Vulkan、WebGPU 与 CPU
  • burn-store 支持导入 PyTorch 与 Safetensors 权重,burn-onnx 可导入 ONNX 模型

容易踩的坑

需要 Rust 1.95 或更高版本;不同后端需按目标平台单独启用对应 feature;Flex CPU/no_std 后端不支持 fusion 与远程执行装饰器。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.22.1
  1. v0.23.0-pre.2pre-release2026-11-09 · 2026-11-09 20:43 UTC
    查看更新说明

    What's Changed

    • chore(deps): bump actions/checkout from 6 to 7 (#6280) @dependabot[bot]
    • feat(core): stream batches through a split model with a thread per stage (#6277) @ThierryCantin-Demers
      • Migration: Implement LayerParallelism::from_layers to rebuild the model from its LayerSequence.
    • refactor(interpolate)!: narrow resize options and consolidate alignment (#6288) @laggui
      • Migration: Coordinate transforms and cubic coefficients move into InterpolateMode variants. Use HalfPixel for the previous align_corners(false), AlignCorners for true, and update serialized configurations. Grid sampling uses GridSampleMode.
    • ci: save Rust caches only from main and let main runs finish (#6233) @agarg21
    • refactor(linalg): remove QR fusion workaround (#6304) @laggui
    • perf(fusion): resolve a collective's members on every device at once (#6293) @ThierryCantin-Demers
    • ci: run staging pin checks only on staging branch pushes (#6300) @laggui
    • Bump cubecl to bbd78b5 and cubek to 17e417b (#6309) @ThierryCantin-Demers
    • fix(nn): use effective kernels for dilated Same padding (#6286) @onenewcode
    • perf(autodiff): run float collectives on the inner backend's collective (#6274) @ThierryCantin-Demers
    • fix(dataset): return errors for invalid JSON rows (#6284) @onenewcode
    • Remote backend: backend extensions, graph capture and device queries on a worker (#6308) @nathanielsimard
    • fix(extension): clippy allow large enum variant (#6324) @laggui
    • feat(dataset): add ImageFolderDataset::class_name (#6310) @Reacher3745
    • feat!: matmul and attention on CubeK tile routines alone; native Metal (#6291) @louisfd
      • Migration: The experimental tile-kernels-only feature and old matmul/flash-attention entry points are removed; use matmul and attention.
    • perf(flex): use macerator 0.5.2 ops for exp, sigmoid, softmax and rounding (#6313) @antimora
    • refactor(cubecl): tidy the tile attention and fused matmul glue (#6328) @louisfd
    • fix(cubecl): use InputScalar for max_pool3d infinity to fix WGSL compilation (#6298) @vboussot
    • Bump cubecl to fdba0a8 and cubek to 06e1c8e (#6332) @ThierryCantin-Demers
    • Device::mode: compile-only and tune passes apply where the work runs (#6326) @nathanielsimard
    • docs(readme): refresh Burn branding and badge layout (#6344) @laggui
    • feat(remote)!: defer remote and router failures to the tensors they write (#6329) @nathanielsimard
      • Migration: RouterClient::flush returns a Result.
    • fix: gate burn-nn linalg layers; burn-remote client builds warning-free (#6327) @nathanielsimard
      • Migration: Enable linalg for CosineSimilarity, PairwiseDistance, CosineEmbeddingLoss, TripletMarginLoss or orthogonal initialization.
    • feat(train)!: add optimizer-step metrics and grouped learning-rate reporting (#6256) @laggui
      • Migration: Replace metric_train_numeric(LearningRateMetric::new()) with metrics(LearningRateMetric::new()). Custom training strategies emit LearnerEvent::OptimizerStep after each optimizer update.
    • docs(readme): remove redundant title and move badges above description (#6346) @laggui
    • feat(group): generate a random tensor split where it is first needed (#6272) @ThierryCantin-Demers
    • A remote mode closes after the client's queued work, not the server stream's (#6342) @nathanielsimard
    • Device description and measurements: Backend methods in Burn's types, answered by a remote server (#6339) @nathanielsimard
      • Migration: Replace memory_pool_usage/memory_pool_report with measure_memory, memory_capacity with description().max_memory, performance_stats with measure_peaks, and identity with capabilities().properties.identity.
    • fix(cubecl): treat an empty tensor as non-overlapping (#6348) @ThierryCantin-Demers
    • refactor(fusion): resolve a collective's members through SpawnedCall (#6349) @ThierryCantin-Demers
    • perf(flex): vectorize f32 ln, tanh, erf, gelu and gelu_backward (#6341) @antimo
  2. v0.23.0-pre.1pre-release2026-10-29 · 2026-10-29 14:15 UTC
    查看更新说明

    What's Changed

    • chore: bump cubek to 83e2c81, back to git cubecl after the 0.22.0 release (#5988) @louisfd
    • fix(fusion): keep an indexed op's output as its block's reference (#5991) @nathanielsimard - also released in 0.22.1.
    • chore: update cubecl to 9f6bb84 and cubek to 4405c35 (#5993) @louisfd
    • fix(fusion): a transaction returns a failed op's error instead of panicking (#5986) @ThierryCantin-Demers
    • perf(remote): read a transaction's tensors in one request (#5983) @ThierryCantin-Demers
    • feat(cubecl): add a col2im path and autotune for conv_transpose3d (#5793) @vboussot
    • fix(module): clarify derive field handling and suggest #[module(skip)] (#5997) @laggui - also released in 0.22.1.
    • chore: bump cubecl to 98652370 (parallel compilation) and cubek to match (#5996) @nathanielsimard
    • feat(remote): replace a device whose server restarted (#5951) @ThierryCantin-Demers
    • Run wasm static constructors once in web examples (#5998) @haydenflinner
    • fix(fusion): register uploads as materialized instead of queuing an Init (#5970) @saiyambharara
    • fix(derive): preserve generic submodules with primitive type arguments (#6000) @laggui - also released in 0.22.1.
    • fix(train): ignore CER padding by token value (#5945) @Mikyx-1
    • fix(train): validate F-beta and default to F1 (#5965) @Mikyx-1
    • fix(vision): call the CPU connected components directly in the cube backend (#5908) @saiyambharara
    • perf(remote): copy large tensors less when sending (#5989) @ThierryCantin-Demers
    • chore!: remove deprecated ndarray backend (#5999) @laggui
    • feat(remote)!: send messages of any size in 1 MiB frames (#6002) @ThierryCantin-Demers
    • chore: bump cubek to 4871781 and cubecl to f508ec57 (#6008) @louisfd
    • chore: bump cubek to 7a887e8 (#6011) @louisfd
    • fix(cubecl): accumulate half col2im in f32 (#5963) @onenewcode
    • chore: clean up references left after the ndarray removal (#6013) @antimora
    • feat: expose persistence feature for CubeCL backends (#6012) @laggui - also released in 0.22.1.
    • feat(pack): make reader size limits configurable (#6007) @Charles23R
    • fix(vision): restore accelerated connected components (#6003) @laggui
    • chore!: remove deprecated libtorch backend (#6009) @laggui
    • fix(router): forward ctc_loss and ctc_loss_backward as single operations (#6001) @khimaros
    • Chore/cubecl execution (#6015) @nathanielsimard
    • feat(tensor): add 3D pooling (avg_pool3d, max_pool3d) ([#5801](ht
  3. v0.22.1最新正式版2026-10-20 · 2026-10-20 17:48 UTC

    What's Changed

    • fix(fusion): keep an indexed op's output as its block's reference (#5991) @nathanielsimard
    • fix(module): clarify derive field handling and suggest #[module(skip)] (#5997) @laggui
    • fix(derive): preserve generic submodules with primitive type arguments (#6000) @laggui
    • feat: expose persistence feature for CubeCL backends (#6012) @laggui
    • fix(docs): enable branches std workaround and repair optional API links (#6016) @laggui
    • fix(dataset): enable branches std workaround for all sqlite builds (#6092) @getong
    • fix(deps): update rustls to 0.23.46 (#6070) @laggui
    • docs(wasm): explain constructor overhead and explicit startup initialization (#6078) @laggui
    • fix(deps): update zip to 9.0.4 (#6096) @laggui
    • fix(fusion): check binding limit for the first operation (#6053) @abroy77
    • chore(deps): update CubeCL to 0.11.1 and CubeK to 0.3.1 @laggui
  4. v0.22.02026-10-06 · 2026-10-06 19:25 UTC
    查看更新说明

    Summary

    Burn 0.22.0 brings five months of improvements to training and inference, along with our biggest API update yet. Over the last four years, we've kept APIs stable where possible while collecting your feedback on what could be improved. This release brings Burn's API much closer to what we want for 1.0.

    The biggest change is that models and tensors no longer carry a backend generic. Devices select where and how they run, and editing a model requires much less recompilation. The release also adds LoRA and QLoRA support, parameter groups and multiple optimizers, graph capture, and improvements to remote execution. New tensor operations, optimizers, and kernel improvements round out the release.

    For more details, check out the release post on our website.

    No More B: Backend

    Burn is still built around the Backend trait, with composable support for autodiff, kernel fusion, and remote execution. User code now selects these capabilities through Device, while models are plain types:

    use burn::{
        module::Module,
        nn::{Linear, LinearConfig},
        tensor::Device,
    };
    
    #[derive(Module, Debug)]
    pub struct Model {
        linear: Linear,
    }
    
    // Requires the cuda feature. Other options include Device::wgpu(..) and Device::flex().
    let device = Device::cuda(0);
    let model = Model {
        linear: LinearConfig::new(4, 2).init(&device),
    };
    

    More of the infrastructure is now implemented in Rust: Pliron replaces the MLIR-based intermediate representation, and Turso replaces the bundled SQLite dependency. CubeCL also adds LLVM-based CUDA and AMD GPU compilation paths. These changes reduce reliance on bundled C and C++ components and make more of the stack accessible to Rust contributors, though LLVM remains a native dependency for the backends that use it. Clean builds can take longer even as model-edit rebuilds become much faster.

    Changelog

    Breaking changes and migration

    See Migrating to Burn 0.22 in the Burn Book for the complete migration guide, including before-and-after examples for devices, autodiff, modules, training, datasets, tensor operations, and custom integrations.

    Start by removing backend parameters such as Model<B> and Tensor<B, D>, selecting a Device, and enabling autodiff with device.autodiff() before initializing a training model and its inputs. Candle has been removed in this release, and NdArray and LibTorch are being deprecated.

    Records now use burnpack. Legacy MessagePack, binary, and JSON recorder files must be loaded with an older compatible Burn version and exported through burn-store before importing the weights into 0.22. Follow the checkpoint migration instructions; this transfers model parameters, not legacy optimizer or scheduler state.

    What's Changed

    Tensor & Modules

    • [Breaking] Remove Tensor backend generic and add high-level Device struct (#4717) @laggui
    • Refactor tensor kind traits (#4957) @laggui
    • refactor(tensor): add BridgeTensor to bridge high-level tensor API with dispatch (#4958) @laggui
    • Bool tensor API improvements (#4955) @Cielbird
    • fix(nn): conv1d initializer fan out (#4973) @laggui
    • feat(ops): autodiff for rfft/irfft (#4956) @cofinite
    • feat: add Calibration::AbsMean for BitNet b1.58 ternary weight quantization (#4989) @simeon-kepp
    • refactor(tensor)!: replace TensorKind::id() with const KIND and rename TensorKindId -> Kind (#5018) @laggui
    • refactor(tensor): seal TensorKind and Parameter traits and consolidate param impls (#5022) @laggui
    • fix(module): clearer error when generic used in both module and skip fields (#5028) @jaweed3
    • fix(tensor): detect NaN element-wise in contains_nan to avoid f16 false positives (#5027) @zhan-wei-919
    • fix(quantization): fallbac
  5. v0.22.0-pre.4pre-release2026-09-22 · 2026-09-22 18:09 UTC
    查看更新说明

    What's Changed

    • fix(cubecl): restrict GEMV CPU autotune priority to 1D vector workloads (#5423) @Sadik00789
    • fix(store): abort instead of double-dropping when a mapper unwinds (#5488) @antimora
    • Chore/bump cubecl cubek revs (#5497) @nathanielsimard
    • fix(deps): restore windows dependency compatibility in lockfile (#5499) @laggui
    • fix(optim): keep tensor data in optimizer records (#5407) @original4422
    • docs(pack): clarify tensor thread-safety contract (#5500) @laggui
    • chore(deps): update cubecl + cubek to fix fma sigsev (#5501) @ThierryCantin-Demers
    • fix(store): preserve extensionless burnpack paths (#5494) @rioyu123
    • feat(optim): add LAMB optimizer (#5495) @Mikyx-1
    • fix(store): respect PyTorch tensor strides (#5392) @original4422
    • refactor(tensor): move padding operations to backend (#5505) @laggui
    • feat(tensor): support mul indexing updates on NdArray and Flex (#5325) @mattisonchao
    • feat(module): generalize Param with module-owned flags (#5498) @laggui
    • refactor(cubecl): interpolate autotuning with cubek strategies and roofline bounds (#5502) @SamuelBelanger
    • fix(router): support rfft and irfft (#5513) @Mikyx-1
    • fix(module): keep the param mapper across valid() and from_inner (#5509) @nathanielsimard
    • feat(tch): support mul indexing updates (#5511) @mattisonchao
    • Update/cube (#5518) @louisfd
    • feat(cubecl): support mul indexing updates (#5512) @mattisonchao
    • test(quantization): strengthen quantized layout coverage (#5503) @Mikyx-1
    • test(cubecl): rename indexing tests to reflect reference matching (#5519) @laggui
    • fix(train): aggregate Dice statistics across batches (#5515) @Mikyx-1
    • fix(train): return final ROUGE-L value (#5517) @Mikyx-1
    • Refactor/cubecl runtimes (#5528) @nathanielsimard
    • refactor(backend): remove specialized indexing add operations (#5523) @laggui
    • fix(store): exclude adapter-matched tensors from unused (#5536) @apoorvdarshan
    • chore: deprecate burn-tch backend (#5525) @antimora
    • feat(autodiff): implement topk backward (#5531) @Mikyx-1
    • fix(store): return deserialization error instead of panicking in nested Deserializer (#5496) @Sadik00789
    • fix(autodiff): zero-safe prod gradients (#5534) @Mikyx-1
    • feat(tensor): support assign indexing updates across backends (#5532) @mattisonchao
    • perf(cubecl): offer Gemm on CPU for general matmuls (#5538) @ThierryCantin-Demers
    • fix(fusion): a panicking operation must not poison its stream (#5535) @nathanielsimard
    • fix(pack): validate size from aligned data offset (#5530) @Mikyx-1
    • chore(deps): follow cubecl's collapsed memory throughput modes (#5510) @ThierryCantin-Demers
    • fix(no-std): use shared sync primitives across crates (#5543) @laggui
    • fix(store): write safetensors files atomically (#5489) @antimora
    • refactor(dispatch): unify routing and strengthen autodiff contract (#5520) @laggui
    • chore(deps): reduce unnecessary dependencies (#5544) @nathanielsimard
    • fix(autodiff): prod backward broadcasting (#5547) @laggui
    • feat(tensor): add batched SVD decomposition to linalg (#5259) @sehaxe
    • fix(store): reject a loaded tensor whose dtype is the wrong kind (#5490) @antimora
    • fix(dispatch): restore autodiff context promotion (#5551) @laggui
    • Refactor/fusion write scope (#5540) @nathanielsimard
    • fix(ndarray): preserve SIMD unary layout and recip precision (#5553) @laggui
    • feat(module): separate gradient control from module freezing (#5537) @laggui
    • feat(backend)!: support asymmetric padding in conv1d and conv2d (#5521) @laggui
    • fix(tensor): validate matmul batch broadcast in TensorCheck (#5555) @ax1s-x1zz
    • feat(tensor): replace no_grad with explicit autodiff conversions (#5557) @laggui
    • docs(tensor): fix unfold window formula (#5559) @Mikyx-1
    • perf(conv): accumulate direct convolution channels in vector registers on CPU (#5545) @ThierryCantin-Demers
    • chore(deps): update cubecl and cubek for fallible throughput probes (#5561) @ThierryCantin-Demers
    • Chore/update cubecl ru

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Rust 1.95 or later License Current Crates.io Version Test Status Discord Documentation Ask DeepWiki Blaze: macOS CI


    Training and inference usually live in separate worlds. Models are typically trained in Python then exported to an open format like ONNX or optimized for production engines like vLLM, ONNX Runtime, or TensorRT. This export step is often brittle and lossy, ruling out complex architectures and advanced deployment use cases.

    Burn unifies the two. By executing multi-platform tensor operations via a single, unified API, the exact code used for training is the exact code that runs in production. This makes workloads like on-device personalization and federated learning straightforward, while enabling teams to go from prototype to deployment in a single codebase.

    Burn preserves the intuitive ergonomics of PyTorch, with dynamic shapes and graphs, but JIT-compiles streams of tensor operations, performing automatic kernel fusion. You get the flexibility of dynamic graphs without the performance drop.

    Rust for Research?

    Rust used to be a tough sell for research: long compilation times disrupted the fast edit-compile-run loop that draws researchers to Python. Burn changes this paradigm. Designed around incremental compilation, modifying model code recompiles in under 5 seconds, even in release mode. This delivers a Python-like feedback loop with the speed and safety of Rust.

    Ecosystem

    Burn is the core of a growing, fully open-source Rust AI ecosystem. You are not adopting a single library, you are joining a stack that spans GPU compute, model interop and domain toolkits, with plenty of room to help shape what comes next.

    CategoryProjectDescription
    ComputeCubeCLGPU compute language and compiler behind Burn's accelerated backends. Write kernels once in Rust, run on CUDA, ROCm, Metal, Vulkan and WebGPU. Usable standalone.
    Model interopburn-onnxImport ONNX models into Burn as native Rust code
    burn-storeSave, load and import model weights, including PyTorch and Safetensors
    Domainsburn-visionComputer vision operators and building blocks
    burn-rlReinforcement learning building blocks
    burn-datasetDataset loading, transforms and ready-made sources
    ModelsmodelsCurated pre-trained models and examples built with Burn
    Toolingburn-benchBenchmark and compare backends, tracking performance over time

    Burn's CubeCL backends (CUDA, ROCm, Metal, Vulkan, WebGPU, CPU) compose with autodiff, fusion and remote-execution decorators, while the pure-Rust Flex CPU/no_std backend composes with autodiff only. See Supported Backends below for the full matrix.

    Every project here is open-source and actively developed. Want to help build the Rust AI ecosystem? The good first issues are a great place to start, and the Contributing guide will get you set up.

    These crates are not maintained by Tracel, but they are part of the same Rust AI story. Anything that helps you load data, build environments, or ship models belongs here. Built something that fits? Open a PR to add it!

    CategoryCrateDescription
    Data & loadingpolarsFast DataFrames for tabular data
    arrow-rsApache Arrow columnar memory format
    imageImage decoding, encoding and processing
    hf-hubDownload models and datasets from the Hugging Face Hub
    Tokenization & NLPtokenizersFast, production-ready tokenizers
    rust-bertReady-to-use NLP pipelines and transformer models
    Numerical & linear algebrandarrayN-dimensional arrays
    nalgebraLinear algebra
    Classical MLlinfaClassical ML toolkit, in the spirit of scikit-learn
    smartcoreClassical ML algorithms, no BLAS/LAPACK required
    Inference & runtimescandleMinimalist ML framework with a focus on LLM inference
    mistral.rsFast, multimodal LLM inference engine
    ortONNX Runtime bindings for hardware-accelerated inference
    tractPure-Rust inference for ONNX and NNEF models
    wonnx100% Rust, WebGPU-accelerated ONNX runtime for native and the web
    LLM apps & RAGrigBuild modular LLM applications and agents
    langchain-rustLangChain-style chain orchestration
    Embeddings & vector searchfastembedGenerate text embeddings and rerank locally
    qdrantVector search engine, written in Rust
    lancedbEmbedded, developer-friendly vector database
    Computer visionkornia-rsLow-level 3D computer vision library
    Simulation & environmentsrapierPhysics engine for robotics and RL environments
    VisualizationrerunMultimodal data and CV/robotics visualization
    plottersPlotting and charting

    Backend

    Burn strives to be as fast as possible on as many hardwares as possible, with robust implementations. We believe this flexibility is crucial for modern needs where you may train your models in the cloud, then deploy on customer hardwares, which vary from user to user.

    Supported Backends

    Most backends support all operating systems, so we don't mention them in the tables below.

    GPU Backends:

    CUDAROCmMetalVulkanWebGPU
    Nvidia☑️--☑️☑️
    AMD-☑️-☑️☑️
    Apple--☑️-☑️
    Intel---☑️☑️
    Qualcom---☑️☑️
    Wasm----☑️

    CPU Backends:

    Cpu (CubeCL)Flex
    X86☑️☑️
    Arm☑️☑️
    Wasm-☑️
    no-std-☑️

    The two native CPU backends are independent. Cpu (cpu feature) is the CubeCL runtime for the CPU: it JIT-compiles the same kernels as the GPU backends through LLVM and supports fusion. Flex (flex feature) is a pure-Rust eager backend with no native dependencies that also runs on Wasm and no_std.

    Migration: LibTorch was deprecated in 0.22.0 and has been removed from main. For GPU acceleration, use a CubeCL backend (CUDA, ROCm, Metal, Vulkan, WebGPU). For CPU execution, use the CubeCL CPU backend or burn-flex.

    Burn's backend architecture lets you swap backends while keeping the same model code. You can enable multiple backends in the same application and choose the device for your tensors and modules at runtime through Device. This gives you the freedom to use different backends side by side and select the hardware best suited to each workload.

    Autodifferentiation and automatic kernel fusion integrate with the same tensor and module APIs, so models benefit from these capabilities on supported backends without changing their implementation.

    In application code, autodiff is runtime context carried by tensors. Devices provide the default context for newly created tensors, and each tensor can later enable or remove autodiff independently. Enabling autodiff permits graph recording; it does not by itself make a tensor retain gradients.

    Internally, Burn implements this by decorating a concrete backend, so autodiff cannot execute by itself. Enable it on a device before creating tensors or initializing a model. With the autodiff and wgpu features enabled:

    use burn::tensor::{Device, Distribution, Tensor};
    
    fn main() {
        let device = Device::wgpu(Default::default()).autodiff();
    
        let x: Tensor<2> = Tensor::random([32, 32], Distribution::Default, &device);
        let y: Tensor<2> = Tensor::random([32, 32], Distribution::Default, &device).require_grad();
    
        let tmp = x.clone() + y.clone();
        let tmp = tmp.matmul(x);
        let tmp = tmp.exp();
    
        let grads = tmp.backward();
        let y_grad = y.grad(&grads).unwrap();
        println!("{y_grad}");
    }
    

    backward() checks graph participation at runtime. Enable autodiff before the forward pass and call require_grad() on source leaves whose gradients you need. is_autodiff(), is_tracked(), and is_require_grad() inspect autodiff association, graph participation, and gradient retention respectively. See the autodiff guide.

    See the Autodiff Backend README for more details.

    This backend decorator enhances a backend with kernel fusion, provided that the inner backend supports it. Note that you can compose this backend with other backend decorators such as Autodiff. All first-party accelerated backends (like WGPU and CUDA) use Fusion by default (burn/fusion feature flag), so you typically don't need to apply it manually.

    #[cfg(not(feature = "fusion"))]
    pub type Cube = burn_cubecl::CubeBackend;
    
    #[cfg(feature = "fusion")]
    pub type Cube = burn_fusion::Fusion<burn_cubecl::CubeBackend>;
    

    Device::autodiff().gradient_checkpointing() enables the balanced gradient-checkpointing strategy, which trades recomputation for reduced activation storage during training.

    See the Fusion Backend README for more details.

    Remote execution has a client and a server. The server's devices select the compute backend; clients use a remote Device with the same tensor API. Iroh, the default transport, reaches a server across any network, authenticated and encrypted; see the server example and the distributed computing guide. On a trusted network, WebSocket is the simplest setup: enable remote-server, remote-websocket, and cuda on the server, and remote-websocket plus autodiff on the client:

    use burn::remote::RemoteHost;
    use burn::server::{RemoteServer, ServeError, WebSocketTransport};
    use burn::tensor::{Device, Distribution, Tensor};
    
    fn main_server() -> Result<(), ServeError> {
        RemoteServer::new([Device::cuda(0)]).serve(WebSocketTransport::new(3000))
    }
    
    fn main_client() -> Result<(), burn::remote::ConnectError> {
        let host = RemoteHost::websocket("ws://localhost:3000");
        let device = Device::remote_options(&host).init()?.autodiff();
        let tensor_gpu = Tensor::<2>::random([3, 3], Distribution::Default, &device);
        Ok(())
    }
    

    Training & Inference

    The whole deep learning workflow is made easy with Burn, as you can monitor your training progress with an ergonomic dashboard, and run inference everywhere from embedded devices to large GPU clusters.

    Burn was built from the ground up with training and inference in mind. It's also worth noting how Burn, in comparison to frameworks like PyTorch, simplifies the transition from training to deployment, eliminating the need for code changes.

    Click on the following sections to expand 👇

    As you can see in the previous video (click on the picture!), a new terminal UI dashboard based on the Ratatui crate allows users to follow their training with ease without having to connect to any external application.

    You can visualize your training and validation metrics updating in real-time and analyze the lifelong progression or recent history of any registered metrics using only the arrow keys. Break from the training loop without crashing, allowing potential checkpoints to be fully written or important pieces of code to complete without interruption 🛡

    Burn supports importing ONNX (Open Neural Network Exchange) models through the burn-onnx crate, allowing you to easily port models from TensorFlow or PyTorch to Burn. The ONNX model is converted into Rust code that uses Burn's native APIs, enabling the imported model to run on any Burn backend (CPU, GPU, WebAssembly) and benefit from all of Burn's optimizations like automatic kernel fusion.

    Our ONNX support is further described in this section of the Burn Book 🔥.

    Note: This crate is in active development and currently supports a limited set of ONNX operators.

    You can load weights from PyTorch or Safetensors formats directly into your Burn-defined models. This makes it easy to reuse existing models while benefiting from Burn's performance and deployment features.

    Learn more in the Saving & Loading Models section of the Burn Book.

    Several of our backends can run in WebAssembly environments: Flex for CPU execution, and WGPU for GPU acceleration via WebGPU. This means that you can run inference directly within a browser. We provide several examples of this:

    • MNIST where you can draw digits and a small convnet tries to find which one it is! 2️⃣ 7️⃣ 😰
    • Image Classification where you can upload images and classify them! 🌄

    Burn's core components support no_std. This means it can run in bare metal environment such as embedded devices without an operating system.

    As of now, only the Flex backend can be used in a no_std environment.

    Benchmarks

    To evaluate performance across different backends and track improvements over time, we provide a dedicated benchmarking suite.

    Run and compare benchmarks using burn-bench.

    Getting Started

    Just heard of Burn? You are at the right place! Just continue reading this section and we hope you can get on board really quickly.

    To begin working effectively with Burn, it is crucial to understand its key components and philosophy. This is why we highly recommend new users to read the first sections of The Burn Book 🔥. It provides detailed examples and explanations covering every facet of the framework, including building blocks like tensors, modules, and optimizers, all the way to advanced usage, like coding your own GPU kernels.

    The project is constantly evolving, and we try as much as possible to keep the book up to date with new additions. However, we might miss some details sometimes, so if you see something weird, let us know! We also gladly accept Pull Requests 😄

    Let's start with a code snippet that shows how intuitive the framework is to use! In the following, we declare a neural network module with some parameters along with its forward pass.

    use burn::nn;
    use burn::module::Module;
    use burn::tensor::Tensor;
    
    #[derive(Module, Debug)]
    pub struct PositionWiseFeedForward {
        linear_inner: nn::Linear,
        linear_outer: nn::Linear,
        dropout: nn::Dropout,
        gelu: nn::Gelu,
    }
    
    impl PositionWiseFeedForward {
        pub fn forward<const D: usize>(&self, input: Tensor<D>) -> Tensor<D> {
            let x = self.linear_inner.forward(input);
            let x = self.gelu.forward(x);
            let x = self.dropout.forward(x);
    
            self.linear_outer.forward(x)
        }
    }
    

    We have a somewhat large amount of examples in the repository that shows how to use the framework in different scenarios.

    Following the book:

    • Basic Workflow : Creates a custom CNN Module to train on the MNIST dataset and use for inference.
    • Custom Training Loop : Implements a basic training loop instead of using the Learner.
    • Custom WGPU Kernel : Learn how to create your own custom operation with the WGPU backend.

    Additional examples:

    • Custom CSV Dataset : Implements a dataset to parse CSV data for a regression task.
    • Regression : Trains a simple MLP on the California Housing dataset to predict the median house value for a district.
    • Custom Image Dataset : Trains a simple CNN on custom image dataset following a simple folder structure.
    • Custom Renderer : Implements a custom renderer to display the Learner progress.
    • Image Classification Web : Image classification web browser demo using Burn, WGPU and WebAssembly.
    • MNIST Inference on Web : An interactive MNIST inference demo in the browser.
    • MNIST Training : Demonstrates how to train a custom Module (MLP) with the Learner configured to log metrics and keep training checkpoints.
    • PyTorch Import Inference : Imports a PyTorch model pre-trained on MNIST to perform inference on a sample image with Burn.
    • Text Classification : Trains a text classification transformer model on the AG News or DbPedia dataset. The trained model can then be used to classify a text sample.
    • Text Generation : Trains a text generation transformer model on the DbPedia dataset.
    • Wasserstein GAN MNIST : Trains a WGAN model to generate new handwritten digits based on MNIST.

    For more practical insights, you can clone the repository and run any of them directly on your computer!

    We keep an updated and curated list of models and examples built with Burn, see the tracel-ai/models repository for more details.

    Don't see the model you want? Don't hesitate to open an issue, and we may prioritize it. Built a model using Burn and want to share it? You can also open a Pull Request and add your model under the community section!

    Deep Learning is a special form of software where you need very high level abstractions as well as extremely fast execution time. Rust is the perfect candidate for that use case since it provides zero-cost abstractions to easily create neural network modules, and fine-grained control over memory to optimize every detail. To this day, the mainstream solution has been to offer APIs in Python but rely on bindings to low-level languages such as C/C++. This reduces portability, increases complexity and creates friction between researchers and engineers. Rust's approach to abstractions is versatile enough to tackle this two-language dichotomy, and Cargo makes it easy to build, test and deploy from any environment, which is usually a pain in Python.

    Rust's AI ecosystem is young, but it is real and growing quickly. Foundational pieces are already here: Burn and CubeCL for training and compute, candle for inference, Hugging Face's tokenizers and safetensors, and polars and ndarray for data. Betting on Rust today means betting on a stack that is growing, and one where contributors still shape the direction. The pieces that don't exist yet are opportunities rather than dead-ends (see Contributing).

    Rust is also what makes one-stack-everywhere possible: a single self-contained binary with no Python runtime to ship, running from servers down to no_std embedded targets.

    Deprecation NoteSince 0.14.0, the internal structure for tensor data has changed. The previous Data struct was deprecated and officially removed since 0.17.0 in favor of the new TensorData struct, which allows for more flexibility by storing the underlying data as bytes and keeping the data type as a field. If you are using Data in your code, make sure to switch to TensorData.

    Burn 0.22 uses burnpack for native records and cannot directly read legacy Recorder formats such as .mpk, .bin, or JSON. Load the checkpoint in a compatible older Burn project, export the model weights through burn-store, and import them into your 0.22 model. See Migrating checkpoints for an example and the distinction between transferring weights and resuming training state.

    For records saved before 0.14.0, an earlier migration step may also be needed: use Burn 0.14, 0.15, or 0.16 with the record-backward-compat feature to load and re-save the record with the newer tensor-data representation. For legacy binary records, first use the version that wrote them to export a self-describing format such as NamedMpkFileRecorder. This historical migration does not convert records to the format required by 0.22; follow the checkpoint migration guide afterward.

    Community

    If you are excited about the project, don't hesitate to join our Discord! We try to be as welcoming as possible to everybody from any background. You can ask your questions and share what you built with the community!

    Contributing

    Before contributing, please read the Contributing Guidelines and our Code of Conduct. The Contributor Book covers architecture, environment setup, and guides for common tasks.

    Status

    Burn is currently in active development, and there will be breaking changes. While any resulting issues are likely to be easy to fix, there are no guarantees at this stage.

    License

    Burn is distributed under the terms of either the MIT License or the Apache License, Version 2.0. Unless otherwise noted, this applies to all contents of this repository, including source code, examples, documentation, and code snippets in the Burn Book and Contributor Book. See the licenses for details.

    Third-party materials and externally downloaded datasets or models remain subject to their respective licenses.

    Opening a pull request is assumed to signal agreement with these licensing terms.