Turn your ESP32-P4 into a searchable knowledge base
Turn a folder of markdown notes into an on-device semantic search engine. One command embeds the documents, packs a flash image and scaffolds a ready-to-flash ESP32-P4 sketch — no server, no SD card, no network.
Until a few months ago, running a sentence embedding model on a microcontroller was not a thing. Keyword spotting? Sure. A tiny intent classifier? Maybe. But tokenizing free text, embedding it with a transformer, and searching a corpus by meaning needed a server. The ESP32-P4 changes that: 32 MB of PSRAM and a fast RISC-V core are enough to run MiniLM-L3 locally.
This article turns a folder of notes into a searchable knowledge base that lives on the board. Type a question on the serial monitor and the P4 tokenizes it, embeds it, and ranks every chunk in its flash-resident index. No server, no SD card, no network. About three seconds per question.
The tool that makes it practical is esp32kb. Point it at the folder and it embeds, quantizes, packs kb.img, and scaffolds a ready-to-flash Arduino sketch. No architecture design, no tokenizer code, no quantization math. Today it ships one model — paraphrase-MiniLM-L3-v2 at sequence length 64, INT8 — and that's the only one it supports. The point is not to be a model menu; it's to get you from notes to a working board this afternoon.
Everything below ran on a Waveshare ESP32-P4 (32 MB flash, 32 MB PSRAM, chip v3.2, 400 MHz) with a corpus of 10 markdown notes → 793 chunks. The numbers are from that run.
The whole recipe at a glance
- Install the two halves
- Point esp32kb at your notes
- Build the knowledge base
- Flash the board
- Ask questions
- Look under the hood
What you need
- An ESP32-P4 board with 32 MB of PSRAM and 32 MB of flash. I used a Waveshare ESP32-P4 (chip v3.2). The 17.4 MB model is copied into PSRAM at boot, so a 16 MB PSRAM board is not enough; the partition table also needs 5 MB for the app, 20 MB for the model and 6 MB for the knowledge base.
- A USB-C cable and a serial port on your computer.
- arduino-cli and the ESP32 Arduino core 3.x (the P4 needs a recent core). The generated
flash.shusesarduino-cli; the IDE is optional. - The
espdlxArduino library, version 1.2.0 or newer — the first release with the ESP32-P4 prebuilt. - Python 3.10+ and
uv(or plainpip). The embedding runs on your CPU throughonnxruntime; no GPU and no PyTorch.
How it fits together
esp32kb has a half on each side of the workflow:
- a Python CLI that reads your notes, embeds them, quantizes the vectors and packs everything into
kb.img; - an Arduino library (
VectorSearch.h, generated into your sketch folder) that tokenizes questions, runs the MiniLM model throughespdlx, and searches the packed vectors on the board.
The exchange between the two is three artifacts:
notes/*.md
│ esp32kb embed (PC)
▼
kb.img + minilm_l3.espdl + VectorSearch.h
│ flash.sh
▼
ESP32-P4: tokenize → embed → search → top-5 chunkskb.img is the searchable index: the vectors, the chunk text, the file names and the WordPiece vocabulary in one container. minilm_l3.espdl is the INT8 model. VectorSearch.h is the firmware library with the model geometry baked in. flash.sh writes all three to the board in one upload.
Keyword search is simpler, but it fails exactly when you need it: ask "How much memory does the P4 have?" and a note that says "32 MB of PSRAM" shares almost no words with the question. The embedding model maps both to nearby vectors, so the note wins anyway. That's the whole value proposition.
Step 1 — Install the two halves
On the Python side, uvx runs the tool without installing it globally:
uvx esp32kb --help
# or, if you prefer a normal install:
pip install esp32kbIf you're following along from a checkout, use uv run --project esp32kb esp32kb --help instead.
On the Arduino side, install the ESP32 core and the espdlx library:
arduino-cli core install esp32:esp32
arduino-cli lib install espdlxIf the Library Manager still offers an older espdlx, install 1.2.0 or newer from salernosimone/arduino-espdlx — the P4 prebuilt is the part that matters. Older versions compile for the S3 only.
Step 2 — Point esp32kb at your notes
Make a folder and put your notes in it. Any structure is fine — the tool walks it recursively:
~/notes/
esp32/
psram.md
flashing.md
projects/
kb.md
reading-list.txtEvery .md, .markdown and .txt file is indexed. Images, PDFs and source files are ignored. There is no schema, no required front matter and no special heading syntax: the text is read as-is, including headings, lists and code blocks.
Chunks never cross file boundaries, and the file name travels with every result. Keeping one topic per note makes the chunks more coherent. Start with 10–50 notes; the PC has to embed every chunk, so more notes means a longer build. Search stays cheap.
Step 3 — Build the knowledge base
This is the whole build:
esp32kb embed --root ~/notes --sketch-dir ~/Arduino/KB--sketch-dir is the Arduino project folder; it is created if it doesn't exist. On my 10-note corpus the output looks like this:
indexed 10 files -> 793 chunks (seq=64, dim=384)
wrote ~/Arduino/KB/model/kb/ (vectors.bin, meta.bin, chunks.bin, files.bin, vocab.txt, kb.img)
wrote ~/Arduino/KB/VectorSearch.h (seq=64, dim=384, topk=5)
wrote ~/Arduino/KB/partitions.csv
copied ~/Arduino/KB/model/minilm_l3.espdl
wrote ~/Arduino/KB/flash.sh
Flash it now with arduino-cli? [y/N]:That one command did the following:
- Chunked every document at sentence and line boundaries, into pieces of at most 62 WordPiece tokens (
seq - 2), never crossing a file. - Embedded each chunk on the PC with MiniLM-L3, using the CPU. No GPU, no PyTorch, no cloud call.
- Normalized and quantized the vectors to INT8 with one global scale shared by the corpus and the queries. Each number becomes one byte instead of four.
- Packed the vectors, chunk text, file names and the 30,522-token vocabulary into
kb.img— 656 KB for 793 chunks. - Baked the model geometry (
KB_SEQ,KB_DIM,KB_TOPKand the container magics) intoVectorSearch.h, so the firmware cannot disagree with the image. - Scaffolded the sketch, the partition table, the model and
flash.sh.
Useful flags: --no-flash builds without flashing, --yes skips the confirmation, and --port / --fqbn skip the serial-port and board menus.
Here's what ends up in the sketch folder:
| path | what it is | edit it? |
|---|---|---|
model/kb/kb.img |
the searchable index (vectors + text + names + vocabulary) | no |
model/minilm_l3.espdl |
the INT8 MiniLM-L3 model | no |
VectorSearch.h |
the firmware library, with the geometry baked in | no — generated |
KB.ino |
a ~40-line demo sketch | yes |
partitions.csv |
5 MB app + 20 MB model + 6 MB KB | no |
flash.sh |
compiles and flashes everything | no — generated |
The .ino is written only when the folder has no sketch; an existing .ino is never overwritten. VectorSearch.h and flash.sh are refreshed on every run.
Step 4 — Flash the board
Answer y at the prompt, or run the generated script yourself:
cd ~/Arduino/KB
./flash.shIt compiles the sketch and uploads three things in one go: the app, the 17.4 MB model at 0x510000, and kb.img at 0x1910000. The first flash takes a few minutes because the model is large; later flashes still rewrite all three, which is slower but keeps the board and the folder from drifting.
The board options are baked into the script:
esp32:esp32:esp32p4:ChipVariant=postv3,FlashSize=32M,PSRAM=enabled,PartitionScheme=customChipVariant=postv3 is for the v3.x P4 silicon I used. On an older revision, switch it to prev3. The partition table looks like this:
| partition | size | contents |
|---|---|---|
app0 |
5 MB | your sketch |
model |
20 MB | minilm_l3.espdl (17.4 MB) |
kb |
6 MB | kb.img (656 KB here) |
Step 5 — Ask questions
Open the serial monitor at 115200 baud. With arduino-cli:
arduino-cli monitor -p <your-port> -b esp32:esp32:esp32p4:ChipVariant=postv3,FlashSize=32M,PSRAM=enabled,PartitionScheme=customThe board prints a prompt. Type a question and press Enter:
KB: MiniLM-L3 int8 vector search (P4, on-device tokenizer)
type a query and press Enter:Each answer is up to five hit lines: a rank, a similarity percentage, the source file and the chunk text. The header line also prints infer and search in microseconds — on my desk they read about 3,020,000 and 3,100, which is 3.02 s for the transformer and 3.1 ms for the search over 793 vectors.
Ask questions the way you'd ask a person, not a search box. "How much PSRAM does the P4 have?" works better than "PSRAM P4"; the model was trained on paraphrase pairs and full sentences are its native input. Queries longer than 62 tokens are truncated.
The numbers on my desk
These are the real measurements from the 10-note corpus, not a synthetic benchmark:
| metric | value |
|---|---|
| board | Waveshare ESP32-P4, 32 MB flash, 32 MB PSRAM, 400 MHz |
| corpus | 10 markdown notes → 793 chunks at seq 64 |
| model | paraphrase-MiniLM-L3-v2, INT8 (w8a8), 17.4 MB |
kb.img |
656 KB |
| inference | 3.02 s per question |
| search | 3.1 ms over 793 vectors |
| top-1 matches PC float | 10/10 |
| top-1 is the expected note | 8/10 |
| expected note in top-5 | 10/10 |
| PSRAM free after init | 13.46 MB |
Top-1 agreement with the float model is 10/10 — the INT8 device picks the same first chunk as the PC. The note I expected was top-1 in 8/10 and in the top-5 in 10/10; that's why the demo returns five hits.
The shape matters more than the exact numbers. Search is not the bottleneck; the transformer is. Doubling the number of chunks doubles the search time, but it is still milliseconds. Doubling the sequence length roughly doubles the inference time.
That's why the default is seq 64. The model can read up to 64 tokens at a time; chunks are capped at 62 (two slots go to [CLS] and [SEP]). Smaller chunks mean more of them and faster inference, but less context per chunk. Larger chunks mean fewer vectors, but each chunk mixes more topics:
| seq | chunks | inference | top-1 vs float | expected note in top-5 |
|---|---|---|---|---|
| 32 | 1,710 | 1.50 s | 8/10 | 10/10 |
| 64 | 793 | 3.02 s | 10/10 | 10/10 |
| 128 | 352 | 6.13 s | 9/10 | 9/10 |
Seq 64 is the sweet spot: seq 32 is faster but loses top-1 accuracy, and seq 128 doubles the latency again while its longer chunks mix several topics and hurt retrieval. These are ten demo queries, not a leaderboard — your corpus will produce different numbers. The useful signal is the trade-off.
Step 6 — Look under the hood
The demo sketch is deliberately boring: read a line, call KB.query(), print the hits. Here it is in full:
#include <Arduino.h>
#include "VectorSearch.h"
// KB demo: MiniLM-L3 embedding search on ESP32-P4.
// The board loads the model + knowledge base from flash, tokenizes queries
// itself and answers free text typed on the serial monitor. No PC needed.
VectorSearch KB;
void setup() {
Serial.begin(115200);
delay(500);
Serial.println("KB: MiniLM-L3 int8 vector search (P4, on-device tokenizer)");
while (!KB.begin()) {
Serial.println("init failed (flash the model + kb.img; see the README).");
delay(1000);
}
Serial.println("type a query and press Enter:");
}
void loop() {
if (Serial.available()) {
String text = Serial.readStringUntil('\n');
text.trim();
if (text.length()) {
std::vector<SearchResult> hits = KB.query(text);
print_results(text, hits);
Serial.println("type a query and press Enter:");
}
}
}
void print_results(String& text, std::vector<SearchResult>& hits) {
Serial.printf("q \"%s\" (%u hits, infer=%uus search=%uus)\n", text.c_str(),
(unsigned) hits.size(), (unsigned) KB.last_infer_us(),
(unsigned) KB.last_search_us());
for (size_t i = 0; i < hits.size(); i++) {
Serial.printf(" #%u (%u%%) [%s] %s\n", (unsigned)(i + 1),
(unsigned)hits[i].score, hits[i].filename().c_str(),
hits[i].read().c_str());
}
}The public API is small enough to fit in your head:
| call | what it does |
|---|---|
KB.begin() |
loads the model, the kb.img container and the tokenizer vocabulary |
KB.query(text) |
returns up to 5 SearchResult objects, best first |
hit.score |
similarity, 0–100 (higher is closer) |
hit.filename() |
the source file of the chunk |
hit.read() |
the chunk text, read lazily from flash |
hit.neighbor(n) |
the chunk n positions away in the same file |
Everything else in VectorSearch.h is implementation. The per-query path is:
- Tokenize the question with WordPiece. The 30,522-token vocabulary lives inside
kb.img;VectorSearch.hbuilds a hash table in PSRAM at boot, so no PC and no tokenizer file are needed. - Fill the model input with
[CLS], the token IDs,[SEP]and[PAD], plus an additive attention mask: 0 on real tokens, a large negative value on padding. Without that mask, padding can dominate the attention at longer sequences and collapse the query embedding. - Run MiniLM-L3 through
dl::Modelfromespdlx— the 17.4 MB INT8 model, about 3 seconds. - Pool and normalize: average the output rows over the real tokens only, then L2-normalize. That gives one 384-number fingerprint for the question.
- Quantize the query with the same global scale used for the corpus, so both sides live in the same INT8 space.
- Search: a coarse pass calls
esp_nn_fully_connected_s8(the P4's PIE SIMD kernel) over all vectors, keeping the top 64. The kernel requantizes to INT8, so the top 64 are then rescored with an exact int32 dot product. The final ranking is identical to a full brute-force scan. - Fetch the text of the five winners from flash. Only those five chunks are read.
Troubleshooting
| Symptom | Fix |
|---|---|
init failed on boot |
The model or kb.img isn't flashed. Run ./flash.sh; it writes both. Check that partitions.csv is the generated one. |
Failed to alloc ... PSRAM |
Use a 32 MB PSRAM board and enable PSRAM. The 17.4 MB model is copied into PSRAM; 16 MB is not enough. |
knowledge base partition 'kb' not found |
kb.img wasn't flashed, or the partition table doesn't define kb. Rerun esp32kb embed and ./flash.sh. |
vocabulary missing |
The kb.img was built without the vocabulary. Rebuild it with esp32kb embed; the vocab travels inside the image. |
| Upload fails or the port changes | The board can re-enumerate. Pick the new port and upload again. |
| No serial output | Check 115200 baud. This board does not always reset when the monitor opens — press the reset button. |
| A query returns nothing | KB.begin() failed during boot. Read the first lines of the serial log; the error names the missing partition. |
| Top-1 is a near miss | Look at the top-5 first: at seq 64 the expected note was in the top-5 10/10 times. If it isn't, add a note that states the fact more directly. |
| Results feel random | Ask a full question, not keywords. The model is English and trained on paraphrase pairs. |
kb.img larger than the ... partition warning |
The 6 MB kb partition is full. Trim the corpus or enlarge the partition (and the matching offset in the build script). |
Build fails with No module named onnxruntime |
Install the Python side in the environment you're running: pip install esp32kb, or use uvx esp32kb. |
| Build fails with a missing ONNX | Don't pass --onnx unless you have a matching model; the bundled MiniLM-L3 is used by default. |
Address 0x510000 is out of range for 24bit flash mapping |
Use the generated VectorSearch.h. It copies the model to PSRAM instead of trying to mmap the partition. |
| Inference is slower than 3 s | Expected at seq 64. Rebuild at seq 32 if you can trade top-1 accuracy for speed. |
Where to go next
Once the board answers, the interesting part is what you do with the answer. The recipe itself never changes: edit notes, rerun esp32kb embed, flash, ask.
- Grow the corpus. The 6 MB partition holds thousands of chunks. Search grows linearly with the number of chunks, but even a few thousand chunks stays in the milliseconds; inference stays the same because the model, not the corpus, is the bottleneck.
- Use the neighbors.
SearchResult::neighbor(n)returns the chunk before or after a hit in the same file. Pulling a hit plus its neighbors gives you a context window without building a bigger model. - Put an LLM after it. The board is a retrieval layer. Send the top-5 chunks (and their neighbors) to an LLM on your PC or a server and you have a local RAG pipeline whose index never leaves the board. The P4 finds; the LLM writes.
- Drive something. A display that shows the matching note, a speaker that reads it, a Telegram bot that answers from the board's knowledge — the sketch is 40 lines, so the output side is yours.
- Rebuild the model. The toolchain is wired to MiniLM-L3 at seq 64 today. The advanced path is
model/export_onnx_mask.py+model/quant_mask.pyto export and quantize another sequence length, replacemodel/minilm_l3.espdlin the sketch folder, and runesp32kb embed --onnx path/to/new.onnx. ChangeSEQin one place; the image, header and model stay in sync.
The Python package is at salernosimone/python-esp32kb; the Arduino runtime is espdlx, and the upstream model runtime is esp-dl.
The trade is simple: 17 MB of flash, 3 seconds of patience, and a board that can find the right note without a server. That's a useful thing to have in your pocket.