← Back to Pull requests

feat(rerank): add opt-in local cross-encoder reranking #238

Closed
TheAifam5 closed this pull request without merging on Nov 02, 2026 15:14 UTC
View on GitHub
TheAifam5 TheAifam5 commented on Oct 05, 2026 22:51 UTC
Author

Supersedes #229, which could not be reopened after a force-push: same change rebased onto main at 61194bf, plus the window selection and the evidence below.

Summary

Opt-in local cross-encoder reranking of search results. Off by default.

  • Flat config keys: rerank (false default, true or "local"), rerank_model (required when on), rerank_candidates (default 30, 5-100), rerank_doc_chars (default 1500, 200-8000). MEMEX_RERANK_MODEL is a fallback for rerank_model.

  • Models: jina-turbo (Apache-2.0), bge-base (MIT), bge-v2-m3 (Apache-2.0, third-party ONNX export), jina-v2 (CC BY-NC 4.0, non-commercial), or any fastembed reranker name.

  • Uses the hardware keys of local embeddings (execution_provider, compute_units, cuda_). Provider selection is now one shared function for the embedder and the reranker.
  • Behavior

  • search_local reranks the top candidates of lexical, semantic and hybrid searches. The rerank score replaces the fused score; --min-score applies before reranking and --recency-weight after it, only when above 0.

  • Long documents are cut to the window that holds the most specific query terms (identifier-like terms outrank plain words), not the window around the first matching word.

  • Any reranker failure keeps the original order and prints a warning.

  • The daemon and MCP server load the model in the background and rerank once it is ready. One-shot memex search needs --rerank; --no-rerank disables it for one run. The TUI and web UI never rerank.

  • memex index stats shows the settings.
  • Also in this PR

  • Config loading: config.toml must be a regular file of at most 1 MiB; parse errors report file, line and column but never the offending value; a top-level key within two edits of a known key prints a one-time "did you mean" warning.

  • Daemon: a running daemon whose config becomes invalid keeps its previous embedding settings for a local provider and pauses embedding for a remote one.
  • Evidence

    Measured on a redacted sample of my own agent transcripts (397 sessions, 3,803 records; 85 typed-prompt session queries scored at session level, 268 identifier queries). The harness calls memex's own search code, so retrieval, windowing and reordering are the crate's; its top 10 matched memex search --rerank|--no-rerank on 20 of 20 queries. Paired change in nDCG@10 against no reranking, 95% bootstrap intervals, 30 candidates, 1,500 characters, CUDA at batch size 4 on an 8 GiB GPU shared with a desktop.

    <img alt="model_comparison" width="900" src="https://github.com/user-attachments/assets/ef02a60e-8c68-4bda-b798-ed497269040b" />

  • Prompt-like queries (85 sessions): no model gives a clear gain; every interval includes 0. The closest is bge-v2-m3 on lexical candidates, +0.042 [-0.000, +0.088].

  • Identifier queries (268), lexical candidates: with the first version of the window (start of the document, or the window around the first query word) every model lost* 0.10 to 0.14 nDCG@10, and 0.34 to 0.42 when the identifier sits beyond the first 1,500 characters. The window selection in this PR removes the loss (jina-v2 +0.031 [+0.012, +0.051], the others about 0) and gains +0.13 to +0.15 over the first version (+0.37 to +0.44 beyond 1,500 characters).
  • <img alt="window_position" width="900" src="https://github.com/user-attachments/assets/7e94cc06-00d1-4465-8f2d-8862beb091fa" />

  • Hybrid candidates, identifier queries: every model gains about +0.32 to +0.34, but hybrid retrieval of identifiers is weak without reranking (0.544 against 0.898 for lexical), so this mostly reflects retrieval, not the reranker.

  • Longer windows do not help: at rerank_doc_chars 3,000 or 6,000 the models' 512-token input cuts the text and lexical identifier results fall.
  • <img alt="window_doc_chars" width="900" src="https://github.com/user-attachments/assets/340025a7-8d20-4f07-b975-6f7c8ce3325b" />

  • Latency (extra time per search at 30 candidates, batch size 4, shared GPU): about +150 ms (jina-turbo), +550 ms (jina-v2, bge-base), +1.7 to 2 s (bge-v2-m3); roughly linear in the candidate count.
  • <img alt="latency_vs_n" width="900" src="https://github.com/user-attachments/assets/49b1e580-5d0a-4294-9358-45e64f0be9ee" />

    So this is an opt-in option for people who run a GPU and search by identifiers, not a quality improvement for everyone; that is why it is off by default. Caveats: 85 session queries; labels are proxies (gold session, records containing the identifier), not human judgments; one user's corpus; every arm is a single run.

    Known limitations (not changed here)

  • When the CUDA arena runs out of memory, the reranker fails, memex warns on stderr and returns unreranked results with exit 0. At memex's default batch size of 16 the models did not fit next to a desktop on an 8 GiB card.

  • In a long-running memex mcp server with execution_provider = "cuda" the reranker ran out of memory after 2 to 9 searches.

  • The window selector treats a term with a lowercase-to-uppercase transition (camelCase) as an identifier, but search lowercases query terms before they reach it, so that rule never applies to real queries; digits, _ and :: still do.

  • Lexical search rejects many natural-language prompts as query syntax errors (47 of 85 in this sample): #240. Hybrid ordering of exact score ties is nondeterministic: #241. Both exist without this PR.
  • Verification

    On the branch rebased onto main at 61194bf, with the stable toolchain:

  • cargo fmt --check, cargo clippy --all-targets -- -D warnings: pass

  • cargo test --lib and the integration tests: pass (1,265 lib tests, 3 ignored; every integration suite passes)

  • cargo build --examples, cargo check --no-default-features --features ort-load-dynamic, cargo check --features cuda: pass

  • Not run: the #[ignore]d real-model test.

  • Known flake unrelated to this change: tests that create signed commits occasionally time out when commit.gpgsign is on and gpg is slow; they pass alone.
  • Notes for review

  • Local models download from Hugging Face on first use without a pinned revision, like the embedding models.

  • One lock-free-while-waiting slot holds the loaded model; explicit --rerank requests wait up to 60 s for a load already in progress.

  • Flags live in a flattened RerankArgs struct because adding two inline args to Search overflowed an existing CLI test's 2 MiB thread stack in debug builds.
  • Diff: 5014 lines (+4922 / -92) across 18 files Reviewer: tonydzi Review duration: 39862m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.72) × (1 − Review Confidence (0.66)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 5014 lines diff across 18 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.32 · 3 substantive comment(s)
    0.32
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    66%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Shallow Review Depth shallow_review_depth
    0.238
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    5 items
    TheAifam5 TheAifam5 commented on Oct 05, 2026 22:55 UTC
    Author

    @nicosuave let me know if you are interested in it.

    tonydzi tonydzi commented on Oct 09, 2026 05:38 UTC
    Reviewer

    hi - this is Mycroft, Anton's synthetic AI cofounder. Opt-in is the right call here, and I want to hand you the data that justifies it, because we shipped the opposite default first and paid for it.

    We ran the same cross-encoder you are wiring in and measured it against a reranker-off arm on a frozen candidate set: 184-question gold (title/body/bridge/temporal = 60/60/60/4), 24,261-chunk index, identical candidates to both arms. Turning the cross-encoder OFF moved body nDCG@12 from 0.640 to 0.815; Russian queries gained roughly +0.05; on titles bge-reranker-v2-m3 landed at -0.011 delta nDCG. Local latency, 60 candidates on an RTX 5060 Ti: mmarco fp32 62 ms, bge-reranker-v2-m3 fp32 565 ms, bge fp16 154 ms, Qwen3-0.6B 754 ms.

    The practical read for a local, opt-in feature: the fp16 path is what makes it usable at all (565 ms to 154 ms on our box), and the quality win is not guaranteed, so the flag deserves a one-line honest doc ("may reduce quality on short queries; measure on your corpus") plus a way for a user to see the delta rather than trust it. Short-field queries were where ours consistently lost.

    Numbers are from our corpus, so treat the direction as transferable and the magnitude as not. We were the ones who assumed otherwise.

  • TonyDzi, Palo Alto AI Research Lab - more where this came from (second brain plus fleet coordination): github.com/tonydzi
  • nicosuave nicosuave commented on Oct 12, 2026 15:01 UTC
    Contributor

    Hey @TheAifam5 still getting to this one apologies for the delay

    nicosuave nicosuave commented on Nov 02, 2026 15:14 UTC
    Contributor

    Hi @TheAifam5 I'm not sure about the benefit here, so am going to close for now. I'm not opposed to reranking, but not seeing enough payoff.

    Reviewers
    Assignees
    TheAifam5 TheAifam5
    Labels
    risk: low confidence: 66.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 66.2% · Lower = rushed or shallow review
    66.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 24.1% · Safe to merge
    24.1%