W W

WINNEX — proof of what a search left out

Every document excluded from the results carries a proof that it could not be in the top-K — by the Cauchy-Schwarz inequality. Zero bound violations by construction.

What is WINNEX

WINNEX — Weighted Inference Neural Network Enhancement. A deterministic, training-free framework that improves a pretrained model using only the geometry it already learned.

When your search says "no document found", WINNEX can prove the document does not exist. Not "we searched and did not see it" — a per-document arithmetic proof that it could not have been in the results. That answer is what a regulator, a court or an auditor accepts.

The problem it eliminates

Approximate vector search returns an answer with no way to know what it missed. HNSW, IVF-PQ and every managed vector database optimise recall as a statistic — "97% of the true neighbours are usually found". That number is measured across a benchmark, not per query, and it says nothing about the question you just asked.

In an unregulated product this is fine. In a system where someone can be asked "why was this document not produced?", it is the entire problem. The failure is silent: the index returns ten confident results, the eleventh relevant document is simply absent, and no log records its absence. WINNEX closes that gap with arithmetic instead of a promise.

What it solves

CapabilityWhat you getPackage
ProofEvery excluded document carries a bound below the K-th score. A verifier recomputes it.winnex-madhava
AuditEd25519 over the commitment, key outside the engine.winnex-tracer
IntegrityThirteen flags catch NaN, zero vectors, dimension mismatch and provider drift before indexing.winnex-ai-normalize

Why use it

  • The answer becomes defensible. A denial letter, a regulatory response, a due-diligence opinion currently rest on "our system retrieved this". WINNEX changes the sentence to "our system retrieved this and can prove nothing else was relevant".
  • It drops into the stack you already run. No retraining, no migration. You keep your encoder and add the proof layer on top of the retriever.
  • A third party can check it without trusting you. The bound is arithmetic — an auditor recalculates it. That is the difference between a log and evidence.

How to start

Three packages on PyPI. The engine is a native wheel; the audit layer is pure Python.

pip install winnex-madhava winnex-tracer winnex-ai-normalize — then build_engine(corpus, basis="pca_corpus") and search_with_commitment. The proof is on by default once the basis is aligned to the corpus.

Architecture

Input is validated before it reaches the index; the engine proves each exclusion; the tracer seals the record; the WORM chains it.

winnex-madhava

C++20 engine. Cauchy-Schwarz bound pruning with an exact post-filter. Returns the top-K plus, for each excluded document, the bound that proves it could not belong.

winnex-ai-normalize

The quality gate. Measures the corpus with the engine's own proof and routes the configuration from the measurement, not from a heuristic. Blocks NaN, degenerate and dimension-mismatched corpora before they are indexed.

winnex-tracer

Ed25519 over the canonical commitment, SHA3-256 hash chain in append-only storage. Removing a record from the middle breaks the link and the verifier names the block.

Limitations

Design constraints, stated because knowing them is how you plan around them.
  • Latency — 20 to 100 times slower than HNSW at equal recall target. Bound computation and the audit path have a cost that cannot be removed.
  • Scale — benchmarked to 100k vectors in the reference configuration. Streaming 100M via mmap is documented, beyond that is unexplored in public benchmarks.
  • The proof covers the vector space, not the encoder — a poor encoder produces a correct but useless proof.
  • It does not improve classification — this is a retrieval engine.
  • Not a compliance certificate — the audit trail is evidence, not ISO/IEC 42001 certification.

License

Packages are released under the Business Source License 1.1 (BSL 1.1).

TermDetail
Source accessAvailable — published on GitHub, readable, compilable
Copy, modify, derivative worksPermitted for non-production use
RestrictedOffering the licensed work as a commercial search service to third parties
Change date2036 — converts to GPL v2.0 or later
Brazilian public sectorFree in production — Additional Use Grant
BSL 1.1 is source-available: the source is published and readable. It is not an OSI-approved open-source licence. Calling it "open source" is inaccurate, and we do not use that term for it.

Brazilian government agencies may use the software in production at no cost. It applies automatically to federal, state and municipal bodies, including tribunals and courts of accounts — not a discount, not a negotiation.

Worked examples

Twenty-one executable examples. Each was run against the published packages; the output shown is what came back, including the numbers that do not favour us.

00

Hello world

getting started›

The smallest working example. A corpus of five vectors, one query, and the proof that the four non-returned vectors could not belong.

The whole program
import numpy as np
import winnex_madhava as mad

corpus = np.array([...], dtype=np.float32)      # 5 vectors, dim 16
engine = mad.build_engine(corpus, dim=16, k=2,
                          k1_fraction=1.0, postfilter=True,
                          audit_exhaustive=True)
result = mad.retrieve(engine, corpus[0], k=2)
Output
indices: [0, 4] bound violations: 0 latency: 0.016 ms proof: every excluded document carries a Cauchy-Schwarz proof...
Reading it line by line

indices: [0, 4] — the query was an exact copy of document 0, so document 0 comes first. Document 4 is [0.7, 0.7, 0, 0, …], whose cosine with the query is 0.7 — the closest of the remaining four.

bound violations: 0 — this is the number that matters. For documents 1, 2 and 3 the engine computed an upper bound on their possible similarity and found it below 0.7. It proved they could not be in the top-2. If this number were anything but zero, the proof would be broken and the library unsound.

latency: 0.016 ms — one query over five vectors. The point is not the speed; it is that the answer arrived with evidence attached.

proof: … — a human-readable summary of what was proven. The machine-readable version is the record produced when audit_exhaustive=True.

In one sentence

Of the five documents, two were returned and three were proven irrelevant — not guessed, not assumed, proven with arithmetic you can re-run.

Download 00_hello_world.py Open in Colab
04

Reproduce the benchmark yourself

verification›

Do not trust our numbers. This generates its own corpus, computes brute-force ground truth, and compares. If it cannot reproduce exact scan on synthetic data, it will not on BIGANN either. The seed is fixed at 42, so your run should match this page.

Output — 20,000 vectors × 384 dims, 50 queries
corpus 20,000 x 384 queries 50 k 10 ---------------------------------------------------------- top-1 agreement 1.0000 setR@10 overlap 1.0000 bound violations 0 (must be 0) ---------------------------------------------------------- build time 514.9 ms search time 1186.6 ms (23.73 ms per query) brute force time 228.4 ms

Colab, CPU compartilhada. The same code on a local machine drops the build to 169,7 ms and the search to 2,16 ms per query — the timings below are from the local run.

Output — the same script, local machine
top-1 agreement 1.0000 setR@10 overlap 1.0000 bound violations 0 ------------------------------------------------ build time 169.7 ms search time 108.0 ms (2.16 ms per query) brute force time 33.6 ms
Reading the output

1.0000 and 1.0000 mean exact reproduction. Every query returned precisely the top-10 a brute-force cosine scan would return. That is the claim being tested, and it held on all 50 queries — on synthetic data the script generated itself, not on a number we supplied.

Search time is higher than brute force here, and that is the honest reading. At 20,000 vectors the bound computation costs more than it saves: 108,0 ms against 33,6 ms. The engine is 3,2× slower per query at this size. What it buys is the bound violations: 0 line — the record that each of the 19,990 documents not returned was proven unable to belong.

The 11× gap between Colab and local is hardware, not code. 1186,6 ms against 108,0 ms for the same script and the same seed. Anyone reading a benchmark should ask which machine produced it; this page shows both.

Where the engine does win at this size is the build: 169,7 ms to index 20,000 vectors. That is the number that makes per-tenant indexes and rebuild-on-write practical.

Download 04_bigann_benchmark.py Open in Colab
05

Catch a corrupted corpus before it breaks the proofs

integrity›

A bound proof is only as strong as the vectors it was computed on. The engine will index a corpus full of NaN and return bound_violations = 0, because the arithmetic is correct — the inputs were garbage. This example feeds it a broken corpus and shows the thirteen-flag audit catching it.

Output — clean corpus vs broken corpus
========================================================== CLEAN CORPUS ========================================================== rows : 500 dim : 64 has_fail : False fail flags : 0 warn flags : 1 nan_fraction : 0.0000 ========================================================== BROKEN CORPUS (NaN, zeros, inf) ========================================================== rows : 500 dim : 64 has_fail : True fail flags : 1 warn flags : 3 nan_fraction : 0.0047 FAIL [dataset.nan] 150 of 32000 values are NaN/inf (0.4687%) — the engine would silently produce garbage scores with 0 bound violations. WARN [dataset.foldable] corpus has NaN/inf (0.4687%) and nan_policy='block_pca' — pca_corpus would amplify the corruption (covariance → NaN eigenvectors → recall collapse, me... WARN [dataset.recall_not_guaranteed] seed recall@K = 0.375 vs the motor's own search_exact (< floor 0.95); 8/8 seed queries are recall_guarantee=pool_only — the returned top-K is the best WITHIN the pool, NOT proven the global top-K.
Output — what the gate costs and what it saves
========================================================== WHAT HAPPENS WITHOUT THE GATE ========================================================== indexed garbage anyway, bound_violations=0 the proof is arithmetically valid and completely meaningless ========================================================== THE CORRECT PIPELINE ========================================================== rows kept : 250 of 500 (250 dropped by the gate) bound_violations: 0 latency : 0.023 ms OK — gate first, index second. The proof means something now.
Reading the output

The most important line is the one without an error. indexed garbage anyway, bound_violations=0 — the engine accepted the broken corpus, ran a search, and reported zero violations. Eight of the ten values it compared were NaN or zero, and the proof came back clean. Zero violations does not mean "the answer is right"; it means "the arithmetic was consistent with the inputs", and consistent garbage is still garbage.

250 of 500 dropped, exactly. The corpus was built with three defects: 100 rows with NaN in column 0, 100 all-zero rows, and 50 rows with inf. 100 + 100 + 50 = 250. The gate removed precisely the defective rows and nothing else — that is the number to check, not a round percentage.

WARN [dataset.recall_not_guaranteed] is the subtle one. Seed recall came back at 0.375 against a floor of 0.95, and all 8 seed queries were classified pool_only. That means the returned top-K is the best within the candidate pool — not proven to be the global top-K. If stage-2 truncation dropped the true neighbour before the bound was computed, the bound never had a chance to be violated. The engine will not claim a guarantee it cannot deliver.

WARN [dataset.foldable] is about PCA, not about the engine. With NaN present, enabling block_pca would build a covariance matrix of NaNs, whose eigenvectors are garbage — and recall collapses with no error raised anywhere. The gate is saying: fix the data before you turn on the compression, not after.

All thirteen flag codes are documented in the main documentation.

Download 05_normalize_quality_gate.py Open in Colab
17

The encoder decides whether the proof means anything

encoder›

Eleven of the examples above embed text by summing ord(ch) % DIM. It runs with no download and no API key — and it does not capture meaning. This example measures the damage, then runs the same test with a real encoder.

Output — paraphrases vs unrelated pairs
DEMO ENCODER — character hash paraphrases min=0.1464 mean=0.3720 unrelated max=0.5162 mean=0.3592 paraphrases above the worst negative : 1/6 margin (min_par − max_neg) : -0.3698 → NO threshold can separate them REAL ENCODER — all-MiniLM-L6-v2 (384 dims, ~90 MB) paraphrases min=0.4803 mean=0.5276 unrelated max=0.5262 mean=0.3316 paraphrases above the worst negative : 3/6 margin (min_par − max_neg) : -0.0459 → NO threshold can separate them
Output — the same search, both encoders
query: 'até quando devo guardar segredo sobre o negócio' (nenhuma palavra em comum com a resposta correta: 'sigilo') demo (character hash): 1. [0.466] O locatário pagará aluguel mensal de $2,000.00 corrigido 2. [0.441] As partes se obrigam a manter sigilo pelo prazo de 5 anos. 3. [0.435] O foro de eleição é a comarca de Goiânia. bound_violations=0 real (all-MiniLM-L6-v2): 1. [0.548] As partes se obrigam a manter sigilo pelo prazo de 5 anos. 2. [0.477] A multa por rescisão antecipada é de três aluguéis. 3. [0.460] O foro de eleição é a comarca de Goiânia. bound_violations=0
Reading the output — the number that matters

Both runs return bound_violations=0. The engine proved the exact top-3 in both cases. What changed is which question was answered.

With the demo encoder, "exact" means exact relative to a character-overlap ranking. The query asks about secrecy; the top result is about rent. The proof is perfectly valid and the answer is wrong.

With the real encoder the correct clause comes first — 0.548 against 0.441 for the same clause under the demo encoder. Nothing about the query mentions "sigilo"; the encoder connects "guardar segredo" to it. That is the entire difference.

The real encoder does not separate everything either

Margin −0.0459 is not a win. One unrelated pair — a termination clause against a delivery deadline — scores 0.5262, above the weakest paraphrase at 0.4803. Only 3 of 6 paraphrases sit above the worst negative.

What the real encoder improves is the average: 0.5276 against 0.3316, a separation that lets a threshold work most of the time. The demo encoder averages 0.3720 against 0.3592 — a gap of 0.013, which is noise.

This is why the quality gate exists (example 05). No encoder separates all cases, so you check the corpus and the recall floor rather than trusting the model.

What this means for examples 01–12

Their bound proofs are valid. Their retrieval results are not meaningful, because the encoder ranks by character overlap. Every one of those pages says so, but the distinction is easy to miss: the number bound_violations=0 looks the same in both worlds.

For anything where the answer matters, replace embed() with a real encoder. It is one import and about 90 MB.

Download 17_encoder_real.py
07

SQL to search — mechanics without the scenario

sql›

The shortest path from a database to a provably complete answer, with no domain framing. Use this when you want the mechanics without the scenario.

Output
pergunta: quanto é o aluguel 1. score=0.8041 O locatário pagará aluguel mensal de $2,000.00 corrigido a 2. score=0.7739 Fica reajustado o valor do aluguel para $2,400.00 mensais. 3. score=0.7169 As partes se obrigam a manter sigilo pelo prazo de 5 anos. bound violations: 0 (must be 0) latency: 0.02 ms proof: every excluded document carries a Cauchy-Schwarz proof that it is not in the top-K (bound_violations == 0); recall vs exact scan: 99.6-100% with progressive configuration OK — the exclusion is proven, not estimated.
Reading the output

The first two hits answer the question directly — the original rent of $2,000.00 and the adjustment to $2,400.00. Read together they tell you the current rent is the second one; the first is history.

The third hit is the honest part. A confidentiality clause scored 0.7169 against a query about rent — it shares vocabulary ("prazo", "partes") and nothing else. Retrieval finds similar text, not correct text. The engine cannot know that a confidentiality clause is not an answer to a rent question; it only guarantees that nothing more similar was left out.

Three documents stayed behind, and the margin is visible. Their exact cosine scores are 0.6928 (medical report), 0.6893 (legal opinion) and 0.6442 (invoice). All three fall below the cut of 0.7169 — set by the confidentiality clause itself. Note how thin the first gap is: 0.6928 against 0.7169 is a difference of 0.024. That is precisely the situation where an approximate index drops a neighbour and nobody notices; here the bound is computed, not assumed.

The proof line reports recall of 99.6–100% against exact scan. This is where honesty matters: it is not stated as 100%. With k1_fraction=1.0 and postfilter the configuration is designed to guarantee recall, but the measured range across progressive configurations is 99.6% at the low end. The engine reports the range it actually measured rather than the best number it saw.

Download 07_sql_generic.py Open in Colab
08

RAG agent — wiring the engine into a pipeline

rag›

How to wire the engine into an existing RAG pipeline, including the system prompt that lets the model state the retrieval was proven complete.

Output
pergunta: qual o valor atual do aluguel contexto entregue ao modelo: [0.752] O aditivo primeiro altera o aluguel para $2,400.00 a partir de janeiro. [0.747] O aluguel mensal é de $2,000.00, corrigido anualmente pelo IGP-M. [0.739] A multa por rescisão antecipada é de três aluguéis. evidence for the audit log: documents excluded with proof : 3 bound violations : 0 latency : 0.02 ms system prompt in use: You answer questions using only the retrieved passages. If the answer is not in the passages, say so plainly — do not guess. The retrieval step is deterministic and carries a proof: every document that was NOT returned has been shown, by bound, to be irrelevant to this query. If a user asks why a specific document was not cited, the system can produce that proof. You may tell them this. OK — retrieval is wired, and it can answer the audit question.
Reading the output

The ordering is right, and that is the whole test. The question asks for the current rent. The addendum ("$2,400.00 a partir de janeiro") comes first at 0.7521; the original clause ("$2,000.00, corrigido pelo IGP-M") comes second at 0.7467. A model that reads only the second passage answers $2,000.00 — wrong, and confidently so. Retrieval order is what prevents that.

The third hit is a false positive you should expect. "A multa por rescisão é de três aluguéis" scores 0.7391 for a question about rent — near-miss vocabulary ("aluguéis") and nothing else. The demo encoder hashes characters, so it cannot tell a penalty clause from a price clause. That is the encoder's limit, not the retrieval's.

The cut fell at 0.7391, excluding three documents at 0.7028, 0.6796 and 0.6517. The margin above the cut is comfortable here (0.036), unlike example 07 where it was 0.024 — a reminder that the guarantee is only as strong as the gap the query produces.

The system prompt is the point

The retrieval block handed to the model carries an evidence section. That is what allows the prompt to say "the system can produce that proof" — because the proof exists in the payload, not because the prompt asserts it. A model told to claim completeness without evidence produces the same sentence with a hallucination underneath it.

What the prompt does not do is check the answer. Nothing here verifies that the model said $2,400.00 instead of $2,000.00 — the example shows retrieval wiring, not answer validation. Anyone deploying this still owns that last step.

Download 08_rag_agent.py Open in Colab
20

The full pipeline — question to audited answer

pipeline›

Example 08 builds the context and stops. This one goes all the way: a real question, a real user, a real database, a real LLM, and an evidence record that can be re-verified afterwards. Ten stages, no gaps. The corpus is 704 clinical records downloaded from Kaggle — not synthetic text.

The ten stages
 1. receive the question        request_id, token, timestamp
 2. authenticate the user       token -> identity + role
 3. query the database          role filter applied BEFORE indexing
 4. retrieve with proof         Madhava, bound_violations = 0
 5. build the context           4 passages, each with a score
 6. call the LLM                DeepSeek, prompt restricted to context
 7. validate the answer         citations + traceable numbers
 8. record the request          everything in one canonical dict
 9. generate the evidence       Ed25519 + WORM
10. verify afterwards           signature + chain + context hash
Output
1. RECEIVE THE QUESTION request_id : REQ-1793902945 pergunta : Estou com sede constante e muito cansado, mas meu exame de g... 2. AUTHENTICATE THE USER user : PAC-4471 role : patient may see : ['patient', 'public'] 3. QUERY THE DATABASE source : Kaggle — health-qa (704 real records) records : 704 indexed : 200 (after role filter) 4. RETRIEVE DOCUMENTS (with bound) encoder : multilingual-MiniLM-L12-v2 (384 dims) top-k : 4 violations : 0 latency : 0.17 ms 5. BUILD THE CONTEXT passages : 4 chars : 1678 top score : 0.775 6. CALL THE LLM model : deepseek-chat answer : Persistent thirst and tiredness, even with glucose normal at the time of the test, are worth raising with your doctor, as they may relate to factors beyond glucose alone... 7. VALIDATE THE ANSWER citations : ['1'] numbers : all trace back to the context result : VALID 8. RECORD THE REQUEST 9. GENERATE THE EVIDENCE signature : Ed25519 (3b6a27bcceb6a42d62a3a8d0...) WORM hash : 18ffc09c217cbf0a594df247a67f972a... size : 1233 bytes 10. VERIFY THE AUDIT AFTERWARDS signature : VALID (Ed25519 signature + integrity hash verified) chain : INTACT (1 block, sha3_256) context : matches answer : Persistent thirst and tiredness, even with glucose nor...
The decision that made this work

Indexing only the response, not the instruction. The Kaggle dataset repeats the same system prompt in the instruction column of all 704 rows. Indexing instruction + output makes every document look alike — top score 0.45 and the top-4 is arbitrary. Indexing the response alone lifts the top score to 0.775 and the first result is the correct clinical case: persistent thirst with normal glucose.

The multilingual encoder. The corpus is in English, the question in Portuguese. all-MiniLM-L6-v2 returns 0.198 and an essentially random top-1. The multilingual variant returns 0.402 on the same data — and 0.775 once the repeated system prompt is out of the index.

Both fixes were found by running it, not by reading the docs. The first version of this example returned 0.199 and the LLM correctly answered "the passages do not contain this information". The pipeline was working; the retrieval was not.

What the validation actually checks

Citations must point at passages that exist. The regex finds [N] and rejects any N outside 1..4.

Numbers must trace back to the context. Any figure in the answer that does not appear in the retrieved passages is flagged — that is where fabricated dosages and values surface.

Abstention is recorded, not penalised. When the LLM says it cannot answer, that is a valid outcome and it gets logged as such.

What this pipeline does not prove

It does not catch hallucination without numbers or citations. The validation checks citations and figures. A confidently wrong sentence with neither passes. Catching that needs human review or a second model — this example is explicit about the limit rather than implying the answer is verified.

It does not prove clinical correctness. The dataset is synthetic and this is not a medical device. The example is a pipeline demonstration, not medical advice.

Without DEEPSEEK_API_KEY the example does not invent an answer. It falls back to the top retrieved passage and marks the LLM as unavailable — faking a response would be worse than failing loudly.

Download 20_pipeline_completo.py
06

Agent memory that can be audited

agent memory›

An agent that remembers past interactions is only as trustworthy as its ability to recall them. If memory silently drops a past instruction, the agent behaves unpredictably and nobody can explain why. This example builds an append-only memory where every write is indexed and every recall carries proof of what was not recalled — the difference between "the agent forgot" and "the agent can demonstrate this memory was not relevant".

The interface
class AuditableMemory:
    def remember(self, texto, **meta): ...   # append + rebuild
    def recall(self, query, k=3): ...   # memories + proof
    def explain(self, query, alvo): ...  # why not recalled?
Output
query: quando posso contatar o cliente [0.909] (contexto) O cliente atua no setor hospitalar, em Portugal. [0.899] (preferencia) O cliente pediu para não ser contatado às sextas. evidence: total memories : 5 recalled : 2 excluded WITH PROOF : 3 bound violations : 0 latency : 0.02 ms why was it not recalled? (top-2, same as the recall above) 'O contrato vence em março de 2027.' não entrou no top-2: ficou em 5º de 5, score 0.817 contra corte 0.899. Exclusão com prova — não um esquecimento. 'O cliente prefere respostas curtas, sem ' não entrou no top-2: ficou em 4º de 5, score 0.839 contra corte 0.899.
Reading the output

Why the recall returned "hospitalar, Portugal" for the question "when can I contact the client". The demo embedding hashes characters, so it matches on vocabulary rather than meaning. "Cliente" appears in both, and the Portugal memory shares the most characters with the query. That is a limitation of the demo encoder, not of the retrieval — swap embed() for a real model and the ranking reflects meaning.

The second hit is the one that matters in production. "Não ser contatado às sextas" is the memory an agent must never lose — a missed preference is a broken commitment. It came second with score 0.899, above the cut.

The two explanations are the point of the example. The contract memory scored 0.817 against a cut of 0.899 — it lost by 0.082, and the output says so. An agent that prints "memory not found" tells you nothing; an agent that prints "5th of 5, score 0.817, cut 0.899" lets you decide whether the embedding is good enough.

Notice that the preference about short answers also fell out — 4th place at 0.839. In a real deployment that is a signal: if your encoder cannot separate "answer briefly" from "when can I call", the threshold needs tuning before it costs you a client.

Why fast rebuild makes this viable

Every remember() rebuilds the index — which sounds expensive until you look at the numbers. A 1M-vector index builds in 1.69 s against 33.6 s for HNSW on the same corpus. Agent memory can grow in real time without the guarantee degrading or the write path blocking.

Download 06_agent_memory.py Open in Colab
15

Normalize — providers, L2 contract and drift

normalize›

Applies the L2 unit-norm contract by hand, shows validation rejecting NaN and wrong dimensions, and demonstrates drift detection with an embedding fingerprint.

Output
provider padrão : qwen3 dimensão : 384 normaliza L2 : True valida NaN : True norma antes : min=89.74 max=106.86 norma depois : min=1.0000 max=1.0000 contrato L2 satisfeito — todo vetor unitário validação de entrada: [aceito] vetores válidos [recusado] com NaN — ValueError [recusado] dimensão errada — ValueError detecção de drift: [sem flag] mesmo espaço [embedding.provider_drift] espaço deslocado: provider openai drifted: batch-centroid cosine 0.045 (< 0.8) vs the previous batch
Reading the output

The norms before are ~90 to 107, after they are exactly 1. Cosine similarity is invariant to that scaling, so the rescaling changes nothing about ranking — what it changes is that the Cauchy–Schwarz bound becomes tight and cheap to compute. An unnormalized corpus still gives correct answers, just with a looser bound and more work per query.

The two rejections are the reason this package exists. A zero vector passes silently through almost every production pipeline: no error, no log line, and the proof stays "valid" over garbage. The NaN case is worse — the bound arithmetic produces NaN, comparisons with NaN are always false, and a document that should have been excluded silently survives every check.

Drift at cosine 0.045 against a 0.8 threshold means the space moved almost completely. Both fingerprints claim the same provider ("openai") and the same dimension (384) — so a schema check would pass. Only the centroid comparison catches it. That is the scenario where a provider silently upgrades a model behind a stable endpoint name, and every query afterwards returns plausible neighbours from an incompatible space.

The seed is fixed at 15 so these numbers are reproducible. Without it the norms and the drift cosine change on every run, and the output you see would never match the page.

Download 15_normalize_providers.py Open in Colab
01

Law firm — e-discovery with provable completeness

legal›

A litigation support database holds custodial documents. Counsel must produce the responsive set and certify nothing was missed — under penalty of sanctions for spoliation. Every platform returns documents; none can show that the withheld set was correctly excluded.

The example loads seven custodial documents into SQLite (the shape Relativity, Everlaw and Concordance all use), withholds the privileged one before indexing, and produces a certificate listing both the production set and the withheld set with proof.

Schema
CREATE TABLE documents (
    doc_id     TEXT PRIMARY KEY,
    custodian  TEXT,
    doc_date   TEXT,
    file_type  TEXT,
    subject    TEXT,
    body       TEXT,
    privilege  INTEGER DEFAULT 0
)
Output — the counts
documents in database : 7 privileged withheld : 1 indexed for search : 6

The count that matters most. Seven documents exist. One was withheld before indexing — the privileged employment contract. That is the first duty in a production review: privileged material must never enter a searchable index, not even one that is later deleted. Only six documents were indexed.

Output — the responsive set
responsive documents: 1. [0.742] DOC-0001 Re: Contrato de Fornecimento - Cláusula 7 2. [0.577] DOC-0004 Conciliação de multas Q1 2024 3. [0.477] DOC-0002 Re: Contrato de Fornecimento - prazo

Why these three and not the others. The query was "multa por atraso na entrega conforme cláusula contratual". The three returned documents are the ones that mention the delay penalty: the original contract clause, the accounting reconciliation of the paid fine, and the internal disagreement about the deadline.

The score column is the cosine similarity. It is shown here because the scores field of the result comes back as zeros in version 1.9.23 — the ordering is correct, the score column is not populated. The example recomputes it so the output is readable.

Output — the certificate
─── production certificate ─── production set : ['DOC-0001', 'DOC-0004', 'DOC-0002'] withheld as irrelevant : ['DOC-0003', 'DOC-0005', 'DOC-0007'] bound violations : 0 (must be 0)

This is the part a court can check. Three documents go to the opposing party. Three stay back — and for each one the engine computed a Cauchy–Schwarz upper bound below 0.477, the score of the third responsive document. That means DOC-0003, DOC-0005 and DOC-0007 could not belong in the responsive set for this query.

Notice what is in the withheld set: the board minutes approving a $48,000 payment, the 2024 vacation policy, and an invoice. The board minutes are arguably relevant to the dispute — which is exactly the point. The engine says they are not similar to this query, and it says so with arithmetic rather than a similarity score. If counsel disagrees, they can query differently; what they cannot say is that the search silently lost something.

What this example does not prove

It proves the exclusion is mathematically sound for this query on this corpus. It does not prove the corpus was complete, that the custodian collection was exhaustive, or that the query captured every legal theory. Those are human obligations. The engine only certifies what it searched.

Download 01_juridico_ediscovery.py Open in Colab
02

Hospital — the record that justifies a bill

health›

An insurer denies a claim. The revenue cycle team has 30 days to produce the clinical documentation proving the procedure was justified, or the revenue is written off. The documentation exists in the EHR — the question is whether the search finds it, and whether anyone can tell the difference between "no record found" and "no record exists".

The example loads clinical notes in the table layout Cerner, Epic, MV and Tasy all use, indexes the notes for one patient under dispute, and produces the statement the hospital sends to the payer.

Schema
CREATE TABLE notas_clinicas (
    id                INTEGER PRIMARY KEY,
    paciente_id       TEXT,
    data_atendimento  TEXT,
    tipo              TEXT,      -- evolução, descrição cirúrgica, sumário
    profissional      TEXT,
    texto             TEXT
)
Output — the record size
patient under dispute : PAC-4471 clinical notes on file: 4

Start with the number four. This patient has four clinical notes in the record. Not four hundred — four. That is realistic for a single admission, and it is the size at which the bound costs almost nothing (0.02 ms). The question is not whether the search is fast; it is whether the appeal can cite every note that supports the bill.

Output — the documentation produced
insurer's question: justificativa clínica para videolaparoscopia documentation produced: 1. [0.558] descrição cirúrgica de 2026-03-02 2. [0.467] evolução de 2026-03-02 3. [0.466] sumário de alta de 2026-03-05

Why these three, in this order. The surgical description scores highest because it names the procedure directly — "apendicectomia videolaparoscópica". It is the document that answers the insurer's question in one line.

The first-day progress note comes second: it records the clinical reasoning that justified operating — pain for 18 hours, fever, raised white count, Blumberg sign. That is the medical necessity argument.

The discharge summary comes third: the final diagnosis, written after the fact, confirming what was done.

Notice the scores cluster tightly (0.558 to 0.466). That is expected in short clinical notes with overlapping vocabulary — and it is exactly the situation where an approximate index drops a neighbour without anyone noticing.

Output — what was excluded
notes supporting the procedure : 3 notes excluded with proof : 1 bound violations : 0

The one note that stays behind — and why it is provable. The excluded note is the 2026-03-04 post-operative progress note. It describes recovery, not justification for surgery. The engine computed its upper bound and found it below 0.466 — it could not belong in the top-3 for a query about the indication.

This distinction matters in an appeal. The hospital is not saying "we chose not to send that note". It is saying the note is not responsive to this question, and the arithmetic proves it.

The sentence that wins the appeal
"Of the 4 notes in this patient's record, 3 were identified as supporting the procedure, and the remaining 1 were excluded on the basis of a mathematical bound proving they are not responsive to this query."

An approximate search returns the same three notes and cannot write the second half of that sentence. When the payer challenges the search — and auditors do — the hospital has evidence rather than assurance.

What this example does not prove

It proves the exclusion is sound for this query on this patient's notes. It does not prove the documentation is clinically sufficient, that the coding was correct, or that the payer will accept the appeal. Those are human judgements. The engine only certifies what it searched.

Download 02_saude_prontuario.py Open in Colab
03

Bank — reconstructing a credit decision for the regulator

finance›

A credit application is denied. The applicant invokes their right to review under LGPD art. 20 / GDPR art. 22, and the regulator asks the bank to reconstruct the grounds. The bank must show which policies applied — and that no policy was missed.

This is the case where approximate search becomes a liability: if the retrieval misses the exception clause that would have approved the application, the bank denied credit on incomplete grounds and cannot demonstrate otherwise.

Schema
CREATE TABLE politicas_credito (
    codigo        TEXT PRIMARY KEY,
    vigencia      TEXT,
    categoria     TEXT,     -- limite, garantia, exceção, restrição
    titulo        TEXT,
    texto         TEXT,
    aprovado_por  TEXT
)
Output — denial at 33% commitment, 7-year relationship
application : PROP-2026-03-4471 income : $18,000.00 payment : $5,940.00 commitment : 33.0% relationship : 7 years decision : NEGADO regulatory query: comprometimento de renda 33% cliente com 7 anos de relacionamento operação sem garantia real policy that governs this decision: 1. [0.818] POL-0187 (garantia) Operações com garantia real 2. [0.813] PRE-0088 (precedente) Caso semelhante - comprometimento de 33% 3. [0.801] POL-0203 (exceção) Política de exceção para relacionamento 4. [0.713] POL-0142 (limite) Comprometimento de renda máximo ─── supervisory response record ─── policies considered applicable : ['POL-0187', 'PRE-0088', 'POL-0203', 'POL-0142'] policies excluded with proof : ['POL-0115', 'POL-0264'] bound violations : 0 latency : 0.03 ms
Reading the output

The four returned clauses are the whole argument, in order. POL-0187 comes first because the operation exceeds $100,000 with no real guarantee — the query says so explicitly. PRE-0088 next: it is the precedent, a client approved at exactly 33% commitment. POL-0203 third: the exception clause that allows up to 35%.

POL-0142 — the 30% cap — comes last, and that is the correct ranking. It is the rule that was applied, but it is the least specific to this applicant's situation. The three above it are the reasons the rule might not apply.

Only two policies were excluded, and both for good reason: POL-0115 covers active credit-bureau restrictions — this applicant has none. POL-0264 covers income documentation for self-employed applicants — not the case here. The engine bounded both out below 0.713 and can show the arithmetic.

0.03 ms for six policies. The cost is not the point at this size. What the bank is buying is the sentence in the supervisory record: two policies were examined and excluded with proof, not merely skipped.

What the reconstruction reveals

POL-0203 allows up to 35% commitment for clients with more than five years of relationship and no active restriction. The applicant has seven years, no restriction, and 33% commitment.

The retrieval surfaces it — and proves no other policy in the repository is responsive. Whether the denial was correct is a credit judgement; whether it was made on a complete reading of policy is now on the record.

These three use demo embeddings

01, 02 and 03 use a deterministic hash embedding so they run with no API key. Swap embed() for a domain encoder before measuring anything — the retrieval logic does not change, but the quality of the result will.

Download 03_financeiro_credito.py Open in Colab
09

Tracer-MED — hospital audit trail

audit · health›

A medical audit service holds 400 reports. The query "apendicite" returns two, and the engine produces a signed record of what it examined and what it excluded.

Output
reports in corpus : 400 reports found : 2 excluded with proof : 17 threshold global : 0.3938 guarantee : exact_global bound violations : 0 exclusion record (sample): doc 13: bound=0.3854 excluído=True doc 38: bound=0.3913 excluído=True doc 89: bound=0.3876 excluído=True OK — busca com garantia global e trilha de auditoria registrada.
Reading the output — the number that needs explaining

17 excluded out of 400 looks wrong at first. If the answer is meant to be complete, why only 17? The answer is in a field this example does not print. Running the same query in audited mode returns bound_pairs: 400 — all 400 documents were examined. The 17 are the ones the bound alone proved outside the top-2. The other 381 were not excluded by the bound; they were resolved by exact score comparison in the postfilter and simply ranked below the cut.

That is why exact_global holds with only 17. The guarantee comes from the postfilter comparing every candidate exactly — not from the bound firing on all of them. The bound is a pruning accelerator; the exact comparison is the proof. A corpus where the bound never fires still returns an exact top-K.

Verified against brute force: this example's top-2 ([1, 301], both at 0.3938) is byte-identical to what a full cosine scan returns. The engine is not approximating here.

What the guarantee level means

exact_global means the returned top-K is proven to be the global top-K, not merely the best within a truncated candidate pool. The recall_not_guaranteed flag from example 05 fires when a configuration can only offer pool_only — that is the case where this claim would be false.

The threshold of 0.3938 is the exact score of the second result, not a user-chosen cutoff. It is derived, and it moves with the query.

Each sampled record carries the bound computed for that document — 0.3854, 0.3913, 0.3876, all below 0.3938. That is the arithmetic an auditor re-runs. The sample is boundary-biased on purpose: it shows the documents closest to slipping through, which are the ones worth spot-checking.

Why this demo corpus is unusually flat

The 400 reports are built from only 10 distinct findings, so many share near-identical embeddings and the top scores cluster at 0.3935–0.3938. On a real corpus with varied vocabulary the bound fires far more often and the threshold sits at a clearly separated value. The low exclusion count here is a property of the synthetic data, not of the engine.

Download 09_tracer_med_auditoria.py Open in Colab
10

Tracer-GOV — procurement audit

audit · public sector›

A court of accounts scans 600 procurement processes for emergency dispensations lacking justification.

Output
processes scanned : 600 processes returned : 5 excluded with proof : 509 guarantee : exact_global bound violations : 0 flagged processes: PROC-0544 dispensa de licitação por emergência em unidade de saúde PROC-0541 dispensa de licitação por emergência em unidade de saúde PROC-0145 dispensa de licitação por emergência em unidade de saúde OK — varredura de 600 processos com prova de completude.
The number that decides whether this is a real audit

73 of the 600 processes are emergency dispensations. They were generated from a fixed list of eight procurement types, and one of those types appears 73 times. The query was written to find exactly them.

With k=5 the example returns 5 of those 73. The engine is not wrong — the top-5 really is the top-5, verified identical to a brute-force scan. But a court of accounts that reads five processes and declares the audit complete has examined 7% of the matches. exact_global does not mean "I found everything relevant"; it means "the five I returned are provably the five closest, and the other 595 are provably further away".

Set k=73 and the answer changes completely: all 73 emergency processes come back, ranked 1 through 73. The guarantee was already exact at k=5 — the parameter that decides coverage is k, and it is the analyst's responsibility, not the engine's.

The honest limit of this example

The query "dispensa de licitação por emergência sem justificativa" asks about a condition — missing justification — that does not exist in the corpus at all. Every process carries only its procurement type. So the ranking is by textual similarity to the procurement type, and the result is "these are emergency dispensations", not "these are unjustified emergency dispensations". Proving the second would require the justification documents themselves to be indexed. The engine certifies what it searched; it cannot certify a fact the corpus never recorded.

Download 10_tracer_gov_licitacao.py Open in Colab
11

Tracer-JUS — contract due diligence

audit · legal›

500 contract clauses searched for early-termination risk. The point is proving no risky clause was omitted — and this example is where that claim needs the most care.

Output
clauses in repository : 500 clauses at risk : 4 excluded with proof : 305 guarantee : exact_global bound violations : 0 clauses requiring attention: CLA-0116 cláusula de rescisão antecipada com multa proporcional ao prazo CLA-0162 cláusula de rescisão antecipada com multa proporcional ao prazo CLA-0132 cláusula de rescisão antecipada com multa proporcional ao prazo warning — what k=4 means here: termination clauses in repository : 54 returned with k=4 : 4 NOT examined : 50 returned with engine k=54 : 54 OK — top-4 exato e comprovado. A cobertura é decisão do analista.
The claim this example cannot make with k=4

54 of the 500 clauses are early-termination clauses. The query was written to find them. With k=4 the example returns 4 — so 50 of the 54 risk clauses are never shown to the analyst.

The engine is not wrong. The top-4 is provably the exact top-4; that part is verified. What exact_global certifies is narrower than it sounds: the four I returned are correct, and the other 496 are provably further away. It does not certify that four is all there is.

An earlier draft of this page ended with "prova de que nenhuma cláusula de risco foi omitida". That sentence was false — the run omitted 50 of them. The example now prints the real count and the gap before it says anything about completeness.

A trap in the API: k is a ceiling set at build time

k is fixed in build_engine. Asking for a larger k in retrieve does not raise the limit — it is truncated silently, with no error and no warning. Verified: an engine built with k=4 returns 4 results when you call retrieve(k=54).

To widen coverage you must rebuild the index with the larger k. The example demonstrates both paths so the difference is visible: 4 results from the original engine, 54 from a rebuilt one. For a due-diligence claim of completeness, size the index to the number of matching documents you expect, not to the number of pages in the report.

Download 11_tracer_jus_contratos.py Open in Colab
12

Tracer-GAP — financial reconciliation

audit · finance›

800 accounting entries in a period with a discrepancy. Internal audit asks which entries lack supporting documentation — and this example shows a failure mode worth more than the result itself.

Output
entries in period : 800 suspicious entries : 5 excluded with proof : 62 guarantee : exact_global bound violations : 0 entries for review: LAN-00733 transferência entre contas sem documento de suporte anexado LAN-00456 transferência entre contas sem documento de suporte anexado LAN-00753 transferência entre contas sem documento de suporte anexado OK — 800 lançamentos varridos, exclusões provadas, nenhum omitido.
Output — what the "ou" hides
what the 'or' hides: condition A — provision without write-off : 95 entries condition B — missing supporting document : 106 entries combined query returns: LAN-00733 transferência entre contas sem documento de suporte anex LAN-00456 transferência entre contas sem documento de suporte anex LAN-00753 transferência entre contas sem documento de suporte anex LAN-00711 transferência entre contas sem documento de suporte anex LAN-00755 transferência entre contas sem documento de suporte anex query A alone returns: LAN-00536 provisão trabalhista sem correspondência na folha LAN-00791 provisão trabalhista sem correspondência na folha LAN-00781 provisão trabalhista sem correspondência na folha LAN-00136 provisão trabalhista sem correspondência na folha LAN-00796 provisão trabalhista sem correspondência na folha
The failure mode: "ou" is not a union

The query was "provisão sem baixa ou documento de suporte". That asks two separate questions: 95 entries have provisions without write-off, 106 lack supporting documentation. An internal auditor reading that query wants both sets.

The combined query returned zero provisions. Not one of the five results came from condition A. All five are condition B. The embedding added both sides of the "ou" into a single vector and the result is a weighted average — and the average sits closer to the larger, longer, more token-dense condition.

This is not a bug in the engine. The top-5 is provably the exact top-5 for that vector. The bug is in translating a boolean query into a single embedding. Vector search has no set semantics: "A or B" is not A ∪ B, and "A and not B" is not representable at all.

The fix is two searches. One per condition, then union the document IDs. The example now demonstrates both and prints the difference, because an auditor who trusts the combined query would sign off having reviewed only half the risk.

And the same coverage caveat as examples 10 and 11

With k=5 you see 5 of the 106 entries lacking documentation, and 0 of the 95 provisions. exact_global certifies that those five are the five closest — it does not certify that five is all there is. For a reconciliation claim, size k at build time to the number of matches you expect, and run one query per condition.

Download 12_tracer_gap_financeiro.py Open in Colab
18

The audit record an engine cannot forge

signature›

The bound proves the top-K is right. But what stops a compromised engine from signing "I excluded 15,508 documents" when it excluded 40? This example closes that hole: sign with Ed25519 using a key held outside the engine, verify, tamper, verify again.

Output
corpus : 600 laudos chave pública : 3b6a27bcceb6a42d62a3a8d02a6f0d73... registro gerado para a query 'apendicite com indicação cirúrgica' audit_id : AUD-2026-0001 total_excluído : 516 threshold global : 0.7517 tamanho do registro: 4347 bytes verificação do registro original status : VALID motivo : Ed25519 signature + integrity hash verified o ataque — adulterar o contador contador original : 516 contador adulterado: 0 verificação do registro adulterado status : INVALID motivo : Ed25519 signature invalid (tampered) verificação com chave pública de outro emissor status : INVALID motivo : Ed25519 signature invalid (tampered)
Reading the output

The record is 4,347 bytes — not the full certificate. It carries the count, the threshold, a boundary sample of excluded documents, an integrity hash and the Ed25519 signature. That is small enough to store one per query in a WORM for years.

Changing 516 to 0 breaks the signature. Not the hash check, not a validation rule — the signature itself. The engine cannot rewrite its own past even if the whole binary is compromised, because the private key never lived inside it.

The third block is a different failure. The record is untouched; the verifier is using another issuer's public key. An auditor needs to tell "this document was altered" apart from "this is not the issuer's key" — both come back INVALID, and the reason string is what distinguishes them.

What this does not prove

It does not prove the search was good — only that the record of what the search did was not altered afterwards. Encoder quality is example 17.

It does not prove the corpus was complete. A document that was never indexed appears in no counter and no proof. The engine certifies what it searched, nothing more.

The private key here is fixed at "00"*32 so the example runs anywhere. In production it comes from a KMS or HSM. If it leaks, every record loses its value — the security is only as good as the key's vault.

Download 18_tracer_assinatura.py
19

A log that proves it was not rewritten

worm›

Example 18 shows a single signed record cannot be altered. But what if someone deletes an entire line from the history? A per-record signature does not detect absence. So the records chain: each one carries the SHA3-256 hash of the previous. Remove one from the middle and the chain breaks — and the verifier says exactly where.

Output
writing 6 signed records to WORM record 1 AUD-0001 hash=8b90d8d90cbf657e... record 2 AUD-0002 hash=f4163612ab33571f... previous=8b90d8d90cbf657e... record 3 AUD-0003 hash=7f7decd5b7d58a07... previous=f4163612ab33571f... record 4 AUD-0004 hash=5072a19a2801fba1... previous=7f7decd5b7d58a07... record 5 AUD-0005 hash=5bad98d3d4319c88... previous=5072a19a2801fba1... record 6 AUD-0006 hash=efa38c40b48fad31... previous=5bad98d3d4319c88... chain verification blocks : 6 algorithm : sha3_256 violations : 0 integrity : INTACT the attack — delete AUD-0004 from the middle of the chain records before : 6 records after : 5 removed : AUD-0004 (block 4) verification after removal blocks : 5 violations : 1 integrity : BROKEN → {'block': 3, 'expected_prev': '7f7decd5b7d58a07...', 'found_prev': '5072a19a2801fba1...'}
Reading the output

Every record points at the one before it. Record 3 carries the hash of record 2, record 4 carries record 3, and so on. That is the chain — not a list with signatures attached, but a structure where each element commits to its predecessor.

Deleting AUD-0004 breaks the link, not the signature. Records 1, 2, 3, 5 and 6 are each still individually valid — their Ed25519 signatures verify. What fails is the chain: record 5 says its predecessor was 5072a19a… and the verifier finds 7f7decd5… in its place. That mismatch is the evidence of removal.

The report localises the break. It does not say "something is wrong" — it names the block, the hash it expected and the hash it found. An auditor can point at the exact position in the history where the record was removed.

What this does not prove

Truncation from the end. If an attacker deletes the last records, the remaining chain is still internally valid. Detecting that requires an external anchor — the daily hash published elsewhere, a timestamp authority, or another system holding the head of the chain. This example does not implement one.

That the search was good. Only that the history of what it did was not altered or truncated in the middle.

The chain is only as strong as the key. It is fixed at "00"*32 here so the example runs anywhere. In production it comes from a KMS or HSM.

Download 19_worm_integridade.py
13

X-Factor — manifold projection from weights

embedding›

Derives the subspace where a model's token embeddings live, without training and without running the model — and measures the same method on data where the answer is known.

Output
embedding table : 4,000 tokens x 256 dims manifold basis : (256, 256) (rank efetivo 236) residual : 0.9521 (variância preservada) controle — dados com rank latente 40: rank efetivo derivado : 36 de 256 residual : 0.9602 redução de dimensão : 256 -> 36 (7.1x menor) foldable @ k=128 : False original : (3, 256) projetado : (3, 256) busca no subespaço: 3 results bound violations : 0
Reading the output — the control is the point

Two measurements, two different data sets. The first block uses pure gaussian noise: rank 236 of 256, and the projection returns the full vector. Noise has no low-dimensional structure, so there is nothing to find.

The control block answers the question that matters: does the method work at all? Same code, same vocabulary size, but the data generated from 40 latent factors. Result: rank 36 of 256 — a 7.1× reduction, with 96% of variance preserved.

Without the control, this example would be a failure report. Reading only the noise result, you cannot tell whether X-Factor is broken or whether the input has no structure. The control separates the two.

Why the demo cannot show reduction on "real-looking" numbers

The reduction depends entirely on the input having low-rank structure. Synthetic randn(V, D) is full-rank by construction — no method can compress it without losing information, and any example claiming otherwise would be measuring noise.

Real token embeddings do have this structure. To see it on actual weights:

from transformers import AutoModel
E = AutoModel.from_pretrained("<model>").get_input_embeddings().weight.detach().numpy()
P, rank, residual = xf.build_xfactor(E, variance_tau=0.95)

X-Factor does not invent structure; it finds it when it exists. Example 14 covers the inference engine that consumes the folded matrices.

Download 13_xfactor_manifold.py Open in Colab
14

Nano — tokenizer and weight blending

inference›

Two components that run with no model download: the deterministic spectral tokenizer — perfect round-trip across five languages, including accents and Japanese — and the weight balancer that fuses two models without gradients.

Output
round-trip test (encode then decode must be identical) [OK ] 576 estados 'Winnex AI' -> 'Winnex AI' [OK ] 1344 estados 'Contrato de locação' -> 'Contrato de locação' [OK ] 1472 estados 'Paciente com febre alta' -> 'Paciente com febre alta' [OK ] 2560 estados 'Ñoño café — acentuação preservada' -> idêntico [OK ] 1344 estados '日本語のテスト' -> idêntico 5 frases, 0 falhas de round-trip. weight blending modelo A (70%): [1.0, 2.0, 3.0, 4.0] modelo B (30%): [10.0, 20.0, 30.0, 40.0] fundido : [3.700000047683716, 7.400000095367432, ...] esperado : [3.7, 7.4, 11.1, 14.8] custo medido, não estimado: texto : 1,920 chars, 1,960 bytes UTF-8 estados gerados : 125,440 expansão : 64 estados por byte (BPE típico: ~0,3 token por byte) encode : 18.11 ms (106,041 chars/s)
Reading the output

The round-trip is exact across five scripts, including Portuguese diacritics and Japanese — with no vocabulary file and no training. That is the actual claim, and it holds.

The state counts are the number to look at. 576 states for 9 characters is 64 per character. That is not a coincidence: the tokenizer emits embed_dim states per UTF-8 byte, so embed_dim=64 means 64× expansion by construction. At 1,960 bytes the text produced 125,440 states.

Compare that to a trained BPE: roughly 0.3 token per byte. This is about 213× less compact — the "about 1000×" figure in earlier drafts was in the right order of magnitude but never measured. The example now prints the real ratio.

The weight blend is trivially correct by inspection: 0.7·1 + 0.3·10 = 3.7. The float32 values print as 3.700000047683716 because that is the nearest representable float32, and the example compares with rel_tol=1e-6 rather than equality — the right way to check a float computation.

What this example does not run — and the docs should say so

This is the tokenizer and the balancer. It does not run ForwardEngine, the inference path that is bit-exact with Transformers on the same weights. None of the 17 examples here executes inference — that needs model weights and a GPU or OpenCL device, which do not belong in a 30-second Colab cell.

An earlier draft of this page pointed to "example 15" for that path. Example 15 is about winnex-ai-normalize, not inference — the reference was wrong and is now removed. For the inference path, see the winnex-nano section of the main documentation.

Download 14_nano_tokenizer.py Open in Colab
16

Build speed across corpus sizes

streaming›

Measures build time from 1,000 to 200,000 vectors and compares query latency against brute force — on the machine you are actually running it on.

Output — Colab CPU
corpus build per 1k docs ────────────────────────────────────── 1,000 10.9 ms 10.90 ms 10,000 82.4 ms 8.24 ms 50,000 413.2 ms 8.26 ms 200,000 1369.0 ms 6.85 ms Do outro lado: latência de query ────────────────────────────────────── corpus madhava brute force 1,000 0.29 ms 4.67 ms 10,000 1.31 ms 5.93 ms 50,000 5.03 ms 10.11 ms 200,000 48.22 ms 66.07 ms
Output — the same script on an i7-14700F
corpus build per 1k docs 1,000 3.9 ms 3.87 ms 10,000 19.4 ms 1.94 ms 50,000 89.7 ms 1.79 ms 200,000 237.9 ms 1.19 ms Do outro lado: latência de query ────────────────────────────────────── corpus madhava brute force 1,000 0.08 ms 0.12 ms 10,000 0.24 ms 25.23 ms 50,000 2.04 ms 25.87 ms 200,000 8.91 ms 21.80 ms
Why both are shown

The build is 5 to 6× faster on the local machine — 237,9 ms against 1369,0 ms at 200,000 vectors. Same code, same seed, different CPU. Any single benchmark number without a machine attached is close to meaningless, so the page shows both.

What holds on both machines is the shape of the curve: build cost per 1,000 documents falls as the corpus grows — 10,90 → 6,85 ms on Colab, 3,87 → 1,19 ms locally. Fixed overhead amortises; the build is linear in corpus size, not quadratic.

Query latency against brute force is a different story on each. On Colab, Madhava beats brute force at every size (48,22 ms against 66,07 ms at 200,000). Locally brute force wins above 10,000 vectors (8,91 ms against 21,80 ms) — the numpy BLAS path is simply faster on a wide desktop CPU than the bound scan.

That difference is worth stating plainly: the "Madhava is competitive with exact scan up to ~50,000 vectors" claim depends on the hardware. It holds on the Colab CPU and does not hold on a fast desktop. The guarantee is identical either way; the latency comparison is not.

The HNSW comparison is a published figure, not a measurement here

The script prints a hard-coded block — Madhava 1,45 s / IVF 15,62 s / HNSW 33,60 s on 99,800 vectors at 1536 dims — as a string literal. It does not run HNSW or IVF. Those numbers come from the published benchmark and are reproduced as text, which means anyone re-running this cell gets that comparison without it being recomputed on their machine.

What is measured on your machine is the build table and the query table above. Treat the HNSW block as a citation, not as something this cell verified.

Download 16_madhava_streaming.py Open in Colab