Repository navigation
Expand file tree
/
Copy pathdataset.py
More file actions
2105 lines (1807 loc) · 75.6 KB
/
Copy pathdataset.py
File metadata and controls
2105 lines (1807 loc) · 75.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Usage:
>>> from xxx.dataset import Dataset
>>> Dataset.Cohere.get(100_000)
"""
import fnmatch
import glob
import json
import logging
import math
import pathlib
import tempfile
import types
import typing
from abc import ABC, abstractmethod
from collections.abc import Iterator
from dataclasses import dataclass
from enum import Enum
from typing import Any, ClassVar, NamedTuple
import h5py
import ir_datasets
import numpy as np
import pandas as pd
import polars as pl
from pyarrow.parquet import ParquetFile
from pydantic import Field as PydanticField
from pydantic import PrivateAttr, field_validator
from vectordb_bench import config
from vectordb_bench.base import BaseModel
from . import utils
from .clients import MetricType
from .data_source import DatasetReader, DatasetSource
from .filter import Filter, FilterOp, NewIntFilter, non_filter
log = logging.getLogger(__name__)
DEFAULT_INSERT_BATCH_SIZE = config.DEFAULT_INSERT_BATCH_SIZE
class SizeLabel(NamedTuple):
size: int
label: str
file_count: int
class BaseDataset(BaseModel):
name: str
size: int
dim: int
metric_type: MetricType
use_shuffled: bool
with_gt: bool = False
_size_label: ClassVar[dict[int, SizeLabel]]
is_custom: bool = False
with_remote_resource: bool = True
# for label filter cases
with_scalar_labels: bool = False
# if True, scalar_labels will be retrieved from a separate parquet file;
# otherwise, they will be obtained from train.parquet.
scalar_labels_file_separated: bool = True
scalar_labels_file: str = "scalar_labels.parquet"
scalar_label_percentages: list[float] = []
scalar_int_rates: list[float] = []
train_id_field: str = "id"
train_vector_field: str = "emb"
test_file: str = "test.parquet"
test_id_field: str = "id"
test_vector_field: str = "emb"
gt_id_field: str = "id"
gt_neighbors_field: str = "neighbors_id"
source: DatasetSource | None = None
source_dataset: str | None = None
source_revision: str | None = None
dataset_metadata: dict[str, Any] | None = None
@field_validator("size")
@classmethod
def verify_size(cls, v: int):
if v not in cls._size_label:
msg = f"Size {v} not supported for the dataset, expected: {cls._size_label.keys()}"
raise ValueError(msg)
return v
@property
def label(self) -> str:
return self._size_label.get(self.size).label
@property
def full_name(self) -> str:
return f"{self.name.capitalize()} ({self.label.capitalize()})"
@property
def dir_name(self) -> str:
return f"{self.name}_{self.label}_{utils.numerize(self.size)}".lower()
@property
def file_count(self) -> int:
return self._size_label.get(self.size).file_count
@property
def train_files(self) -> list[str]:
return utils.compose_train_files(self.file_count, self.use_shuffled)
class CustomDataset(BaseDataset):
dir: str
file_num: int
is_custom: bool = True
with_remote_resource: bool = False
train_file: str = "train"
train_id_field: str = "id"
train_vector_field: str = "emb"
test_file: str = "test.parquet"
gt_file: str = "neighbors.parquet"
test_vector_field: str = "emb"
gt_neighbors_field: str = "neighbors_id"
with_scalar_labels: bool = True
scalar_labels_file_separated: bool = True
scalar_labels_file: str = "scalar_labels.parquet"
label_percentages: list[float] = []
@field_validator("size")
@classmethod
def verify_size(cls, v: int):
return v
@property
def label(self) -> str:
return "Custom"
@property
def dir_name(self) -> str:
return self.dir
@property
def file_count(self) -> int:
return self.file_num
@property
def train_files(self) -> list[str]:
if ("," not in self.train_file) and self.file_num > 1:
return utils.compose_train_files(self.file_num, self.use_shuffled)
train_file = self.train_file
prefix = f"{train_file}"
train_files = []
prefix_s = [item.strip() for item in prefix.split(",") if item.strip()]
for i in range(len(prefix_s)):
sub_file = f"{prefix_s[i]}.parquet"
train_files.append(sub_file)
return train_files
class ParquetDataset(BaseDataset):
"""Artifact roles and schema for a Parquet vector dataset."""
train_selectors: tuple[str, ...]
query_selectors: tuple[str, ...]
gt_selector: str
ground_truth_width: int
query_count: int | None = None
family: str | None = None
point_type: str | None = None
@field_validator("size")
@classmethod
def verify_size(cls, value: int) -> int:
if value <= 0:
msg = f"Dataset size must be positive, got {value}"
raise ValueError(msg)
return value
@property
def label(self) -> str:
return self.family or "Parquet"
@property
def full_name(self) -> str:
return self.name
@property
def dir_name(self) -> str:
return self.name
@property
def train_files(self) -> list[str]:
return list(self.train_selectors)
class LAION(BaseDataset):
name: str = "LAION"
dim: int = 768
metric_type: MetricType = MetricType.L2
use_shuffled: bool = False
with_gt: bool = True
with_scalar_labels: bool = True
scalar_label_percentages: list[float] = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]
_size_label: ClassVar[dict[int, SizeLabel]] = {
100_000_000: SizeLabel(100_000_000, "LARGE", 100),
}
@dataclass(frozen=True)
class SearchDatasetFiles:
test_file: str | tuple[str, ...]
gt_file: str
width: int | None = None
query_count: int | None = None
@property
def test_files(self) -> tuple[str, ...]:
if isinstance(self.test_file, str):
return (self.test_file,)
return self.test_file
LAION_SEARCH_DATASET_FILES = (
(1_000, SearchDatasetFiles("test.parquet", "neighbors.parquet", width=1_000, query_count=1_000)),
(
100_000,
SearchDatasetFiles(
"test_nq200.parquet",
"neighbors_top100k_nq200.parquet",
width=100_000,
query_count=200,
),
),
(
1_000_000,
SearchDatasetFiles(
"test_nq200.parquet",
"neighbors_top1m_nq200.parquet",
width=1_000_000,
query_count=200,
),
),
)
# Published widths are capped by the population left after applying each ID threshold.
LAION_INT_FILTER_SEARCH_WIDTHS: dict[float, tuple[int, ...]] = {
0.5: (100_000, 1_000_000),
0.6: (100_000, 1_000_000),
0.7: (100_000, 1_000_000),
0.8: (100_000, 1_000_000),
0.9: (100_000, 1_000_000),
0.95: (100_000, 1_000_000),
0.98: (100_000, 1_000_000),
0.99: (100_000, 1_000_000),
0.995: (100_000, 500_000),
0.998: (100_000, 200_000),
0.999: (100_000,),
}
@dataclass(frozen=True)
class ParquetGroundTruth:
path: pathlib.Path
neighbors_field: str
row_count: int
width: int
@classmethod
def from_file(
cls,
path: pathlib.Path,
*,
id_field: str,
neighbors_field: str,
expected_query_ids: typing.Sequence[Any],
minimum_width: int,
expected_width: int | None = None,
) -> "ParquetGroundTruth":
if not path.exists():
msg = f"No such file: {path}"
raise FileNotFoundError(msg)
parquet_file = ParquetFile(path, memory_map=True, pre_buffer=False)
schema_names = parquet_file.schema_arrow.names
missing_fields = [field for field in (id_field, neighbors_field) if field not in schema_names]
if missing_fields:
msg = f"Ground truth file {path} is missing fields: {missing_fields}"
raise ValueError(msg)
query_ids = parquet_file.read(columns=[id_field]).column(0).to_pylist()
if query_ids != list(expected_query_ids):
msg = f"Ground truth query IDs in {path} do not match the selected query file"
raise ValueError(msg)
row_count = parquet_file.metadata.num_rows
minimum_observed_width = None
observed_rows = 0
for batch in parquet_file.iter_batches(batch_size=1, columns=[neighbors_field]):
for row in batch.column(0):
if not row.is_valid:
msg = f"Ground truth file {path} contains a null neighbors row"
raise ValueError(msg)
width = len(row.values)
observed_rows += 1
minimum_observed_width = width if minimum_observed_width is None else min(minimum_observed_width, width)
if expected_width is not None and width != expected_width:
msg = f"Ground truth width {width} in {path} does not match expected width {expected_width}"
raise ValueError(msg)
if width < minimum_width:
msg = f"Ground truth width {width} in {path} is smaller than requested K={minimum_width}"
raise ValueError(msg)
if observed_rows != row_count or minimum_observed_width is None:
msg = f"Ground truth row count in {path} is invalid: expected {row_count}, read {observed_rows}"
raise ValueError(msg)
return cls(
path=path,
neighbors_field=neighbors_field,
row_count=row_count,
width=minimum_observed_width,
)
def __len__(self) -> int:
return self.row_count
def iter_rows(self) -> Iterator[Any]:
parquet_file = ParquetFile(self.path, memory_map=True, pre_buffer=False)
for batch in parquet_file.iter_batches(batch_size=1, columns=[self.neighbors_field]):
for row in batch.column(0):
yield row.values.to_numpy(zero_copy_only=False) # noqa: PD011
class GIST(BaseDataset):
name: str = "GIST"
dim: int = 960
metric_type: MetricType = MetricType.L2
use_shuffled: bool = False
_size_label: ClassVar[dict[int, SizeLabel]] = {
100_000: SizeLabel(100_000, "SMALL", 1),
1_000_000: SizeLabel(1_000_000, "MEDIUM", 1),
}
class Cohere(BaseDataset):
name: str = "Cohere"
dim: int = 768
metric_type: MetricType = MetricType.COSINE
use_shuffled: bool = config.USE_SHUFFLED_DATA
with_gt: bool = True
_size_label: ClassVar[dict[int, SizeLabel]] = {
100_000: SizeLabel(100_000, "SMALL", 1),
1_000_000: SizeLabel(1_000_000, "MEDIUM", 1),
10_000_000: SizeLabel(10_000_000, "LARGE", 10),
}
with_scalar_labels: bool = True
scalar_label_percentages: list[float] = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]
scalar_int_rates: list[float] = [
0.001,
0.002,
0.005,
0.01,
0.02,
0.05,
0.1,
0.2,
0.3,
0.4,
0.5,
0.6,
0.7,
0.8,
0.9,
0.95,
0.98,
0.99,
0.995,
0.998,
0.999,
]
class Bioasq(BaseDataset):
name: str = "Bioasq"
dim: int = 1024
metric_type: MetricType = MetricType.COSINE
use_shuffled: bool = config.USE_SHUFFLED_DATA
with_gt: bool = True
_size_label: ClassVar[dict[int, SizeLabel]] = {
1_000_000: SizeLabel(1_000_000, "MEDIUM", 1),
10_000_000: SizeLabel(10_000_000, "LARGE", 10),
}
with_scalar_labels: bool = True
scalar_label_percentages: list[float] = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]
scalar_int_rates: list[float] = [
0.001,
0.002,
0.005,
0.01,
0.02,
0.05,
0.1,
0.2,
0.3,
0.4,
0.5,
0.6,
0.7,
0.8,
0.9,
0.95,
0.98,
0.99,
0.995,
0.998,
0.999,
]
class Glove(BaseDataset):
name: str = "Glove"
dim: int = 200
metric_type: MetricType = MetricType.COSINE
use_shuffled: bool = False
_size_label: ClassVar[dict[int, SizeLabel]] = {1_000_000: SizeLabel(1_000_000, "MEDIUM", 1)}
class SIFT(BaseDataset):
name: str = "SIFT"
dim: int = 128
metric_type: MetricType = MetricType.L2
use_shuffled: bool = False
_size_label: ClassVar[dict[int, SizeLabel]] = {
500_000: SizeLabel(
500_000,
"SMALL",
1,
),
5_000_000: SizeLabel(5_000_000, "MEDIUM", 1),
# 50_000_000: SizeLabel(50_000_000, "LARGE", 50),
}
class OpenAI(BaseDataset):
name: str = "OpenAI"
dim: int = 1536
metric_type: MetricType = MetricType.COSINE
use_shuffled: bool = config.USE_SHUFFLED_DATA
with_gt: bool = True
_size_label: ClassVar[dict[int, SizeLabel]] = {
50_000: SizeLabel(50_000, "SMALL", 1),
500_000: SizeLabel(500_000, "MEDIUM", 1),
5_000_000: SizeLabel(5_000_000, "LARGE", 10),
}
with_scalar_labels: bool = True
scalar_label_percentages: list[float] = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]
scalar_int_rates: list[float] = [
0.001,
0.002,
0.005,
0.01,
0.02,
0.05,
0.1,
0.2,
0.3,
0.4,
0.5,
0.6,
0.7,
0.8,
0.9,
0.95,
0.98,
0.99,
0.995,
0.998,
0.999,
]
class DatasetManager(BaseModel, ABC):
"""Common in-memory contract consumed by vector benchmark runners."""
data: BaseDataset
load_timeout: float | int = config.LOAD_TIMEOUT_DEFAULT
optimize_timeout: float | int | None = config.OPTIMIZE_TIMEOUT_DEFAULT
test_data: list[list[float]] | None = None
gt_data: ParquetGroundTruth | list[list[int]] | None = None
search_files: SearchDatasetFiles | None = None
scalar_labels: pl.DataFrame | None = None
train_files: list[str] = []
reader: DatasetReader | None = None
resolved_files: dict[str, pathlib.Path] = {}
result_metadata: dict[str, Any] | None = None
def __eq__(self, obj: any):
if isinstance(obj, DatasetManager):
return self.data.name == obj.data.name and self.data.label == obj.data.label
return False
def __hash__(self) -> int:
return hash((self.data.name, self.data.label))
def set_reader(self, reader: DatasetReader):
self.reader = reader
@property
def preferred_source(self) -> DatasetSource | None:
return self.data.source
@property
def data_dir(self) -> pathlib.Path:
"""data local directory: config.DATASET_LOCAL_DIR/{dataset_name}/{dataset_dirname}
Examples:
>>> sift_s = Dataset.SIFT.manager(500_000)
>>> sift_s.relative_path
'/tmp/vectordb_bench/dataset/sift/sift_small_500k/'
"""
return pathlib.Path(
config.DATASET_LOCAL_DIR,
self.data.name.lower(),
self.data.dir_name,
)
def __iter__(self):
return self.iter_batches(DEFAULT_INSERT_BATCH_SIZE)
@abstractmethod
def iter_batches(self, batch_size: int):
"""Return insertion batches without materializing the whole corpus."""
@abstractmethod
def prepare(
self,
source: DatasetSource = DatasetSource.S3,
filters: Filter = non_filter,
with_train_files: bool = True,
with_scalar_labels: bool = False,
k: int | None = None,
) -> bool:
"""Resolve the source and load query and ground-truth data."""
def max_search_k(self, filters: Filter = non_filter) -> int | None:
return None
@abstractmethod
def resolve_search_files(self, *, k: int, filters: Filter = non_filter) -> SearchDatasetFiles:
"""Validate search inputs and describe the query and ground-truth data."""
def _local_path(self, file_name: str) -> pathlib.Path:
return self.resolved_files.get(file_name, pathlib.Path(self.data_dir, file_name))
class ParquetDatasetManager(DatasetManager):
"""Prepare and stream datasets stored as Parquet files."""
def iter_batches(self, batch_size: int):
return ParquetDatasetIterator(self, batch_size=batch_size)
# TODO passing use_shuffle from outside
def prepare(
self,
source: DatasetSource = DatasetSource.S3,
filters: Filter = non_filter,
with_train_files: bool = True,
with_scalar_labels: bool = False,
k: int | None = None,
) -> bool:
"""Download the dataset from DatasetSource
url = f"{source}/{self.data.dir_name}"
Args:
source(DatasetSource): S3 or AliyunOSS, default as S3
filters(Filter): combined with dataset's with_gt to
compose the correct ground_truth file
k(int | None): requested search depth used to select and validate ground truth
Returns:
bool: whether the dataset is successfully prepared
"""
requested_k = config.K_DEFAULT if k is None else k
train_selectors = self.data.train_files if with_train_files else []
gt_file = None
test_selectors = ()
if self.data.with_gt:
self.search_files = self.resolve_search_files(k=requested_k, filters=filters)
gt_file, test_selectors = self.search_files.gt_file, self.search_files.test_files
actual_source = self.preferred_source or source
if self.data.with_remote_resource:
download_files = [*train_selectors, *test_selectors]
if gt_file is not None:
download_files.append(gt_file)
if self.data.with_scalar_labels and self.data.scalar_labels_file_separated:
download_files.append(self.data.scalar_labels_file)
download_files = list(dict.fromkeys(download_files))
self.resolved_files = actual_source.reader().read(
dataset=self.data.source_dataset or self.data.dir_name.lower(),
files=download_files,
local_ds_root=self.data_dir,
revision=self.data.source_revision,
)
self.train_files = self._resolve_selectors(train_selectors)
test_files = self._resolve_selectors(test_selectors)
resolved_gt_files = self._resolve_selectors((gt_file,)) if gt_file is not None else []
if len(resolved_gt_files) > 1:
msg = f"Ground truth selector {gt_file!r} resolved to multiple files"
raise ValueError(msg)
resolved_gt_file = resolved_gt_files[0] if resolved_gt_files else None
needs_scalar_labels = filters.type == FilterOp.StrEqual or with_scalar_labels
# read scalar_labels_file if separated
if needs_scalar_labels and self.data.with_scalar_labels and self.data.scalar_labels_file_separated:
self.scalar_labels = self._read_file(self.data.scalar_labels_file)
if resolved_gt_file is not None and test_files:
query_frames = [self._read_file(file) for file in test_files]
test_frame = query_frames[0] if len(query_frames) == 1 else pl.concat(query_frames, how="vertical")
if self.search_files.query_count is not None and len(test_frame) != self.search_files.query_count:
msg = (
f"Query row count {len(test_frame)} in {test_files} does not match "
f"expected count {self.search_files.query_count}"
)
raise ValueError(msg)
query_ids = test_frame[self.data.test_id_field].to_list()
self.test_data = test_frame[self.data.test_vector_field].to_list()
self.gt_data = ParquetGroundTruth.from_file(
self._local_path(resolved_gt_file),
id_field=self.data.gt_id_field,
neighbors_field=self.data.gt_neighbors_field,
expected_query_ids=query_ids,
minimum_width=requested_k,
expected_width=self.search_files.width,
)
if isinstance(self.data, ParquetDataset):
self.result_metadata = self._result_metadata(
actual_source,
train_files=self.train_files,
query_files=test_files,
ground_truth_file=resolved_gt_file,
)
log.debug(f"{self.data.name}: available train files {self.train_files}")
return True
def max_search_k(self, filters: Filter = non_filter) -> int | None:
if isinstance(self.data, ParquetDataset):
self._validate_registered_filters(filters)
return self.data.ground_truth_width
if not isinstance(self.data, LAION):
return None
if isinstance(filters, NewIntFilter):
widths = LAION_INT_FILTER_SEARCH_WIDTHS.get(filters.filter_rate)
return widths[-1] if widths is not None else None
if filters.type == FilterOp.NonFilter:
return LAION_SEARCH_DATASET_FILES[-1][0]
return LAION_SEARCH_DATASET_FILES[0][0]
def resolve_search_files(self, *, k: int, filters: Filter = non_filter) -> SearchDatasetFiles:
if k <= 0:
msg = f"{self.data.name} search K must be positive, got {k}"
raise ValueError(msg)
if isinstance(self.data, ParquetDataset):
self._validate_registered_filters(filters)
if k > self.data.ground_truth_width:
msg = f"{self.data.name} supports K from 1 to {self.data.ground_truth_width}, got {k}"
raise ValueError(msg)
return SearchDatasetFiles(
self.data.query_selectors,
self.data.gt_selector,
width=self.data.ground_truth_width,
query_count=self.data.query_count,
)
if isinstance(self.data, LAION):
max_k = LAION_SEARCH_DATASET_FILES[-1][0]
if k > max_k:
msg = f"LAION supports K up to {max_k:,}, got {k:,}"
raise ValueError(msg)
if isinstance(filters, NewIntFilter):
widths = LAION_INT_FILTER_SEARCH_WIDTHS.get(filters.filter_rate)
if widths is None:
supported_rates = ", ".join(f"{rate * 100:g}%" for rate in LAION_INT_FILTER_SEARCH_WIDTHS)
msg = f"LAION supported filter rates are: {supported_rates}; got {filters.filter_rate * 100:g}%"
raise ValueError(msg)
if k <= LAION_SEARCH_DATASET_FILES[0][0]:
return SearchDatasetFiles(self.data.test_file, filters.groundtruth_file)
for width in widths:
if k <= width:
width_suffix = f"{width // 1_000_000}m" if width >= 1_000_000 else f"{width // 1_000}k"
return SearchDatasetFiles(
"test_nq200.parquet",
f"neighbors_{filters.int_rate}_top{width_suffix}_nq200.parquet",
width=width,
query_count=200,
)
msg = (
f"LAION integer filter {filters.filter_rate * 100:g}% supports K up to "
f"{widths[-1]:,}, got {k:,}"
)
raise ValueError(msg)
if filters.type != FilterOp.NonFilter:
if k > LAION_SEARCH_DATASET_FILES[0][0]:
msg = "LAION large-TopK ground truth is published only for integer filters"
raise ValueError(msg)
return SearchDatasetFiles(self.data.test_file, filters.groundtruth_file)
for upper_bound, files in LAION_SEARCH_DATASET_FILES:
if k <= upper_bound:
return files
return SearchDatasetFiles(self.data.test_file, filters.groundtruth_file)
@staticmethod
def _validate_registered_filters(filters: Filter) -> None:
if filters.type != FilterOp.NonFilter:
msg = "Parquet dataset does not contain scalar fields or filtered ground truth"
raise ValueError(msg)
def _resolve_selectors(self, selectors: typing.Iterable[str]) -> list[str]:
resolved = []
for selector in selectors:
matches = sorted(name for name in self.resolved_files if fnmatch.fnmatchcase(name, selector))
if not matches and not glob.has_magic(selector) and self._local_path(selector).exists():
matches = [selector]
if not matches:
msg = f"No dataset files match selector {selector!r}"
raise FileNotFoundError(msg)
for name in matches:
if name not in resolved:
resolved.append(name)
return resolved
def _result_metadata(
self,
source: DatasetSource,
*,
train_files: list[str],
query_files: list[str],
ground_truth_file: str | None,
) -> dict[str, Any]:
metadata = dict(self.data.dataset_metadata or {})
metadata.update(
{
"name": self.data.name,
"family": getattr(self.data, "family", None),
"source": source.value,
"repository": self.data.source_dataset,
"revision": self.data.source_revision,
"metric_type": self.data.metric_type.value,
"point_type": getattr(self.data, "point_type", None),
"storage_format": "parquet",
"train_files": train_files,
"query_files": query_files,
"ground_truth_file": ground_truth_file,
}
)
return metadata
def _read_file(self, file_name: str) -> pl.DataFrame:
"""read one file from disk into memory"""
log.info(f"Read the entire file into memory: {file_name}")
p = self._local_path(file_name)
if not p.exists():
log.warning(f"No such file: {p}")
return pl.DataFrame()
return pl.read_parquet(p)
class ParquetDatasetIterator:
def __init__(self, dataset: ParquetDatasetManager, batch_size: int = DEFAULT_INSERT_BATCH_SIZE):
if batch_size <= 0:
msg = f"insert batch size must be greater than 0, got {batch_size}"
raise ValueError(msg)
self._ds = dataset
self._batch_size = batch_size
self._idx = 0 # file number
self._cur = None
self._sub_idx = [0 for i in range(len(self._ds.train_files))] # iter num for each file
def __getstate__(self):
"""Custom pickle support to handle unpicklable generator."""
state = self.__dict__.copy()
# Remove the unpicklable generator from ParquetFile.iter_batches()
state["_cur"] = None
return state
def __setstate__(self, state: Any):
"""Restore state after unpickling."""
self.__dict__.update(state)
def __iter__(self):
return self
def _get_iter(self, file_name: str):
p = self._ds._local_path(file_name)
log.info(f"Get iterator for {p.name}")
if not p.exists():
msg = f"No such file: {p}"
log.warning(msg)
raise IndexError(msg)
return ParquetFile(p, memory_map=True, pre_buffer=True).iter_batches(self._batch_size)
def __next__(self) -> pd.DataFrame:
"""return the data in the next file of the training list"""
if self._idx < len(self._ds.train_files):
if self._cur is None:
file_name = self._ds.train_files[self._idx]
self._cur = self._get_iter(file_name)
try:
return next(self._cur).to_pandas()
except StopIteration:
if self._idx == len(self._ds.train_files) - 1:
raise StopIteration from None
self._idx += 1
file_name = self._ds.train_files[self._idx]
self._cur = self._get_iter(file_name)
return next(self._cur).to_pandas()
raise StopIteration
# Backwards-compatible name for callers that imported the Parquet iterator directly.
DataSetIterator = ParquetDatasetIterator
class Hdf5Dataset(BaseDataset):
"""Schema and source details for an HDF5 vector dataset."""
file_name: str
train_key: str = "train"
test_key: str = "test"
neighbors_key: str = "neighbors"
distances_key: str | None = "distances"
dimension_attr: str | None = "dimension"
distance_attr: str | None = "distance"
point_type_attr: str | None = "point_type"
source_distance: str | None = None
point_type: str | None = None
ground_truth_width: int = 100
family: str | None = None
distribution: str | None = None
modality: str | None = None
@field_validator("size")
@classmethod
def verify_size(cls, value: int) -> int:
if value <= 0:
msg = f"Dataset size must be positive, got {value}"
raise ValueError(msg)
return value
@property
def label(self) -> str:
return self.family or "HDF5"
@property
def full_name(self) -> str:
return self.name
@property
def dir_name(self) -> str:
return self.name
@property
def train_files(self) -> list[str]:
return [self.file_name]
class Hdf5DatasetIterator:
"""Keep one HDF5 file open for the lifetime of an insertion iterator."""
def __init__(self, dataset: Hdf5Dataset, path: pathlib.Path, batch_size: int):
if batch_size <= 0:
msg = f"insert batch size must be greater than 0, got {batch_size}"
raise ValueError(msg)
self._dataset = dataset
self._batch_size = batch_size
self._offset = 0
self._file: h5py.File | None = None
self._train: h5py.Dataset | None = None
self._file = h5py.File(path, "r")
self._train = self._file[dataset.train_key]
def __iter__(self):
return self
def __next__(self) -> pd.DataFrame:
if self._train is None or self._offset >= len(self._train):
self.close()
raise StopIteration
end = min(self._offset + self._batch_size, len(self._train))
vectors = np.ascontiguousarray(self._train[self._offset : end])
batch = pd.DataFrame(
{
self._dataset.train_id_field: np.arange(self._offset, end, dtype=np.int64),
self._dataset.train_vector_field: list(vectors),
}
)
self._offset = end
return batch
def close(self) -> None:
self._train = None
if self._file is not None:
self._file.close()
self._file = None
def __del__(self):
self.close()
class Hdf5DatasetManager(DatasetManager):
"""Prepare query data and stream corpus vectors directly from HDF5."""
data: Hdf5Dataset
source_path: pathlib.Path | None = None
def iter_batches(self, batch_size: int):
if not self.train_files:
return iter(())
if self.source_path is None:
raise RuntimeError("HDF5 dataset is not prepared")
return Hdf5DatasetIterator(self.data, self.source_path, batch_size)
def max_search_k(self, filters: Filter = non_filter) -> int | None:
self._validate_unfiltered(filters)
return self.data.ground_truth_width
def resolve_search_files(self, *, k: int, filters: Filter = non_filter) -> SearchDatasetFiles:
self._validate_unfiltered(filters)
if not 1 <= k <= self.data.ground_truth_width:
msg = f"{self.data.name} supports K from 1 to {self.data.ground_truth_width}, got {k}"
raise ValueError(msg)
return SearchDatasetFiles(
self.data.file_name,
self.data.file_name,
width=self.data.ground_truth_width,
)
def prepare(
self,
source: DatasetSource = DatasetSource.S3,
filters: Filter = non_filter,
with_train_files: bool = True,
with_scalar_labels: bool = False,
k: int | None = None,
) -> bool:
if with_scalar_labels:
msg = f"{self.data.name} does not provide scalar labels"
raise ValueError(msg)
requested_k = config.K_DEFAULT if k is None else k
self.search_files = self.resolve_search_files(k=requested_k, filters=filters)
actual_source = self.preferred_source or source
if self.data.with_remote_resource:
self.resolved_files = actual_source.reader().read(
self.data.source_dataset or self.data.dir_name,
[self.data.file_name],
self.data_dir,
revision=self.data.source_revision,
)
self.source_path = self._local_path(self.data.file_name)
with h5py.File(self.source_path, "r") as hdf5:
self._validate_source(hdf5)
queries = np.ascontiguousarray(hdf5[self.data.test_key][:])
neighbors = np.ascontiguousarray(hdf5[self.data.neighbors_key][:])
if neighbors.size and (neighbors.min() < 0 or neighbors.max() >= self.data.size):
msg = f"Neighbor ID is outside [0, {self.data.size}) for {self.data.name}"
raise ValueError(msg)
self.test_data = queries.tolist()
self.gt_data = neighbors.tolist()
self.train_files = self.data.train_files if with_train_files else []
self.result_metadata = self._result_metadata(actual_source)
return True
@staticmethod
def _validate_unfiltered(filters: Filter) -> None:
if filters.type != FilterOp.NonFilter:
msg = "HDF5 dataset does not contain scalar fields or filtered ground truth"
raise ValueError(msg)
def _validate_source(self, source: h5py.File) -> None:
required_arrays = {self.data.train_key, self.data.test_key, self.data.neighbors_key}
if self.data.distances_key is not None:
required_arrays.add(self.data.distances_key)
missing_arrays = required_arrays - set(source)
if missing_arrays:
msg = f"Invalid HDF5 {self.data.file_name}: missing arrays={sorted(missing_arrays)}"
raise ValueError(msg)
self._validate_attr(source, self.data.dimension_attr, self.data.dim)