Skip to content

[WIP] Experimenting with late interaction - #478

Draft
ahuber21 wants to merge 17 commits into
dev/ahuber/late-interaction-basefrom
dev/ahuber/late-interaction
Draft

ahuber21 wants to merge 17 commits into
dev/ahuber/late-interaction-basefrom
dev/ahuber/late-interaction

Conversation

@ahuber21

Copy link
Copy Markdown
Member

No description provided.

ahuber21 and others added 17 commits November 30, 2026 06:22
solve_impl's thread_local SolverWorkspace is accessed once per QEmd
distance evaluation (via QEmdImpl::compute_decoded), the dominant site
in the 3% of graph-build cycles LBR profiling attributed to
__tls_get_addr. The data access now uses initial-exec; a residual
TLSGD call remains for the compiler's once-per-thread destructor
registration (SolverWorkspace's vector members give it a non-trivial
dtor), which an attribute can't reach since it targets a
compiler-synthesized guard variable, not ws itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ntial

update_potential's pivot loop walks the moved subtree in thread (preorder)
order, so is_source(node, m) interleaves source and sink nodes with no
pattern and mispredicts on about half the iterations: 25% of all branch-miss
samples in a 50-pass perf record on the qEMD replay set1. A `?:`-written
select still compiled to a branch (no measured gain). Indexing into
two-element arrays of pointers/deltas by is_source(node, m) (0 = sink,
1 = source) compiles to a load instead.

Measured on the qEMD replay tool (gem-experiment cpp/explore/08_qemd_replay),
set1 (5,258 problems) and set5 (5,217 problems, hold-out), single thread
pinned to node 0: set1 t1 cycles/solve 305,748 -> 272,851 (-10.8%),
branch-misses/solve 6,141 -> 4,652 (-24.2%); set5 t1 cycles/solve
290,292 -> 261,328 (-10.0%), branch-misses 5,845 -> 4,466 (-24.0%); 112
threads solves/s set1 582,972 -> 625,432 (+7.3%), set5 611,943 -> 754,200
(+23.3%). Checksums bit-exact before and after on both sets
(0xab3a9a4d912b431d, 0xf0eebe14bce86c12), including an AVX2-forced replay
of set1; ref_failures 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds a cheap relaxed-EMD lower bound (RWMD: each side's cheapest match on
the other side, weighted and summed) that greedy_search can use to skip a
candidate's qEMD solve once the search window is full and the bound
already exceeds the window's worst distance, scaled by an aggressiveness
`s >= 0` (`s == 0` is exact). Off by default: QEmd's new qemd_skip_s
constructor argument defaults to unset, and distance::lower_bound's
generic customization point (concepts/distance.h) compiles away entirely
for any distance type that does not define lower_bound, so every non-GEM
Vamana build is unaffected. The runtime reads the setting once per build
from SVS_GEM_QEMD_SKIP_S (unset = off) rather than adding it to the public
GemBuildParameters/GemSearchParameters structs, which Knowhere links
against by layout.

Also adds SVS_GEM_QEMD_COUNT-gated instrumentation (off by default) used
to measure, before implementing the skip, what share of qEMD solves come
from search vs. pruning and what the exact and swept bounds would skip.

Measured on a 100,000-doc subset against an exact MaxSim oracle: s=0 is
4.9% faster with recall unchanged within noise; s=0.1 is 23.4% faster for
a 0.03-point recall@10 drop at window 1,000; returns diminish sharply past
s=0.2. Full curve in gem-experiment's data/qemd-prune-sweep-v1/RESULTS.md.
Not merged into any default path; the setting stays off unless requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ance

GCC 11 still emitted a jne for the `?:` picking u between
rev_thread[par_stem] and last_succ[stem] (both plain, already-available
array reads), 5.15% of branch-miss samples on replay set 1. An all-ones/
all-zeros mask select removes the jump. Replay set 1: 272,113.7 ->
264,325.2 cycles/solve (-2.9%), set 5: 260,447.4 -> 250,319.3 (-3.9%),
identical FNV-1a64 checksum and ref_failures=0 on both sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Lets quantize(tokens, PretrainedCodebook, ...) run a few e-means epochs on
the segment's own tokens before assignment, seeded from the pretrained
centroids via svs::kmeans::emeans_train's initial_centroids overload. New
CodebookParameters::refine_epochs (default 0) controls it; 0 keeps the
quantize path byte-identical to before. coarse_of_fine/num_coarse keep the
pretrained routing even after a refine, since a few epochs move centroids
only slightly.

On the 28,900-doc slice (shared 1% codebook), refine recovers most of the
shared-codebook penalty: 3 epochs land at 35 distinct centroids/doc, close
to a segment's own codebook (34.8).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Lets a GemIndex::build from a GemTrainingData codebook request the SVS-side
e-means refine (CodebookParameters::refine_epochs). 0 (default) keeps the
build byte-identical to before. Additive field at the end of
GemBuildParameters; bumps the runtime minor version 0.5 -> 0.6 since the
struct crosses the .so boundary and every linked caller needs the new
layout. The build log now reports refine_s next to the other phase timings.

BREAKING CHANGE: GemBuildParameters grew a trailing field
(codebook_refine_epochs); any caller linking a prebuilt libsvs_runtime.so
must rebuild against the matching header before picking up this version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces the SVS_GEM_QEMD_SKIP_S env var with a real build parameter, so
callers set it the same way as alpha or the build window size. 0 (default)
disables the lower-bound skip, matching the env var's old unset behavior.
Logs the effective s next to SVS_GEM_BUILD_PHASES.

BREAKING CHANGE: GemBuildParameters grew qemd_skip_s; covered by the 0.6 runtime bump of
codebook_refine_epochs, so callers relink once for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CountingDistance forwarded compute but not lower_bound, so wrapping a
distance for build stats silently disabled the greedy-search and
(new) robust-prune lower-bound skips whenever SVS_ENABLE_STATS was on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ecides it

QEmd::lower_bound already proves a search candidate can't improve the
window; the same bound proves a prune candidate can't be knocked out,
so robust prune skips the solve under the same condition. Uses alpha
as given; no logic branches on its value. Compiles away for distances
without lower_bound, as greedy_search.h's skip does.

Adds a counting build (SVS_GEM_QEMD_COUNT) that logs, instead of acting
on, the share of pruning pairs the bound and the parked northwest-corner
upper bound would each decide, and their cost against a real solve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HasTwoArgLowerBound alone doesn't guarantee a smaller-is-better
comparator; the bound-vs-ratio inequality in the progressive prune
skip only holds under that ordering. Gate has_lower_bound on
decltype(cmp) being std::less<>, matching QEmd's compare alias.
Behaviour for QEmd is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CountingDistance forwarding lower_bound (2198593) and the
progressive-prune lower_bound skip (d691d7f) had no regression
tests. Add a CountingDistance forwarding check and a
heuristic_prune_neighbors comparison that the skip matches the
unskipped result while computing fewer real solves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Direct-mapped, lock-free 128 MiB cache of qEMD solves, keyed order-free on the
two docs' id-array pointers, for brief 7 of
notes/research/2026-12-01-vectorizable-transport-solver.md. Measured on the
arm B slice (docs 500000-528900, s=0.1): graph_s 37.8s against the 77.3s
reference, hit rate 0.70. Off by default via QEmd's new pair_cache ctor arg
and GemBuildParameters::qemd_pair_cache.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…build

The cache from the previous commit matched on a 32-bit hash tag, so a
colliding pair could return another pair's distance, and an empty
document's data() aliased the next document's, so it could hit on that
document's entry.

PairDistanceCache now stores both addresses in full and checks both on
every hit. A slot is three words (sequence|value, lo, hi) under a
per-slot seqlock: an insert claims the slot with one CAS and is dropped
if another insert holds it; a find never waits and misses unless the
sequence is even and unchanged across its key loads. So a hit's key
and value come from one insert, unless 2^31 inserts land on that slot
during one find. A two-word design that splits the value across two
pointer words is not exact: two keys sharing one address can leave a
slot holding one key's high half next to the other's low half.
Misses solve in address order, since qEMD is not bit-symmetric; hit or
miss, the result is QEmd::compute of the address-ordered pair.
Zero-token documents bypass the cache. All-zero is the empty slot, so
value-initialization is the only pass over the table.

QEmd no longer owns a cache. PairCachedQEmd decorates it and
build_gem_graph(..., GemPairCache::On) creates one per call, where the
dataset cannot move. The decorator forwards compute, lower_bound,
fix_argument, comparator, router, the SVS_GEM_QEMD_COUNT hooks,
PruneStrategy, build_adaptor and build_entry_points; build_gem_graph
static_asserts that compare, broadcast, ShouldFix, HasTwoArgLowerBound
and the prune strategy match QEmd's.

The table is next_pow2(n_docs * kPairsPerDoc) slots, kPairsPerDoc =
1000, at most 2^27 slots (3 GiB). Lookup and hit counts moved into
QemdCounters under SVS_GEM_QEMD_COUNT; nothing prints by default.

BREAKING CHANGE: GemBuildParameters::qemd_pair_cache sits in what was
trailing padding, so a caller compiled against the old header passes
an indeterminate byte. Value-initialization does not make this safe:
GemBuildParameters is an aggregate, so `{}` aggregate-initializes and
leaves padding unspecified, and `GemBuildParameters bp;` does not
touch it. Covered by the unreleased 0.6 runtime bump of
codebook_refine_epochs, so callers relink once for all three fields.
build_gem_graph takes GemPairCache before the allocator, so callers
that pass an allocator add GemPairCache::Off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PairDistanceCache is now 8-way set-associative: 8-slot buckets of 24-byte
slots (192 B, cache-line aligned, states/lo/hi as three lines). Size is
min(budget / 24 B, n_docs * 1000) slots rounded down to whole buckets;
the budget defaults to 8 GiB (kDefaultBudgetBytes) and replaces the old
2^27-slot cap. A full bucket replaces a slot not hit since its last
sweep (one used bit per slot, CLOCK-style), after empty slots. The
per-slot seqlock stays, with a 31-bit sequence, so a lookup never
returns another pair's value.

GemPairCache becomes a struct {enabled, budget_bytes}; GemPairCache::On
and ::Off keep existing callers compiling. PairCachedQEmd counts lookups
and hits per copy (no shared atomic on the lookup path) and adds them to
the cache when destroyed; build_gem_graph reports them in GemBuildReport
(pair_cache_lookups, pair_cache_hits, pair_cache_hit_rate()).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add qemd_pair_cache_gib (default 8), validated to [1, 2^20] when the
cache is on, and pass it to build_gem_graph as the byte budget. The
SVS_GEM_BUILD_PHASES line now also reports refine_epochs, pair_cache,
pair_cache_gib and pair_cache_hit_rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A concurrent used-bit set or a replacement sweep changed the state word
between the seqlock loads and turned a valid read into a miss. Compare
only the sequence and value bits; exactness is unchanged. Also assert
that the 64-bit state atomics are lock-free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ahuber21
ahuber21 changed the base branch from main to dev/ahuber/late-interaction-base December 2, 2026 15:20

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant