-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathvector_mhnsw.cc
More file actions
1811 lines (1559 loc) · 54 KB
/
vector_mhnsw.cc
File metadata and controls
1811 lines (1559 loc) · 54 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
/*
Copyright (c) 2024, 2025, MariaDB plc
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA
*/
#include <my_global.h>
#include "key.h" // key_copy()
#include "create_options.h"
#include "table_cache.h"
#include "vector_mhnsw.h"
#include <scope.h>
#include <my_atomic_wrapper.h>
#include "bloom_filters.h"
// distance can be a little bit < 0 because of fast math
static constexpr float NEAREST = -1.0f;
// Algorithm parameters
static constexpr float alpha = 1.1f;
static constexpr uint ef_construction= 10;
static constexpr uint max_ef= 10000;
static constexpr size_t subdist_part= 192;
static constexpr float subdist_margin= 1.05f;
static constexpr double subdist_stddev_threshold= 0.05; // 3σ, p>99.9%
static constexpr ulonglong subdist_stddev_valid= 10000; // sufficient
/*
The class below can assume normal distribution and only collect
M1 and M2, or go beyond that and collect M3 and M4 to account
for non-gaussian. The second mode is useful for research and tuning,
but M2 is all we need in production for now.
*/
#define STATS_NON_GAUSSIAN 0 /* 0 for no, 3 for yes */
struct stats_collector
{
ulonglong n= 0;
double M1= 0, M2= 0, M3= 0, M4= 0;
void add(ulonglong nB, double M1B, double M2B, double M3B, double M4B)
{ // parallel Welford's online algorithm
ulonglong nA= n;
n+= nB;
double d= M1B-M1, dn= d/n, t1= d*dn*nA*nB;
M1+= dn*nB;
#if STATS_NON_GAUSSIAN
M4+= M4B + t1*dn*dn*(nA*nA-nA*nB+nB*nB)
+ 6*dn*dn*(nA*nA*M2B+nB*nB*M2)
+ 4*dn*(nA*M3B-nB*M3);
M3+= M3B + dn*t1*(nA-nB) + 3*dn*(nA*M2B-nB*M2)
#endif
M2+= t1;
}
void add(double x) { if (std::isfinite(x)) add(1, x, 0, 0, 0); }
void add(const stats_collector &b) { if (b.n) add(b.n, b.M1, b.M2, b.M3, b.M4); }
double mean() { return M1; }
double stddev() { return std::sqrt(M2/n); }
double skewness() { return M3/M2/stddev(); }
double kurtosis() { return n*M4/M2/M2 - STATS_NON_GAUSSIAN; }
double quantile(double z) // Cornish–Fisher expansion
{
return mean() + stddev() * (z +
skewness() / 6 * (z*z-1) +
kurtosis() / 24 * (z*z*z-3*z) -
skewness() * skewness() / 36 * (2*z*z*z-5*z));
}
};
/*
graph related statistical data. stored in MHNSW_Share.
copied from ctx to a local structure under a lock.
*/
struct Stats
{
double ef_power= 0.6; // for the bloom filter size heuristic
float diameter= 0;
size_t graph_size= 0;
stats_collector subdist;
};
static ulonglong mhnsw_max_cache_size;
static MYSQL_SYSVAR_ULONGLONG(max_cache_size, mhnsw_max_cache_size,
PLUGIN_VAR_RQCMDARG, "Upper limit for one MHNSW vector index cache",
nullptr, nullptr, 16*1024*1024, 1024*1024, SIZE_T_MAX, 1);
static MYSQL_THDVAR_UINT(ef_search, PLUGIN_VAR_RQCMDARG,
"Larger values mean slower SELECTs but more accurate results. "
"Defines the minimal number of result candidates to look for in the "
"vector index for ORDER BY ... LIMIT N queries. The search will never "
"search for less rows than that, even if LIMIT is smaller",
nullptr, nullptr, 20, 1, max_ef, 1);
static MYSQL_THDVAR_UINT(default_m, PLUGIN_VAR_RQCMDARG,
"Larger values mean slower SELECTs and INSERTs, larger index size "
"and higher memory consumption but more accurate results",
nullptr, nullptr, 6, 3, 200, 1);
enum metric_type : uint { EUCLIDEAN, COSINE };
static const char *distance_names[]= { "euclidean", "cosine", nullptr };
static TYPELIB distances= CREATE_TYPELIB_FOR(distance_names);
static MYSQL_THDVAR_ENUM(default_distance, PLUGIN_VAR_RQCMDARG,
"Distance function to build the vector index for",
nullptr, nullptr, EUCLIDEAN, &distances);
struct ha_index_option_struct
{
ulonglong M; // option struct does not support uint
metric_type metric;
};
enum Graph_table_fields {
FIELD_LAYER, FIELD_TREF, FIELD_VEC, FIELD_NEIGHBORS
};
enum Graph_table_indices {
IDX_TREF, IDX_LAYER
};
class MHNSW_Share;
class FVectorNode;
/*
One vector, an array of coordinates in ctx->vec_len dimensions
*/
#pragma pack(push, 1)
struct FVector
{
static constexpr size_t data_header= sizeof(float);
static constexpr size_t alloc_header= data_header + sizeof(float)*2;
float abs2, subabs2, scale;
int16_t dims[4];
uchar *data() const { return (uchar*)(&scale); }
static size_t data_size(size_t n)
{ return data_header + n*2; }
static size_t data_to_value_size(size_t data_size)
{ return (data_size - data_header)*2; }
static const FVector *create(const MHNSW_Share *ctx, void *mem, const void *src);
void postprocess(bool use_subdist, size_t vec_len)
{
int16_t *d= dims;
fix_tail(vec_len);
if (use_subdist)
{
subabs2= scale * scale * dot_product(d, d, subdist_part) / 2;
d+= subdist_part;
vec_len-= subdist_part;
}
else
subabs2= 0;
abs2= subabs2 + scale * scale * dot_product(d, d, vec_len) / 2;
}
#ifdef AVX2_IMPLEMENTATION
/************* AVX2 *****************************************************/
static constexpr size_t AVX2_bytes= 256/8;
static constexpr size_t AVX2_dims= AVX2_bytes/sizeof(int16_t);
static_assert(subdist_part % AVX2_dims == 0);
AVX2_IMPLEMENTATION
static float dot_product(const int16_t *v1, const int16_t *v2, size_t len)
{
typedef float v8f __attribute__((vector_size(AVX2_bytes)));
union { v8f v; __m256 i; } tmp;
__m256i *p1= (__m256i*)v1;
__m256i *p2= (__m256i*)v2;
v8f d= {0};
for (size_t i= 0; i < (len + AVX2_dims-1)/AVX2_dims; p1++, p2++, i++)
{
tmp.i= _mm256_cvtepi32_ps(_mm256_madd_epi16(*p1, *p2));
d+= tmp.v;
}
return d[0] + d[1] + d[2] + d[3] + d[4] + d[5] + d[6] + d[7];
}
AVX2_IMPLEMENTATION
static size_t alloc_size(size_t n)
{ return alloc_header + MY_ALIGN(n*2, AVX2_bytes) + AVX2_bytes - 1; }
AVX2_IMPLEMENTATION
static FVector *align_ptr(void *ptr)
{ return (FVector*)(MY_ALIGN(((intptr)ptr) + alloc_header, AVX2_bytes)
- alloc_header); }
AVX2_IMPLEMENTATION
void fix_tail(size_t vec_len)
{
bzero(dims + vec_len, (MY_ALIGN(vec_len, AVX2_dims) - vec_len)*2);
}
#endif
#ifdef AVX512_IMPLEMENTATION
/************* AVX512 ****************************************************/
static constexpr size_t AVX512_bytes= 512/8;
static constexpr size_t AVX512_dims= AVX512_bytes/sizeof(int16_t);
static_assert(subdist_part % AVX512_dims == 0);
AVX512_IMPLEMENTATION
static float dot_product(const int16_t *v1, const int16_t *v2, size_t len)
{
__m512i *p1= (__m512i*)v1;
__m512i *p2= (__m512i*)v2;
__m512 d= _mm512_setzero_ps();
for (size_t i= 0; i < (len + AVX512_dims-1)/AVX512_dims; p1++, p2++, i++)
d= _mm512_add_ps(d, _mm512_cvtepi32_ps(_mm512_madd_epi16(*p1, *p2)));
return _mm512_reduce_add_ps(d);
}
AVX512_IMPLEMENTATION
static size_t alloc_size(size_t n)
{ return alloc_header + MY_ALIGN(n*2, AVX512_bytes) + AVX512_bytes - 1; }
AVX512_IMPLEMENTATION
static FVector *align_ptr(void *ptr)
{ return (FVector*)(MY_ALIGN(((intptr)ptr) + alloc_header, AVX512_bytes)
- alloc_header); }
AVX512_IMPLEMENTATION
void fix_tail(size_t vec_len)
{
bzero(dims + vec_len, (MY_ALIGN(vec_len, AVX512_dims) - vec_len)*2);
}
#endif
/*
ARM NEON implementation. A microbenchmark shows 1.7x dot_product() performance
improvement compared to regular -O2/-O3 builds and 2.4x compared to builds
with auto-vectorization disabled.
There seem to be no performance difference between vmull+vmull_high and
vmull+vmlal2_high implementations.
*/
#ifdef NEON_IMPLEMENTATION
static constexpr size_t NEON_bytes= 128 / 8;
static constexpr size_t NEON_dims= NEON_bytes / sizeof(int16_t);
static_assert(subdist_part % NEON_dims == 0);
static float dot_product(const int16_t *v1, const int16_t *v2, size_t len)
{
int64_t d= 0;
for (size_t i= 0; i < (len + NEON_dims - 1) / NEON_dims; i++)
{
int16x8_t p1= vld1q_s16(v1);
int16x8_t p2= vld1q_s16(v2);
d+= vaddlvq_s32(vmull_s16(vget_low_s16(p1), vget_low_s16(p2))) +
vaddlvq_s32(vmull_high_s16(p1, p2));
v1+= NEON_dims;
v2+= NEON_dims;
}
return static_cast<float>(d);
}
static size_t alloc_size(size_t n)
{ return alloc_header + MY_ALIGN(n * 2, NEON_bytes) + NEON_bytes - 1; }
static FVector *align_ptr(void *ptr)
{ return (FVector*) (MY_ALIGN(((intptr) ptr) + alloc_header, NEON_bytes)
- alloc_header); }
void fix_tail(size_t vec_len)
{
bzero(dims + vec_len, (MY_ALIGN(vec_len, NEON_dims) - vec_len) * 2);
}
#endif
#ifdef POWER_IMPLEMENTATION
/************* POWERPC *****************************************************/
static constexpr size_t POWER_bytes= 128 / 8; // Assume 128-bit vector width
static constexpr size_t POWER_dims= POWER_bytes / sizeof(int16_t);
static_assert(subdist_part % POWER_dims == 0);
static float dot_product(const int16_t *v1, const int16_t *v2, size_t len)
{
// Using vector long long for int64_t accumulation
vector long long ll_sum= {0, 0};
// Round up to process full vector, including padding
size_t base= ((len + POWER_dims - 1) / POWER_dims) * POWER_dims;
#pragma GCC unroll 4
for (size_t i= 0; i < base; i+= POWER_dims)
{
vector short x= vec_ld(0, &v1[i]);
vector short y= vec_ld(0, &v2[i]);
// Vectorized multiplication using vec_mule() and vec_mulo()
vector int product_hi= vec_mule(x, y);
vector int product_lo= vec_mulo(x, y);
// Extend vector int to vector long long for accumulation
vector long long llhi1= vec_unpackh(product_hi);
vector long long llhi2= vec_unpackl(product_hi);
vector long long lllo1= vec_unpackh(product_lo);
vector long long lllo2= vec_unpackl(product_lo);
ll_sum+= llhi1 + llhi2 + lllo1 + lllo2;
}
return static_cast<float>(static_cast<int64_t>(ll_sum[0]) +
static_cast<int64_t>(ll_sum[1]));
}
static size_t alloc_size(size_t n)
{
return alloc_header + MY_ALIGN(n * 2, POWER_bytes) + POWER_bytes - 1;
}
static FVector *align_ptr(void *ptr)
{
return (FVector*)(MY_ALIGN(((intptr)ptr) + alloc_header, POWER_bytes)
- alloc_header);
}
void fix_tail(size_t vec_len)
{
bzero(dims + vec_len, (MY_ALIGN(vec_len, POWER_dims) - vec_len) * 2);
}
#undef DEFAULT_IMPLEMENTATION
#endif
/************* no-SIMD default ******************************************/
#ifdef DEFAULT_IMPLEMENTATION
DEFAULT_IMPLEMENTATION
static float dot_product(const int16_t *v1, const int16_t *v2, size_t len)
{
int64_t d= 0;
for (size_t i= 0; i < len; i++)
d+= int32_t(v1[i]) * int32_t(v2[i]);
return static_cast<float>(d);
}
DEFAULT_IMPLEMENTATION
static size_t alloc_size(size_t n) { return alloc_header + n*2; }
DEFAULT_IMPLEMENTATION
static FVector *align_ptr(void *ptr) { return (FVector*)ptr; }
DEFAULT_IMPLEMENTATION
void fix_tail(size_t) { }
#endif
float distance_to(const FVector *other, size_t vec_len) const
{
return abs2 + other->abs2 - scale * other->scale *
dot_product(dims, other->dims, vec_len);
}
float distance_greater_than(const FVector *other, size_t vec_len, float than,
Stats *stats) const
{
float k = scale * other->scale;
float dp= dot_product(dims, other->dims, subdist_part);
float subdist= (subabs2 + other->subabs2 - k * dp)/subdist_part*vec_len;
if (subdist > than)
return subdist;
dp+= dot_product(dims+subdist_part, other->dims+subdist_part,
vec_len - subdist_part);
float dist= abs2 + other->abs2 - k * dp;
stats->subdist.add(subdist/dist);
return dist;
}
};
#pragma pack(pop)
/*
An array of pointers to graph nodes
It's mainly used to store all neighbors of a given node on a given layer.
An array is fixed size, 2*M for the zero layer, M for other layers
see MHNSW_Share::max_neighbors().
Number of neighbors is zero-padded to multiples of 8 (for SIMD Bloom filter).
Also used as a simply array of nodes in search_layer, the array size
then is defined by ef or efConstruction.
*/
struct Neighborhood: public Sql_alloc
{
FVectorNode **links;
size_t num;
FVectorNode **init(FVectorNode **ptr, size_t n)
{
num= 0;
links= ptr;
n= MY_ALIGN(n, 8);
bzero(ptr, n*sizeof(*ptr));
return ptr + n;
}
};
/* how to execute distance_greater_than() */
enum dgt_mode { NOSTAT_NOSUBDIST, STAT_NOSUBDIST, STAT_SUBDIST };
/*
One node in a graph = one row in the graph table
stores a vector itself, ref (= position) in the graph (= hlindex)
table, a ref in the main table, and an array of Neighborhood's, one
per layer.
It's lazily initialized, may know only gref, everything else is
loaded on demand.
On the other hand, on INSERT the new node knows everything except
gref - which only becomes known after ha_write_row.
Allocated on memroot in two chunks. One is the same size for all nodes
and stores FVectorNode object, gref, tref, and vector. The second
stores neighbors, all Neighborhood's together, its size depends
on the number of layers this node is on.
There can be millions of nodes in the cache and the cache size
is constrained by mhnsw_max_cache_size, so every byte matters here
*/
#pragma pack(push, 1)
class FVectorNode
{
private:
MHNSW_Share *ctx;
const FVector *make_vec(const void *v);
int alloc_neighborhood(uint8_t layer);
public:
const FVector *vec= nullptr;
Neighborhood *neighbors= nullptr;
uint8_t max_layer;
bool stored:1, deleted:1;
FVectorNode(MHNSW_Share *ctx_, const void *gref_);
FVectorNode(MHNSW_Share *ctx_, const void *tref_, uint8_t layer,
const void *vec_);
float distance_to(const FVector *other) const;
float distance_greater_than(const FVector *other, float than, dgt_mode mode,
Stats *stats) const;
int load(TABLE *graph);
int load_from_record(TABLE *graph);
int save(TABLE *graph);
size_t tref_len() const;
size_t gref_len() const;
uchar *gref() const;
uchar *tref() const;
void push_neighbor(size_t layer, FVectorNode *v);
static const uchar *get_key(const void *elem, size_t *key_len, my_bool);
};
#pragma pack(pop)
/*
Shared algorithm context. The graph.
Stored in TABLE_SHARE and on TABLE_SHARE::mem_root.
Stores the complete graph in MHNSW_Share::root,
The mapping gref->FVectorNode is in the node_cache.
Both root and node_cache are protected by a cache_lock, but it's
needed when loading nodes and is not used when the whole graph is in memory.
Graph can be traversed concurrently by different threads, as traversal
changes neither nodes nor the ctx.
Nodes can be loaded concurrently by different threads, this is protected
by a partitioned node_lock.
reference counter allows flushing the graph without interrupting
concurrent searches.
MyISAM automatically gets exclusive write access because of the TL_WRITE,
but InnoDB has to use a dedicated ctx->commit_lock for that
*/
class MHNSW_Share : public Sql_alloc
{
mysql_mutex_t cache_lock; // for node_cache and stats
mysql_mutex_t node_lock[8];
void cache_internal(FVectorNode *node)
{
DBUG_ASSERT(node->stored);
node_cache.insert(node);
}
void *alloc_node_internal()
{
return alloc_root(&root, sizeof(FVectorNode) + gref_len + tref_len
+ FVector::alloc_size(vec_len));
}
protected:
std::atomic<uint> refcnt{0};
MEM_ROOT root;
Stats stats;
Hash_set<FVectorNode> node_cache{PSI_INSTRUMENT_MEM, FVectorNode::get_key};
public:
ulonglong version= 0; // protected by commit_lock
mysql_rwlock_t commit_lock;
size_t vec_len= 0;
size_t byte_len= 0;
FVectorNode *start= 0;
const uint tref_len;
const uint gref_len;
const uint M;
metric_type metric;
bool use_subdist;
MHNSW_Share(TABLE *t)
: tref_len(t->file->ref_length), gref_len(t->hlindex->file->ref_length),
M(static_cast<uint>(t->s->key_info[t->s->keys].option_struct->M)),
metric(t->s->key_info[t->s->keys].option_struct->metric)
{
mysql_rwlock_init(PSI_INSTRUMENT_ME, &commit_lock);
mysql_mutex_init(PSI_INSTRUMENT_ME, &cache_lock, MY_MUTEX_INIT_FAST);
for (uint i=0; i < array_elements(node_lock); i++)
mysql_mutex_init(PSI_INSTRUMENT_ME, node_lock + i, MY_MUTEX_INIT_SLOW);
init_alloc_root(PSI_INSTRUMENT_MEM, &root, 1024*1024, 0, MYF(0));
}
virtual ~MHNSW_Share()
{
free_root(&root, MYF(0));
mysql_rwlock_destroy(&commit_lock);
mysql_mutex_destroy(&cache_lock);
for (size_t i=0; i < array_elements(node_lock); i++)
mysql_mutex_destroy(node_lock + i);
}
uint lock_node(FVectorNode *ptr)
{
my_hasher_st hasher= my_hasher_mysql5x();
my_hash_sort_bin(&hasher, 0, (uchar*)&ptr, sizeof(ptr));
uint ticket= hasher.m_nr1 % array_elements(node_lock);
mysql_mutex_lock(node_lock + ticket);
return ticket;
}
void unlock_node(uint ticket)
{
mysql_mutex_unlock(node_lock + ticket);
}
uint max_neighbors(size_t layer) const
{
return (layer ? 1 : 2) * M; // heuristic from the paper
}
void set_lengths(size_t len)
{
byte_len= len;
vec_len= len / sizeof(float);
use_subdist= vec_len >= subdist_part * 2;
}
static int acquire(MHNSW_Share **ctx, TABLE *table, bool for_update);
static MHNSW_Share *get_from_share(TABLE_SHARE *share, TABLE *table);
virtual void reset(TABLE_SHARE *share)
{
share->lock_share();
if (static_cast<MHNSW_Share*>(share->hlindex->hlindex_data) == this)
{
share->hlindex->hlindex_data= nullptr;
--refcnt;
}
share->unlock_share();
}
void release(TABLE *table)
{
return release(table->file->has_transactions(), table->s);
}
virtual void release(bool can_commit, TABLE_SHARE *share)
{
if (can_commit)
mysql_rwlock_unlock(&commit_lock);
if (root_size(&root) > mhnsw_max_cache_size)
reset(share);
if (--refcnt == 0)
this->~MHNSW_Share(); // XXX reuse
}
virtual MHNSW_Share *dup(bool can_commit)
{
refcnt++;
if (can_commit)
mysql_rwlock_rdlock(&commit_lock);
return this;
}
FVectorNode *get_node(const void *gref)
{
mysql_mutex_lock(&cache_lock);
FVectorNode *node= node_cache.find(gref, gref_len);
if (!node)
{
node= new (alloc_node_internal()) FVectorNode(this, gref);
cache_internal(node);
}
mysql_mutex_unlock(&cache_lock);
return node;
}
/* used on INSERT, gref isn't known, so cannot cache the node yet */
void *alloc_node()
{
mysql_mutex_lock(&cache_lock);
auto p= alloc_node_internal();
mysql_mutex_unlock(&cache_lock);
return p;
}
/* explicitly cache the node after alloc_node() */
void cache_node(FVectorNode *node)
{
mysql_mutex_lock(&cache_lock);
cache_internal(node);
mysql_mutex_unlock(&cache_lock);
}
/* find the node without creating, only used on merging trx->ctx */
FVectorNode *find_node(const void *gref)
{
mysql_mutex_lock(&cache_lock);
FVectorNode *node= node_cache.find(gref, gref_len);
mysql_mutex_unlock(&cache_lock);
return node;
}
void *alloc_neighborhood(size_t max_layer)
{
mysql_mutex_lock(&cache_lock);
auto p= alloc_root(&root, sizeof(Neighborhood)*(max_layer+1) +
sizeof(FVectorNode*)*(MY_ALIGN(M, 4)*2 + MY_ALIGN(M,8)*max_layer));
mysql_mutex_unlock(&cache_lock);
return p;
}
void read_stats(Stats *out)
{
mysql_mutex_lock(&cache_lock);
*out= stats;
mysql_mutex_unlock(&cache_lock);
}
void set_stats(size_t graph_size)
{
mysql_mutex_lock(&cache_lock);
stats.graph_size= graph_size;
mysql_mutex_unlock(&cache_lock);
}
void add_to_stats(const Stats &addend)
{
mysql_mutex_lock(&cache_lock);
stats.graph_size+= addend.graph_size;
stats.diameter= std::max(stats.diameter, addend.diameter);
stats.ef_power= std::max(stats.ef_power, addend.ef_power);
stats.subdist.add(addend.subdist);
mysql_mutex_unlock(&cache_lock);
}
};
/*
This is a non-shared context that exists within one transaction.
At the end of the transaction it's either discarded (on rollback)
or merged into the shared ctx (on commit).
trx's are stored in thd->ha_data[] in a single-linked list,
one instance of trx per TABLE_SHARE and allocated on the
thd->transaction->mem_root
*/
class MHNSW_Trx : public MHNSW_Share
{
public:
MDL_ticket *table_id;
bool list_of_nodes_is_lost= false;
MHNSW_Trx *next= nullptr;
MHNSW_Trx(TABLE *table) : MHNSW_Share(table), table_id(table->mdl_ticket) {}
void reset(TABLE_SHARE *) override
{
node_cache.clear();
free_root(&root, MYF(0));
start= nullptr;
list_of_nodes_is_lost= true;
}
void release(bool, TABLE_SHARE *) override
{
if (--refcnt == 0 && root_size(&root) > mhnsw_max_cache_size)
reset(nullptr);
}
virtual MHNSW_Share *dup(bool) override
{
refcnt++;
return this;
}
static MHNSW_Trx *get_from_thd(TABLE *table, bool for_update);
// it's okay in a transaction-local cache, there's no concurrent access
Hash_set<FVectorNode> &get_cache() { return node_cache; }
static transaction_participant tp;
static int do_commit(THD *thd, bool);
static int do_savepoint_rollback(THD *thd, void *);
static int do_rollback(THD *thd, bool);
static int do_prepare(THD *thd, bool);
};
struct transaction_participant MHNSW_Trx::tp=
{
0, 0, 0,
nullptr, /* close_connection */
[](THD *, void *){ return 0; }, /* savepoint_set */
MHNSW_Trx::do_savepoint_rollback,
[](THD *thd){ return true; }, /*savepoint_rollback_can_release_mdl*/
nullptr, /*savepoint_release*/
MHNSW_Trx::do_commit, MHNSW_Trx::do_rollback,
MHNSW_Trx::do_prepare, /* prepare */
nullptr, /* recover */
nullptr, nullptr, /* commit/rollback_by_xid */
nullptr, nullptr, /* recover_rollback_by_xid/recovery_done */
nullptr, nullptr, nullptr, /* snapshot, commit/prepare_ordered */
nullptr, nullptr /* checkpoint, versioned */
};
int MHNSW_Trx::do_savepoint_rollback(THD *thd, void *)
{
for (auto trx= static_cast<MHNSW_Trx*>(thd_get_ha_data(thd, &tp));
trx; trx= trx->next)
trx->reset(nullptr);
return 0;
}
int MHNSW_Trx::do_rollback(THD *thd, bool all)
{
if (!all && thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
return do_savepoint_rollback(thd, nullptr);
MHNSW_Trx *trx_next;
for (auto trx= static_cast<MHNSW_Trx*>(thd_get_ha_data(thd, &tp));
trx; trx= trx_next)
{
trx_next= trx->next;
trx->~MHNSW_Trx();
}
thd_set_ha_data(current_thd, &tp, nullptr);
return 0;
}
int MHNSW_Trx::do_commit(THD *thd, bool all)
{
if (!all && thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
return 0;
MHNSW_Trx *trx_next;
for (auto trx= static_cast<MHNSW_Trx*>(thd_get_ha_data(thd, &tp));
trx; trx= trx_next)
{
trx_next= trx->next;
if (trx->table_id)
{
const MDL_key *key= trx->table_id->get_key();
LEX_CSTRING db= {key->db_name(), key->db_name_length()},
tbl= {key->name(), key->name_length()};
TABLE_LIST tl;
tl.init_one_table(&db, &tbl, nullptr, TL_IGNORE);
TABLE_SHARE *share= tdc_acquire_share(thd, &tl, GTS_TABLE, nullptr);
if (share)
{
auto ctx= share->hlindex ? MHNSW_Share::get_from_share(share, nullptr)
: nullptr;
if (ctx)
{
mysql_rwlock_wrlock(&ctx->commit_lock);
ctx->version++;
if (trx->list_of_nodes_is_lost)
ctx->reset(share);
else
{
// consider copying nodes from trx to shared cache when it makes
// sense. for ann_benchmarks it does not.
// also, consider flushing only changed nodes (a flag in the node)
for (FVectorNode &from : trx->get_cache())
if (FVectorNode *node= ctx->find_node(from.gref()))
node->vec= nullptr;
ctx->start= nullptr;
}
ctx->release(true, share);
}
tdc_release_share(share);
}
}
trx->~MHNSW_Trx();
}
thd_set_ha_data(current_thd, &tp, nullptr);
return 0;
}
int MHNSW_Trx::do_prepare(THD *thd, bool)
{
/* Explicit XA is not supported yet */
return thd->transaction->xid_state.is_explicit_XA()
? HA_ERR_UNSUPPORTED : 0;
}
MHNSW_Trx *MHNSW_Trx::get_from_thd(TABLE *table, bool for_update)
{
if (!table->file->has_transactions())
return NULL;
THD *thd= table->in_use;
auto trx= static_cast<MHNSW_Trx*>(thd_get_ha_data(thd, &tp));
if (!for_update && !trx)
return NULL;
while (trx && trx->table_id != table->mdl_ticket) trx= trx->next;
if (!trx)
{
trx= new (&thd->transaction->mem_root) MHNSW_Trx(table);
trx->next= static_cast<MHNSW_Trx*>(thd_get_ha_data(thd, &tp));
thd_set_ha_data(thd, &tp, trx);
if (!trx->next)
{
if (thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
trans_register_ha(thd, true, &tp, 0);
trans_register_ha(thd, false, &tp, 0);
}
}
trx->refcnt++;
return trx;
}
MHNSW_Share *MHNSW_Share::get_from_share(TABLE_SHARE *share, TABLE *table)
{
share->lock_share();
auto ctx= static_cast<MHNSW_Share*>(share->hlindex->hlindex_data);
if (!ctx && table)
{
ctx= new (&share->hlindex->mem_root) MHNSW_Share(table);
if (!ctx) return nullptr;
share->hlindex->hlindex_data= ctx;
ctx->refcnt++;
}
if (ctx)
ctx->refcnt++;
share->unlock_share();
return ctx;
}
int MHNSW_Share::acquire(MHNSW_Share **ctx, TABLE *table, bool for_update)
{
TABLE *graph= table->hlindex;
if (!(*ctx= MHNSW_Trx::get_from_thd(table, for_update)))
{
*ctx= MHNSW_Share::get_from_share(table->s, table);
if (table->file->has_transactions())
mysql_rwlock_rdlock(&(*ctx)->commit_lock);
}
if ((*ctx)->start)
return 0;
if (int err= graph->file->ha_index_init(IDX_LAYER, 1))
return err;
int err= graph->file->ha_index_last(graph->record[0]);
graph->file->ha_index_end();
if (err)
return err;
graph->file->position(graph->record[0]);
(*ctx)->set_lengths(FVector::data_to_value_size(graph->field[FIELD_VEC]->value_length()));
if (int err= graph->file->info(HA_STATUS_VARIABLE))
return err;
(*ctx)->set_stats(graph->file->stats.records);
auto node= (*ctx)->get_node(graph->file->ref);
if ((err= node->load_from_record(graph)))
return err;
(*ctx)->start= node; // set the shared start only when node is fully loaded
return 0;
}
const FVector *FVector::create(const MHNSW_Share *ctx, void *mem, const void *src)
{
float scale=0, *v= (float *)src;
for (size_t i= 0; i < ctx->vec_len; i++)
scale= std::max(scale, std::abs(get_float(v + i)));
FVector *vec= align_ptr(mem);
vec->scale= scale ? scale/32767 : 1;
if (std::round(scale/vec->scale) > 32767)
vec->scale= std::nextafter(vec->scale, FLT_MAX);
for (size_t i= 0; i < ctx->vec_len; i++)
vec->dims[i] = static_cast<int16_t>(std::round(get_float(v + i) / vec->scale));
vec->postprocess(ctx->use_subdist, ctx->vec_len);
if (ctx->metric == COSINE)
{
if (vec->abs2 > 0.0f)
{
vec->scale/= std::sqrt(2*vec->abs2);
vec->subabs2/= 2*vec->abs2;
}
vec->abs2= 0.5f;
}
return vec;
}
/* copy the vector, preprocessed as needed */
const FVector *FVectorNode::make_vec(const void *v)
{
return FVector::create(ctx, tref() + tref_len(), v);
}
FVectorNode::FVectorNode(MHNSW_Share *ctx_, const void *gref_)
: ctx(ctx_), stored(true), deleted(false)
{
memcpy(gref(), gref_, gref_len());
}
FVectorNode::FVectorNode(MHNSW_Share *ctx_, const void *tref_, uint8_t layer,
const void *vec_)
: ctx(ctx_), stored(false), deleted(false)
{
DBUG_ASSERT(tref_);
memset(gref(), 0xff, gref_len()); // important: larger than any real gref
memcpy(tref(), tref_, tref_len());
vec= make_vec(vec_);
alloc_neighborhood(layer);
}
float FVectorNode::distance_to(const FVector *other) const
{
return vec->distance_to(other, ctx->vec_len);
}
float FVectorNode::distance_greater_than(const FVector *other, float than,
dgt_mode mode, Stats *stats) const
{
static constexpr float mul[3]= {0, 10, subdist_margin };
if (mode == NOSTAT_NOSUBDIST)
return distance_to(other);
return vec->distance_greater_than(other, ctx->vec_len,
than*mul[mode], stats);
}
int FVectorNode::alloc_neighborhood(uint8_t layer)
{
if (neighbors)
return 0;
max_layer= layer;
neighbors= (Neighborhood*)ctx->alloc_neighborhood(layer);
auto ptr= (FVectorNode**)(neighbors + (layer+1));
for (size_t i= 0; i <= layer; i++)
ptr= neighbors[i].init(ptr, ctx->max_neighbors(i));
return 0;
}
int FVectorNode::load(TABLE *graph)
{
if (likely(vec))
return 0;
DBUG_ASSERT(stored);
// trx: consider loading nodes from shared, when it makes sense
// for ann_benchmarks it does not
if (int err= graph->file->ha_rnd_pos(graph->record[0], gref()))
return err;
return load_from_record(graph);
}
int FVectorNode::load_from_record(TABLE *graph)
{
DBUG_ASSERT(ctx->byte_len);
uint ticket= ctx->lock_node(this);
SCOPE_EXIT([this, ticket](){ ctx->unlock_node(ticket); });
if (vec)
return 0;
String buf, *v= graph->field[FIELD_TREF]->val_str(&buf);
deleted= graph->field[FIELD_TREF]->is_null();
if (!deleted)
{