Neural sparse retrieval: learn weights in a vocabulary
神经稀疏检索
Train a tiny sparse map; compare pooling, expansion and the cost regularizer.
sparse-neural-retrievalA word can receive weight without appearing
The query says “bicycle”; a repair note says “cycle.” A strict word match sees different coordinates. A neural sparse retriever can learn to activate useful vocabulary coordinates that were absent from the input. It can then score with an inverted index, much like a lexical system, while the weights and expansions come from a learned model.
Sparse does not mean unlearned, and dense does not mean semantic by definition. Here “sparse” means that many coordinates are exactly zero; each output coordinate corresponds to a vocabulary token. A nonzero coordinate can be inspected, but seeing a token label does not prove the expansion is correct or explain every hidden computation. SPLADE uses a pretrained masked-language-model head to produce vocabulary logits, followed by nonnegative activation, aggregation and regularization. SPLADE, section 3.2
Keep the pooling version explicit
Let z_ij be the logit for output vocabulary coordinate j at input position i. The original SPLADE paper applies a rectifier followed by log saturation, then sums positions:
A negative logit contributes zero. A positive logit has a diminishing derivative, so increasing it does not increase weight linearly. SPLADE v2 proposes replacing the sum with a maximum; the earlier sum equation in its background section is not the proposed change. SPLADE v2, section 3.2
The vocabulary-space dot product permits an inverted index over nonzero document coordinates. A query visits lists for its active coordinates and accumulates weighted matches. Learned expansion can improve vocabulary overlap, but too many active coordinates make more postings eligible.
For nonempty positive set P_i, our toy training uses the probability of retrieving any known positive. This is a declared multi-positive extension, not a verbatim reproduction of the papers’ training recipe:
SPLADE discusses a FLOPS regularizer, a smooth cost-related surrogate built from squared mean coordinate weights. With N representations in a batch, write:
The papers allow separate query and document regularization strengths; our program sets both to the same λ to keep the comparison small. The penalty discourages coordinates with high average weight. It is not a direct measurement of hardware floating-point operations or every document’s nonzero count. SPLADE, section 3.2 SPLADE v2, section 3.1
Our separate work counter counts active query–document coordinate products across all fixture pairs:
The distinction is visible without training. Repeating row [2,0] gives surrogate 4 and one active coordinate per row. Repeating [1,1] gives surrogate 2 but two active coordinates. Both have row L1 norm 2. Smaller surrogate does not imply fewer active coordinates in every example.
For backpropagation, the positive branch of the activation has derivative 1/(1+z). The regularizer contributes the mean weight scaled by batch size:
At the rectifier kink we choose zero. Max pooling routes each coordinate’s gradient to the first maximizing input position, a declared subgradient rule. Repeated token IDs must accumulate their gradients rather than overwrite them.
Train a ten-coordinate dictionary
Use Python 3.12 and NumPy 1.26. Ten authored token IDs cover repair, bicycle, brake, cable, cycle, stopping, wire, car, cell and research. The three queries and nine simplified document fragments have positive sets {0,4,5,7}, {3} and {8}. Document 6 is empty. These fragments deliberately simplify the fuller corpus used by the neighboring retrieval examples; they are not a benchmark dataset.
A trainable 10×10 lookup table maps each input token to vocabulary logits. It starts from the identity plus seed-13 Gaussian noise. Max pooling follows log1p-ReLU. We run 400 full-batch gradient steps at learning rate 0.15, independently for λ=0,0.03,0.3. This is a context-free learned token map, with no Transformer, masked-language pretraining, mined hard negatives or distillation.
"""Original context-free sparse encoder: train vocabulary coordinates, not a language model."""
import json
import numpy as np
# Authored token IDs: repair=0, bicycle=1, brake=2, cable=3,
# cycle=4, stopping=5, wire=6, car=7, cell=8, research=9.
QUERIES=[[0,1,2,3],[7,2,0],[8,4,9]]
DOCS=[[0,1,2,3],[1,2],[1],[7,2,3,0],[4,5,6],[0,1,2,3,3,3],[],[2,3,1,0],[8,4,5,9]]
def encode(w, sequences, pooling='max'):
w=np.asarray(w,dtype=float)
if w.ndim!=2 or w.shape[0]!=w.shape[1] or not np.isfinite(w).all() or pooling not in ('sum','max'):
raise ValueError('finite square map and sum/max pooling required')
output=[];cache=[]
for seq in sequences:
if any(type(t) is not int or t<0 or t>=len(w) for t in seq):raise ValueError('token out of vocabulary')
if not seq:output.append(np.zeros(len(w)));cache.append(None);continue
z=w[seq];a=np.log1p(np.maximum(z,0));choice=np.argmax(a,axis=0)
output.append(a.sum(axis=0) if pooling=='sum' else a[choice,np.arange(len(w))])
cache.append((seq,z,choice))
return np.array(output),cache
def backward(w, cache, grad, pooling='max'):
result=np.zeros_like(w)
for row,item in zip(grad,cache):
if item is None:continue
seq,z,choice=item;g=np.broadcast_to(row,z.shape).copy()
if pooling=='max':g*=np.arange(len(seq))[:,None]==choice[None,:]
g*=np.where(z>0,1/(1+np.maximum(z,0)),0)
np.add.at(result,seq,g)
return result
def objective(w,regularization=.03):
if not np.isfinite(regularization) or regularization<0:raise ValueError('nonnegative regularization required')
q,cq=encode(w,QUERIES);d,cd=encode(w,DOCS);s=q@d.T
mask=np.zeros(s.shape,dtype=bool)
for i,ids in enumerate(([0,4,5,7],[3],[8])):mask[i,ids]=True
z=s-s.max(axis=1,keepdims=True);e=np.exp(z);p=e/e.sum(axis=1,keepdims=True)
positive=np.where(mask,s,-np.inf);shift=positive.max(axis=1,keepdims=True)
ep=np.exp(positive-shift);pp=ep/ep.sum(axis=1,keepdims=True)
rank=float(np.mean(s.max(axis=1,keepdims=True)+np.log(e.sum(axis=1,keepdims=True))-shift-np.log(ep.sum(axis=1,keepdims=True))))
gs=(p-pp)/len(q);mq=q.mean(axis=0);md=d.mean(axis=0)
penalty=float(mq@mq+md@md)
gq=gs@d+2*regularization*mq/len(q);gd=gs.T@q+2*regularization*md/len(d)
grad=backward(w,cq,gq)+backward(w,cd,gd)
return rank+regularization*penalty,grad,dict(rank_loss=rank,proxy=penalty,
active_query_coordinates=float(np.count_nonzero(q)/len(q)),
active_doc_coordinates=float(np.count_nonzero(d)/len(d)),
posting_products=int(np.sum((q>0).astype(int)@(d>0).astype(int).T)),
top1=np.argmax(s,axis=1).tolist())
def train(regularization,steps=400):
if type(steps) is not int or not 0<=steps<=2000:raise ValueError('steps in 0..2000 required')
w=np.random.default_rng(13).normal(0,.2,(10,10))+np.eye(10)
initial=objective(w,regularization)[0]
for _ in range(steps):
_,g,_=objective(w,regularization);w-=.15*g
loss,_,stats=objective(w,regularization)
return dict(regularization=regularization,initial_objective=initial,final_objective=loss,**stats)
def demo():
a=np.array([[2.,0],[2.,0]]);b=np.array([[1.,1],[1.,1]])
return dict(runs=[train(x) for x in [0.,.03,.3]],
counterexample=dict(l1=[2.,2.],proxy=[float((x.mean(axis=0)**2).sum()) for x in [a,b]],
active=[1,2]),
scope='Three training queries and nine simplified authored documents; context-free token map, not SPLADE reproduction.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
The three runs return training top documents [0,3,8]. Ranking loss rises from about 0.072373 without regularization to 0.350943 at λ=0.3, while the measured active products fall from 60 to 30; the middle run has 52. The regularized objective and the ranking loss are different quantities, so do not compare objectives with different λ as if they measured the same target. All observations are on the training fixture.
The encode function also supports sum pooling. Duplicating an identical input logit row doubles its sum contribution but leaves its max unchanged. In a real contextual encoder, repeating a token can change other logits, so this operator property does not prove full-model invariance to repeated text. Independent tests check both pooling gradients, the ranking-plus-regularizer gradient and the cost counterexample.
Sparse output does not make encoding free
This lookup implementation gathers O(TV) logits for T tokens and V vocabulary coordinates, with dense table storage O(V²). These are costs of the toy map. A contextual masked-language model has additional encoder and vocabulary-projection costs. Sparse retrieval reduces downstream scoring work only to the extent that representations and index execution exploit sparsity; our NumPy program still uses dense matrix multiplication.
Expansion may activate the wrong sense of a word, and strong regularization can suppress useful rare coordinates. Max pooling changes how repeated evidence is combined, not whether the evidence is true. Real evaluation needs held-out queries, index size, posting distributions, latency and relevance measures at a fixed cutoff. SPLADE v2 also investigates document-only encoding and distillation with hard negatives; those are distinct changes beyond replacing sum with max. SPLADE v2, sections 3.3–3.4
Inspect the coordinate, then the cost
- Can the output weight for “bicycle” be positive when the input contains only “cycle”?
Answer: Yes. The learned output coordinates need not be restricted to input tokens. That is expansion; whether this particular expansion is useful depends on context and the retrieval need.
- Duplicate a row with activated weights [0.4,0.2]. What changes under sum and max pooling?
Answer: Sum becomes [0.8,0.4], while max remains [0.4,0.2]. This holds for identical fixed activation rows, not necessarily for a contextual encoder after the input text changes.
- Compare repeated [2,0] rows with repeated [1,1] rows under the regularizer.
Answer: The proxies are 2²=4 and 1²+1²=2, while active coordinates per row are one and two. The lower proxy has more active coordinates here, so it is a surrogate rather than an exact count.
- Is choosing λ=0.3 justified just because it halves active products in the fixture?
Answer: No. Ranking loss also rises, and the fixture is training data. Select the tradeoff on development queries using relevance, index size and measured latency, then report performance once on a held-out set.
Two papers, several changes
Read the original paper’s section 3.2 for sum pooling and sparsity, then the v2 paper’s separate subsections for max pooling, document-only scoring and improved training. The first paper also explains SparTerm before presenting SPLADE; do not attribute the predecessor’s gating rule to SPLADE. Continue to inverted indexes for postings and hybrid search for combining independently scored candidates.
Make a prediction, then check
Does a smaller FLOPS regularizer prove fewer nonzero coordinates for every document?
Learning objectives
- Distinguish vocabulary coordinates, learned expansion, pooling versions and a cost surrogate.
- Run the original example and explain its failure case.
Prerequisites & connections
Explore related knowledge →References
- SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking — arXiv v1
Thibault Formal; Benjamin Piwowarski; Stéphane Clinchant · 2021 - SPLADE v2: Sparse Lexical and Expansion Model for Information Retrieval — arXiv v1
Thibault Formal; Benjamin Piwowarski; Carlos Lassance; Stéphane Clinchant · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF2–3: log1p-ReLU sum pooling, in-batch ranking and FLOPS relaxation; distinguish predecessor SparTerm equations. Viewed physical PDF2–3: prior sum model versus proposed max pooling, document-only variant, distillation and hard negatives. Read author header on PDF1. 6 paired equations and four explained exercises. Finite differences verify sum/max pooling and regularized ranking gradients; checked expansion, repeated tokens, empty input, active products and surrogate counterexample.
- Finite differences verify sum/max pooling and regularized ranking gradients; checked expansion, repeated tokens, empty input, active products and surrogate counterexample.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking — arXiv v1 · Viewed physical PDF2–3: log1p-ReLU sum pooling, in-batch ranking and FLOPS relaxation; distinguish predecessor SparTerm equations.
- SPLADE v2: Sparse Lexical and Expansion Model for Information Retrieval — arXiv v1 · Viewed physical PDF2–3: prior sum model versus proposed max pooling, document-only variant, distillation and hard negatives. Read author header on PDF1.
Related topics