Bunsen
by ZSpaceLabs
bunsen aims to be a "batteries included" complementary community standard library for extending
the burn tensor library.
Book
Read the bunsen book
Organization
Burn Extensions
bunsen::burner- this is a library ofburn::module::Modulelifecycle components that extend the current functionality of burn.bunsen::burner::module::reflectionhas powerful tools for dynamicburn::module::Modulereflection.bunsen::burner::optimhas parameter-group optimizer extensions.bunsen::burner::tensorhasTensorextension traits (swap/release,select_dim, elementwise range masks,boolcounting) andTensorDataindex views.
contracts- this is a library of runtime tensor-shape contracts.
Component Libraries
bunsen::blocks- this is a library ofburn::module::Modulecomponents. This includes simple inner layers, recurrent utility blocks, and entire model families.bunsen::ops- this is a libraryburn::tensor::Tensoroperations.bunsen::kits- this is a library of full models and simulation kits.bimm- image models:resnet,swinngpts- partial implementation ofnanochatsims-conwaygame of life,lbm2D fluid flow.speech- completesilero_vad, partialwhisper
App and Testing Support Libs
bunsen::errors- this is a library of error types and tooling.bunsen::support- this is a library of support functions for bunsen, including testing tooling which may be useful for clients.bunsen::zspace- this is a library of z-space / index utilities.
API Examples
A "good parts" survey of some of bunsen's features. See the
docs and the
book for the full API.
Builtin Kits
bunsen::kits collects complete, runnable domain implementations over the crate's blocks and ops: whole models with
their pretrained loaders, and simulations. Every kit's module docs carry a worked example, generic over the backend;
the stubs below show the default way in, and link to the example that uses each kit. Pretrained weights come through
one mechanism everywhere: a PretrainedCache, the kit's default_{kit}_factory(), and a name (openai/base,
torchvision/resnet18, hf:org/repo for a Hugging Face repo, bundled:... for weights built into the binary).
Speech
Whisper
docs ·
example: whisper-cli
OpenAI's Whisper, with an index of pretrained checkpoints and a stream driver that turns audio pushed in chunks into timed transcript segments.
use ;
let cache = new?;
let bundle = default_whisper_factory?.?;
let driver: = new.init_from_bundle?;
let mut ctx = driver.new_context?;
for block in samples.chunks
Silero VAD
docs ·
example: whisper-cli's real-time presets
Voice-activity detection: the probability that each chunk of audio holds speech, with the weights built into the
binary under the silero-weights feature.
use ;
let vad = default_silero_factory?.?.handle;
let vad = vad.expect_branch;
let mut ctx = new.init;
for chunk in samples.chunks_exact
Vision (bimm)
ResNet
docs ·
examples: resnet_finetune,
resnet_tiny
The ResNet family, with torchvision's and timm's pretrained rows (torchvision/resnet50, timm/resnet18_a1) and the
model surgery a fine-tune wants.
use ;
let loaded = default_resnet_factory?.?;
let model: = unwrap_or_clone
.with_classes
.with_stochastic_drop_block;
Simulations (sims)
Conway's Game of Life
use ;
let mut sim: = ConwayLife2DConfig .init;
sim.fuzz;
sim.step;
Lattice Boltzmann Fluid Flow
A D2Q9 lattice Boltzmann fluid. The population lives on a [H, W, 3, 3] grid, one 3x3 velocity stencil per cell, and
each step streams it, relaxes it toward thermal equilibrium (BGK, with a mass-conserving correction), and bounces it
back off a solid mask.
use ;
let rho = SPEED_OF_SOUND / 100.0;
let mut sim: = new
.with_relaxation
.init;
// A dense spot in the rest population, a wall, and the mass to hold.
sim.dist = sim.dist.slice_fill;
sim.solid_mask = sim.solid_mask.slice_fill;
sim.save_correct_total_mass;
sim.advance_step;
// [H, W, (y, x)] momentum: the field the example draws.
let momentum = macroscopic_momentum;
Shape Contracts
bunsen::contracts provides allocation-free, always-on runtime tensor-shape contracts. A contract pairs paper-style
shape notation with runtime checking:
it asserts that a tensor's shape matches a declared pattern and unpacks named dimensions for downstream use, catching
shape errors at their source. Single checks run in ~160 ns; the amortized periodic variants average a few ns.
use *;
// Assert and unpack named dimensions in one shot:
let shape = ;
let = unpack_shape_contract!;
assert_eq!;
// Patterns support products, sums, and bound dimensions — e.g. a windowed
// image where height = h_wins * window_size:
let = unpack_shape_contract!;
In hot loops, use assert_shape_contract_periodically! to amortize the check via exponential backoff while still
catching regressions:
use *;
assert_shape_contract_periodically!;
Tensor Op Extensions
bunsen::burner::tensor provides extension traits that add utility methods directly to burn::Tensor — in scope after
use bunsen::burner::tensor::*;:
TensorOpExt(all tensor kinds) —swapexchanges two tensors in place;releasemoves a tensor out of a field, leaving an empty tensor behind;select_dimselects one index along a dimension and squeezes it, dropping the rank by one.TensorIntOpExt(Inttensors) —square, andbounded_elemfor elementwise[start, end)range checks producingBoolmasks.TensorBoolOpExt(Booltensors) —count_dim/count_dimscounttrueelements along one or more dimensions, with negative indexing.
use *;
use *;
// Extract row `i` of a matrix as a vector:
// Count the `true` cells in each row of a boolean grid:
TensorData Index Views
TensorDataView and TensorDataViewMut wrap burn's low-level
TensorData to give ergonomic multi-dimensional element access via bracket notation — view[&[i, j]] — instead of
manually flattening indices. The views deref to the underlying TensorData, so .shape and friends are right there.
Handy for inspecting or patching raw tensor data without building full tensors.
use *;
use *;
let data = from;
let view: = view;
// Deref exposes the underlying TensorData metadata:
assert_eq!;
assert_eq!;
assert_eq!;
The mut view supports in-place writes:
use *;
use *;
let mut data = from;
let mut view: = view;
view = 10.0;
assert_eq!;
XML Module Reflection
bunsen::burner::module::reflection::XmlModuleTree turns any burn Module
into a queryable XML meta-description of its structure. This enables type-erased introspection and XPath-style parameter
selection — e.g. "every rank-2 weight under the transformer blocks" — which is exactly what you need to slice a model
into parameter groups for per-group optimizers.
Take a small container module:
use ;
use *;
let module = ;
Reflecting it yields a queryable XML description of the structure:
use XmlModuleTree;
// As XmlModuleTree holds a non-Send active query environment, it must be `mut`
// to run queries.
let mut mtree = build;
// Dump the structure to inspect it:
println!;
// Select parameters by XPath and collect their ParamIds — e.g. just the
// rank-2 Linear weights:
let matrix_params = mtree
.select_params
.to_param_ids ?;
The dumped structure mirrors the module's fields, with each @name taken from the struct field and a stable param_id
per tensor:
Blocks & Ops
bunsen::blocks is a library of burn::module::Module building blocks (stateful layers with trainable parameters), and
bunsen::ops is a library of stateless
Tensor operations. A survey of what's available:
blocks/
├── transformers/
│ ├── attention — CausalSelfAttention, scaled_dot_product_attention,
│ │ causal_mask, KVCache (autoregressive decode cache)
│ ├── embedding — RotaryEmbedding (RoPE)
│ └── mlp — Mlp feed-forward block, layer_norm_mlp
└── images/
├── conv — ConvNorm2d, ConvBlock2d (Conv → Norm → Activation)
├── patching — PatchEmbed (ViT-style patch tokenizer)
├── pool — AvgPool2dSame (TF-style SAME padding)
└── drop — DropBlock2d, DropPath (stochastic depth)
ops/
├── arange — float_arange, float_linspace (+ Vec variants)
├── noise — noise, noise_like (distribution sampling + clamp)
├── clamp — ClampOp (optional min/max bounds)
├── drop — dropout, drop_block_2d
├── norm — rms_norm (RMS normalization)
├── repeat — repeat_interleave (NumPy/PyTorch semantics)
├── conv — conv output-shape arithmetic, same-padding helpers,
│ convolve_func_2d
└── embedding — unembed, iota_embedding, identity_embedding
Examples
The bunsen repo includes a number of complex demos. The goal of the demos is to showcase the capabilities of the
library; while also collecting a working edge of problems which could and should be improved by further development.
See examples/ for the full index.
License
bunsen is distributed under the terms of both the MIT license and the Apache License (Version 2.0).