Hyperembed: Writing an Embedding Inference Engine in Rust
When I decided to write an embedding inference engine, people said "why? sentence-transformers already exists." They were right. sentence-transformers runs in Python, supports more than 5000 models, and the PyTorch ecosystem is mature.
But my goal wasn't just doing embeddings. My goal was doing embeddings everywhere. Not on a server, not on a phone, not on an embedded device. On all of them. With a single binary. Zero Python dependencies. Zero PyTorch dependencies. Zero ONNX runtime.
Pure Rust. Just Rust.
That's how Hyperembed was born.
The problem: where does embedding inference happen?
Today embedding inference happens in these places:
- Cloud API (OpenAI, Cohere, etc.): The easiest. But you get network latency, API costs and data privacy issues.
- Server side (sentence-transformers + GPU): Better. But you need a GPU, a Python runtime, memory management.
- Edge / on-device: Nearly impossible. PyTorch Mobile is big, ONNX Runtime is heavy, model optimization is complicated.
Hyperembed targets that third category: embedding inference at the edge, on-device, on embedded systems. Thanks to Rust.
How does it work?
An embedding inference engine has to do the following:
- Tokenizer: Turn text into tokens (BERT tokenizer, WordPiece)
- Model loading: Load the BERT model (weights, config)
- Forward pass: Run the tokens through the model, get the hidden states
- Pooling: Produce a single embedding vector from the hidden states (mean pooling, CLS token, etc.)
Hyperembed implements all of this from scratch, in Rust.
Tokenizer (WordPiece)
Implementing the BERT tokenizer was more fun than I expected. The WordPiece algorithm:
- Split the text on whitespace
- Split each word into the longest matching subtokens in the vocabulary
- Convert the subtokens into IDs
- Add the special tokens ([CLS], [SEP])
To do this in Rust I used a trie (prefix tree). With a 30,000-token vocabulary, subword tokenization runs on the order of microseconds. About 50x faster than Python, because Python does string slicing for every token.
Model loading
BERT models usually come in two formats:
- PyTorch (.bin): Raw (pickle + tensors)
- ONNX (.onnx): Portable but big
Hyperembed reads the PyTorch format directly. To parse tensors saved with torch.save() in Rust, I implemented the pickle format. What Python's pickle module does, I wrote from scratch in Rust.
How hard was it? Pretty hard. The pickle format was designed to serialize Python objects. It works like a stack-based VM. There are opcodes, there's memoization, there's reference resolution. Implementing it in Rust took about 2000 lines of code. But the result: I can load any PyTorch BERT model without PyTorch.
Forward pass
The most critical part. The Transformer forward pass:
Input → Embedding → [Attention → FFN] × 12 → Pooling → Output
Every layer is matrix multiplication. A lot of matrix multiplication. For the 12-layer BERT-base:
- Each attention head: Q, K, V projections (3 matrix multiplications)
- Attention: Q @ K^T, softmax, then multiply by V
- FFN: 2 big matrix multiplications (768→3072, 3072→768)
About 110M parameters in total. Billions of floating-point operations per forward pass.
To make this fast:
- SIMD optimizations: Matrix multiplication with AVX2/NEON instructions using Rust's
std::simdmodule - Cache-friendly memory layout: Storing weights column-major instead of row-major to improve cache locality
- Fused operations: Doing LayerNorm + the residual connection in a single pass
- Weight quantization: INT8 quantization instead of FP32 (optional, shrinks the model 4x)
The result: about 3-5x faster than sentence-transformers (in CPU mode). Not in GPU mode, of course. I can't compete with CUDA kernels. But on the CPU, especially on a low-power ARM chip, Hyperembed pulls way ahead.
Pooling
To produce an embedding vector from BERT's final hidden states:
- CLS token pooling: Take the hidden state of the [CLS] token
- Mean pooling: Take the average of all tokens' hidden states (excluding padding tokens)
- Max pooling: Take the maximum values
Hyperembed supports all of them. The default is mean pooling, the best choice for most use cases.
Benchmarks
A few benchmark results (MacBook M2, CPU only, batch size=1):
| Model | Framework | Latency (ms) | Memory (MB) |
|---|---|---|---|
| BERT-base | sentence-transformers (Python) | 45 | 850 |
| BERT-base | ONNX Runtime (C++) | 28 | 520 |
| BERT-base | Hyperembed (Rust) | 11 | 180 |
| BERT-tiny | sentence-transformers (Python) | 12 | 340 |
| BERT-tiny | Hyperembed (Rust) | 2.3 | 65 |
ARM Cortex-A72 (Raspberry Pi 4):
| Model | sentence-transformers | Hyperembed |
|---|---|---|
| BERT-tiny | 380ms | 45ms |
This is where the cost difference shows up on embedded devices. The Python runtime, the GIL, the garbage collector, dynamic type checks: all of it is very expensive on ARM. Rust's zero-cost abstractions are what make the real difference on resource-constrained devices.
Semantic search pipeline
Hyperembed's main use case: semantic search. Finding the documents in a collection that are semantically closest to the user's query.
Pipeline:
- Vectorize all documents with Hyperembed
- Write the vectors to a vector database (Qdrant, Milvus, or a simple FAISS index)
- Vectorize the user's query
- Find the k closest documents with cosine similarity
Hyperembed's Rust API:
use hyperembed::{Embedder, EmbedderConfig};
let config = EmbedderConfig::default()
.with_model("sentence-transformers/all-MiniLM-L6-v2")?
.with_pooling(PoolingStrategy::Mean);
let embedder = Embedder::new(config)?;
let documents = vec![
"The Rust programming language is designed for systems programming.",
"Python is popular in data science and machine learning.",
"JavaScript is a language that runs in web browsers.",
];
let doc_embeddings = embedder.embed_batch(&documents)?;
let query_embedding = embedder.embed("systems programming language")?;
let similarities: Vec<f32> = doc_embeddings.iter()
.map(|d| cosine_similarity(&query_embedding, d))
.collect();
// → [0.92, 0.45, 0.31] - Rust is the closest, as expected
The future of local-first AI
Hyperembed is part of a bigger vision: local-first AI.
Today 99% of AI runs in the cloud. OpenAI API, Anthropic API, Google Cloud AI. That model brings these problems:
- Latency: A network round-trip for every query
- Cost: Per-token pricing that multiplies as you scale
- Privacy: Your data sits on someone else's server
- Dependency: When the API goes down, your app stops working
- Offline: No internet, no AI
Local-first AI solves all of these. The model runs on your device. Embeddings are computed on your device. The vector database runs on your device (something like SQLite + sqlite-vec).
Hyperembed is the embedding layer of this vision. The other layers:
- Inference: local LLM runtimes like llama.cpp and mistral.rs
- Vector storage: LanceDB, sqlite-vec
- Orchestration: your own agent framework
In 2026 you can run a 7B-parameter LLM on a MacBook. In 2027 you'll be able to run one on a phone. Hyperembed handles the embedding side of that shift. And since it's written in Rust, it can run in the same process as the LLM runtimes, with zero IPC overhead.
What did I learn?
1. The pickle format is a dark art. I never would have guessed I'd have to implement a VM just to parse Python objects. But I did. And it works.
2. SIMD in Rust is more accessible than you think. std::simd is stabilizing on nightly. Writing portable SIMD no longer needs unsafe and inline assembly.
3. BERT inference is simpler than you think. The Transformer architecture looks complicated, but it's really a few basic operations on repeat: matmul, softmax, layer norm, GELU. Once you implement those, the rest is a loop.
4. Rust is underrated for ML inference. Everyone writes Python + CUDA, but for CPU inference Rust is much better. Memory management, SIMD, zero-cost abstractions: all of it cuts inference latency dramatically.
What's next?
v0.3 roadmap:
- More model architectures: RoBERTa, DistilBERT, MiniLM
- GGUF format support: the quantization format llama.cpp uses
- WASM target: embedding inference in the browser (!)
- Python binding: usable from Python with
pip install hyperembed - ONNX export: export your own model as ONNX (the reverse: ONNX → Hyperembed)
Try it
git clone https://github.com/neuralforgeone/hyperembed
cd hyperembed
cargo build --release
cargo run --example semantic_search
It's not on crates.io yet. But soon you'll be able to type cargo add hyperembed.
In the next post I'll talk about BareEngine: an editor-first game engine for Metin2-style MMORPG worlds. A return, with C++, to where I started 10 years ago: game servers.