Skip to content

feat: generate distribution-aware filtered datasets with exact ground truth - #903

Open
yejonz wants to merge 4 commits into
zilliztech:mainfrom
yejonz:filtered-dataset-v01
Open

yejonz wants to merge 4 commits into
zilliztech:mainfrom
yejonz:filtered-dataset-v01

Conversation

@yejonz

@yejonz yejonz commented Nov 11, 2026

Copy link
Copy Markdown

Fixes #881.

What changed

VectorDBBench's filtered cases come from fixed datasets whose labels are assigned independently of the vectors, at a few preset percentages. There was no way to build a filtered dataset with skewed metadata, or with metadata that follows the vectors (where the matching rows sit away from most queries), and still have exact ground truth for it.

This adds vectordb_bench/backend/filtered_dataset, a generator for those datasets. A spec sets:

  • the vectors: count, dimension, metric (L2, COSINE or IP) and seed
  • a labels column and an int_attr column, each uniform or Zipf, with a correlation setting from 0 (independent of the vectors) to 1 (follows vector position)
  • filter cases at target selectivities: label equality, or a half-open int range

It writes train, test and scalar_labels parquet in the custom-dataset layout, the unfiltered neighbors.parquet, one neighbors_<case>.parquet per case with the exact top-k over only the matching rows (ranked by distance, then id), and a manifest.json. For each case the manifest records the filter actually used, its actual selectivity and matching rows, short or empty ground truth, ties at the k-th neighbor, and how many queries have no unfiltered neighbor that passes the filter, next to the count expected if the metadata were independent of the vectors.

verify re-evaluates every filter from the written metadata and recomputes the neighbors with a separate exact search.

The base files load through CustomDataset as they are. Running the per-case filters is left to V02 (#882): the runner needs these filter types, and has to accept ground-truth rows shorter than K when fewer rows match. Sizes are capped at num_train * dim <= 50M.

Example

$ python -m vectordb_bench.backend.filtered_dataset generate --config spec.yaml --out ./fixture
00_label_equal_0.01          labels == "label_18"                     target 0.01    actual 0.0102  no unfiltered match: 286 queries (independent: 178.6)
01_label_equal_0.1           labels == "label_01"                     target 0.1     actual 0.1218  no unfiltered match: 73 queries (independent: 0.0)
02_int_range_0.05            int_attr >= 0 and int_attr < 1           target 0.05    actual 0.2289  no unfiltered match: 171 queries (independent: 0.0)
03_int_range_0.05            int_attr >= 221 and int_attr < 438       target 0.05    actual 0.0502  no unfiltered match: 292 queries (independent: 2.9)
Wrote ./fixture
$ python -m vectordb_bench.backend.filtered_dataset verify ./fixture
OK: 4 cases verified in ./fixture

This is 50,000 x 64 COSINE vectors and 500 queries, with Zipf metadata and correlation: 0.9 on both columns. With correlation: 0 the same spec gives 179 queries with no unfiltered match for the first case, against 178.6 expected, so the setting shows up where it should. Case 02 shows what happens on heavily tied integers: value 0 alone covers 23% of rows, so the closest non-empty range overshoots the 5% target, and the manifest records the actual 0.2289.

Verification

  • tests/test_filtered_dataset.py, 26 tests: ground truth against a full-sort reference with forced ties and with different chunk sizes; every neighbor passes its filter; the same seed gives identical files; short and empty results; the correlation setting; verify catching a tampered file and a wrong selectivity; loading through the custom-dataset reader; spec validation; the CLI.
  • make lint passes.
  • Default spec (100,000 x 128, 1,000 queries, 6 cases): about 15 s, and verify --sample 100 passes. At the size cap (390,000 x 128) generation peaked at 1.26 GB and took 52 s on an M-series MacBook.
  • verify also passes on COSINE and IP fixtures.

Not tested here

  • Running the generated cases against a database, which needs V02.
  • Windows (CI runs it; the code only uses numpy and pyarrow).

… truth

Adds vectordb_bench/backend/filtered_dataset, a generator for filtered-search
fixtures (Stanford catalog V01). A spec sets vector shape, metric, seed, label
and int metadata distributions (uniform or Zipf), how strongly the metadata
follows vector position, and target selectivities for label-equality and
int-range filters. It writes the custom-dataset layout (train, test,
scalar_labels, one neighbors file per case) plus a manifest with each case's
actual selectivity, matching rows, short or empty ground truth, boundary ties
and how often unfiltered neighbors already pass the filter. Ground truth is an
exact float64 top-k ranked by (distance, id). A verify command re-checks a
fixture against an independent exact reference.

issue: zilliztech#881
Signed-off-by: yejonz <yejonz@gmail.com>
Cap num_train * dim (50M elements, about 1.3 GB peak and below Arrow's int32
list offsets) and the int domain width. Say that only the base files load
through CustomDataset today and per-case ground truth needs V02. Qualify the
reproducibility claim and record numpy/pyarrow versions in the manifest.
Accept an empty --config with --seed, and reword --overwrite.

Signed-off-by: yejonz <yejonz@gmail.com>
…ately

Signed-off-by: yejonz <yejonz@gmail.com>
@sre-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: yejonz
To complete the pull request process, please assign xuanyang-cn after the PR has been reviewed.
You can assign the PR to them by writing /assign @xuanyang-cn in a comment when ready.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@yejonz

yejonz commented Nov 11, 2026

Copy link
Copy Markdown
Author

/assign @XuanYang-cn

@jamesgao-jpg

Copy link
Copy Markdown
Collaborator

Thanks for this contribution! Having reproducible filtered-search fixtures with controlled metadata skew and vector/metadata correlation will be useful. I have reviewed the implementation and am leaving a few comments below.

@jamesgao-jpg jamesgao-jpg left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran the 26 focused tests and reproduced the following edge cases with small local fixtures. Please take a look when you have a chance, thanks!

else:
start = int(case_spec.start_quantile * n)
low = int(sorted_int[start])
end = start + round(target * n)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Count from the first row tied at the lower bound. The filter includes all rows equal to low, but end starts at the quantile position, which can be in the middle of that tie. For 100 values consisting of 50 zeros, 10 ones and 40 twos, start_quantile=0.49 and target 0.6 select [0, 3) (100 rows), although [0, 2) matches exactly 60. Please determine the candidate upper bound from the first occurrence of low and compare the nearest non-empty bounds.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 5d4c8ab. The range now counts from the first row equal to low, so your example picks [0, 2) with 60 rows. Added test_int_range_counts_from_the_first_row_tied_at_the_lower_bound.

problems.append(f"{name}: query {qid} has {len(row)} neighbors, expected {expected_width}")
elif len(np.unique(row)) != len(row):
problems.append(f"{name}: query {qid} repeats a neighbor id")
elif len(row) and not mask[row].all():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Check neighbor ID bounds before indexing. NumPy treats negative IDs as offsets from the end, so the mask and distance checks can accept an invalid ID. I generated a one-training-row fixture, replaced its sole ground-truth ID 0 with -1, and verify_dataset() returned no problems. Please validate that every neighbor ID is in [0, len(train)) before indexing; out-of-range positive IDs should also be reported as verification failures.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5d4c8ab. Neighbor ids outside 0..len(train)-1 are now reported before any indexing, both negative and too-large ones. Added test_verify_reports_neighbor_ids_out_of_range.


def _neighbors(path: pathlib.Path) -> list[np.ndarray]:
table = pq.read_table(path)
return [np.asarray(row, dtype=np.int64) for row in table.column(NEIGHBORS_FIELD).to_pylist()]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate ground-truth query IDs against the test file. This reads only neighbors_id, so the verifier accepts ground truth whose id column does not identify the corresponding queries. I changed the first query ID to 9999: verify_dataset() returned no problems, while the existing ParquetGroundTruth.from_file() rejected that same file due to mismatched query IDs. Please check the IDs and their order for the unfiltered and each filtered ground-truth file.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5d4c8ab. Verify now checks the id column of the unfiltered and every per-case ground-truth file against the test ids, in order. Added test_verify_reports_query_ids_that_do_not_match_the_test_file.

# hard case for filtered ANN. Compare with the count expected if metadata ignored the vectors;
# a much larger count means the metadata is correlated with vector position.
"queries_with_no_unfiltered_match": int(np.count_nonzero(pass_rates == 0)),
"expected_queries_with_no_unfiltered_match_if_independent": spec.num_test

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Use the fixed-population independence baseline. The metadata assignment has a fixed observed number of matching rows and a query's top-k contains distinct rows, so the probability of no matching neighbor is sampling without replacement, not (1 - selectivity) ** k. With 10 rows, 5 matching rows, k=5 and 100 queries, this records 3.125 expected queries, while the exact value is 100 * C(5, 5) / C(10, 5) = 0.397. The discrepancy can mislead the correlation diagnostic on small fixtures. Please compute the hypergeometric probability using the observed matching count.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 5d4c8ab. The baseline now uses the hypergeometric probability with the observed matching count, so your example records 0.397. Added test_independence_baseline_samples_without_replacement.

…endence baseline

Count an int range from the first row tied at its lower bound, so a run of
ties at the start no longer pushes the upper bound past the closest match.
In verify, report neighbor ids outside 0..N-1 before indexing (NumPy reads
-1 as the last row) and check each ground-truth file's query ids against the
test file. Compute the expected queries with no unfiltered match by sampling
without replacement from the observed matching rows (hypergeometric) instead
of (1 - selectivity) ** k.

Signed-off-by: yejonz <yejonz@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement]: [Stanford V01] Generate distribution-aware filtered datasets and exact ground truth

3 participants