Reranking and hybrid retrieval
First-stage retrieval is cheap and approximate; the final quality is decided by a second stage that is more expensive and only sees a few hundred candidates. Cross-encoders that read query and document together are studied, the late interaction of ColBERT, the learned sparse retrieval of SPLADE, the fusion of lexical and dense rankings, and listwise reranking with LLMs. A small cross-encoder is trained on the local GPU, and a hybrid cascade is built and evaluated rigorously.
After this lesson you can
- Explain why a cross-encoder is more accurate and much more expensive than a bi-encoder and calculate its cost in a cascade.
- Train a small cross-encoder with pointwise and listwise losses and use it to reorder the BM25 and dense retriever candidates.
- Implement MaxSim late-interaction scoring and reciprocal rank fusion, and compare rank fusion with score normalization.
- Use a SPLADE model and relate its term expansion with the masked language head.
- Apply listwise reranking using a local LLM with a sliding window and measure its sensitivity to the order of input.
Before you start
Candidates come before ranking
A first-stage retriever searches throughout the collection and delivers a set of candidates. A reranker dedicates more computation to ordering them. A reranker that only sees those candidates cannot rank a relevant document that never reached it. The input recall marks a ceiling, but it does not determine the nDCG by itself: the position and relevance of what did arrive also matter.
A cross-encoder concatenates query and passage, allows attention between them, and produces a score for each pair. A bi-encoder encodes documents in advance and queries only once; the cross-encoder reprocesses each pair. The second can capture finer interactions, but its cost grows with the candidates and length. Being more expressive does not imply that it always ranks better: training data, distribution, and truncated length matter.
The values were calculated with multilingual-e5-small and the published ms-marco-MiniLM-L6-v2 cross-encoder on three illustrative passages. The map averages the heads of the last layer, only from query tokens to passage tokens. The logit is not a calibrated probability and is not numerically compared to the cosine. In this example, the model even assigns a logit slightly higher to the negated variant: the figure illustrates an observed limitation, not a semantic guarantee.
Learning to rank
Given example query-passage-label triples, a pointwise loss applies binary cross-entropy to each pair. A pairwise loss compares a positive and a negative; a listwise loss applies softmax to the scores of the candidates for the same query and assigns mass to the known positive. A list can have several relevant items, so the target distribution should reflect the available judgments.
For a logit and binary label , the pointwise loss and a listwise loss with a single positive can be written as
The first treats each pair as a classification; the second explicitly compares candidates from the same query. A pairwise loss can use , rewarding the separation of positive and negative. These formulas do not guarantee that an unannotated negative is irrelevant.
Hard negatives from BM25 are lexically similar to the query and force discrimination; some may be relevant but unannotated. It is not advisable to treat them as absolute truth. Evaluate the reranker on candidates produced by the retriever that will be used and keep the training, validation, and test queries separate. The methodology of monoBERT illustrates pair scoring.
Late interaction and sparse retrieval
In late interaction, the query and the document are separately encoded into token vectors. ColBERT sums, for each query token, the highest similarity with a token from the document:
A mask excludes padding before the maximum; an empty query or a document without valid tokens needs an explicit convention. Saving a vector per token costs more memory than one per document. ColBERT combines precomputed representations with fine interaction; ColBERTv2 uses residual compression, among other improvements.
The matrix uses real E5 token vectors as illustration of the operation, including their prefixes; E5 is not a ColBERT checkpoint. The maximum per row does not mean that a token from the passage causally explains the relevance.
The learned sparse retrieval approach of SPLADE projects token states with a masked-language-model head to the vocabulary, applies non-negative activation and groups weights by term. It can assign weight to terms that do not appear literally, so it expands query and document. Regularization promotes sparsity; weights are served with an inverted index and their dot product produces the score. A model and its exact aggregation function must be identified: not all variants use the same.
In the variant used below, if is the logit for the vocabulary term in the valid position , the weight of the term is . The maximum is taken only over valid positions; the regularization during training influences how many weights are nonzero. The inverted index avoids traversing terms that do not contribute, but its cost depends on the length of the lists and the distribution of weights.
Fusion without confusing scales
The reciprocal rank fusion sums contributions according to the position of each document:
Ranks start at one; a document absent from a truncated list contributes zero for that list. The weighted formula extends the uniform sum in the original RRF paper. A strictly increasing transformation of a system’s scores preserves its order and so does its RRF contribution, with ties and tie-breaking fixed. The sum of scores requires comparable scales. Min-max changes if an extremum appears; z-score also depends on the distribution. RRF avoids dependence on score magnitudes but discards score differences and introduces its own weights and constant.
A retrieval cascade can combine lexical and dense search, merge candidates, apply a cross-encoder, and reserve an LLM for an even smaller list. Measure candidate recall and nDCG after each stage, as well as construction cost, batch latency, memory, and transfer. The measured values for each stage should correspond to the same queries and judgments; comparing rerankers with different candidates confuses the evaluation.
Ordering lists with a generative model
Listwise LLM reranking presents a query and several passages, requests a permutation, and validates it before use. A sliding window allows handling larger lists than the context, but the result depends on window size, overlap, and order. The model may omit or repeat identifiers: an implementation must retain every candidate exactly once, restore omitted candidates, and log invalid responses.
Repeat the same set with input permutations to measure sensitivity to position. Count input and output tokens and compare over the same candidates, not only on different inputs. The work RankGPT studies generative models for this task; their results depend on the model and evaluated set.
Reproduce the first two figures
This cell loads E5 and the published cross-encoder to calculate the cosines, logits, and attention for the first figure and the token vectors for the second. The texts are examples built for explanation; the scores come from a real execution. The attention uses the last layer and averages heads. The cell needs to download models and is omitted from the automatic test.
import json, numpy as np, torch
from transformers import AutoTokenizer,AutoModel,AutoModelForSequenceClassification
from sentence_transformers import SentenceTransformer
bi=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
cross_name='cross-encoder/ms-marco-MiniLM-L6-v2'
cross_revision='233902d25c440f23af6f7d6e94d2946bac0bee0a'
tok=AutoTokenizer.from_pretrained(cross_name,revision=cross_revision)
cross=AutoModelForSequenceClassification.from_pretrained(cross_name,revision=cross_revision,attn_implementation='eager').eval()
query='Does aspirin reduce heart attack risk?'
passages=['Aspirin reduces the risk of heart attack in some patients.',
'Aspirin does not reduce the risk of heart attack in some patients.',
'Ibuprofen reduces the risk of heart attack in some patients.']
qvec=bi.encode(['query: '+query],normalize_embeddings=True)[0]
pvec=bi.encode(['passage: '+x for x in passages],normalize_embeddings=True)
print('ocho componentes de consulta y pasajes:',qvec[:8].tolist(),pvec[:,:8].tolist())
out=[]
with torch.no_grad():
for passage,cos in zip(passages,pvec@qvec):
batch=tok(query,passage,return_tensors='pt',truncation=True,max_length=128)
result=cross(**batch,output_attentions=True)
qidx=[i for i,(t,s) in enumerate(zip(batch['input_ids'][0],batch['token_type_ids'][0])) if s.item()==0 and t.item() not in tok.all_special_ids]
didx=[i for i,(t,s) in enumerate(zip(batch['input_ids'][0],batch['token_type_ids'][0])) if s.item()==1 and t.item() not in tok.all_special_ids]
att=result.attentions[-1][0].mean(0)
out.append({'passage':passage,'cosine':float(cos),'logit':float(result.logits[0,0]),'queryTokens':tok.convert_ids_to_tokens(batch['input_ids'][0,qidx]),'docTokens':tok.convert_ids_to_tokens(batch['input_ids'][0,didx]),'attention':att[qidx][:,didx].tolist()})
print([(x['cosine'],x['logit']) for x in out],flush=True)
print(json.dumps(out,ensure_ascii=False))
# E5 token vectors illustrate MaxSim; E5 is not a ColBERT checkpoint.
etok=AutoTokenizer.from_pretrained('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3')
emodel=AutoModel.from_pretrained('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3').eval()
queries=['query: aspirin heart risk','query: ibuprofen heart risk']
document='passage: Aspirin reduces the risk of heart attack.'
def encode(text):
t=etok(text,return_tensors='pt',return_special_tokens_mask=True)
mask=t.pop('special_tokens_mask')[0].bool()
with torch.no_grad(): h=emodel(**t).last_hidden_state[0]
h=torch.nn.functional.normalize(h[~mask],dim=1)
return etok.convert_ids_to_tokens(t['input_ids'][0,~mask]),h
dt,dh=encode(document); rows=[]
for q in queries:
qt,qh=encode(q);rows.append({'query':q,'queryTokens':qt,'docTokens':dt,'similarity':([email protected]).tolist()})
print(json.dumps(rows,ensure_ascii=False))npm run lab and open the connection link.Local laboratory: fine-tune a cross-encoder
You need NumPy, PyTorch, transformers, datasets, requests, an internet connection, and storage for models and data. The code reads 64 triplets from MS MARCO with BM25 negatives, which may contain false negatives. The dataset card indicates that negatives were filtered with the cross-encoder that here also serves as the published comparison. The MiniLM scoring head is initialized from scratch; two independent fine-tuning runs start with the same weights and take eight steps, one with pointwise loss and the other with softmax over a three-passage list. Both models and a published cross-encoder then rerank the same 100 BM25 candidates for the first 10 test queries of SciFact.
In this small execution, nDCG@10 was 0.72475 for BM25, 0.01815 for pointwise fine-tuning, 0.00000 for listwise fine-tuning, and 0.75294 for the published model. The sample and fine-tuning run are too small to draw general conclusions; initial and final losses are training diagnostics, not generalization evaluation. The cell is excluded from automatic testing because of download requirements and cost, but it was run at the stated scale.
import json,zipfile,csv,io,re,time,requests
from itertools import islice
from collections import Counter
import numpy as np, torch
from datasets import load_dataset
from transformers import AutoTokenizer,AutoModelForSequenceClassification
torch.manual_seed(21);np.random.seed(21)
device='cuda' if torch.cuda.is_available() else 'cpu'
stream=iter(load_dataset('sentence-transformers/msmarco-bm25','triplet-50',revision='ce8a493a65af5e872c3c92f72a89e2e99e175f02',split='train',streaming=True))
rows=list(islice(stream,64))
if hasattr(stream,'close'): stream.close()
print('train rows',len(rows),'fields',list(rows[0])[:5],flush=True)
base='sentence-transformers/all-MiniLM-L6-v2'
base_rev='1110a243fdf4706b3f48f1d95db1a4f5529b4d41'
tok=AutoTokenizer.from_pretrained(base,revision=base_rev)
model=AutoModelForSequenceClassification.from_pretrained(base,revision=base_rev,num_labels=1).to(device)
initial={k:v.detach().clone() for k,v in model.state_dict().items()}
def pairs(qs,ds):
return tok(qs,ds,padding=True,truncation=True,max_length=192,return_tensors='pt').to(device)
def train(mode):
model.load_state_dict(initial);model.train();opt=torch.optim.AdamW(model.parameters(),lr=2e-5)
losses=[]
for start in range(0,len(rows),8):
b=rows[start:start+8]
qs=[r['query'] for r in b for _ in range(3)]
ds=[d for r in b for d in (r['positive'],r['negative_1'],r['negative_2'])]
logits=model(**pairs(qs,ds)).logits.reshape(-1,3)
if mode=='pointwise':
y=torch.zeros_like(logits);y[:,0]=1
loss=torch.nn.functional.binary_cross_entropy_with_logits(logits,y)
else:
loss=torch.nn.functional.cross_entropy(logits,torch.zeros(len(b),dtype=torch.long,device=device))
opt.zero_grad();loss.backward();opt.step();losses.append(loss.item())
print(mode,'steps',len(losses),'first/last',losses[0],losses[-1],flush=True)
return {k:v.detach().cpu().clone() for k,v in model.state_dict().items()}
states={mode:train(mode) for mode in ('pointwise','listwise')}
response=requests.get('https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip',timeout=90)
response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
corpus=[json.loads(x) for x in z.read('scifact/corpus.jsonl').decode().splitlines()]
queries={x['_id']:x['text'] for x in map(json.loads,z.read('scifact/queries.jsonl').decode().splitlines())}
qrows=list(csv.DictReader(io.StringIO(z.read('scifact/qrels/test.tsv').decode()),delimiter='\t'))
qrels={}
for r in qrows:
if int(r['score'])>0:qrels.setdefault(r['query-id'],set()).add(r['corpus-id'])
qids=sorted(qrels)[:10]
ids=[x['_id'] for x in corpus];texts=[x.get('title','')+' '+x['text'] for x in corpus]
tokens=lambda t:re.findall(r'\w+',t.lower())
docs=[tokens(t) for t in texts];counts=[Counter(t) for t in docs]
df=Counter(word for doc in counts for word in doc)
N=len(docs);avg=np.mean([len(d) for d in docs])
def bm(q):
score=np.zeros(N)
for word in tokens(q):
if word not in df:continue
idf=np.log(1+(N-df[word]+.5)/(df[word]+.5))
for i,c in enumerate(counts):
f=c[word]
score[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(docs[i])/avg)) if f else 0
return np.argsort(-score,kind='stable')[:100]
candidates=[bm(queries[q]) for q in qids]
def metric(ranks):
values=[]
for qid,rank in zip(qids,ranks):
rel=qrels[qid]
dcg=sum((ids[j] in rel)/np.log2(i+2) for i,j in enumerate(rank[:10]))
ideal=sum(1/np.log2(i+2) for i in range(min(10,len(rel))))
values.append(float(dcg/ideal))
return np.mean(values),values
def rerank(net,tokenizer):
net.eval();out=[]
with torch.no_grad():
for qid,cand in zip(qids,candidates):
scores=[]
for start in range(0,len(cand),16):
sub=cand[start:start+16]
b=tokenizer([queries[qid]]*len(sub),[texts[i] for i in sub],padding=True,truncation=True,max_length=192,return_tensors='pt').to(device)
scores.extend(net(**b).logits[:,0].cpu().tolist())
out.append(cand[np.argsort(-np.array(scores),kind='stable')])
return out
results={'BM25':metric(candidates)}
for mode in states:
model.load_state_dict(states[mode]);results[mode]=metric(rerank(model,tok));print(mode,results[mode][0],flush=True)
pub='cross-encoder/ms-marco-MiniLM-L6-v2';pub_rev='233902d25c440f23af6f7d6e94d2946bac0bee0a'
ptok=AutoTokenizer.from_pretrained(pub,revision=pub_rev)
pretrained=AutoModelForSequenceClassification.from_pretrained(pub,revision=pub_rev).to(device)
results['publicado']=metric(rerank(pretrained,ptok))
print('SciFact first 10 nDCG@10',[(k,v[0]) for k,v in results.items()],flush=True)
print(json.dumps(results,indent=2))npm run lab and open the connection link.Now apply those same two tuned models and the published model to the 100 dense E5 candidates for the same ten queries and the same SciFact judgments. Execute the previous cell first: this reuses their models, states, texts, and evaluation function. Use the appropriate prefix for each side and normalize the vectors before the dot product. Thus, you compare each stage with its own input and avoid confusing a change of candidates with a change of reranker.
In a CPU execution of the ten queries, E5 obtained nDCG@10 0.81437. Reordering its 100 candidates, the pointwise fine-tuning obtained 0.02021, the listwise 0, and the published cross-encoder 0.76604. For the published model, the mean paired difference relative to E5 was −0.04834; a bootstrap of 10000 resamples of queries, seed 21, gave the percentile interval [−0.12648, 0]. It is a very small sample and selected by order of identifier: it does not demonstrate that the published model worsens in general. Documents without positive judgments are counted as non-relevant for this metric, which may hide unannotated relevance.
from sentence_transformers import SentenceTransformer
e5=SentenceTransformer('intfloat/multilingual-e5-small',
revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device=device)
D=e5.encode(['passage: '+t for t in texts],batch_size=16,
normalize_embeddings=True,convert_to_numpy=True,show_progress_bar=True)
Q=e5.encode(['query: '+queries[q] for q in qids],batch_size=16,
normalize_embeddings=True,convert_to_numpy=True)
candidates=[np.argsort(-(D@q),kind='stable')[:100] for q in Q]
dense_results={'E5':metric(candidates)}
for mode in states:
model.load_state_dict(states[mode])
dense_results[mode]=metric(rerank(model,tok))
dense_results['publicado']=metric(rerank(pretrained,ptok))
print('SciFact primeras diez consultas, nDCG@10:',
[(name,value[0]) for name,value in dense_results.items()])
delta=np.array(dense_results['publicado'][1])-np.array(dense_results['E5'][1])
rng=np.random.default_rng(21)
boot=np.mean(delta[rng.integers(0,len(delta),(10000,len(delta)))],axis=1)
print('diferencia pareada e intervalo bootstrap:',float(delta.mean()),np.quantile(boot,[.025,.975]))
print(json.dumps(dense_results,indent=2))npm run lab and open the connection link.Local laboratory: hybrid retrieval and SPLADE
With NumPy, SciPy, PyTorch, sentence-transformers, transformers and requests, the code downloads two BEIR collections and applies BM25, E5 and SPLADE cocondenser ensembledistil. It builds sparse inverted lists with CSC and checks scores against the sparse product. SPLADE aggregation uses max of log1p of ReLU on valid tokens. RRF fuses lists up to 100 results; an absent document contributes zero. The first 20 test queries ordered by identifier are used only as demonstration: they do not replace the evaluation of all judgments.
In SciFact, with 5183 documents, nDCG@10 measured was 0.6689 BM25, 0.6873 E5, 0.6436 SPLADE and 0.6811 for BM25+E5. In NFCorpus, with 3633 documents, it was 0.2645, 0.2978, 0.2692 and 0.2956 respectively; E5+SPLADE gave 0.3203. The code calculates paired bootstrap intervals of the differences against BM25 for each corpus. These are exploratory analyses with only 20 queries and several comparisons, not a guarantee of improvement. The complete corpora and the two lists of 20 queries are real; the representations were calculated for this run.
import io,zipfile,json,csv,re,collections,time,requests
import numpy as np,torch
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForMaskedLM
from scipy.sparse import csr_matrix
torch.set_num_threads(4)
device='cuda' if torch.cuda.is_available() else 'cpu'
e5=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device=device)
name='naver/splade-cocondenser-ensembledistil'
revision='49cf4c7b0db5b870a401ddf5e2669993ef3699c7'
tokenizer=AutoTokenizer.from_pretrained(name,revision=revision)
mlm=AutoModelForMaskedLM.from_pretrained(name,revision=revision).to(device).eval()
def load(name,path):
response=requests.get(path,timeout=90);response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
corpus=[json.loads(x) for x in z.read(name+'/corpus.jsonl').decode().splitlines()]
queries={x['_id']:x['text'] for x in map(json.loads,z.read(name+'/queries.jsonl').decode().splitlines())}
rows=list(csv.DictReader(io.StringIO(z.read(name+'/qrels/test.tsv').decode()),delimiter='\t'))
qrels={}
for r in rows:
if int(r['score'])>0:qrels.setdefault(r['query-id'],{})[r['corpus-id']]=int(r['score'])
qids=sorted(qrels)[:20]
return corpus,queries,qrels,qids
def sparse_encode(texts):
vals=[];cols=[];ptr=[0]
with torch.no_grad():
for start in range(0,len(texts),8):
b=tokenizer(texts[start:start+8],padding=True,truncation=True,max_length=128,return_tensors='pt').to(device)
logits=mlm(**b).logits
weights=(torch.log1p(torch.relu(logits))*b['attention_mask'].unsqueeze(-1)).amax(dim=1).cpu().numpy()
for row in weights:
nz=np.flatnonzero(row>0);cols.extend(nz.tolist());vals.extend(row[nz].tolist());ptr.append(len(cols))
return csr_matrix((np.array(vals,dtype=np.float32),np.array(cols),np.array(ptr)),shape=(len(texts),tokenizer.vocab_size))
def tokenize(x):return re.findall(r'\w+',x.lower())
def bm_scores(q,docs,counts,df):
n=len(docs);avg=np.mean([len(d) for d in docs]);score=np.zeros(n)
for w in tokenize(q):
if w not in df:continue
idf=np.log(1+(n-df[w]+.5)/(df[w]+.5))
for i,c in enumerate(counts):
f=c[w]
if f:score[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(docs[i])/avg))
return score
def top(scores,k=100):
return np.argsort(-scores,kind='stable')[:k]
def rrf(rankings,k=60):
score=collections.defaultdict(float)
for ranking in rankings:
for r,i in enumerate(ranking,1):score[int(i)]+=1/(k+r)
return sorted(score,key=lambda i:(-score[i],i))
def metric(qid,rank,ids,qrels):
rel=qrels[qid]
gains=lambda grade:2**grade-1
dcg=sum(gains(rel.get(ids[j],0))/np.log2(i+2) for i,j in enumerate(rank[:10]))
ideal=sum(gains(g)/np.log2(i+2) for i,g in enumerate(sorted(rel.values(),reverse=True)[:10]))
return dcg/ideal
outputs={}
for name,path in [('scifact','https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip'),('nfcorpus','https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/nfcorpus.zip')]:
corpus,queries,qrels,qids=load(name,path);ids=[x['_id'] for x in corpus]
texts=[(x.get('title','')+' '+x['text']).strip() for x in corpus]
qs=[queries[q] for q in qids]
docs=[tokenize(t) for t in texts];counts=[collections.Counter(d) for d in docs];df=collections.Counter(w for d in counts for w in d)
dense=e5.encode(['passage: '+t for t in texts],batch_size=16,normalize_embeddings=True,convert_to_numpy=True,show_progress_bar=False)
dq=e5.encode(['query: '+q for q in qs],batch_size=16,normalize_embeddings=True,convert_to_numpy=True)
sparse=sparse_encode(texts);sq=sparse_encode(qs)
postings=sparse.tocsc() # una columna por término y sus documentos/ponderaciones
rows={k:[] for k in ('BM25','E5','SPLADE','BM25+E5','BM25+SPLADE','E5+SPLADE','todos')}
for i,qid in enumerate(qids):
b=top(bm_scores(qs[i],docs,counts,df));e=top(dense@dq[i])
scores=np.zeros(len(ids),dtype=np.float32)
for term,weight in zip(sq[i].indices,sq[i].data):
begin,end=postings.indptr[term:term+2]
scores[postings.indices[begin:end]]+=weight*postings.data[begin:end]
assert np.allclose(scores,(sparse@sq[i].T).toarray().reshape(-1),rtol=1e-5,atol=1e-5)
s=top(scores)
for label,rank in [('BM25',b),('E5',e),('SPLADE',s),('BM25+E5',rrf([b,e])),('BM25+SPLADE',rrf([b,s])),('E5+SPLADE',rrf([e,s])),('todos',rrf([b,e,s]))]:
rows[label].append(metric(qid,rank,ids,qrels))
rng=np.random.default_rng(21);base=np.array(rows['BM25'])
result={}
for label,values in rows.items():
arr=np.array(values);delta=arr-base
boot=np.mean(delta[rng.integers(0,len(delta),(2000,len(delta)))],axis=1)
result[label]={'ndcg':float(arr.mean()),'delta_vs_bm25':float(delta.mean()),'paired_ci':np.quantile(boot,[.025,.975]).tolist(),'per_query':values}
outputs[name]={'N':len(ids),'Q':len(qids),'results':result}
print(name,'N',len(ids),'Q',len(qids),[(k,v['ndcg']) for k,v in result.items()],flush=True)
print(json.dumps(outputs,indent=2))npm run lab and open the connection link.import numpy as np
def maxsim(Q,D,mask):
sims=np.einsum('qd,bld->bql',Q,D)
return np.where(mask[:,None,:],sims,-np.inf).max(axis=2).sum(axis=1)
Q=np.array([[1.,0.],[0.,1.]])
D=np.array([[[1.,0.],[0.,1.],[99.,99.]],[[.5,.5],[.2,.3],[9.,9.]]])
mask=np.array([[1,1,0],[1,1,0]],dtype=bool)
print(maxsim(Q,D,mask))The padding is masked before the maximum; the example assumes at least one valid token in each document. The second part of the code exercise implements RRF independently.
Local laboratory: windows and input order
The first cell builds BM25 and calculates the scores of the published cross-encoder for 100 candidates of query 1132 from SciFact. This example has been deliberately chosen because its two judged relevant documents are in BM25 positions 5 and 36. The cell saves rerank-lab/cascade.json for the next; it does not present this query as an estimate of average performance.
import json,zipfile,csv,io,re,requests
from pathlib import Path
from collections import Counter
import numpy as np,torch
from transformers import AutoTokenizer,AutoModelForSequenceClassification
torch.set_num_threads(4)
response=requests.get('https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip',timeout=90)
response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
corpus=[json.loads(x) for x in z.read('scifact/corpus.jsonl').decode().splitlines()]
queries={x['_id']:x['text'] for x in map(json.loads,z.read('scifact/queries.jsonl').decode().splitlines())}
rows=list(csv.DictReader(io.StringIO(z.read('scifact/qrels/test.tsv').decode()),delimiter='\t'))
qrels={}
for r in rows:
if int(r['score'])>0:qrels.setdefault(r['query-id'],set()).add(r['corpus-id'])
qid='1132';q=queries[qid] # ejemplo escogido: relevantes a distintas profundidades BM25
ids=[x['_id'] for x in corpus];texts=[x.get('title','')+' '+x['text'] for x in corpus]
tokenize=lambda t:re.findall(r'\w+',t.lower())
docs=[tokenize(t) for t in texts];counts=[Counter(d) for d in docs]
df=Counter(w for d in counts for w in d);N=len(docs);avg=np.mean([len(d) for d in docs])
score=np.zeros(N)
for w in tokenize(q):
if w not in df:continue
idf=np.log(1+(N-df[w]+.5)/(df[w]+.5))
for i,c in enumerate(counts):
f=c[w]
if f:score[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(docs[i])/avg))
candidates=np.argsort(-score,kind='stable')[:100]
name='cross-encoder/ms-marco-MiniLM-L6-v2';revision='233902d25c440f23af6f7d6e94d2946bac0bee0a';tok=AutoTokenizer.from_pretrained(name,revision=revision)
model=AutoModelForSequenceClassification.from_pretrained(name,revision=revision).eval()
values=[]
with torch.no_grad():
for start in range(0,100,8):
batch=candidates[start:start+8]
inp=tok([q]*len(batch),[texts[i] for i in batch],padding=True,truncation=True,max_length=192,return_tensors='pt')
values.extend(model(**inp).logits[:,0].tolist())
data={'qid':qid,'query':q,'totalRelevant':len(qrels[qid]),
'candidates':[{'id':ids[j],'text':texts[j],'relevant':ids[j] in qrels[qid],'bm25':float(score[j]),'cross':float(v)} for j,v in zip(candidates,values)]}
Path('rerank-lab').mkdir(exist_ok=True)
with open('rerank-lab/cascade.json','w',encoding='utf-8') as f:json.dump(data,f,ensure_ascii=False)
print('query',qid,'candidates',len(candidates),'relevant',len(qrels[qid]),'relevant candidates',sum(x['relevant'] for x in data['candidates']),flush=True)npm run lab and open the connection link.The second cell needs llama-cpp-python and huggingface_hub, and downloads the two files of Qwen2.5-7B-Instruct quantized Q4_K_M from the specified revision. They occupy several gigabytes and the model can take a long time on CPU. For the cross-encoder’s first eight candidates, apply sliding windows of size four with a stride of two, starting at the end, repair missing or repeated identifiers, and repeat with the input order inverted. Record responses, tokens, and duration per window, and nDCG@10 against the same judgments. Each run is a sample of a single query; variations do not prove a general effect.
In the execution with llama-cpp-python 0.3.36 on CPU and eight threads, the cross-encoder and the two permutations of 7B gave nDCG@10 0.6131 for this query, although the final orders of eight documents were different. The three windows consumed 1218 tokens with the order of the cross-encoder and 1264 with the inverse; respectively, five and four identifiers were missing in the answers, which were completed by preserving their input order. The sum of call times was approximately 222 and 404 seconds, without model loading and on a shared machine. These are GGUF results; the figure uses the following NF4 measurements, with assumed editable costs.
import os,json,re,time,random,math
from llama_cpp import Llama
from huggingface_hub import hf_hub_download
with open('rerank-lab/cascade.json',encoding='utf-8') as f:data=json.load(f)
repo='Qwen/Qwen2.5-7B-Instruct-GGUF'
revision='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
files=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
paths=[hf_hub_download(repo,f,revision=revision) for f in files]
model_path=paths[0]
llm=Llama(model_path=model_path,n_ctx=2048,n_threads=8,verbose=False)
docs=sorted(data['candidates'],key=lambda d:-d['cross'])
base=docs[:8]
def ndcg(ranking):
dcg=sum((1 if d['relevant'] else 0)/math.log2(i+2) for i,d in enumerate(ranking[:10]))
ideal=sum(1/math.log2(i+2) for i in range(min(10,data['totalRelevant'])))
return dcg/ideal if ideal else 0
def order_window(window):
text='\n'.join('['+str(i+1)+'] '+d['text'][:350] for i,d in enumerate(window))
prompt=('Rank the passages by relevance to the query. Return ONLY their numbers in order, '
'using each number once, such as [2] > [1].\nQuery: '+data['query']+'\n'+text)
start=time.perf_counter()
ans=llm.create_chat_completion(messages=[{'role':'user','content':prompt}],temperature=0,max_tokens=40)
elapsed=time.perf_counter()-start
raw=ans['choices'][0]['message']['content']
found=[]
for v in re.findall(r'\d+',raw):
i=int(v)-1
if 0<=i<len(window) and i not in found:found.append(i)
missing=[i for i in range(len(window)) if i not in found]
return [window[i] for i in found+missing],{'raw':raw,'missing':len(missing),'seconds':elapsed,'usage':ans['usage']}
def sliding(items):
items=list(items);log=[]
for end in range(len(items),0,-2):
start=max(0,end-4)
items[start:end],rec=order_window(items[start:end]);log.append(rec)
if start==0:break
return items,log
records=[]
for label,front in [('orden_cross',base),('orden_inverso',list(reversed(base)))]:
result,log=sliding(front)
result=result+docs[8:]
record={'order':label,'ndcg':ndcg(result),'top8':[d['id'] for d in result[:8]],'calls':log}
records.append(record)
print(label,'ndcg@10',record['ndcg'],'top8',record['top8'],'tokens',sum(x['usage']['total_tokens'] for x in log),flush=True)
print('cross nDCG@10',ndcg(docs),flush=True)
with open('rerank-lab/listwise-results.json','w',encoding='utf-8') as f:json.dump(records,f,ensure_ascii=False,indent=2)npm run lab and open the connection link.The following variant sweeps depths 4, 8 and 12 and both orders over the same candidates and judgments. It uses the original checkpoint in NF4 with transformers and bitsandbytes, rather than the preceding GGUF file; its results are therefore not interchangeable with those of the preceding cell. Save each completed case so that the run can resume. It requires a CUDA GPU with enough memory, in addition to accelerate and bitsandbytes. The test environment uses transformers 5.23.0, bitsandbytes 0.50.2, and accelerate 1.16.0. The same repair procedure preserves all identifiers, and each window records its response and tokens.
import hashlib, json, math, re, time
from pathlib import Path
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
data=json.loads(Path('rerank-lab/cascade.json').read_text(encoding='utf-8'))
repo='Qwen/Qwen2.5-7B-Instruct'
revision='a09a35458c702b33eeacc393d103063234e8bc28'
tok=AutoTokenizer.from_pretrained(repo,revision=revision)
quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',
bnb_4bit_compute_dtype=torch.float16)
model=AutoModelForCausalLM.from_pretrained(repo,revision=revision,
quantization_config=quant,device_map={'':0},dtype=torch.float16).eval()
path=Path('rerank-lab/listwise-nf4.json')
records=json.loads(path.read_text(encoding='utf-8')) if path.exists() else []
fingerprint=hashlib.sha256(json.dumps(data,ensure_ascii=False,sort_keys=True).encode('utf-8')).hexdigest()
if any(r.get('fingerprint')!=fingerprint or r.get('revision')!=revision for r in records):
raise ValueError('El checkpoint pertenece a otros candidatos o a otro modelo')
completed={(r['depth'],r['order']) for r in records}
docs=sorted(data['candidates'],key=lambda d:-d['cross'])
def ndcg(ranking):
dcg=sum(int(d['relevant'])/math.log2(i+2) for i,d in enumerate(ranking[:10]))
ideal=sum(1/math.log2(i+2) for i in range(min(10,data['totalRelevant'])))
return dcg/ideal if ideal else 0.
def order_window(window):
text='\n'.join(f'[{i+1}] {d["text"][:350]}' for i,d in enumerate(window))
prompt=('Rank the passages by relevance to the query. Return ONLY their numbers in order, '
'using each number once, such as [2] > [1].\nQuery: '+data['query']+'\n'+text)
tokens=tok.apply_chat_template([{'role':'user','content':prompt}],
add_generation_prompt=True,return_tensors='pt').to(model.device)
start=time.perf_counter()
with torch.inference_mode():
output=model.generate(**tokens,do_sample=False,max_new_tokens=40,pad_token_id=tok.eos_token_id)
input_ids=tokens['input_ids']
if input_ids.device.type=='cuda': torch.cuda.synchronize(input_ids.device)
raw=tok.decode(output[0,input_ids.shape[1]:],skip_special_tokens=True)
found=[]
for v in re.findall(r'\d+',raw):
i=int(v)-1
if 0<=i<len(window) and i not in found: found.append(i)
missing=[i for i in range(len(window)) if i not in found]
return [window[i] for i in found+missing],{'raw':raw,'missing':len(missing),
'seconds':time.perf_counter()-start,'input_tokens':input_ids.shape[1],
'output_tokens':output.shape[1]-input_ids.shape[1]}
for depth in (4,8,12):
for order in ('cross','inverso'):
if (depth,order) in completed: continue
items=list(docs[:depth])
if order=='inverso': items.reverse()
calls=[]
for end in range(len(items),0,-2):
start=max(0,end-4)
items[start:end],call=order_window(items[start:end]);calls.append(call)
if start==0: break
record={'fingerprint':fingerprint,'revision':revision,'depth':depth,'order':order,'ndcg':ndcg(items+docs[depth:]),
'cross_ndcg':ndcg(docs),'top':[d['id'] for d in items],'calls':calls}
records.append(record)
tmp=path.with_suffix('.tmp')
tmp.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf-8')
tmp.replace(path)
print(depth,order,'nDCG@10',record['ndcg'],flush=True)npm run lab and open the connection link.In the NF4 execution, the nDCG@10 with cross-encoder and reversed input orders were respectively 0.6131 and 0.3869 for depth 4; 0.6131 and 0.6131 for depth 8; and 0.3869 and 0.6131 for depth 12. The cross-encoder without LLM obtained 0.6131. The depths used 1, 3, and 5 windows respectively; the six runs consumed between 447 and 2088 tokens between input and output, and in three of them there was an omitted identifier that was fixed. These are six executions of a single selected query: they do not prove a general trend in quality nor attribute causality to the order. The figure shows these real rankings and calculates a frontier only for your chosen costs.
Exercises
Step 1 of 3. What does a strictly increasing transformation preserve?
import numpy as np
def maxsim(Q, D, mask):
pass
def rrf(rankings, k):
pass