splade-deep
БесплатноБез исполняемых скриптовНе проверенSPLADE / SPLADE++ learned sparse retrieval in depth. How SPLADE differs from BM25 (learned term expansion), FLOPS regularization, indexing in Qdrant sparse…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
SPLADE Deep Dive
SPLADE vs BM25 in One Sentence
BM25 scores documents by raw term frequency weighted by IDF. SPLADE uses a masked-language-model head to predict a learned weight for every term in the vocabulary — including terms that never appeared in the document.
This is called learned term expansion: a document about "token refresh" gets non-zero weights for "oauth", "bearer", "jwt", "access" even if those words are absent in the surface text.
The FLOPS Regularizer
Without constraint, SPLADE would fill the whole vocabulary with small non-zero weights, which is slow to index and search. SPLADE adds a FLOPS loss that penalizes the expected number of non-zero dot products at query time:
L = L_rank + lambda_q * FLOPS(q) + lambda_d * FLOPS(d)
lambda_q > lambda_d produces short, precise queries with slightly fatter documents — the right tradeoff for inverted-index serving. Published SPLADE++ (splade-cocondenser-ensembledistil) averages ~120 non-zero terms per document.
When SPLADE Wins
| Corpus | BM25 | SPLADE | Dense only |
|---|---|---|---|
| In-domain with rich labels | Good | Best | Tied with SPLADE |
| Out-of-domain (BEIR avg) | OK | Strong | Varies per model |
| Jargon-heavy (medical, legal) | Strong for exact terms | Strongest (learned expansion) | Often weakest |
| Very short queries (1-2 terms) | Wins on exact match | Adds expansion | Often too fuzzy |
| Very long documents | Hurts | Holds up | Degrades more |
Rule of thumb: SPLADE replaces BM25 in a hybrid pipeline when you have a GPU at ingest. BM25 is still the right choice if you cannot afford GPU encoding.
Encoding with Hugging Face Transformers
# pip install transformers torch
from transformers import AutoTokenizer, AutoModelForMaskedLM
import torch
MODEL_ID = "naver/splade-cocondenser-ensembledistil" # SPLADE++; MIT license
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForMaskedLM.from_pretrained(MODEL_ID).eval()
if torch.cuda.is_available():
model = model.to("cuda").half()
@torch.inference_mode()
def splade_encode(text: str, max_length: int = 256) -> dict[int, float]:
tok = tokenizer(text, return_tensors="pt", truncation=True, max_length=max_length)
if torch.cuda.is_available():
tok = {k: v.to("cuda") for k, v in tok.items()}
logits = model(**tok).logits # (1, seq_len, vocab)
attn = tok["attention_mask"].unsqueeze(-1)
weights = torch.max(
torch.log1p(torch.relu(logits)) * attn, dim=1
).values.squeeze(0) # (vocab,)
idx = torch.nonzero(weights).squeeze(-1)
return {int(i): float(weights[i]) for i in idx.tolist()}
For batching (ingest-time), replace with a real DataLoader; one-at-a-time will bottleneck on GPU launch overhead.
Efficient Batching for Ingest
from torch.utils.data import DataLoader
def collate(batch):
return tokenizer(batch, padding=True, truncation=True, max_length=256,
return_tensors="pt")
@torch.inference_mode()
def batch_splade(texts: list[str], batch_size: int = 32) -> list[dict[int, float]]:
loader = DataLoader(texts, batch_size=batch_size, collate_fn=collate)
out = []
for tok in loader:
tok = {k: v.to("cuda") for k, v in tok.items()}
logits = model(**tok).logits
attn = tok["attention_mask"].unsqueeze(-1)
w = torch.max(torch.log1p(torch.relu(logits)) * attn, dim=1).values
for row in w:
idx = torch.nonzero(row).squeeze(-1)
out.append({int(i): float(row[i]) for i in idx.tolist()})
return out
At 32-batch on an A10G, SPLADE++ encodes ~400-800 docs/sec depending on length.
Indexing in Qdrant (native sparse vectors)
from qdrant_client import QdrantClient, models
client = QdrantClient(url="http://localhost:6333", prefer_grpc=True)
client.create_collection(
"splade-kb",
vectors_config={}, # no dense needed if pure SPLADE
sparse_vectors_config={
"splade": models.SparseVectorParams(
index=models.SparseIndexParams(on_disk=False, full_scan_threshold=5000),
),
},
)
def to_sparse(weights: dict[int, float]) -> models.SparseVector:
items = sorted(weights.items())
return models.SparseVector(indices=[i for i, _ in items],
values=[v for _, v in items])
client.upsert(
"splade-kb",
points=[models.PointStruct(id=i, vector={"splade": to_sparse(w)}, payload={"text": t})
for i, (w, t) in enumerate(zip(doc_weights, docs))],
)
# Query
q_weights = splade_encode("token refresh 403")
result = client.query_points(
"splade-kb",
query=to_sparse(q_weights),
using="splade",
limit=10,
)
Indexing in Elasticsearch (rank_features)
Elasticsearch's rank_features field accepts a map of token-string -> weight; SPLADE terms map to BERT WordPiece tokens. Use the tokenizer's convert_ids_to_tokens to stringify.
from elasticsearch import Elasticsearch, helpers
Установить splade-deep в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл splade-deep?
SPLADE / SPLADE++ learned sparse retrieval in depth. How SPLADE differs from BM25 (learned term expansion), FLOPS regularization, indexing in Qdrant sparse vectors and Elasticsearch, hybrid with dense, efficiency tradeoffs, and when SPLADE beats BM25. USE WHEN: user mentions "SPLADE", "SPLADE++", "learned sparse", "neural sparse", "FLOPS regularization", "sparse vector retrieval", "naver/splade" DO NOT USE FOR: classical BM25 tuning - use `retrieval/bm25-tuning`; dense retrieval - use `vector-stores/*`; hybrid fusion math - use `rag/hybrid-search`
Как установить скилл splade-deep?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл splade-deep запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
agent-skill-stack
Find, evaluate, and assemble the smallest compatible set of AI Agent Skills for an end-to-end natural-language goal. Use when a user wants Skills for a…
от GitHubbuild-evidence-map
Build an auditable evidence map for a contested technical choice, research synthesis, proposal review, or consequential decision. Use when Copilot must…
от GitHubpinecone-rag
Build production RAG pipelines and persistent agent memory using Pinecone as the vector database backend. ALWAYS USE THIS SKILL when the user mentions…
от GitHubqdrant-monitoring-debugging
Diagnoses Qdrant production issues using metrics and observability tools. Use when someone reports 'optimizer stuck', 'indexing too slow', 'memory too high'…
от GitHub