-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpq_index_test.go
More file actions
1614 lines (1398 loc) · 40.1 KB
/
pq_index_test.go
File metadata and controls
1614 lines (1398 loc) · 40.1 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
package comet
import (
"bytes"
"io"
"sync"
"testing"
)
// TestCalculatePQParams tests PQ parameter calculation
func TestCalculatePQParams(t *testing.T) {
tests := []struct {
name string
dim int
wantM int
wantNbits int
}{
{"dimension 768", 768, 8, 8},
{"dimension 384", 384, 8, 8},
{"dimension 128", 128, 8, 8},
{"dimension 64", 64, 8, 8},
{"dimension 32", 32, 8, 8},
{"dimension 16", 16, 8, 8},
{"dimension 100", 100, 10, 8}, // 100 divisible by 10
{"dimension 17", 17, 17, 8}, // 17 only divisible by itself and 1
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
M, Nbits := CalculatePQParams(tt.dim)
if M != tt.wantM {
t.Errorf("CalculatePQParams(%d) M = %d, want %d", tt.dim, M, tt.wantM)
}
if Nbits != tt.wantNbits {
t.Errorf("CalculatePQParams(%d) Nbits = %d, want %d", tt.dim, Nbits, tt.wantNbits)
}
// Verify M divides dim
if tt.dim%M != 0 {
t.Errorf("CalculatePQParams(%d) returned M=%d which doesn't divide dimension", tt.dim, M)
}
})
}
}
// TestNewPQIndex tests PQ index creation with various parameters
func TestNewPQIndex(t *testing.T) {
tests := []struct {
name string
dim int
distanceKind DistanceKind
M int
Nbits int
wantErr bool
}{
{"valid L2 index", 128, Euclidean, 8, 8, false},
{"valid Cosine index", 384, Cosine, 8, 8, false},
{"valid L2Squared index", 768, L2Squared, 8, 8, false},
{"zero dimension", 0, Euclidean, 8, 8, true},
{"negative dimension", -1, Euclidean, 8, 8, true},
{"zero M", 128, Euclidean, 0, 8, true},
{"negative M", 128, Euclidean, -1, 8, true},
{"M doesn't divide dim", 100, Euclidean, 8, 8, true},
{"zero Nbits", 128, Euclidean, 8, 0, true},
{"negative Nbits", 128, Euclidean, 8, -1, true},
{"Nbits too large", 128, Euclidean, 8, 17, true},
{"invalid distance kind", 128, DistanceKind("invalid"), 8, 8, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idx, err := NewPQIndex(tt.dim, tt.distanceKind, tt.M, tt.Nbits)
if tt.wantErr {
if err == nil {
t.Error("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Expected no error but got: %v", err)
}
if idx == nil {
t.Error("Expected non-nil index")
}
if idx.Dimensions() != tt.dim {
t.Errorf("Dimensions() = %d, want %d", idx.Dimensions(), tt.dim)
}
if idx.DistanceKind() != tt.distanceKind {
t.Errorf("DistanceKind() = %v, want %v", idx.DistanceKind(), tt.distanceKind)
}
if idx.Kind() != PQIndexKind {
t.Errorf("Kind() = %v, want %v", idx.Kind(), PQIndexKind)
}
if idx.Trained() {
t.Error("New index should not be trained")
}
// Verify derived parameters
expectedKsub := 1 << tt.Nbits
if idx.Ksub != expectedKsub {
t.Errorf("Ksub = %d, want %d", idx.Ksub, expectedKsub)
}
expectedDsub := tt.dim / tt.M
if idx.dsub != expectedDsub {
t.Errorf("dsub = %d, want %d", idx.dsub, expectedDsub)
}
}
})
}
}
// TestPQIndexTrain tests training functionality
func TestPQIndexTrain(t *testing.T) {
dim := 8
M := 4
Nbits := 8
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Create sufficient training vectors
numVectors := 300 // More than Ksub=256
trainingVectors := make([]VectorNode, numVectors)
for i := 0; i < numVectors; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 10)
}
trainingVectors[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors)
if err != nil {
t.Fatalf("Train() error: %v", err)
}
// Verify index is trained
if !idx.Trained() {
t.Error("Index should be marked as trained")
}
// Verify codebooks were learned
if len(idx.codebooks) != M {
t.Errorf("Expected %d codebooks, got %d", M, len(idx.codebooks))
}
// Verify each codebook has correct size
expectedKsub := 1 << Nbits // 256
expectedDsub := dim / M
for i, codebook := range idx.codebooks {
expectedSize := expectedKsub * expectedDsub
if len(codebook) != expectedSize {
t.Errorf("Codebook %d has size %d, want %d", i, len(codebook), expectedSize)
}
}
}
// TestPQIndexTrainInsufficientVectors tests training with too few vectors
func TestPQIndexTrainInsufficientVectors(t *testing.T) {
dim := 8
M := 4
Nbits := 8 // Ksub = 256
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Only provide 100 vectors when 256 are required
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors)
if err == nil {
t.Error("Expected error when training with insufficient vectors")
}
}
// TestPQIndexTrainDimensionMismatch tests training with wrong dimension vectors
func TestPQIndexTrainDimensionMismatch(t *testing.T) {
dim := 8
M := 4
Nbits := 8
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Create vectors with wrong dimension
trainingVectors := make([]VectorNode, 300)
for i := 0; i < 300; i++ {
// Wrong dimension: 10 instead of 8
vec := make([]float32, 10)
for j := 0; j < 10; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors)
if err == nil {
t.Error("Expected error when training with wrong dimension vectors")
}
}
// TestPQIndexAddBeforeTrain tests that add fails before training
func TestPQIndexAddBeforeTrain(t *testing.T) {
idx, err := NewPQIndex(8, Euclidean, 4, 8)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
node := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8})
err = idx.Add(*node)
if err == nil {
t.Error("Expected error when adding before training")
}
}
// TestPQIndexAdd tests adding vectors to the index
func TestPQIndexAdd(t *testing.T) {
dim := 8
M := 4
Nbits := 6 // Ksub = 64, more manageable for testing
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 10)
}
trainingVectors[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors)
if err != nil {
t.Fatalf("Train() error: %v", err)
}
// Add vectors
vectors := [][]float32{
{1, 2, 3, 4, 5, 6, 7, 8},
{2, 3, 4, 5, 6, 7, 8, 9},
{3, 4, 5, 6, 7, 8, 9, 10},
{4, 5, 6, 7, 8, 9, 10, 11},
}
for _, v := range vectors {
node := NewVectorNode(v)
err := idx.Add(*node)
if err != nil {
t.Errorf("Add() error: %v", err)
}
}
// Verify vectors were added
if len(idx.codes) != len(vectors) {
t.Errorf("Expected %d codes, got %d", len(vectors), len(idx.codes))
}
if len(idx.vectorNodes) != len(vectors) {
t.Errorf("Expected %d vector nodes, got %d", len(vectors), len(idx.vectorNodes))
}
// Verify each code has M bytes
for i, code := range idx.codes {
if len(code) != M {
t.Errorf("Code %d has length %d, want %d", i, len(code), M)
}
}
}
// TestPQIndexAddDimensionMismatch tests adding wrong dimension vectors
func TestPQIndexAddDimensionMismatch(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Try to add 10D vector to 8D index
node := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
err = idx.Add(*node)
if err == nil {
t.Error("Expected error when adding wrong dimension vector")
}
}
// TestPQIndexAddZeroVectorCosine tests adding zero vector with cosine distance
func TestPQIndexAddZeroVectorCosine(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Cosine, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first with non-zero vectors
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i + 1) // Non-zero
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Try to add zero vector (cannot be normalized)
node := NewVectorNode([]float32{0, 0, 0, 0, 0, 0, 0, 0})
err = idx.Add(*node)
if err == nil {
t.Error("Expected error when adding zero vector with cosine distance")
}
}
// TestPQIndexRemove tests removing vectors from the index
func TestPQIndexRemove(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train and add vectors
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
node1 := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8})
node2 := NewVectorNode([]float32{2, 3, 4, 5, 6, 7, 8, 9})
node3 := NewVectorNode([]float32{3, 4, 5, 6, 7, 8, 9, 10})
idx.Add(*node1)
idx.Add(*node2)
idx.Add(*node3)
// Remove middle node (soft delete)
err = idx.Remove(*node2)
if err != nil {
t.Errorf("Remove() error: %v", err)
}
// Vectors should still be in slices (soft delete)
if len(idx.codes) != 3 {
t.Errorf("Expected 3 codes after soft delete, got %d", len(idx.codes))
}
if len(idx.vectorNodes) != 3 {
t.Errorf("Expected 3 vector nodes after soft delete, got %d", len(idx.vectorNodes))
}
// Call Flush to perform hard delete
err = idx.Flush()
if err != nil {
t.Errorf("Flush() error: %v", err)
}
// Now vectors should be physically removed
if len(idx.codes) != 2 {
t.Errorf("Expected 2 codes after flush, got %d", len(idx.codes))
}
if len(idx.vectorNodes) != 2 {
t.Errorf("Expected 2 vector nodes after flush, got %d", len(idx.vectorNodes))
}
// Verify correct nodes remain
remainingIDs := []uint32{node1.ID(), node3.ID()}
for i, node := range idx.vectorNodes {
if node.ID() != remainingIDs[i] {
t.Errorf("Node %d has ID %d, want %d", i, node.ID(), remainingIDs[i])
}
}
// Try to remove already deleted vector
err = idx.Remove(*node2)
if err == nil {
t.Error("Remove() expected error for already deleted vector")
}
}
// TestPQIndexRemoveNonExistent tests removing non-existent vector
func TestPQIndexRemoveNonExistent(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Try to remove a node that was never added
node := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8})
err = idx.Remove(*node)
if err == nil {
t.Error("Expected error when removing non-existent vector")
}
}
// TestPQIndexFlush tests the flush method
func TestPQIndexFlush(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train the index
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Add some vectors
node1 := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8})
node2 := NewVectorNode([]float32{2, 3, 4, 5, 6, 7, 8, 9})
node3 := NewVectorNode([]float32{3, 4, 5, 6, 7, 8, 9, 10})
idx.Add(*node1)
idx.Add(*node2)
idx.Add(*node3)
// Flush with no deletions should succeed and keep all vectors
if err := idx.Flush(); err != nil {
t.Errorf("Flush() error: %v", err)
}
if len(idx.codes) != 3 {
t.Errorf("Expected 3 codes after flush with no deletions, got %d", len(idx.codes))
}
// Soft delete two vectors
idx.Remove(*node1)
idx.Remove(*node2)
// Vectors still in memory before flush
if len(idx.codes) != 3 {
t.Errorf("Expected 3 codes before flush, got %d", len(idx.codes))
}
// Flush should remove deleted vectors
if err := idx.Flush(); err != nil {
t.Errorf("Flush() error: %v", err)
}
// Only one vector should remain
if len(idx.codes) != 1 {
t.Errorf("Expected 1 code after flush, got %d", len(idx.codes))
}
if len(idx.vectorNodes) != 1 {
t.Errorf("Expected 1 vector node after flush, got %d", len(idx.vectorNodes))
}
// Verify the remaining vector is node3
if idx.vectorNodes[0].ID() != node3.ID() {
t.Errorf("Expected remaining vector to be node3, got node with ID %d", idx.vectorNodes[0].ID())
}
// Verify deleted bitmap is cleared
if idx.deletedNodes.GetCardinality() != 0 {
t.Errorf("Expected deletedNodes bitmap to be empty after flush, got cardinality %d", idx.deletedNodes.GetCardinality())
}
// Multiple flushes should be safe
if err := idx.Flush(); err != nil {
t.Errorf("Second Flush() error: %v", err)
}
}
// TestPQIndexGetters tests getter methods
func TestPQIndexGetters(t *testing.T) {
dim := 384
M := 8
Nbits := 8
distanceKind := Cosine
idx, err := NewPQIndex(dim, distanceKind, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
if idx.Dimensions() != dim {
t.Errorf("Dimensions() = %d, want %d", idx.Dimensions(), dim)
}
if idx.DistanceKind() != distanceKind {
t.Errorf("DistanceKind() = %v, want %v", idx.DistanceKind(), distanceKind)
}
if idx.Kind() != PQIndexKind {
t.Errorf("Kind() = %v, want %v", idx.Kind(), PQIndexKind)
}
if idx.Trained() {
t.Error("New index should not be trained")
}
// Train and check again
trainingVectors := make([]VectorNode, 300)
for i := 0; i < 300; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i + 1) % 10)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
if !idx.Trained() {
t.Error("Trained index should return true for Trained()")
}
}
// TestPQIndexNewSearch tests search builder creation
func TestPQIndexNewSearch(t *testing.T) {
idx, err := NewPQIndex(8, Euclidean, 4, 6)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
search := idx.NewSearch()
if search == nil {
t.Error("NewSearch() returned nil")
}
// Verify it's the correct type
pqSearch, ok := search.(*pqIndexSearch)
if !ok {
t.Error("NewSearch() did not return *pqIndexSearch")
}
// Verify defaults
if pqSearch.k != 10 {
t.Errorf("Default k = %d, want 10", pqSearch.k)
}
}
// TestPQIndexConcurrentAdd tests concurrent additions to the index
func TestPQIndexConcurrentAdd(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 10)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Add vectors concurrently
var wg sync.WaitGroup
numGoroutines := 10
vectorsPerGoroutine := 10
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(offset int) {
defer wg.Done()
for j := 0; j < vectorsPerGoroutine; j++ {
vec := make([]float32, dim)
for k := 0; k < dim; k++ {
vec[k] = float32(offset*100 + j*10 + k)
}
node := NewVectorNode(vec)
err := idx.Add(*node)
if err != nil {
t.Errorf("Add() error: %v", err)
}
}
}(i)
}
wg.Wait()
// Verify all vectors were added
expected := numGoroutines * vectorsPerGoroutine
if len(idx.codes) != expected {
t.Errorf("Expected %d codes after concurrent adds, got %d", expected, len(idx.codes))
}
if len(idx.vectorNodes) != expected {
t.Errorf("Expected %d vector nodes after concurrent adds, got %d", expected, len(idx.vectorNodes))
}
}
// TestPQIndexEncode tests the encode function
func TestPQIndexEncode(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train first
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 10)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Test encode
testVec := []float32{1, 2, 3, 4, 5, 6, 7, 8}
code := idx.encode(testVec)
// Verify code length
if len(code) != M {
t.Errorf("Code length = %d, want %d", len(code), M)
}
// Verify each code element is within valid range
Ksub := 1 << Nbits
for i, c := range code {
if int(c) >= Ksub {
t.Errorf("Code[%d] = %d, which is >= Ksub=%d", i, c, Ksub)
}
}
// Encode same vector twice, should get same code
code2 := idx.encode(testVec)
if len(code) != len(code2) {
t.Error("Encoding same vector twice gave different length codes")
}
for i := range code {
if code[i] != code2[i] {
t.Errorf("Encoding same vector twice gave different codes at position %d: %d vs %d", i, code[i], code2[i])
}
}
}
// TestPQIndexDifferentDistanceMetrics tests PQ with different distance metrics
func TestPQIndexDifferentDistanceMetrics(t *testing.T) {
tests := []struct {
name string
distanceKind DistanceKind
}{
{"Euclidean", Euclidean},
{"L2Squared", L2Squared},
{"Cosine", Cosine},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, tt.distanceKind, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i + 1) // Non-zero for cosine
}
trainingVectors[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors)
if err != nil {
t.Fatalf("Train() error: %v", err)
}
// Add and verify
node := NewVectorNode([]float32{1, 2, 3, 4, 5, 6, 7, 8})
err = idx.Add(*node)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if len(idx.codes) != 1 {
t.Errorf("Expected 1 code, got %d", len(idx.codes))
}
})
}
}
// TestPQIndexCompressionRatio tests that PQ achieves significant compression
func TestPQIndexCompressionRatio(t *testing.T) {
dim := 768
M := 8
Nbits := 8
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train
trainingVectors := make([]VectorNode, 300)
for i := 0; i < 300; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 100)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Add vector
node := NewVectorNode(make([]float32, dim))
idx.Add(*node)
// Check compression
// Original: dim * 4 bytes = 768 * 4 = 3072 bytes
// Compressed: M bytes = 8 bytes
originalSize := dim * 4
compressedSize := M
compressionRatio := float64(originalSize) / float64(compressedSize)
if compressionRatio < 100 {
t.Errorf("Expected compression ratio > 100x, got %.2fx", compressionRatio)
}
t.Logf("Compression: %d bytes -> %d bytes (%.0fx)", originalSize, compressedSize, compressionRatio)
}
// TestPQIndexLargeScale tests PQ with more realistic scale
func TestPQIndexLargeScale(t *testing.T) {
if testing.Short() {
t.Skip("Skipping large scale test in short mode")
}
dim := 128
M := 8
Nbits := 8
numVectors := 1000
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Generate training vectors
trainingVectors := make([]VectorNode, 300)
for i := 0; i < 300; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 100)
}
trainingVectors[i] = *NewVectorNode(vec)
}
// Train
err = idx.Train(trainingVectors)
if err != nil {
t.Fatalf("Train() error: %v", err)
}
// Add vectors
for i := 0; i < numVectors; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 100)
}
node := NewVectorNode(vec)
err := idx.Add(*node)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
}
// Verify vectors were added
if len(idx.codes) != numVectors {
t.Errorf("Expected %d codes, got %d", numVectors, len(idx.codes))
}
// Calculate memory usage
originalMemory := numVectors * dim * 4 // float32 = 4 bytes
compressedMemory := numVectors * M
codebookMemory := M * (1 << Nbits) * (dim / M) * 4
totalMemory := compressedMemory + codebookMemory
t.Logf("Original memory: %d bytes (%.2f MB)", originalMemory, float64(originalMemory)/(1024*1024))
t.Logf("Compressed codes: %d bytes (%.2f KB)", compressedMemory, float64(compressedMemory)/1024)
t.Logf("Codebooks: %d bytes (%.2f KB)", codebookMemory, float64(codebookMemory)/1024)
t.Logf("Total PQ memory: %d bytes (%.2f MB)", totalMemory, float64(totalMemory)/(1024*1024))
t.Logf("Compression ratio: %.2fx", float64(originalMemory)/float64(totalMemory))
}
// TestPQIndexCodebookStructure tests that codebooks have correct structure
func TestPQIndexCodebookStructure(t *testing.T) {
dim := 16
M := 4
Nbits := 6
Ksub := 1 << Nbits // 64
dsub := dim / M // 4
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32((i*dim + j) % 20)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Verify codebook structure
if len(idx.codebooks) != M {
t.Fatalf("Expected %d codebooks, got %d", M, len(idx.codebooks))
}
for m := 0; m < M; m++ {
expectedSize := Ksub * dsub
if len(idx.codebooks[m]) != expectedSize {
t.Errorf("Codebook %d has size %d, want %d", m, len(idx.codebooks[m]), expectedSize)
}
// Verify we can access each centroid
for k := 0; k < Ksub; k++ {
start := k * dsub
end := start + dsub
centroid := idx.codebooks[m][start:end]
if len(centroid) != dsub {
t.Errorf("Centroid %d in codebook %d has length %d, want %d", k, m, len(centroid), dsub)
}
}
}
}
// TestPQIndexMultipleTraining tests that training can be called multiple times
func TestPQIndexMultipleTraining(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// First training
trainingVectors1 := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors1[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors1)
if err != nil {
t.Fatalf("First Train() error: %v", err)
}
// Second training (retraining)
trainingVectors2 := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i + 100)
}
trainingVectors2[i] = *NewVectorNode(vec)
}
err = idx.Train(trainingVectors2)
if err != nil {
t.Fatalf("Second Train() error: %v", err)
}
// Should still be trained
if !idx.Trained() {
t.Error("Index should be trained after retraining")
}
}
// TestPQIndexSoftDeleteWithSearch tests that soft-deleted nodes are filtered during search
func TestPQIndexSoftDeleteWithSearch(t *testing.T) {
dim := 8
M := 4
Nbits := 6
idx, err := NewPQIndex(dim, Euclidean, M, Nbits)
if err != nil {
t.Fatalf("NewPQIndex() error: %v", err)
}
// Train the index
trainingVectors := make([]VectorNode, 100)
for i := 0; i < 100; i++ {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = float32(i)
}
trainingVectors[i] = *NewVectorNode(vec)
}
idx.Train(trainingVectors)
// Add test vectors
node1 := NewVectorNode([]float32{1, 0, 0, 0, 0, 0, 0, 0})
node2 := NewVectorNode([]float32{2, 0, 0, 0, 0, 0, 0, 0})
node3 := NewVectorNode([]float32{3, 0, 0, 0, 0, 0, 0, 0})
node4 := NewVectorNode([]float32{4, 0, 0, 0, 0, 0, 0, 0})
idx.Add(*node1)
idx.Add(*node2)
idx.Add(*node3)
idx.Add(*node4)
// Search should return all 4 vectors
query := []float32{1.5, 0, 0, 0, 0, 0, 0, 0}
results, err := idx.NewSearch().WithQuery(query).WithK(10).Execute()
if err != nil {
t.Fatalf("Search error: %v", err)
}
if len(results) != 4 {
t.Errorf("Expected 4 results before deletion, got %d", len(results))
}
// Soft delete node2 and node3
idx.Remove(*node2)
idx.Remove(*node3)
// Search should now return only 2 vectors (node1 and node4)