r/rust • • 5d ago

🛠️ project From a BERT encoder to a Rust inference engine

Hi,

About a year ago I posted kjarni here (https://www.reddit.com/r/rust/comments/1n1ick5/i_built_rust_bert_encoder/) when it was basically a BERT encoder(i wanted to run my own embeddings in WASM and thought it would be good to learn Rust and compilation to WASM).

It's now an inference engine in rust, small footprint, low overhead, almost all pure Rust crates. It started around two years ago after years of C++ i wanted to give Rust an honest chance with an ambitious project, i wanted to get the BERT model running and just kept at it.

Now it does embeddings, search, transcription, classification, reranking and chat

It runs on macOS, Linux and Windows, on x86 and ARM, and there's something to be said for Rust making that this painless. It also compiles to a C ABI so I wrote bindings for C#, Go, C++, C and Python, and they all behave the same since each one is a thin veneer over the same library. It also builds to WASM

I wanted the API to be as simple as I could get it, in rust it looks like this and it's basically the same in C#/Go/C++/Python:

let whisper = Transcriber::builder("whisper-small").build().await?;
let text = whisper.transcribe_file("meeting.wav")?.text;
let summary = kjarni::chat::send("qwen2.5-1.5b-instruct", &format!("Summarise: {text}")).await?;

What i particularly like is that every model goes through the same decode loop on CPU and GPU. There's a backend trait with an associated token type, so the next token stays where it lives (an ndarray on the CPU, a GPU tensor on the GPU), and an enum picks the backend, with the GPU arm cfg'd out for the CPU-only wasm build. It's not perfect, the enum wrapper downcasts the token through Box<dyn Any>, so if someone has a nicer way i'm all ears: https://github.com/kjarni-ai/kjarni/blob/69b51af046014d36fe939a2f1b26f8fda21770e3/crates/kjarni-transformers/src/decoder/backend.rs#L155-L177

A lot of the work went into getting the same output as torch. Embeddings agree to within 1e-6, and greedy chat replies, summaries and translations come out word for word the same

Speed wise I'd call it pretty competitive with torch and llama.cpp (on the models kjarni supports). On the GPU they use CUDA and I use wgpu, so it runs on Vulkan, Metal and DX12. On the CPU they link against Intel MKL and I use faer (pure Rust) or my own SIMD kernels

Some numbers, all on Linux on one machine (i7-13700, RTX A2000):

  • pip install is 28 MB vs 1.4 GB for PyTorch, and a fresh process gets its first embedding in 91 ms vs about 2.8 s
  • bge-m3 batches are about 23% faster than PyTorch, mpnet 7%
  • whisper-small runs at 10.7x real time, openai-whisper 10.6x
  • 4-bit chat models on the GPU from 3B up are within 5% of llama.cpp on CUDA, and close to or ahead of its Vulkan backend
  • where I lose: PyTorch is 18% faster on MiniLM batches and processes prompts 1.5x faster on the CPU, my 4-bit CPU kernels generate at 75-91% of llama.cpp's speed, and llama.cpp is way faster on long prompts on the GPU since I don't have flash attention yet

All the numbers and how they were measured are here: https://github.com/kjarni-ai/kjarni/blob/69b51af046014d36fe939a2f1b26f8fda21770e3/README.md#how-it-compares

Someone will probably ask why not just use candle. Candle is great but it's more of a framework, you still end up dealing with model exports and tokenizers. I wanted something where I just embed my documents or transcribe a file without too much headache

Code is here if you want to take a gander: https://github.com/kjarni-ai/kjarni , would be happy to hear what you think, especially about the API and the wgpu side

10 Upvotes

6 comments sorted by

1

u/GetExord 4d ago

On removing `Box<dyn Any>` per token in the decode loop: moving the dynamic dispatch *above* the loop usually makes both the types and the hot path much cleaner.

Two idioms that work well in Rust without sacrificing backend separation:

  1. Keep the backend trait parameterized (`trait DecoderBackend { type Token; ... }`), put the decode loop inside a generic `fn decode_loop<B: DecoderBackend>(backend: &mut B, ...)` so `B::Token` stays monomorphized with zero heap allocation or downcasting per step, and push the enum branch once to session creation (`enum Session { Cpu(Engine<CpuBackend>), Gpu(Engine<GpuBackend>) }`).
  2. If callers truly need one erased tensor/token handle passed across boundaries, replace `Box<dyn Any>` with a small closed enum (`enum DeviceToken { Cpu(CpuArray), #[cfg(feature = "gpu")] Gpu(wgpu::Buffer) }`). Exhaustive `match` eliminates runtime `Any` panics and removes the per-step `Box` allocation completely.

On the `wgpu` long-prompt side: alongside a tiled online-softmax attention kernel in WGSL (keeping tiles in workgroup shared memory instead of materializing the N^2 matrix in VRAM), check whether sampling triggers a synchronous `map_async` staging-buffer readback of full vocab logits on every step. Running `argmax` or top-k reduction in a tiny compute pass so you only read back 1 `u32` (or `K` pairs) rather than the full vocab `f32` buffer removes a lot of GPU queue stalls.

1

u/mr_potatohead_ 4d ago

the Box<dyn Any> is only in the seq2seq path and boxed once per generation, not per token. the logits readback pulls the full vocab each step because greedy decoding doesn't use the GPU argmax kernel yet, and LLM attention is already tiled, the n squared path only affects encoders

3

u/Melodic-Amoeba3364 5d ago

That 91 ms vs 2.8 s cold start is gnarly. The pip install size difference alone makes this worth a look for anything containerized or edge. Going from a BERT encoder side project to a full engine with cross-language bindings in two years is a hell of a trajectory.

1

u/mr_potatohead_ 5d ago

thanks! yeah the containers/edge thing is kind of what i had in mind. the CLI is one 35 MB binary that only needs libc, it runs fine in a bare debian-slim image and pulls the model itself. the cold start is mostly just not having to import torch, the weights get mmapped so loading is cheap too

-2

u/sparklingLipzz 4d ago

yeah the cold start numbers are ridiculous, makes me want to actually try building something with it instead of just reading about torch setups

2

u/tanmaynargas2901 3d ago

On the Box<dyn Any> downcast: you can probably avoid it by not erasing the token type at all.

Keep the decode loop generic over the backend trait, and only put the enum match at the outer entry point. Each arm calls the same generic function with its concrete backend, so the token stays an ndarray or a GPU tensor the whole way through.

The cfg'd GPU arm then lives in that one match only. The tradeoff is the loop gets monomorphized twice, so a bit more compile time and binary size.