-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathsqlite-vector.c
More file actions
1834 lines (1489 loc) · 67.2 KB
/
sqlite-vector.c
File metadata and controls
1834 lines (1489 loc) · 67.2 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
//
// sqlite-vector.c
// sqlitevector
//
// Created by Marco Bambini on 16/06/25.
//
#include "fp16/fp16.h"
#include "sqlite-vector.h"
#include "distance-cpu.h"
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#ifdef _WIN32
char *strcasestr(const char *haystack, const char *needle) {
if (!haystack || !needle) return NULL;
if (!*needle) return (char *)haystack;
for (; *haystack; ++haystack) {
const char *h = haystack;
const char *n = needle;
while (*h && *n && tolower((unsigned char)*h) == tolower((unsigned char)*n)) {
++h;
++n;
}
if (!*n) return (char *)haystack;
}
return NULL;
}
#endif
#if defined(_WIN32) || defined(__linux__)
#include <float.h>
#endif
#ifndef SQLITE_CORE
SQLITE_EXTENSION_INIT1
#endif
#define DEBUG_VECTOR_ALWAYS(...) do {printf(__VA_ARGS__ );printf("\n");} while (0)
#if ENABLE_VECTOR_DEBUG
#define DEBUG_VECTOR(...) do {printf(__VA_ARGS__ );printf("\n");} while (0)
#else
#define DEBUG_VECTOR(...)
#endif
#define SKIP_SPACES(_p) while (*(_p) && isspace((unsigned char)*(_p))) (_p)++
#define TRIM_TRAILING(_start, _len) while ((_len) > 0 && isspace((unsigned char)(_start)[(_len) - 1])) (_len)--
#define DEFAULT_MAX_MEMORY 30*1024*1024
#define MAX_TABLES 128
#define STATIC_SQL_SIZE 2048
#define INT64_TO_INT8PTR(_val, _ptr) do { \
(_ptr)[0] = (int8_t)(((_val) >> 0) & 0xFF); \
(_ptr)[1] = (int8_t)(((_val) >> 8) & 0xFF); \
(_ptr)[2] = (int8_t)(((_val) >> 16) & 0xFF); \
(_ptr)[3] = (int8_t)(((_val) >> 24) & 0xFF); \
(_ptr)[4] = (int8_t)(((_val) >> 32) & 0xFF); \
(_ptr)[5] = (int8_t)(((_val) >> 40) & 0xFF); \
(_ptr)[6] = (int8_t)(((_val) >> 48) & 0xFF); \
(_ptr)[7] = (int8_t)(((_val) >> 56) & 0xFF); \
} while(0)
#define INT64_FROM_INT8PTR(_ptr) \
((int64_t)((uint8_t)(_ptr)[0]) | \
((int64_t)((uint8_t)(_ptr)[1]) << 8) | \
((int64_t)((uint8_t)(_ptr)[2]) << 16) | \
((int64_t)((uint8_t)(_ptr)[3]) << 24) | \
((int64_t)((uint8_t)(_ptr)[4]) << 32) | \
((int64_t)((uint8_t)(_ptr)[5]) << 40) | \
((int64_t)((uint8_t)(_ptr)[6]) << 48) | \
((int64_t)((uint8_t)(_ptr)[7]) << 56))
#define SWAP(_t, a, b) do { _t tmp = (a); (a) = (b); (b) = tmp; } while (0)
#define VECTOR_COLUMN_IDX 0
#define VECTOR_COLUMN_VECTOR 1
#define VECTOR_COLUMN_K 2
#define VECTOR_COLUMN_MEMIDX 3
#define VECTOR_COLUMN_ROWID 4
#define VECTOR_COLUMN_DISTANCE 5
#define OPTION_KEY_TYPE "type"
#define OPTION_KEY_DIMENSION "dimension"
#define OPTION_KEY_NORMALIZED "normalized"
#define OPTION_KEY_MAXMEMORY "max_memory"
#define OPTION_KEY_QUANTTYPE "quant_type"
#define OPTION_KEY_DISTANCE "distance"
typedef struct {
vector_type v_type; // vector type
int v_dim; // vector dimension
bool v_normalized; // is vector normalized ?
vector_distance v_distance; // vector distance function
vector_qtype q_type; // quantization type
uint64_t max_memory; // max memory
} vector_options;
typedef struct {
char *t_name; // table name
char *c_name; // column name
char *pk_name; // INTEGER primary key name (in case of WITHOUT ROWID tables) or rowid if NULL
vector_options options; // options parsed in key=value arguments
float scale; // computed value by quantization
float offset; // computed value by quantization
void *preloaded;
int precounter;
} table_context;
typedef struct {
table_context tables[MAX_TABLES]; // simple array of MAX_TABLES tables
int table_count; // number of entries in tables array
} vector_context;
typedef struct {
sqlite3_vtab base; // Base class - must be first
sqlite3 *db;
vector_context *ctx;
} vFullScan;
typedef struct {
sqlite3_vtab_cursor base; // Base class - must be first
sqlite3_int64 *rowids;
double *distance;
int size;
int max_index;
int row_index;
int row_count;
table_context *table;
} vFullScanCursor;
typedef bool (*keyvalue_callback)(sqlite3_context *context, void *xdata, const char *key, int key_len, const char *value, int value_len);
typedef int (*vcursor_run_callback)(sqlite3 *db, vFullScanCursor *c, const void *v1, int v1size);
typedef int (*vcursor_sort_callback)(vFullScanCursor *c);
extern distance_function_t dispatch_distance_table[VECTOR_DISTANCE_MAX][VECTOR_TYPE_MAX];
extern char *distance_backend_name;
// MARK: - FLOAT / BFLOAT16 -
// there is a native bfloat16_t ARM intrinsic
typedef uint16_t float16_t;
typedef uint16_t bfloat16_t;
static inline bfloat16_t float32_to_bfloat16 (float f) {
uint32_t bits = *(uint32_t *)&f;
return (bfloat16_t)(bits >> 16);
}
static inline float bfloat16_to_float32 (bfloat16_t bf) {
uint32_t bits = ((uint32_t)bf) << 16;
return *(float *)&bits;
}
// convert 16-bit float (IEEE-754 binary16) to 32-bit float
static inline float float16_to_float32 (uint16_t h) {
uint16_t h_exp = (h & 0x7C00u);
uint16_t h_sig = (h & 0x03FFu);
uint32_t f_sgn = ((uint32_t)h & 0x8000u) << 16;
if (h_exp == 0x0000u) {
// Zero or subnormal
if (h_sig == 0) {
return *((float*)&f_sgn); // ±0.0
} else {
// Normalize subnormal
float result = (float)(h_sig) / 1024.0f;
return *((float*)&f_sgn) ? -result : result;
}
} else if (h_exp == 0x7C00u) {
// Inf or NaN
uint32_t f_inf_nan = f_sgn | 0x7F800000u | ((uint32_t)(h_sig) << 13);
return *((float*)&f_inf_nan);
}
// Normalized number
uint32_t f_exp = ((uint32_t)(h_exp >> 10) + (127 - 15)) << 23;
uint32_t f_sig = ((uint32_t)h_sig) << 13;
uint32_t f = f_sgn | f_exp | f_sig;
float result;
*((uint32_t*)&result) = f;
return result;
}
// convert 32-bit float to 16-bit float (IEEE-754 binary16), result stored as uint16_t
static inline uint16_t float32_to_float16(float f) {
union {
uint32_t u;
float f;
} v;
v.f = f;
uint32_t f_bits = v.u;
uint32_t sign = (f_bits >> 16) & 0x8000;
int32_t exp = ((f_bits >> 23) & 0xFF) - 127 + 15;
uint32_t frac = f_bits & 0x007FFFFF;
if (exp <= 0) {
// Subnormal or underflow
if (exp < -10) {
// Too small for subnormal — flush to zero
return (uint16_t)sign;
}
// Subnormal
frac |= 0x00800000; // add implicit leading 1
int shift = 14 - exp;
uint16_t subnormal = (uint16_t)(frac >> shift);
// Round to nearest
if ((frac >> (shift - 1)) & 1) subnormal += 1;
return sign | subnormal;
} else if (exp >= 31) {
// Overflow → Inf or NaN
if (frac == 0) {
return (uint16_t)(sign | 0x7C00); // Inf
} else {
return (uint16_t)(sign | 0x7C00 | (frac >> 13)); // NaN
}
}
// Normal range: round and pack
uint16_t h_exp = (uint16_t)(exp << 10);
uint16_t h_frac = (uint16_t)(frac >> 13);
// Round to nearest
if (frac & 0x00001000) {
h_frac += 1;
if (h_frac == 0x0400) { // mantissa overflow
h_frac = 0;
h_exp += 0x0400;
if (h_exp >= 0x7C00) h_exp = 0x7C00; // clamp to Inf
}
}
return (uint16_t)(sign | h_exp | h_frac);
}
// MARK: - Quantization -
static inline void quantize_float32_to_u8 (float *v, uint8_t *q, float offset, float scale, int n) {
int i = 0;
for (; i + 3 < n; i += 4) {
float s0 = (v[i] - offset) * scale;
float s1 = (v[i + 1] - offset) * scale;
float s2 = (v[i + 2] - offset) * scale;
float s3 = (v[i + 3] - offset) * scale;
int r0 = (int)(s0 + 0.5f * (1.0f - 2.0f * (s0 < 0.0f)));
int r1 = (int)(s1 + 0.5f * (1.0f - 2.0f * (s1 < 0.0f)));
int r2 = (int)(s2 + 0.5f * (1.0f - 2.0f * (s2 < 0.0f)));
int r3 = (int)(s3 + 0.5f * (1.0f - 2.0f * (s3 < 0.0f)));
r0 = r0 > 255 ? 255 : (r0 < 0 ? 0 : r0);
r1 = r1 > 255 ? 255 : (r1 < 0 ? 0 : r1);
r2 = r2 > 255 ? 255 : (r2 < 0 ? 0 : r2);
r3 = r3 > 255 ? 255 : (r3 < 0 ? 0 : r3);
q[i] = (uint8_t)r0;
q[i + 1] = (uint8_t)r1;
q[i + 2] = (uint8_t)r2;
q[i + 3] = (uint8_t)r3;
}
// Handle remaining elements
for (; i < n; ++i) {
float scaled = (v[i] - offset) * scale;
int rounded = (int)(scaled + 0.5f * (1.0f - 2.0f * (scaled < 0.0f)));
rounded = rounded > 255 ? 255 : (rounded < 0 ? 0 : rounded);
q[i] = (uint8_t)rounded;
}
}
static inline void quantize_float16_to_u8 (const int16_t *v, uint8_t *q, float offset, float scale, int n) {
for (int i = 0; i < n; ++i) {
float x = (float16_to_float32((uint16_t)v[i]) - offset) * scale;
int r = (int)(x + 0.5f * (1.0f - 2.0f * (x < 0.0f)));
q[i] = (uint8_t)(r < 0 ? 0 : (r > 255 ? 255 : r));
}
}
static inline void quantize_bfloat16_to_u8(const int16_t *v, uint8_t *q, float offset, float scale, int n) {
for (int i = 0; i < n; ++i) {
float x = (bfloat16_to_float32(v[i]) - offset) * scale;
int r = (int)(x + 0.5f * (1.0f - 2.0f * (x < 0.0f))); // round to nearest
q[i] = (uint8_t)(r < 0 ? 0 : (r > 255 ? 255 : r)); // clamp to [0, 255]
}
}
static inline void quantize_u8_to_u8 (const uint8_t *v, uint8_t *q, float offset, float scale, int n) {
for (int i = 0; i < n; ++i) {
float x = ((float)v[i] - offset) * scale;
int r = (int)(x + 0.5f * (1.0f - 2.0f * (x < 0.0f)));
q[i] = (uint8_t)(r < 0 ? 0 : (r > 255 ? 255 : r));
}
}
static inline void quantize_i8_to_u8 (const int8_t *v, uint8_t *q, float offset, float scale, int n) {
for (int i = 0; i < n; ++i) {
float x = ((float)v[i] - offset) * scale;
int r = (int)(x + 0.5f * (1.0f - 2.0f * (x < 0.0f)));
q[i] = (uint8_t)(r < 0 ? 0 : (r > 255 ? 255 : r));
}
}
// MARK: - SQLite Utils -
bool sqlite_system_exists (sqlite3 *db, const char *name, const char *type) {
DEBUG_VECTOR("system_exists %s: %s", type, name);
sqlite3_stmt *vm = NULL;
bool result = false;
char sql[1024];
snprintf(sql, sizeof(sql), "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='%s' AND name=? COLLATE NOCASE);", type);
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto finalize;
rc = sqlite3_bind_text(vm, 1, name, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto finalize;
rc = sqlite3_step(vm);
if (rc == SQLITE_ROW) {
result = (bool)sqlite3_column_int(vm, 0);
rc = SQLITE_OK;
}
finalize:
if (rc != SQLITE_OK) DEBUG_VECTOR_ALWAYS("Error executing %s in system_exists for type %s name %s (%s).", sql, type, name, sqlite3_errmsg(db));
if (vm) sqlite3_finalize(vm);
return result;
}
bool sqlite_table_exists (sqlite3 *db, const char *name) {
return sqlite_system_exists(db, name, "table");
}
bool sqlite_trigger_exists (sqlite3 *db, const char *name) {
return sqlite_system_exists(db, name, "trigger");
}
static bool context_result_error (sqlite3_context *context, int rc, const char *format, ...) {
char buffer[4096];
va_list arg;
va_start (arg, format);
vsnprintf(buffer, sizeof(buffer), format, arg);
va_end (arg);
if (context) {
sqlite3_result_error(context, buffer, -1);
sqlite3_result_error_code(context, rc);
}
return false;
}
static const char *sqlite_type_name (int type) {
switch (type) {
case SQLITE_TEXT: return "TEXT";
case SQLITE_INTEGER: return "INTEGER";
case SQLITE_FLOAT: return "REAL";
case SQLITE_BLOB: return "BLOB";
}
return "N/A";
}
static char *sqlite_strdup (const char *str) {
if (!str) return NULL;
size_t len = strlen(str) + 1;
char *result = (char*)sqlite3_malloc((int)len);
if (result) memcpy(result, str, len);
return result;
}
bool sqlite_column_exists (sqlite3 *db, const char *table_name, const char *column_name) {
char sql[STATIC_SQL_SIZE];
sqlite3_snprintf(sizeof(sql), sql, "SELECT EXISTS(SELECT 1 FROM pragma_table_info('%q') WHERE name = ?1);", table_name);
bool result = false;
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, column_name, -1, SQLITE_STATIC);
if (sqlite3_step(stmt) == SQLITE_ROW) {
result = (sqlite3_column_int(stmt, 0) != 0);
}
}
sqlite3_finalize(stmt);
return result;
}
bool sqlite_column_is_blob (sqlite3 *db, const char *table_name, const char *column_name) {
char sql[STATIC_SQL_SIZE];
sqlite3_snprintf(sizeof(sql), sql, "SELECT type FROM pragma_table_info('%q') WHERE name=?", table_name);
bool result = false;
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, column_name, -1, SQLITE_STATIC);
if (sqlite3_step(stmt) == SQLITE_ROW) {
// see https://www.sqlite.org/datatype3.html (Determination Of Column Affinity)
const char *type = (const char *)sqlite3_column_text(stmt, 0);
result = (type == NULL) || strcasestr(type, "BLOB");
}
}
sqlite3_finalize(stmt);
return result;
}
static bool sqlite_table_is_without_rowid (sqlite3 *db, const char *table_name) {
const char *sql = "SELECT sql FROM sqlite_master WHERE type='table' AND name=?";
sqlite3_stmt *stmt = NULL;
bool result = false;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, table_name, -1, SQLITE_STATIC);
if (sqlite3_step(stmt) == SQLITE_ROW) {
const char *statement = (const char *)sqlite3_column_text(stmt, 0);
result = (statement && strcasestr(statement, "WITHOUT ROWID"));
}
}
sqlite3_finalize(stmt);
return result;
}
static char *sqlite_get_int_prikey_column (sqlite3 *db, const char *table_name) {
char sql[STATIC_SQL_SIZE];
sqlite3_snprintf(sizeof(sql), sql, "SELECT COUNT(*), type, name FROM pragma_table_info('%q') WHERE pk > 0;", table_name);
char *prikey = NULL;
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, table_name, -1, SQLITE_STATIC);
if (sqlite3_step(stmt) == SQLITE_ROW) {
int count = sqlite3_column_int(stmt, 0);
if (count == 1) {
const char *decl_type = (const char *)sqlite3_column_text(stmt, 1);
// see https://www.sqlite.org/datatype3.html (Determination Of Column Affinity)
if (strcasestr(decl_type, "INT")) {
prikey = sqlite_strdup((const char *)sqlite3_column_text(stmt, 2));
}
}
}
}
sqlite3_finalize(stmt);
return prikey;
}
static bool sqlite_sanity_check (sqlite3_context *context, const char *table_name, const char *column_name) {
// sanity check table and column name
sqlite3 *db = sqlite3_context_db_handle(context);
// table_name must exists
if (sqlite_table_exists(db, table_name) == false) {
context_result_error(context, SQLITE_ERROR, "Table '%s' does not exist.", table_name);
return false;
}
// column_name must exists
if (sqlite_column_exists(db, table_name, column_name) == false) {
context_result_error(context, SQLITE_ERROR, "Column '%s' does not exist in table '%s'.", column_name, table_name);
return false;
}
// column_name must be of type BLOB
if (sqlite_column_is_blob(db, table_name, column_name) == false) {
context_result_error(context, SQLITE_ERROR, "Column '%s' in table '%s' must be of type BLOB.", column_name, table_name);
return false;
}
return true;
}
static int sqlite_vtab_set_error (sqlite3_vtab *vtab, const char *format, ...) {
va_list arg;
va_start (arg, format);
char *err = sqlite3_vmprintf(format, arg);
va_end (arg);
vtab->zErrMsg = err;
return SQLITE_ERROR;
}
static sqlite3_int64 sqlite_read_int64 (sqlite3 *db, const char *sql) {
sqlite3_int64 value = 0;
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
if (sqlite3_step(stmt) == SQLITE_ROW) {
value = sqlite3_column_int64(stmt, 0);
}
}
sqlite3_finalize(stmt);
return value;
}
// MARK: - General Utils -
static size_t vector_type_to_size (vector_type type) {
switch (type) {
case VECTOR_TYPE_F32: return sizeof(float);
case VECTOR_TYPE_F16: return sizeof(uint16_t);
case VECTOR_TYPE_BF16: return sizeof(uint16_t/*bfloat16*/); // TODO: FIX ME
case VECTOR_TYPE_U8: return sizeof(uint8_t);
case VECTOR_TYPE_I8: return sizeof(int8_t);
}
return 0;
}
static vector_type vector_name_to_type (const char *vname) {
if (strcasecmp(vname, "FLOAT32") == 0) return VECTOR_TYPE_F32;
if (strcasecmp(vname, "FLOAT16") == 0) return VECTOR_TYPE_F16;
if (strcasecmp(vname, "FLOATB16") == 0) return VECTOR_TYPE_BF16;
if (strcasecmp(vname, "UINT8") == 0) return VECTOR_TYPE_U8;
if (strcasecmp(vname, "INT8") == 0) return VECTOR_TYPE_I8;
return 0;
}
const char *vector_type_to_name (vector_type type) {
switch (type) {
case VECTOR_TYPE_F32: return "FLOAT32";
case VECTOR_TYPE_F16: return "FLOAT16";
case VECTOR_TYPE_BF16: return "FLOATB16";
case VECTOR_TYPE_U8: return "UINT8";
case VECTOR_TYPE_I8: return "INT8";
}
return "N/A";
}
static vector_qtype quant_name_to_type (const char *qname) {
if (strcasecmp(qname, "QUANTU8") == 0) return VECTOR_QUANT_8BIT;
return 0;
}
static vector_distance distance_name_to_type (const char *dname) {
if (strcasecmp(dname, "L2") == 0) return VECTOR_DISTANCE_L2;
if (strcasecmp(dname, "EUCLIDEAN") == 0) return VECTOR_DISTANCE_L2;
if (strcasecmp(dname, "SQUARED_L2") == 0) return VECTOR_DISTANCE_SQUARED_L2;
if (strcasecmp(dname, "COSINE") == 0) return VECTOR_DISTANCE_COSINE;
if (strcasecmp(dname, "DOT") == 0) return VECTOR_DISTANCE_DOT;
if (strcasecmp(dname, "INNER") == 0) return VECTOR_DISTANCE_DOT;
if (strcasecmp(dname, "L1") == 0) return VECTOR_DISTANCE_L1;
if (strcasecmp(dname, "MANHATTAN") == 0) return VECTOR_DISTANCE_L1;
return 0;
}
const char *vector_distance_to_name (vector_distance type) {
switch (type) {
case VECTOR_DISTANCE_L2: return "L2";
case VECTOR_DISTANCE_SQUARED_L2: return "L2 SQUARED";
case VECTOR_DISTANCE_COSINE: return "COSINE";
case VECTOR_DISTANCE_DOT: return "DOT";
case VECTOR_DISTANCE_L1: return "L1";
}
return "N/A";
}
static bool sanity_check_args (sqlite3_context *context, const char *func_name, int argc, sqlite3_value **argv, int ntypes, int *types) {
if (argc != ntypes) {
context_result_error(context, SQLITE_ERROR, "Function '%s' expects %d arguments, but %d were provided.", func_name, ntypes, argc);
return false;
}
for (int i=0; i<argc; ++i) {
int actual_type = sqlite3_value_type(argv[i]);
if (actual_type != types[i]) {
context_result_error(context, SQLITE_ERROR, "Function '%s': argument %d must be of type %s (got %s).", func_name, (i+1), sqlite_type_name(types[i]), sqlite_type_name(actual_type));
return false;
}
}
return true;
}
static bool parse_keyvalue_string (sqlite3_context *context, const char *str, keyvalue_callback callback, void *xdata) {
if (!str) return true;
const char *p = str;
while (*p) {
SKIP_SPACES(p);
const char *key_start = p;
while (*p && *p != '=' && *p != ',') p++;
int key_len = (int)(p - key_start);
TRIM_TRAILING(key_start, key_len);
if (*p != '=') {
// Skip malformed pair
while (*p && *p != ',') p++;
if (*p == ',') p++;
continue;
}
p++; // skip '='
SKIP_SPACES(p);
const char *val_start = p;
while (*p && *p != ',') p++;
int val_len = (int)(p - val_start);
TRIM_TRAILING(val_start, val_len);
bool rc = callback(context, xdata, key_start, key_len, val_start, val_len);
if (!rc) return rc;
if (*p == ',') p++;
}
return true;
}
static uint64_t human_to_number (const char *s) {
char *end = NULL;
double d = strtod(s, &end);
if ((d == 0) || (d == HUGE_VAL)) return 0;
// skip whitespace before suffix
SKIP_SPACES(end);
// determine multiplier from suffix
if (strncasecmp(end, "KB", 2) == 0) d *= 1024;
else if (strncasecmp(end, "MB", 2) == 0) d *= 1024 * 1024;
else if (strncasecmp(end, "GB", 2) == 0) d *= 1024 * 1024 * 1024;
else if (*end != 0) return 0; // invalid suffix
// sanity check
if (d < 0 || d > (double)INT64_MAX) return 0;
return (uint64_t)d;
}
bool vector_keyvalue_callback (sqlite3_context *context, void *xdata, const char *key, int key_len, const char *value, int value_len) {
vector_options *options = (vector_options *)xdata;
// sanity check
if (!key || key_len == 0) return false;
if (!value || value_len == 0) return false;
// debug
// printf("KEY: \"%.*s\", VALUE: \"%.*s\"\n", key_len, key, value_len, value);
// convert value to c-string
char buffer[256] = {0};
size_t len = (value_len > sizeof(buffer)-1) ? sizeof(buffer)-1 : value_len;
memcpy(buffer, value, len);
if (strncasecmp(key, OPTION_KEY_TYPE, key_len) == 0) {
vector_type type = vector_name_to_type(buffer);
if (type == 0) return context_result_error(context, SQLITE_ERROR, "Invalid vector type: '%s' is not a recognized type.", buffer);
options->v_type = type;
return true;
}
if (strncasecmp(key, OPTION_KEY_DIMENSION, key_len) == 0) {
int dimension = (int)strtol(buffer, NULL, 0);
if (dimension <= 0) return context_result_error(context, SQLITE_ERROR, "Invalid vector dimension: expected a positive integer, got '%s'.", buffer);
options->v_dim = dimension;
return true;
}
if (strncasecmp(key, OPTION_KEY_NORMALIZED, key_len) == 0) {
int normalized = (int)strtol(buffer, NULL, 0);
options->v_normalized = (normalized != 0);
return true;
}
if (strncasecmp(key, OPTION_KEY_MAXMEMORY, key_len) == 0) {
uint64_t max_memory = human_to_number(buffer);
if (max_memory >= 0) options->max_memory = (int)max_memory;
return true;
}
if (strncasecmp(key, OPTION_KEY_QUANTTYPE, key_len) == 0) {
vector_qtype type = quant_name_to_type(buffer);
if (type == 0) return context_result_error(context, SQLITE_ERROR, "Invalid quantization type: '%s' is not a recognized or supported quantization type.", buffer);
options->q_type = type;
return true;
}
if (strncasecmp(key, OPTION_KEY_DISTANCE, key_len) == 0) {
vector_distance type = distance_name_to_type(buffer);
if (type == 0) return context_result_error(context, SQLITE_ERROR, "Invalid distance name: '%s' is not a recognized or supported distance.", buffer);
options->v_distance = type;
return true;
}
// means ignore unknown keys
return true;
}
// MARK: - SQL -
static char *generate_create_quant_table (const char *table_name, const char *column_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "CREATE TABLE IF NOT EXISTS vector0_%q_%q (rowid1 INTEGER, rowid2 INTEGER, counter INTEGER, data BLOB);", table_name, column_name);
}
static char *generate_drop_quant_table (const char *table_name, const char *column_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "DROP TABLE IF EXISTS vector0_%q_%q;", table_name, column_name);
}
static char *generate_select_from_table (const char *table_name, const char *column_name, const char *pk_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "SELECT %q, %q FROM %q ORDER BY %q;", pk_name, column_name, table_name, pk_name);
}
static char *generate_select_quant_table (const char *table_name, const char *column_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "SELECT counter, data FROM vector0_%q_%q;", table_name, column_name);
}
static char *generate_memory_quant_table (const char *table_name, const char *column_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "SELECT SUM(LENGTH(data)) FROM vector0_%q_%q;", table_name, column_name);
}
static char * generate_insert_quant_table (const char *table_name, const char *column_name, char sql[STATIC_SQL_SIZE]) {
return sqlite3_snprintf(STATIC_SQL_SIZE, sql, "INSERT INTO vector0_%q_%q (rowid1, rowid2, counter, data) VALUES (?, ?, ?, ?);", table_name, column_name);
}
// MARK: - Vector Context and Options -
void *vector_context_create (void) {
vector_context *ctx = (vector_context *)sqlite3_malloc(sizeof(vector_context));
if (!ctx) return NULL;
memset(ctx, 0, sizeof(vector_context));
return (void *)ctx;
}
table_context *vector_context_lookup (vector_context *ctx, const char *table_name, const char *column_name) {
for (int i=0; i<ctx->table_count; ++i) {
// tname and cname can be NULL after adding vector_cleanup function
const char *tname = ctx->tables[i].t_name;
const char *cname = ctx->tables[i].c_name;
if (tname && cname && (strcasecmp(tname, table_name) == 0) && (strcasecmp(cname, column_name) == 0)) return &ctx->tables[i];
}
return NULL;
}
void vector_context_add (sqlite3_context *context, vector_context *ctx, const char *table_name, const char *column_name, vector_options *options) {
// check if there is a free slot
if (ctx->table_count >= MAX_TABLES) {
context_result_error(context, SQLITE_ERROR, "Cannot add table: maximum number of allowed tables reached (%d).", MAX_TABLES);
return;
}
char *t_name = sqlite_strdup(table_name);
char *c_name = sqlite_strdup(column_name);
if (!t_name || !c_name) {
context_result_error(context, SQLITE_NOMEM, "Out of memory: unable to duplicate table or column name.");
if (t_name) sqlite3_free(t_name);
if (c_name) sqlite3_free(c_name);
return;
}
char *prikey = NULL;
sqlite3 *db = sqlite3_context_db_handle(context);
bool is_without_rowid = sqlite_table_is_without_rowid(db, table_name);
prikey = (is_without_rowid == false) ? sqlite_strdup("rowid") : sqlite_get_int_prikey_column(db, table_name);
// sanity check primary key
if (!prikey) {
(is_without_rowid) ? context_result_error(context, SQLITE_NOMEM, "Out of memory: unable to duplicate rowid column name.") : context_result_error(context, SQLITE_ERROR, "WITHOUT ROWID table '%s' must have exactly one PRIMARY KEY column of type INTEGER.", table_name);
return;
}
int index = ctx->table_count;
ctx->tables[index].t_name = t_name;
ctx->tables[index].c_name = c_name;
ctx->tables[index].pk_name = prikey;
ctx->tables[index].options = *options;
ctx->table_count++;
}
void vector_options_init (vector_options *options) {
memset(options, 0, sizeof(vector_options));
options->v_type = VECTOR_TYPE_F32;
options->v_distance = VECTOR_DISTANCE_L2;
options->max_memory = DEFAULT_MAX_MEMORY;
options->q_type = VECTOR_QUANT_8BIT;
}
vector_options vector_options_create (void) {
vector_options options;
vector_options_init(&options);
return options;
}
// MARK: - Public -
static int vector_serialize_quantization (sqlite3 *db, const char *table_name, const char *column_name, uint32_t nrows, uint8_t *data, ptrdiff_t data_size, int64_t min_rowid, int64_t max_rowid) {
char sql[STATIC_SQL_SIZE];
generate_insert_quant_table(table_name, column_name, sql);
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto vector_serialize_quantization_cleanup;
rc = sqlite3_bind_int64(vm, 1, min_rowid);
if (rc != SQLITE_OK) goto vector_serialize_quantization_cleanup;
rc = sqlite3_bind_int64(vm, 2, max_rowid);
if (rc != SQLITE_OK) goto vector_serialize_quantization_cleanup;
rc = sqlite3_bind_int(vm, 3, nrows);
if (rc != SQLITE_OK) goto vector_serialize_quantization_cleanup;
rc = sqlite3_bind_blob(vm, 4, (const void *)data, (int)data_size, SQLITE_STATIC);
if (rc != SQLITE_OK) goto vector_serialize_quantization_cleanup;
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) rc = SQLITE_OK;
vector_serialize_quantization_cleanup:
if (rc != SQLITE_OK) printf("Error in vector_serialize_quantization: %s\n", sqlite3_errmsg(db));
if (vm) sqlite3_finalize(vm);
return rc;
}
static int vector_rebuild_quantization (sqlite3_context *context, const char *table_name, const char *column_name, table_context *t_ctx, vector_qtype qtype, uint64_t max_memory) {
int rc = SQLITE_NOMEM;
sqlite3_stmt *vm = NULL;
char sql[STATIC_SQL_SIZE];
sqlite3 *db = sqlite3_context_db_handle(context);
const char *pk_name = t_ctx->pk_name;
int dim = t_ctx->options.v_dim;
//vector_type type = t_ctx->options.v_type;
// compute size of a single quant, format is: rowid + quantize dimensions
int q_size = sizeof(int64_t) + (dim * sizeof(uint8_t));
// max_memory == 0 means use all required memory
if (max_memory == 0) {
char sql[STATIC_SQL_SIZE];
sqlite3_snprintf(sizeof(sql), sql, "SELECT COUNT(*) FROM %q;", table_name);
int64_t count = sqlite_read_int64(db, sql);
max_memory = (count == 0) ? DEFAULT_MAX_MEMORY : (uint64_t)(count * q_size);
}
// max number of vectors that fits in max_memory
uint32_t max_vectors = (uint32_t)(max_memory / q_size);
uint8_t *data = sqlite3_malloc64((sqlite3_uint64)(max_vectors * q_size));
uint8_t *original = data;
if (!data) goto vector_rebuild_quantization_cleanup;
// SELECT rowid, embedding FROM table
generate_select_from_table(table_name, column_name, pk_name, sql);
rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto vector_rebuild_quantization_cleanup;
// STEP 1
// find global min/max across ALL vectors
#if defined(_WIN32) || defined(__linux__)
float min_val = FLT_MAX;
float max_val = -FLT_MAX;
#else
float min_val = MAXFLOAT;
float max_val = -MAXFLOAT;
#endif
while (1) {
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) {rc = SQLITE_OK; break;}
else if (rc != SQLITE_ROW) break;
float *v = (float *)sqlite3_column_blob(vm, 1);
for (int i=0; i<dim; ++i) {
if (v[i] < min_val) min_val = v[i];
if (v[i] > max_val) max_val = v[i];
}
}
// calculate scale and offset and set table them to table context
float scale = 255.0f / (max_val - min_val);
float offset = min_val;
t_ctx->scale = scale;
t_ctx->offset = offset;
// restart processing from the beginning
rc = sqlite3_reset(vm);
if (rc != SQLITE_OK) goto vector_rebuild_quantization_cleanup;
// begin quantization (ONLY 8bit is supported in this version)
uint32_t n_processed = 0;
uint32_t tot_processed = 0;
int64_t min_rowid = 0, max_rowid = 0;
while (1) {
rc = sqlite3_step(vm);
if (rc == SQLITE_DONE) {rc = SQLITE_OK; break;}
else if (rc != SQLITE_ROW) break;
int64_t rowid = (int64_t)sqlite3_column_int64(vm, 0);
float *v = (float *)sqlite3_column_blob(vm, 1);
if (n_processed == 0) min_rowid = rowid;
// copy rowid
INT64_TO_INT8PTR(rowid, data);
data += sizeof(int64_t);
// quantize vector
quantize_float32_to_u8(v, data, offset, scale, dim);
data += (dim * sizeof(uint8_t));
max_rowid = rowid;
++n_processed;
++tot_processed;
if (n_processed == max_vectors) {
size_t batch_size = data - original; // compute actual bytes used
rc = vector_serialize_quantization(db, table_name, column_name, n_processed, original, batch_size, min_rowid, max_rowid);
if (rc != SQLITE_OK) goto vector_rebuild_quantization_cleanup;
n_processed = 0;
data = original;
}
}
// handle remaining vectors
if (n_processed > 0) {
size_t batch_size = data - original;
rc = vector_serialize_quantization(db, table_name, column_name, n_processed, original, batch_size, min_rowid, max_rowid);
}
vector_rebuild_quantization_cleanup:
if (rc != SQLITE_OK) printf("Error in vector_rebuild_quantization: %s\n", sqlite3_errmsg(db));
if (original) sqlite3_free(original);
if (vm) sqlite3_finalize(vm);
return rc;
}
static void vector_quantize (sqlite3_context *context, const char *table_name, const char *column_name, const char *arg_options) {
table_context *t_ctx = vector_context_lookup((vector_context *)sqlite3_user_data(context), table_name, column_name);
if (!t_ctx) {
context_result_error(context, SQLITE_ERROR, "Vector context not found for table '%s' and column '%s'. Ensure that vector_init() has been called before using vector_quantize().", table_name, column_name);
return;
}
int rc = SQLITE_ERROR;
char sql[STATIC_SQL_SIZE];
sqlite3 *db = sqlite3_context_db_handle(context);
rc = sqlite3_exec(db, "BEGIN;", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto quantize_cleanup;
generate_drop_quant_table(table_name, column_name, sql);
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) goto quantize_cleanup;
generate_create_quant_table(table_name, column_name, sql);
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
if (rc != SQLITE_OK) goto quantize_cleanup;
vector_options options = vector_options_create();
bool res = parse_keyvalue_string(context, arg_options, vector_keyvalue_callback, &options);
if (res == false) return;
rc = vector_rebuild_quantization(context, table_name, column_name, t_ctx, options.q_type, options.max_memory);
if (rc != SQLITE_OK) goto quantize_cleanup;
rc = sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto quantize_cleanup;
quantize_cleanup:
if (rc != SQLITE_OK) {
printf("%s", sqlite3_errmsg(db));
sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL);
sqlite3_result_error_code(context, rc);
return;
}
}
static void vector_quantize3 (sqlite3_context *context, int argc, sqlite3_value **argv) {