multilingual-e5-small-Focused-CrossRecall
intfloat/multilingual-e5-small fine-tuned (LoRA, merged) for the long-term memory search of a self-hosted personal assistant:
Russian or English chat messages → English memory topics (title + short note), with one fixed cosine threshold that keeps
small talk, tasks and general questions out of the results.
Drop-in replacement for Xenova/multilingual-e5-small onnx/model_quantized.onnx: same architecture (XLM-R, 12 layers, hidden 384),
same vocabulary and sentencepiece.bpe.model, same ONNX inputs (input_ids, attention_mask, token_type_ids, int64) and output
last_hidden_state [B, T, 384], same int8 dynamic quantization layout, 118 MB.
Usage
Prefixes query: / passage: , mean pooling over the attention mask, L2 normalization, cosine = dot product.
XLM-R ids from SentencePiece: [0] + [3 if i == 0 else i + 1 for i in sp.encode(text)][:510] + [2], pad with 1.
import numpy as np, onnxruntime as ort, sentencepiece as spm
sess = ort.InferenceSession("onnx/model_quantized.onnx", providers=["CPUExecutionProvider"])
sp = spm.SentencePieceProcessor(model_file="sentencepiece.bpe.model")
def embed(texts):
rows = [[0, *(3 if i == 0 else i + 1 for i in sp.encode(t)[:510]), 2] for t in texts]
w = max(map(len, rows)); x = np.full((len(rows), w), 1, np.int64); m = np.zeros_like(x)
for i, r in enumerate(rows): x[i, :len(r)] = r; m[i, :len(r)] = 1
h = sess.run(None, {"input_ids": x, "attention_mask": m, "token_type_ids": np.zeros_like(x)})[0]
v = (h * m[..., None]).sum(1) / m.sum(1, keepdims=True)
return v / np.linalg.norm(v, axis=1, keepdims=True)
topics = embed(["passage: Nightly backups\nA cron job at 03:00 dumps the database to an S3 bucket, kept 14 days."])
print(embed(["query: где лежат бэкапы базы?"]) @ topics.T) # relevant: ~0.4-0.6
print(embed(["query: напиши стих про осень"]) @ topics.T) # unrelated: < 0.2
Threshold: the score scale differs from the base model (relevant ≈ 0.45, unrelated ≈ 0.05-0.15). Use ≈ 0.30 (the base model's typical 0.8+ thresholds do not apply).
Results (int8 ONNX, CPU, exact inference pipeline above)
Real memory of the deployed assistant (43 English topics, 141 test queries written from the topic titles: 87 with a relevant topic, 40 unrelated, 12 "hard" unrelated = general questions on a topic's subject):
| model | recall@1 | recall@5 | AUC relevant vs unrelated | AUC vs hard unrelated | false positives on unrelated at recall@5 ≥ 0.9 |
|---|---|---|---|---|---|
| Xenova/multilingual-e5-small (int8) | 0.908 | 0.989 | 0.862 | 0.479 | 47% |
| this model | 0.931 | 0.977 | 0.961 | 0.870 | 3% |
At threshold 0.30: recall@5 0.92, false positives on unrelated 2.5%, on hard unrelated 42% (5/12).
Synthetic dev set (43 topics, 99 queries, 68 cross-language; 40 unrelated, 12 hard):
| model | recall@1 | recall@5 | AUC vs unrelated | AUC vs hard |
|---|---|---|---|---|
| base (int8) | 0.384 | 0.737 | 0.498 | 0.435 |
| this model | 0.818 | 0.980 | 0.957 | 0.938 |
General: Tatoeba rus-eng accuracy@1 (query ru → passage en) 0.901 / 0.799 → 0.917 / 0.915 (ru→en / en→ru); RuBQ subset (300 queries, 3465 docs) nDCG@10 0.896 → 0.867 (RU→RU retrieval is slightly worse).
Training
- Data: synthetic, written by Claude Haiku 5.5: 40 invented users × 42 English memory topics (infrastructure, projects, preferences, rules, facts, about the user, about the assistant); per topic 5 Russian + 2 English user messages and 1+1 hard unrelated questions; ~1.3k unrelated chat messages. No real user data was used for training.
- General mix against forgetting: SberQuAD train (question → context) and TED talks ru↔en pairs (Tatoeba test sentences excluded).
- Batches: 2 users per step, all their topics are the candidates (in-user hard negatives); 64 relevant + 16 hard-unrelated + 16 unrelated queries.
- Loss: multi-positive InfoNCE (τ 0.05) + squared hinges around a target threshold + a decision loss
τ_d · softplus((max_k cos(unrelated_j, topic_k) − cos(q_i, its topic) + 0.1) / τ_d)over all (relevant, unrelated) pairs in the batch (weight 3) + in-batch InfoNCE on the general mix. - LoRA r16 / α32 on query, key, value, dense; embeddings frozen; AdamW lr 2e-4, 4 epochs, 1 × T4 (~19 min). The adapter is in
lora/. - Export: torch.onnx opset 14 →
onnxruntime.quantization.quantize_dynamic(MatMul QInt8 per-channel, reduce_range; Gather uint8). Control: the same exporter applied to the untouched base model reproduces the Xenova file's metrics.
Limitations
- Tuned for short English notes and short chat queries; long documents and RU→RU retrieval were not targeted.
- Test queries for the real memory were written from titles, which favours lexical overlap; hard-unrelated questions on a topic's exact subject still often pass the threshold.
Model tree for AmaLS367/multilingual-e5-small-Focused-CrossRecall
Base model
intfloat/multilingual-e5-small