Understand weighted token expansion, inverted-list execution, exact-term safeguards and the real storage cost of sparse semantic search.
Learned sparse retrieval: weighted terms without dense-vector search
Represent meaning as weighted terms
Learned sparse retrieval maps a query and a passage to small sets of vocabulary terms with nonzero weights. A model may assign weight to a related term that never appeared literally in the passage. That expansion can bridge wording differences while retaining an inverted-index execution path. It is not ordinary keyword search: the weights and extra terms come from a model, so their meaning depends on its training data and version. It is also not a dense embedding, where nearly every vector coordinate is populated. Lexical analysis remains valuable for exact strings that a model might split or suppress.
Build postings for nonzero coordinates
At index time, write each nonzero passage coordinate to a posting list keyed by vocabulary term, with passage ID and weight. At query time, visit only lists for nonzero query coordinates and accumulate the products of query and passage weights. A term absent from either side contributes zero. Pruning tiny weights can reduce disk and query work, but aggressive pruning can remove the only bridge for a rare question. Measure posting-list length, index bytes and recall at a fixed latency target before choosing a pruning threshold.
Keep identifiers on a literal path
A model-generated term for an equipment family must not replace an exact serial number, ticket ID or regulatory clause. Preserve raw identifiers in a separately analyzed field, route identifier-heavy queries through a literal match, and fuse its candidates with the learned sparse list. Keep authorization and document-status filters before final ranking. Hybrid fusion can combine branches without pretending that BM25 and sparse-model scores share one scale. A model expansion is a recall aid; it is never permission to rewrite a user's stated identifier.
Version both sides of the match
Query and passage term weights must come from compatible model and vocabulary versions. If the query encoder changes while old passage postings remain, the same term ID may have a different role or weight distribution. Store model and tokenizer IDs with the index generation, and switch serving traffic only after a complete compatible build. A dual-index migration allows comparison of labeled query slices before cutover. Embedding migrations follow the same generation discipline even though the storage format differs.
Evaluate where expansion helps and hurts
Build judged slices for paraphrases, abbreviations, rare identifiers, multilingual text and adversarial keyword stuffing. Compare learned sparse retrieval against a lexical baseline and a dense branch at the same candidate budget, measuring recall, latency, index size and unsupported-answer rate. Inspect which expansion coordinates caused a false positive; human-readable terms make diagnosis possible, but a readable term does not prove semantic correctness. An answer still needs source evidence and a claim-level support check.
Worked contract
from collections import defaultdict
def sparse_candidates(query_weights: dict[str, float],
passage_weights: dict[str, dict[str, float]],
allowed_ids: set[str]) -> list[tuple[str, float]]:
postings = defaultdict(list)
for passage_id, weights in passage_weights.items():
if passage_id not in allowed_ids:
continue
for term, weight in weights.items():
if weight > 0:
postings[term].append((passage_id, weight))
scores = defaultdict(float)
for term, query_weight in query_weights.items():
if query_weight <= 0:
continue
for passage_id, passage_weight in postings.get(term, ()):
scores[passage_id] += query_weight * passage_weight
return sorted(scores.items(), key=lambda item: (-item[1], item[0]))
passages = {"pump-p47": {"seal": .8, "leak": .4},
"pump-p48": {"seal": .2, "motor": .9},
"private-plan": {"seal": 1.0}}
ranked = sparse_candidates({"seal": .6, "leak": .3}, passages,
{"pump-p47", "pump-p48"})
assert ranked == [("pump-p47", .6), ("pump-p48", .12)]Performance and operating cost
For an already built index, query work is proportional to the total posting entries visited for nonzero query terms, plus sorting or top-K selection over scored candidates. The demonstration rebuilds postings in O(W) time and O(W) space for W nonzero passage weights; a production index stores them once and pays that cost during ingestion. Model inference, larger expanded vocabularies and long posting lists can dominate latency. Compare end-to-end cost, not just the dot product.
Common Mistakes
- Calling model expansion a verified synonym dictionary.
- Pruning weights solely for index size without a rare-query recall test.
- Mixing query and passage encoders from incompatible generations.
- Letting an expanded term outrank a required exact identifier or bypass access filters.
Validation drill
On 43 judged maintenance questions, compare lexical, learned sparse and fused top-12 recall. Keep separate slices for serial IDs, paraphrases and terms seen in only one manual revision; report p95 latency and index bytes alongside recall.
