diff --git a/DEVELOPER_GUIDE.md b/DEVELOPER_GUIDE.md index 6f0d2a7..0bd5964 100644 --- a/DEVELOPER_GUIDE.md +++ b/DEVELOPER_GUIDE.md @@ -589,7 +589,7 @@ Every serialized index starts with a fixed header (`nsparse::IndexHeader` in `ns The payload follows immediately, and its layout is the index type's own business. A type parses it in `read_index` (copying), `mmap_index` (borrowed from a file mapping), or both — `DiskSeismicIndex` is mmap-only and its `read_index` just throws, while `IDMapIndex` has no `mmap_index` at all and instead threads `io_flags` down to its delegate. -Versions are numbered **per index type**, not per file: `IndexIO::format_version()` returns the type's own `kFormatVersion`, so revising one type's payload leaves the others' numbering alone. An `IDMapIndex` writes its own header for the id map and then a second, complete header for the delegate it wraps, each with its own version. +Versions are numbered **per index type**, not per file: `IndexIO::format_version()` returns the type's own `kFormatVersion`, so revising one type's payload leaves the others' numbering alone. A file is stamped with `IndexIO::written_format_version()`, which defaults to the same; a type can stamp an older version when that file's payload is still the older layout, so older builds keep reading it (the disk SEISMIC types write 1 when nothing is truncated). An `IDMapIndex` writes its own header for the id map and then a second, complete header for the delegate it wraps, each with its own version. The same central code rejects a version outside `1..format_version()` before dispatching to either parse path — a file from a newer build fails with a clear error instead of consuming whatever its fields happen to align with. diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index fd93b7b..449c84f 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -94,6 +94,18 @@ target_link_libraries(index_size_stats PRIVATE absl::flat_hash_map ) +# Recall of a narrower inline forward layout, simulated over an index already on +# disk. Not a google-benchmark target: it reports recall for a grid of candidate +# formats, and deliberately says nothing about latency. +add_executable(prune_sim prune_sim.cpp) +target_include_directories(prune_sim PRIVATE ${PROJECT_SOURCE_DIR}) +target_link_libraries(prune_sim PRIVATE + ${NSPARSE_BENCH_LIB} + OpenMP::OpenMP_CXX + absl::flat_hash_set + absl::flat_hash_map +) + # Peak-RSS build-memory driver for the term-batched build. Not a # google-benchmark target: that harness reports throughput, and what matters here # is the high-water mark of a single build, one configuration per process. diff --git a/benchmarks/DISK_SEISMIC_BENCH.md b/benchmarks/DISK_SEISMIC_BENCH.md index 20cd089..5d130dc 100644 --- a/benchmarks/DISK_SEISMIC_BENCH.md +++ b/benchmarks/DISK_SEISMIC_BENCH.md @@ -107,6 +107,113 @@ of the inline forward index and delta coding would take 29.5 → 19.4 GiB, but d the critical path of scoring a block and measured a 1.5× warm-latency cost, so it was not taken. 4-bit values would save 7.4 GiB and is lossy. `doc_id[]`/`off[]` are ~1% together. +## Truncating the extra inline copies — `inline_max_nnz` + +Packing the blocks removed bytes nothing read. What remains is bytes that *are* read but are +**duplicated**: `index_size_stats` puts the inline forward index at 45.6 of the 50.0 GiB, and +a doc's vector is stored **12.97 times** over — once per posting list that retains it. One +shared copy per doc would take `comps[] + vals[]` from 44.28 GiB to 3.42. That duplication is +not waste, it is the whole design: it makes a block one contiguous read. + +`inline_max_nnz=T` splits the difference. One copy of each doc stays whole (the one the +`DocLocator` directory already points at); every other copy keeps only its T largest codes. +Block scores are then **lower bounds**, so search re-scores its `rescore` best candidates +against the whole copies and re-ranks. Two knobs, one at build time and one per query: + +| | T=0 (baseline) | T=64 | T=48 | T=32 | +|---|---|---|---|---| +| index file | 49.967 GiB | 27.667 GiB | **22.971 GiB** | 18.246 GiB | +| vs baseline | | −44.6% | **−54.0%** | −63.5% | +| inline forward index | 45.570 GiB | 23.27 GiB | 18.574 GiB | 13.850 GiB | +| stored nnz | 15.85 e9 | 7.78 e9 | 6.20 e9 | 4.51 e9 | +| cluster summaries | 4.297 GiB (8.6%) | 4.297 (15.5%) | 4.297 (18.7%) | 4.297 (23.6%) | +| build wall / peak RSS | 9:01 / 20.9 GiB | 11:20 / 20.9 | 11:12 / 20.9 | 8:36 / 20.9 | + +Latency and recall, `base_full` / λ=6000 β=400 α=0.4 / 8-bit / cut=3 k'=50 k=10 / 1 thread, +`seismic-ec2`, one binary per round over all the files, caches dropped before each arm's first +pass. `seed=42` on every build, so recall differences are the format's and not k-means noise: + +| arm | rescore | warm p50 | vs baseline | recall@10 | Δ recall | +|---|---|---|---|---|---| +| T=0 | — | 0.2157 ms | 1.00× | 0.926246 | — | +| T=64 | 10 | 0.1698 ms | 0.79× | 0.844728 | −8.2 pp | +| T=64 | 50 | 0.1899 ms | 0.88× | 0.924900 | −0.13 pp | +| T=64 | 100 | **0.2117 ms** | **0.98×** | 0.925989 | −0.03 pp | +| T=64 | 200 | 0.2565 ms | 1.19× | 0.926232 | −0.001 pp | +| T=64 | 300 | 0.2986 ms | 1.38× | 0.926203 | −0.004 pp | +| T=48 | none | 0.1569 ms | 0.73× | 0.784585 | −14.2 pp | +| T=48 | 100 | 0.2033 ms | 0.94× | 0.924484 | −0.18 pp | +| T=48 | 200 | **0.2470 ms** | **1.15×** | 0.925888 | −0.04 pp | +| T=48 | 300 | 0.2877 ms | 1.33× | 0.926089 | −0.02 pp | +| T=48 | 600 | 0.4046 ms | 1.88× | 0.926203 | −0.004 pp | +| T=32 | 100 | 0.1936 ms | 0.90× | 0.915115 | −1.11 pp | +| T=32 | 200 | 0.2359 ms | 1.09× | 0.922908 | −0.33 pp | +| T=32 | 300 | 0.2760 ms | 1.28× | 0.924699 | −0.15 pp | + +Using it, from C++ or Python (the SWIG bindings expose the same names): + +```python +index = nsparse.index_factory(dim, "disk_seismic_sq,quantizer=8bit|vmin=0|vmax=3|" + "lambda=6000|beta=400|alpha=0.4|inline_max_nnz=64") +# ... add, build, write_index, read_index(path, nsparse.kUseMmap) ... +params = nsparse.DiskSeismicSQSearchParameters(0.0, 3.0, 3, 50, 100) # vmin vmax cut k' rescore +params.rescore = 200 # per query; default nsparse.kAutoRescoreDepth = max(200, 3·k) +``` + +`inline_max_nnz` is fixed at build time and recorded in the file (as 0 when no copy was long +enough to cut). `rescore` is ignored on an untruncated index; the default, `kAutoRescoreDepth` +(0), resolves to max(200, 3·k), because the depth a query needs grows with k; an explicit value +is raised to k when smaller and capped at the pool the selected blocks hold; a negative one is +rejected. + +Two points worth naming, both at this table's operating point only (warm, k=10, cut=3, k'=50, +λ=6000): at a larger k the depth has to grow with it, which is what the automatic default does. +**T=64 with rescore=100 is free** here: 44.6% off the file at 0.98× the +latency and a recall difference smaller than the ±0.1 pp a k-means seed causes on its own. +**T=48 with rescore=200** buys another 9 points of file size for 1.15× latency, still at +recall parity. Below T=48 recall starts to cost real ground, so T=32 is only worth it when disk +is the binding constraint. + +Read the "none" row as the cost of the scan alone: with 39% of the nnz left inline, scoring the +candidate blocks is **0.73×** the baseline. Everything above that is the second pass, and it is +not arithmetic — at ~0.45 µs per re-scored doc it is ~1400 cycles to read 420 bytes, because +reaching one whole copy is a four-deep chase (locator → directory → block header → slice) +through tables far past any cache. That is why `rescore` is the latency knob and why +`resolve_docs` walks the candidates through each step together, in bounded chunks, rather than +one doc at a time: doing that took the per-doc cost from 0.68 µs to 0.45 µs (−34%) with +bit-identical results at every depth. + +Two honest costs beyond latency, both from one cold run (caches dropped, all 6,980 queries) at +T=48 with `rescore=300`. Both grow with the depth: + +- **Cold first pass** 897 s → 1,153 s (+28.5%). The file is half the size, but the second pass + reads whole copies from blocks the scan did not select: ~142 distinct blocks per query beyond + the scan's 50 at `rescore=300` (~93 at 200), so a cold run faults in more distinct pages even + though there are fewer bytes overall. +- **Resident set** 6.04 → 7.56 GiB (+25%), `RssFile` 5.71 → 7.23, for the same reason. At + `rescore=200`, the default at k=10, a page-exact replay gives `RssFile` 5.71 → 6.60 GiB + (+16%). The smaller file does *not* buy a smaller working set here; it buys disk. + +What did **not** work, so nobody repeats it: + +- **Choosing the kept components per block instead of per doc.** The hypothesis was that a + query selecting a block correlates with that block's summary, so keeping the components with + the largest `code × block-max` should rank better than the doc's own largest codes. + Simulated over the real index it is a wash — T=48 at depth 100 gives 0.9249 against 0.9246, + T=32 0.9172 against 0.9175. The block max is usually the doc's own value for the components + that matter, so the ordering barely moves. More fundamentally: which components a query will + hit is query information, and no static choice can carry it. +- **Bounding the second pass** so most candidates skip it. The dropped codes are all below the + doc's boundary code, which gives `truncated + boundary × query_L1` as an upper bound — two + orders of magnitude looser than the scores it would have to separate. It prunes nothing. + +`prune_sim [criterion]` +is what made this affordable: it reads an existing index and runs the real block-budget search +over a *simulated* truncated layout, so a whole (T, rescore) grid costs one pass instead of a +build per cell. Its T=0/R=0 row must reproduce the index's own measured recall — that is the +control, and it does (0.926103 against 0.926074 measured). Trust it for recall only; it +recomputes the truncation per query, so its timings mean nothing. + ## Caveats - **`base_small` is a smoke test, not a benchmark** — it fits in cache, so the diff --git a/benchmarks/index_size_stats.cpp b/benchmarks/index_size_stats.cpp index 6049868..777a4dc 100644 --- a/benchmarks/index_size_stats.cpp +++ b/benchmarks/index_size_stats.cpp @@ -68,6 +68,9 @@ uint64_t vbyte_len(uint64_t value) { return bytes; } +// Retention checkpoints for the per-doc "keep the T largest codes" policy. +constexpr std::array kTopT = {16, 24, 32, 48, 64, 96}; + struct Stats { uint64_t n_blocks = 0; // Doc slots, i.e. postings: a doc counts once per block that holds it. @@ -98,8 +101,50 @@ struct Stats { uint64_t blocks_docids_unsorted = 0; uint64_t vals_nonzero = 0; uint64_t vals_le15 = 0; // would fit 4 bits as stored + + // Lossy levers. The code histogram gives every code-threshold cut at once + // (how many values, and how much of the L1 mass, sit at or below a code); + // kept_nnz/kept_mass give the per-doc top-T cut. Both weight a doc once per + // block that holds it, which is what the stored bytes do. + std::array code_hist{}; + uint64_t mass_total = 0; + std::array kept_nnz{}; + std::array kept_mass{}; + + // Distinct component ids per block, i.e. what a per-block dictionary could + // fold away: the ratio to nnz bounds any transposed/dictionary layout. + uint64_t distinct_comps = 0; }; +// The T largest codes of one doc, by descending-code walk over a 256-bin +// histogram: how many values that keeps (ties at the cut included, so >= T) and +// how much of the doc's L1 mass they carry. O(nnz + 256) per doc, no sort. +void size_doc_topt(const uint8_t* vals, uint32_t len, Stats* stats) { + std::array hist{}; + uint64_t mass = 0; + for (uint32_t j = 0; j < len; ++j) { + hist[vals[j]] += 1; + mass += vals[j]; + } + stats->mass_total += mass; + size_t next = 0; + uint64_t kept = 0; + uint64_t kept_mass = 0; + for (int code = 255; code >= 0 && next < kTopT.size(); --code) { + kept += hist[code]; + kept_mass += static_cast(hist[code]) * + static_cast(code); + // Every checkpoint this bin reached takes the totals as they stand: a + // partial bin cannot be split without ordering the ties, and rounding up + // to the whole bin is what a writer keeping >= T values would store. + while (next < kTopT.size() && (kept >= kTopT[next] || code == 0)) { + stats->kept_nnz[next] += std::min(kept, len); + stats->kept_mass[next] += kept_mass; + ++next; + } + } +} + // Component ids of one doc: how much delta coding would buy, two ways, and // whether they ascend (which is what makes the deltas small). void size_doc_comps(const nsparse::term_t* comps, uint32_t len, Stats* stats) { @@ -132,6 +177,22 @@ void size_doc_comps(const nsparse::term_t* comps, uint32_t len, Stats* stats) { stats->c_comps_flagged += flagged; } +// Distinct component ids in a block, counted with a stamp array indexed by +// component id: O(nnz), and no per-block clearing (the stamp is the block +// ordinal). `seen` must be sized to the term space. +uint64_t count_distinct(const BlockView& view, uint64_t total_nnz, + uint64_t stamp, std::vector* seen) { + uint64_t distinct = 0; + for (uint64_t j = 0; j < total_nnz; ++j) { + const uint32_t comp = view.comps[j]; + if (comp < seen->size() && (*seen)[comp] != stamp) { + (*seen)[comp] = stamp; + ++distinct; + } + } + return distinct; +} + void accumulate(const BlockView& view, size_t element_size, uint64_t align, Stats* stats) { const uint64_t n_docs = view.n_docs; @@ -194,6 +255,10 @@ void accumulate(const BlockView& view, size_t element_size, uint64_t align, const uint8_t value = view.vals[j]; stats->vals_nonzero += value != 0 ? 1 : 0; stats->vals_le15 += value <= kFourBitMax ? 1 : 0; + stats->code_hist[value] += 1; + } + for (uint32_t i = 0; i < view.n_docs; ++i) { + size_doc_topt(view.doc_vals(i, 1), view.nnz(i), stats); } } } @@ -260,6 +325,10 @@ int main(int argc, char** argv) { const uint64_t align = fwd.page_size(); Stats stats; + // Stamped by block ordinal (from 1, so the zero-initialized state is "never + // seen"), which is why the per-block distinct count needs no clearing. + std::vector seen(static_cast(dimension) + 1, 0); + uint64_t stamp = 0; for (uint32_t pl = 0; pl < fwd.num_lists(); ++pl) { const uint64_t n_blocks = fwd.num_blocks_in_list(pl); for (uint32_t block = 0; block < n_blocks; ++block) { @@ -268,6 +337,8 @@ int main(int argc, char** argv) { continue; } accumulate(view, element_size, align, &stats); + stats.distinct_comps += + count_distinct(view, view.offsets[view.n_docs], ++stamp, &seen); } } stats.b_dir = stats.n_blocks * sizeof(nsparse::detail::InlineDirEntry); @@ -323,7 +394,73 @@ int main(int argc, char** argv) { saving("vals: 4-bit codes", stats.b_vals, stats.nnz / 2); } + // Fewer stored values, rather than fewer bits per value: comps + vals are + // ~3 bytes of every nnz, so dropping an nnz saves all three and also drops + // the dot-product term that reads it. Both cuts are lossy -- the sizes here + // say what they would buy, not whether recall survives them. + if (element_size == 1) { + const double all_nnz = static_cast(stats.nnz); + const double all_mass = static_cast(stats.mass_total); + std::printf( + "\n== dropping low-weight components (lossy; comps+vals = %.1f%% " + "of the file) ==\n", + 100.0 * static_cast(stats.b_comps + stats.b_vals) / + static_cast(file_bytes)); + std::printf(" keep code > threshold:\n"); + uint64_t at_or_below = 0; + uint64_t mass_at_or_below = 0; + for (uint32_t code = 0; code < 256; ++code) { + at_or_below += stats.code_hist[code]; + mass_at_or_below += + stats.code_hist[code] * static_cast(code); + // A few decades of the curve is enough to read its shape. + if (code != 0 && code != 1 && code != 2 && code != 4 && + code != 8 && code != 16 && code != 32 && code != 64) { + continue; + } + const double kept = all_nnz - static_cast(at_or_below); + std::printf( + " > %3u keep %5.1f%% of nnz, %5.1f%% of L1 mass " + "file ~%7.3f GiB\n", + code, 100.0 * kept / all_nnz, + 100.0 * (all_mass - static_cast(mass_at_or_below)) / + all_mass, + gib(file_bytes) - + (gib(stats.b_comps + stats.b_vals) * + (static_cast(at_or_below) / all_nnz))); + } + std::printf(" keep the T largest codes per doc:\n"); + for (size_t i = 0; i < kTopT.size(); ++i) { + const double kept = static_cast(stats.kept_nnz[i]); + std::printf( + " T = %3u keep %5.1f%% of nnz, %5.1f%% of L1 mass " + "file ~%7.3f GiB\n", + kTopT[i], 100.0 * kept / all_nnz, + 100.0 * static_cast(stats.kept_mass[i]) / all_mass, + gib(file_bytes) - + (gib(stats.b_comps + stats.b_vals) * (1.0 - kept / all_nnz))); + } + // A deduplicated store costs one copy of the corpus; the inline layout + // stores one per block that holds the doc. + std::printf( + " one shared copy per doc instead of %.2f inline copies: " + "%.3f -> %.3f GiB for comps+vals\n", + static_cast(stats.n_docs) / + static_cast(num_vectors), + gib(stats.b_comps + stats.b_vals), + gib(stats.b_comps + stats.b_vals) / + (static_cast(stats.n_docs) / + static_cast(num_vectors))); + } + std::printf("\n== diagnostics ==\n"); + std::printf(" distinct comps per block: %.1f of %.1f nnz (%.2fx)\n", + static_cast(stats.distinct_comps) / + static_cast(stats.n_blocks), + static_cast(stats.nnz) / + static_cast(stats.n_blocks), + static_cast(stats.nnz) / + static_cast(stats.distinct_comps)); std::printf(" docs with non-ascending comps: %llu / %llu\n", static_cast(stats.docs_comps_unsorted), static_cast(stats.n_docs)); diff --git a/benchmarks/prune_sim.cpp b/benchmarks/prune_sim.cpp new file mode 100644 index 0000000..7cb07f0 --- /dev/null +++ b/benchmarks/prune_sim.cpp @@ -0,0 +1,530 @@ +/** + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +// What would recall be if the inline forward index stored only part of each +// document? Reads an existing 8-bit disk_seismic_sq index and runs the real +// block-budget search over a *simulated* narrower layout, so a candidate format +// can be scored for recall before anything is built: an index takes tens of +// minutes to write and 50 GiB to hold, and a grid over it would take a day. +// +// prune_sim \ +// +// +// Each (T, R) pair is one simulated layout: +// T keep only the T largest codes of each doc in each block (0 = keep all). +// This is the lossy part: block scoring sees a truncated vector. +// R after block scoring, re-score the R best candidates against their full +// vectors and re-rank (0 = no re-scoring). Stands in for a deduplicated +// whole-corpus store, which costs one copy of the corpus rather than the +// ~13 the inline layout keeps -- so it is read here from the same block, +// the bytes being identical either way. +// T=0,R=0 reproduces the shipped index and must match its measured recall; +// that is the control this tool is trusted on. +// +// Latency here means nothing (the truncation is recomputed per query from the +// full stored vector, which a real build would do once at write time) -- this +// answers recall only, and reports the kept-nnz fraction so the size the format +// would reach can be read off the same run. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "nsparse/cluster/inverted_list_clusters.h" +#include "nsparse/disk_seismic_search.h" +#include "nsparse/inline_forward_index.h" +#include "nsparse/io/inline_forward_index_io.h" +#include "nsparse/io/seismic_invlists_writer.h" +#include "nsparse/types.h" +#include "nsparse/utils/distance_simd.h" +#include "nsparse/utils/mmap_cursor.h" +#include "nsparse/utils/mmap_file.h" +#include "nsparse/utils/ranker.h" +#include "nsparse/utils/scalar_quantizer.h" + +using nsparse::InvertedListClusters; +using nsparse::MmapCursor; +using nsparse::MmapFile; +using nsparse::QuantizerType; +using nsparse::ScalarQuantizer; +using nsparse::SeismicInvertedListsWriter; +using nsparse::detail::BlockCandidate; +using nsparse::detail::BlockView; +using nsparse::detail::InlineForwardIndex; + +namespace { + +struct CSRMatrix { + int64_t nrow = 0; + int64_t ncol = 0; + int64_t nnz = 0; + std::vector indptr; + std::vector indices; + std::vector data; +}; + +CSRMatrix read_csr(const std::string& path) { + std::ifstream file(path, std::ios::binary); + if (!file.is_open()) { + throw std::runtime_error("cannot open CSR file: " + path); + } + CSRMatrix matrix; + std::array sizes{}; + file.read(reinterpret_cast(sizes.data()), sizeof(sizes)); + matrix.nrow = sizes[0]; + matrix.ncol = sizes[1]; + matrix.nnz = sizes[2]; + matrix.indptr.resize(matrix.nrow + 1); + file.read(reinterpret_cast(matrix.indptr.data()), + static_cast((matrix.nrow + 1) * + sizeof(int64_t))); + std::vector indices32(matrix.nnz); + file.read(reinterpret_cast(indices32.data()), + static_cast(matrix.nnz * sizeof(int32_t))); + matrix.indices.assign(indices32.begin(), indices32.end()); + matrix.data.resize(matrix.nnz); + file.read(reinterpret_cast(matrix.data.data()), + static_cast(matrix.nnz * sizeof(float))); + return matrix; +} + +std::vector> read_truth(const std::string& path) { + std::ifstream file(path); + if (!file.is_open()) { + throw std::runtime_error("cannot open truth file: " + path); + } + std::vector> truth; + std::string line; + while (std::getline(file, line)) { + if (line.empty()) { + continue; + } + std::vector ids; + std::stringstream stream(line); + std::string field; + while (std::getline(stream, field, ',')) { + // The truth file holds ids in scientific notation ("7.187155e+06"), + // so it has to be read as a double: an integer parse would stop at + // the decimal point and silently yield 7. + if (!field.empty()) { + ids.push_back(std::llround(std::stod(field))); + } + } + truth.push_back(std::move(ids)); + } + return truth; +} + +std::vector parse_list(const std::string& text) { + std::vector values; + std::stringstream stream(text); + std::string field; + while (std::getline(stream, field, ',')) { + if (!field.empty()) { + values.push_back( + static_cast(std::stoul(field))); + } + } + return values; +} + +// One candidate doc, carrying where its full vector lives so the re-scoring +// pass can reach it without a second directory lookup. The pointers borrow from +// the mapping, which outlives the query. +struct Candidate { + float approx = 0.0F; + nsparse::idx_t doc_id = 0; + const nsparse::term_t* comps = nullptr; + const uint8_t* vals = nullptr; + uint32_t nnz = 0; +}; + +// How a truncated copy chooses which components to keep. +enum class Criterion { + // The doc's own largest codes. Ignores which block the copy is in, so every + // copy of a doc keeps the same components. + kValue = 0, + // The doc's code times the block's largest code for that component. A query + // that selects a block scores highly against the block's summary, so its + // weight sits on the components the block as a whole is strong in -- which + // makes this a far better predictor of what the query will actually dot + // against than the doc's own weight alone. Each copy keeps a different set. + kValueTimesBlockMax = 1, +}; + +// Dot the query against only the `keep` components a `kValueTimesBlockMax` copy +// would have stored. `weight` is the block aggregate, indexed by component. +float weighted_truncated_score(const nsparse::term_t* comps, + const uint8_t* vals, uint32_t nnz, + const uint8_t* dense, + const std::vector& weight, + uint32_t keep, + std::vector>* scratch, + uint64_t* kept_out) { + scratch->clear(); + scratch->reserve(nnz); + for (uint32_t i = 0; i < nnz; ++i) { + scratch->emplace_back( + static_cast(vals[i]) * weight[comps[i]], i); + } + std::nth_element(scratch->begin(), + scratch->begin() + static_cast(keep) - 1, + scratch->end(), + [](const auto& a, const auto& b) { return a.first > b.first; }); + uint32_t score = 0; + for (uint32_t i = 0; i < keep; ++i) { + const uint32_t idx = (*scratch)[i].second; + score += static_cast(dense[comps[idx]]) * vals[idx]; + } + *kept_out += keep; + return static_cast(score); +} + +// Dot the query against only the `keep` largest codes of a doc, the vector a +// truncating writer would have stored. The cut code comes from a 256-bin +// histogram walked downwards; codes above it are all kept and the bin that +// straddles the limit is taken in array order, which is the tie-break a writer +// doing the same partial selection would land on. +float truncated_score(const nsparse::term_t* comps, const uint8_t* vals, + uint32_t nnz, const uint8_t* dense, uint32_t keep, + uint64_t* kept_out) { + std::array hist{}; + for (uint32_t i = 0; i < nnz; ++i) { + hist[vals[i]] += 1; + } + uint32_t above = 0; + int cut = 255; + for (; cut >= 0; --cut) { + if (above + hist[cut] > keep) { + break; + } + above += hist[cut]; + } + if (cut < 0) { // the whole vector fits the budget + *kept_out += nnz; + return static_cast( + nsparse::detail::dot_product_uint8_dense(comps, vals, nnz, dense)); + } + uint32_t quota = keep - above; + uint32_t score = 0; + uint32_t kept = 0; + const auto cut_code = static_cast(cut); + for (uint32_t i = 0; i < nnz; ++i) { + const uint8_t value = vals[i]; + if (value > cut_code) { + // fall through to the accumulate below + } else if (value == cut_code && quota > 0) { + --quota; + } else { + continue; + } + score += static_cast(dense[comps[i]]) * value; + ++kept; + } + *kept_out += kept; + return static_cast(score); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 9) { + std::fprintf(stderr, + "usage: %s " + " [criterion]\n", + argv[0]); + return 1; + } + const std::string index_path = argv[1]; + const CSRMatrix queries = read_csr(argv[2]); + const std::vector> truth = read_truth(argv[3]); + const int k = std::stoi(argv[4]); + const int cut = std::stoi(argv[5]); + const int k_prime = std::stoi(argv[6]); + const std::vector t_list = parse_list(argv[7]); + const std::vector r_list = parse_list(argv[8]); + // 0 = keep the doc's own largest codes; 1 = keep the largest + // code * block-max products (see Criterion). + const auto criterion = static_cast(argc > 9 ? std::stoi(argv[9]) + : 0); + + MmapFile file(index_path, MmapFile::AccessPattern::kPointLookup); + MmapCursor cursor(file.data(), file.size()); + const auto type_id = cursor.read_scalar(); + cursor.read_scalar(); // format version + const auto dimension = cursor.read_scalar(); + std::array fourcc{}; + std::memcpy(fourcc.data(), &type_id, 4); + if (std::strcmp(fourcc.data(), "DSSQ") != 0) { + std::fprintf(stderr, "not a disk_seismic_sq index (got %s)\n", + fourcc.data()); + return 1; + } + const auto quantizer_type = cursor.read_scalar(); + const auto vmin = cursor.read_scalar(); + const auto vmax = cursor.read_scalar(); + if (quantizer_type != QuantizerType::QT_8bit) { + std::fprintf(stderr, "only the 8-bit quantizer is simulated\n"); + return 1; + } + const ScalarQuantizer quantizer(quantizer_type, vmin, vmax); + + const auto num_vectors = cursor.read_scalar(); + SeismicInvertedListsWriter inv_lists; + inv_lists.mmap_deserialize(&cursor); + const std::vector clusters = + std::move(inv_lists.release()); + InlineForwardIndex fwd; + fwd.mmap_deserialize(&cursor); + if (fwd.element_size() != 1) { + std::fprintf(stderr, "index element_size is %zu, expected 1\n", + fwd.element_size()); + return 1; + } + + // Queries are encoded with the index's own range, which is what + // DiskSeismicScalarQuantizedIndex::encode_query does absent an override. + std::vector query_codes(queries.nnz); + quantizer.encode(queries.data.data(), query_codes.data(), queries.nnz); + + const int64_t n_queries = + std::min(queries.nrow, static_cast(truth.size())); + std::printf( + "index %s dim=%d docs=%llu blocks=%llu | queries %lld | k=%d cut=%d " + "k_prime=%d\n", + index_path.c_str(), dimension, + static_cast(num_vectors), + static_cast(fwd.num_blocks()), + static_cast(n_queries), k, cut, k_prime); + std::printf("criterion %d (%s)\n", static_cast(criterion), + criterion == Criterion::kValue ? "code" + : "code * block max"); + std::printf("%6s %6s %10s %10s %10s\n", "T", "R", "recall", "kept_nnz", + "cands"); + + for (const uint32_t keep : t_list) { + for (const uint32_t rescore : r_list) { + // Only the candidate pool size can change the result when nothing + // is truncated, so skip the rescoring sweep for the control. + if (keep == 0 && rescore != 0 && rescore != r_list.front()) { + continue; + } + double hits = 0; + uint64_t kept_total = 0; + uint64_t nnz_total = 0; + uint64_t cand_total = 0; + +#pragma omp parallel + { + std::vector dense(static_cast(dimension), 0); + absl::flat_hash_set visited; + std::vector block_candidates; + std::vector score_scratch; + std::vector candidates; + // Block aggregate, indexed by component, with a per-block stamp + // so it never has to be cleared. + std::vector weight(static_cast(dimension), 0); + std::vector stamped(static_cast(dimension), 0); + std::vector> sel_scratch; + uint64_t block_stamp = 0; + double local_hits = 0; + uint64_t local_kept = 0; + uint64_t local_nnz = 0; + uint64_t local_cands = 0; + +#pragma omp for schedule(dynamic, 16) + for (int64_t q = 0; q < n_queries; ++q) { + const int64_t start = queries.indptr[q]; + const auto len = + static_cast(queries.indptr[q + 1] - start); + const nsparse::term_t* q_idx = + queries.indices.data() + start; + const uint8_t* q_val = query_codes.data() + start; + for (size_t i = 0; i < len; ++i) { + dense[q_idx[i]] = q_val[i]; + } + + const std::vector cuts = + nsparse::detail::top_cut_tokens(q_idx, q_val, len, cut, + 1); + block_candidates.clear(); + for (const nsparse::term_t term : cuts) { + if (term >= clusters.size()) { + continue; + } + const InvertedListClusters& list = clusters[term]; + const size_t n_clusters = list.cluster_size(); + if (n_clusters == 0) { + continue; + } + list.score_summaries_transposed(q_idx, q_val, len, + score_scratch); + for (size_t cid = 0; cid < n_clusters; ++cid) { + block_candidates.push_back( + {score_scratch[cid], term, + static_cast(cid)}); + } + } + const size_t budget = + std::min(static_cast(k_prime), + block_candidates.size()); + if (budget < block_candidates.size()) { + std::nth_element( + block_candidates.begin(), + block_candidates.begin() + + static_cast(budget), + block_candidates.end(), + [](const BlockCandidate& a, + const BlockCandidate& b) { + return a.score > b.score; + }); + block_candidates.resize(budget); + } + + visited.clear(); + candidates.clear(); + for (const BlockCandidate& block : block_candidates) { + const BlockView view = fwd.block(block.pl, block.cid); + if (view.absent()) { + continue; + } + if (criterion == Criterion::kValueTimesBlockMax && + keep != 0) { + ++block_stamp; + const uint32_t total = view.offsets[view.n_docs]; + for (uint32_t j = 0; j < total; ++j) { + const nsparse::term_t comp = view.comps[j]; + const uint8_t value = view.vals[j]; + if (stamped[comp] != block_stamp) { + stamped[comp] = block_stamp; + weight[comp] = value; + } else if (value > weight[comp]) { + weight[comp] = value; + } + } + } + for (uint32_t i = 0; i < view.n_docs; ++i) { + const auto doc_id = + static_cast(view.doc_ids[i]); + if (!visited.insert(doc_id).second) { + continue; + } + const uint32_t nnz = view.nnz(i); + const nsparse::term_t* comps = view.doc_comps(i); + const uint8_t* vals = view.doc_vals(i, 1); + local_nnz += nnz; + float score = 0.0F; + if (keep == 0 || nnz <= keep) { + local_kept += nnz; + score = static_cast( + nsparse::detail::dot_product_uint8_dense( + comps, vals, nnz, dense.data())); + } else if (criterion == + Criterion::kValueTimesBlockMax) { + score = weighted_truncated_score( + comps, vals, nnz, dense.data(), weight, + keep, &sel_scratch, &local_kept); + } else { + score = truncated_score(comps, vals, nnz, + dense.data(), keep, + &local_kept); + } + candidates.push_back( + {score, doc_id, comps, vals, nnz}); + } + } + local_cands += candidates.size(); + + // Rank on the truncated scores, then re-score the top R + // against the full vectors and re-rank those. + const size_t pool = + rescore == 0 + ? static_cast(k) + : std::max(static_cast(k), + static_cast(rescore)); + const size_t take = std::min(pool, candidates.size()); + std::partial_sort( + candidates.begin(), + candidates.begin() + static_cast(take), + candidates.end(), + [](const Candidate& a, const Candidate& b) { + return a.approx > b.approx; + }); + candidates.resize(take); + if (rescore != 0 && keep != 0) { + for (Candidate& candidate : candidates) { + candidate.approx = static_cast( + nsparse::detail::dot_product_uint8_dense( + candidate.comps, candidate.vals, + candidate.nnz, dense.data())); + } + const size_t final_take = + std::min(static_cast(k), candidates.size()); + std::partial_sort( + candidates.begin(), + candidates.begin() + + static_cast(final_take), + candidates.end(), + [](const Candidate& a, const Candidate& b) { + return a.approx > b.approx; + }); + candidates.resize(final_take); + } + + const std::vector& want = truth[q]; + const std::unordered_set want_set(want.begin(), + want.end()); + size_t found = 0; + for (size_t i = 0; + i < candidates.size() && i < static_cast(k); + ++i) { + if (want_set.count( + static_cast(candidates[i].doc_id)) != + 0) { + ++found; + } + } + local_hits += static_cast(found) / + static_cast(k); + + for (size_t i = 0; i < len; ++i) { + dense[q_idx[i]] = 0; + } + } +#pragma omp critical + { + hits += local_hits; + kept_total += local_kept; + nnz_total += local_nnz; + cand_total += local_cands; + } + } + + std::printf("%6u %6u %10.6f %9.2f%% %10.1f\n", keep, rescore, + hits / static_cast(n_queries), + 100.0 * static_cast(kept_total) / + static_cast(nnz_total), + static_cast(cand_total) / + static_cast(n_queries)); + std::fflush(stdout); + } + } + return 0; +} diff --git a/benchmarks/sq_residency_bench.cpp b/benchmarks/sq_residency_bench.cpp index 4af41f8..ae07156 100644 --- a/benchmarks/sq_residency_bench.cpp +++ b/benchmarks/sq_residency_bench.cpp @@ -19,7 +19,7 @@ // // build // search [truth.txt|-] [cut] -// [k_prime] [heap_factor] [labels_out.txt] +// [k_prime] [heap_factor] [labels_out.txt|-] [rescore] #include #include @@ -37,6 +37,7 @@ #include #include "nsparse/disk_seismic_index.h" +#include "nsparse/disk_seismic_search.h" #include "nsparse/index.h" #include "nsparse/index_factory.h" #include "nsparse/io/index_io.h" @@ -188,7 +189,7 @@ int do_search(int argc, char** argv) { if (argc < 7) { std::cerr << "search " "[truth.txt|-] [cut] [k_prime] [heap_factor] " - "[labels_out.txt]\n"; + "[labels_out.txt|-] [rescore|-]\n"; return 2; } std::string dat_path = argv[2]; @@ -208,7 +209,15 @@ int do_search(int argc, char** argv) { const float heap_factor = argc > 10 ? static_cast(std::atof(argv[10])) : 1.0F; // Where to write the final labels, in the truth-file format, so another run // can be scored against them. - const std::string labels_out_path = argc > 11 ? argv[11] : ""; + const std::string labels_out_path = + (argc > 11 && std::strcmp(argv[11], "-") != 0) ? argv[11] : ""; + // Candidates re-scored against their whole vectors, for an index whose + // inline copies are truncated (inline_max_nnz); absent or "-" is the + // library's automatic depth, and anything else is passed through as given + // (so a negative is rejected by search). A whole-copy index ignores it. + const int rescore = (argc > 12 && std::strcmp(argv[12], "-") != 0) + ? std::stoi(argv[12]) + : nsparse::kAutoRescoreDepth; const int io_flags = residency == "mmap" ? nsparse::IndexIoFlag::kUseMmap : 0; @@ -237,8 +246,13 @@ int do_search(int argc, char** argv) { std::unique_ptr params; if (k_prime > 0) { - params = std::make_unique(cut, k_prime); - std::cout << "search_params cut " << cut << " k_prime " << k_prime << "\n"; + params = std::make_unique( + cut, k_prime, rescore); + std::cout << "search_params cut " << cut << " k_prime " << k_prime + << " rescore " << rescore << " (effective " + << nsparse::detail::resolve_rescore_depth( + std::max(rescore, 0), k) + << ")\n"; } else { params = std::make_unique(cut, heap_factor); std::cout << "search_params cut " << cut << " heap_factor " << heap_factor << "\n"; diff --git a/nsparse/CMakeLists.txt b/nsparse/CMakeLists.txt index 9b0b889..31452aa 100644 --- a/nsparse/CMakeLists.txt +++ b/nsparse/CMakeLists.txt @@ -60,6 +60,7 @@ set(NSPARSE_HEADERS utils/distance_sve.h utils/distance_simd.h utils/ranker.h + utils/omp_exception.h cluster/random_kmeans.h cluster/inverted_list_clusters.h cluster/kmeans_utils.h diff --git a/nsparse/disk_seismic_index.cpp b/nsparse/disk_seismic_index.cpp index a5cffd2..0647c30 100644 --- a/nsparse/disk_seismic_index.cpp +++ b/nsparse/disk_seismic_index.cpp @@ -27,8 +27,9 @@ namespace nsparse { DiskSeismicIndex::DiskSeismicIndex(int dim) : DiskSeismicIndexBase(dim, detail::kDefaultSeismicClusterParams) {} -DiskSeismicIndex::DiskSeismicIndex(int dim, SeismicClusterParameters parameter) - : DiskSeismicIndexBase(dim, parameter) {} +DiskSeismicIndex::DiskSeismicIndex(int dim, SeismicClusterParameters parameter, + uint32_t inline_max_nnz) + : DiskSeismicIndexBase(dim, parameter, inline_max_nnz) {} size_t DiskSeismicIndex::code_element_size() const { return U32; } @@ -58,7 +59,7 @@ DiskSeismicIndex* DiskSeismicIndex::mmap_index(const IndexHeader& header, cursor.skip(pos); // No extra header for the float index; the shared payload follows directly. - index->load_mapped_payload(&cursor, std::move(mmap_file)); + index->load_mapped_payload(&cursor, std::move(mmap_file), header.version); return index.release(); } } // namespace nsparse diff --git a/nsparse/disk_seismic_index.h b/nsparse/disk_seismic_index.h index 7ab1abf..7a1d858 100644 --- a/nsparse/disk_seismic_index.h +++ b/nsparse/disk_seismic_index.h @@ -24,15 +24,39 @@ namespace nsparse { // Default block budget K': the primary recall/latency knob. inline constexpr int kDefaultBlockBudget = 50; +// How many of the best block-scored candidates get re-scored against their +// untruncated vectors, for an index built with a truncated inline forward index +// (see inline_forward_index.h). Ignored when nothing is truncated. +// +// This is the recall/latency knob, and it is not free: reaching a whole copy is +// a scattered read, so each extra candidate costs far more than its dot product +// (benchmarks/DISK_SEISMIC_BENCH.md has the curve). The depth a query needs +// grows with k and with the candidate pool (k', cut), so the default is +// relative to k: kAutoRescoreDepth resolves to +// max(kAutoRescoreMinDepth, kAutoRescorePerK * k). The constants were tuned on +// MS MARCO at inline_max_nnz=48, lambda=6000, cut=3, k'=50: 200 is where +// recall@10 comes back within k-means seed noise, and 3-5 k is where k=100/200 +// does. A wider pool (larger k') with a smaller depth can match recall for less +// latency, so tune the two together. +inline constexpr int kAutoRescoreDepth = 0; +inline constexpr int kAutoRescoreMinDepth = 200; +inline constexpr int kAutoRescorePerK = 3; + // `cut` (inherited) bounds which posting lists' summaries are scored; `k_prime` // caps how many blocks are read (the k_prime highest-scoring ones). Replaces -// the inherited heap_factor, which the disk-resident indexes ignore. +// the inherited heap_factor, which the disk-resident indexes ignore. `rescore` +// matters only for an index built with inline_max_nnz > 0: kAutoRescoreDepth +// (0) picks a depth from k, a positive value below k is raised to k, and a +// negative one is rejected. struct DiskSeismicSearchParameters : public SeismicSearchParameters { int k_prime = kDefaultBlockBudget; + int rescore = kAutoRescoreDepth; DiskSeismicSearchParameters() = default; - DiskSeismicSearchParameters(int cut, int k_prime) + DiskSeismicSearchParameters(int cut, int k_prime, + int rescore = kAutoRescoreDepth) : SeismicSearchParameters(cut, /*heap_factor=*/1.0F), - k_prime(k_prime) {} + k_prime(k_prime), + rescore(rescore) {} }; // A SEISMIC index whose per-document forward vectors live on disk as float, in @@ -44,11 +68,16 @@ struct DiskSeismicSearchParameters : public SeismicSearchParameters { class DiskSeismicIndex : public DiskSeismicIndexBase { public: static constexpr std::array name = {'D', 'S', 'E', 'I'}; - // Bump whenever write_index's payload layout changes. - static constexpr uint32_t kFormatVersion = 1; + // Bump whenever write_index's payload layout changes. 2 added the + // truncated inline forward index: a v2 file may hold partial copies that a + // v1 reader would score as if whole. Reading v1 stays supported (nothing is + // truncated there), and an untruncated index is still written as v1 (see + // written_format_version), so only truncated files need the newer build. + static constexpr uint32_t kFormatVersion = 2; explicit DiskSeismicIndex(int dim); - DiskSeismicIndex(int dim, SeismicClusterParameters parameter); + DiskSeismicIndex(int dim, SeismicClusterParameters parameter, + uint32_t inline_max_nnz = 0); ~DiskSeismicIndex() override = default; std::array id() const override { return name; } diff --git a/nsparse/disk_seismic_index_base.cpp b/nsparse/disk_seismic_index_base.cpp index 256b931..73433c9 100644 --- a/nsparse/disk_seismic_index_base.cpp +++ b/nsparse/disk_seismic_index_base.cpp @@ -32,15 +32,19 @@ #include "nsparse/sparse_vectors.h" #include "nsparse/types.h" #include "nsparse/utils/checks.h" -#include "nsparse/utils/ranker.h" #include "nsparse/utils/mmap_cursor.h" #include "nsparse/utils/mmap_file.h" +#include "nsparse/utils/omp_exception.h" +#include "nsparse/utils/ranker.h" namespace nsparse { DiskSeismicIndexBase::DiskSeismicIndexBase(int dim, - SeismicClusterParameters parameter) - : MmapIndex(dim), cluster_parameter_(parameter) {} + SeismicClusterParameters parameter, + uint32_t inline_max_nnz) + : MmapIndex(dim), + cluster_parameter_(parameter), + inline_max_nnz_(inline_max_nnz) {} void DiskSeismicIndexBase::add(idx_t n, const offset_t* indptr, const term_t* indices, const float* values) { @@ -74,6 +78,26 @@ auto DiskSeismicIndexBase::search(idx_t n, const offset_t* indptr, const term_t* indices, const float* values, int k, SearchParameters* search_parameters) -> pair_of_score_id_vectors_t { + // Validated before any early return, so a bad value fails the same way on + // every query and every index -- empty, exact-match, or truncated or not. + const detail::DiskSeismicCutBudget budget = + detail::resolve_cut_and_budget(search_parameters); + const int cut = budget.cut; + const int k_prime = budget.k_prime; + // k_prime is a block budget, not a document count: a block holds many docs, + // so k_prime < k is valid (a few blocks can still fill k, and a short-fall + // is padded like any under-budget search). Only a non-positive budget is + // rejected. + if (k_prime <= 0) { + throw std::invalid_argument( + "DiskSeismic index: k_prime (block budget) must be positive"); + } + if (budget.rescore < 0) { + throw std::invalid_argument( + "DiskSeismic index: rescore (re-scoring depth) must be " + "non-negative"); + } + // Quit early when there is nothing to score: no vectors, no queries, or no // forward-vector source (fwd_ empty and vectors_ null — a corrupt or // uninitialized index). @@ -127,19 +151,6 @@ auto DiskSeismicIndexBase::search(idx_t n, const offset_t* indptr, } } - const detail::DiskSeismicCutBudget budget = - detail::resolve_cut_and_budget(search_parameters); - const int cut = budget.cut; - const int k_prime = budget.k_prime; - // k_prime is a block budget, not a document count: a block holds many docs, - // so k_prime < k is valid (a few blocks can still fill k, and a short-fall - // is padded like any under-budget search). Only a non-positive budget is - // rejected. - if (k_prime <= 0) { - throw std::invalid_argument( - "DiskSeismic index: k_prime (block budget) must be positive"); - } - // Encode the whole query batch once at the stored width; a query's codes // start at query_batch + start * element_size. const size_t element_size = code_element_size(); @@ -156,11 +167,22 @@ auto DiskSeismicIndexBase::search(idx_t n, const offset_t* indptr, const detail::InlineForwardIndex* fwd = fwd_.num_blocks() > 0 ? &fwd_ : nullptr; const SparseVectors* vectors = fwd == nullptr ? vectors_.get() : nullptr; + // A truncated forward index makes block scores lower bounds, so the best + // candidates have to be scored again against the whole copies. Nothing to do + // when max_doc_nnz is 0 (including every pre-truncation file, which records + // 0) or for a fresh in-RAM build, whose vectors are the corpus itself. + const bool rescore_needed = + fwd != nullptr && fwd->max_doc_nnz() > 0 && doc_locators_ != nullptr; + const detail::FullVectorStore store = + rescore_needed ? full_vector_store() : detail::FullVectorStore{}; + const int rescore_depth = + rescore_needed ? detail::resolve_rescore_depth(budget.rescore, k) : 0; const IDSelector* id_selector = search_parameters == nullptr ? nullptr : search_parameters->get_id_selector(); const size_t dense_bytes = static_cast(dimension_) * element_size; + detail::OmpExceptionCapture errors; #pragma omp parallel { // Per-thread scratch reused across the queries a thread handles: the @@ -171,27 +193,37 @@ auto DiskSeismicIndexBase::search(idx_t n, const offset_t* indptr, visited.reserve(static_cast(std::max(k, 1)) * 4096); std::vector candidates; std::vector score_scratch; + // Per-thread, so the batched whole-vector resolve reuses its buffers + // across the queries this thread handles. + detail::RescorePass rescore{.store = store, + .depth = rescore_depth, + .scratch = {}, + .slices = {}}; #pragma omp for schedule(dynamic, 64) for (idx_t query_idx = 0; query_idx < n; ++query_idx) { - const offset_t start = indptr[query_idx]; - const size_t len = indptr[query_idx + 1] - start; - const term_t* query_indices = indices + start; - const uint8_t* query_codes = - query_batch + static_cast(start) * element_size; - const std::vector cuts = detail::top_cut_tokens( - query_indices, query_codes, len, cut, element_size); - auto [scores, ids] = detail::block_budget_query( - dense.data(), element_size, visited, candidates, score_scratch, - query_indices, query_codes, len, cuts, k, k_prime, - clustered_inverted_lists, fwd, vectors, id_selector); - decode_scores(scores, search_parameters); - scores.resize(k, -1.0F); - ids.resize(k, detail::INVALID_IDX); - result_distances[query_idx] = std::move(scores); - result_labels[query_idx] = std::move(ids); + errors.run([&] { + const offset_t start = indptr[query_idx]; + const size_t len = indptr[query_idx + 1] - start; + const term_t* query_indices = indices + start; + const uint8_t* query_codes = + query_batch + static_cast(start) * element_size; + const std::vector cuts = detail::top_cut_tokens( + query_indices, query_codes, len, cut, element_size); + auto [scores, ids] = detail::block_budget_query( + dense.data(), element_size, visited, candidates, + score_scratch, query_indices, query_codes, len, cuts, k, + k_prime, clustered_inverted_lists, fwd, vectors, + id_selector, rescore_needed ? &rescore : nullptr); + decode_scores(scores, search_parameters); + scores.resize(k, -1.0F); + ids.resize(k, detail::INVALID_IDX); + result_distances[query_idx] = std::move(scores); + result_labels[query_idx] = std::move(ids); + }); } } + errors.rethrow(); return {result_distances, result_labels}; } @@ -210,15 +242,21 @@ void DiskSeismicIndexBase::write_index(IOWriter* io_writer) { SparseVectors empty_vectors({.element_size = code_element_size(), .dimension = static_cast(dimension_)}); const SparseVectors& v = vectors_ != nullptr ? *vectors_ : empty_vectors; - detail::InlineForwardIndex forward(clustered_inverted_lists, v); + // One table, two readers: the inline writer needs it to leave exactly one + // copy of each doc whole, and the directory below persists it so search can + // find that copy again. + const std::vector locators = build_doc_locators(v); + detail::InlineForwardIndex forward( + clustered_inverted_lists, v, detail::InlineForwardIndex::kDefaultPageSize, + detail::InlineLayout::kPacked, inline_max_nnz_, + inline_max_nnz_ == 0 ? nullptr : &locators); forward.serialize(io_writer); - write_doc_directory(io_writer, v); + write_doc_directory(io_writer, v, locators); } -void DiskSeismicIndexBase::write_doc_directory( - IOWriter* io_writer, const SparseVectors& vectors) const { +auto DiskSeismicIndexBase::build_doc_locators( + const SparseVectors& vectors) const -> std::vector { const size_t num_docs = vectors.num_vectors(); - const size_t element_size = vectors.get_element_size(); // Default to remainder; the loop below overrides docs it finds in a block. std::vector locators( @@ -226,7 +264,8 @@ void DiskSeismicIndexBase::write_doc_directory( std::vector covered(num_docs, false); // Must mirror InlineForwardIndex::write_body's block/slot iteration so the // recorded (posting_list, block, slot) match the blocks it writes. - // First occurrence wins; every copy of a doc's vector is identical. + // First occurrence wins; when nothing is truncated every copy of a doc's + // vector is identical, and when something is, this is the one left whole. for (size_t pl = 0; pl < clustered_inverted_lists.size(); ++pl) { const InvertedListClusters& list = clustered_inverted_lists[pl]; const size_t n_clusters = list.cluster_size(); @@ -245,18 +284,34 @@ void DiskSeismicIndexBase::write_doc_directory( } } } + // Docs in no block get a remainder row, numbered in doc-id order -- the + // order write_doc_directory emits them in. + uint32_t remainder_row = 0; + for (size_t doc_id = 0; doc_id < num_docs; ++doc_id) { + if (!covered[doc_id]) { + locators[doc_id] = {detail::DocLocator::kRemainder, remainder_row, + 0}; + ++remainder_row; + } + } + return locators; +} - // Docs in no block, in doc-id order: keep their full vectors here and point - // the locator at the row. +void DiskSeismicIndexBase::write_doc_directory( + IOWriter* io_writer, const SparseVectors& vectors, + const std::vector& locators) const { + const size_t num_docs = vectors.num_vectors(); + const size_t element_size = vectors.get_element_size(); + + // The docs no block holds, in the doc-id order their rows were numbered in. SparseVectors remainder( {.element_size = element_size, .dimension = static_cast(get_dimension())}); const offset_t* indptr = vectors.indptr_data(); const term_t* indices = vectors.indices_data(); const uint8_t* values = vectors.values_data(); - uint32_t remainder_row = 0; for (size_t doc_id = 0; doc_id < num_docs; ++doc_id) { - if (covered[doc_id]) { + if (locators[doc_id].posting_list != detail::DocLocator::kRemainder) { continue; } const offset_t start = indptr[doc_id]; @@ -266,8 +321,6 @@ void DiskSeismicIndexBase::write_doc_directory( row_indptr, 2, indices + start, nnz, values + static_cast(start) * element_size, nnz * element_size); - locators[doc_id] = {detail::DocLocator::kRemainder, remainder_row, 0}; - ++remainder_row; } // Aligned u64 doc count, then the locator array, then the remainder @@ -291,7 +344,8 @@ void DiskSeismicIndexBase::read_index(IOReader* /*io_reader*/, } void DiskSeismicIndexBase::load_mapped_payload(MmapCursor* cursor, - MmapFile&& mapped) { + MmapFile&& mapped, + uint32_t format_version) { // Same order write_index wrote them (past any extra header the caller // already consumed): doc count, summaries, inline forward. num_vectors_ = cursor->read_scalar(); @@ -299,6 +353,9 @@ void DiskSeismicIndexBase::load_mapped_payload(MmapCursor* cursor, inv_list_writer.mmap_deserialize(cursor); detail::InlineForwardIndex forward; forward.mmap_deserialize(cursor); + if (format_version < 2) { + forward.ignore_max_doc_nnz(); + } clustered_inverted_lists = std::move(inv_list_writer.release()); fwd_ = std::move(forward); @@ -315,6 +372,16 @@ void DiskSeismicIndexBase::load_mapped_payload(MmapCursor* cursor, doc_locators_ = cursor->read_array(num_locators); num_locators_ = num_locators; remainder_.mmap_deserialize(cursor); + // Only a truncated index reads the table on every query (its second pass); + // otherwise only the <= k exact path does, and resolve_doc checks each + // locator it uses. The table is ~12 B per doc, read once front to back, so + // let the kernel read ahead instead of faulting it in a page at a time. + if (fwd_.max_doc_nnz() > 0) { + mapped.read_sequentially( + reinterpret_cast(doc_locators_), + num_locators_ * sizeof(detail::DocLocator), + [this] { validate_doc_locators(); }); + } // Now that the summaries and forward index are populated (still borrowing // from `mapped`, which is alive here), let the concrete index reject a @@ -326,29 +393,34 @@ void DiskSeismicIndexBase::load_mapped_payload(MmapCursor* cursor, index_mapping_ = std::move(mapped); } -auto DiskSeismicIndexBase::get_doc(idx_t doc_id, size_t element_size) const - -> DocSlice { - const detail::DocLocator loc = doc_locators_[doc_id]; - if (loc.posting_list == detail::DocLocator::kRemainder) { - if (loc.block >= remainder_.num_vectors()) { +void DiskSeismicIndexBase::validate_doc_locators() const { + // Directory-only: confirming each slot holds its doc would read every + // block, so resolve_doc / doc_slice check that per resolve instead. + const size_t remainder_rows = remainder_.num_vectors(); + for (uint64_t doc_id = 0; doc_id < num_locators_; ++doc_id) { + const detail::DocLocator& locator = doc_locators_[doc_id]; + if (locator.posting_list == detail::DocLocator::kRemainder) { + if (locator.block >= remainder_rows) { + throw std::runtime_error( + "DiskSeismic index: remainder locator out of range"); + } + continue; + } + const detail::InlineDirEntry* entry = + fwd_.dir_entry(locator.posting_list, locator.block); + if (entry == nullptr || locator.slot >= entry->n_docs) { throw std::runtime_error( - "DiskSeismic exact match: remainder locator out of range"); + "DiskSeismic index: doc locator outside its block"); } - const offset_t* r_indptr = remainder_.indptr_data(); - const offset_t r_start = r_indptr[loc.block]; - return {remainder_.indices_data() + r_start, - remainder_.values_data() + - static_cast(r_start) * element_size, - static_cast(r_indptr[loc.block + 1] - r_start)}; } - const detail::BlockView bv = fwd_.block(loc.posting_list, loc.block); - if (bv.absent() || loc.slot >= bv.n_docs || - bv.doc_ids[loc.slot] != static_cast(doc_id)) { - throw std::runtime_error( - "DiskSeismic exact match: doc locator does not resolve to its doc"); - } - return {bv.doc_comps(loc.slot), bv.doc_vals(loc.slot, element_size), - bv.nnz(loc.slot)}; +} + +auto DiskSeismicIndexBase::full_vector_store() const + -> detail::FullVectorStore { + return {.fwd = &fwd_, + .locators = doc_locators_, + .num_locators = num_locators_, + .remainder = &remainder_}; } auto DiskSeismicIndexBase::exact_match_directory( @@ -362,63 +434,70 @@ auto DiskSeismicIndexBase::exact_match_directory( const uint8_t* query_codes = encode_query(values, total_nnz, search_parameters, query_scratch); const std::vector ids = selector.ordered_ids(); + const detail::FullVectorStore store = full_vector_store(); std::vector> result_distances(n); std::vector> result_labels(n); const size_t dense_bytes = static_cast(get_dimension()) * element_size; + detail::OmpExceptionCapture errors; #pragma omp parallel { // Per-thread dense query buffer, cleared per query below. std::vector dense(dense_bytes, 0); #pragma omp for schedule(dynamic, 64) for (idx_t query_idx = 0; query_idx < n; ++query_idx) { - const offset_t start = indptr[query_idx]; - const size_t len = - static_cast(indptr[query_idx + 1] - start); - const term_t* q_indices = indices + start; - const uint8_t* q_codes = - query_codes + static_cast(start) * element_size; - for (size_t i = 0; i < len; ++i) { - std::copy_n( - q_codes + i * element_size, element_size, - dense.data() + - static_cast(q_indices[i]) * element_size); - } - - detail::TopKHolder holder(k); - for (const idx_t doc_id : ids) { - if (doc_id < 0 || - static_cast(doc_id) >= num_locators_) { - continue; // out-of-range member: nothing to score + errors.run([&] { + const offset_t start = indptr[query_idx]; + const size_t len = + static_cast(indptr[query_idx + 1] - start); + const term_t* q_indices = indices + start; + const uint8_t* q_codes = + query_codes + static_cast(start) * element_size; + for (size_t i = 0; i < len; ++i) { + std::copy_n( + q_codes + i * element_size, element_size, + dense.data() + + static_cast(q_indices[i]) * element_size); } - const DocSlice doc = get_doc(doc_id, element_size); - // Dot the doc's slice against the dense query via a 2-entry - // indptr. - const offset_t slice_indptr[2] = { - 0, static_cast(doc.nnz)}; - const float score = detail::compute_similarity( - 0, slice_indptr, doc.comps, doc.vals, dense.data(), - element_size); - holder.add(score, doc_id); - } - // Decode before padding so the -1 pad is not decoded. - auto [scores, labels] = holder.top_k_items_descending(); - decode_scores(scores, search_parameters); - scores.resize(k, -1.0F); - labels.resize(k, detail::INVALID_IDX); + detail::TopKHolder holder(k); + for (const idx_t doc_id : ids) { + if (doc_id < 0 || + static_cast(doc_id) >= num_locators_) { + continue; // out-of-range member: nothing to score + } + const detail::DocSlice doc = + detail::resolve_doc(store, doc_id, element_size); + // Dot the doc's slice against the dense query via a 2-entry + // indptr. + const offset_t slice_indptr[2] = { + 0, static_cast(doc.nnz)}; + const float score = detail::compute_similarity( + 0, slice_indptr, doc.comps, doc.vals, dense.data(), + element_size); + holder.add(score, doc_id); + } - for (size_t i = 0; i < len; ++i) { - std::fill_n(dense.data() + static_cast(q_indices[i]) * - element_size, - element_size, uint8_t{0}); - } - result_distances[query_idx] = std::move(scores); - result_labels[query_idx] = std::move(labels); + // Decode before padding so the -1 pad is not decoded. + auto [scores, labels] = holder.top_k_items_descending(); + decode_scores(scores, search_parameters); + scores.resize(k, -1.0F); + labels.resize(k, detail::INVALID_IDX); + + for (size_t i = 0; i < len; ++i) { + std::fill_n( + dense.data() + + static_cast(q_indices[i]) * element_size, + element_size, uint8_t{0}); + } + result_distances[query_idx] = std::move(scores); + result_labels[query_idx] = std::move(labels); + }); } } + errors.rethrow(); return {result_distances, result_labels}; } diff --git a/nsparse/disk_seismic_index_base.h b/nsparse/disk_seismic_index_base.h index 3f9bf5a..2251a62 100644 --- a/nsparse/disk_seismic_index_base.h +++ b/nsparse/disk_seismic_index_base.h @@ -28,20 +28,6 @@ namespace nsparse { -namespace detail { -// Locates one full copy of a doc's vector. When posting_list == kRemainder the -// vector is row `block` of the remainder store; otherwise it is slot `slot` of -// inline-forward block (posting_list, block). -struct DocLocator { - uint32_t posting_list; - uint32_t block; - uint32_t slot; - static constexpr uint32_t kRemainder = UINT32_MAX; -}; -static_assert(sizeof(DocLocator) == 12, - "DocLocator is borrowed from the mapping"); -} // namespace detail - // Shared implementation of the two disk-resident SEISMIC indexes: the cluster // summaries live in RAM, the per-document forward vectors live on disk in the // block-contiguous (inline) layout and are borrowed via mmap at search time, @@ -57,6 +43,15 @@ class DiskSeismicIndexBase : public MmapIndex, public IndexIO { // Persisted, since a mapped index has no in-RAM vectors_ to derive it from. size_t num_vectors() const override { return num_vectors_; } + // With nothing truncated the payload is the v1 layout byte for byte + // (max_doc_nnz stays 0, in bytes v1 left as padding), so it is stamped 1 + // and builds that predate truncation still open it. Only while 2 is + // current: a later layout change must stamp its own version on every file. + [[nodiscard]] uint32_t written_format_version() const override { + return inline_max_nnz_ == 0 && format_version() == 2 ? 1 + : format_version(); + } + void add(idx_t n, const offset_t* indptr, const term_t* indices, const float* values) override; void build() override; @@ -77,7 +72,12 @@ class DiskSeismicIndexBase : public MmapIndex, public IndexIO { } protected: - DiskSeismicIndexBase(int dim, SeismicClusterParameters parameter); + // inline_max_nnz > 0 truncates the extra inline copies of each doc to their + // largest inline_max_nnz components and makes search re-score its best + // candidates against the whole copies; 0 keeps every copy whole. See + // inline_forward_index.h for the format and the trade. + DiskSeismicIndexBase(int dim, SeismicClusterParameters parameter, + uint32_t inline_max_nnz = 0); // --- Hooks the concrete indexes implement. --- @@ -115,8 +115,10 @@ class DiskSeismicIndexBase : public MmapIndex, public IndexIO { // Reads the shared payload (doc count, summaries, inline forward) from the // cursor, validates it, and commits the mapping. Each concrete mmap_index - // reads its own extra header first, then calls this. - void load_mapped_payload(MmapCursor* cursor, MmapFile&& mapped); + // reads its own extra header first, then calls this with the file's + // format version (both disk types share the numbering: 2 added truncation). + void load_mapped_payload(MmapCursor* cursor, MmapFile&& mapped, + uint32_t format_version); // Maps a disk index file for querying. Every disk index is point-accessed // (~k' small inline-forward blocks per query), so the mapping must use @@ -142,23 +144,28 @@ class DiskSeismicIndexBase : public MmapIndex, public IndexIO { void read_index(IOReader* io_reader, const IndexHeader& header, int io_flags = 0) override; - // Appends the doc-locator directory and remainder vectors, built from the - // same clusters and vectors as the inline forward. - void write_doc_directory(IOWriter* io_writer, - const SparseVectors& vectors) const; - - // One doc's within-doc slice: component ids, element_size-wide codes, and - // the count. Borrowed from the live mapping or remainder_ (both outlive the - // call), so valid only within one search(). - struct DocSlice { - const term_t* comps = nullptr; - const uint8_t* vals = nullptr; - size_t nnz = 0; - }; - // Resolves one selected doc's full vector through the doc-locator - // directory: an inline-forward block slot, or a row of remainder_ when the - // doc was pruned from every block. Throws on a corrupt locator. - [[nodiscard]] DocSlice get_doc(idx_t doc_id, size_t element_size) const; + // Which block holds each doc's whole copy: its first occurrence in + // (posting list, block, slot) order, or a remainder row for a doc no block + // holds. Computed once per write_index and used twice -- the inline forward + // writer needs it to know which copy to keep whole, and the serialized + // directory is the same table -- so the two cannot disagree about where a + // doc's whole vector is. + [[nodiscard]] std::vector build_doc_locators( + const SparseVectors& vectors) const; + + // Appends the doc-locator directory and the remainder vectors (the docs + // whose locator says kRemainder, in doc-id order). + void write_doc_directory( + IOWriter* io_writer, const SparseVectors& vectors, + const std::vector& locators) const; + + // The store the re-scoring pass reads, or an empty one when this index has + // no locator table (a fresh in-RAM build). + [[nodiscard]] detail::FullVectorStore full_vector_store() const; + // Rejects a locator that points outside the directory or the remainder + // store. Run at load on a truncated index, whose every query reads the + // table, so search never meets one mid-query. + void validate_doc_locators() const; // Scores every selected doc directly through the doc-locator directory, for // a mapped index. Requires doc_locators_ populated. [[nodiscard]] auto exact_match_directory( @@ -168,9 +175,11 @@ class DiskSeismicIndexBase : public MmapIndex, public IndexIO { -> pair_of_score_id_vectors_t; SeismicClusterParameters cluster_parameter_; + uint32_t inline_max_nnz_ = 0; size_t num_vectors_ = 0; // A borrowed per-doc locator table plus the full vectors of the docs that - // are missing from every block, used by the mapped-index exact match. + // are missing from every block. Reached by the mapped-index exact match and + // by the re-scoring pass, both of which need a doc's whole vector. const detail::DocLocator* doc_locators_ = nullptr; uint64_t num_locators_ = 0; SparseVectors remainder_; diff --git a/nsparse/disk_seismic_scalar_quantized_index.cpp b/nsparse/disk_seismic_scalar_quantized_index.cpp index 80c13e4..45914f5 100644 --- a/nsparse/disk_seismic_scalar_quantized_index.cpp +++ b/nsparse/disk_seismic_scalar_quantized_index.cpp @@ -74,8 +74,9 @@ DiskSeismicScalarQuantizedIndex::DiskSeismicScalarQuantizedIndex(int dim) DiskSeismicScalarQuantizedIndex::DiskSeismicScalarQuantizedIndex( QuantizerType quantizer_type, float vmin, float vmax, - SeismicClusterParameters parameter, int dim) - : DiskSeismicIndexBase(dim, parameter), sq_(quantizer_type, vmin, vmax) {} + SeismicClusterParameters parameter, int dim, uint32_t inline_max_nnz) + : DiskSeismicIndexBase(dim, parameter, inline_max_nnz), + sq_(quantizer_type, vmin, vmax) {} size_t DiskSeismicScalarQuantizedIndex::code_element_size() const { return sq_.bytes_per_value(); @@ -154,7 +155,7 @@ DiskSeismicScalarQuantizedIndex* DiskSeismicScalarQuantizedIndex::mmap_index( const auto vmax = cursor.read_scalar(); index->sq_ = make_scalar_quantizer(sq_type, vmin, vmax); - index->load_mapped_payload(&cursor, std::move(mmap_file)); + index->load_mapped_payload(&cursor, std::move(mmap_file), header.version); return index.release(); } } // namespace nsparse diff --git a/nsparse/disk_seismic_scalar_quantized_index.h b/nsparse/disk_seismic_scalar_quantized_index.h index 002bb03..a731d1a 100644 --- a/nsparse/disk_seismic_scalar_quantized_index.h +++ b/nsparse/disk_seismic_scalar_quantized_index.h @@ -24,12 +24,16 @@ namespace nsparse { // Overrides the quantizer range a query is encoded with (the type is always the -// index's); everything else is DiskSeismicSearchParameters (cut + k_prime). +// index's); everything else is DiskSeismicSearchParameters (cut, k_prime, and +// the re-scoring depth for an index built with inline_max_nnz). struct DiskSeismicSQSearchParameters : public DiskSeismicSearchParameters { float vmin; float vmax; - DiskSeismicSQSearchParameters(float vmin, float vmax, int cut, int k_prime) - : DiskSeismicSearchParameters(cut, k_prime), vmax(vmax), vmin(vmin) {} + DiskSeismicSQSearchParameters(float vmin, float vmax, int cut, int k_prime, + int rescore = kAutoRescoreDepth) + : DiskSeismicSearchParameters(cut, k_prime, rescore), + vmax(vmax), + vmin(vmin) {} }; // A DiskSeismicIndex over scalar-quantized codes: the forward vectors and the @@ -44,14 +48,18 @@ struct DiskSeismicSQSearchParameters : public DiskSeismicSearchParameters { class DiskSeismicScalarQuantizedIndex : public DiskSeismicIndexBase { public: static constexpr std::array name = {'D', 'S', 'S', 'Q'}; - // Bump whenever write_index's payload layout changes. - static constexpr uint32_t kFormatVersion = 1; + // Bump whenever write_index's payload layout changes. 2 added the + // truncated inline forward index: a v2 file may hold partial copies that a + // v1 reader would score as if whole. Reading v1 stays supported (nothing is + // truncated there), and an untruncated index is still written as v1 (see + // written_format_version), so only truncated files need the newer build. + static constexpr uint32_t kFormatVersion = 2; explicit DiskSeismicScalarQuantizedIndex(int dim); DiskSeismicScalarQuantizedIndex(QuantizerType quantizer_type, float vmin, float vmax, - SeismicClusterParameters parameter, - int dim); + SeismicClusterParameters parameter, int dim, + uint32_t inline_max_nnz = 0); ~DiskSeismicScalarQuantizedIndex() override = default; std::array id() const override { return name; } diff --git a/nsparse/disk_seismic_search.cpp b/nsparse/disk_seismic_search.cpp index c0807c1..f5e60b3 100644 --- a/nsparse/disk_seismic_search.cpp +++ b/nsparse/disk_seismic_search.cpp @@ -8,7 +8,6 @@ */ #include "nsparse/disk_seismic_search.h" - #include #include #include @@ -19,16 +18,39 @@ #include "nsparse/id_selector.h" #include "nsparse/index.h" #include "nsparse/io/inline_forward_index_io.h" +#include "nsparse/seismic_common.h" // compute_similarity #include "nsparse/seismic_index.h" // SeismicSearchParameters #include "nsparse/sparse_vectors.h" #include "nsparse/types.h" #include "nsparse/utils/distance_simd.h" +#include "nsparse/utils/prefetch.h" #include "nsparse/utils/ranker.h" #include "nsparse/utils/vector_process.h" namespace nsparse::detail { namespace { +// Docs ahead to start fetching while the current one is being summed. Small +// enough that the outstanding prefetches fit the core's line-fill buffers, large +// enough to cover a DRAM hit at the ~200 cycles one doc's dot product takes. +constexpr size_t kRescoreLookahead = 6; + +// Start the first cache lines of a doc's row at the stored value width. +void prefetch_row_head(const DocSlice& doc, size_t element_size) { + constexpr size_t kRowLines = 2; + if (element_size == U32) { + prefetch_vector_head(doc.comps, + reinterpret_cast(doc.vals), doc.nnz, + kRowLines); + } else if (element_size == U16) { + prefetch_vector_head(doc.comps, + reinterpret_cast(doc.vals), + doc.nnz, kRowLines); + } else { + prefetch_vector_head(doc.comps, doc.vals, doc.nnz, kRowLines); + } +} + // Score one doc's vector against the dense query and push it, honoring // visited-dedup and the id selector. `dense` and `vals` are element_size bytes // per component; the width selects the kernel (4 = float, 2 = uint16, else @@ -95,22 +117,33 @@ void score_block(const InlineForwardIndex* fwd, const SparseVectors* vectors, DiskSeismicCutBudget resolve_cut_and_budget( const SearchParameters* search_parameters) { // A DiskSeismicSearchParameters (including a quantized subclass) carries - // k_prime; a plain SeismicSearchParameters (or null) uses the default - // budget. + // k_prime and the re-scoring depth; a plain SeismicSearchParameters (or + // null) uses the defaults. const DiskSeismicSearchParameters defaults; int cut = defaults.cut; int k_prime = defaults.k_prime; + int rescore = defaults.rescore; if (const auto* disk_parameters = dynamic_cast( search_parameters)) { cut = disk_parameters->cut; k_prime = disk_parameters->k_prime; + rescore = disk_parameters->rescore; } else if (const auto* seismic_parameters = dynamic_cast( search_parameters)) { cut = seismic_parameters->cut; } - return {cut, k_prime}; + return {cut, k_prime, rescore}; +} + +int resolve_rescore_depth(int rescore, int k) { + if (rescore == kAutoRescoreDepth) { + const int64_t scaled = static_cast(kAutoRescorePerK) * k; + return static_cast(std::min( + std::max(kAutoRescoreMinDepth, scaled), INT32_MAX)); + } + return std::max(rescore, k); } std::vector top_cut_tokens(const term_t* indices, const uint8_t* codes, @@ -139,7 +172,7 @@ pair_of_score_id_vector_t block_budget_query( const std::vector& cuts, int k, int k_prime, const std::vector& clusters, const InlineForwardIndex* fwd, const SparseVectors* vectors, - const IDSelector* id_selector) { + const IDSelector* id_selector, RescorePass* rescore) { // Scatter the query into the dense lookup table: element_size contiguous // bytes per non-zero dim. for (size_t i = 0; i < query_len; ++i) { @@ -171,9 +204,10 @@ pair_of_score_id_vector_t block_budget_query( } } - // Select the global top-k_prime blocks by summary score. The order among - // them does not affect the result (dedup + exact scoring are - // order-independent). + // Select the global top-k_prime blocks by summary score. Their order only + // matters on a truncated index: visited keeps the first copy of a doc the + // scan meets, so it decides whether the doc enters the pool with its exact + // score or a lower bound. Without truncation every copy is the same. const size_t budget = std::min(static_cast(k_prime), candidates.size()); if (budget < candidates.size()) { @@ -185,13 +219,69 @@ pair_of_score_id_vector_t block_budget_query( candidates.resize(budget); } - // Score the selected blocks; visited dedups docs shared across them. - TopKHolder holder(k); + // Score the selected blocks; visited dedups docs shared across them. With + // truncated blocks these scores only rank the candidate pool, so keep the + // best `rescore` of them rather than just the best k. + // Any depth at all is worth a second pass on a truncated index: at exactly k + // it cannot pull in a doc the block scores ranked out, but it still replaces + // k lower bounds with k exact scores. Skipping it would hand back the lower + // bounds as if they were scores. + const bool two_phase = rescore != nullptr; + size_t pool_depth = static_cast(k); + if (two_phase) { + // The pool can never hold more docs than the selected blocks do, so a + // depth past that (INT32_MAX meaning "all") must not size the heap's + // reserve. The directory is in RAM, so this is O(k'). + size_t pool_bound = 0; + for (const BlockCandidate& candidate : candidates) { + const InlineDirEntry* entry = + fwd == nullptr ? nullptr + : fwd->dir_entry(candidate.pl, candidate.cid); + pool_bound += entry == nullptr ? 0 : entry->n_docs; + } + pool_depth = + std::max(pool_depth, + std::min(static_cast(std::max(rescore->depth, 0)), + pool_bound)); + } + TopKHolder holder(static_cast(pool_depth)); for (const BlockCandidate& candidate : candidates) { score_block(fwd, vectors, clusters, candidate.pl, candidate.cid, dense, element_size, id_selector, holder, visited); } + pair_of_score_id_vector_t result = holder.top_k_items_descending(); + if (two_phase) { + // Second pass: the same docs against their untruncated vectors. Every + // block score is a lower bound on the true one, so a doc can only have + // been ranked too low here -- which is why the pool has to be wider + // than k, and why re-scoring it is enough to recover the ranking. + // Resolved in one batch: the walk to a whole vector is a pointer chase + // through tables far larger than cache, and doing it per doc would + // serialize those misses (see resolve_docs). + resolve_docs(rescore->store, result.second.data(), + result.second.size(), element_size, &rescore->scratch, + &rescore->slices); + TopKHolder exact(k); + for (size_t i = 0; i < result.second.size(); ++i) { + // Each row is a scattered read, so start the ones a few docs ahead + // while this one is being summed. Only the head: the row is + // contiguous, so the hardware prefetcher takes it from there, and + // asking for whole rows would exhaust the line-fill buffers. + if (i + kRescoreLookahead < rescore->slices.size()) { + const DocSlice& ahead = rescore->slices[i + kRescoreLookahead]; + prefetch_row_head(ahead, element_size); + } + const DocSlice& doc = rescore->slices[i]; + const offset_t slice_indptr[2] = {0, + static_cast(doc.nnz)}; + exact.add(compute_similarity(0, slice_indptr, doc.comps, doc.vals, + dense, element_size), + result.second[i]); + } + result = exact.top_k_items_descending(); + } + // Restore only the query's own positions to zero (mirrors the scatter at // entry): element_size bytes per touched dim. The scattered writes are // bounded by query_len and negligible next to the block scoring. @@ -201,7 +291,7 @@ pair_of_score_id_vector_t block_budget_query( element_size, uint8_t{0}); } - return holder.top_k_items_descending(); + return result; } } // namespace nsparse::detail diff --git a/nsparse/disk_seismic_search.h b/nsparse/disk_seismic_search.h index 343b525..1312a88 100644 --- a/nsparse/disk_seismic_search.h +++ b/nsparse/disk_seismic_search.h @@ -36,16 +36,34 @@ struct BlockCandidate { uint32_t cid; }; -// (cut, k_prime) resolved from search parameters, defaulting to +// (cut, k_prime, rescore) resolved from search parameters, defaulting to // DiskSeismicSearchParameters. Each index still validates k_prime with its own // error message. struct DiskSeismicCutBudget { int cut; int k_prime; + int rescore; }; DiskSeismicCutBudget resolve_cut_and_budget( const SearchParameters* search_parameters); +// The re-scoring depth a search runs at: kAutoRescoreDepth resolves to +// max(kAutoRescoreMinDepth, kAutoRescorePerK * k), anything else is raised to k +// (fewer than k re-scored candidates could not fill the result). Expects a +// non-negative `rescore`. +int resolve_rescore_depth(int rescore, int k); + +// The second scoring pass, for an index whose inline copies are truncated: where +// the whole vectors are, how many candidates to re-score, and the per-thread +// scratch the batched resolve needs. One per query thread, reused across +// queries. +struct RescorePass { + FullVectorStore store; + int depth = 0; + DocResolveScratch scratch; + std::vector slices; +}; + // The `cut` highest-weighted query terms, read from `codes` at `element_size` // bytes per value (4 = float, 2 = uint16, 1 = uint8). std::vector top_cut_tokens(const term_t* indices, const uint8_t* codes, @@ -65,6 +83,13 @@ pair_of_score_id_vectors_t initialize_padded_results(idx_t n, int k); // it is non-null, else from the in-RAM `vectors` of a fresh build. Returns the // raw (undecoded) top-k scores + ids, unpadded: the caller decodes if it must // and pads to k. +// +// When `rescore` is non-null the blocks hold truncated copies, so block scores +// are lower bounds and a second pass is required: its `depth` best candidates +// by block score (at least k, at most the pool the selected blocks hold) are +// scored again against their untruncated vectors and that ranking is returned. +// Pass null when every copy is whole, which is the only correct choice then -- +// a second pass would score the same bytes twice. pair_of_score_id_vector_t block_budget_query( uint8_t* dense, size_t element_size, absl::flat_hash_set& visited, std::vector& candidates, std::vector& score_scratch, @@ -72,7 +97,7 @@ pair_of_score_id_vector_t block_budget_query( const std::vector& cuts, int k, int k_prime, const std::vector& clusters, const InlineForwardIndex* fwd, const SparseVectors* vectors, - const IDSelector* id_selector); + const IDSelector* id_selector, RescorePass* rescore = nullptr); } // namespace nsparse::detail diff --git a/nsparse/index_factory.cpp b/nsparse/index_factory.cpp index 946ff7c..a672963 100644 --- a/nsparse/index_factory.cpp +++ b/nsparse/index_factory.cpp @@ -9,10 +9,13 @@ #include "nsparse/index_factory.h" +#include +#include #include #include #include #include +#include #include #include "nsparse/brutal_index.h" @@ -68,6 +71,25 @@ SeismicClusterParameters parse_cluster_params(const GetParam& get_param) { .seed = std::stoi(get_param("seed", std::to_string(kRandomSeed)))}; } +// How many components a doc's extra inline copies keep, for the two disk types +// (0 = keep every copy whole). See inline_forward_index.h. +template +uint32_t parse_inline_max_nnz(const GetParam& get_param) { + // The whole token must be a decimal integer: std::stoll/stoul stop at the + // first non-digit ("1e3" -> 1, "0x40" -> 0) and stoul wraps "-1", each of + // which would silently build a different index than the one asked for. + const std::string text = get_param("inline_max_nnz", "0"); + uint64_t value = 0; + const char* end = text.data() + text.size(); + const auto [ptr, ec] = std::from_chars(text.data(), end, value); + if (ec != std::errc{} || ptr != end || value > UINT32_MAX) { + throw std::invalid_argument( + "inline_max_nnz must be an integer in [0, 2^32), got '" + text + + "'"); + } + return static_cast(value); +} + struct QuantizerConfig { QuantizerType type; float vmin; @@ -149,13 +171,15 @@ Index* index_factory(int dimension, const char* description) { } if (index_type == "disk_seismic") { - return new DiskSeismicIndex(dimension, parse_cluster_params(get_param)); + return new DiskSeismicIndex(dimension, parse_cluster_params(get_param), + parse_inline_max_nnz(get_param)); } if (index_type == "disk_seismic_sq") { const QuantizerConfig q = parse_quantizer_config(get_param); return new DiskSeismicScalarQuantizedIndex( - q.type, q.vmin, q.vmax, parse_cluster_params(get_param), dimension); + q.type, q.vmin, q.vmax, parse_cluster_params(get_param), dimension, + parse_inline_max_nnz(get_param)); } if (index_type == "seismic_sq") { diff --git a/nsparse/inline_forward_index.h b/nsparse/inline_forward_index.h index 3f43b7b..7f897d4 100644 --- a/nsparse/inline_forward_index.h +++ b/nsparse/inline_forward_index.h @@ -10,6 +10,7 @@ #ifndef INLINE_FORWARD_INDEX_H #define INLINE_FORWARD_INDEX_H +#include #include #include @@ -19,8 +20,8 @@ namespace nsparse::detail { /** * On-disk "inline" (block-contiguous) forward-index format: each doc's vector * is copied into every block (cluster) it belongs to, so a block is one - * contiguous mmap read. Single file, host byte order, rebuildable (no - * cross-version guarantee): + * contiguous mmap read. Single file, host byte order, versioned by the + * enclosing disk index's kFormatVersion (a current reader still loads v1): * [InlineForwardIndexHeader] (padded to page_size when page-aligned) * per block (structure-of-arrays, a within-block CSR): * [u32 n_docs] @@ -37,8 +38,35 @@ namespace nsparse::detail { * element types compute_similarity consumes; off[] is a u32 within-block CSR * offset, capped at INT32_MAX by the writer so it converts to idx_t losslessly. * Component: io/inline_forward_index_io.h. + * + * A doc's vector is duplicated into every block that holds it -- about 13 + * copies at the standard parameters -- which is what makes a block one + * contiguous read and also what makes the section the bulk of the file. The + * header's `max_doc_nnz` bounds the *extra* copies: when it is non-zero, one + * copy of each doc stays whole and every other copy keeps only its largest + * max_doc_nnz components. Blocks are then cheaper to score but their scores are + * lower bounds, so a reader that sees max_doc_nnz != 0 must re-score its best + * candidates against the whole copies (DocLocator finds them) before trusting + * the ranking. max_doc_nnz == 0 means every copy is whole and no re-scoring is + * needed. */ +// Locates the one copy of a doc's vector that is never truncated. When +// posting_list == kRemainder the vector is row `block` of the remainder store +// (docs that no block holds); otherwise it is slot `slot` of inline-forward +// block (posting_list, block). Serialized as a per-doc array, so a format struct +// rather than a search-side detail. +struct DocLocator { + uint32_t posting_list; + uint32_t block; + uint32_t slot; + static constexpr uint32_t kRemainder = UINT32_MAX; +}; +static_assert(sizeof(DocLocator) == 12, + "DocLocator is borrowed from the mapping"); +static_assert(std::is_standard_layout_v); +static_assert(std::is_trivially_copyable_v); + // Block placement: page-aligned (padded to page_size) or packed (blocks // back-to-back on the minimum kMinBlockAlign boundary that keeps the per-block // arrays readable in place; the default). The header page_size records the @@ -63,10 +91,18 @@ inline constexpr uint64_t kMinBlockAlign = 8; // to kMinBlockAlign when packed). struct InlineForwardIndexHeader { uint32_t element_size; // 1, 2, or 4 + // Components kept by a doc's truncated copies; 0 = every copy is whole, + // including when the limit was set but no copy exceeded it. Sits in what + // was padding after element_size, so the header keeps its size; those bytes + // are not guaranteed zero in a file written before this field existed, so + // a reader of a format-version-1 index ignores them. + uint32_t max_doc_nnz; uint64_t n_blocks; uint64_t page_size; // effective block alignment (>= kMinBlockAlign) }; static_assert(sizeof(InlineForwardIndexHeader) == 24); +static_assert(offsetof(InlineForwardIndexHeader, n_blocks) == 8, + "max_doc_nnz must occupy the old padding, not shift the fields"); static_assert(std::is_standard_layout_v); static_assert(std::is_trivially_copyable_v); diff --git a/nsparse/io/index_io.cpp b/nsparse/io/index_io.cpp index d1ad869..60e517e 100644 --- a/nsparse/io/index_io.cpp +++ b/nsparse/io/index_io.cpp @@ -179,7 +179,7 @@ void write_index(Index* index, IOWriter* io_writer, bool keep_open) { } // write header write_header({.id = fourcc(index->id()), - .version = index_io->format_version(), + .version = index_io->written_format_version(), .dimension = index->get_dimension()}, io_writer); // write index customized payload diff --git a/nsparse/io/inline_forward_index_io.cpp b/nsparse/io/inline_forward_index_io.cpp index 80f99ca..0b6589a 100644 --- a/nsparse/io/inline_forward_index_io.cpp +++ b/nsparse/io/inline_forward_index_io.cpp @@ -9,9 +9,13 @@ #include "nsparse/io/inline_forward_index_io.h" +#include +#include #include #include #include +#include +#include #include #include #include @@ -26,20 +30,194 @@ #include "nsparse/types.h" #include "nsparse/utils/checks.h" #include "nsparse/utils/mmap_cursor.h" +#include "nsparse/utils/prefetch.h" namespace nsparse::detail { +namespace { + +// One stored code, widened. Exact for the 1- and 2-byte code widths and for +// float, so comparing widened values orders them exactly as the stored ones. A +// NaN weight reads as -inf: the selection needs a strict weak order, and a NaN +// is the first thing a truncated copy should drop. +double code_value(const uint8_t* values, size_t index, size_t element_size) { + if (element_size == sizeof(float)) { + float value = NAN; + std::memcpy(&value, values + index * sizeof(float), sizeof(float)); + return std::isnan(value) ? -std::numeric_limits::infinity() + : value; + } + if (element_size == sizeof(uint16_t)) { + uint16_t value = 0; + std::memcpy(&value, values + index * sizeof(uint16_t), + sizeof(uint16_t)); + return value; + } + return values[index]; +} + +} // namespace // The record bounds math (nnz up to INT32_MAX times record width) assumes a // 64-bit size_t so it cannot overflow. static_assert(sizeof(size_t) >= 8, "InlineForwardIndex assumes 64-bit size_t"); +DocSlice resolve_doc(const FullVectorStore& store, idx_t doc_id, + size_t element_size) { + if (doc_id < 0 || static_cast(doc_id) >= store.num_locators) { + throw std::out_of_range( + "DiskSeismic: doc id outside the locator directory"); + } + const DocLocator locator = store.locators[doc_id]; + if (locator.posting_list == DocLocator::kRemainder) { + if (store.remainder == nullptr || + locator.block >= store.remainder->num_vectors()) { + throw std::runtime_error( + "DiskSeismic: remainder locator out of range"); + } + const offset_t* indptr = store.remainder->indptr_data(); + const offset_t start = indptr[locator.block]; + return {store.remainder->indices_data() + start, + store.remainder->values_data() + + static_cast(start) * element_size, + static_cast(indptr[locator.block + 1] - start)}; + } + const BlockView view = store.fwd->block(locator.posting_list, locator.block); + if (view.absent() || locator.slot >= view.n_docs || + view.doc_ids[locator.slot] != static_cast(doc_id)) { + throw std::runtime_error( + "DiskSeismic: doc locator does not resolve to its doc"); + } + return {view.doc_comps(locator.slot), + view.doc_vals(locator.slot, element_size), view.nnz(locator.slot)}; +} + +void resolve_docs(const FullVectorStore& store, const idx_t* doc_ids, + size_t n_docs, size_t element_size, + DocResolveScratch* scratch, std::vector* out) { + // Docs per chunk. The walk is staged so each step's misses overlap, but a + // core has only ~10-16 line-fill buffers: prefetching a whole 300-doc batch + // in one sweep drops all but the first dozen and the loads miss anyway. A + // chunk of this size keeps the outstanding prefetches inside that budget + // while still overlapping enough of them to matter. + constexpr size_t kChunk = 12; + + out->clear(); + out->reserve(n_docs); + + for (size_t begin = 0; begin < n_docs; begin += kChunk) { + const size_t end = std::min(begin + kChunk, n_docs); + const size_t len = end - begin; + scratch->locators.assign(len, DocLocator{}); + scratch->entries.assign(len, nullptr); + + // Stage 1: the locator table, one random 12-byte read per doc. + for (size_t i = 0; i < len; ++i) { + const idx_t doc_id = doc_ids[begin + i]; + if (doc_id < 0 || + static_cast(doc_id) >= store.num_locators) { + throw std::out_of_range( + "DiskSeismic: doc id outside the locator directory"); + } + NSPARSE_PREFETCH(&store.locators[doc_id], 0, 0); + } + // Stage 2: read the locators, prefetch each one's directory entry. A + // remainder doc has no entry and is resolved singly in stage 4, being + // rare enough (docs that no block holds) not to be worth pipelining. + for (size_t i = 0; i < len; ++i) { + scratch->locators[i] = store.locators[doc_ids[begin + i]]; + const DocLocator& locator = scratch->locators[i]; + if (locator.posting_list != DocLocator::kRemainder) { + scratch->entries[i] = + store.fwd->dir_entry(locator.posting_list, locator.block); + NSPARSE_PREFETCH(scratch->entries[i], 0, 0); + } + } + // Stage 3: read the entries, prefetch the block prefix the slice math + // reads ([n_docs][doc_id[]][off[]]). + for (size_t i = 0; i < len; ++i) { + if (scratch->entries[i] != nullptr) { + NSPARSE_PREFETCH( + store.fwd->block_base() + scratch->entries[i]->byte_off, 0, + 0); + } + } + // Stage 4: slice. The rows themselves are left to the caller, which + // prefetches them with its own bounded lookahead as it scores. + for (size_t i = 0; i < len; ++i) { + if (scratch->entries[i] == nullptr) { + out->push_back( + resolve_doc(store, doc_ids[begin + i], element_size)); + continue; + } + out->push_back(store.fwd->doc_slice( + *scratch->entries[i], scratch->locators[i].slot, + static_cast(doc_ids[begin + i]))); + } + } +} + +InlineForwardIndex::CodeCut InlineForwardIndex::select_top_codes( + const uint8_t* values, uint64_t nnz, uint64_t keep, size_t element_size, + std::vector* scratch) { + // `keep` of `nnz` values, chosen largest-first. Rather than a list of + // indices this returns the boundary value and how many of the values *at* + // it are in: everything above the boundary is in, and the ties are taken in + // stored order. That keeps the two emit passes to one comparison per value + // and leaves the kept components in ascending component order, which the + // format requires. + scratch->clear(); + scratch->reserve(nnz); + for (uint64_t i = 0; i < nnz; ++i) { + scratch->push_back(code_value(values, i, element_size)); + } + const auto boundary = + scratch->begin() + static_cast(keep) - 1; + std::nth_element(scratch->begin(), boundary, scratch->end(), + std::greater<>()); + const double cut = *boundary; + // Nothing outside the first `keep` can exceed the boundary, so counting + // there counts the whole array. + uint32_t above = 0; + for (uint64_t i = 0; i < keep; ++i) { + above += (*scratch)[i] > cut ? 1U : 0U; + } + return {cut, static_cast(keep) - above, false}; +} + +void InlineForwardIndex::gather_selected(const term_t* comps, + const uint8_t* values, uint64_t nnz, + size_t element_size, CodeCut cut, + std::vector* comps_out, + std::vector* vals_out) { + uint32_t quota = cut.ties; + for (uint64_t i = 0; i < nnz; ++i) { + const double value = code_value(values, i, element_size); + if (value <= cut.boundary) { + if (value < cut.boundary || quota == 0) { + continue; + } + --quota; + } + if (comps_out != nullptr) { + comps_out->push_back(comps[i]); + } + if (vals_out != nullptr) { + const uint8_t* src = values + i * element_size; + vals_out->insert(vals_out->end(), src, src + element_size); + } + } +} + InlineForwardIndex::InlineForwardIndex( const std::vector& lists, - const SparseVectors& vectors, uint64_t page_size, InlineLayout layout) + const SparseVectors& vectors, uint64_t page_size, InlineLayout layout, + uint32_t max_doc_nnz, const std::vector* full_copies) : lists_(&lists), vectors_(&vectors), write_page_size_(page_size), - write_layout_(layout) { + write_layout_(layout), + write_max_doc_nnz_(max_doc_nnz), + write_full_copies_(full_copies) { if (layout == InlineLayout::kPageAligned) { const bool is_power_of_two = page_size != 0 && (page_size & (page_size - 1)) == 0; @@ -49,6 +227,36 @@ InlineForwardIndex::InlineForwardIndex( "least sizeof(InlineForwardIndexHeader)"); } } + // Truncating without knowing where each whole copy went would leave no way + // to re-score, and a locator table with nothing truncated is a caller that + // thinks it asked for truncation. Reject both rather than silently picking + // one interpretation. + if ((max_doc_nnz == 0) != (full_copies == nullptr)) { + throw std::invalid_argument( + "InlineForwardIndex: max_doc_nnz and the whole-copy locators must " + "be given together"); + } + if (full_copies != nullptr && + full_copies->size() != vectors.num_vectors()) { + throw std::invalid_argument( + "InlineForwardIndex: the whole-copy locators must have one entry " + "per vector"); + } +} + +uint64_t InlineForwardIndex::doc_stored_nnz(idx_t doc_id, uint64_t full_nnz, + uint32_t pl, uint32_t block) const { + if (write_max_doc_nnz_ == 0 || full_nnz <= write_max_doc_nnz_) { + return full_nnz; + } + // count_block validated doc_id against num_vectors, and the constructor + // checked the table covers every vector, so this index is in range. + const DocLocator& locator = + (*write_full_copies_)[static_cast(doc_id)]; + if (locator.posting_list == pl && locator.block == block) { + return full_nnz; // the one copy that stays whole + } + return write_max_doc_nnz_; } // Buf's move copies the source's data()/size() and moves only its owner, so a @@ -59,16 +267,22 @@ InlineForwardIndex::InlineForwardIndex(InlineForwardIndex&& other) noexcept vectors_(other.vectors_), write_page_size_(other.write_page_size_), write_layout_(other.write_layout_), + write_max_doc_nnz_(other.write_max_doc_nnz_), + write_full_copies_(other.write_full_copies_), block_base_(other.block_base_), element_size_(other.element_size_), page_size_(other.page_size_), + max_doc_nnz_(other.max_doc_nnz_), entries_(std::move(other.entries_)), list_offset_(std::move(other.list_offset_)) { other.lists_ = nullptr; other.vectors_ = nullptr; + other.write_max_doc_nnz_ = 0; + other.write_full_copies_ = nullptr; other.block_base_ = nullptr; other.element_size_ = 0; other.page_size_ = 0; + other.max_doc_nnz_ = 0; other.entries_ = Buf(); other.list_offset_ = Buf(); } @@ -80,16 +294,22 @@ InlineForwardIndex& InlineForwardIndex::operator=( vectors_ = other.vectors_; write_page_size_ = other.write_page_size_; write_layout_ = other.write_layout_; + write_max_doc_nnz_ = other.write_max_doc_nnz_; + write_full_copies_ = other.write_full_copies_; block_base_ = other.block_base_; element_size_ = other.element_size_; page_size_ = other.page_size_; + max_doc_nnz_ = other.max_doc_nnz_; entries_ = std::move(other.entries_); list_offset_ = std::move(other.list_offset_); other.lists_ = nullptr; other.vectors_ = nullptr; + other.write_max_doc_nnz_ = 0; + other.write_full_copies_ = nullptr; other.block_base_ = nullptr; other.element_size_ = 0; other.page_size_ = 0; + other.max_doc_nnz_ = 0; other.entries_ = Buf(); other.list_offset_ = Buf(); } @@ -97,7 +317,8 @@ InlineForwardIndex& InlineForwardIndex::operator=( } InlineForwardIndex::BlockCounts InlineForwardIndex::count_block( - std::span docs, const offset_t* indptr, size_t num_vectors) { + std::span docs, const offset_t* indptr, size_t num_vectors, + uint32_t pl, uint32_t block) const { // n_docs and the within-block offsets are u32 on the wire. if (docs.size() > UINT32_MAX) { throw std::length_error( @@ -105,6 +326,7 @@ InlineForwardIndex::BlockCounts InlineForwardIndex::count_block( } const uint32_t n_docs = static_cast(docs.size()); uint64_t total_nnz = 0; + bool truncates = false; for (const idx_t doc_id : docs) { if (doc_id < 0 || static_cast(doc_id) >= num_vectors) { throw std::out_of_range( @@ -112,7 +334,11 @@ InlineForwardIndex::BlockCounts InlineForwardIndex::count_block( std::to_string(doc_id) + " outside [0, " + std::to_string(num_vectors) + ")"); } - total_nnz += static_cast(indptr[doc_id + 1] - indptr[doc_id]); + const auto full_nnz = + static_cast(indptr[doc_id + 1] - indptr[doc_id]); + const uint64_t stored = doc_stored_nnz(doc_id, full_nnz, pl, block); + truncates = truncates || stored != full_nnz; + total_nnz += stored; // Capped at INT32_MAX (not the u32 max): off[] is uint32_t on the wire // but must stay reinterpretable as idx_t (int32_t) on the search path, // and a wrapped offset would also desync the block from its length. @@ -121,10 +347,10 @@ InlineForwardIndex::BlockCounts InlineForwardIndex::count_block( "InlineForwardIndex: block total nnz exceeds INT32_MAX"); } } - return {n_docs, total_nnz}; + return {n_docs, total_nnz, truncates}; } -uint64_t InlineForwardIndex::section_length() const { +InlineForwardIndex::SectionSize InlineForwardIndex::section_size() const { const std::vector& lists = *lists_; const SparseVectors& vectors = *vectors_; const size_t element_size = vectors.get_element_size(); @@ -146,11 +372,15 @@ uint64_t InlineForwardIndex::section_length() const { // inline_block_offsets/inline_align_up), touching no payload. serialize() // asserts the streamed body matches this length, so any drift fails closed. uint64_t cur_off = inline_align_up(sizeof(InlineForwardIndexHeader), align); - for (const auto& list : lists) { + bool truncates = false; + for (size_t pl = 0; pl < lists.size(); ++pl) { + const InvertedListClusters& list = lists[pl]; const size_t n_clusters = list.cluster_size(); for (size_t block = 0; block < n_clusters; ++block) { - const BlockCounts counts = - count_block(list.get_docs(block), indptr, num_vectors); + const BlockCounts counts = count_block( + list.get_docs(block), indptr, num_vectors, + static_cast(pl), static_cast(block)); + truncates = truncates || counts.truncates; cur_off += inline_block_offsets(counts.n_docs, counts.total_nnz, element_size) .end; @@ -158,8 +388,9 @@ uint64_t InlineForwardIndex::section_length() const { } } const uint64_t dir_offset = cur_off; - return dir_offset + n_blocks * sizeof(InlineDirEntry) + - sizeof(InlineForwardIndexTrailer); + return {.length = dir_offset + n_blocks * sizeof(InlineDirEntry) + + sizeof(InlineForwardIndexTrailer), + .truncates = truncates}; } void InlineForwardIndex::serialize(IOWriter* writer) const { @@ -175,10 +406,13 @@ void InlineForwardIndex::serialize(IOWriter* writer) const { // comes from a payload-free sizing pass, so the (corpus-sized) body streams // straight to the writer rather than being buffered in RAM first. io_align::pad_to(writer, kMinBlockAlign); - uint64_t section_len = section_length(); + const SectionSize size = section_size(); + uint64_t section_len = size.length; writer->write(§ion_len, sizeof(section_len), 1); const size_t body_start = writer->pos(); - write_body(writer); + // A limit no copy reached (T >= every multi-copy doc's nnz) writes the same + // blocks as no limit, so record 0 and spare every query the second pass. + write_body(writer, size.truncates ? write_max_doc_nnz_ : 0); // The prefix must equal what the body actually wrote, or a reader would // trust a wrong length. Catches any sizing/emitting drift at the source. if (writer->pos() - body_start != section_len) { @@ -188,7 +422,8 @@ void InlineForwardIndex::serialize(IOWriter* writer) const { } } -void InlineForwardIndex::write_body(IOWriter* writer) const { +void InlineForwardIndex::write_body(IOWriter* writer, + uint32_t max_doc_nnz) const { static_assert(sizeof(term_t) == kInlineCompWidth, "component id width must match the inline format"); @@ -215,6 +450,7 @@ void InlineForwardIndex::write_body(IOWriter* writer) const { InlineForwardIndexHeader header{}; header.element_size = static_cast(element_size); + header.max_doc_nnz = max_doc_nnz; header.n_blocks = n_blocks; header.page_size = align; writer->write(&header, sizeof(header), 1); @@ -232,27 +468,51 @@ void InlineForwardIndex::write_body(IOWriter* writer) const { entries.reserve(n_blocks); std::vector doc_ids; std::vector offsets; + // Per-slot selection, computed once and used by both the comps pass and the + // vals pass so the two cannot disagree about which components the doc keeps. + // A default-constructed CodeCut (whole == true) means the slot stores + // everything, which is every slot when truncation is off. + std::vector cuts; + std::vector cut_scratch; + std::vector comps_scratch; + std::vector vals_scratch; for (size_t pl = 0; pl < lists.size(); ++pl) { const InvertedListClusters& list = lists[pl]; const size_t n_clusters = list.cluster_size(); for (size_t block = 0; block < n_clusters; ++block) { const std::span docs = list.get_docs(block); const uint64_t block_off = cur_off; - // Validate + count once (the same call section_length() used), then + // Validate + count once (the same call section_size() used), then // build doc_id[]/off[] (the within-block CSR prefix sum) from the // now-safe docs. count_block keeps off[] within INT32_MAX, so the // running total below cannot wrap or desync the recorded length. - const BlockCounts counts = count_block(docs, indptr, num_vectors); + const BlockCounts counts = + count_block(docs, indptr, num_vectors, + static_cast(pl), + static_cast(block)); const uint32_t n_docs = counts.n_docs; const uint64_t total_nnz = counts.total_nnz; doc_ids.clear(); offsets.assign(1, 0); doc_ids.reserve(n_docs); offsets.reserve(n_docs + 1); + cuts.clear(); + cuts.reserve(n_docs); uint64_t running = 0; for (const idx_t doc_id : docs) { - running += - static_cast(indptr[doc_id + 1] - indptr[doc_id]); + const offset_t start = indptr[doc_id]; + const auto nnz = + static_cast(indptr[doc_id + 1] - start); + const uint64_t stored = doc_stored_nnz( + doc_id, nnz, static_cast(pl), + static_cast(block)); + cuts.push_back( + stored == nnz + ? CodeCut{} + : select_top_codes( + values + static_cast(start) * element_size, + nnz, stored, element_size, &cut_scratch)); + running += stored; doc_ids.push_back(static_cast(doc_id)); offsets.push_back(static_cast(running)); } @@ -268,13 +528,26 @@ void InlineForwardIndex::write_body(IOWriter* writer) const { // comps[] then (pad to element_size) then vals[], each doc's slice // concatenated in block order. - for (const idx_t doc_id : docs) { + for (uint32_t slot = 0; slot < n_docs; ++slot) { + const idx_t doc_id = docs[slot]; const offset_t start = indptr[doc_id]; - const size_t nnz = indptr[doc_id + 1] - start; - if (nnz > 0) { + const auto nnz = + static_cast(indptr[doc_id + 1] - start); + if (nnz == 0) { + continue; + } + if (cuts[slot].whole) { writer->write(const_cast(indices + start), sizeof(term_t), nnz); + continue; } + comps_scratch.clear(); + gather_selected( + indices + start, + values + static_cast(start) * element_size, nnz, + element_size, cuts[slot], &comps_scratch, nullptr); + writer->write(comps_scratch.data(), sizeof(term_t), + comps_scratch.size()); } const uint64_t comps_end = layout.comps + total_nnz * sizeof(term_t); @@ -283,15 +556,25 @@ void InlineForwardIndex::write_body(IOWriter* writer) const { writer->write(const_cast(zero_pad.data()), 1, vals_pad); } - for (const idx_t doc_id : docs) { + for (uint32_t slot = 0; slot < n_docs; ++slot) { + const idx_t doc_id = docs[slot]; const offset_t start = indptr[doc_id]; - const size_t nnz = indptr[doc_id + 1] - start; - if (nnz > 0) { - writer->write( - const_cast( - values + static_cast(start) * element_size), - 1, nnz * element_size); + const auto nnz = + static_cast(indptr[doc_id + 1] - start); + if (nnz == 0) { + continue; + } + const uint8_t* doc_vals = + values + static_cast(start) * element_size; + if (cuts[slot].whole) { + writer->write(const_cast(doc_vals), 1, + nnz * element_size); + continue; } + vals_scratch.clear(); + gather_selected(indices + start, doc_vals, nnz, element_size, + cuts[slot], nullptr, &vals_scratch); + writer->write(vals_scratch.data(), 1, vals_scratch.size()); } const uint64_t block_len = layout.end; @@ -373,6 +656,7 @@ void InlineForwardIndex::load_directory(const uint8_t* base, } element_size_ = header.element_size; page_size_ = header.page_size; + max_doc_nnz_ = header.max_doc_nnz; // Effective block alignment: a power of two, at least kMinBlockAlign. if (page_size_ < kMinBlockAlign || (page_size_ & (page_size_ - 1)) != 0) { throw std::runtime_error("InlineForwardIndex: bad page_size"); @@ -506,6 +790,62 @@ uint64_t InlineForwardIndex::num_blocks_in_list(uint32_t pl) const { return list_offset_[pl + 1] - list_offset_[pl]; } +const InlineDirEntry* InlineForwardIndex::dir_entry(uint32_t pl, + uint32_t block) const { + // An out-of-range pl makes num_blocks_in_list(pl) return 0, so this returns + // before list_offset_[pl] is ever indexed. + if (block >= num_blocks_in_list(pl)) { + return nullptr; + } + const InlineDirEntry& entry = entries_[list_offset_[pl] + block]; + if (entry.pl != pl || entry.block != block) { + return nullptr; // directory not in the expected (pl, block) order + } + return &entry; +} + +DocSlice InlineForwardIndex::doc_slice(const InlineDirEntry& entry, + uint32_t slot, uint32_t doc_id) const { + if (slot >= entry.n_docs) { + throw std::runtime_error("InlineForwardIndex: slot outside its block"); + } + const uint8_t* base = block_base_ + entry.byte_off; + // doc_id[] and off[] must fit before the offsets can be read; the comps + // offset is where they end and is independent of total_nnz. + const InlineBlockOffsets hdr = + inline_block_offsets(entry.n_docs, 0, element_size_); + if (hdr.comps > entry.len) { + throw std::runtime_error( + "InlineForwardIndex: block header overruns block"); + } + // The locator table is the only record of where a doc's whole copy is, so + // check it names this doc; otherwise a corrupt locator would score another + // doc's vector under this id. + const auto* doc_ids = reinterpret_cast(base + hdr.doc_ids); + if (doc_ids[slot] != doc_id) { + throw std::runtime_error( + "DiskSeismic: doc locator does not resolve to its doc"); + } + const auto* offsets = reinterpret_cast(base + hdr.off); + const uint64_t total_nnz = offsets[entry.n_docs]; + const InlineBlockOffsets layout = + inline_block_offsets(entry.n_docs, total_nnz, element_size_); + // The same length equality block() checks, which is what makes total_nnz -- + // and so the arrays the slice points into -- trustworthy. + if (layout.end != entry.len) { + throw std::runtime_error("InlineForwardIndex: block length mismatch"); + } + const uint32_t start = offsets[slot]; + const uint32_t end = offsets[slot + 1]; + if (start > end || end > total_nnz) { + throw std::runtime_error( + "InlineForwardIndex: block offsets not monotonic"); + } + return {reinterpret_cast(base + layout.comps) + start, + base + layout.vals + static_cast(start) * element_size_, + end - start}; +} + BlockView InlineForwardIndex::block(uint32_t pl, uint32_t block) const { // An out-of-range pl makes num_blocks_in_list(pl) return 0, so this returns // an absent view before list_offset_[pl] is ever indexed. diff --git a/nsparse/io/inline_forward_index_io.h b/nsparse/io/inline_forward_index_io.h index 7cd56be..2aafd17 100644 --- a/nsparse/io/inline_forward_index_io.h +++ b/nsparse/io/inline_forward_index_io.h @@ -51,6 +51,53 @@ struct BlockView { } }; +// One doc's within-doc slice: component ids, element_size-wide codes, and the +// count. Borrowed from a live mapping (or an in-RAM store), so valid only for as +// long as its source is. +struct DocSlice { + const term_t* comps = nullptr; + const uint8_t* vals = nullptr; + size_t nnz = 0; +}; + +class InlineForwardIndex; + +// Where to find the untruncated copy of any doc when the blocks hold truncated +// ones (see inline_forward_index.h). `locators` is the per-doc directory; a doc +// that no block holds lives in `remainder` instead. One copy of the corpus, not +// one per block, which is what makes re-scoring cheap enough to pay for the +// truncation. +struct FullVectorStore { + const InlineForwardIndex* fwd = nullptr; + const DocLocator* locators = nullptr; + uint64_t num_locators = 0; + const SparseVectors* remainder = nullptr; +}; + +// The untruncated vector of `doc_id`. Throws on a locator that does not resolve +// to its doc (a corrupt directory), so a caller never scores another doc's +// bytes. +DocSlice resolve_doc(const FullVectorStore& store, idx_t doc_id, + size_t element_size); + +// Scratch for the batched resolve below, owned by the caller and reused across +// queries so the walk allocates nothing. +struct DocResolveScratch { + std::vector locators; + std::vector entries; +}; + +// resolve_doc for many docs at once, and much faster per doc: reaching one whole +// vector is a four-deep pointer chase (locator -> directory entry -> block +// header -> the doc's slice), each step a likely cache miss on a table far too +// big to cache, and done one doc at a time the misses serialize. This walks all +// the docs through each step together, prefetching the next step's input for +// every doc before any of them needs it, so the misses overlap instead. Same +// results as calling resolve_doc in a loop, including the throws. +void resolve_docs(const FullVectorStore& store, const idx_t* doc_ids, + size_t n_docs, size_t element_size, + DocResolveScratch* scratch, std::vector* out); + // The inline forward-index as a serialization component (format in // inline_forward_index.h). Construct with the source lists + vectors to write // it (serialize); default-construct to read it. On read the directory is copied @@ -86,10 +133,18 @@ class InlineForwardIndex : public MmapSerializable { // Write mode. `lists`/`vectors` must outlive any serialize() call. // page_size: block alignment when page-aligned (power of two, >= header // size); ignored when packed, which is the default (see InlineLayout). + // + // max_doc_nnz > 0 truncates a doc's *extra* copies to its largest + // max_doc_nnz components (see inline_forward_index.h); `full_copies` then + // names, per doc id, the one block whose copy stays whole, and must outlive + // serialize() too. The two arguments only make sense together, so passing + // one without the other throws. InlineForwardIndex(const std::vector& lists, const SparseVectors& vectors, uint64_t page_size = kDefaultPageSize, - InlineLayout layout = InlineLayout::kPacked); + InlineLayout layout = InlineLayout::kPacked, + uint32_t max_doc_nnz = 0, + const std::vector* full_copies = nullptr); // Explicit, not defaulted: Buf's move keeps the source's size()/data() // (only its owner moves), so the moved-from members are reset to stay @@ -111,15 +166,45 @@ class InlineForwardIndex : public MmapSerializable { return list_offset_.empty() ? 0 : list_offset_.size() - 1; } uint64_t page_size() const { return page_size_; } + // 0 = every copy of every doc is whole; otherwise block scores are lower + // bounds and the caller must re-score its best candidates against the whole + // copies. See inline_forward_index.h. + uint32_t max_doc_nnz() const { return max_doc_nnz_; } uint64_t num_blocks_in_list(uint32_t pl) const; + // Section start, i.e. where a directory entry's byte_off is measured from. + // Exposed so a batched walk can prefetch a block before reading it. + const uint8_t* block_base() const { return block_base_; } BlockView block(uint32_t pl, uint32_t block) const; + // The directory entry for (pl, block), or null when the block is absent. + // Exposed so a batched walk can prefetch the entry before dereferencing it. + const InlineDirEntry* dir_entry(uint32_t pl, uint32_t block) const; + // One doc's slice out of an already-located block. Reads only + // doc_id[slot], off[slot], off[slot + 1] and off[n_docs], where block() + // validates the whole block -- worth separating because the re-scoring pass + // wants one doc out of a block it will not otherwise touch. Still + // fail-closed: the slot, the block length, and that the slot holds `doc_id` + // are checked, so a corrupt entry or locator cannot yield another doc's or + // an out-of-range slice. + DocSlice doc_slice(const InlineDirEntry& entry, uint32_t slot, + uint32_t doc_id) const; + // For a file written before max_doc_nnz existed: its header bytes there + // were padding, so never read them as a limit. + void ignore_max_doc_nnz() { max_doc_nnz_ = 0; } + private: - // n_docs and total_nnz of a block, from a validated doc-id span. + // n_docs and total_nnz of a block, from a validated doc-id span, and + // whether any copy in it is cut short. struct BlockCounts { uint32_t n_docs; uint64_t total_nnz; + bool truncates; + }; + // Byte length of the section body, and whether any copy is truncated. + struct SectionSize { + uint64_t length; + bool truncates; }; // page_size when page-aligned, else kMinBlockAlign (packed). uint64_t write_alignment() const { @@ -127,17 +212,47 @@ class InlineForwardIndex : public MmapSerializable { : kMinBlockAlign; } // Validate a block's doc ids and return its counts; total_nnz is capped at - // INT32_MAX so off[] stays idx_t-convertible. Shared by section_length() - // (sizing) and write_body() (emitting) so their per-block math can't drift. - static BlockCounts count_block(std::span docs, - const offset_t* indptr, size_t num_vectors); - // Byte length of the section body, from a payload-free sizing pass over - // lists + indptr. Lets serialize() write the length prefix without first - // rendering the body into a buffer. - uint64_t section_length() const; + // INT32_MAX so off[] stays idx_t-convertible. Shared by section_size() + // (sizing) and write_body() (emitting) so their per-block math can't drift, + // which is also why it must know which block it is: a doc contributes its + // whole nnz to one block and a truncated nnz to the rest. + BlockCounts count_block(std::span docs, const offset_t* indptr, + size_t num_vectors, uint32_t pl, + uint32_t block) const; + // Components this block stores for `doc_id`: all of them when truncation is + // off, when the doc is short enough anyway, or when this is the block + // holding the doc's whole copy; else write_max_doc_nnz_. + uint64_t doc_stored_nnz(idx_t doc_id, uint64_t full_nnz, uint32_t pl, + uint32_t block) const; + + // Which of a doc's components a truncated copy keeps: everything whose code + // is above `boundary`, plus the first `ties` of those equal to it. `whole` + // short-circuits a copy that keeps everything. + struct CodeCut { + double boundary = 0.0; + uint32_t ties = 0; + bool whole = true; + }; + // The cut that keeps the `keep` largest of `nnz` codes. `scratch` is reused + // across calls so the per-doc selection does not allocate. + static CodeCut select_top_codes(const uint8_t* values, uint64_t nnz, + uint64_t keep, size_t element_size, + std::vector* scratch); + // Append the components (and/or the value bytes) the cut keeps, in stored + // order. Either output may be null; both read the same cut, which is what + // keeps the comps[] and vals[] passes in step. + static void gather_selected(const term_t* comps, const uint8_t* values, + uint64_t nnz, size_t element_size, CodeCut cut, + std::vector* comps_out, + std::vector* vals_out); + // The section body's size, from a payload-free sizing pass over lists + + // indptr. Lets serialize() write the length prefix without first rendering + // the body into a buffer. + SectionSize section_size() const; // Stream the section body (header, blocks, directory, trailer) straight to // the writer; serialize() precedes it with padding + the length prefix. - void write_body(IOWriter* writer) const; + // `max_doc_nnz` is what the header records. + void write_body(IOWriter* writer, uint32_t max_doc_nnz) const; // Validate the section at [base, base + section_len) and load its directory // into RAM; sets element_size_/page_size_/entries_/list_offset_. void load_directory(const uint8_t* base, size_t section_len); @@ -149,12 +264,15 @@ class InlineForwardIndex : public MmapSerializable { const SparseVectors* vectors_ = nullptr; uint64_t write_page_size_ = kDefaultPageSize; InlineLayout write_layout_ = InlineLayout::kPageAligned; + uint32_t write_max_doc_nnz_ = 0; + const std::vector* write_full_copies_ = nullptr; // Read mode. const uint8_t* block_base_ = nullptr; // section start (blocks at +byte_off) size_t element_size_ = 0; uint64_t page_size_ = 0; + uint32_t max_doc_nnz_ = 0; Buf entries_; // directory copied into RAM Buf list_offset_; // start of each list in entries_ }; diff --git a/nsparse/io/io.h b/nsparse/io/io.h index 19d9a9f..82a155c 100644 --- a/nsparse/io/io.h +++ b/nsparse/io/io.h @@ -83,6 +83,14 @@ class IndexIO { // change ship without one, which is the failure the header exists to catch. [[nodiscard]] virtual uint32_t format_version() const = 0; + // The version write_index stamps on this file. format_version() is also + // the newest version read_index accepts, so a type whose payload is + // sometimes still an older layout can stamp that one instead and keep + // older builds reading those files. + [[nodiscard]] virtual uint32_t written_format_version() const { + return format_version(); + } + virtual void write_index(IOWriter* io_writer) {}; // `header` is what the file declared, with its version already checked diff --git a/nsparse/python/swignsparse.swig b/nsparse/python/swignsparse.swig index 717ebc5..b1719c8 100644 --- a/nsparse/python/swignsparse.swig +++ b/nsparse/python/swignsparse.swig @@ -199,6 +199,10 @@ import_array(); // The disk-resident indexes derive from DiskSeismicIndexBase (itself a // MmapIndex), so SWIG needs the base first or the Python classes lose their // inherited search / num_vectors / add. +// One wrapper with keyword arguments, rescore= included: a defaulted parameter +// would otherwise split into overloads, which SWIG wraps as *args only. +%feature("compactdefaultargs") nsparse::DiskSeismicSQSearchParameters::DiskSeismicSQSearchParameters; +%feature("kwargs") nsparse::DiskSeismicSQSearchParameters::DiskSeismicSQSearchParameters; %include "nsparse/disk_seismic_index_base.h" %include "nsparse/disk_seismic_index.h" %include "nsparse/disk_seismic_scalar_quantized_index.h" diff --git a/nsparse/utils/mmap_file.h b/nsparse/utils/mmap_file.h index b7d6f8c..a2e0f46 100644 --- a/nsparse/utils/mmap_file.h +++ b/nsparse/utils/mmap_file.h @@ -90,6 +90,37 @@ class MmapFile { const uint8_t* data() const { return data_; } size_t size() const { return size_; } + // Runs `read` with readahead on over [begin, begin + len), a range of this + // mapping, then puts the mapping's own hint back. For a one-off sweep + // through part of a MADV_RANDOM mapping, where each cold 4 KiB page would + // otherwise be its own synchronous read. + template + void read_sequentially(const uint8_t* begin, size_t len, Read&& read) { + if (len > 0 && (begin < data_ || + len > size_ - static_cast(begin - data_))) { + throw std::out_of_range("mmap: range outside the mapping"); + } +#if !defined(_WIN32) + if (len > 0 && !hugetlb_) { + const auto page = static_cast(::sysconf(_SC_PAGESIZE)); + // madvise takes a page-aligned start. + const size_t lead = reinterpret_cast(begin) & (page - 1); + // Restored even if `read` throws: the mapping may outlive it. + struct Advice { + void* addr; + size_t len; + int restore; + ~Advice() { ::madvise(addr, len, restore); } + } advice{const_cast(begin - lead), len + lead, + random_ ? MADV_RANDOM : MADV_NORMAL}; + ::madvise(advice.addr, advice.len, MADV_SEQUENTIAL); + read(); + return; + } +#endif + read(); + } + void open(const std::string& path, AccessPattern access = AccessPattern::kScan) { close(); @@ -204,6 +235,7 @@ class MmapFile { // "hugepage" | "random" | "normal" | "hugetlb". if (mode == "random") { ::madvise(addr, size_, MADV_RANDOM); + random_ = true; } else if (mode == "normal") { // leave kernel defaults } else { @@ -234,6 +266,7 @@ class MmapFile { #endif data_ = nullptr; size_ = 0; + random_ = false; } private: @@ -241,9 +274,11 @@ class MmapFile { data_ = other.data_; size_ = other.size_; hugetlb_ = other.hugetlb_; + random_ = other.random_; other.data_ = nullptr; other.size_ = 0; other.hugetlb_ = false; + other.random_ = false; #if defined(_WIN32) file_ = other.file_; mapping_ = other.mapping_; @@ -255,6 +290,7 @@ class MmapFile { const uint8_t* data_ = nullptr; size_t size_ = 0; bool hugetlb_ = false; // data_ is an anonymous MAP_HUGETLB copy, not the file + bool random_ = false; // mapped with MADV_RANDOM #if defined(_WIN32) HANDLE file_ = INVALID_HANDLE_VALUE; HANDLE mapping_ = nullptr; diff --git a/nsparse/utils/omp_exception.h b/nsparse/utils/omp_exception.h new file mode 100644 index 0000000..ef9018c --- /dev/null +++ b/nsparse/utils/omp_exception.h @@ -0,0 +1,55 @@ +/** + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +#ifndef OMP_EXCEPTION_H +#define OMP_EXCEPTION_H +#include +#include +#include + +namespace nsparse::detail { + +// An exception leaving an OpenMP region is std::terminate, so SWIG/JNI callers +// would see an abort instead of an error. Run each iteration of a parallel loop +// body through run(): the first exception is kept and the remaining iterations +// are skipped (they cannot break out of an `omp for`), then rethrow() raises it +// once the region has ended. +class OmpExceptionCapture { +public: + template + void run(Body&& body) noexcept { + if (failed_.load(std::memory_order_relaxed)) { + return; + } + try { + body(); + } catch (...) { + const std::lock_guard lock(mutex_); + if (!error_) { + error_ = std::current_exception(); + } + failed_.store(true, std::memory_order_relaxed); + } + } + + void rethrow() const { + if (error_) { + std::rethrow_exception(error_); + } + } + +private: + std::atomic failed_{false}; + std::mutex mutex_; + std::exception_ptr error_; +}; + +} // namespace nsparse::detail + +#endif // OMP_EXCEPTION_H diff --git a/python_tests/disk_seismic_contract.py b/python_tests/disk_seismic_contract.py index c617c9b..0020362 100644 --- a/python_tests/disk_seismic_contract.py +++ b/python_tests/disk_seismic_contract.py @@ -23,6 +23,7 @@ K, PAD_DIST, PAD_LABEL, + assert_same_ranking_modulo_ties, make_index, roundtrip, search, @@ -42,12 +43,25 @@ class DiskSeismicContract: CUT = 8 K_PRIME = 200 - def params(self, cut=None, k_prime=None): + # Components a truncated index keeps in each doc's extra inline copies. The + # session corpus has 30 per doc, so this cuts most copies to under a third. + INLINE_MAX_NNZ = 8 + + def params(self, cut=None, k_prime=None, rescore=None): """The index's SearchParameters. Subclass provides the concrete type; - None means "use the default", so k_prime=0 is passed through (not - coalesced) for the rejection test.""" + None means "use the default", so k_prime=0 / rescore=-1 are passed + through (not coalesced) for the rejection tests, and rescore=None + leaves the library default in place.""" raise NotImplementedError + def truncated(self, corpus, path, limit=None): + """A seeded index built with inline_max_nnz and mmap-reloaded: + truncation exists only in the serialized form, so a fresh in-RAM build + never exercises it.""" + limit = self.INLINE_MAX_NNZ if limit is None else limit + spec = f"{self.SEEDED}|inline_max_nnz={limit}" + return roundtrip(make_index(spec, corpus), path, nsparse.kUseMmap) + @pytest.mark.parametrize("residency", ["memory", "mmap"]) def test_happy_case(self, residency, corpus, queries, oracle, tmp_path): """factory -> ingest -> build -> query -> accuracy, in both residencies.""" @@ -206,3 +220,151 @@ def test_seeded_build_is_reproducible(self, corpus, queries): second = search(make_index(self.SEEDED, corpus), queries, params=self.params()) np.testing.assert_array_equal(second[1], first[1]) np.testing.assert_array_equal(second[0], first[0]) + + # --- inline_max_nnz (build) and rescore (query) --- + + def test_rescore_defaults_to_the_library_depth(self): + """rescore is a plain per-query field: defaulted (to the automatic, + k-relative depth), overridable at construction, and settable + afterwards.""" + assert self.params().rescore == nsparse.kAutoRescoreDepth + p = self.params(rescore=7) + assert p.rescore == 7 + p.rescore = 11 + assert p.rescore == 11 + + def test_truncation_shrinks_the_file(self, corpus, tmp_path): + """The point of inline_max_nnz: each tighter limit is a smaller file.""" + sizes = [] + for limit in [0, 16, self.INLINE_MAX_NNZ]: + path = tmp_path / f"limit{limit}.idx" + nsparse.write_index( + make_index(f"{self.SEEDED}|inline_max_nnz={limit}", corpus), str(path) + ) + sizes.append(path.stat().st_size) + assert sizes[0] > sizes[1] > sizes[2], sizes + + def test_truncated_matches_whole_when_everything_is_rescored( + self, corpus, queries, tmp_path + ): + """Truncation only changes how candidates are ranked before the second + pass, so with every block selected and every candidate re-scored the + result is the untruncated index's.""" + whole = self.truncated(corpus, tmp_path / "whole.idx", limit=0) + cut = self.truncated(corpus, tmp_path / "cut.idx") + everything = self.params(k_prime=10**6, rescore=10**6) + assert_same_ranking_modulo_ties( + search(cut, queries, params=everything), + search(whole, queries, params=self.params(k_prime=10**6)), + ) + + def test_rescore_below_the_pool_still_ranks_well( + self, corpus, queries, oracle, tmp_path + ): + """A depth below the candidate pool is where the block scores decide + what gets re-scored: recall must hold up there, and the result must + differ from re-scoring everything, or the fixture no longer exercises + the first pass at all.""" + cut = self.truncated(corpus, tmp_path / "cut.idx") + _, partial = search(cut, queries, params=self.params(rescore=100)) + _, everything = search(cut, queries, params=self.params(rescore=10**6)) + want_labels, _ = oracle + assert recall_at_k(partial, want_labels) >= 0.80 + assert not np.array_equal(partial, everything) + + def test_truncated_index_clears_the_recall_floor( + self, corpus, queries, oracle, tmp_path + ): + """At the default depth a truncated index is still a usable index.""" + cut = self.truncated(corpus, tmp_path / "cut.idx") + _, labels = search(cut, queries, params=self.params()) + want_labels, _ = oracle + assert recall_at_k(labels, want_labels) >= self.RECALL_FLOOR + + def test_rescore_is_ignored_without_truncation(self, corpus, queries, tmp_path): + """With every copy whole there is nothing to re-score.""" + whole = self.truncated(corpus, tmp_path / "whole.idx", limit=0) + shallow = search(whole, queries, params=self.params(rescore=K)) + deep = search(whole, queries, params=self.params(rescore=10**6)) + np.testing.assert_array_equal(shallow[1], deep[1]) + np.testing.assert_array_equal(shallow[0], deep[0]) + + def test_rescored_scores_are_exact(self, corpus, queries, tmp_path): + """A returned score is the doc's true score, not its truncated copy's + lower bound -- even at depth k, where the second pass cannot change which + docs come back. The oracle is the untruncated index scoring exactly the + returned docs: a selector of size <= k takes the exact-match path.""" + whole = self.truncated(corpus, tmp_path / "whole.idx", limit=0) + cut = self.truncated(corpus, tmp_path / "cut.idx") + dists, labels = search(cut, queries, params=self.params(rescore=K)) + for q in range(queries.n): + members = np.ascontiguousarray(labels[q][labels[q] >= 0], dtype=np.int32) + exact = self.params() + selector = nsparse.SetIDSelector(members) + exact.set_id_selector(selector) + want_d, want_l = search(whole, slice_corpus(queries, q, q + 1), params=exact) + want = dict(zip(want_l[0].tolist(), want_d[0].tolist())) + for doc, score in zip(labels[q], dists[q]): + if doc >= 0: + assert score == pytest.approx(want[int(doc)], rel=1e-6, abs=1e-6), ( + f"query {q} doc {doc} returned a lower bound" + ) + + @pytest.mark.parametrize("below", [1, K - 1]) + def test_rescore_below_k_behaves_like_k(self, below, corpus, queries, tmp_path): + """Fewer than k re-scored candidates could not fill the result, so the + depth is raised to k.""" + cut = self.truncated(corpus, tmp_path / "cut.idx") + at_k = search(cut, queries, params=self.params(rescore=K)) + under = search(cut, queries, params=self.params(rescore=below)) + np.testing.assert_array_equal(under[1], at_k[1]) + np.testing.assert_array_equal(under[0], at_k[0]) + + def test_deeper_rescore_never_lowers_the_result(self, corpus, queries, tmp_path): + """A deeper pass re-scores a superset of candidates, and the k best exact + scores of a superset are never worse: each query's summed top-k score is + non-decreasing in the depth.""" + cut = self.truncated(corpus, tmp_path / "cut.idx") + previous = None + for depth in [K, 2 * K, 50, 200, 10**6]: + dists, _ = search(cut, queries, params=self.params(k_prime=10**6, rescore=depth)) + total = np.where(dists > 0, dists, 0).astype(np.float64).sum(axis=1) + if previous is not None: + assert (total >= previous - 1e-4).all(), f"depth {depth} lowered a query" + previous = total + + @pytest.mark.parametrize("limit", [0, 8]) + def test_rejects_negative_rescore(self, limit, corpus, queries, tmp_path): + """A negative depth is rejected on any disk index, used or not.""" + index = self.truncated(corpus, tmp_path / "index.idx", limit=limit) + with pytest.raises(ValueError, match="non-negative"): + search(index, queries, params=self.params(rescore=-1)) + + @pytest.mark.parametrize( + "bad", ["-1", "4294967296", "abc", "", "1e3", "0x40", "64abc", "64.9"] + ) + def test_factory_rejects_a_bad_inline_max_nnz(self, corpus, bad): + """A malformed limit fails the spec instead of becoming "no truncation".""" + with pytest.raises(ValueError): + nsparse.index_factory(corpus.dim, f"{self.SPEC}|inline_max_nnz={bad}") + + def test_truncated_with_id_map(self, corpus, queries, doc_ids, tmp_path): + """idmap forwards the search parameters, rescore included, to a + truncated delegate and maps the re-scored ids back: it returns exactly + what the delegate does at the same depth, translated to caller ids.""" + spec = f"idmap,{self.SEEDED}|inline_max_nnz={self.INLINE_MAX_NNZ}" + index = roundtrip( + make_index(spec, corpus, ids=doc_ids), tmp_path / "idmap.idx", nsparse.kUseMmap + ) + delegate = self.truncated(corpus, tmp_path / "delegate.idx") + ids = np.asarray(doc_ids) + results = [] + for depth in [10, 50]: + params = self.params(rescore=depth) + _, labels = search(index, queries, params=params) + _, internal = search(delegate, queries, params=params) + want = np.where(internal >= 0, ids[np.maximum(internal, 0)], internal) + np.testing.assert_array_equal(labels, want) + results.append(labels) + # The two depths must disagree somewhere, or dropping rescore would pass. + assert not np.array_equal(results[0], results[1]) diff --git a/python_tests/support.py b/python_tests/support.py index e7eb8d8..6f58470 100644 --- a/python_tests/support.py +++ b/python_tests/support.py @@ -123,3 +123,24 @@ def roundtrip(index, path, flag=0): """ nsparse.write_index(index, str(path)) return nsparse.read_index(str(path), flag) + + +def assert_same_ranking_modulo_ties(got, want): + """Same scores rank for rank, and the same docs except where equal scores + leave the order (or, in the last run of ties, the cut at k) up to the + tie-break. Quantized scores are small integers, so ties are routine and + which tied doc wins is not part of any format's contract.""" + got_d, got_l = got + want_d, want_l = want + np.testing.assert_allclose(got_d, want_d, rtol=1e-6, atol=1e-6) + for q in range(want_d.shape[0]): + row = want_d[q] + start = 0 + for end in range(1, len(row) + 1): + if end < len(row) and np.isclose(row[end], row[start]): + continue + if end < len(row): + assert sorted(got_l[q, start:end]) == sorted(want_l[q, start:end]), ( + f"query {q}: tie run at rank {start} holds different docs" + ) + start = end diff --git a/python_tests/test_disk_seismic_index.py b/python_tests/test_disk_seismic_index.py index f5ebbdf..aefab2c 100644 --- a/python_tests/test_disk_seismic_index.py +++ b/python_tests/test_disk_seismic_index.py @@ -24,7 +24,9 @@ class TestDiskSeismic(DiskSeismicContract): # Calibrated against the session corpus; a floor, not a target. RECALL_FLOOR = 0.80 - def params(self, cut=None, k_prime=None): + def params(self, cut=None, k_prime=None, rescore=None): cut = self.CUT if cut is None else cut k_prime = self.K_PRIME if k_prime is None else k_prime - return nsparse.DiskSeismicSearchParameters(cut, k_prime) + if rescore is None: + return nsparse.DiskSeismicSearchParameters(cut, k_prime) + return nsparse.DiskSeismicSearchParameters(cut, k_prime, rescore) diff --git a/python_tests/test_disk_seismic_sq_index.py b/python_tests/test_disk_seismic_sq_index.py index 5a64fe0..c27f2a1 100644 --- a/python_tests/test_disk_seismic_sq_index.py +++ b/python_tests/test_disk_seismic_sq_index.py @@ -40,10 +40,22 @@ class TestDiskSeismicSQ(DiskSeismicContract): # quantization adds noise, so a tight bound would flake. RECALL_FLOOR = 0.75 - def params(self, cut=None, k_prime=None): + def params(self, cut=None, k_prime=None, rescore=None): cut = self.CUT if cut is None else cut k_prime = self.K_PRIME if k_prime is None else k_prime - return nsparse.DiskSeismicSQSearchParameters(VMIN, VMAX, cut, k_prime) + if rescore is None: + return nsparse.DiskSeismicSQSearchParameters(VMIN, VMAX, cut, k_prime) + return nsparse.DiskSeismicSQSearchParameters(VMIN, VMAX, cut, k_prime, rescore) + + def test_parameters_take_keywords(self): + """The constructor keeps its keyword arguments, rescore= included.""" + p = nsparse.DiskSeismicSQSearchParameters(vmin=0.0, vmax=3.0, cut=3, k_prime=50) + assert (p.vmin, p.vmax, p.cut, p.k_prime) == (0.0, 3.0, 3, 50) + assert p.rescore == nsparse.kAutoRescoreDepth + p = nsparse.DiskSeismicSQSearchParameters( + vmin=0.0, vmax=3.0, cut=3, k_prime=50, rescore=7 + ) + assert p.rescore == 7 # --- quantization-specific --- diff --git a/tests/disk_seismic_index_test.cpp b/tests/disk_seismic_index_test.cpp index c2d10d6..c9ad000 100644 --- a/tests/disk_seismic_index_test.cpp +++ b/tests/disk_seismic_index_test.cpp @@ -305,4 +305,92 @@ TEST(DiskSeismicIndex, FactoryCreatesIt) { EXPECT_EQ(index->id(), DiskSeismicIndex::name); } +// The float disk index shares the truncation machinery but stores 4-byte values, +// so it selects "the largest" over a different code width. Same anchor: with +// everything re-scored the truncated index ranks exactly like the whole one. +TEST(DiskSeismicIndex, TruncatedInlineMatchesWholeWhenEverythingIsRescored) { + const CSR corpus = make_corpus(1200, /*seed=*/1); + const CSR queries = make_corpus(30, /*seed=*/2); + + DiskSeismicIndex whole(kDim, cluster_params()); + add_corpus(whole, corpus); + whole.build(); + TempIndexFile whole_file("nsparse_dsei_trunc_whole.idx"); + write_index(&whole, whole_file.c_str()); + std::unique_ptr whole_mapped( + read_index(whole_file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(whole_mapped, nullptr); + + DiskSeismicIndex cut(kDim, cluster_params(), /*inline_max_nnz=*/6); + add_corpus(cut, corpus); + cut.build(); + TempIndexFile cut_file("nsparse_dsei_trunc_cut.idx"); + write_index(&cut, cut_file.c_str()); + std::unique_ptr cut_mapped( + read_index(cut_file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(cut_mapped, nullptr); + + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/kAllBlocks); + DiskSeismicSearchParameters rescore_all(/*cut=*/10, /*k_prime=*/kAllBlocks, + /*rescore=*/100000); + expect_same_ranking_modulo_ties( + search_all(*cut_mapped, queries, 10, &rescore_all), + search_all(*whole_mapped, queries, 10, ¶ms)); + EXPECT_LT(cut_file.size(), whole_file.size()); +} + +// Builds, writes, and mmap-reloads a float index over `corpus` with +// inline_max_nnz = `limit` (0 = every copy whole). +std::unique_ptr mapped_dsei(const CSR& corpus, uint32_t limit, + TempIndexFile& file) { + DiskSeismicIndex index(kDim, cluster_params(), limit); + add_corpus(index, corpus); + index.build(); + write_index(&index, file.c_str()); + return std::unique_ptr( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); +} + +// Nothing truncated is the v1 layout, so it is stamped 1 and builds from before +// truncation still read it. A truncated file must never be: a v1 reader would +// score its partial copies as if whole. +TEST(DiskSeismicIndex, StampsVersionOneUnlessTruncated) { + const CSR corpus = make_corpus(600, /*seed=*/7); + TempIndexFile whole("nsparse_dsei_stamp_whole.idx"); + ASSERT_NE(mapped_dsei(corpus, /*limit=*/0, whole), nullptr); + EXPECT_EQ(file_format_version(whole.c_str()), 1U); + TempIndexFile cut("nsparse_dsei_stamp_cut.idx"); + ASSERT_NE(mapped_dsei(corpus, /*limit=*/4, cut), nullptr); + EXPECT_EQ(file_format_version(cut.c_str()), + DiskSeismicIndex::kFormatVersion); +} + +// A format-version-1 file has no max_doc_nnz; the bytes it sits in were +// padding. A truncated file relabelled v1 puts a limit there: read as v1 it is +// scored as if whole, so the re-scoring depth has nothing to change. +TEST(DiskSeismicIndex, ReadsAFormatVersionOneFile) { + const CSR corpus = make_corpus(800, /*seed=*/8); + const CSR queries = make_corpus(20, /*seed=*/9); + TempIndexFile file("nsparse_dsei_v1.idx"); + DiskSeismicSearchParameters shallow(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/10); + DiskSeismicSearchParameters deep(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/INT32_MAX); + { + // Read as written, the depth does change results, so the check below + // can see a v1 reader that honors the limit. + std::unique_ptr v2 = mapped_dsei(corpus, /*limit=*/4, file); + ASSERT_NE(v2, nullptr); + ASSERT_NE(search_all(*v2, queries, 10, &shallow), + search_all(*v2, queries, 10, &deep)); + } + ASSERT_EQ(file_format_version(file.c_str()), + DiskSeismicIndex::kFormatVersion); + set_file_format_version(file.c_str(), 1); + std::unique_ptr v1(read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(v1, nullptr); + expect_same_results(search_all(*v1, queries, 10, &shallow), + search_all(*v1, queries, 10, &deep)); +} + } // namespace nsparse diff --git a/tests/disk_seismic_scalar_quantized_index_test.cpp b/tests/disk_seismic_scalar_quantized_index_test.cpp index b8e69e1..359c999 100644 --- a/tests/disk_seismic_scalar_quantized_index_test.cpp +++ b/tests/disk_seismic_scalar_quantized_index_test.cpp @@ -11,16 +11,22 @@ #include +#include +#include #include #include +#include #include #include +#include #include #include #include #include #include "nsparse/disk_seismic_index.h" +#include "nsparse/disk_seismic_search.h" +#include "nsparse/id_selector.h" #include "nsparse/index_factory.h" #include "nsparse/io/buffered_io.h" #include "nsparse/io/index_io.h" @@ -511,4 +517,615 @@ TEST(DiskSeismicSQIndex, MmapCodesCsrBuildMatchesAddBuild) { std::invalid_argument); } +// --- Truncated inline forward index (inline_max_nnz) --- + +// The anchor for the whole scheme: truncating the extra inline copies changes +// only how candidates are *ranked* before re-scoring, so with every block +// selected and a re-scoring depth past the candidate pool the result must be +// bit-identical to keeping every copy whole. +TEST(DiskSeismicSQIndex, TruncatedInlineMatchesWholeWhenEverythingIsRescored) { + const CSR corpus = make_corpus(1500, /*seed=*/1); + const CSR queries = make_corpus(40, /*seed=*/2); + // A limit well below the corpus's 5..25 nnz per doc, so most copies are cut. + constexpr uint32_t kInlineMaxNnz = 6; + + DiskSeismicScalarQuantizedIndex whole(QuantizerType::QT_8bit, 0.0F, 1.0F, + cluster_params(), kDim); + add_corpus(whole, corpus); + whole.build(); + TempIndexFile whole_file("nsparse_dssq_trunc_whole.idx"); + write_index(&whole, whole_file.c_str()); + std::unique_ptr whole_mapped( + read_index(whole_file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(whole_mapped, nullptr); + + DiskSeismicScalarQuantizedIndex cut(QuantizerType::QT_8bit, 0.0F, 1.0F, + cluster_params(), kDim, kInlineMaxNnz); + add_corpus(cut, corpus); + cut.build(); + TempIndexFile cut_file("nsparse_dssq_trunc_cut.idx"); + write_index(&cut, cut_file.c_str()); + std::unique_ptr cut_mapped( + read_index(cut_file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(cut_mapped, nullptr); + + // Same clusters (fixed seed) and every block selected, so both see the same + // candidate pool. + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/kAllBlocks); + DiskSeismicSearchParameters rescore_all(/*cut=*/10, /*k_prime=*/kAllBlocks, + /*rescore=*/100000); + expect_same_ranking_modulo_ties( + search_all(*cut_mapped, queries, 10, &rescore_all), + search_all(*whole_mapped, queries, 10, ¶ms)); + EXPECT_LT(cut_file.size(), whole_file.size()); +} + +// The whole point: the file gets smaller, and the truncation survives the round +// trip so a reader knows it must re-score. +TEST(DiskSeismicSQIndex, TruncatedInlineShrinksTheFile) { + const CSR corpus = make_corpus(1200, /*seed=*/7); + std::uintmax_t previous = 0; + // Tighter limits are monotonically smaller files; 0 keeps every copy whole. + for (const uint32_t limit : {0U, 12U, 6U, 3U}) { + DiskSeismicScalarQuantizedIndex index(QuantizerType::QT_8bit, 0.0F, + 1.0F, cluster_params(), kDim, + limit); + add_corpus(index, corpus); + index.build(); + TempIndexFile file("nsparse_dssq_trunc_size.idx"); + write_index(&index, file.c_str()); + if (previous != 0) { + EXPECT_LT(file.size(), previous) << "limit " << limit; + } + previous = file.size(); + std::unique_ptr mapped( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(mapped, nullptr); + // Searching a truncated index still returns k results. + const CSR queries = make_corpus(5, /*seed=*/8); + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32); + const ScoreIds got = search_all(*mapped, queries, 10, ¶ms); + for (const auto& ids : got.second) { + for (const idx_t id : ids) { + EXPECT_NE(id, detail::INVALID_IDX) << "limit " << limit; + } + } + } +} + +// Docs that no block holds live in the remainder store, which is never +// truncated: the mapped exact-match path must score them on their whole +// vectors, exactly as the fresh in-RAM index does. The victims carry two terms +// against a limit of one, and both terms' lists prune them (more than kLambda +// fillers outweigh them on each), so a cut remainder row would show up. +TEST(DiskSeismicSQIndex, TruncationLeavesRemainderDocsWhole) { + constexpr int kFillers = 64; + constexpr int kVictims = 3; + CSR corpus; + corpus.n = kFillers + kVictims; + corpus.indptr.push_back(0); + for (int r = 0; r < kFillers; ++r) { + for (const term_t term : + {term_t{0}, term_t{1}, static_cast(r + 2)}) { + corpus.indices.push_back(term); + corpus.values.push_back(1.0F); + } + corpus.indptr.push_back(static_cast(corpus.indices.size())); + } + std::vector victims; + for (int v = 0; v < kVictims; ++v) { + corpus.indices.push_back(0); + corpus.values.push_back(0.01F * static_cast(v + 1)); + corpus.indices.push_back(1); + corpus.values.push_back(0.02F); + corpus.indptr.push_back(static_cast(corpus.indices.size())); + victims.push_back(kFillers + v); + } + DiskSeismicScalarQuantizedIndex index(QuantizerType::QT_8bit, 0.0F, 1.0F, + cluster_params(), kDim, + /*inline_max_nnz=*/1); + add_corpus(index, corpus); + index.build(); + + CSR queries; + queries.n = 1; + queries.indptr = {0, 2}; + queries.indices = {0, 1}; + queries.values = {1.0F, 1.0F}; + SetIDSelector selector(victims.size(), victims.data()); + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32); + params.set_id_selector(&selector); + const ScoreIds fresh = search_all(index, queries, 10, ¶ms); + + TempIndexFile file("nsparse_dssq_trunc_remainder.idx"); + write_index(&index, file.c_str()); + std::unique_ptr mapped( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(mapped, nullptr); + const ScoreIds got = search_all(*mapped, queries, 10, ¶ms); + expect_all_members_returned(got, victims); + expect_same_results(got, fresh); +} + +// A truncated index built through the factory string, since that is how the +// knob reaches production callers. +TEST(DiskSeismicSQIndex, FactoryAcceptsInlineMaxNnz) { + const CSR corpus = make_corpus(600, /*seed=*/3); + std::unique_ptr index(index_factory( + kDim, + "disk_seismic_sq,quantizer=8bit|vmin=0.0|vmax=1.0|lambda=32|beta=8|" + "alpha=0.4|seed=42|inline_max_nnz=6")); + ASSERT_NE(index, nullptr); + add_corpus(*index, corpus); + index->build(); + TempIndexFile file("nsparse_dssq_trunc_factory.idx"); + write_index(index.get(), file.c_str()); + std::unique_ptr mapped( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(mapped, nullptr); + EXPECT_EQ(mapped->num_vectors(), static_cast(corpus.n)); + + // The key has to reach the writer, not just parse. + std::unique_ptr whole(index_factory( + kDim, + "disk_seismic_sq,quantizer=8bit|vmin=0.0|vmax=1.0|lambda=32|beta=8|" + "alpha=0.4|seed=42|inline_max_nnz=0")); + add_corpus(*whole, corpus); + whole->build(); + TempIndexFile whole_file("nsparse_dssq_trunc_factory_whole.idx"); + write_index(whole.get(), whole_file.c_str()); + EXPECT_LT(file.size(), whole_file.size()); +} + +// --- The rescore search parameter --- + +// Builds, writes, and mmap-reloads a seeded 8-bit index over `corpus`, with +// inline_max_nnz = `limit` (0 = every copy whole). Truncation only exists on +// disk, so every rescore test has to go through a reload. +std::unique_ptr mapped_sq(const CSR& corpus, uint32_t limit, + TempIndexFile& file) { + DiskSeismicScalarQuantizedIndex index(QuantizerType::QT_8bit, 0.0F, 1.0F, + cluster_params(), kDim, limit); + add_corpus(index, corpus); + index.build(); + write_index(&index, file.c_str()); + return std::unique_ptr(read_index(file.c_str(), IndexIoFlag::kUseMmap)); +} + +TEST(DiskSeismicSearchParameters, CarriesRescoreDepth) { + EXPECT_EQ(DiskSeismicSearchParameters().rescore, kAutoRescoreDepth); + EXPECT_EQ(DiskSeismicSearchParameters(3, 50).rescore, kAutoRescoreDepth); + EXPECT_EQ(DiskSeismicSearchParameters(3, 50, 77).rescore, 77); + EXPECT_EQ(DiskSeismicSQSearchParameters(0.0F, 1.0F, 3, 50).rescore, + kAutoRescoreDepth); + EXPECT_EQ(DiskSeismicSQSearchParameters(0.0F, 1.0F, 3, 50, 77).rescore, 77); + + // resolve_cut_and_budget is what search reads it through: a disk parameter + // carries its own depth, anything else gets the default. + const DiskSeismicSQSearchParameters sq(0.0F, 1.0F, 4, 60, 77); + const detail::DiskSeismicCutBudget from_sq = + detail::resolve_cut_and_budget(&sq); + EXPECT_EQ(from_sq.cut, 4); + EXPECT_EQ(from_sq.k_prime, 60); + EXPECT_EQ(from_sq.rescore, 77); + const SeismicSearchParameters plain(5, 1.0F); + EXPECT_EQ(detail::resolve_cut_and_budget(&plain).rescore, + kAutoRescoreDepth); + EXPECT_EQ(detail::resolve_cut_and_budget(nullptr).rescore, + kAutoRescoreDepth); +} + +// The automatic depth grows with k so the oversampling does not vanish at a +// large k; an explicit depth is the caller's, only floored at k. +TEST(DiskSeismicSearchParameters, AutoRescoreDepthScalesWithK) { + EXPECT_EQ(detail::resolve_rescore_depth(kAutoRescoreDepth, 10), + kAutoRescoreMinDepth); + EXPECT_EQ(detail::resolve_rescore_depth(kAutoRescoreDepth, 100), + kAutoRescorePerK * 100); + EXPECT_EQ(detail::resolve_rescore_depth(kAutoRescoreDepth, 1'000'000'000), + INT32_MAX); + EXPECT_EQ(detail::resolve_rescore_depth(50, 10), 50); + EXPECT_EQ(detail::resolve_rescore_depth(5, 10), 10); + EXPECT_EQ(detail::resolve_rescore_depth(INT32_MAX, 10), INT32_MAX); +} + +// On an index whose copies are all whole there is nothing to re-score, so the +// depth must not change a single result. +TEST(DiskSeismicSQIndex, RescoreIsIgnoredWithoutTruncation) { + const CSR corpus = make_corpus(1200, /*seed=*/11); + const CSR queries = make_corpus(30, /*seed=*/12); + TempIndexFile file("nsparse_dssq_rescore_whole.idx"); + std::unique_ptr mapped = mapped_sq(corpus, 0, file); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters shallow(/*cut=*/10, /*k_prime=*/32, /*rescore=*/10); + DiskSeismicSearchParameters deep(/*cut=*/10, /*k_prime=*/32, /*rescore=*/100000); + expect_same_results(search_all(*mapped, queries, 10, &shallow), + search_all(*mapped, queries, 10, &deep)); +} + +// After re-scoring, a returned score is the doc's true score, not the lower +// bound its truncated copy gave -- even at depth k, where the second pass +// cannot change which docs come back, only what they score. +TEST(DiskSeismicSQIndex, RescoredScoresAreExact) { + const CSR corpus = make_corpus(1200, /*seed=*/13); + const CSR queries = make_corpus(20, /*seed=*/14); + constexpr int kK = 10; + TempIndexFile cut_file("nsparse_dssq_rescore_exact_cut.idx"); + std::unique_ptr cut = mapped_sq(corpus, /*limit=*/4, cut_file); + TempIndexFile whole_file("nsparse_dssq_rescore_exact_whole.idx"); + std::unique_ptr whole = mapped_sq(corpus, 0, whole_file); + ASSERT_NE(cut, nullptr); + ASSERT_NE(whole, nullptr); + + for (const int depth : {kK, 50}) { + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32, depth); + const ScoreIds got = search_all(*cut, queries, kK, ¶ms); + for (idx_t q = 0; q < queries.n; ++q) { + // An enumerable selector of size <= k takes the exact-match path, + // which scores exactly the named docs against their whole vectors + // in the untruncated index: an independent oracle. + std::vector members; + for (const idx_t id : got.second[q]) { + if (id != detail::INVALID_IDX) { + members.push_back(id); + } + } + SetIDSelector selector(members.size(), members.data()); + DiskSeismicSearchParameters exact(/*cut=*/10, /*k_prime=*/32); + exact.set_id_selector(&selector); + CSR one; + one.n = 1; + one.indptr = {0, queries.indptr[q + 1] - queries.indptr[q]}; + one.indices.assign(queries.indices.begin() + queries.indptr[q], + queries.indices.begin() + queries.indptr[q + 1]); + one.values.assign(queries.values.begin() + queries.indptr[q], + queries.values.begin() + queries.indptr[q + 1]); + const ScoreIds want = search_all(*whole, one, kK, &exact); + for (size_t j = 0; j < members.size(); ++j) { + const auto at = std::find(want.second[0].begin(), + want.second[0].end(), members[j]); + ASSERT_NE(at, want.second[0].end()); + EXPECT_FLOAT_EQ(got.first[q][j], + want.first[0][at - want.second[0].begin()]) + << "depth " << depth << " query " << q << " doc " + << members[j] << " returned a lower bound"; + } + } + } +} + +// Fewer than k re-scored candidates could not fill the result, so a depth below +// k behaves exactly like depth k. +TEST(DiskSeismicSQIndex, RescoreBelowKIsRaisedToK) { + const CSR corpus = make_corpus(1200, /*seed=*/15); + const CSR queries = make_corpus(30, /*seed=*/16); + TempIndexFile file("nsparse_dssq_rescore_floor.idx"); + std::unique_ptr mapped = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters at_k(/*cut=*/10, /*k_prime=*/32, /*rescore=*/10); + const ScoreIds want = search_all(*mapped, queries, 10, &at_k); + for (const int below : {1, 9}) { + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32, below); + expect_same_results(search_all(*mapped, queries, 10, ¶ms), want); + } +} + +// A deeper second pass re-scores a superset of candidates, and the k best exact +// scores of a superset are never worse -- so each query's summed top-k score is +// non-decreasing in the depth. (Recall itself can only tie-break differently.) +TEST(DiskSeismicSQIndex, DeeperRescoreNeverLowersTheResult) { + const CSR corpus = make_corpus(1500, /*seed=*/17); + const CSR queries = make_corpus(30, /*seed=*/18); + TempIndexFile file("nsparse_dssq_rescore_monotone.idx"); + std::unique_ptr mapped = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(mapped, nullptr); + std::vector previous(queries.n, -1.0); + for (const int depth : {10, 20, 50, 200, 100000}) { + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/kAllBlocks, + depth); + const ScoreIds got = search_all(*mapped, queries, 10, ¶ms); + for (idx_t q = 0; q < queries.n; ++q) { + double sum = 0.0; + for (const float score : got.first[q]) { + sum += score > 0.0F ? score : 0.0F; + } + EXPECT_GE(sum, previous[q] - 1e-4) + << "depth " << depth << " lowered query " << q; + previous[q] = sum; + } + } +} + +// A negative depth is a caller bug, rejected on any disk index whether or not it +// would have been used, like a non-positive k_prime. +TEST(DiskSeismicSQIndex, RejectsNegativeRescore) { + const CSR corpus = make_corpus(600, /*seed=*/19); + const CSR queries = make_corpus(5, /*seed=*/20); + for (const uint32_t limit : {0U, 4U}) { + TempIndexFile file("nsparse_dssq_rescore_negative.idx"); + std::unique_ptr mapped = mapped_sq(corpus, limit, file); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/-1); + EXPECT_THROW(search_all(*mapped, queries, 10, ¶ms), + std::invalid_argument) + << "inline_max_nnz " << limit; + // The exact-match path never reads the depth, but still rejects it. + const std::vector members = {1, 2, 3}; + SetIDSelector selector(members.size(), members.data()); + params.set_id_selector(&selector); + EXPECT_THROW(search_all(*mapped, queries, 10, ¶ms), + std::invalid_argument) + << "inline_max_nnz " << limit << " with a <= k selector"; + } +} + +// A malformed limit must fail the build spec, not quietly become "no +// truncation" -- std::stoul alone would wrap "-1" to ULONG_MAX. +TEST(DiskSeismicSQIndex, FactoryRejectsABadInlineMaxNnz) { + const std::string base = + "disk_seismic_sq,quantizer=8bit|vmin=0.0|vmax=1.0|lambda=32|beta=8|" + "inline_max_nnz="; + for (const char* bad : + {"-1", "4294967296", "abc", "", "1e3", "0x40", "64abc", "64.9"}) { + EXPECT_THROW(std::unique_ptr( + index_factory(kDim, (base + bad).c_str())), + std::exception) + << "inline_max_nnz=" << bad; + } + EXPECT_NE(std::unique_ptr(index_factory(kDim, (base + "0").c_str())), + nullptr); + EXPECT_NE(std::unique_ptr( + index_factory(kDim, (base + "4294967295").c_str())), + nullptr); +} + +// A depth far past the candidate pool means "re-score everything": the same +// result as any other depth past the pool, without sizing the heap by it. +TEST(DiskSeismicSQIndex, RescoreDepthPastThePoolReScoresAll) { + const CSR corpus = make_corpus(1200, /*seed=*/21); + const CSR queries = make_corpus(30, /*seed=*/22); + TempIndexFile file("nsparse_dssq_rescore_huge.idx"); + std::unique_ptr mapped = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters pool(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/100000); + DiskSeismicSearchParameters huge(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/INT32_MAX); + expect_same_results(search_all(*mapped, queries, 10, &huge), + search_all(*mapped, queries, 10, &pool)); +} + +// rescore=kAutoRescoreDepth is the depth resolve_rescore_depth names, at both a +// small k (the floor) and a large one (the per-k multiple). +TEST(DiskSeismicSQIndex, AutoRescoreRunsAtItsResolvedDepth) { + const CSR corpus = make_corpus(1500, /*seed=*/23); + const CSR queries = make_corpus(20, /*seed=*/24); + TempIndexFile file("nsparse_dssq_rescore_auto.idx"); + std::unique_ptr mapped = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(mapped, nullptr); + for (const int k : {10, 100}) { + DiskSeismicSearchParameters automatic(/*cut=*/10, + /*k_prime=*/kAllBlocks); + DiskSeismicSearchParameters explicit_depth( + /*cut=*/10, /*k_prime=*/kAllBlocks, + detail::resolve_rescore_depth(kAutoRescoreDepth, k)); + expect_same_results(search_all(*mapped, queries, k, &automatic), + search_all(*mapped, queries, k, &explicit_depth)); + } +} + +// The per-thread re-scoring scratch has to stay per thread: a batch spanning +// many OpenMP chunks must return what one-query-at-a-time searches do. +TEST(DiskSeismicSQIndex, TruncatedBatchMatchesOneQueryAtATime) { + const CSR corpus = make_corpus(1500, /*seed=*/25); + const CSR queries = make_corpus(400, /*seed=*/26); + TempIndexFile file("nsparse_dssq_rescore_batch.idx"); + std::unique_ptr mapped = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/50); + const ScoreIds batch = search_all(*mapped, queries, 10, ¶ms); + for (idx_t q = 0; q < queries.n; ++q) { + CSR one; + one.n = 1; + one.indptr = {0, queries.indptr[q + 1] - queries.indptr[q]}; + one.indices.assign(queries.indices.begin() + queries.indptr[q], + queries.indices.begin() + queries.indptr[q + 1]); + one.values.assign(queries.values.begin() + queries.indptr[q], + queries.values.begin() + queries.indptr[q + 1]); + const ScoreIds single = search_all(*mapped, one, 10, ¶ms); + ASSERT_EQ(single.second[0], batch.second[q]) << "query " << q; + ASSERT_EQ(single.first[0], batch.first[q]) << "query " << q; + } +} + +// Where write_doc_directory put the locator table, in a file with no remainder +// docs: such a file ends [u64 n][DocLocator x n][u64 0 = empty remainder]. +size_t locator_table_offset(const std::vector& bytes, size_t n_docs) { + const size_t table_bytes = n_docs * sizeof(detail::DocLocator); + EXPECT_GE(bytes.size(), table_bytes + 2 * sizeof(uint64_t)); + uint64_t remainder_rows = 1; + std::memcpy(&remainder_rows, bytes.data() + bytes.size() - sizeof(uint64_t), + sizeof(uint64_t)); + EXPECT_EQ(remainder_rows, 0U) << "fixture must have no remainder docs"; + const size_t table = bytes.size() - sizeof(uint64_t) - table_bytes; + uint64_t count = 0; + std::memcpy(&count, bytes.data() + table - sizeof(uint64_t), + sizeof(uint64_t)); + EXPECT_EQ(count, n_docs); + return table; +} + +std::vector read_file(const char* path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), + std::istreambuf_iterator()}; +} + +void write_file(const char* path, const std::vector& bytes) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + out.write(bytes.data(), static_cast(bytes.size())); +} + +// A locator outside the directory is caught when a truncated index loads, not +// by the first query that happens to re-score that doc. +TEST(DiskSeismicSQIndex, ReadRejectsALocatorOutsideItsBlock) { + const CSR corpus = make_corpus(600, /*seed=*/27); + TempIndexFile file("nsparse_dssq_corrupt_locator.idx"); + ASSERT_NE(mapped_sq(corpus, /*limit=*/4, file), nullptr); + const std::vector clean = read_file(file.c_str()); + const size_t table = locator_table_offset(clean, corpus.n); + detail::DocLocator first{}; + std::memcpy(&first, clean.data() + table, sizeof(first)); + ASSERT_NE(first.posting_list, detail::DocLocator::kRemainder); + + detail::DocLocator past_its_block = first; + past_its_block.slot = 1'000'000; + detail::DocLocator past_its_list = first; + past_its_list.block = 1'000'000; + // The fixture has no remainder rows, so even row 0 is out of range. + const detail::DocLocator past_the_remainder{detail::DocLocator::kRemainder, + 0, 0}; + for (const detail::DocLocator& corrupt : + {past_its_block, past_its_list, past_the_remainder}) { + std::vector bytes = clean; + std::memcpy(bytes.data() + table, &corrupt, sizeof(corrupt)); + write_file(file.c_str(), bytes); + expect_mmap_read_rejected(file.c_str(), "locator"); + } +} + +// An untruncated index skips that load-time scan: only the <= k exact path +// reads its locators, and it checks each one it uses -- so the same corruption +// fails that search instead, and leaves block search alone. +TEST(DiskSeismicSQIndex, UntruncatedIndexReportsACorruptLocatorWhenUsed) { + const CSR corpus = make_corpus(600, /*seed=*/27); + const CSR queries = make_corpus(5, /*seed=*/31); + TempIndexFile file("nsparse_dssq_corrupt_locator_whole.idx"); + ASSERT_NE(mapped_sq(corpus, /*limit=*/0, file), nullptr); + std::vector bytes = read_file(file.c_str()); + const size_t table = locator_table_offset(bytes, corpus.n); + detail::DocLocator locator{}; + std::memcpy(&locator, bytes.data() + table, sizeof(locator)); + ASSERT_NE(locator.posting_list, detail::DocLocator::kRemainder); + locator.slot = 1'000'000; + std::memcpy(bytes.data() + table, &locator, sizeof(locator)); + write_file(file.c_str(), bytes); + + std::unique_ptr mapped( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(mapped, nullptr); + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/32); + EXPECT_NO_THROW(search_all(*mapped, queries, 10, ¶ms)); + const idx_t doc = 0; // the locator corrupted above + SetIDSelector selector(1, &doc); + params.set_id_selector(&selector); + EXPECT_THROW(search_all(*mapped, queries, 10, ¶ms), std::runtime_error); +} + +// A locator naming another doc's slot passes the load-time range check, so the +// re-scoring pass is what catches it -- and that error has to reach the caller +// as an exception, not abort the process from inside the OpenMP region. +TEST(DiskSeismicSQIndex, SearchReportsALocatorNamingAnotherDoc) { + const CSR corpus = make_corpus(600, /*seed=*/28); + TempIndexFile file("nsparse_dssq_swapped_locator.idx"); + ASSERT_NE(mapped_sq(corpus, /*limit=*/4, file), nullptr); + std::vector bytes = read_file(file.c_str()); + const size_t table = locator_table_offset(bytes, corpus.n); + std::vector locators(corpus.n); + std::memcpy(locators.data(), bytes.data() + table, + locators.size() * sizeof(detail::DocLocator)); + // Two docs whose whole copies share a block: point the second at the + // first's slot. + idx_t victim = -1; + for (idx_t a = 0; a < corpus.n && victim < 0; ++a) { + for (idx_t b = a + 1; b < corpus.n; ++b) { + if (locators[a].posting_list != detail::DocLocator::kRemainder && + locators[a].posting_list == locators[b].posting_list && + locators[a].block == locators[b].block) { + locators[b].slot = locators[a].slot; + victim = b; + break; + } + } + } + ASSERT_GE(victim, 0); + std::memcpy(bytes.data() + table, locators.data(), + locators.size() * sizeof(detail::DocLocator)); + write_file(file.c_str(), bytes); + std::unique_ptr mapped( + read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(mapped, nullptr); + + // The victim's own vector as the query, many times over so the batch spans + // threads, with every block and every candidate re-scored. + CSR queries; + queries.indptr.push_back(0); + const offset_t start = corpus.indptr[victim]; + const offset_t end = corpus.indptr[victim + 1]; + for (queries.n = 0; queries.n < 200; ++queries.n) { + queries.indices.insert(queries.indices.end(), + corpus.indices.begin() + start, + corpus.indices.begin() + end); + queries.values.insert(queries.values.end(), + corpus.values.begin() + start, + corpus.values.begin() + end); + queries.indptr.push_back(static_cast(queries.indices.size())); + } + DiskSeismicSearchParameters params(/*cut=*/10, /*k_prime=*/kAllBlocks, + /*rescore=*/INT32_MAX); + EXPECT_THROW(search_all(*mapped, queries, 10, ¶ms), std::runtime_error); + + // The <= k exact path a filtered query takes resolves through the same + // table, in an OpenMP region of its own. + SetIDSelector selector(1, &victim); + DiskSeismicSearchParameters exact(/*cut=*/10, /*k_prime=*/kAllBlocks); + exact.set_id_selector(&selector); + EXPECT_THROW(search_all(*mapped, queries, 10, &exact), std::runtime_error); +} + +// Nothing truncated is the v1 layout, so it is stamped 1 and builds from before +// truncation still read it. A truncated file must never be: a v1 reader would +// score its partial copies as if whole. +TEST(DiskSeismicSQIndex, StampsVersionOneUnlessTruncated) { + const CSR corpus = make_corpus(600, /*seed=*/32); + TempIndexFile whole("nsparse_dssq_stamp_whole.idx"); + ASSERT_NE(mapped_sq(corpus, /*limit=*/0, whole), nullptr); + EXPECT_EQ(file_format_version(whole.c_str()), 1U); + TempIndexFile cut("nsparse_dssq_stamp_cut.idx"); + ASSERT_NE(mapped_sq(corpus, /*limit=*/4, cut), nullptr); + EXPECT_EQ(file_format_version(cut.c_str()), + DiskSeismicScalarQuantizedIndex::kFormatVersion); +} + +// A format-version-1 file has no max_doc_nnz; the bytes it sits in were +// padding, so a v1 reader must not take them as a limit. A truncated file +// relabelled v1 puts a limit there: read as v1 it is scored as if whole, so the +// re-scoring depth has nothing to change. +TEST(DiskSeismicSQIndex, ReadsAFormatVersionOneFile) { + const CSR corpus = make_corpus(800, /*seed=*/29); + const CSR queries = make_corpus(20, /*seed=*/30); + TempIndexFile file("nsparse_dssq_v1.idx"); + DiskSeismicSearchParameters shallow(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/10); + DiskSeismicSearchParameters deep(/*cut=*/10, /*k_prime=*/32, + /*rescore=*/INT32_MAX); + { + // Read as written, the depth does change results, so the check below + // can see a v1 reader that honors the limit. + std::unique_ptr v2 = mapped_sq(corpus, /*limit=*/4, file); + ASSERT_NE(v2, nullptr); + ASSERT_NE(search_all(*v2, queries, 10, &shallow), + search_all(*v2, queries, 10, &deep)); + } + ASSERT_EQ(file_format_version(file.c_str()), + DiskSeismicScalarQuantizedIndex::kFormatVersion); + set_file_format_version(file.c_str(), 1); + std::unique_ptr v1(read_index(file.c_str(), IndexIoFlag::kUseMmap)); + ASSERT_NE(v1, nullptr); + expect_same_results(search_all(*v1, queries, 10, &shallow), + search_all(*v1, queries, 10, &deep)); +} + } // namespace nsparse diff --git a/tests/disk_seismic_test_util.h b/tests/disk_seismic_test_util.h index 7eb2d34..f78a546 100644 --- a/tests/disk_seismic_test_util.h +++ b/tests/disk_seismic_test_util.h @@ -14,6 +14,8 @@ #include #include +#include +#include #include #include #include @@ -133,6 +135,22 @@ class TempIndexFile { std::string path_str_ = path_.string(); }; +// The format version a file's IndexHeader records, right after its type id. +inline uint32_t file_format_version(const char* path) { + std::ifstream in(path, std::ios::binary); + in.seekg(static_cast(sizeof(uint32_t))); + uint32_t version = 0; + in.read(reinterpret_cast(&version), sizeof(version)); + return version; +} + +// Relabels a file in place, as if another version had written it. +inline void set_file_format_version(const char* path, uint32_t version) { + std::fstream out(path, std::ios::binary | std::ios::in | std::ios::out); + out.seekp(static_cast(sizeof(uint32_t))); + out.write(reinterpret_cast(&version), sizeof(version)); +} + using ScoreIds = std::pair>, std::vector>>; @@ -168,6 +186,45 @@ inline void expect_all_members_returned(const ScoreIds& got, } } +// Same ranking, allowing docs with equal scores to come back in either order. +// Quantized dot products are small integers, so ties at the k-th place are +// routine and which tied doc lands inside k is not part of what a format change +// promises. Scores must still match rank for rank; within each run of equal +// scores the label sets must match, except the last run, which k may have cut +// through -- there only the count is comparable. +inline void expect_same_ranking_modulo_ties(const ScoreIds& a, + const ScoreIds& b) { + ASSERT_EQ(a.second.size(), b.second.size()); + for (size_t q = 0; q < a.second.size(); ++q) { + ASSERT_EQ(a.first[q].size(), b.first[q].size()); + for (size_t j = 0; j < a.first[q].size(); ++j) { + EXPECT_FLOAT_EQ(a.first[q][j], b.first[q][j]) + << "score differs at query " << q << " rank " << j; + } + size_t run_start = 0; + for (size_t j = 1; j <= a.first[q].size(); ++j) { + const bool run_ends = + j == a.first[q].size() || a.first[q][j] != a.first[q][run_start]; + if (!run_ends) { + continue; + } + const std::multiset got(a.second[q].begin() + run_start, + a.second[q].begin() + j); + const std::multiset want(b.second[q].begin() + run_start, + b.second[q].begin() + j); + if (j == a.first[q].size()) { + EXPECT_EQ(got.size(), want.size()) + << "trailing tie run differs in size at query " << q; + } else { + EXPECT_EQ(got, want) + << "tie run at query " << q << " rank " << run_start + << " holds different docs"; + } + run_start = j; + } + } +} + inline void expect_same_results(const ScoreIds& a, const ScoreIds& b) { ASSERT_EQ(a.second.size(), b.second.size()); for (size_t q = 0; q < a.second.size(); ++q) { diff --git a/tests/inline_forward_index_test.cpp b/tests/inline_forward_index_test.cpp index b5f8526..d40a585 100644 --- a/tests/inline_forward_index_test.cpp +++ b/tests/inline_forward_index_test.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -682,3 +683,388 @@ TEST(InlineForwardIndex, NullArgumentsRejected) { InlineForwardIndex reader; EXPECT_THROW(reader.mmap_deserialize(nullptr), std::invalid_argument); } + +// --- Truncated extra copies (header max_doc_nnz) --- + +// A doc in two blocks, truncated to its largest few components everywhere but +// the one block its locator names -- which is what lets a re-scoring reader +// recover the whole vector. +TEST(InlineForwardIndex, KeepsOneWholeCopyAndTruncatesTheRest) { + constexpr uint32_t kKeep = 2; + // Doc 0 has 5 components with distinct values, so "the largest 2" is + // unambiguous: components 3 and 4 (values 0.9 and 0.8). + auto vectors = create_float_vectors( + {{0, 1, 2, 3, 4}, {1, 2}}, + {{0.1F, 0.2F, 0.3F, 0.9F, 0.8F}, {0.5F, 0.6F}}, 10); + // Two posting lists, each with one block, both holding doc 0. + auto lists = build_lists({{{0, 1}}, {{0}}}, vectors); + // Doc 0's whole copy goes to list 0 block 0 slot 0, doc 1's to the same + // block at slot 1. + const std::vector full_copies = {{0, 0, 0}, + {0, 0, 1}}; + + InlineForwardIndex writer(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, kKeep, &full_copies); + nsparse::BufferedIOWriter buffer; + writer.serialize(&buffer); + const std::vector bin = buffer.data(); + EXPECT_EQ(parse_header(bin).max_doc_nnz, kKeep); + + auto index = read_index(bin); + EXPECT_EQ(index.max_doc_nnz(), kKeep); + + // The named block keeps doc 0 whole. + const BlockView whole = index.block(0, 0); + ASSERT_FALSE(whole.absent()); + ASSERT_EQ(whole.n_docs, 2U); + EXPECT_EQ(whole.nnz(0), 5U); + const std::vector all_comps(whole.doc_comps(0), + whole.doc_comps(0) + 5); + EXPECT_EQ(all_comps, (std::vector{0, 1, 2, 3, 4})); + // Doc 1 is shorter than the limit, so it is whole wherever it appears. + EXPECT_EQ(whole.nnz(1), 2U); + + // The other copy keeps only the two largest, still in ascending component + // order so the block stays readable as a CSR row. + const BlockView cut = index.block(1, 0); + ASSERT_FALSE(cut.absent()); + ASSERT_EQ(cut.n_docs, 1U); + ASSERT_EQ(cut.nnz(0), kKeep); + const std::vector kept(cut.doc_comps(0), + cut.doc_comps(0) + kKeep); + EXPECT_EQ(kept, (std::vector{3, 4})); + const auto* kept_vals = + reinterpret_cast(cut.doc_vals(0, nsparse::U32)); + EXPECT_FLOAT_EQ(kept_vals[0], 0.9F); + EXPECT_FLOAT_EQ(kept_vals[1], 0.8F); +} + +// Ties at the cut are taken in stored order, so exactly max_doc_nnz components +// survive rather than every component that equals the boundary value. +TEST(InlineForwardIndex, TruncationKeepsExactlyTheLimitAcrossTies) { + constexpr uint32_t kKeep = 3; + // All five values equal: every component is a tie at the boundary. + auto vectors = create_uint8_vectors({{0, 1, 2, 3, 4}, {7}}, + {{5, 5, 5, 5, 5}, {9}}, 10); + auto lists = build_lists({{{0}}, {{0, 1}}}, vectors); + // Doc 0's whole copy is in list 1, so list 0's copy is the truncated one. + const std::vector full_copies = {{1, 0, 0}, + {1, 0, 1}}; + InlineForwardIndex writer(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, kKeep, &full_copies); + nsparse::BufferedIOWriter buffer; + writer.serialize(&buffer); + const std::vector bin = buffer.data(); + auto index = read_index(bin); + + const BlockView cut = index.block(0, 0); + ASSERT_FALSE(cut.absent()); + ASSERT_EQ(cut.nnz(0), kKeep); + const std::vector kept(cut.doc_comps(0), + cut.doc_comps(0) + kKeep); + EXPECT_EQ(kept, (std::vector{0, 1, 2})); + EXPECT_EQ(index.block(1, 0).nnz(0), 5U); // the whole copy +} + +// Truncating shrinks the section; the default writes nothing truncated. +TEST(InlineForwardIndex, TruncationShrinksTheSectionAndDefaultsOff) { + auto vectors = create_float_vectors( + {{0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4, 5}}, + {{0.1F, 0.2F, 0.3F, 0.4F, 0.5F, 0.6F}, + {0.6F, 0.5F, 0.4F, 0.3F, 0.2F, 0.1F}}, + 10); + auto lists = build_lists({{{0, 1}}, {{0, 1}}}, vectors); + const std::vector full_copies = {{0, 0, 0}, + {0, 0, 1}}; + + const auto whole = + serialize_bytes(lists, vectors, InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked); + EXPECT_EQ(parse_header(whole).max_doc_nnz, 0U); + EXPECT_EQ(read_index(whole).max_doc_nnz(), 0U); + + InlineForwardIndex writer(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, /*max_doc_nnz=*/2, + &full_copies); + nsparse::BufferedIOWriter buffer; + writer.serialize(&buffer); + EXPECT_LT(buffer.data().size(), whole.size()); +} + +// The two truncation arguments are meaningless apart, so neither is accepted +// alone, and a locator table has to cover every vector. +TEST(InlineForwardIndex, RejectsInconsistentTruncationArguments) { + auto vectors = sample_float_vectors(); + auto lists = build_lists(kLayout, vectors); + const std::vector full_copies( + vectors.num_vectors(), {0, 0, 0}); + const std::vector too_short(1, {0, 0, 0}); + + EXPECT_THROW(InlineForwardIndex(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, /*max_doc_nnz=*/2, + nullptr), + std::invalid_argument); + EXPECT_THROW(InlineForwardIndex(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, /*max_doc_nnz=*/0, + &full_copies), + std::invalid_argument); + EXPECT_THROW(InlineForwardIndex(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, /*max_doc_nnz=*/2, + &too_short), + std::invalid_argument); +} + +// --- Whole-copy resolution (resolve_doc / resolve_docs / doc_slice) --- + +// The locator table the index writer builds: each doc's first occurrence in +// (pl, block, slot) order, which is the copy a truncating writer keeps whole. +std::vector first_occurrence_locators( + const std::vector>>& layout, + size_t num_docs) { + using nsparse::detail::DocLocator; + std::vector locators(num_docs, + {DocLocator::kRemainder, 0, 0}); + std::vector seen(num_docs, false); + for (size_t pl = 0; pl < layout.size(); ++pl) { + for (size_t block = 0; block < layout[pl].size(); ++block) { + for (size_t slot = 0; slot < layout[pl][block].size(); ++slot) { + const auto doc = static_cast(layout[pl][block][slot]); + if (!seen[doc]) { + seen[doc] = true; + locators[doc] = {static_cast(pl), + static_cast(block), + static_cast(slot)}; + } + } + } + } + return locators; +} + +// 40 docs of 6 components each, every doc in three blocks, truncated to 2 -- +// enough docs to cross resolve_docs' internal chunk boundary several times. +struct TruncatedFixture { + static constexpr size_t kDocs = 40; + static constexpr uint32_t kKeep = 2; + nsparse::SparseVectors vectors; + std::vector>> layout; + std::vector locators; + std::vector bin; + + TruncatedFixture() + : vectors(nsparse::SparseVectors( + {.element_size = nsparse::U32, .dimension = 64})) { + for (size_t doc = 0; doc < kDocs; ++doc) { + std::vector comps; + std::vector vals; + for (nsparse::term_t c = 0; c < 6; ++c) { + comps.push_back(static_cast(doc % 8 + c * 9)); + vals.push_back(0.1F * static_cast(c + 1) + + 0.001F * static_cast(doc)); + } + vectors.add_vector(comps.data(), comps.size(), + reinterpret_cast(vals.data()), + vals.size() * sizeof(float)); + } + // Three lists; list p puts doc d in block (d + p) % 5. + for (size_t pl = 0; pl < 3; ++pl) { + std::vector> blocks(5); + for (size_t doc = 0; doc < kDocs; ++doc) { + blocks[(doc + pl) % 5].push_back( + static_cast(doc)); + } + layout.push_back(std::move(blocks)); + } + locators = first_occurrence_locators(layout, kDocs); + auto lists = build_lists(layout, vectors); + InlineForwardIndex writer(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, kKeep, &locators); + nsparse::BufferedIOWriter buffer; + writer.serialize(&buffer); + bin = buffer.data(); + } +}; + +TEST(InlineForwardIndex, ResolveDocReturnsTheWholeCopy) { + TruncatedFixture fx; + auto index = read_index(fx.bin); + const nsparse::detail::FullVectorStore store{ + .fwd = &index, + .locators = fx.locators.data(), + .num_locators = fx.locators.size(), + .remainder = nullptr}; + const auto* indptr = fx.vectors.indptr_data(); + for (size_t doc = 0; doc < TruncatedFixture::kDocs; ++doc) { + const nsparse::detail::DocSlice slice = nsparse::detail::resolve_doc( + store, static_cast(doc), nsparse::U32); + const auto start = indptr[doc]; + ASSERT_EQ(slice.nnz, static_cast(indptr[doc + 1] - start)) + << "doc " << doc << " resolved to a truncated copy"; + EXPECT_EQ(0, std::memcmp(slice.comps, fx.vectors.indices_data() + start, + slice.nnz * sizeof(nsparse::term_t))); + EXPECT_EQ(0, std::memcmp(slice.vals, + fx.vectors.values_data() + + static_cast(start) * sizeof(float), + slice.nnz * sizeof(float))); + } +} + +// The batched walk is an optimization of resolve_doc and must agree with it +// exactly -- same slices, in the caller's order, duplicates included -- across +// more docs than one internal chunk. +TEST(InlineForwardIndex, ResolveDocsMatchesResolveDocOneByOne) { + TruncatedFixture fx; + auto index = read_index(fx.bin); + const nsparse::detail::FullVectorStore store{ + .fwd = &index, + .locators = fx.locators.data(), + .num_locators = fx.locators.size(), + .remainder = nullptr}; + std::vector ids; + for (size_t i = 0; i < 3 * TruncatedFixture::kDocs; ++i) { + ids.push_back(static_cast((i * 17) % + TruncatedFixture::kDocs)); + } + nsparse::detail::DocResolveScratch scratch; + std::vector slices; + nsparse::detail::resolve_docs(store, ids.data(), ids.size(), nsparse::U32, + &scratch, &slices); + ASSERT_EQ(slices.size(), ids.size()); + for (size_t i = 0; i < ids.size(); ++i) { + const auto one = nsparse::detail::resolve_doc(store, ids[i], + nsparse::U32); + EXPECT_EQ(slices[i].comps, one.comps) << "position " << i; + EXPECT_EQ(slices[i].vals, one.vals) << "position " << i; + EXPECT_EQ(slices[i].nnz, one.nnz) << "position " << i; + } + + // Reusing the scratch for a shorter batch must not leave stale entries. + nsparse::detail::resolve_docs(store, ids.data(), 3, nsparse::U32, &scratch, + &slices); + EXPECT_EQ(slices.size(), 3U); + nsparse::detail::resolve_docs(store, ids.data(), 0, nsparse::U32, &scratch, + &slices); + EXPECT_TRUE(slices.empty()); +} + +TEST(InlineForwardIndex, ResolveRejectsDocsOutsideTheDirectory) { + TruncatedFixture fx; + auto index = read_index(fx.bin); + const nsparse::detail::FullVectorStore store{ + .fwd = &index, + .locators = fx.locators.data(), + .num_locators = fx.locators.size(), + .remainder = nullptr}; + const auto past_end = static_cast(TruncatedFixture::kDocs); + EXPECT_THROW(nsparse::detail::resolve_doc(store, past_end, nsparse::U32), + std::out_of_range); + EXPECT_THROW(nsparse::detail::resolve_doc(store, -1, nsparse::U32), + std::out_of_range); + + const std::vector ids = {0, 1, past_end}; + nsparse::detail::DocResolveScratch scratch; + std::vector slices; + EXPECT_THROW(nsparse::detail::resolve_docs(store, ids.data(), ids.size(), + nsparse::U32, &scratch, &slices), + std::out_of_range); +} + +// A locator naming a slot its block does not have is a corrupt directory; both +// resolve paths must refuse it rather than read past the block. +TEST(InlineForwardIndex, ResolveRejectsALocatorPastItsBlock) { + TruncatedFixture fx; + auto index = read_index(fx.bin); + std::vector corrupt = fx.locators; + corrupt[0].slot = 1000; + const nsparse::detail::FullVectorStore store{ + .fwd = &index, + .locators = corrupt.data(), + .num_locators = corrupt.size(), + .remainder = nullptr}; + EXPECT_THROW(nsparse::detail::resolve_doc(store, 0, nsparse::U32), + std::runtime_error); + const std::vector ids = {0}; + nsparse::detail::DocResolveScratch scratch; + std::vector slices; + EXPECT_THROW(nsparse::detail::resolve_docs(store, ids.data(), ids.size(), + nsparse::U32, &scratch, &slices), + std::runtime_error); + + const nsparse::detail::InlineDirEntry* entry = index.dir_entry(0, 0); + ASSERT_NE(entry, nullptr); + EXPECT_THROW(index.doc_slice(*entry, entry->n_docs, 0), std::runtime_error); + EXPECT_EQ(index.dir_entry(0, 99), nullptr); + EXPECT_EQ(index.dir_entry(99, 0), nullptr); +} + +// A locator naming another doc's valid slot is just as corrupt: both resolve +// paths must refuse it rather than re-score that doc's vector under this id. +TEST(InlineForwardIndex, ResolveRejectsALocatorNamingAnotherDoc) { + TruncatedFixture fx; + auto index = read_index(fx.bin); + std::vector corrupt = fx.locators; + // Docs 0 and 5 share list 0's block 0; point doc 5 at doc 0's slot. + ASSERT_EQ(corrupt[5].posting_list, corrupt[0].posting_list); + ASSERT_EQ(corrupt[5].block, corrupt[0].block); + corrupt[5].slot = corrupt[0].slot; + const nsparse::detail::FullVectorStore store{.fwd = &index, + .locators = corrupt.data(), + .num_locators = corrupt.size(), + .remainder = nullptr}; + EXPECT_THROW(nsparse::detail::resolve_doc(store, 5, nsparse::U32), + std::runtime_error); + const std::vector ids = {0, 5}; + nsparse::detail::DocResolveScratch scratch; + std::vector slices; + EXPECT_THROW(nsparse::detail::resolve_docs(store, ids.data(), ids.size(), + nsparse::U32, &scratch, &slices), + std::runtime_error); +} + +// A NaN weight must not break the selection's ordering: the truncating write +// still produces a loadable section, and the NaN is the component it drops. +TEST(InlineForwardIndex, TruncationDropsANaNWeightFirst) { + constexpr uint32_t kKeep = 3; + auto vectors = create_float_vectors({{0, 1, 2, 3, 4}}, + {{0.4F, NAN, 0.2F, 0.9F, 0.1F}}, 10); + auto lists = build_lists({{{0}}, {{0}}}, vectors); + const std::vector full_copies = {{0, 0, 0}}; + InlineForwardIndex writer(lists, vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, kKeep, &full_copies); + nsparse::BufferedIOWriter buffer; + ASSERT_NO_THROW(writer.serialize(&buffer)); + auto index = read_index(buffer.data()); + const BlockView cut = index.block(1, 0); + ASSERT_FALSE(cut.absent()); + ASSERT_EQ(cut.nnz(0), kKeep); + const std::vector kept(cut.doc_comps(0), + cut.doc_comps(0) + kKeep); + EXPECT_EQ(kept, (std::vector{0, 2, 3})); +} + +// A limit no multi-copy doc exceeds cuts nothing, so the section must be the +// untruncated one byte for byte -- max_doc_nnz 0 included, or every query would +// pay a second pass that cannot change anything. +TEST(InlineForwardIndex, ALimitNoCopyReachesWritesTheUntruncatedSection) { + TruncatedFixture fx; // 6 components per doc + auto lists = build_lists(fx.layout, fx.vectors); + const auto whole = + serialize_bytes(lists, fx.vectors, InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked); + for (const uint32_t limit : {6U, 7U, UINT32_MAX}) { + InlineForwardIndex writer(lists, fx.vectors, + InlineForwardIndex::kDefaultPageSize, + InlineLayout::kPacked, limit, &fx.locators); + nsparse::BufferedIOWriter buffer; + writer.serialize(&buffer); + EXPECT_EQ(buffer.data(), whole) << "limit " << limit; + } +}