Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/vec1/vec1.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / vec1 / vec1.c` 13164 lines ยท 379695 bytes Raw Blame History 1 /* 2 ** 2026-02-04 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 ** This file contains the SQLite vector ANN extension "vec1". To build 14 ** as a loadable module on x86_64 with gcc: 15 ** 16 ** gcc -O3 -DNDEBUG -mavx2 -mfma vec1.c -shared -fPIC -o vec1.so 17 ** 18 ** Documentation available at: 19 ** 20 ** https://sqlite.org/vec1 21 */ 22 23 /* 24 ** The two distance metrics supported by the system. 25 */ 26 #define VEC1_DISTANCE_L2 1 27 #define VEC1_DISTANCE_COS 2 28 29 /* 30 ** Default values for training parameters. 31 */ 32 #define VEC1_TRAINING_DEFAULT_CODESIZE 0 33 #define VEC1_TRAINING_DEFAULT_NBUCKET 0 34 #define VEC1_TRAINING_DEFAULT_SVD_VERIFY 0 35 #define VEC1_TRAINING_DEFAULT_OPQ 0 36 #define VEC1_TRAINING_DEFAULT_NOPQ_ROUND 5 37 #define VEC1_TRAINING_DEFAULT_RESIDUAL 1 38 #define VEC1_TRAINING_DEFAULT_DISTANCE VEC1_DISTANCE_L2 39 40 /* 41 ** Max and min values for various parameters. 42 ** 43 ** VEC1_MAX_K: 44 ** At present, a KANN query with an index allocates K*16 bytes for 45 ** the heap data structure used to accumulate the K best matches. 46 ** In its default configuration, sqlite3_malloc() is limited to 47 ** 1GB allocations. So limit K so as to at least avoid SQLITE_NOMEM 48 ** errors in the default configuration. 49 */ 50 #define VEC1_MAX_K 32*1024*1024 51 52 /* 53 ** Software version. Returned by "SELECT vec1_info()". 54 */ 55 #define VEC1_VERSION "0.8" 56 57 /* 58 ** Values for Vec1ModelHeader.iVersion: 59 ** 60 ** VEC1_HEADER_VERSION: 61 ** Used by default, if nothing below applies. 62 ** 63 ** VEC1_HEADER_VERSION_BIN: 64 ** Used if the model uses a binary-quantizer. 65 */ 66 #define VEC1_HEADER_VERSION (0*1000 + 4) 67 #define VEC1_HEADER_VERSION_BIN (0*1000 + 7) 68 69 /* 70 ** Shadow tables version. Stored in %_config table. Corresponds to the 71 ** minimum version that matches the current shadow table setup. 72 */ 73 #define VEC1_CURRENT_FMTVERSION (0*1000 + 4) 74 75 76 #include "sqlite3.h" 77 78 /* 79 ** Unless VEC1_STATIC is defined, compile as a loadable extension. 80 */ 81 #ifndef VEC1_STATIC 82 83 # include "sqlite3ext.h" 84 SQLITE_EXTENSION_INIT3 85 86 #endif 87 88 /* System include files */ 89 # include 90 # include 91 # include 92 # include 93 # include 94 # include 95 96 /* INFINITY is C99. Fall back to HUGE_VAL for C89 compilers. */ 97 #ifndef INFINITY 98 # define INFINITY HUGE_VAL 99 #endif 100 101 /* Standard sized types. */ 102 typedef sqlite3_int64 i64; 103 typedef sqlite3_uint64 u64; 104 typedef unsigned char u8; 105 typedef unsigned int u32; 106 typedef unsigned short u16; 107 typedef float f32; 108 typedef int i32; 109 typedef char i8; 110 111 #if !defined(VEC1_TEST_SCALAR) 112 113 #define VERTICAL_SUM_GENERIC(aAcc, nAcc, I) { \ 114 int dd; \ 115 for(dd=4; dd1 ) aAcc[0] = I (aAcc[0], aAcc[1]); \ 118 } 119 120 #ifdef __AVX2__ 121 122 # define VEC1_HAVE_AVX2 1 123 124 # define VEC1_TRANSPOSE_WIDTH 32 125 # define VEC1_NTRANSPOSE_WIDTH 8 126 127 /* 128 ** Dimensions used for vec1BestMatchN() and vec1BestMatchTransposeN(). 129 */ 130 # define VEC1_MULTIMATCH_NVEC 8 131 # define VEC1_MULTIMATCH_NCENT 8 132 133 /* AVX2 builds should use transposed arrays of centroids where possible. 134 ** This avoids horizontal sums (expensive by design on AVX2) and frees 135 ** up registers, allowing more concurrent FMA and other operations. */ 136 # define VEC1_USE_TRANSPOSITION 1 137 138 /* 139 ** When assembling the covariance matrix (part of OPQ rotation training), 140 ** deal with (VEC1_COVAR_MULTIMATCH_MULT * VEC1_MULTIMATCH_NVEC) vectors 141 ** at a time. See vec1CovarianceWork() for details. 142 */ 143 # define VEC1_COVAR_MULTIMATCH_MULT 1 144 145 # include 146 147 # if defined(__FMA__) || defined(_MSC_VER) 148 /* With MSVC, __AVX2__ implies __FMA__ */ 149 # define FMADD(a,b,c) _mm256_fmadd_ps((a),(b),(c)) 150 # define FMADD64(a,b,c) _mm256_fmadd_pd((a),(b),(c)) 151 # else 152 # define FMADD(a,b,c) _mm256_add_ps((c), _mm256_mul_ps((a),(b))) 153 # define FMADD64(a,b,c) _mm256_add_pd((c), _mm256_mul_pd((a),(b))) 154 # endif 155 156 /* Load 8 unaligned floats. Or 4 unaligned doubles. */ 157 # define LOADU(a) _mm256_loadu_ps(a) 158 # define LOADU64(a) _mm256_loadu_pd(a) 159 160 /* 161 ** Parameter vec is a __m256 register containing 8 floats. Parameter 162 ** s is a float. This macro sets s to the sum of the 8 values in vec. i.e. 163 ** 164 ** s = vec[0] + vec[1] + vec[2] + vec[3] 165 ** + vec[4] + vec[5] + vec[6] + vec[7]; 166 */ 167 # define HORIZONTAL_SUM(s, vec) \ 168 { \ 169 __m128 vc_high = _mm256_extractf128_ps(vec, 1); \ 170 __m128 vc_low = _mm256_castps256_ps128(vec); \ 171 __m128 vc128 = _mm_add_ps(vc_high, vc_low); \ 172 vc128 = _mm_hadd_ps(vc128, vc128); \ 173 vc128 = _mm_hadd_ps(vc128, vc128); \ 174 s = _mm_cvtss_f32(vc128); \ 175 } 176 177 /* 178 ** Parameter vec is a __m256 register containing 4 doubles. Parameter 179 ** s is a double. This macro sets s to the sum of the 4 values in vec. i.e. 180 ** 181 ** s = vec[0] + vec[1] + vec[2] + vec[3] 182 */ 183 # define HORIZONTAL_SUM64(s, vec) \ 184 { \ 185 __m128d _lo = _mm256_castpd256_pd128(vec); \ 186 __m128d _hi = _mm256_extractf128_pd(vec, 1); \ 187 __m128d _sum = _mm_add_pd(_lo, _hi); \ 188 (s) = _mm_cvtsd_f64(_mm_hadd_pd(_sum, _sum)); \ 189 } 190 191 /* 192 ** aAcc[] is an nAcc element array of type _m256 containing 8 32-bit floats. 193 ** This macro sums the vectors and writes the results to aAcc[0]. 194 */ 195 # define VERTICAL_SUM(aAcc, nAcc) VERTICAL_SUM_GENERIC(aAcc,nAcc,_mm256_add_ps) 196 197 #elif defined(__aarch64__) 198 199 # define VEC1_HAVE_NEON 1 200 201 # define VEC1_TRANSPOSE_WIDTH 32 202 203 # define VEC1_MULTIMATCH_NVEC 4 204 # define VEC1_MULTIMATCH_NCENT 4 205 206 # define VEC1_COVAR_MULTIMATCH_MULT 4 207 208 # include 209 210 /* 211 ** aAcc[] is an nAcc element array of type float32x4. This macro sums the 212 ** vectors and writes the results to aAcc[0]. 213 */ 214 #define VERTICAL_SUM(aAcc, nAcc) VERTICAL_SUM_GENERIC(aAcc, nAcc, vaddq_f32) 215 216 #endif 217 218 #endif /* VEC1_TEST_SCALAR */ 219 220 221 #ifndef VEC1_TRANSPOSE_WIDTH 222 223 /* Scalar fallback. Even scalar needs transpose widths. */ 224 # define VEC1_TRANSPOSE_WIDTH 8 225 226 # define VEC1_MULTIMATCH_NVEC 4 227 # define VEC1_MULTIMATCH_NCENT 4 228 229 # define VEC1_COVAR_MULTIMATCH_MULT 1 230 231 #endif 232 233 #define VEC1_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) 234 #define VEC1_SMALLEST_INT64 (((i64)-1) - VEC1_LARGEST_INT64) 235 236 #define SWAP(T, a, b) { T tmp; tmp = a; a = b; b = tmp; } 237 238 /* 239 ** Return a hardware counter value. These are used to calculate the 240 ** percentages in the performance reports from vec1cat.qprofile and the 241 ** final progress callback from within vec1_train(). 242 */ 243 static u64 vec1HardwareTimer(void){ 244 u64 ret = 0; 245 246 #if !defined(__STRICT_ANSI__) 247 # if defined(__aarch64__) 248 __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(ret)); 249 # elif defined(__GNUC__) && defined(__x86_64__) 250 unsigned int lo, hi; 251 __asm__ __volatile__("rdtscp" : "=a"(lo), "=d"(hi) :: "%rcx"); 252 ret = ((u64)hi << 32) | lo; 253 # endif 254 #endif 255 256 return ret; 257 } 258 259 260 /* 261 ** Figure out which threading model to use. Define VEC1_THREADS_WINDOWS 262 ** to use windows threads, VEC1_THREADS_PTHREADS to use pthreads, or 263 ** neither to use no threads. 264 */ 265 #if !defined(VEC1_THREADS) || VEC1_THREADS!=0 266 # if defined(_WIN32) 267 # define VEC1_THREADS_WINDOWS 1 268 # define VEC1_THREADS 1 269 # elif defined(__unix__) || defined(__APPLE__) || defined(__linux__) 270 # define VEC1_THREADS_PTHREADS 271 # define VEC1_THREADS 1 272 # else 273 # define VEC1_THREADS 0 274 # endif 275 #endif 276 277 #define size_of_array(X) ((int)(sizeof(X)/sizeof((X)[0]))) 278 #define MAX(a,b) ((ab) ? (b) : (a)) 280 281 #define UNUSED_PARAMETER(x) (void)(x) 282 #define UNUSED_PARAMETER2(x,y) (void)(x),(void)(y) 283 284 typedef struct Vec1Tab Vec1Tab; 285 typedef struct Vec1TabList Vec1TabList; 286 287 /* 288 ** An instance of the following object is allocated when registering 289 ** the vec1 module with a database handle. A pointer is passed as the 290 ** the context pointer to sqlite3_create_module_v2(). It maintains a 291 ** list of all Vec1Tab tables attached to the database handle. 292 ** 293 ** This object does not need a mutex, as it belongs to a single db handle. 294 ** The db handle mutex ensures exclusive access. 295 */ 296 struct Vec1TabList { 297 int nRef; 298 sqlite3 *db; 299 Vec1Tab *pFirst; 300 int nThread; /* Number of threads to use for various ops */ 301 double nProbeArg; /* Default "nprobe" for queries */ 302 }; 303 304 /* 305 ** This structure represents a model-header. When serialized, the format 306 ** is a packed array of six 32-bit big-endian integers, in the order 307 ** shown in the struct below. 308 */ 309 typedef struct Vec1ModelHeader Vec1ModelHeader; 310 struct Vec1ModelHeader { 311 u32 iVersion; /* Version number currently 0004 */ 312 u32 flags; 313 u32 nElem; /* Size of vectors in elements */ 314 u32 nCodebook; /* Number of codebooks for PQ */ 315 u32 nBucket; /* Number of buckets for IVF */ 316 u32 eDistance; /* A VEC1_DISTANCE_XXX value */ 317 }; 318 #define VEC1_HEADER_SIZE (6*sizeof_u32) 319 320 /* 321 ** Candidate values for the "flags" field of a Vec1ModelHeader. As follows: 322 ** 323 ** VEC1_MODEL_INDEX: 324 ** Set for any configuration except "none". 325 ** 326 ** VEC1_MODEL_ROTATE: 327 ** Set if model includes a full rotation matrix. 328 ** 329 ** VEC1_MODEL_RESIDUAL: 330 ** Set if residual, not full, vectors are encoded. 331 ** 332 ** VEC1_MODEL_BITQUANT: 333 ** Set to use bitwise quantization instead of PQ. Compressed vectors are 334 ** a 32-bit float (the norm) followed by bitwise sketch of the vector 335 ** or residual vector. 336 ** 337 ** VEC1_MODEL_WHT: 338 ** Do Walsh Hadamard transform. 339 */ 340 #define VEC1_MODEL_INDEX 0x01 341 #define VEC1_MODEL_ROTATE 0x02 342 #define VEC1_MODEL_RESIDUAL 0x04 343 #define VEC1_MODEL_BITQUANT 0x08 344 #define VEC1_MODEL_WHT 0x10 345 346 /* 347 ** Use these instead of actual sizeof() macros to avoid signed/unsigned 348 ** compiler warnings. 349 */ 350 #define sizeof_u16 2 351 #define sizeof_u32 4 352 #define sizeof_f32 4 353 #define sizeof_f64 8 354 355 /* 356 ** The three types of vector elements (that will eventually be) supported. 357 */ 358 #define VEC1_TYPE_FLOAT32 0 359 #define VEC1_TYPE_INT32 1 360 #define VEC1_TYPE_INT8 2 361 362 /* 363 ** Maximum allowed threads for both vec1 and vec1_train(). 364 */ 365 #define VEC1_MAX_NTHREAD 128 366 367 static int vec1CorruptError(void){ 368 return SQLITE_CORRUPT_VTAB; 369 } 370 #define VEC1_CORRUPT vec1CorruptError(); 371 372 static void vec1PutU32(u8 *aBuf, u32 val){ 373 aBuf[0] = (val >> 24) & 0xFF; 374 aBuf[1] = (val >> 16) & 0xFF; 375 aBuf[2] = (val >> 8) & 0xFF; 376 aBuf[3] = (val >> 0) & 0xFF; 377 } 378 379 /* 380 ** Write a model header into buffer aBuf[]. 381 */ 382 static void vec1HeaderWrite( 383 u8 *aBuf, 384 int flags, 385 int nElem, 386 int nCodebook, 387 int nBucket, 388 int eDistance 389 ){ 390 /* VEC1_HEADER_VERSION_BIN if the model uses a binary quantizer, 391 ** VEC1_HEADER_VERSION otherwise. */ 392 u32 eHdrVersion = VEC1_HEADER_VERSION; 393 if( flags & VEC1_MODEL_BITQUANT ){ 394 eHdrVersion = VEC1_HEADER_VERSION_BIN; 395 } 396 397 vec1PutU32(&aBuf[0], eHdrVersion); 398 vec1PutU32(&aBuf[4], flags); 399 vec1PutU32(&aBuf[8], nElem); 400 vec1PutU32(&aBuf[12], nCodebook); 401 vec1PutU32(&aBuf[16], nBucket); 402 vec1PutU32(&aBuf[20], eDistance); 403 } 404 405 406 static u32 vec1GetU32(const u8 *aBuf){ 407 return (((u32)aBuf[0]) << 24) 408 + (((u32)aBuf[1]) << 16) 409 + (((u32)aBuf[2]) << 8) 410 + (((u32)aBuf[3]) << 0); 411 } 412 413 /* 414 ** Deserialize buffer aBuf into object p. 415 */ 416 static void vec1HeaderRead(const u8 *aBuf, Vec1ModelHeader *p){ 417 p->iVersion = vec1GetU32(&aBuf[0]); 418 p->flags = vec1GetU32(&aBuf[4]); 419 p->nElem = vec1GetU32(&aBuf[8]); 420 p->nCodebook = vec1GetU32(&aBuf[12]); 421 p->nBucket = vec1GetU32(&aBuf[16]); 422 p->eDistance = vec1GetU32(&aBuf[20]); 423 } 424 425 /* 426 ** Version of sqlite3_free() that can be used as a destructor function with 427 ** things like sqlite3_bind_blob(). 428 */ 429 static void vec1SqliteFree(void *x){ 430 sqlite3_free(x); 431 } 432 433 typedef struct Vec1AnnResult Vec1AnnResult; 434 struct Vec1AnnResult { 435 sqlite3_int64 iRowid; 436 double fDist; 437 }; 438 439 typedef struct Vec1AnnHeap Vec1AnnHeap; 440 struct Vec1AnnHeap { 441 Vec1AnnResult *aRes; /* Heap array */ 442 i64 nRes; /* Current number of elements */ 443 i64 nMax; /* Capacity */ 444 i64 nAlloc; /* Current allocated size of aRes[] */ 445 int rc; /* Error code (perhaps SQLITE_NOMEM) */ 446 int bStreaming; 447 double fMin; /* Current threshold for admittance */ 448 }; 449 450 typedef struct Vec1Buffer Vec1Buffer; 451 struct Vec1Buffer { 452 unsigned char *a; 453 int n; 454 int nAlloc; 455 }; 456 457 /* 458 ** Return the dot-product of vectors A and B, each d elements in size. 459 */ 460 static float vec1DotProduct( 461 int d, 462 const float *A, 463 const float *B 464 ){ 465 float sum = 0.0f; 466 int j = 0; 467 468 #ifdef VEC1_HAVE_AVX2 469 # ifndef VEC1_DOT_NACC 470 # define VEC1_DOT_NACC 4 471 # endif 472 const int nAcc = VEC1_DOT_NACC; 473 int cc; 474 475 /* Create and initialize to zero nAcc accumulator registers. */ 476 __m256 acc[VEC1_DOT_NACC]; 477 for(cc=0; cc y using row-major matrix A. 536 */ 537 static void vec1RotateVector( 538 int d, 539 const float* A, /* d x d, row-major */ 540 const float* x, /* input vector, length d */ 541 float* y /* output vector, length d */ 542 ){ 543 int i; 544 for(i=0; iaRes = (Vec1AnnResult *)sqlite3_malloc64(sizeof(Vec1AnnResult) * nAlloc); 573 if( p->aRes==0 ){ 574 return SQLITE_NOMEM; 575 } 576 p->nRes = 0; 577 p->nMax = nMax; 578 p->nAlloc = nAlloc; 579 p->bStreaming = bStreaming; 580 p->fMin = INFINITY; 581 return SQLITE_OK; 582 } 583 584 /* 585 ** A new element, element i, has just been added to the heap as a new leaf 586 ** node. This function repairs the heap by bubbling-up from the new node 587 ** to the root. 588 */ 589 static void vec1HeapBubbleUp(Vec1AnnHeap *p, int i){ 590 int idx = i; 591 while( idx>0 ){ 592 int idxParent = (idx-1)/2; 593 if( p->aRes[idxParent].fDist>p->aRes[idx].fDist ) break; 594 SWAP(Vec1AnnResult, p->aRes[idx], p->aRes[idxParent]); 595 idx = idxParent; 596 } 597 } 598 599 /* 600 ** A new element has just replaced the heap root node (i.e. the previous 601 ** entry with the largest distance in the heap has been replaced by a 602 ** smaller distance. This function repairs the heap by bubbling-down from 603 ** the new root towards the leaves. 604 */ 605 static void vec1HeapBubbleDown(Vec1AnnHeap *p){ 606 int idx = 0; 607 for(;;){ 608 int idxLeft = idx*2 + 1; 609 int idxRight = idxLeft + 1; 610 int idxMax = idx; 611 612 if( idxLeftnMax && p->aRes[idxLeft].fDist>p->aRes[idxMax].fDist ){ 613 idxMax = idxLeft; 614 } 615 if( idxRightnMax && p->aRes[idxRight].fDist>p->aRes[idxMax].fDist ){ 616 idxMax = idxRight; 617 } 618 if( idxMax==idx ) break; 619 620 SWAP(Vec1AnnResult, p->aRes[idx], p->aRes[idxMax]); 621 idx = idxMax; 622 } 623 } 624 625 /* 626 ** Add an entry to the heap structure. If the heap is already full, the 627 ** entry with the largest fDist value seen so far is discarded. 628 */ 629 static void vec1HeapInsert(Vec1AnnHeap *p, sqlite3_int64 iRowid, double fDist){ 630 if( p->nResnMax ){ 631 p->aRes[p->nRes].iRowid = iRowid; 632 p->aRes[p->nRes].fDist = fDist; 633 vec1HeapBubbleUp(p, (int)p->nRes); 634 p->nRes++; 635 }else if( p->bStreaming ){ 636 637 if( p->nRes>=p->nAlloc ){ 638 i64 nNew = p->nAlloc * 2; 639 Vec1AnnResult *aNew = 0; 640 if( p->rc==SQLITE_OK ){ 641 i64 nByte = nNew*sizeof(Vec1AnnResult); 642 aNew = (Vec1AnnResult*)sqlite3_realloc64(p->aRes, nByte); 643 } 644 if( aNew==0 ){ 645 p->rc = SQLITE_NOMEM; 646 return; 647 } 648 p->aRes = aNew; 649 p->nAlloc = nNew; 650 } 651 652 p->aRes[p->nRes].iRowid = iRowid; 653 p->aRes[p->nRes].fDist = fDist; 654 if( fDistaRes[0].fDist ){ 655 SWAP(Vec1AnnResult, p->aRes[0], p->aRes[p->nRes]); 656 vec1HeapBubbleDown(p); 657 } 658 p->nRes++; 659 }else if( fDistaRes[0].fDist ){ 660 p->aRes[0].iRowid = iRowid; 661 p->aRes[0].fDist = fDist; 662 vec1HeapBubbleDown(p); 663 p->fMin = p->aRes[0].fDist; 664 } 665 } 666 667 668 /* 669 ** Ensure there is room in the buffer for another nByte bytes of data. That 670 ** is, make sure the allocated size is at least (pBuf->n + nByte). 671 ** 672 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if an OOM error is 673 ** encountered. 674 */ 675 static int vec1BufferGrow(Vec1Buffer *pBuf, sqlite3_int64 nByte){ 676 if( nByte>pBuf->nAlloc-pBuf->n ){ 677 sqlite3_int64 nNew = pBuf->nAlloc; 678 unsigned char *aNew = 0; 679 680 if( nNew==0 ) nNew = nByte + 100; 681 while( nNew < (pBuf->n + nByte) ){ 682 nNew = nNew * 2; 683 } 684 aNew = sqlite3_realloc64(pBuf->a, nNew); 685 if( aNew==0 ){ 686 return SQLITE_NOMEM; 687 } 688 pBuf->a = aNew; 689 pBuf->nAlloc = (int)nNew; 690 } 691 692 return SQLITE_OK; 693 } 694 695 /* 696 ** Ensure that the buffer passed as the first argument has at least nByte 697 ** bytes of space allocated. 698 */ 699 static int vec1BufferSize(Vec1Buffer *pBuf, sqlite3_int64 nByte){ 700 if( nByte>pBuf->nAlloc ){ 701 u8 *aNew = sqlite3_realloc64(pBuf->a, nByte); 702 if( aNew==0 ){ 703 return SQLITE_NOMEM; 704 } 705 pBuf->a = aNew; 706 pBuf->nAlloc = (int)nByte; 707 } 708 return SQLITE_OK; 709 } 710 711 /* 712 ** Free the allocation and zero the buffer structure. 713 */ 714 static void vec1BufferFree(Vec1Buffer *pBuf){ 715 sqlite3_free(pBuf->a); 716 memset(pBuf, 0, sizeof(Vec1Buffer)); 717 } 718 719 720 /* 721 ** Set the error message in context object pCtx to the result of formatting 722 ** zFmt printf() style. 723 */ 724 static void vec1ResultErrorF( 725 sqlite3_context *pCtx, /* Context to set error in */ 726 const char *zFmt, /* printf() style format for error message */ 727 ... /* Trailing arguments for printf() */ 728 ){ 729 char *zMsg = 0; 730 va_list ap; 731 va_start(ap, zFmt); 732 zMsg = sqlite3_vmprintf(zFmt, ap); 733 va_end(ap); 734 sqlite3_result_error(pCtx, zMsg, -1); 735 sqlite3_free(zMsg); 736 } 737 738 /* 739 ** Attempt to allocate and zero a block of nByte bytes of memory. If 740 ** succesful, return a pointer to the new allocation. It is the responsibility 741 ** of the caller to eventually free the allocation using sqlite3_free(). 742 ** 743 ** If the allocation attempt fails, return 0 and leave an OOM error in 744 ** context object pCtx. 745 */ 746 static void *vec1ContextMalloc(sqlite3_context *pCtx, sqlite3_int64 nByte){ 747 void *pRet = sqlite3_malloc64(nByte); 748 if( pRet==0 ){ 749 sqlite3_result_error_nomem(pCtx); 750 }else{ 751 memset(pRet, 0, nByte); 752 } 753 return pRet; 754 } 755 756 /* 757 ** Implementation of scalar function vec1_info(). 758 */ 759 static void vec1InfoFunc( 760 sqlite3_context *pCtx, 761 int nVal, 762 sqlite3_value **aVal 763 ){ 764 char *z = 0; 765 const char *zSimd = 0; 766 const char *zThreads = 0; 767 768 UNUSED_PARAMETER2(nVal, aVal); 769 770 #if defined(VEC1_HAVE_AVX2) 771 zSimd = "AVX2"; 772 #elif defined(VEC1_HAVE_NEON) 773 zSimd = "NEON"; 774 #else 775 zSimd = "Scalar"; 776 #endif 777 778 #if VEC1_THREADS 779 zThreads = "multi-threaded"; 780 #else 781 zThreads = "single-threaded"; 782 #endif 783 784 z = sqlite3_mprintf("version %s (%s, %s)", VEC1_VERSION, zSimd, zThreads); 785 786 if( z==0 ){ 787 sqlite3_result_error_nomem(pCtx); 788 }else{ 789 sqlite3_result_text(pCtx, z, -1, vec1SqliteFree); 790 } 791 } 792 793 794 /* 795 ** Return true if character c counts as whitespace. This is used 796 ** by vec1_from_json(). 797 */ 798 static int vec1_isspace(char c){ 799 return (c==' '); 800 } 801 802 /* 803 ** Implementation of scalar function vec1_from_json(). Converts a json array 804 ** of numbers into a vector in vec1 native format (32-bit little-endian 805 ** floats). 806 */ 807 static void vec1FromJsonFunc( 808 sqlite3_context *pCtx, 809 int nVal, 810 sqlite3_value **aVal 811 ){ 812 const char *zJson = (const char*)sqlite3_value_text(aVal[0]); 813 int nJson = sqlite3_value_bytes(aVal[0]); 814 const char *p = zJson; 815 float *aVec = 0; 816 int nVec = 0; 817 818 assert( nVal==1 ); 819 UNUSED_PARAMETER(nVal); 820 821 /* vec1_from_json(NULL) returns NULL */ 822 if( sqlite3_value_type(aVal[0])==SQLITE_NULL ) return; 823 824 /* Allocate space for the return value */ 825 aVec = (float*)sqlite3_malloc(sizeof_f32*(nJson/2)); 826 if( !aVec ){ 827 sqlite3_result_error_nomem(pCtx); 828 return; 829 } 830 831 while( vec1_isspace(*p) ) p++; 832 if( *p!='[' ) goto parse_failed; 833 p++; 834 835 while( 1 ){ 836 char *p2 = 0; 837 double rVal = 0.0; 838 839 while( vec1_isspace(*p) ) p++; 840 rVal = strtod(p, &p2); 841 if( p==p2 ) goto parse_failed; 842 843 p = p2; 844 aVec[nVec] = (float)rVal; 845 nVec++; 846 847 while( vec1_isspace(*p) ) p++; 848 if( *p==']' ){ 849 p++; 850 break; 851 } 852 if( *p!=',' ) goto parse_failed; 853 p++; 854 } 855 856 while( vec1_isspace(*p) ) p++; 857 if( *p ) goto parse_failed; 858 859 sqlite3_result_blob(pCtx, (void*)aVec, nVec*sizeof_f32, vec1SqliteFree); 860 return; 861 862 parse_failed: 863 sqlite3_free(aVec); 864 sqlite3_result_error(pCtx, "error parsing json vector", -1); 865 } 866 867 /* 868 ** SQL Scalar Functions: 869 ** 870 ** vec1_to_json(BLOB) 871 ** vec1_to_json_f(BLOB) 872 ** vec1_to_json_i(BLOB) 873 */ 874 static void vec1ToJsonGeneric( 875 sqlite3_context *pCtx, 876 int eType, 877 int nBytePerElem, 878 sqlite3_value *pVal 879 ){ 880 int ii; 881 sqlite3 *db = sqlite3_context_db_handle(pCtx); 882 sqlite3_str *pStr = 0; 883 884 int n = sqlite3_value_bytes(pVal); 885 const void *a = sqlite3_value_blob(pVal); 886 887 if( n==0 || (n%nBytePerElem)!=0 ){ 888 sqlite3_result_error(pCtx, "vec1: invalid vector argument", -1); 889 return; 890 } 891 n = n / nBytePerElem; 892 893 pStr = sqlite3_str_new(db); 894 if( eType==VEC1_TYPE_FLOAT32 ){ 895 const float *aFloat = (const float*)a; 896 sqlite3_str_appendf(pStr, "[%.9g", aFloat[0]); 897 for(ii=1; ii> 56) & 0xFF; 1052 aBuf[1] = (val >> 48) & 0xFF; 1053 aBuf[2] = (val >> 40) & 0xFF; 1054 aBuf[3] = (val >> 32) & 0xFF; 1055 aBuf[4] = (val >> 24) & 0xFF; 1056 aBuf[5] = (val >> 16) & 0xFF; 1057 aBuf[6] = (val >> 8) & 0xFF; 1058 aBuf[7] = (val >> 0) & 0xFF; 1059 } 1060 1061 /* 1062 ** Read and return a 64-bit unsigned big-endian integer from buffer aBuf[]. 1063 */ 1064 static u64 vec1GetU64(const u8 *aBuf){ 1065 return (((u64)aBuf[0]) << 56) 1066 + (((u64)aBuf[1]) << 48) 1067 + (((u64)aBuf[2]) << 40) 1068 + (((u64)aBuf[3]) << 32) 1069 + (((u64)aBuf[4]) << 24) 1070 + (((u64)aBuf[5]) << 16) 1071 + (((u64)aBuf[6]) << 8) 1072 + (((u64)aBuf[7]) << 0); 1073 } 1074 1075 /* 1076 ** Subtract a2 from a1 and leave the result in aOut. i.e. 1077 ** 1078 ** aOut = a1 - a2 1079 */ 1080 static void vec1Sub(float *aOut, const float *a1, const float *a2, int n){ 1081 int i; 1082 for(i=0; i 1334 1335 /* 1336 ** Unix version of thread object. 1337 */ 1338 struct Vec1Thread { 1339 pthread_t tid; 1340 }; 1341 1342 /* 1343 ** Unix version of mutex object. 1344 */ 1345 struct Vec1Mutex { 1346 pthread_mutex_t mutex; 1347 }; 1348 1349 /* 1350 ** Unix version of condition variable. 1351 */ 1352 struct Vec1Cond { 1353 pthread_cond_t cond; 1354 }; 1355 1356 /* 1357 ** Create a new thread running xTask(pIn). If successful, set *ppThread 1358 ** to the new thread handle and return SQLITE_OK. Otherwise, if an 1359 ** error occurs, set *ppThread to 0 and return either SQLITE_ERROR 1360 ** or SQLITE_NOMEM as appropriate. 1361 */ 1362 static int vec1ThreadCreate( 1363 Vec1Thread **ppThread, 1364 void *(*xTask)(void*), 1365 void *pIn 1366 ){ 1367 Vec1Thread *p = sqlite3_malloc(sizeof(Vec1Thread)); 1368 if( p==0 ){ *ppThread = 0; return SQLITE_NOMEM; } 1369 if( pthread_create(&p->tid, 0, xTask, pIn)!=0 ){ 1370 sqlite3_free(p); 1371 *ppThread = 0; 1372 return SQLITE_ERROR; 1373 } 1374 *ppThread = p; 1375 return SQLITE_OK; 1376 } 1377 1378 /* 1379 ** Join the thread pThread. If successful set *ppOut to the value 1380 ** returned by the thread's xTask routine and return SQLITE_OK. 1381 ** Otherwise, return SQLITE_ERROR and set *ppOut to 0. 1382 ** 1383 ** The thread handle may not be used after this function has been 1384 ** called. The results of doing so are undefined. 1385 */ 1386 static int vec1ThreadJoin(Vec1Thread *pThread, void **ppOut){ 1387 int rc = SQLITE_OK; 1388 if( pthread_join(pThread->tid, ppOut)!=0 ){ 1389 rc = SQLITE_ERROR; 1390 if( ppOut ) *ppOut = 0; 1391 } 1392 sqlite3_free(pThread); 1393 return rc; 1394 } 1395 1396 /* 1397 ** Create a new mutex. If successful, set *ppMutex to the new 1398 ** mutex handle and return SQLITE_OK. Otherwise, set *ppMutex to 0 1399 ** and return an SQLite error code - SQLITE_NOMEM or SQLITE_ERROR as 1400 ** appropriate. 1401 */ 1402 static int vec1MutexCreate(Vec1Mutex **ppMutex){ 1403 Vec1Mutex *p = sqlite3_malloc(sizeof(Vec1Mutex)); 1404 if( p==0 ){ *ppMutex = 0; return SQLITE_NOMEM; } 1405 if( pthread_mutex_init(&p->mutex, 0)!=0 ){ 1406 sqlite3_free(p); 1407 *ppMutex = 0; 1408 return SQLITE_ERROR; 1409 } 1410 *ppMutex = p; 1411 return SQLITE_OK; 1412 } 1413 1414 1415 /* 1416 ** Destroy (free) the mutex passed as the only argument. 1417 */ 1418 static void vec1MutexDestroy(Vec1Mutex *pMutex){ 1419 pthread_mutex_destroy(&pMutex->mutex); 1420 sqlite3_free(pMutex); 1421 } 1422 1423 1424 /* 1425 ** Enter the mutex passed as the only argument. The results of calling 1426 ** this function on a mutex that is already held are undefined. 1427 */ 1428 static void vec1MutexEnter(Vec1Mutex *pMutex){ 1429 pthread_mutex_lock(&pMutex->mutex); 1430 } 1431 1432 1433 /* 1434 ** Leave the mutex passed as the only argument. 1435 */ 1436 static void vec1MutexLeave(Vec1Mutex *pMutex){ 1437 pthread_mutex_unlock(&pMutex->mutex); 1438 } 1439 1440 1441 /* 1442 ** Create a new posix style condition variable. 1443 */ 1444 static int vec1CondCreate(Vec1Cond **ppCond){ 1445 Vec1Cond *p = sqlite3_malloc(sizeof(Vec1Cond)); 1446 if( p==0 ){ *ppCond = 0; return SQLITE_NOMEM; } 1447 if( pthread_cond_init(&p->cond, 0)!=0 ){ 1448 sqlite3_free(p); 1449 *ppCond = 0; 1450 return SQLITE_ERROR; 1451 } 1452 *ppCond = p; 1453 return SQLITE_OK; 1454 } 1455 1456 1457 /* 1458 ** Destroy the condition variable passed as the only argument. 1459 */ 1460 static void vec1CondDestroy(Vec1Cond *pCond){ 1461 pthread_cond_destroy(&pCond->cond); 1462 sqlite3_free(pCond); 1463 } 1464 1465 /* 1466 ** Mutex pMutex must be held when this is called. It causes the 1467 ** thread to atomically relinquish the mutex and wait on the 1468 ** condition variable. When the condition is signaled by another 1469 ** thread calling vec1CondBroadcast(), this thread will reaquire 1470 ** mutex pMutex and continue. 1471 */ 1472 static void vec1CondWait(Vec1Mutex *pMutex, Vec1Cond *pCond){ 1473 pthread_cond_wait(&pCond->cond, &pMutex->mutex); 1474 } 1475 1476 /* 1477 ** Wake up threads waiting on the condition variable passed as 1478 ** the only argument. 1479 */ 1480 static void vec1CondBroadcast(Vec1Cond *pCond){ 1481 pthread_cond_broadcast(&pCond->cond); 1482 } 1483 1484 1485 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ 1486 /******************************** End Unix Pthreads *************************/ 1487 1488 1489 /********************************* Win32 Threads ****************************/ 1490 #if defined(VEC1_THREADS_WINDOWS) 1491 1492 #include 1493 1494 struct Vec1Thread { 1495 HANDLE hThread; 1496 void *(*xTask)(void*); 1497 void *pIn; 1498 void *pOut; 1499 }; 1500 1501 struct Vec1Mutex { 1502 CRITICAL_SECTION cs; 1503 }; 1504 1505 struct Vec1Cond { 1506 CONDITION_VARIABLE cv; 1507 }; 1508 1509 /* Windows thread trampoline - WINAPI calling convention */ 1510 static DWORD WINAPI vec1ThreadMain(LPVOID pArg){ 1511 Vec1Thread *p = (Vec1Thread*)pArg; 1512 p->pOut = p->xTask(p->pIn); 1513 return 0; 1514 } 1515 1516 static int vec1ThreadCreate( 1517 Vec1Thread **ppThread, 1518 void *(*xTask)(void*), 1519 void *pIn 1520 ){ 1521 Vec1Thread *p = sqlite3_malloc(sizeof(Vec1Thread)); 1522 if( p==0 ){ *ppThread = 0; return SQLITE_NOMEM; } 1523 p->xTask = xTask; 1524 p->pIn = pIn; 1525 p->pOut = 0; 1526 p->hThread = CreateThread(NULL, 0, vec1ThreadMain, p, 0, NULL); 1527 if( p->hThread==NULL ){ 1528 sqlite3_free(p); 1529 *ppThread = 0; 1530 return SQLITE_ERROR; 1531 } 1532 *ppThread = p; 1533 return SQLITE_OK; 1534 } 1535 1536 static int vec1ThreadJoin(Vec1Thread *pThread, void **ppOut){ 1537 int rc = SQLITE_OK; 1538 if( WaitForSingleObject(pThread->hThread, INFINITE)!=WAIT_OBJECT_0 ){ 1539 rc = SQLITE_ERROR; 1540 if( ppOut ) *ppOut = 0; 1541 }else{ 1542 if( ppOut ) *ppOut = pThread->pOut; 1543 } 1544 CloseHandle(pThread->hThread); 1545 sqlite3_free(pThread); 1546 return rc; 1547 } 1548 1549 static int vec1MutexCreate(Vec1Mutex **ppMutex){ 1550 Vec1Mutex *p = sqlite3_malloc(sizeof(Vec1Mutex)); 1551 if( p==0 ){ *ppMutex = 0; return SQLITE_NOMEM; } 1552 InitializeCriticalSection(&p->cs); 1553 *ppMutex = p; 1554 return SQLITE_OK; 1555 } 1556 1557 static void vec1MutexDestroy(Vec1Mutex *pMutex){ 1558 DeleteCriticalSection(&pMutex->cs); 1559 sqlite3_free(pMutex); 1560 } 1561 1562 static void vec1MutexEnter(Vec1Mutex *pMutex){ 1563 EnterCriticalSection(&pMutex->cs); 1564 } 1565 1566 static void vec1MutexLeave(Vec1Mutex *pMutex){ 1567 LeaveCriticalSection(&pMutex->cs); 1568 } 1569 1570 static int vec1CondCreate(Vec1Cond **ppCond){ 1571 Vec1Cond *p = sqlite3_malloc(sizeof(Vec1Cond)); 1572 if( p==0 ){ *ppCond = 0; return SQLITE_NOMEM; } 1573 InitializeConditionVariable(&p->cv); 1574 *ppCond = p; 1575 return SQLITE_OK; 1576 } 1577 1578 static void vec1CondDestroy(Vec1Cond *pCond){ 1579 /* Windows condition variables have no destroy function */ 1580 sqlite3_free(pCond); 1581 } 1582 1583 static void vec1CondWait(Vec1Mutex *pMutex, Vec1Cond *pCond){ 1584 SleepConditionVariableCS(&pCond->cv, &pMutex->cs, INFINITE); 1585 } 1586 1587 static void vec1CondBroadcast(Vec1Cond *pCond){ 1588 WakeAllConditionVariable(&pCond->cv); 1589 } 1590 1591 1592 1593 #endif /* SQLITE_OS_WIN_THREADS */ 1594 /******************************** End Win32 Threads *************************/ 1595 1596 /* 1597 ***************************************************************************** 1598 *****************************************************************************/ 1599 1600 typedef struct Vec1JobQueue Vec1JobQueue; 1601 1602 #if VEC1_THREADS 1603 1604 typedef struct Vec1Job Vec1Job; 1605 1606 struct Vec1Job { 1607 void *pCtx; 1608 void (*xWork)(void *pCtx); 1609 int (*xFinish)(void *pCtx, int); 1610 Vec1Job *pJobNext; 1611 }; 1612 1613 /* 1614 ** nJob is the number of jobs on either the pWaiting or pFinished list, 1615 ** or else being worked on by a thread. nJob is incremented when the 1616 ** job is added to pWaiting, decremented when it is removed from pFinished. 1617 ** Always by the main thread. 1618 */ 1619 struct Vec1JobQueue { 1620 Vec1Mutex *pMutex; 1621 Vec1Cond *pCond1; 1622 Vec1Cond *pCond2; 1623 Vec1Thread **apWorker; 1624 int nWorker; /* Number of worker threads */ 1625 int bDone; /* True if threads should exit */ 1626 int nJob; /* Total number of unfinished jobs */ 1627 1628 Vec1Job *pWaiting; /* List of jobs waiting for xWork() */ 1629 Vec1Job *pFinished; /* List of jobs waiting for xFinish() */ 1630 Vec1Job *pFree; /* List of spare Vec1Job structures */ 1631 }; 1632 1633 static void *vec1JobWorkerMain(void *pCtx){ 1634 Vec1JobQueue *p = (Vec1JobQueue*)pCtx; 1635 1636 while( 1 ){ 1637 Vec1Job *pJob = 0; 1638 1639 /* Try to find a new job to work on. */ 1640 vec1MutexEnter(p->pMutex); 1641 while( p->pWaiting==0 && p->bDone==0 ){ 1642 vec1CondWait(p->pMutex, p->pCond1); 1643 } 1644 pJob = p->pWaiting; 1645 if( pJob ) p->pWaiting = pJob->pJobNext; 1646 vec1MutexLeave(p->pMutex); 1647 1648 /* If pJob is 0, we're done. Thread should exit. */ 1649 if( pJob==0 ) break; 1650 1651 /* Do the work for this job. */ 1652 pJob->xWork(pJob->pCtx); 1653 1654 /* Put the job on the finished list. If it is currently empty, the 1655 ** main thread may be waiting. Signal it in that case. */ 1656 vec1MutexEnter(p->pMutex); 1657 if( p->pFinished==0 ) vec1CondBroadcast(p->pCond2); 1658 pJob->pJobNext = p->pFinished; 1659 p->pFinished = pJob; 1660 vec1MutexLeave(p->pMutex); 1661 } 1662 1663 return 0; 1664 } 1665 1666 static int vec1JobQueueFinishJobs(Vec1JobQueue *pQueue, int rcin){ 1667 int rc = rcin; 1668 1669 if( pQueue==0 ) return rc; 1670 1671 while( 1 ){ 1672 Vec1Job *pFin = 0; 1673 Vec1Job *pWork = 0; 1674 1675 /* Try to find a job to help with. If there is nothing, wait on pCond2. */ 1676 vec1MutexEnter(pQueue->pMutex); 1677 while( pQueue->pFinished==0 && pQueue->pWaiting==0 && pQueue->nJob>0 ){ 1678 vec1CondWait(pQueue->pMutex, pQueue->pCond2); 1679 } 1680 if( pQueue->pFinished ){ 1681 pFin = pQueue->pFinished; 1682 pQueue->pFinished = pFin->pJobNext; 1683 pQueue->nJob--; 1684 }else if( pQueue->pWaiting ){ 1685 pWork = pQueue->pWaiting; 1686 pQueue->pWaiting = pWork->pJobNext; 1687 pQueue->nJob--; 1688 } 1689 vec1MutexLeave(pQueue->pMutex); 1690 1691 if( pFin==0 && pWork==0 ) break; 1692 if( pWork ){ 1693 pWork->xWork(pWork->pCtx); 1694 pFin = pWork; 1695 } 1696 1697 { 1698 int rc2 = pFin->xFinish(pFin->pCtx, rc); 1699 if( rc==SQLITE_OK ) rc = rc2; 1700 } 1701 1702 vec1MutexEnter(pQueue->pMutex); 1703 pFin->pJobNext = pQueue->pFree; 1704 pQueue->pFree = pFin; 1705 vec1MutexLeave(pQueue->pMutex); 1706 } 1707 1708 return rc; 1709 } 1710 1711 1712 static void vec1JobQueueFree(Vec1JobQueue *pQueue){ 1713 if( pQueue ){ 1714 if( pQueue->pMutex && pQueue->pCond1 ){ 1715 int ii; 1716 vec1JobQueueFinishJobs(pQueue, SQLITE_ERROR); 1717 1718 vec1MutexEnter(pQueue->pMutex); 1719 pQueue->bDone = 1; 1720 vec1CondBroadcast(pQueue->pCond1); 1721 vec1MutexLeave(pQueue->pMutex); 1722 for(ii=0; iinWorker; ii++){ 1723 void *dummy = 0; 1724 vec1ThreadJoin(pQueue->apWorker[ii], &dummy); 1725 } 1726 } 1727 1728 if( pQueue->pMutex ) vec1MutexDestroy(pQueue->pMutex); 1729 if( pQueue->pCond1 ) vec1CondDestroy(pQueue->pCond1); 1730 if( pQueue->pCond2 ) vec1CondDestroy(pQueue->pCond2); 1731 1732 assert( pQueue->pWaiting==0 ); 1733 assert( pQueue->pFinished==0 ); 1734 assert( pQueue->pFree!=0 ); 1735 sqlite3_free(pQueue); 1736 } 1737 } 1738 1739 1740 /* 1741 ** Allocate a new job-queue. 1742 */ 1743 static Vec1JobQueue *vec1JobQueueNew(int nWorker){ 1744 int rc = SQLITE_OK; 1745 Vec1JobQueue *pNew = 0; 1746 int nJob = nWorker + 8; 1747 1748 int nByte = 1749 sizeof(Vec1JobQueue) + 1750 sizeof(Vec1Thread*)*nWorker + 1751 sizeof(Vec1Job) * nJob; 1752 1753 assert( nWorker>=0 ); 1754 pNew = (Vec1JobQueue*)vec1MallocZero(nByte); 1755 if( pNew==0 ){ 1756 rc = SQLITE_NOMEM; 1757 }else{ 1758 int ii; 1759 Vec1Job *pJob; 1760 1761 pNew->apWorker = (Vec1Thread**)&pNew[1]; 1762 pJob = (Vec1Job*)&pNew->apWorker[nWorker]; 1763 for(ii=0; iipJobNext = pNew->pFree; 1765 pNew->pFree = pJob; 1766 pJob++; 1767 } 1768 1769 rc = vec1MutexCreate(&pNew->pMutex); 1770 if( rc==SQLITE_OK ) rc = vec1CondCreate(&pNew->pCond1); 1771 if( rc==SQLITE_OK ) rc = vec1CondCreate(&pNew->pCond2); 1772 for(ii=0; rc==SQLITE_OK && iiapWorker[ii], vec1JobWorkerMain, pNew); 1774 if( rc==SQLITE_OK ){ 1775 pNew->nWorker++; 1776 } 1777 } 1778 } 1779 1780 if( rc!=SQLITE_OK ){ 1781 vec1JobQueueFree(pNew); 1782 pNew = 0; 1783 } 1784 1785 return pNew; 1786 } 1787 1788 static int vec1DummyFinal(void *pCtx, int rcin){ 1789 UNUSED_PARAMETER(pCtx); 1790 return rcin; 1791 } 1792 1793 static int vec1JobQueueAddJob( 1794 Vec1JobQueue *pQueue, 1795 void (*xWork)(void *pCtx), 1796 int (*xFinish)(void *pCtx, int), 1797 void *pCtx 1798 ){ 1799 Vec1Job *pFree = 0; 1800 Vec1Job *pFinish = 0; 1801 Vec1Job *pWork = 0; 1802 int rc = SQLITE_OK; 1803 1804 if( xFinish==0 ) xFinish = vec1DummyFinal; 1805 if( pQueue==0 ){ 1806 xWork(pCtx); 1807 return xFinish(pCtx, SQLITE_OK); 1808 } 1809 1810 /* Check if this thread needs to do any xFinish() or xWork() calls. And 1811 ** try to get a free Vec1Job object at the same time. */ 1812 vec1MutexEnter(pQueue->pMutex); 1813 1814 assert( pQueue->pWaiting || pQueue->pFree || pQueue->pFinished ); 1815 if( pQueue->pFree ){ 1816 pFree = pQueue->pFree; 1817 pQueue->pFree = pFree->pJobNext; 1818 }else if( pQueue->pFinished ){ 1819 pFinish = pQueue->pFinished; 1820 pQueue->pFinished = pFinish->pJobNext; 1821 pQueue->nJob--; 1822 }else{ 1823 pWork = pQueue->pWaiting; 1824 pQueue->pWaiting = pWork->pJobNext; 1825 pQueue->nJob--; 1826 } 1827 1828 vec1MutexLeave(pQueue->pMutex); 1829 1830 /* At most 1 of pFree, pFinish and pWork may be non NULL */ 1831 assert( (pFree!=0)+(pFinish!=0)+(pWork!=0)<=1 ); 1832 1833 if( pWork ){ 1834 pWork->xWork(pWork->pCtx); 1835 pFinish = pWork; 1836 } 1837 if( pFinish ){ 1838 rc = pFinish->xFinish(pFinish->pCtx, SQLITE_OK); 1839 pFree = pFinish; 1840 } 1841 assert( pFree ); 1842 1843 pFree->pCtx = pCtx; 1844 pFree->xWork = xWork; 1845 pFree->xFinish = xFinish; 1846 vec1MutexEnter(pQueue->pMutex); 1847 if( pQueue->pWaiting==0 ) vec1CondBroadcast(pQueue->pCond1); 1848 pFree->pJobNext = pQueue->pWaiting; 1849 pQueue->pWaiting = pFree; 1850 pQueue->nJob++; 1851 vec1MutexLeave(pQueue->pMutex); 1852 1853 return rc; 1854 } 1855 1856 #else /* VEC1_THREADS=0 */ 1857 1858 /* 1859 ** Dummy implementation of job-queue for single-threaded builds. 1860 */ 1861 static int vec1JobQueueFinishJobs(Vec1JobQueue *pQueue, int rcin){ 1862 return rcin; 1863 } 1864 static void vec1JobQueueFree(Vec1JobQueue *pQueue){} 1865 static Vec1JobQueue *vec1JobQueueNew(int a){ return 0; } 1866 static int vec1JobQueueAddJob( 1867 Vec1JobQueue *pQueue, 1868 void (*xWork)(void *pCtx), 1869 int (*xFinish)(void *pCtx, int), 1870 void *pCtx 1871 ){ 1872 xWork(pCtx); 1873 return xFinish ? xFinish(pCtx, SQLITE_OK) : SQLITE_OK; 1874 } 1875 1876 #endif 1877 1878 /* 1879 ** Minimum and maximum values allowed for the 'blocksize' command. 1880 */ 1881 #define VEC1_BLOCKSIZE_MIN 1024 1882 #define VEC1_BLOCKSIZE_MAX (16*1024*1024) 1883 1884 #define VEC1_BLOCKSIZE_DEFAULT (1024*1024) 1885 #define VEC1_BLOCKSIZE_MIN_DEFAULT (16*1024) 1886 1887 #define VEC1_VECSIZE_MIN 2 1888 #define VEC1_VECSIZE_MAX 4096 1889 1890 /* 1891 ** Number of codes in each codebook. This is always 256. 1892 */ 1893 #define VEC1_PQ_CODEBOOK_SZ 256 1894 1895 #define VEC1_MIN_CODESIZE 1 1896 #define VEC1_MAX_CODESIZE 256 1897 1898 #define VEC1_MIN_BUCKET 0 1899 #define VEC1_MAX_BUCKET 65536 1900 1901 #define VEC1_MIN_NOPQ_ROUND 1 1902 #define VEC1_MAX_NOPQ_ROUND 32 1903 1904 #define VEC1_PQ_KMEANS_NITER 30 1905 #define VEC1_PQ_KMEANS_STOPVAL 0.999 1906 1907 /* 1908 ** Minimum number of vectors required for PQ training. 1909 */ 1910 #define VEC1_PQ_TRAINING_SET_MIN (VEC1_PQ_CODEBOOK_SZ * 2) 1911 1912 #define VEC1_TRAINING_TOTAL 0 1913 #define VEC1_TRAINING_ROT_CODEBOOKS 1 1914 #define VEC1_TRAINING_ROT_COVARIANCE 2 1915 #define VEC1_TRAINING_ROT_JACOBI 3 1916 #define VEC1_TRAINING_ROT_VECTORS 4 1917 1918 #define VEC1_TRAINING_COARSE_INIT 5 1919 #define VEC1_TRAINING_COARSE_KMEANS 6 1920 1921 #define VEC1_TRAINING_RESIDUALS 7 1922 #define VEC1_TRAINING_CODEBOOKS 8 1923 1924 #define VEC1_TRAINING_NTIMER 9 1925 1926 1927 /* 1928 ** When accumulating training data, allocate space in chunks of 1929 ** VEC1_TRAINING_SZCHUNK. The number of chunks is limited only by available 1930 ** memory. 1931 */ 1932 #define VEC1_TRAINING_SZCHUNK (32*1024*1024) 1933 1934 /* 1935 ** Values for Vec1TrainCtx.eQuant 1936 */ 1937 #define VEC1_QUANTIZE_NONE 0 1938 #define VEC1_QUANTIZE_PQ 1 1939 #define VEC1_QUANTIZE_OPQ 2 1940 #define VEC1_QUANTIZE_BQ 3 1941 1942 /* 1943 ** Training vectors collected by xStep() are stored in an instance 1944 ** of this structure. 1945 */ 1946 typedef struct Vec1TrainVectors Vec1TrainVectors; 1947 struct Vec1TrainVectors { 1948 int nElem; /* Number of elements in each vector */ 1949 i64 nVec; /* Number of vectors in chunk array */ 1950 i64 nChunk; /* Number of chunks allocated so far */ 1951 i64 nVecPerChunk; /* Number of vectors in each chunk */ 1952 float **aChunk; /* Array of nChunk allocated chunks */ 1953 }; 1954 1955 /* 1956 ** Context object for the vec1_train() aggregate function. 1957 ** 1958 ** eQuant: 1959 ** A VEC1_QUANTIZE_XYZ value. Set by the "quantizer" option. 1960 ** 1961 ** nCodesize: 1962 ** For PQ or OPQ, the number of vector sub-spaces. For BQ, the number of 1963 ** bytes required to store the bit-vector. For 1 bit per dimension this 1964 ** value is set to ((d+7)/8). 1965 ** 1966 ** nBucket: 1967 ** Number of IVF buckets used by coarse quantizer. Set to 0 to disable 1968 ** coarse quant altogether. 1969 */ 1970 typedef struct Vec1TrainCtx Vec1TrainCtx; 1971 struct Vec1TrainCtx { 1972 /* Training vectors collected by xStep() */ 1973 Vec1TrainVectors tv; 1974 1975 /* Training parameters configured by json argument */ 1976 int eDistance; /* VEC1_DISTANCE_L2 or COS */ 1977 int eQuant; /* VEC1_QUANTIZE_XX value */ 1978 int nCodesize; /* Number of vector sub-spaces */ 1979 int nBucket; /* Number of IVF buckets */ 1980 1981 int bOpq; 1982 1983 int bResidual; 1984 int bSvdVerify; 1985 int bWHT; /* Use WHT transformation */ 1986 int nThread; /* Number of CPU threads to use */ 1987 int nOpqRound; /* Number of OPQ rounds */ 1988 char *zLogFunction; /* Name of user SQL function for logging */ 1989 char *zProfileFunction; /* Name of user SQL function for profile */ 1990 sqlite3_stmt *pLogStmt; /* SELECT zLogFunction(?, ?) */ 1991 1992 sqlite3_context *pCtx; /* Context object for errors */ 1993 int rc; /* Error code for training operation */ 1994 1995 /* Used for calculating "percent" value passed to "SELECT zLogFunction()" */ 1996 int nTotalWork; 1997 int nCompletedWork; 1998 1999 /* Calculated based on training parameters + size of first vector */ 2000 int nCodeElem; /* Number of elements in codebook vectors */ 2001 2002 u64 aTime[VEC1_TRAINING_NTIMER]; 2003 }; 2004 2005 #define VEC1_TRAINING_WORK_OPQ 2 2006 #define VEC1_TRAINING_WORK_COARSE1 1 2007 #define VEC1_TRAINING_WORK_COARSE2 1 2008 #define VEC1_TRAINING_WORK_CODEBOOKS 1 2009 2010 /* 2011 ** Return a pointer to the requested training vector. The results are 2012 ** undefined if parameter iVec is out of range. 2013 */ 2014 static float *vec1TrainingVector(Vec1TrainVectors *p, i64 iVec){ 2015 i64 iChunk = iVec / p->nVecPerChunk; 2016 i64 iOff = (iVec % p->nVecPerChunk) * p->nElem; 2017 return &((p->aChunk[iChunk])[iOff]); 2018 } 2019 2020 /* 2021 ** aSub[] is a vector of nCodeElem elements. aCodebook[] is a codebook of 2022 ** nCode vectors, each of nCodeElem elements. Return the index of the best 2023 ** match for aSub in aCodebook[]. 2024 */ 2025 static int vec1BestMatchSimple( 2026 const float *aCodebook, /* Codebook of nCodeElem element vectors */ 2027 int nCode, /* Number of vectors in aCodebook */ 2028 const float *aSub, /* nCodeElem element vector */ 2029 int nCodeElem, /* Size of vectors in elements */ 2030 double *pfBest /* Distance to best match */ 2031 ){ 2032 double fBestDist = INFINITY; 2033 int iBest = 0; 2034 int ii; 2035 2036 for(ii=0; ii=0 && iBestaVec, p->nElem, i) 2082 2083 typedef struct LloydsJob LloydsJob; 2084 struct LloydsJob { 2085 /* Data to train on */ 2086 Vec1TrainVectors *pVec; 2087 i64 iFirst; /* First vector for this job */ 2088 i64 iEof; /* Index of last vector +1 for this job */ 2089 2090 int nK; /* Number of centroids */ 2091 const float *aCentroid; /* Centroids */ 2092 #ifdef VEC1_USE_TRANSPOSITION 2093 float *aTrans; /* Transposed centroids */ 2094 #endif 2095 2096 /* Outputs */ 2097 double fTotal; 2098 float *aSum; 2099 i64 *aCount; 2100 }; 2101 2102 /* 2103 ** Context object for simple PRNG. See functions vec1RandomInit() and 2104 ** vec1RandomNext() for details. 2105 */ 2106 typedef struct Vec1Random Vec1Random; 2107 struct Vec1Random { 2108 u64 state; 2109 u64 inc; 2110 }; 2111 2112 static u32 vec1RandomNext(Vec1Random *p) { 2113 u32 xorshifted, rot; 2114 u64 old = p->state; 2115 p->state = old * ((((u64)0x5851F42D)<<32)|0x4C957F2D) + p->inc; 2116 xorshifted = (u32)(((old >> 18u) ^ old) >> 27u); 2117 rot = (u32)(old >> 59u); 2118 return ((xorshifted >> rot) | (xorshifted << ((32 - rot) & 31))) & 0x7FFFFFFF; 2119 } 2120 2121 static void vec1RandomInit(Vec1Random *p, u64 seed, u64 id){ 2122 p->state = 0; 2123 p->inc = (id << 1u) | 1u; 2124 vec1RandomNext(p); 2125 p->state += seed; 2126 vec1RandomNext(p); 2127 } 2128 2129 2130 typedef struct KMeansInitJob KMeansInitJob; 2131 struct KMeansInitJob { 2132 i64 iFirst; /* First vector for this job */ 2133 i64 iEof; /* Index of last vector +1 for this job */ 2134 double fTotalMin; /* Total of aMin[iFirst..iEof-1] */ 2135 2136 Vec1TrainVectors *pVec; 2137 u32 *aWeight; 2138 2139 float *aMin; 2140 int *aBest; 2141 2142 float *aCentroid; 2143 int nCentroid; 2144 int iFirstNew; 2145 }; 2146 2147 static void vec1KMeansInitWork(void *pCtx){ 2148 KMeansInitJob *p = (KMeansInitJob*)pCtx; 2149 const int nElem = p->pVec->nElem; 2150 double fTotalMin = 0.0; 2151 i64 ii; 2152 2153 for(ii=p->iFirst; iiiEof; ii++){ 2154 int jj; 2155 float *vec = vec1TrainingVector(p->pVec, ii); 2156 for(jj=p->iFirstNew; jjnCentroid; jj++){ 2157 float *cent = &p->aCentroid[jj * nElem]; 2158 float dist = (float)vec1L2Dist(vec, cent, nElem); 2159 if( jj==0 || distaMin[ii] ){ 2160 p->aMin[ii] = dist; 2161 if( p->aBest ) p->aBest[ii] = jj; 2162 } 2163 } 2164 fTotalMin += ((double)p->aMin[ii] * (p->aWeight ? p->aWeight[ii] : 1)); 2165 } 2166 2167 p->fTotalMin = fTotalMin; 2168 } 2169 2170 /* 2171 ** Macro used to assign vectors to jobs in cases where an algorithm 2172 ** parallelizes across vectors. The pJob object must have at least the 2173 ** following member: 2174 ** 2175 ** struct XyzJob { 2176 ** ... 2177 ** Vec1TrainVectors *pVec; // Training vectors to use a subset of 2178 ** i64 iFirst; // index of first vector in pVec to use 2179 ** i64 iEof; // 1 past index of last vector in pVec to use 2180 ** ... 2181 ** }; 2182 */ 2183 #define ASSIGN_VECTORS_TO_JOB(pV, pJob, iJob, nJob) \ 2184 pJob->pVec = (pV); \ 2185 pJob->iFirst = (iJob==0) ? 0 : pJob[-1].iEof; \ 2186 pJob->iEof = pJob->iFirst + ((pV)->nVec - pJob->iFirst) / (nJob - iJob); \ 2187 assert( pJob->iEof<=(pV)->nVec ); \ 2188 assert( (iJob==nJob-1)==(pJob->iEof==(pV)->nVec) ); 2189 2190 /* 2191 ** 2192 */ 2193 static int vec1KMeansInitOne( 2194 Vec1TrainVectors *pVec, 2195 u32 *aWeight, 2196 Vec1JobQueue *pQueue, /* Job queue to use (NULL -> 1 thread) */ 2197 int nK, /* Required number of outputs */ 2198 int nPerRound, /* Number of centroids per round */ 2199 int nTail, /* Number of tail rounds */ 2200 float *aOut, /* Array to populate with centroids */ 2201 u32 *aHist /* Array to populate with histogram */ 2202 ){ 2203 const int nJob = (pQueue ? pQueue->nWorker + 1 : 1); 2204 const int nElem = pVec->nElem; 2205 const int nVByte = nElem * sizeof_f32; 2206 2207 Vec1Random rnd; 2208 2209 i64 nByte; /* Bytes of space to allocate */ 2210 KMeansInitJob *aJob = 0; 2211 float *aMin = 0; 2212 int *aBest = 0; 2213 int ii; /* Loop counter for per-job loop */ 2214 int rr; /* Loop counter for per-round loop */ 2215 int nCentroid = 0; 2216 int nNewCentroid = 0; 2217 float *vec = 0; 2218 2219 vec1RandomInit(&rnd, vec1Rand31(), 0); 2220 2221 nByte = 2222 (sizeof(KMeansInitJob) * nJob) + 2223 (pVec->nVec * sizeof_f32) + 2224 (aHist ? pVec->nVec * sizeof_u32 : 0); 2225 aJob = vec1MallocZero(nByte); 2226 if( aJob==0 ){ 2227 return SQLITE_NOMEM; 2228 } 2229 aMin = (float*)&aJob[nJob]; 2230 if( aHist ){ 2231 aBest = (int*)&aMin[pVec->nVec]; 2232 } 2233 2234 for(ii=0; iiaMin = aMin; 2238 pJob->aBest = aBest; 2239 pJob->aWeight = aWeight; 2240 pJob->aCentroid = aOut; 2241 } 2242 2243 /* First centroid is allocated by random selection. */ 2244 vec = vec1TrainingVector(pVec, vec1RandomNext(&rnd)%pVec->nVec); 2245 memcpy(aOut, vec, nVByte); 2246 nCentroid = nNewCentroid = 1; 2247 2248 for(rr=1; rrnVec-1; vv++){ 2277 fTarget -= (aMin[vv] * (aWeight ? aWeight[vv] : 1)); 2278 if( fTarget<=0.0 ) break; 2279 } 2280 memcpy(&aOut[nCentroid*nElem], vec1TrainingVector(pVec, vv), nVByte); 2281 nCentroid++; 2282 }else{ 2283 /* KMeans || case */ 2284 int cc; 2285 vv = vec1RandomNext(&rnd) % pVec->nVec; 2286 for(cc=0; ccnVec; 2293 } 2294 2295 memcpy(&aOut[nCentroid*nElem], vec1TrainingVector(pVec, vv), nVByte); 2296 nCentroid++; 2297 } 2298 } 2299 } 2300 2301 if( aHist ){ 2302 i64 vv; 2303 for(vv=0; vvnVec; vv++){ 2304 aHist[aBest[vv]]++; 2305 } 2306 } 2307 2308 sqlite3_free(aJob); 2309 return SQLITE_OK; 2310 } 2311 2312 2313 static int vec1KMeansPlusPlus( 2314 Vec1TrainVectors *pVec, 2315 Vec1JobQueue *pQueue, /* Job queue to use (NULL -> 1 thread) */ 2316 int nK, /* Required number of outputs */ 2317 float *aOut /* Array to populate with centroids */ 2318 ){ 2319 const int nPerRound = 8; 2320 const int nTailRound = 32; 2321 return vec1KMeansInitOne(pVec, 0, pQueue, nK, nPerRound, nTailRound, aOut, 0); 2322 } 2323 2324 #if defined(_MSC_VER) 2325 # define VEC1_NOINLINE __declspec(noinline) 2326 #elif defined(__GNUC__) 2327 # define VEC1_NOINLINE __attribute__((noinline)) 2328 #else 2329 # define VEC1_NOINLINE 2330 #endif 2331 2332 static VEC1_NOINLINE void vec1AddInPlaceScalar( 2333 float * a1, 2334 const float * a2, 2335 int n 2336 ){ 2337 int i; 2338 for(i=0; ipVec; 2646 int nElem = pVec->nElem; 2647 i64 ii; 2648 2649 p->fTotal = 0.0f; 2650 memset(p->aSum, 0, sizeof_f32 * p->nK * nElem); 2651 memset(p->aCount, 0, sizeof(i64) * p->nK); 2652 2653 /* Loop through those vectors that are our responsibility, 2654 ** VEC1_MULTIMATCH_NVEC vectors at a time. Each iteration of this outer 2655 ** loop will compare VEC1_MULTIMATCH_NVEC training vectors to all candidate 2656 ** centroids, and update p->aCount[] and p->aSum[] with the results. */ 2657 ii = p->iFirst; 2658 for( ; ii<=(p->iEof-VEC1_MULTIMATCH_NVEC); ii+=VEC1_MULTIMATCH_NVEC){ 2659 int vv; 2660 2661 const float *aVec[VEC1_MULTIMATCH_NVEC]; 2662 int aBest[VEC1_MULTIMATCH_NVEC]; 2663 2664 /* Initialize the training vector array with the VEC1_MULTIMATCH_NVEC 2665 ** training vectors that will be considered by this loop. */ 2666 for(vv=0; vvaCentroid, p->aTrans, p->nK, aVec, aBest, &p->fTotal 2672 ); 2673 2674 /* Scalar array aBest[] now contains the index of the best centroid 2675 ** for each of the VEC1_MULTIMATCH_NVEC training vectors being considered 2676 ** by this loop. Update aCount[] and aSum[] avvordingly. */ 2677 for(vv=0; vvaCount[iBest]++; 2680 vec1AddInPlace(&p->aSum[iBest*nElem], aVec[vv], nElem); 2681 } 2682 2683 #if 0 2684 /* Check (assert) using vec1BestMatchSimple() that the fancy code above 2685 ** actually worked. */ 2686 for(vv=0; vvaCentroid, p->nK, aVec[vv], nElem, 0 2689 ); 2690 if( iBest2!=aBest[vv] ){ 2691 const float *c1 = &p->aCentroid[aBest[vv] * nElem]; 2692 const float *c2 = &p->aCentroid[iBest2 * nElem]; 2693 float d1 = vec1L2Dist(aVec[vv], c1, nElem); 2694 float d2 = vec1L2Dist(aVec[vv], c2, nElem); 2695 assert( d1==d2 2696 || (d1>=d2 && ((d1 - d2) / d1) < 0.00001) 2697 || (d2>d1 && ((d2 - d1) / d2) < 0.00001) 2698 ); 2699 } 2700 } 2701 #endif 2702 } 2703 2704 /* Scalar tail - handle training vectors that were not done above as 2705 ** part of a batch of VEC1_MULTIMATCH_NVEC. */ 2706 for(; iiiEof; ii++){ 2707 const float *aSub = vec1TrainingVector(pVec, ii); 2708 int iBest = vec1BestMatchSimple( 2709 p->aCentroid, p->nK, aSub, nElem, &p->fTotal 2710 ); 2711 assert( iBest>=0 && iBestnK ); 2712 p->aCount[iBest]++; 2713 vec1AddInPlace(&p->aSum[iBest * nElem], aSub, nElem); 2714 } 2715 } 2716 2717 /* 2718 ** Parameter aIn points to an array of centroids containing nK vectors, 2719 ** each nElem elements in size. i.e. so that element j of vector i is 2720 ** stored in aIn[i*nElem + j]. Total size of the array is nK*nElem values. 2721 ** 2722 ** Parameter aOut[] also points to an array of nK*nElem elements. This 2723 ** function populates that array with the transposed version of the codebook 2724 ** before returning. 2725 */ 2726 static void vec1CodebookTranspose( 2727 const float *aIn, /* Centroid array in on-disk format */ 2728 int nElem, /* Number of elements in each vectors */ 2729 int nWidth, /* Transpose width */ 2730 int nK, /* Number of centroids */ 2731 float *aOut /* Populate this array with transformation */ 2732 ){ 2733 int K, d; 2734 float *pOut = aOut; 2735 2736 /* If nK is not divisible by nWidth, just ignore any tail vectors. */ 2737 assert( (nK % nWidth)==0 || nWidth==VEC1_MULTIMATCH_NCENT ); 2738 nK = (nK / nWidth) * nWidth; 2739 2740 for(K=0; KpLogStmt && p->rc==SQLITE_OK ){ 2753 int percent = ((100*p->nCompletedWork) / p->nTotalWork); 2754 char *zMsg = 0; 2755 va_list ap; 2756 va_start(ap, zFmt); 2757 zMsg = sqlite3_vmprintf(zFmt, ap); 2758 va_end(ap); 2759 2760 if( zMsg==0 ){ 2761 p->rc = SQLITE_NOMEM; 2762 }else{ 2763 sqlite3_bind_int(p->pLogStmt, 1, percent); 2764 sqlite3_bind_text(p->pLogStmt, 2, zMsg, -1, SQLITE_TRANSIENT); 2765 sqlite3_step(p->pLogStmt); 2766 sqlite3_free(zMsg); 2767 p->rc = sqlite3_reset(p->pLogStmt); 2768 } 2769 2770 if( p->rc==SQLITE_NOMEM ){ 2771 sqlite3_result_error_nomem(p->pCtx); 2772 }else if( p->rc!=SQLITE_OK ){ 2773 sqlite3 *db = sqlite3_db_handle(p->pLogStmt); 2774 vec1ResultErrorF(p->pCtx, "%s", sqlite3_errmsg(db)); 2775 } 2776 } 2777 } 2778 2779 #define START_TRAINING_TIMER(p, i) { p->aTime[i] -= vec1HardwareTimer(); } 2780 #define END_TRAINING_TIMER(p, i) { p->aTime[i] += vec1HardwareTimer(); } 2781 2782 static int vec1Ann1KMeans( 2783 Vec1TrainCtx *p, /* Training data + parameters */ 2784 Vec1TrainVectors *pVec, /* Vectors to train K-Means on */ 2785 Vec1JobQueue *pQueue, /* Job-queue, or NULL for single thread */ 2786 int nK, /* Value of K in K-means */ 2787 float *aCode /* OUT: Populate this array */ 2788 ){ 2789 i64 nByte = 0; 2790 int ii; 2791 int iIter; 2792 int nElem = pVec->nElem; 2793 i64 *pCountCsr = 0; 2794 float *pSumCsr = 0; 2795 double fPrevTotal = 0.0; 2796 2797 i64 *aCount = 0; 2798 float *aSum = 0; 2799 2800 LloydsJob *aJob = 0; 2801 int rc = SQLITE_OK; 2802 int nThread = p ? p->nThread : 1; 2803 2804 /* Allocate array of jobs to use for multi-threaded Lloyd's algorithm. 2805 ** We use this even if there are no worker threads - in that case 2806 ** allocate an array of 1. The algorithm parallelizes across vectors - each 2807 ** jobs is assigned a subset of the vectors to work on. 2808 ** 2809 ** Each job requires the following working space: 2810 ** 2811 ** + aCount -> (sizeof(i64) * K) bytes 2812 ** + aSum -> (sizeof_f32 * nElem * K) bytes 2813 ** 2814 ** All aCount[] arrays are allocated before all aSum[] arrays, so that the 2815 ** 64-bit integers are correctly aligned. 2816 */ 2817 nByte = nThread * ( 2818 sizeof(LloydsJob) + 2819 nElem * nK * sizeof_f32 + /* aSum[] */ 2820 nK * sizeof(i64) /* aCount[] */ 2821 ); 2822 2823 aJob = (LloydsJob*)sqlite3_malloc64(nByte); 2824 if( aJob==0 ) return SQLITE_NOMEM; 2825 memset(aJob, 0, sizeof(LloydsJob) * nThread); 2826 2827 pCountCsr = (i64*)&aJob[nThread]; 2828 pSumCsr = (float*)&pCountCsr[(i64)nThread * nK]; 2829 2830 /* Initialize each job object in the array */ 2831 for(ii=0; iinK = nK; 2839 pJob->aCentroid = aCode; 2840 pJob->aCount = pCountCsr; 2841 pCountCsr += nK; 2842 pJob->aSum = pSumCsr; 2843 pSumCsr += (nK * nElem); 2844 } 2845 aCount = aJob[0].aCount; 2846 aSum = aJob[0].aSum; 2847 2848 #ifdef VEC1_USE_TRANSPOSITION 2849 /* If this build uses transposed arrays of centroids, allocate space 2850 ** for the array here, and give each job a pointer to it. */ 2851 aJob[0].aTrans = (float*)sqlite3_malloc64( sizeof_f32 * (nElem * nK) ); 2852 if( aJob[0].aTrans==0 ){ 2853 rc = SQLITE_NOMEM; 2854 goto vec1_kmeans_out; 2855 } 2856 for(ii=1; iinCompletedWork += VEC1_TRAINING_WORK_COARSE1; 2879 } 2880 2881 /* Initial centroids have now been chosen. So do K-means iteration to 2882 ** improve the centroids. */ 2883 if( p ){ 2884 START_TRAINING_TIMER(p, VEC1_TRAINING_COARSE_KMEANS); 2885 vec1TrainLog(p, "k-means iterations for coarse quant"); 2886 } 2887 for(iIter=0; iItereDistance==VEC1_DISTANCE_COS ){ 2919 /* If this call is training a coarse quantizer for cosine distance, 2920 ** use "spherical k-means". This means that instead of just updating 2921 ** the centroid to be the average of all points assigned to it, we 2922 ** do that and then normalize the result - so that the centroid 2923 ** remains on the surface of the unit sphere. */ 2924 memcpy(aCode, aSum, sizeof_f32 * nK * nElem); 2925 for(ii=0; ii0 ){ 2934 int iElem; 2935 for(iElem=0; iElem0 && (fTotal / fPrevTotal)>=VEC1_PQ_KMEANS_STOPVAL ){ 2948 iIter = VEC1_PQ_KMEANS_NITER; 2949 } 2950 fPrevTotal = fTotal; 2951 } 2952 if( p ){ 2953 END_TRAINING_TIMER(p, VEC1_TRAINING_COARSE_KMEANS); 2954 p->nCompletedWork += VEC1_TRAINING_WORK_COARSE2; 2955 } 2956 2957 vec1_kmeans_out: 2958 #ifdef VEC1_USE_TRANSPOSITION 2959 sqlite3_free( aJob[0].aTrans ); 2960 #endif 2961 sqlite3_free(aJob); 2962 return rc; 2963 } 2964 2965 /* 2966 ** This function is called to train a coarse quantizer from within a 2967 ** vec1_train() invocation. Output array aCentroid[], which must be 2968 ** (p->tv.nElem * p->nBucket) elements in size, is packed with 2969 ** the p->nBucket centroids to use for coarse quantization before 2970 ** returning. 2971 */ 2972 static void vec1TrainCoarseQuant( 2973 Vec1TrainCtx *p, /* Training data + parameters */ 2974 Vec1JobQueue *pQueue, /* Job-queue, or NULL for single thread */ 2975 float *aCentroid /* OUT: Populate this array */ 2976 ){ 2977 if( p->rc==SQLITE_OK ){ 2978 int rc = vec1Ann1KMeans(p, &p->tv, pQueue, p->nBucket, aCentroid); 2979 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); 2980 if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ 2981 p->rc = rc; 2982 sqlite3_result_error_nomem(p->pCtx); 2983 } 2984 } 2985 } 2986 2987 static int vec1ConfigInt( 2988 int eType, 2989 i64 iVal, /* Proposed parameter value */ 2990 int nMin, /* Minimum allowed value */ 2991 int nMax, /* Maximum allowed value */ 2992 int bAllowZero, /* True if 0 is also allowed */ 2993 const char *zName, /* Name of parameter */ 2994 char **pzErr /* OUT: Error message */ 2995 ){ 2996 int rc = SQLITE_OK; 2997 if( eType!=SQLITE_INTEGER 2998 || (!(bAllowZero && iVal==0) && (iValnMax)) 2999 ){ 3000 *pzErr = sqlite3_mprintf( 3001 "vec1: %s must be set to an integer value between %d and %d%s", 3002 zName, nMin, nMax, (bAllowZero ? ", or 0" : "") 3003 ); 3004 rc = SQLITE_ERROR; 3005 } 3006 return rc; 3007 } 3008 3009 static int vec1ConfigBool( 3010 int *pbOut, 3011 int eType, 3012 i64 iVal, 3013 const char *zName, 3014 char **pzErr 3015 ){ 3016 int rc = SQLITE_OK; 3017 if( eType==SQLITE_INTEGER && (iVal==0 || iVal==1) ){ 3018 *pbOut = (iVal!=0); 3019 }else{ 3020 *pzErr = sqlite3_mprintf("vec1: %s must be set to a boolean value", zName); 3021 rc = SQLITE_ERROR; 3022 } 3023 return rc; 3024 } 3025 3026 static int vec1ConfigEnum( 3027 int *piOpt, /* OUT: Index of selected value */ 3028 const char *zVal, /* Candidate value */ 3029 const char **azOpt, /* Array of options */ 3030 const char *zName, /* Name of parameter */ 3031 char **pzErr /* OUT: Error message */ 3032 ){ 3033 int ii; 3034 char *zErr = 0; 3035 for(ii=0; azOpt[ii]; ii++){ 3036 if( sqlite3_stricmp(zVal, azOpt[ii])==0 ){ 3037 *piOpt = ii; 3038 return SQLITE_OK; 3039 } 3040 } 3041 3042 zErr = sqlite3_mprintf("unrecognized %s '%s', should be one of", zName, zVal); 3043 for(ii=0; azOpt[ii]; ii++){ 3044 if( azOpt[ii+1] ){ 3045 zErr = sqlite3_mprintf("%z %s,", zErr, azOpt[ii]); 3046 }else{ 3047 zErr = sqlite3_mprintf("%z or %s", zErr, azOpt[ii]); 3048 } 3049 } 3050 *pzErr = zErr; 3051 return SQLITE_ERROR; 3052 } 3053 3054 static int vec1ConfigDistance( 3055 int *peDist, /* OUT: VEC1_DISTANCE_L2 or DISTANCE_COS */ 3056 const char *zVal, /* Candidate value */ 3057 char **pzErr /* OUT: Error message */ 3058 ){ 3059 const char *azDist[] = {"l2", "cos", 0}; 3060 int iOpt = 0; 3061 int rc = vec1ConfigEnum(&iOpt, zVal, azDist, "distance", pzErr); 3062 assert( VEC1_DISTANCE_L2==1 ); 3063 assert( VEC1_DISTANCE_COS==2 ); 3064 *peDist = iOpt+1; 3065 return rc; 3066 } 3067 3068 /* 3069 ** Parameter zVal points to a string that was the value for the "quantize" 3070 ** field of a training configuration object. If the string is a recognized 3071 ** value for this field, output parameter (*peQuant) is set to the 3072 ** corresponding VEC1_QUANTIZE_XXX value and SQLITE OK returned. 3073 ** 3074 ** Otherwise, if the value cannot be recognized, (*pzErr) is set to point 3075 ** to a buffer containing an English language error message and SQLITE_ERROR 3076 ** is returned. It is the responsibility of the caller to eventually free 3077 ** the (*pzErr) buffer using sqlite3_free(). The final value of (*peQuant) 3078 ** is undefined in this case. 3079 */ 3080 static int vec1ConfigQuantizer( 3081 int *peQuant, /* OUT: VEC1_QUANT_XXX value */ 3082 const char *zVal, /* Candidate value */ 3083 char **pzErr /* OUT: Error message */ 3084 ){ 3085 const char *azQuant[] = {"none", "pq", "opq", "bq", 0}; 3086 3087 assert( sqlite3_stricmp("none", azQuant[VEC1_QUANTIZE_NONE])==0 ); 3088 assert( sqlite3_stricmp("pq", azQuant[VEC1_QUANTIZE_PQ])==0 ); 3089 assert( sqlite3_stricmp("opq", azQuant[VEC1_QUANTIZE_OPQ])==0 ); 3090 assert( sqlite3_stricmp("bq", azQuant[VEC1_QUANTIZE_BQ])==0 ); 3091 3092 return vec1ConfigEnum(peQuant, zVal, azQuant, "quantizer", pzErr); 3093 } 3094 3095 static int vec1Ann1TrainCfg( 3096 void *pCtx, 3097 const char *zOpt, 3098 int eType, 3099 i64 iVal, 3100 double fVal, 3101 const char *zVal, 3102 char **pz 3103 ){ 3104 int rc = SQLITE_OK; 3105 Vec1TrainCtx *p = (Vec1TrainCtx*)pCtx; 3106 3107 const char *azOpt[] = { 3108 "distance", /* 0 */ 3109 "codesize", /* 1 */ 3110 "nbucket", /* 2 */ 3111 "quantizer", /* 3 */ 3112 3113 "nthread", /* 4 */ 3114 "svd_verify", /* 5 */ 3115 "opq", /* 6 */ 3116 "progress", /* 7 */ 3117 "residual", /* 8 */ 3118 "wht", /* 9 */ 3119 "nopq_round", /* 10 */ 3120 "profile", /* 11 */ 3121 3122 "index", /* 12 */ 3123 0 3124 }; 3125 int eOpt = -1; 3126 3127 UNUSED_PARAMETER(fVal); 3128 3129 rc = vec1ConfigEnum(&eOpt, zOpt, azOpt, "option", pz); 3130 if( rc==SQLITE_OK ){ 3131 switch( eOpt ){ 3132 case 0: assert( sqlite3_stricmp("distance", zOpt)==0 ); 3133 rc = vec1ConfigDistance(&p->eDistance, zVal, pz); 3134 break; 3135 3136 case 1: assert( sqlite3_stricmp("codesize", zOpt)==0 ); 3137 rc = vec1ConfigInt(eType, iVal, 3138 VEC1_MIN_CODESIZE, VEC1_MAX_CODESIZE, 1, zOpt, pz 3139 ); 3140 p->nCodesize = (int)iVal; 3141 break; 3142 3143 case 2: assert( sqlite3_stricmp("nbucket", zOpt)==0 ); 3144 rc = vec1ConfigInt(eType, iVal, 3145 VEC1_MIN_BUCKET, VEC1_MAX_BUCKET, 1, zOpt, pz 3146 ); 3147 p->nBucket = (int)iVal; 3148 break; 3149 3150 case 3: assert( sqlite3_stricmp("quantizer", zOpt)==0 ); 3151 rc = vec1ConfigQuantizer(&p->eQuant, zVal, pz); 3152 break; 3153 3154 case 4: assert( sqlite3_stricmp("nthread", zOpt)==0 ); 3155 rc = vec1ConfigInt(eType, iVal, 1, VEC1_MAX_NTHREAD, 0, zOpt, pz); 3156 #if VEC1_THREADS 3157 p->nThread = (int)iVal; 3158 #endif 3159 break; 3160 3161 case 5: assert( sqlite3_stricmp("svd_verify", zOpt)==0 ); 3162 rc = vec1ConfigBool(&p->bSvdVerify, eType, iVal, zOpt, pz); 3163 break; 3164 3165 case 6: assert( sqlite3_stricmp("opq", zOpt)==0 ); 3166 rc = vec1ConfigBool(&p->bOpq, eType, iVal, zOpt, pz); 3167 break; 3168 3169 case 7: assert( sqlite3_stricmp("progress", zOpt)==0 ); 3170 sqlite3_free(p->zLogFunction); 3171 p->zLogFunction = sqlite3_mprintf("%s", zVal); 3172 if( p->zLogFunction==0 ) rc = SQLITE_NOMEM; 3173 break; 3174 3175 case 8: assert( sqlite3_stricmp("residual", zOpt)==0 ); 3176 rc = vec1ConfigBool(&p->bResidual, eType, iVal, zOpt, pz); 3177 break; 3178 3179 case 9: assert( sqlite3_stricmp("wht", zOpt)==0 ); 3180 rc = vec1ConfigBool(&p->bWHT, eType, iVal, zOpt, pz); 3181 break; 3182 3183 case 10: assert( sqlite3_stricmp("nopq_round", zOpt)==0 ); 3184 rc = vec1ConfigInt(eType, iVal, 3185 VEC1_MIN_NOPQ_ROUND, VEC1_MAX_NOPQ_ROUND, 0, zOpt, pz 3186 ); 3187 p->nOpqRound = (int)iVal; 3188 break; 3189 3190 case 11: assert( sqlite3_stricmp("profile", zOpt)==0 ); 3191 sqlite3_free(p->zProfileFunction); 3192 p->zProfileFunction = sqlite3_mprintf("%s", zVal); 3193 if( p->zProfileFunction==0 ) rc = SQLITE_NOMEM; 3194 break; 3195 3196 default: assert( sqlite3_stricmp("index", zOpt)==0 ); 3197 assert( eOpt==12 ); /* index */ 3198 if( sqlite3_stricmp("trained", zVal) ){ 3199 *pz = sqlite3_mprintf( 3200 "unrecognized index '%s', should be 'trained'", zVal 3201 ); 3202 rc = SQLITE_ERROR; 3203 } 3204 break; 3205 } 3206 } 3207 3208 return rc; 3209 } 3210 3211 #define VEC1_INDEX_NONE 1 3212 #define VEC1_INDEX_FLAT 2 3213 3214 typedef struct Vec1FlatIndex Vec1FlatIndex; 3215 struct Vec1FlatIndex { 3216 int eDistance; 3217 int eIndex; 3218 }; 3219 3220 static int vec1FlatIndexCfg( 3221 void *pCtx, 3222 const char *zOpt, 3223 int eType, 3224 i64 iVal, 3225 double fVal, 3226 const char *zVal, 3227 char **pz 3228 ){ 3229 int rc = SQLITE_OK; 3230 Vec1FlatIndex *p = (Vec1FlatIndex*)pCtx; 3231 3232 UNUSED_PARAMETER(eType); 3233 UNUSED_PARAMETER(iVal); 3234 UNUSED_PARAMETER(fVal); 3235 3236 if( sqlite3_stricmp("distance", zOpt)==0 ){ 3237 rc = vec1ConfigDistance(&p->eDistance, zVal, pz); 3238 }else 3239 if( sqlite3_stricmp("index", zOpt)==0 ){ 3240 const char *azIdx[] = {"none", "flat", 0}; 3241 int iOpt = 0; 3242 rc = vec1ConfigEnum(&iOpt, zVal, azIdx, "index", pz); 3243 assert( VEC1_INDEX_NONE==1 ); 3244 assert( VEC1_INDEX_FLAT==2 ); 3245 p->eIndex = iOpt+1; 3246 }else{ 3247 *pz = sqlite3_mprintf("unknown parameter: %s", zOpt); 3248 rc = SQLITE_ERROR; 3249 } 3250 3251 return rc; 3252 } 3253 3254 /* 3255 ** aVec[] is a vector nElem elements in size. If any of these elements is 3256 ** non-finite - either NaN or an Infinity value - return SQLITE_ERROR. 3257 ** Return SQLITE_OK if all elements are finite. 3258 */ 3259 static int vec1VectorIsNonFinite(const float *aVec, int nElem){ 3260 static const u32 MASK = 0x7F800000; 3261 int ii = 0; 3262 3263 #if defined(VEC1_HAVE_AVX2) 3264 const __m256i exp_mask = _mm256_set1_epi32(MASK); 3265 for(; ii<=(nElem-8); ii+=8){ 3266 __m256i bits = _mm256_loadu_si256((__m256i*)&aVec[ii]); 3267 __m256i exp_bits = _mm256_and_si256(bits, exp_mask); 3268 __m256i nonfinite = _mm256_cmpeq_epi32(exp_bits, exp_mask); 3269 if( _mm256_movemask_ps(_mm256_castsi256_ps(nonfinite)) ){ 3270 goto error_out; 3271 } 3272 } 3273 #endif 3274 3275 #if defined(VEC1_HAVE_NEON) 3276 const uint32x4_t exp_mask = vdupq_n_u32(MASK); 3277 for(; ii<=(nElem-4); ii+=4){ 3278 uint32x4_t bits = vld1q_u32((u32*)&aVec[ii]); 3279 uint32x4_t exp_bits = vandq_u32(bits, exp_mask); 3280 uint32x4_t nonfinite = vceqq_u32(exp_bits, exp_mask); 3281 if( vmaxvq_u32(nonfinite) ){ 3282 goto error_out; 3283 } 3284 } 3285 #endif 3286 3287 for(; ii(VEC1_VECSIZE_MAX*sizeof_f32)) 3312 ){ 3313 *pzErrmsg = sqlite3_mprintf("invalid vector size: %lld bytes", nByte); 3314 return SQLITE_ERROR; 3315 } 3316 return SQLITE_OK; 3317 } 3318 3319 3320 #define VEC1_REALLOC_NVEC 10000 3321 3322 /* 3323 ** The xStep() method for the vec1_train() aggregate function: 3324 ** 3325 ** vec1_train(VECTOR, CONFIG) 3326 ** 3327 ** All that this step function does is populate the Vec1TrainCtx.aVec[] array. 3328 ** The interesting stuff happens in vec1TrainFinal(). 3329 */ 3330 static void vec1TrainStep( 3331 sqlite3_context *pCtx, 3332 int nArg, 3333 sqlite3_value **aArg 3334 ){ 3335 Vec1TabList *pList = (Vec1TabList*)sqlite3_user_data(pCtx); 3336 Vec1TrainCtx *p = 0; 3337 int n = 0; 3338 const u8 *a = 0; 3339 i64 iChunk = 0; 3340 char *zErr = 0; 3341 3342 assert( nArg==1 || nArg==2 ); 3343 p = (Vec1TrainCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 3344 if( !p ) return; 3345 3346 n = sqlite3_value_bytes(aArg[0]); 3347 a = (const u8*)sqlite3_value_blob(aArg[0]); 3348 3349 /* Check the vector is a valid size. */ 3350 if( vec1CheckVectorSize(n, &zErr) ){ 3351 vec1ResultErrorF(pCtx, "vec1_train: %z", zErr); 3352 return; 3353 } 3354 3355 /* Check there are no Inf or Nan values in the vector. */ 3356 if( vec1VectorIsNonFinite((const float*)a, (n/sizeof_f32)) ){ 3357 sqlite3_result_error(pCtx, 3358 "vec1_train: non-finite value not allowed in vector", -1 3359 ); 3360 return; 3361 } 3362 3363 /* Unless this is the first training vector, check that it is the same 3364 ** size as all the other vectors in the training set. */ 3365 if( p->tv.nElem!=0 && p->tv.nElem!=(int)(n/sizeof_f32) ){ 3366 sqlite3_result_error(pCtx, "vec1_train: bad argument", -1); 3367 return; 3368 } 3369 3370 /* If this is the first call to xStep() for this aggregate, initialize 3371 ** the various "training parameters" fields of Vec1TrainCtx. */ 3372 if( p->tv.nElem==0 ){ 3373 p->tv.nElem = n/sizeof_f32; 3374 p->tv.nVecPerChunk = (VEC1_TRAINING_SZCHUNK / (p->tv.nElem*sizeof_f32)); 3375 3376 /* Configure default values */ 3377 p->eDistance = VEC1_TRAINING_DEFAULT_DISTANCE; 3378 p->nBucket = VEC1_TRAINING_DEFAULT_NBUCKET; 3379 p->nThread = pList->nThread; 3380 p->nOpqRound = VEC1_TRAINING_DEFAULT_NOPQ_ROUND; 3381 p->bSvdVerify = VEC1_TRAINING_DEFAULT_SVD_VERIFY; 3382 p->bResidual = VEC1_TRAINING_DEFAULT_RESIDUAL; 3383 p->eQuant = -1; 3384 p->nCodesize = -1; 3385 p->bWHT = -1; 3386 p->bOpq = -1; 3387 3388 /* If a configuration object was passed, update the Vec1TrainCtx with 3389 ** its field values now. */ 3390 if( nArg==2 ){ 3391 sqlite3 *db = sqlite3_context_db_handle(pCtx); 3392 const char *zCfg = (const char*)sqlite3_value_text(aArg[1]); 3393 char *zErr = 0; 3394 int rc = vec1ParseJsonConfig(db, zCfg, vec1Ann1TrainCfg, (void*)p, &zErr); 3395 if( rc ){ 3396 if( zErr!=0 ){ 3397 vec1ResultErrorF(pCtx, "%z", zErr); 3398 }else{ 3399 sqlite3_result_error_code(pCtx, rc); 3400 } 3401 return; 3402 } 3403 } 3404 3405 /* If no quantizer was specified, select one automatically now. */ 3406 if( p->eQuant<0 ){ 3407 if( p->nCodesize<=0 ){ 3408 p->eQuant = VEC1_QUANTIZE_NONE; 3409 }else if( p->bOpq>0 ){ 3410 p->eQuant = VEC1_QUANTIZE_OPQ; 3411 }else{ 3412 p->eQuant = VEC1_QUANTIZE_PQ; 3413 } 3414 } 3415 3416 /* If no "wht" value was explicitly specified, enable the Walsh-Hadamard 3417 ** Transform for binary quantizers. Disable it for other quantizers. */ 3418 if( p->bWHT<0 ) p->bWHT = (p->eQuant==VEC1_QUANTIZE_BQ); 3419 3420 /* If no value was specified for "codesize", choose a default. This 3421 ** is 32 for PQ or OPQ, 0 for "none" quantizer, and (nElem+7)/8 for BQ. */ 3422 if( p->eQuant==VEC1_QUANTIZE_NONE ){ 3423 p->nCodesize = 0; 3424 p->bResidual = 0; 3425 }else if( p->eQuant==VEC1_QUANTIZE_BQ ){ 3426 if( p->nCodesize<=0 || p->nCodesize>=((p->tv.nElem+7)/8) ){ 3427 /* No explicit codesize. Or an explicit codesize large enough to 3428 ** use 1 bit per dimension. So do that - use 1 bit per dimension. */ 3429 p->nCodesize = (p->tv.nElem + 7) / 8; 3430 }else{ 3431 /* Explicit codesize too small for 1 bit per dimension. So use 1 bit 3432 ** for each two dimensions. */ 3433 p->nCodesize = (p->tv.nElem + 15) / 16; 3434 } 3435 }else if( p->nCodesize<=0 ){ 3436 if( p->eQuant==VEC1_QUANTIZE_PQ ){ 3437 p->nCodesize = (p->tv.nElem + 7) / 8; 3438 }else{ 3439 assert( p->eQuant==VEC1_QUANTIZE_OPQ ); 3440 p->nCodesize = 32; 3441 } 3442 } 3443 3444 if( p->eQuant==VEC1_QUANTIZE_PQ || p->eQuant==VEC1_QUANTIZE_OPQ ){ 3445 /* Usually, tv.nElem will be an integer multiple of nCodebook. In 3446 ** this case set nCodeElem is just set to (tv.nElem / nCodebook) and 3447 ** nCodebook remains as configured. 3448 ** 3449 ** Or, if tv.nElem is not a multiple of nCodebook, set nCodeElem to 3450 ** the smallest value that allows us to cover the entire vector with 3451 ** nCodebook codebooks. Then reduce nCodebook to the minimum number 3452 ** of codebooks required to cover the vector with nCodeElem 3453 ** sub-vectors. */ 3454 p->nCodeElem = ((p->tv.nElem+p->nCodesize-1) / p->nCodesize); 3455 p->nCodesize = ((p->tv.nElem+p->nCodeElem-1) / p->nCodeElem); 3456 } 3457 } 3458 3459 iChunk = (p->tv.nVec+1)/p->tv.nVecPerChunk; 3460 if( iChunk>=p->tv.nChunk ){ 3461 float **aNew = (float**)sqlite3_realloc64( 3462 p->tv.aChunk, sizeof(float*) * (iChunk+1) 3463 ); 3464 if( aNew==0 ){ 3465 sqlite3_result_error_nomem(pCtx); 3466 p->rc = SQLITE_NOMEM; 3467 return; 3468 } 3469 p->tv.aChunk = aNew; 3470 p->tv.aChunk[iChunk] = (float*)sqlite3_malloc(VEC1_TRAINING_SZCHUNK); 3471 if( p->tv.aChunk[iChunk]==0 ){ 3472 sqlite3_result_error_nomem(pCtx); 3473 p->rc = SQLITE_NOMEM; 3474 return; 3475 } 3476 p->tv.nChunk++; 3477 } 3478 3479 /* Append a copy of the vector to Vec1TrainCtx.aVec[]. */ 3480 memcpy(vec1TrainingVector(&p->tv, p->tv.nVec), sqlite3_value_blob(aArg[0]),n); 3481 p->tv.nVec++; 3482 } 3483 3484 /* 3485 ** Normalize all the training vectors. 3486 */ 3487 static void vec1TrainNormalizeAll(Vec1TrainCtx *p){ 3488 i64 ii; 3489 for(ii=0; iitv.nVec; ii++){ 3490 vec1NormalizeVector(vec1TrainingVector(&p->tv, ii), p->tv.nElem); 3491 } 3492 } 3493 3494 /* 3495 ** Free a Vec1TrainVectors object allocated by vec1CodebookWork() or 3496 ** vec1CopyVectors(). In these objects the aChunk[] array is part of the same 3497 ** allocation as the structure itself. 3498 */ 3499 static void vec1FreeVectors(Vec1TrainVectors *pFree){ 3500 if( pFree ){ 3501 i64 ii; 3502 for(ii=0; iinChunk; ii++){ 3503 sqlite3_free(pFree->aChunk[ii]); 3504 } 3505 sqlite3_free(pFree); 3506 } 3507 } 3508 3509 /* 3510 ** An instance of the following structure is allocated for each PQ codebook 3511 ** to train. Each codebook can then be trained in a separate thread. 3512 */ 3513 typedef struct Vec1CodebookJob Vec1CodebookJob; 3514 struct Vec1CodebookJob { 3515 Vec1TrainCtx *p; 3516 Vec1TrainVectors *pTrain; 3517 int iOff; 3518 float *aCode; 3519 int rc; 3520 }; 3521 3522 static void vec1CodebookWork(void *pCtx){ 3523 Vec1CodebookJob *pJob = (Vec1CodebookJob*)pCtx; 3524 Vec1TrainCtx *p = pJob->p; 3525 const int nBytePerVec = p->nCodeElem * sizeof_f32; 3526 const i64 nVec = pJob->pTrain->nVec; 3527 const i64 nVecPerChunk = (VEC1_TRAINING_SZCHUNK / nBytePerVec); 3528 const i64 nChunk = (nVec + nVecPerChunk - 1) / nVecPerChunk; 3529 3530 /* Allocate the Vec1TrainVectors structure and its aChunk[] array */ 3531 Vec1TrainVectors *pVec = (Vec1TrainVectors*)vec1MallocZero( 3532 sizeof(Vec1TrainVectors) + sizeof(float*) * nChunk 3533 ); 3534 3535 if( pVec==0 ){ 3536 pJob->rc = SQLITE_NOMEM; 3537 }else{ 3538 i64 ii; 3539 int nShort = 0; 3540 pVec->nElem = p->nCodeElem; 3541 pVec->nVec = nVec; 3542 pVec->nVecPerChunk = nVecPerChunk; 3543 pVec->nChunk = nChunk; 3544 pVec->aChunk = (float**)&pVec[1]; 3545 3546 /* If the training vector size is not an integer multiple of the 3547 ** sub-vector size and this is the rightmost sub-vector (the one that 3548 ** will need to be padded with 0.0 values), set nShort to non-zero. */ 3549 if( (pJob->iOff + p->nCodeElem)>pJob->pTrain->nElem ){ 3550 nShort = pJob->pTrain->nElem - pJob->iOff; 3551 } 3552 3553 /* Allocate chunks for the new Vec1TrainVectors structure. If nShort 3554 ** is set, also zero them out. */ 3555 for(ii=0; iinChunk; ii++){ 3556 /* Allocate space for this chunk. Either VEC1_TRAINING_SZCHUNK or 3557 ** enough space for all remaining sub-vectors, whichever is smaller. */ 3558 i64 nAlloc = MIN(VEC1_TRAINING_SZCHUNK, 3559 (pVec->nVec - (ii * pVec->nVecPerChunk)) * nBytePerVec 3560 ); 3561 pVec->aChunk[ii] = (float*)sqlite3_malloc64(nAlloc); 3562 3563 if( pVec->aChunk[ii]==0 ){ 3564 pJob->rc = SQLITE_NOMEM; 3565 break; 3566 } 3567 if( nShort>0 ){ 3568 memset(pVec->aChunk[ii], 0, nAlloc); 3569 } 3570 } 3571 3572 if( pJob->rc==SQLITE_OK ){ 3573 int nCopy = (nShort ? nShort : pVec->nElem) * sizeof_f32; 3574 for(ii=0; iinVec; ii++){ 3575 float *aVec = vec1TrainingVector(pJob->pTrain, ii); 3576 memcpy(vec1TrainingVector(pVec, ii), &aVec[pJob->iOff], nCopy); 3577 } 3578 3579 pJob->rc = vec1Ann1KMeans(0, pVec, 0, VEC1_PQ_CODEBOOK_SZ, pJob->aCode); 3580 } 3581 3582 vec1FreeVectors(pVec); 3583 } 3584 } 3585 3586 static int vec1CodebookFinal(void *pCtx, int rcin){ 3587 UNUSED_PARAMETER(rcin); 3588 return ((Vec1CodebookJob*)pCtx)->rc; 3589 } 3590 3591 static void vec1TrainPQCodebooks( 3592 Vec1TrainCtx *p, 3593 Vec1TrainVectors *pVec, 3594 Vec1JobQueue *pQueue, 3595 float *aBook 3596 ){ 3597 if( p->rc==SQLITE_OK ){ 3598 Vec1CodebookJob *aJob = 0; 3599 3600 aJob = vec1MallocZero(sizeof(Vec1CodebookJob) * p->nCodesize); 3601 if( aJob ){ 3602 int ii; 3603 int rc = SQLITE_OK; 3604 for(ii=0; rc==SQLITE_OK && iinCodesize; ii++){ 3605 Vec1CodebookJob *pJob = &aJob[ii]; 3606 pJob->p = p; 3607 pJob->iOff = ii * p->nCodeElem; 3608 pJob->aCode = &aBook[ii * p->nCodeElem * VEC1_PQ_CODEBOOK_SZ]; 3609 pJob->rc = SQLITE_OK; 3610 pJob->pTrain = pVec; 3611 rc = vec1JobQueueAddJob( 3612 pQueue, vec1CodebookWork, vec1CodebookFinal, pJob 3613 ); 3614 } 3615 p->rc = vec1JobQueueFinishJobs(pQueue, rc); 3616 }else{ 3617 p->rc = SQLITE_NOMEM; 3618 } 3619 3620 if( p->rc!=SQLITE_OK ){ 3621 sqlite3_result_error_code(p->pCtx, p->rc); 3622 } 3623 sqlite3_free(aJob); 3624 } 3625 } 3626 3627 static void vec1TransposeMatrix(double *aMatrix, int nElem) { 3628 int i, j; 3629 for (i = 0; i < nElem - 1; i++) { 3630 for (j = i + 1; j < nElem; j++) { 3631 double tmp = aMatrix[i * nElem + j]; 3632 aMatrix[i * nElem + j] = aMatrix[j * nElem + i]; 3633 aMatrix[j * nElem + i] = tmp; 3634 } 3635 } 3636 } 3637 static int vec1JacobiDoOnePair( 3638 int p, int q, 3639 double *A, 3640 int d, 3641 double *Vt, 3642 double fTol 3643 ){ 3644 double alpha = 0.0, beta = 0.0, gamma = 0.0; 3645 int r = 0; 3646 3647 double *Ap = A + p*d; 3648 double *Aq = A + q*d; 3649 #ifdef VEC1_HAVE_AVX2 3650 __m256d valpha, vbeta, vgamma; 3651 #endif 3652 #ifdef VEC1_HAVE_NEON 3653 float64x2_t valpha, vbeta, vgamma; 3654 #endif 3655 3656 #ifdef VEC1_HAVE_AVX2 3657 valpha = _mm256_setzero_pd(); 3658 vbeta = _mm256_setzero_pd(); 3659 vgamma = _mm256_setzero_pd(); 3660 for(/*no-op*/; r<(d-3); r+=4) { 3661 __m256d vAp = _mm256_loadu_pd(Ap + r); 3662 __m256d vAq = _mm256_loadu_pd(Aq + r); 3663 valpha = FMADD64(vAp, vAp, valpha); 3664 vbeta = FMADD64(vAq, vAq, vbeta); 3665 vgamma = FMADD64(vAp, vAq, vgamma); 3666 } 3667 HORIZONTAL_SUM64(alpha, valpha); 3668 HORIZONTAL_SUM64(beta, vbeta); 3669 HORIZONTAL_SUM64(gamma, vgamma); 3670 #endif 3671 #ifdef VEC1_HAVE_NEON 3672 valpha = vdupq_n_f64(0.0); 3673 vbeta = vdupq_n_f64(0.0); 3674 vgamma = vdupq_n_f64(0.0); 3675 for(/*no-op*/; r<=(d-2); r+=2) { 3676 float64x2_t vAp = vld1q_f64(&Ap[r]); 3677 float64x2_t vAq = vld1q_f64(&Aq[r]); 3678 valpha = vfmaq_f64(valpha, vAp, vAp); 3679 vbeta = vfmaq_f64(vbeta, vAq, vAq); 3680 vgamma = vfmaq_f64(vgamma, vAp, vAq); 3681 } 3682 alpha = vaddvq_f64(valpha); 3683 beta = vaddvq_f64(vbeta); 3684 gamma = vaddvq_f64(vgamma); 3685 #endif 3686 3687 assert( p=fTol*sqrt(alpha*beta) ){ 3696 double zeta = (beta - alpha) / (2.0 * gamma); 3697 double t, c, s; 3698 double *Vtp, *Vtq; 3699 #ifdef VEC1_HAVE_AVX2 3700 __m256d vc, vs, vms; 3701 #endif 3702 #ifdef VEC1_HAVE_NEON 3703 float64x2_t vc, vs, vms; 3704 #endif 3705 if (zeta >= 0.0){ 3706 t = 1.0 / ( zeta + sqrt(1.0 + zeta * zeta)); 3707 }else{ 3708 t = -1.0 / (-zeta + sqrt(1.0 + zeta * zeta)); 3709 } 3710 3711 /* Damping factor apparently sometimes required by parallel Jacobi. 3712 ** Wait to see if we have a problem first I suppose... */ 3713 /* t = t*0.5; */ 3714 c = 1.0 / sqrt(1.0 + t * t); 3715 s = -c * t; 3716 3717 /* Rotate columns p and q of A */ 3718 r = 0; 3719 #ifdef VEC1_HAVE_AVX2 3720 vc = _mm256_set1_pd(c); 3721 vs = _mm256_set1_pd(s); 3722 vms = _mm256_set1_pd(-s); 3723 for(; rnThread + (p->nThread==1); 3880 int nBlk = nJob*2; 3881 int nByte = nJob * sizeof(Vec1JacobiJob); 3882 3883 Vec1JacobiJob *aJob = (Vec1JacobiJob*)vec1MallocZero(nByte); 3884 *pnJob = 0; 3885 if( aJob==0 ){ 3886 p->rc = SQLITE_NOMEM; 3887 sqlite3_result_error_nomem(p->pCtx); 3888 }else{ 3889 int ii; 3890 int nColPerBlk = (nElem + nBlk-1)/ nBlk; 3891 for(ii=0; iiA = A; 3894 pJob->nElem = nElem; 3895 pJob->Vt = Vt; 3896 pJob->fTol = fTol; 3897 pJob->iJob = ii; 3898 pJob->nColPerBlk = nColPerBlk; 3899 pJob->nBlk = nBlk; 3900 } 3901 3902 *pnJob = nJob; 3903 *pnStep = nBlk-1; 3904 } 3905 return aJob; 3906 } 3907 3908 static void vec1JacobiWork(void *pArg){ 3909 Vec1JacobiJob *pJob = (Vec1JacobiJob*)pArg; 3910 int iBlk1 = 0; 3911 int iBlk2 = 0; 3912 int p0, p1, q0, q1; 3913 int p; 3914 3915 vec1RoundRobinPair(pJob->nBlk, pJob->r, pJob->iJob, &iBlk1, &iBlk2); 3916 if( iBlk1>iBlk2 ){ 3917 SWAP(int, iBlk1, iBlk2); 3918 } 3919 3920 p0 = iBlk1 * pJob->nColPerBlk; 3921 q0 = iBlk2 * pJob->nColPerBlk; 3922 p1 = MIN(p0 + pJob->nColPerBlk, pJob->nElem); 3923 q1 = MIN(q0 + pJob->nColPerBlk, pJob->nElem); 3924 3925 /* Do cross-block pairs */ 3926 for(p=p0; pnApply += vec1JacobiDoOnePair( 3930 p, q, pJob->A, pJob->nElem, pJob->Vt, pJob->fTol 3931 ); 3932 } 3933 } 3934 3935 /* If this is round 0, also do intra-block pairs */ 3936 if( pJob->r==0 ){ 3937 for(p=p0; pnApply += vec1JacobiDoOnePair( 3941 p, q, pJob->A, pJob->nElem, pJob->Vt, pJob->fTol 3942 ); 3943 } 3944 } 3945 for(p=q0; pnApply += vec1JacobiDoOnePair( 3949 p, q, pJob->A, pJob->nElem, pJob->Vt, pJob->fTol 3950 ); 3951 } 3952 } 3953 } 3954 } 3955 3956 /* 3957 ** This routine computes SVD of a column-major square matrix A (d x d): 3958 ** 3959 ** A = U * diag(S) * Vt 3960 ** 3961 ** Parameters: 3962 ** A - input [d*d], column-major. MODIFIED BY THIS ROUTINE 3963 ** d - matrix dimension 3964 ** U - output [d*d], column-major. Columns = left singular vectors. 3965 ** S - output [d]. Singular values, not sorted. 3966 ** Vt - output [d*d], column-major storage of V^T. 3967 ** Row j of V^T (right singular vector j) occupies 3968 ** column j in memory: elements Vt[j*d .. j*d+d-1]. 3969 ** nMaxIter - max sweeps 3970 ** fTol - convergence tolerance 3971 ** 3972 ** Returns number of sweeps performed. 3973 **/ 3974 static void vec1JacobiSVD( 3975 Vec1TrainCtx *pTrain, 3976 Vec1JobQueue *pQueue, 3977 double *A, 3978 int d, 3979 double *U, 3980 double *S, 3981 double *Vt, 3982 int nMaxIter, /* Maximum number of sweeps */ 3983 double fTol 3984 ){ 3985 int j = 0; /* Iterator */ 3986 int nSweep = 0; /* Number of sweeps performed so far */ 3987 int nStep = 0; /* Number of steps per sweep */ 3988 3989 Vec1JacobiJob *aJob = 0; 3990 int nJob = 0; 3991 3992 assert( nMaxIter>0 && fTol>0.0 ); 3993 aJob = vec1JacobiAlloc(pTrain, A, d, Vt, fTol, &nJob, &nStep); 3994 if( aJob==0 ) return; 3995 3996 /* Vt is initialised to an identity matrix. */ 3997 memset(Vt, 0, d * d * sizeof(double)); 3998 for(j=0; j0 ) break; 4018 } 4019 if( j==nJob ){ 4020 nSweep = nMaxIter; 4021 } 4022 } 4023 4024 /* Vt was accumulated in row-major format. Flip it back to column-major */ 4025 vec1TransposeMatrix(Vt, d); 4026 4027 /* 4028 ** Columns of A are now orthogonal. The singular value j is the norm 4029 ** of column j of A. Column j of U is column j of A, normalised. 4030 */ 4031 for(j=0; jfTol ){ 4044 for (r=0; rthreshold || fOrthVT>threshold || fReconstruction>threshold ){ 4209 vec1ResultErrorF(pCtx, "vec1: SVD error - " 4210 "fOrthU=%f, fOrthVT=%f, fReconstruction=%f", 4211 fOrthU, fOrthVT, fReconstruction 4212 ); 4213 return SQLITE_ERROR; 4214 } 4215 4216 return SQLITE_OK; 4217 } 4218 4219 typedef struct Vec1CovarianceJob Vec1CovarianceJob; 4220 struct Vec1CovarianceJob { 4221 double *aM; /* output matrix - each job writes distinct rows */ 4222 float *aBook; /* codebook */ 4223 4224 Vec1TrainVectors *pVec; 4225 4226 int nCodeElem; /* Number of elements in each subspace */ 4227 int iSub; /* Our job to do this subspace */ 4228 double fTotalDist; /* private accumulator */ 4229 #ifdef VEC1_USE_TRANSPOSITION 4230 float *aTrans; /* Transposed version of this job's codebook */ 4231 #endif 4232 }; 4233 4234 /* 4235 ** One job per sub-space. 4236 */ 4237 static Vec1CovarianceJob *vec1CovarianceAlloc( 4238 Vec1TrainCtx *p, 4239 double *aM, 4240 Vec1TrainVectors *pVec, 4241 float *aBook, 4242 int *pnJob /* OUT: number of jobs */ 4243 ){ 4244 int nByte = sizeof(Vec1CovarianceJob) * p->nCodesize; 4245 Vec1CovarianceJob *aJob; 4246 4247 #ifdef VEC1_USE_TRANSPOSITION 4248 /* Add space for each job to create a transposed version of its codebook */ 4249 nByte += sizeof_f32 * p->nCodeElem * VEC1_PQ_CODEBOOK_SZ * p->nCodesize; 4250 #endif 4251 aJob = (Vec1CovarianceJob*)vec1MallocZero(nByte); 4252 4253 assert( p->rc==SQLITE_OK ); 4254 *pnJob = 0; 4255 if( aJob ){ 4256 int ii; 4257 #ifdef VEC1_USE_TRANSPOSITION 4258 float *aTrans = (float*)&aJob[p->nCodesize]; 4259 for(ii=0; iinCodesize; ii++){ 4260 aJob[ii].aTrans = &aTrans[ii * p->nCodeElem * VEC1_PQ_CODEBOOK_SZ]; 4261 } 4262 #endif 4263 for(ii=0; iinCodesize; ii++){ 4264 Vec1CovarianceJob *pJob = &aJob[ii]; 4265 pJob->aM = aM; 4266 pJob->aBook = aBook; 4267 pJob->pVec = pVec; 4268 pJob->nCodeElem = p->nCodeElem; 4269 pJob->iSub = ii; 4270 } 4271 *pnJob = p->nCodesize; 4272 }else{ 4273 sqlite3_result_error_nomem(p->pCtx); 4274 p->rc = SQLITE_NOMEM; 4275 } 4276 4277 return aJob; 4278 } 4279 4280 #if defined(VEC1_HAVE_AVX2) 4281 /* 4282 ** Convert each element of the 8-float vector fVec to a double, and add 4283 ** each scalar value to the corresponding aOut[] element. 4284 */ 4285 static void vec1AddToDoubleArrayAVX2(double *aOut, __m256 fVec){ 4286 __m256d lo = _mm256_cvtps_pd(_mm256_castps256_ps128(fVec) ); 4287 __m256d hi = _mm256_cvtps_pd(_mm256_extractf128_ps(fVec, 1)); 4288 __m256d lo1 = LOADU64(&aOut[0]); 4289 __m256d hi1 = LOADU64(&aOut[4]); 4290 _mm256_storeu_pd(&aOut[0], _mm256_add_pd(lo, lo1)); 4291 _mm256_storeu_pd(&aOut[4], _mm256_add_pd(hi, hi1)); 4292 } 4293 #endif 4294 4295 #if defined(VEC1_HAVE_NEON) 4296 /* 4297 ** Convert each element of the 4-float vector fVec to a double, and add 4298 ** each scalar value to the corresponding aOut[] element. 4299 */ 4300 static void vec1AddToDoubleArrayNEON(double *aOut, float32x4_t fVec){ 4301 float64x2_t lo = vcvt_f64_f32(vget_low_f32(fVec)); 4302 float64x2_t hi = vcvt_high_f64_f32(fVec); 4303 float64x2_t lo1 = vld1q_f64(&aOut[0]); 4304 float64x2_t hi1 = vld1q_f64(&aOut[2]); 4305 vst1q_f64(&aOut[0], vaddq_f64(lo, lo1)); 4306 vst1q_f64(&aOut[2], vaddq_f64(hi, hi1)); 4307 } 4308 #endif 4309 4310 /* 4311 ** The number of vectors handled by each pass in vec1CovarianceWork(). 4312 */ 4313 #define VEC1_COVAR_NVEC (VEC1_MULTIMATCH_NVEC * VEC1_COVAR_MULTIMATCH_MULT) 4314 4315 /* 4316 ** For each vv in (0..VEC1_COVAR_NVEC-1), and each ii in 4317 ** (0..nElem-1), do the following: 4318 ** 4319 ** aOut[ii] = aOut[ii] + SUM(aScalar[vv] * aIn[vv][ii]) 4320 */ 4321 static void vec1CovarianceAccumulateN( 4322 double *aOut, 4323 const float *aIn[VEC1_COVAR_NVEC], 4324 const float aScalar[VEC1_COVAR_NVEC], 4325 int nElem 4326 ){ 4327 int ii = 0; 4328 int vv; 4329 4330 #ifdef VEC1_HAVE_AVX2 4331 #define VEC1_COVAR_NACC 8 4332 __m256 vs[VEC1_COVAR_NVEC]; 4333 for(vv=0; vviSub*pJob->nCodeElem; 4412 float *aCode = &pJob->aBook[iSubOff * VEC1_PQ_CODEBOOK_SZ]; 4413 i64 ii; 4414 int kk; 4415 4416 i64 nVec = pJob->pVec->nVec; 4417 int nElem = pJob->pVec->nElem; 4418 int nKK = MIN(pJob->nCodeElem, nElem - iSubOff); 4419 4420 #if defined(VEC1_USE_TRANSPOSITION) 4421 /* Populate this job's transposed copy of its slice of the codebook. */ 4422 vec1CodebookTranspose( 4423 aCode, pJob->nCodeElem, VEC1_NTRANSPOSE_WIDTH, VEC1_PQ_CODEBOOK_SZ, 4424 pJob->aTrans 4425 ); 4426 #endif 4427 4428 /* Loop through the training vectors that are our responsibility, 4429 ** VEC1_COVAR_NVEC at a time. Each iteration of this outer loop 4430 ** compares VEC1_COVAR_NVEC sub-vectors to all candidate codebook 4431 ** entries (VEC1_MULTIMATCH_NVEC at a time, as that is the width the 4432 ** best-match routines operate on), then updates pJob->aM[] with the 4433 ** results. */ 4434 ii = 0; 4435 for(; ii<=(nVec-VEC1_COVAR_NVEC); ii+=VEC1_COVAR_NVEC){ 4436 int vv, iBatch; 4437 const float *aVec[VEC1_COVAR_NVEC]; 4438 const float *aSub[VEC1_COVAR_NVEC]; 4439 int aBest[VEC1_COVAR_NVEC]; 4440 const float *aSubHat[VEC1_COVAR_NVEC]; 4441 4442 for(vv=0; vvpVec, ii+vv); 4444 aSub[vv] = &aVec[vv][iSubOff]; 4445 } 4446 4447 for(iBatch=0; iBatchnCodeElem, aCode, pJob->aTrans, VEC1_PQ_CODEBOOK_SZ, 4451 &aSub[off], &aBest[off], &pJob->fTotalDist 4452 ); 4453 } 4454 4455 for(vv=0; vvnCodeElem]; 4457 } 4458 4459 /* For each row of pJob->aM[], gather the VEC1_COVAR_NVEC 4460 ** scalars that apply to it and stream through the whole row once, 4461 ** rather than once per training vector. */ 4462 for(kk=0; kkaM[(kk+iSubOff) * nElem], aVec, aScalar, nElem 4469 ); 4470 } 4471 } 4472 4473 /* Scalar tail - handle training vectors not covered by the batched 4474 ** loop above because nVec is not a multiple of VEC1_COVAR_NVEC. */ 4475 for(; iipVec, ii); 4477 const float *aSub = &aVec[iSubOff]; 4478 int iBest = vec1BestMatchSimple( 4479 aCode, VEC1_PQ_CODEBOOK_SZ, aSub, pJob->nCodeElem, &pJob->fTotalDist 4480 ); 4481 float *aSubHat = &aCode[iBest * pJob->nCodeElem]; 4482 4483 for(kk=0; kkaM[(kk+iSubOff) * nElem]; 4486 int iVec; 4487 for(iVec=0; iVecnVec vectors, each p->nElem elements each. 4497 */ 4498 static void vec1PqFindRotation( 4499 Vec1TrainCtx *p, 4500 Vec1JobQueue *pQueue, 4501 Vec1TrainVectors *pTrain, /* Rotated vectors to train on */ 4502 float *aBook, /* Current codebook */ 4503 float *aRotation /* OUT: best rotation */ 4504 ){ 4505 if( p->rc==SQLITE_OK ){ 4506 double *aM = 0; 4507 double *aU = 0; 4508 double *aVT = 0; 4509 double *aS = 0; 4510 double *aW = 0; 4511 int ii; 4512 int nElem2 = (p->tv.nElem * p->tv.nElem); 4513 4514 Vec1CovarianceJob *aJob = 0; 4515 int nJob = 0; 4516 4517 /* Allocate space for 4 nElem*nElem matrices - W, M, U and VT. And one 4518 ** nElem vector - S. */ 4519 aM = (double*)vec1MallocZero( 4520 4 * nElem2 * sizeof(double) + 4521 p->tv.nElem * sizeof(double) 4522 ); 4523 if( aM==0 ){ 4524 p->rc = SQLITE_NOMEM; 4525 sqlite3_result_error_nomem(p->pCtx); 4526 return; 4527 } 4528 aVT = &aM[nElem2]; 4529 aU = &aVT[nElem2]; 4530 aW = &aU[nElem2]; 4531 aS = &aW[nElem2]; 4532 4533 /* Step 1. Calculate the cross-covariance matrix M between training set X 4534 ** and the quantized version of the training set X^. i.e. the sum of the 4535 ** following for all x in X: 4536 ** 4537 ** xT . x^ 4538 ** 4539 ** (x1) (x1*x1^, x1*x2^, x1*x3^) 4540 ** (x2) . (x1^, x2^, x3^) == (x2*x1^, x2*x2^, x2*x3^) 4541 ** (x3) (x3*x1^, x3*x2^, x3*x3^) 4542 ** 4543 ** Because the covariance matrix is going to LAPACK, it has to be in 4544 ** column-major order. So aM[1]==(x2*x1^). 4545 */ 4546 START_TRAINING_TIMER(p, VEC1_TRAINING_ROT_COVARIANCE); 4547 aJob = vec1CovarianceAlloc(p, aM, pTrain, aBook, &nJob); 4548 if( aJob ){ 4549 for(ii=0; iitv.nElem, aU, aS, aVT, 50, 1e-14); 4560 END_TRAINING_TIMER(p, VEC1_TRAINING_ROT_JACOBI); 4561 vec1MatrixMultiply(aRotation, aU, aVT, p->tv.nElem); 4562 4563 if( p->rc==SQLITE_OK && p->bSvdVerify ){ 4564 p->rc = vec1SVDSelfTest(p->pCtx, aM, aU, aS, aVT, p->tv.nElem); 4565 } 4566 sqlite3_free(aM); 4567 } 4568 } 4569 4570 typedef struct Vec1RotationJob Vec1RotationJob; 4571 struct Vec1RotationJob { 4572 4573 Vec1TrainVectors *pVec; /* Input vectors */ 4574 Vec1TrainVectors *pOut; /* Output vectors */ 4575 4576 i64 iFirst; 4577 i64 iEof; 4578 4579 const float *aRotation; /* nElem*nElem rotation matrix */ 4580 #ifdef VEC1_USE_TRANSPOSITION 4581 const float *aRotationNT; /* Transposed rotation matrix */ 4582 #endif 4583 }; 4584 4585 static Vec1RotationJob *vec1RotationAlloc( 4586 Vec1TrainCtx *p, 4587 const float *aRotation, 4588 const float *aRotationNT, 4589 Vec1TrainVectors *pOut /* Store rotated vectors here */ 4590 ){ 4591 int nByte = p->nThread * sizeof(Vec1RotationJob); 4592 Vec1RotationJob *aJob = vec1MallocZero(nByte); 4593 if( aJob ){ 4594 int ii; 4595 for(ii=0; iinThread; ii++){ 4596 Vec1RotationJob *pJob = &aJob[ii]; 4597 ASSIGN_VECTORS_TO_JOB(&p->tv, pJob, ii, p->nThread); 4598 pJob->aRotation = aRotation; 4599 pJob->pOut = pOut; 4600 #ifdef VEC1_USE_TRANSPOSITION 4601 pJob->aRotationNT = aRotationNT; 4602 #else 4603 (void)aRotationNT; 4604 #endif 4605 } 4606 4607 } 4608 return aJob; 4609 } 4610 4611 #if defined(VEC1_USE_TRANSPOSITION) 4612 static void vec1RotateVectorTransposeN( 4613 float *aOut[VEC1_MULTIMATCH_NVEC], 4614 const float *aIn[VEC1_MULTIMATCH_NVEC], 4615 int nElem, 4616 const float *aRotation, 4617 const float *aRotationNT 4618 ){ 4619 int vv; 4620 int d; 4621 int ii; 4622 4623 /* ii is the first output element in the VEC1_MULTIMATCH_NVEC output 4624 ** vectors. Each iteration of this outer loop populates 8 elements 4625 ** of each of them */ 4626 for(ii=0; ii<=(nElem-8); ii+=8){ 4627 const float *aNT = &aRotationNT[(ii * nElem)]; 4628 __m256 aAcc[VEC1_MULTIMATCH_NVEC]; 4629 4630 for(vv=0; vvpVec->nElem; 4730 4731 i64 ii = pJob->iFirst; 4732 for(; ii<=(pJob->iEof-VEC1_MULTIMATCH_NVEC); ii+=VEC1_MULTIMATCH_NVEC){ 4733 const float *aIn[VEC1_MULTIMATCH_NVEC]; 4734 float *aOut[VEC1_MULTIMATCH_NVEC]; 4735 int vv; 4736 for(vv=0; vvpVec, vv+ii); 4738 aOut[vv] = vec1TrainingVector(pJob->pOut, vv+ii); 4739 } 4740 4741 #ifdef VEC1_USE_TRANSPOSITION 4742 vec1RotateVectorTransposeN( 4743 aOut, aIn, nElem, pJob->aRotation, pJob->aRotationNT 4744 ); 4745 #else 4746 vec1RotateVectorN(aOut, aIn, nElem, pJob->aRotation); 4747 #endif 4748 } 4749 4750 for(; iiiEof; ii++){ 4751 const float *pIn = vec1TrainingVector(pJob->pVec, ii); 4752 float *pOut = vec1TrainingVector(pJob->pOut, ii); 4753 vec1RotateVector(nElem, pJob->aRotation, pIn, pOut); 4754 } 4755 } 4756 4757 /* 4758 ** Create and return a deep copy of the training vectors passed as the 4759 ** only argument. 4760 */ 4761 static Vec1TrainVectors *vec1CopyVectors(Vec1TrainVectors *pIn){ 4762 Vec1TrainVectors *pRet = 0; 4763 i64 ii; 4764 4765 pRet = (Vec1TrainVectors*)vec1MallocZero( 4766 sizeof(Vec1TrainVectors) + sizeof(float*) * pIn->nChunk 4767 ); 4768 if( pRet==0 ) return pRet; 4769 pRet->nElem = pIn->nElem; 4770 pRet->nVec = pIn->nVec; 4771 pRet->nVecPerChunk = pIn->nVecPerChunk; 4772 pRet->nChunk = pIn->nChunk; 4773 pRet->aChunk = (float**)&pRet[1]; 4774 4775 for(ii=0; iinChunk; ii++){ 4776 i64 nByte = pRet->nVecPerChunk * pIn->nElem * sizeof_f32; 4777 pRet->aChunk[ii] = (float*)sqlite3_malloc(VEC1_TRAINING_SZCHUNK); 4778 if( pRet->aChunk[ii]==0 ){ 4779 vec1FreeVectors(pRet); 4780 return 0; 4781 } 4782 if( ii==pIn->nChunk-1 ){ 4783 nByte = (pRet->nVec - ii*pRet->nVecPerChunk) * pRet->nElem*sizeof_f32; 4784 } 4785 assert( nByte<=VEC1_TRAINING_SZCHUNK ); 4786 memcpy(pRet->aChunk[ii], pIn->aChunk[ii], nByte); 4787 } 4788 4789 return pRet; 4790 } 4791 4792 static void vec1TrainRotation( 4793 Vec1TrainCtx *p, 4794 Vec1JobQueue *pQueue, 4795 float *aBook, 4796 float *aRotation 4797 ){ 4798 const int nElem = p->tv.nElem; 4799 const int nMatrixByte = sizeof_f32 * nElem * nElem; 4800 int iRound = 0; /* Current OPQ round */ 4801 i64 ii; 4802 float *aRot = (float*)sqlite3_malloc(nMatrixByte * 2); 4803 float *aRot2 = &aRot[nElem*nElem]; 4804 Vec1TrainVectors *pTrain = vec1CopyVectors(&p->tv); 4805 Vec1RotationJob *aJob = 0; 4806 aJob = vec1RotationAlloc(p, aRotation, aRot2, pTrain); 4807 4808 if( pTrain==0 || aRot==0 || aJob==0 ){ 4809 sqlite3_result_error_nomem(p->pCtx); 4810 p->rc = SQLITE_NOMEM; 4811 } 4812 4813 for(iRound=0; iRoundnOpqRound; iRound++){ 4814 vec1TrainLog(p, "OPQ round %d/%d", iRound+1, p->nOpqRound); 4815 START_TRAINING_TIMER(p, VEC1_TRAINING_ROT_CODEBOOKS); 4816 vec1TrainPQCodebooks(p, pTrain, pQueue, aBook); 4817 END_TRAINING_TIMER(p, VEC1_TRAINING_ROT_CODEBOOKS); 4818 4819 vec1PqFindRotation(p, pQueue, pTrain, aBook, aRot); 4820 4821 if( p->rc==SQLITE_OK ){ 4822 if( iRound==0 ){ 4823 memcpy(aRotation, aRot, nMatrixByte); 4824 }else{ 4825 memcpy(aRot2, aRotation, nMatrixByte); 4826 vec1MatrixMultiplyF(aRotation, aRot2, aRot, nElem); 4827 } 4828 4829 START_TRAINING_TIMER(p, VEC1_TRAINING_ROT_VECTORS); 4830 #ifdef VEC1_USE_TRANSPOSITION 4831 vec1CodebookTranspose(aRotation, 4832 nElem, VEC1_NTRANSPOSE_WIDTH, nElem, aRot2 4833 ); 4834 #endif 4835 for(ii=0; iinThread; ii++){ 4836 vec1JobQueueAddJob(pQueue, vec1RotationWork, 0, &aJob[ii]); 4837 } 4838 vec1JobQueueFinishJobs(pQueue, SQLITE_OK); 4839 END_TRAINING_TIMER(p, VEC1_TRAINING_ROT_VECTORS); 4840 } 4841 p->nCompletedWork += VEC1_TRAINING_WORK_OPQ; 4842 } 4843 4844 if( p->rc==SQLITE_OK ){ 4845 for(ii=0; iitv.nChunk; ii++){ 4846 SWAP(float*, p->tv.aChunk[ii], pTrain->aChunk[ii]); 4847 } 4848 } 4849 sqlite3_free(aJob); 4850 sqlite3_free(aRot); 4851 vec1FreeVectors(pTrain); 4852 } 4853 4854 static void vec1TrainLogTimes(Vec1TrainCtx *p){ 4855 double fTotal = (double)p->aTime[VEC1_TRAINING_TOTAL]; 4856 if( p->zProfileFunction ){ 4857 struct Counter { 4858 const char *zName; 4859 int iTime; 4860 } aCounter[] = { 4861 { "rot_codebooks", VEC1_TRAINING_ROT_CODEBOOKS }, 4862 { "rot_covariance", VEC1_TRAINING_ROT_COVARIANCE }, 4863 { "rot_jacobi", VEC1_TRAINING_ROT_JACOBI }, 4864 { "rot_vectors", VEC1_TRAINING_ROT_VECTORS }, 4865 { "coarse_init", VEC1_TRAINING_COARSE_INIT }, 4866 { "coarse_lloyds", VEC1_TRAINING_COARSE_KMEANS }, 4867 { "residuals", VEC1_TRAINING_RESIDUALS }, 4868 { "codebooks", VEC1_TRAINING_CODEBOOKS } 4869 }; 4870 int icall; 4871 for(icall=0; icall<2; icall++){ 4872 int ii; 4873 char *zSql = 0; 4874 4875 sqlite3_str *pSql = sqlite3_str_new(0); 4876 sqlite3_str_appendf(pSql, "SELECT \"%w\"('{", p->zProfileFunction); 4877 if( icall==0 ){ 4878 for(ii=0; ii0) ? ", " : ""), 4880 aCounter[ii].zName, p->aTime[ aCounter[ii].iTime ]*100.00 / fTotal 4881 ); 4882 } 4883 }else{ 4884 for(ii=0; iiaTime[ aCounter[ii].iTime ]; 4886 sqlite3_str_appendf(pSql, "%s\"%s\": ", 4887 ((ii>0) ? ", " : ""), aCounter[ii].zName 4888 ); 4889 if( val>(1000*1000*1000) ){ 4890 sqlite3_str_appendf(pSql, "\"%.2fG\"", (double)val / `1000000000`.0); 4891 }else if( val>(10*1000*1000) ){ 4892 sqlite3_str_appendf(pSql, "\"%dM\"", (int)(val / (1000*1000))); 4893 }else if( val>(1*1000*1000) ){ 4894 sqlite3_str_appendf(pSql, "\"%.2fM\"", (double)val / `1000000`.0); 4895 }else if( val>(10*1000) ){ 4896 sqlite3_str_appendf(pSql, "\"%dK\"", (int)(val / (1000))); 4897 }else if( val>(1000) ){ 4898 sqlite3_str_appendf(pSql, "\"%.2fK\"", (double)val / 1000.0); 4899 }else{ 4900 sqlite3_str_appendf(pSql, "\"%d\"", (int)val); 4901 } 4902 } 4903 } 4904 4905 sqlite3_str_appendf(pSql, "}')"); 4906 zSql = sqlite3_str_finish(pSql); 4907 4908 if( zSql==0 ){ 4909 sqlite3_result_error_nomem(p->pCtx); 4910 break; 4911 }else{ 4912 sqlite3 *db = sqlite3_context_db_handle(p->pCtx); 4913 char *zErrmsg = 0; 4914 int rc = sqlite3_exec(db, zSql, 0, 0, &zErrmsg); 4915 if( rc!=SQLITE_OK ){ 4916 sqlite3_result_error(p->pCtx, zErrmsg, -1); 4917 sqlite3_result_error_code(p->pCtx, rc); 4918 break; 4919 } 4920 sqlite3_free(zErrmsg); 4921 sqlite3_free(zSql); 4922 } 4923 } 4924 } 4925 } 4926 4927 typedef struct Vec1ResidualJob Vec1ResidualJob; 4928 struct Vec1ResidualJob { 4929 /* Data to train on */ 4930 const Vec1TrainCtx *p; 4931 Vec1TrainVectors *pVec; 4932 i64 iFirst; 4933 i64 iEof; 4934 const float *aCentroid; 4935 int nCentroid; 4936 }; 4937 4938 static void vec1TrainResidualWorker(void *pCtx){ 4939 Vec1ResidualJob *p = (Vec1ResidualJob*)pCtx; 4940 i64 ii; 4941 int nElem = p->pVec->nElem; 4942 4943 for(ii=p->iFirst; iiiEof; ii++){ 4944 float *a = vec1TrainingVector(p->pVec, ii); 4945 int iBest = vec1BestMatchSimple(p->aCentroid, p->nCentroid, a, nElem, 0); 4946 vec1SubInPlace(a, &p->aCentroid[iBest * nElem], nElem); 4947 } 4948 } 4949 4950 static void vec1TrainFindResiduals( 4951 Vec1TrainCtx *p, 4952 Vec1JobQueue *pQueue, 4953 const float *aCentroid 4954 ){ 4955 if( p->rc==SQLITE_OK ){ 4956 int ii; 4957 int nJob = p->nThread; 4958 Vec1ResidualJob *aJob = 0; 4959 int rc = SQLITE_OK; 4960 4961 assert( nJob>=1 ); 4962 aJob = (Vec1ResidualJob*)vec1MallocZero(sizeof(Vec1ResidualJob) * nJob); 4963 if( aJob==0 ){ 4964 sqlite3_result_error_nomem(p->pCtx); 4965 p->rc = SQLITE_NOMEM; 4966 return; 4967 } 4968 4969 for(ii=0; iitv, pJob, ii, nJob); 4972 pJob->p = p; 4973 pJob->aCentroid = aCentroid; 4974 pJob->nCentroid = p->nBucket; 4975 vec1JobQueueAddJob(pQueue, vec1TrainResidualWorker, 0, (void*)pJob); 4976 } 4977 4978 vec1JobQueueFinishJobs(pQueue, rc); 4979 sqlite3_free(aJob); 4980 } 4981 } 4982 4983 static void vec1TrainPrepareLog(Vec1TrainCtx *p){ 4984 if( p->zLogFunction ){ 4985 char *zSql = sqlite3_mprintf("SELECT %s(?, ?)", p->zLogFunction); 4986 if( zSql==0 ){ 4987 sqlite3_result_error_nomem(p->pCtx); 4988 p->rc = SQLITE_NOMEM; 4989 }else{ 4990 sqlite3 *db = sqlite3_context_db_handle(p->pCtx); 4991 p->rc = sqlite3_prepare_v2(db, zSql, -1, &p->pLogStmt, 0); 4992 sqlite3_free(zSql); 4993 if( p->rc==SQLITE_ERROR ){ 4994 sqlite3_result_error(p->pCtx, sqlite3_errmsg(db), -1); 4995 }else if( p->rc!=SQLITE_OK ){ 4996 sqlite3_result_error_code(p->pCtx, p->rc); 4997 } 4998 } 4999 } 5000 } 5001 5002 static void vec1TrainWorkInit(Vec1TrainCtx *p){ 5003 int nTotal = 0; 5004 5005 if( p->eQuant==VEC1_QUANTIZE_OPQ ){ 5006 nTotal += VEC1_TRAINING_WORK_OPQ * p->nOpqRound; 5007 } 5008 if( p->nBucket>0 ){ 5009 nTotal += VEC1_TRAINING_WORK_COARSE1 + VEC1_TRAINING_WORK_COARSE2; 5010 } 5011 if( p->eQuant==VEC1_QUANTIZE_PQ || p->eQuant==VEC1_QUANTIZE_OPQ ){ 5012 nTotal += VEC1_TRAINING_WORK_CODEBOOKS; 5013 } 5014 5015 p->nTotalWork = (nTotal ? nTotal : 1); 5016 } 5017 5018 /* 5019 ** Return true if n is a power of 2, or false otherwise. 5020 */ 5021 static int vec1IsPow2(int n) { 5022 return n > 0 && (n & (n-1)) == 0; 5023 } 5024 5025 /* 5026 ** Apply Walsh-Hadamard Transform to n element vector x. n must 5027 ** be a power of 2. 5028 */ 5029 static void vec1WHT(float *x, int n){ 5030 int stride, i, j; 5031 assert( vec1IsPow2(n) ); 5032 for (stride = 1; stride < n; stride <<= 1) { 5033 for (i = 0; i < n; i += stride << 1) { 5034 for (j = i; j < i + stride; j++) { 5035 float a = x[j]; 5036 float b = x[j + stride]; 5037 x[j] = a + b; 5038 x[j+stride] = a - b; 5039 } 5040 } 5041 } 5042 } 5043 5044 /* 5045 ** Apply Walsh-Hadamard transform to nElem element vector aVec. 5046 */ 5047 static void vec1ApplyWHT(float *aVec, int nElem){ 5048 if (vec1IsPow2(nElem)) { 5049 vec1WHT(aVec, nElem); 5050 }else{ 5051 int p = 1; 5052 while( (p<<1)tv.nVec; ii++){ 5065 vec1ApplyWHT(vec1TrainingVector(&p->tv, ii), p->tv.nElem); 5066 } 5067 } 5068 5069 /* 5070 ** The xFinal() method for the vec1_train() aggregate function. 5071 ** 5072 ** Output a trained model blob. 5073 */ 5074 static void vec1TrainFinal(sqlite3_context *pCtx){ 5075 Vec1TrainCtx *p = 0; 5076 float *aBook = 0; /* Code books */ 5077 float *aCentroid = 0; /* Centroids */ 5078 float *aRotation = 0; /* Rotation */ 5079 5080 i64 nByte = 0; 5081 u8 *aByte = 0; 5082 5083 float *pCsr = 0; 5084 Vec1JobQueue *pQueue = 0; 5085 u32 flags = 0; 5086 i64 ii; 5087 int bPQ = 0; 5088 i64 nElem = 0; /* 64-bit copy of p->tv.nElem */ 5089 5090 /* Check that sufficient training vectors were provided. */ 5091 p = (Vec1TrainCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 5092 if( p==0 ) return; 5093 p->pCtx = pCtx; 5094 bPQ = (p->eQuant==VEC1_QUANTIZE_PQ || p->eQuant==VEC1_QUANTIZE_OPQ); 5095 nElem = p->tv.nElem; 5096 5097 /* If an error occurred in xStep(), then the statement is being aborted and 5098 ** this call is just to clean up. Do not start training. */ 5099 if( p->rc!=SQLITE_OK ) goto train_final_out; 5100 5101 if( p->tv.nVec==0 ){ 5102 vec1ResultErrorF(pCtx, 5103 "too few training vectors (have 0, require more than that)" 5104 ); 5105 goto train_final_out; 5106 } 5107 if( p->nBucket || bPQ ){ 5108 int nReq = p->nBucket * 4; 5109 if( bPQ ) nReq = MAX(VEC1_PQ_TRAINING_SET_MIN, nReq); 5110 if( p->tv.nVectv.nVec 5114 ); 5115 goto train_final_out; 5116 } 5117 } 5118 5119 vec1TrainWorkInit(p); 5120 vec1TrainPrepareLog(p); 5121 vec1TrainLog(p, "vectors loaded, starting training"); 5122 if( p->rc!=SQLITE_OK ) goto train_final_out; 5123 5124 START_TRAINING_TIMER(p, VEC1_TRAINING_TOTAL); 5125 5126 /* If this is training for "cos" distance, not "l2", normalize all 5127 ** training vectors before proceding as usual. */ 5128 if( p->eDistance==VEC1_DISTANCE_COS ){ 5129 vec1TrainNormalizeAll(p); 5130 } 5131 5132 /* Allocate space for the model. Space is required for (a) the header and 5133 ** coarse centroids, (b) the PQ codebooks and (c) the OPQ rotation 5134 ** matrix. */ 5135 nByte = VEC1_HEADER_SIZE + sizeof_f32 * p->nBucket * nElem; 5136 if( bPQ ){ 5137 nByte += sizeof_f32 * p->nCodesize * p->nCodeElem * VEC1_PQ_CODEBOOK_SZ; 5138 } 5139 if( p->eQuant==VEC1_QUANTIZE_OPQ ){ 5140 nByte += sizeof_f32 * nElem * nElem; 5141 } 5142 5143 aByte = (u8*)vec1ContextMalloc(pCtx, nByte); 5144 if( aByte==0 ) goto train_final_out; 5145 pCsr = (float*)&aByte[VEC1_HEADER_SIZE]; 5146 if( bPQ ){ 5147 aBook = pCsr; 5148 pCsr += (i64)p->nCodesize * p->nCodeElem * VEC1_PQ_CODEBOOK_SZ; 5149 } 5150 if( p->nBucket>0 ){ 5151 aCentroid = pCsr; 5152 pCsr += p->nBucket * nElem; 5153 } 5154 if( p->eQuant==VEC1_QUANTIZE_OPQ ){ 5155 aRotation = pCsr; 5156 pCsr += nElem * nElem; 5157 } 5158 assert( (u8*)pCsr==&aByte[nByte] ); 5159 5160 /* Allocate a jobs queue, if multi-threading is required. If it is not 5161 ** required, leave pQueue set to NULL. Things will proceed in a single 5162 ** thread in that case. */ 5163 #if VEC1_THREADS 5164 if( p->nThread>1 ){ 5165 pQueue = vec1JobQueueNew(p->nThread-1); 5166 if( pQueue==0 ){ 5167 sqlite3_result_error_nomem(pCtx); 5168 goto train_final_out; 5169 } 5170 } 5171 #endif 5172 5173 /* Write the model header into the output buffer. */ 5174 flags = VEC1_MODEL_INDEX 5175 | ((p->nBucket>0 && p->bResidual) ? VEC1_MODEL_RESIDUAL : 0) 5176 | ((p->eQuant==VEC1_QUANTIZE_OPQ) ? VEC1_MODEL_ROTATE : 0) 5177 | (p->bWHT ? VEC1_MODEL_WHT : 0) 5178 | ((p->eQuant==VEC1_QUANTIZE_BQ) ? VEC1_MODEL_BITQUANT : 0); 5179 vec1HeaderWrite(aByte, flags, 5180 p->tv.nElem, p->nCodesize, p->nBucket, p->eDistance 5181 ); 5182 5183 /* If an OPQ rotation is require, calculate one now */ 5184 if( p->eQuant==VEC1_QUANTIZE_OPQ ){ 5185 vec1TrainRotation(p, pQueue, aBook, aRotation); 5186 }else if( p->bWHT ){ 5187 vec1TrainApplyWHT(p); 5188 } 5189 5190 if( p->nBucket>0 ){ 5191 vec1TrainCoarseQuant(p, pQueue, aCentroid); 5192 5193 /* For each training vector, find the closest centroid. Then subtract 5194 ** the centroid from the training vector, to leave the residual vector. 5195 ** This is what the PQ step trains on. */ 5196 if( bPQ && p->bResidual ){ 5197 vec1TrainLog(p, "calculating residuals"); 5198 START_TRAINING_TIMER(p, VEC1_TRAINING_RESIDUALS); 5199 vec1TrainFindResiduals(p, pQueue, aCentroid); 5200 END_TRAINING_TIMER(p, VEC1_TRAINING_RESIDUALS); 5201 } 5202 } 5203 5204 /* Now train the PQ codebooks, if required. Each codebook is trained in 5205 ** parallel, using a separate thread if threads were configured. */ 5206 if( bPQ ){ 5207 vec1TrainLog(p, "PQ codebook training"); 5208 START_TRAINING_TIMER(p, VEC1_TRAINING_CODEBOOKS); 5209 vec1TrainPQCodebooks(p, &p->tv, pQueue, aBook); 5210 p->nCompletedWork += VEC1_TRAINING_WORK_CODEBOOKS; 5211 END_TRAINING_TIMER(p, VEC1_TRAINING_CODEBOOKS); 5212 } 5213 5214 /* Return the result blob. */ 5215 if( p->rc==SQLITE_OK ){ 5216 sqlite3_result_blob(pCtx, (void*)aByte, (int)nByte, vec1SqliteFree); 5217 aByte = 0; 5218 } 5219 5220 train_final_out: 5221 END_TRAINING_TIMER(p, VEC1_TRAINING_TOTAL); 5222 vec1TrainLog(p, "training complete"); 5223 vec1TrainLogTimes(p); 5224 sqlite3_finalize(p->pLogStmt); 5225 sqlite3_free(p->zLogFunction); 5226 sqlite3_free(p->zProfileFunction); 5227 for(ii=0; iitv.nChunk; ii++){ 5228 sqlite3_free(p->tv.aChunk[ii]); 5229 } 5230 sqlite3_free(p->tv.aChunk); 5231 vec1JobQueueFree(pQueue); 5232 sqlite3_free(aByte); 5233 } 5234 5235 5236 typedef struct Vec1Model Vec1Model; 5237 struct Vec1Model { 5238 Vec1ModelHeader hdr; 5239 const float *aModel; 5240 const float *aCentroid; 5241 const float *aRotation; 5242 5243 int nCodeElem; 5244 float *aModelT; 5245 5246 #ifdef VEC1_USE_TRANSPOSITION 5247 float *aCentroidNT; 5248 float *aModelNT; 5249 float *aRotationNT; 5250 #endif 5251 }; 5252 5253 static int vec1DecodeModel( 5254 const u8 *aBlob, 5255 int nByte, 5256 Vec1Model *pMod, 5257 char **pzErr 5258 ){ 5259 const u8 *pCsr = aBlob; 5260 int nCodebook = 0; 5261 5262 if( nBytehdr); 5267 pCsr += VEC1_HEADER_SIZE; 5268 5269 assert( VEC1_HEADER_VERSION_BIN>VEC1_HEADER_VERSION ); 5270 if( pMod->hdr.iVersion!=VEC1_HEADER_VERSION 5271 && pMod->hdr.iVersion!=VEC1_HEADER_VERSION_BIN 5272 ){ 5273 if( pMod->hdr.iVersionhdr.iVersion / 1000), (pMod->hdr.iVersion % 1000) 5279 ); 5280 } 5281 return SQLITE_ERROR; 5282 } 5283 5284 /* Check header fields are within the acceptable ranges. This also serves 5285 ** to ensure that the 32-bit arithmetic used to calculate offsets below 5286 ** does not overflow. */ 5287 if( pMod->hdr.nElem>VEC1_VECSIZE_MAX 5288 || pMod->hdr.nBucket>VEC1_MAX_BUCKET 5289 || pMod->hdr.nCodebook>pMod->hdr.nElem 5290 ){ 5291 *pzErr = sqlite3_mprintf("vec1: model is corrupt"); 5292 return SQLITE_ERROR; 5293 } 5294 5295 nCodebook = pMod->hdr.nCodebook; 5296 if( nCodebook>0 ){ 5297 if( (pMod->hdr.flags & VEC1_MODEL_BITQUANT)==0 ){ 5298 pMod->nCodeElem = (pMod->hdr.nElem + nCodebook-1)/nCodebook; 5299 pMod->aModel = (float*)pCsr; 5300 pCsr += (nCodebook*pMod->nCodeElem*VEC1_PQ_CODEBOOK_SZ * sizeof_f32); 5301 }else{ 5302 if( ((pMod->hdr.nElem + 7)/8)==(u32)nCodebook ){ 5303 pMod->nCodeElem = 8; 5304 }else if( ((pMod->hdr.nElem + 15)/16)==(u32)nCodebook ){ 5305 pMod->nCodeElem = 16; 5306 }else{ 5307 *pzErr = sqlite3_mprintf("vec1: unrecognized bq codesize"); 5308 return SQLITE_ERROR; 5309 } 5310 } 5311 } 5312 if( pMod->hdr.nBucket>0 ){ 5313 pMod->aCentroid = (float*)pCsr; 5314 pCsr += (pMod->hdr.nElem * pMod->hdr.nBucket * sizeof_f32); 5315 } 5316 if( (pMod->hdr.flags & VEC1_MODEL_ROTATE) ){ 5317 pMod->aRotation = (float*)pCsr; 5318 pCsr += (pMod->hdr.nElem * pMod->hdr.nElem * sizeof_f32); 5319 } 5320 5321 if( (pCsr - aBlob)!=nByte ){ 5322 *pzErr = sqlite3_mprintf( 5323 "vec1: model size mismatch: have %d, expected %d", nByte, (pCsr-aBlob) 5324 ); 5325 return SQLITE_ERROR; 5326 } 5327 5328 return SQLITE_OK; 5329 } 5330 5331 #if defined(VEC1_USE_TRANSPOSITION) 5332 static int vec1ModelAllocTCent(Vec1Model *pMod){ 5333 int rc = SQLITE_OK; 5334 if( pMod->aCentroidNT==0 && (pMod->hdr.nBucket>0 || pMod->aModel) ){ 5335 int nElem = pMod->hdr.nElem; 5336 int nByte = sizeof_f32 * nElem * pMod->hdr.nBucket; 5337 if( pMod->aModel ){ 5338 int nFloatPerCodebook = pMod->nCodeElem * pMod->hdr.nCodebook; 5339 nByte += (VEC1_PQ_CODEBOOK_SZ * nFloatPerCodebook * sizeof_f32); 5340 if( pMod->aRotation ){ 5341 nByte += (nElem * nElem) * sizeof_f32; 5342 } 5343 } 5344 pMod->aCentroidNT = (float*)sqlite3_malloc(nByte); 5345 if( pMod->aCentroidNT==0 ){ 5346 rc = SQLITE_NOMEM; 5347 }else{ 5348 assert( pMod->aCentroid || pMod->hdr.nBucket==0 ); 5349 vec1CodebookTranspose(pMod->aCentroid, nElem, 5350 VEC1_NTRANSPOSE_WIDTH, pMod->hdr.nBucket, pMod->aCentroidNT 5351 ); 5352 5353 if( pMod->aModel ){ 5354 u32 M; 5355 int szCodebook = pMod->nCodeElem * VEC1_PQ_CODEBOOK_SZ; 5356 pMod->aModelNT = &pMod->aCentroidNT[nElem * pMod->hdr.nBucket]; 5357 for(M=0; Mhdr.nCodebook; M++){ 5358 vec1CodebookTranspose( 5359 &pMod->aModel[szCodebook*M], 5360 pMod->nCodeElem, VEC1_NTRANSPOSE_WIDTH, VEC1_PQ_CODEBOOK_SZ, 5361 &pMod->aModelNT[szCodebook*M] 5362 ); 5363 } 5364 5365 if( pMod->aRotation ){ 5366 /* Create a transposed version of the rotation matrix. */ 5367 pMod->aRotationNT = &pMod->aModelNT[szCodebook * M]; 5368 vec1CodebookTranspose(pMod->aRotation, 5369 nElem, VEC1_NTRANSPOSE_WIDTH, nElem, pMod->aRotationNT 5370 ); 5371 } 5372 } 5373 } 5374 } 5375 return rc; 5376 } 5377 5378 static void vec1ModelFreeTCent(Vec1Model *pMod){ 5379 sqlite3_free(pMod->aCentroidNT); 5380 pMod->aCentroidNT = 0; 5381 pMod->aModelNT = 0; 5382 pMod->aRotationNT = 0; 5383 } 5384 #else 5385 # define vec1ModelAllocTCent(pMod) SQLITE_OK 5386 # define vec1ModelFreeTCent(pMod) 5387 #endif 5388 5389 /************************************************************************* 5390 ** Start of virtual table code 5391 */ 5392 5393 /* %_IDX TABLE LIST FORMAT: 5394 ** 5395 ** Each list begins with 3 32-bit unsigned integers in big-endian format. 5396 ** As follows: 5397 ** 5398 ** bytes 0..3: Flags value. 5399 ** bytes 4..7: Total number of entries in list. 5400 ** bytes 8..11: Number of tombstone entries in list 5401 ** 5402 ** Following these is an array of rowid values - either unsigned 32-bit 5403 ** values or 64-bit signed values, depending on the flags set in the 5404 ** first field value of the list. In the 32-bit format, the tombstone 5405 ** value is 0xFFFFFFFF. For the 64-bit format, it is 0. Rowids are stored 5406 ** in big-endian format. 5407 ** 5408 ** There are two formats - one that uses 32-bit rowids, and another that 5409 ** uses 64-bit rowids. Format consists of one or more blocks. Each block 5410 ** stores 16 PQ codes: 5411 ** 5412 ** * 16 rowid values - either 16 * 32-bit unsigned or 16 * 64-bit 5413 ** signed. The only way to know which is to read the first/last 5414 ** column values from the %_idx table. 5415 ** 5416 ** * The lookup value for the first codebook for each of the 16 5417 ** codes in the block. Followed by the lookup value for the second 5418 ** codebook for each of the 16 codes, and so on. 5419 ** 5420 ** A PQ code list always consists of an exact number of blocks. In the 5421 ** 32-bit rowid format, a rowid value of 0xFFFFFFFF indicates an invalid 5422 ** entry. In the 64-bit format, an invalid entry is one with a rowid value 5423 ** of 0. 5424 */ 5425 5426 /* %_META TABLE LIST FORMAT: 5427 ** 5428 ** Meta table lists always begin with 2 32-bit unsigned integers in 5429 ** big-endian format: 5430 ** 5431 ** Bytes 0..3: 32-bit big-endian flags field. 5432 ** Bytes 4..7: 32-bit big-endian nEntry field. 5433 ** 5434 ** The flags field is set to a combination of VEC1_META_XXX flags. The 5435 ** nEntry fields is set to the number of entries in the list. The format 5436 ** of the rest of the list is different depending on the flags: 5437 ** 5438 ** VEC1_META_GENERIC: 5439 ** 5440 ** This is the fallback format used if none of the other formats can be 5441 ** used. It encodes each value separately as a varint type followed by 5442 ** encoded data. Specifically, for type values 0, 1 and 2: 5443 ** 5444 ** 0: NULL value. 0 byte payload. 5445 ** 1: Unsigned integer value in range [0..254]. 1 byte payload. 5446 ** 2: Integer value. 4 byte payload in range [-`2147483647`..+`2147483647`]. 5447 ** 3: Integer value. 8 byte payload. 5448 ** 4: Real value. 8 byte payload. 5449 ** 5450 ** Odd values larger than 2 are text values, with size in bytes of 5451 ** (type - 2)/2. Even values larger than 2 are blobs. 5452 ** 5453 ** VEC1_META_1BYTEINT: 5454 ** This format may be used if all values in the list are either NULL or 5455 ** integers between 0 and 254, inclusive. Each value is stored as 5456 ** a 1 byte unsigned value, with 255 (0xFF) representing NULL. 5457 ** 5458 ** VEC1_META_4BYTEINT: 5459 ** This format may be used if all values in the list are either NULL or 5460 ** integers between -`2147483648` and +`2147483646`, inclusive. Each value is 5461 ** stored as a 4 byte two's complement value, with +`2147483647` 5462 ** (0x7FFFFFFF) representing NULL. 5463 ** 5464 ** VEC1_META_REAL: 5465 ** This format may be used if all values in the list are real or NULL. 5466 ** Bit pattern 0x7FF8000000000001 is used for NULL. 5467 ** 5468 ** Flag VEC1_META_HASNULL is set if the list contains at least one NULL 5469 ** value. 5470 */ 5471 #define VEC1_META_GENERIC 0x01 5472 #define VEC1_META_1BYTEINT 0x02 5473 #define VEC1_META_4BYTEINT 0x04 5474 #define VEC1_META_REAL 0x08 5475 #define VEC1_META_HASNULL 0x10 5476 5477 #define VEC1_META_TYPEMASK ( \ 5478 VEC1_META_GENERIC | VEC1_META_1BYTEINT | VEC1_META_4BYTEINT | VEC1_META_REAL \ 5479 ) 5480 5481 #define VEC1_META_SZHDR 8 5482 #define VEC1_META_1BYTENULL 255 5483 5484 #define VEC1_META_REALNULL 0x7FF8000000000001 5485 5486 #define VEC1_META_4BYTEMIN (-`2147483647`-1) 5487 #define VEC1_META_4BYTEMAX +`2147483646` 5488 #define VEC1_META_4BYTENULL +`2147483647` 5489 5490 /* When a meta-value array is loaded from disk, at least VEC1_META_PADDING 5491 ** extra bytes of memory are allocated. This is to allow readers to safely 5492 ** overread the record slightly if it is corrupt. */ 5493 #define VEC1_META_PADDING 20 5494 5495 typedef struct Vec1Csr Vec1Csr; 5496 5497 /* 5498 ** Flags that may be part of the first 32-bit unsigned integer of a PQ list. 5499 */ 5500 #define VEC1_LIST_64BIT 0x01 /* Set for 64-bit rowids, clear for 32-bit */ 5501 #define VEC1_LIST_SORTED 0x02 /* True if rowid array is in sorted order */ 5502 5503 /* Size of list header in byte */ 5504 #define VEC1_LIST_SZHDR (3*sizeof_u32) 5505 5506 #define VEC1_TOMBSTONE_32 0xFFFFFFFF 5507 #define VEC1_TOMBSTONE_64 0 5508 5509 5510 /* 5511 ** Fields in the virtual table: 5512 */ 5513 #define VEC1_COLUMN_CMD 0 5514 #define VEC1_COLUMN_ARG 1 5515 #define VEC1_COLUMN_DISTANCE 2 5516 #define VEC1_COLUMN_VECTOR 3 5517 /* Followed by Vec1Tab.nMeta meta-data columns */ 5518 5519 /* 5520 ** MODEL (0): 5521 ** This integer value is set to 1 when a model is first provided to 5522 ** the table, and incremented each time the model is updated thereafter. 5523 ** 5524 ** BLOCKSIZE (1): 5525 ** The config entry for the target size (in bytes) for chunks stored in 5526 ** the %_idx table. 5527 ** 5528 ** FMTVERSION (5): 5529 ** This is an integer - the current format version. Currently this is 5530 ** always 1, but will be increased if the format changes. If a client 5531 ** finds a format it does not understand, it has to rebuild the index. 5532 */ 5533 5534 #define VEC1_CONFIG_MODEL 0 5535 #define VEC1_CONFIG_BLOCKSIZE 1 5536 #define VEC1_CONFIG_NELEM 2 5537 #define VEC1_CONFIG_BLOCKSIZE_MIN 3 5538 #define VEC1_CONFIG_FMTVERSION 5 5539 5540 5541 5542 /* 5543 ** Return the shadow-schema used by the vec1_ann table named zTab. Parameter 5544 ** zDb must be the name of the database (e.g. "main", "temp" or the name 5545 ** of an attached database). 5546 */ 5547 static char *vec1ShadowSchema(const char *zDb, const char *zTab, int nMeta){ 5548 const char zFmt[] = 5549 5550 /* Configuration table. This contains persistent configuration parameters, 5551 ** including the training data. Keys must be one of the VEC1_CONFIG_XXX 5552 ** values defined above. */ 5553 "CREATE TABLE %Q.'%q_config'(id INTEGER PRIMARY KEY, val ANY);" 5554 5555 /* Base table. This contains the raw data as provided by the user. */ 5556 "CREATE TABLE %Q.'%q_base'(" 5557 "id INTEGER PRIMARY KEY, " 5558 "vector BLOB%z" 5559 ");" 5560 5561 /* Index data */ 5562 "CREATE TABLE %Q.'%q_idx'(" 5563 "id INTEGER PRIMARY KEY, "/* Id of blob */ 5564 "bucket INTEGER, " /* Index of bucket for this blob (or NULL) */ 5565 "first INTEGER, " /* Smallest rowid in blob */ 5566 "last INTEGER, " /* Largest rowid in blob */ 5567 "val BLOB" /* Blob containing rowids + PQ codes */ 5568 ");" 5569 "CREATE INDEX %Q.'%q_idx_idx' ON '%q_idx'(bucket, first, last);" 5570 5571 /* Training data (codebooks and centroids). This is stored as a single 5572 ** blob with id=1, in the same format as returned by vec1_train(). */ 5573 "CREATE TABLE %Q.'%q_model'(id INTEGER PRIMARY KEY, val BLOB);" 5574 5575 /* Meta table. Contains arrays of meta values stored in parallel with 5576 ** arrays in the %_idx table. For column iMeta and %_idx array id=iId, 5577 ** the id used in this table is ((iId<<8) + iMeta). */ 5578 "CREATE TABLE %Q.'%q_meta'(" 5579 "id INTEGER PRIMARY KEY, " 5580 "val BLOB" 5581 ");" 5582 ; 5583 5584 int ii; 5585 char *zMeta = 0; 5586 for(ii=0; iinMeta meta-list builders */ 5672 }; 5673 5674 #define VEC1_BLOCKED_NONE 0 5675 #define VEC1_BLOCKED_PQ 1 5676 #define VEC1_BLOCKED_BIN 2 5677 5678 /* 5679 ** An object of this type is used to accumulate one or more new vector 5680 ** index entries in memory before they are flushed to disk. 5681 */ 5682 typedef struct Vec1Writer Vec1Writer; 5683 struct Vec1Writer { 5684 Vec1Tab *pTab; /* Vec1 table object */ 5685 int bRebuild; /* True if this is a 'rebuild' op */ 5686 float *aResidual; /* Temp space for residual vector */ 5687 u8 *aPQ; /* Temp space for PQ */ 5688 int nBld; /* Size of aBld[] */ 5689 Vec1ListBuilder *aBld; /* Array of list builders */ 5690 }; 5691 5692 #define VEC1_INSTRUMENT_QUERIES 1 5693 5694 #ifdef VEC1_INSTRUMENT_QUERIES 5695 5696 # define VEC1_QINSTR_TOTAL 0 5697 # define VEC1_QINSTR_INITQUERY 1 5698 # define VEC1_QINSTR_COARSE 2 5699 # define VEC1_QINSTR_IDXREAD 3 5700 # define VEC1_QINSTR_METAREAD 4 5701 # define VEC1_QINSTR_METASCAN 5 5702 # define VEC1_QINSTR_LUT 6 5703 # define VEC1_QINSTR_PQSCAN 7 5704 # define VEC1_QINSTR_FINALSORT 8 5705 5706 # define VEC1_QINSTR_NCOUNTER 9 5707 5708 5709 # define VEC1_QINSTR_START(pTab, eCounter) { \ 5710 (pTab)->aCycle[eCounter] -= vec1HardwareTimer(); \ 5711 } 5712 5713 # define VEC1_QINSTR_STOP(pTab, eCounter) { \ 5714 (pTab)->aCount[eCounter]++; \ 5715 (pTab)->aCycle[eCounter] += vec1HardwareTimer(); \ 5716 } 5717 5718 #else 5719 # define VEC1_QINSTR_STOP(pTab, eCounter) 5720 # define VEC1_QINSTR_START(pTab, eCounter) 5721 #endif 5722 5723 #define VEC1_META_COLUMN_BITS 8 5724 #define VEC1_MAX_META_COLUMNS (1<base.zErrMsg); 5893 pTab->base.zErrMsg = zMsg; 5894 } 5895 5896 /* 5897 ** Prepare the SQL statement passed as the second argument. If successful, 5898 ** set (*pStmt) to point to the prepared statement handle and return 5899 ** SQLITE_OK. It is the responsibility of the caller to eventually finalize 5900 ** the statement using sqlite3_finalize(). 5901 ** 5902 ** Or, if an error occurs, set (*ppStmt) to NULL, return an SQLite error 5903 ** code and leave an error message in the virtual table object. 5904 */ 5905 static int vec1PrepareSql( 5906 Vec1Tab *pTab, 5907 sqlite3_stmt **ppStmt, 5908 const char *zFmt, 5909 ... 5910 ){ 5911 char *zSql = 0; 5912 int rc = SQLITE_OK; 5913 va_list ap; 5914 5915 va_start(ap, zFmt); 5916 zSql = sqlite3_vmprintf(zFmt, ap); 5917 va_end(ap); 5918 5919 *ppStmt = 0; 5920 if( zSql ){ 5921 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, ppStmt, 0); 5922 sqlite3_free(zSql); 5923 if( rc!=SQLITE_OK ){ 5924 vec1VtabError(pTab, "%s", sqlite3_errmsg(pTab->db)); 5925 } 5926 }else{ 5927 rc = SQLITE_NOMEM; 5928 } 5929 return rc; 5930 } 5931 5932 #define VEC1_SQL_SCAN_BASE 1 5933 #define VEC1_SQL_INSERT_IDX 2 5934 5935 #define VEC1_SQL_SCAN_IDX 3 5936 #define VEC1_SQL_CNT_IDX 4 5937 5938 #define VEC1_SQL_FILTER_IDX 5 5939 5940 #define VEC1_SQL_WRITE_CONFIG 5 5941 #define VEC1_SQL_INCR_CONFIG 6 5942 #define VEC1_SQL_LOAD_CONFIG 7 5943 5944 5945 5946 5947 static int vec1GetSql(Vec1Tab *pTab, int eSql, sqlite3_stmt **ppStmt){ 5948 const char *azSql[] = { 5949 #define VEC1_SQL_INSERT_BASE 0 5950 "INSERT INTO %Q.'%q_base' VALUES(?, ?%s)", 5951 "SELECT * FROM %Q.'%q_base' ORDER BY 1", 5952 "INSERT INTO %Q.'%q_idx'(id, bucket, first, last, val)VALUES(?,?,?,?,?)", 5953 5954 "SELECT val, bucket, rowid FROM %Q.'%q_idx'", 5955 "SELECT sum( length(val) / ? ) FROM %Q.'%q_idx'", 5956 5957 "REPLACE INTO %Q.'%q_config'(id, val) VALUES(?, ?)", 5958 "INSERT INTO %Q.'%q_config'(id, val) VALUES(?, 1) " 5959 "ON CONFLICT(id) DO UPDATE SET val=val+1", 5960 5961 "SELECT id, val FROM %Q.'%q_config'", 5962 5963 #define VEC1_SQL_LOOKUP_BASE 8 5964 "SELECT * FROM %Q.'%q_base' WHERE id=?", 5965 5966 #define VEC1_SQL_EDIT_IDX 9 5967 "SELECT id, min( length(val) ) FROM %Q.'%q_idx' WHERE bucket=?", 5968 5969 #define VEC1_SQL_DEL_LOOKUP_BASE 10 5970 /* Used when removing a row by id. This statement deletes the %_base 5971 ** entry and returns the vector so that the user may use it to 5972 ** find the %_idx entry to delete. */ 5973 "DELETE FROM %Q.'%q_base' WHERE id=? RETURNING vector", 5974 5975 #define VEC1_SQL_SEARCH_IDX 11 5976 "SELECT id FROM %Q.'%q_idx' WHERE bucket=? AND ? BETWEEN first AND last", 5977 5978 #define VEC1_SQL_SEARCH_IDX_FOR_INSERT 12 5979 "SELECT id, first, last, val " 5980 "FROM %Q.'%q_idx' WHERE bucket=? AND length(val)=0 && eSqlaStmt) ); 6010 6011 if( pTab->aStmt[eSql]==0 ){ 6012 6013 if( eSql==VEC1_SQL_INSERT_BASE ){ 6014 int ii; 6015 char *zExtra = 0; 6016 for(ii=0; iinMeta; ii++){ 6017 zExtra = vec1MPrintf(&rc, "%z,?", zExtra); 6018 } 6019 if( rc==SQLITE_OK ){ 6020 rc = vec1PrepareSql( 6021 pTab, &pTab->aStmt[eSql], azSql[eSql], 6022 pTab->zDb, pTab->zName, zExtra 6023 ); 6024 } 6025 sqlite3_free(zExtra); 6026 }else{ 6027 rc = vec1PrepareSql( 6028 pTab, &pTab->aStmt[eSql], azSql[eSql], pTab->zDb, pTab->zName 6029 ); 6030 } 6031 } 6032 6033 *ppStmt = pTab->aStmt[eSql]; 6034 return rc; 6035 } 6036 6037 static void vec1UnloadModel(Vec1Tab *pTab){ 6038 sqlite3_free(pTab->pModBlob); 6039 sqlite3_free(pTab->mod.aModelT); 6040 vec1ModelFreeTCent(&pTab->mod); 6041 pTab->pModBlob = 0; 6042 pTab->cfg.iModelVersion = 0; 6043 memset(&pTab->mod, 0, sizeof(pTab->mod)); 6044 } 6045 6046 static void vec1UnloadConfig(Vec1Tab *pTab){ 6047 pTab->cfg.nElem = 0; 6048 } 6049 6050 /* 6051 ** xDisconnect method. Free the virtual table object passed as the only 6052 ** argument. 6053 */ 6054 static int vec1DisconnectMethod(sqlite3_vtab *pVtab){ 6055 Vec1Tab *pTab = (Vec1Tab*)pVtab; 6056 int ii; 6057 6058 /* Remove this table object from the database handle list of vec1 tables */ 6059 if( pTab->pTabList ){ 6060 Vec1Tab **pp = &pTab->pTabList->pFirst; 6061 while( *pp!=pTab ) pp = &(*pp)->pTabNext; 6062 *pp = pTab->pTabNext; 6063 } 6064 6065 for(ii=0; iiaStmt); ii++){ 6066 sqlite3_finalize(pTab->aStmt[ii]); 6067 } 6068 vec1UnloadModel(pTab); 6069 sqlite3_free(pTab->zDb); 6070 sqlite3_free(pTab->zName); 6071 sqlite3_free(pTab->zTrainTbl); 6072 sqlite3_free(pTab->zIdxTbl); 6073 sqlite3_free(pTab->aTmpVec); 6074 sqlite3_free(pTab); 6075 return SQLITE_OK; 6076 } 6077 6078 static int vec1SqlExec(Vec1Tab *pTab, const char *zSqlfmt, char **pzErr){ 6079 char *zSql = 0; 6080 int rc = SQLITE_OK; 6081 6082 zSql = sqlite3_mprintf(zSqlfmt, pTab->zDb, pTab->zName); 6083 if( zSql==0 ){ 6084 rc = SQLITE_NOMEM; 6085 }else{ 6086 rc = sqlite3_exec(pTab->db, zSql, 0, 0, pzErr); 6087 sqlite3_free(zSql); 6088 } 6089 6090 return rc; 6091 } 6092 6093 static void vec1StmtReset(int *pRc, sqlite3_stmt *pStmt){ 6094 int rc = sqlite3_reset(pStmt); 6095 if( *pRc==SQLITE_OK ) *pRc = rc; 6096 } 6097 6098 static void vec1StmtFinalize(int *pRc, sqlite3_stmt *pStmt){ 6099 int rc = sqlite3_finalize(pStmt); 6100 if( *pRc==SQLITE_OK ) *pRc = rc; 6101 } 6102 6103 /* 6104 ** Return true if character c is an ASCII range whitespace character. 6105 */ 6106 static int vec1IsWhitespace(char c){ 6107 return (c==' ' || c=='\t' || c=='\r' || c=='\n'); 6108 } 6109 6110 /* 6111 ** Check that zName is a legal name for a vec1 column. A legal column name 6112 ** is any single token or quoted string, with no trailing garbage. For 6113 ** the purposes of this function, a token is a contiguous sequence of 6114 ** non-whitespace characters that do not begin with a quote character. 6115 ** 6116 ** If zName is a legal name (or an illegal name that will be detected by 6117 ** sqlite3_declare_vtab()), SQLITE_OK is returned and (*pzErr) is left 6118 ** unchanged. Or, if it is not a legal name, SQLITE_ERROR is returned, and 6119 ** *pzErr is left to point to a buffer containing an English language 6120 ** error message. It is the responsibility of the caller to eventually 6121 ** free this buffer using sqlite3_free(). 6122 */ 6123 static int vec1CheckColumnName(const char *zName, char **pzErr){ 6124 char aName[16]; 6125 int nName = 0; 6126 const char *z = zName; 6127 6128 while( vec1IsWhitespace(*z) ) z++; 6129 6130 if( (*z)=='"' || (*z)=='\'' || (*z)=='`' ){ 6131 char q = *z++; 6132 while( 1 ){ 6133 if( (*z)=='\0' ){ 6134 *pzErr = sqlite3_mprintf("vec1: unmatched quote character"); 6135 return SQLITE_ERROR; 6136 } 6137 if( (*z)==q ){ 6138 z++; 6139 if( (*z)!=q ) break; 6140 } 6141 if( nName<(int)sizeof(aName) ) aName[nName++] = *z; 6142 z++; 6143 } 6144 } 6145 else if( (*z)=='[' ){ 6146 z++; 6147 while( (*z) && (*z)!=']' ){ 6148 if( nName<(int)sizeof(aName) ) aName[nName++] = *z; 6149 z++; 6150 } 6151 if( (*z)=='\0' ){ 6152 *pzErr = sqlite3_mprintf("vec1: unmatched [ character"); 6153 return SQLITE_ERROR; 6154 } 6155 z++; 6156 } 6157 else { 6158 while( (*z) && 0==vec1IsWhitespace(*z) ){ 6159 if( nName<(int)sizeof(aName) ) aName[nName++] = *z; 6160 z++; 6161 } 6162 } 6163 6164 while( vec1IsWhitespace(*z) ) z++; 6165 if( (*z)!='\0' ){ 6166 *pzErr = sqlite3_mprintf("vec1: trailing characters after column name"); 6167 return SQLITE_ERROR; 6168 } 6169 6170 if( (nName==5 && 0==sqlite3_strnicmp(aName, "rowid", 5)) 6171 || (nName==8 && 0==sqlite3_strnicmp(aName, "distance", 8)) 6172 ){ 6173 *pzErr = sqlite3_mprintf("vec1: reserved column name: %s", zName); 6174 return SQLITE_ERROR; 6175 } 6176 6177 return SQLITE_OK; 6178 } 6179 6180 /* 6181 ** Invoke sqlite3_declare_vtab() for this table. 6182 */ 6183 static int vec1DeclareVtab( 6184 sqlite3 *db, 6185 int argc, 6186 const char *const* argv, 6187 char **pzErr 6188 ){ 6189 const char *zVector = "vector"; 6190 char *zExtra = 0; 6191 char *zCreate = 0; 6192 int rc = SQLITE_OK; 6193 int ii; 6194 6195 for(ii=3; rc==SQLITE_OK && ii3 ){ 6201 zVector = argv[3]; 6202 } 6203 for(ii=4; iizDb = vec1Strdup(&rc, argv[1]); 6252 pTab->zName = vec1Strdup(&rc, argv[2]); 6253 pTab->zTrainTbl = vec1MPrintf(&rc, "%s_model", argv[2]); 6254 pTab->zIdxTbl = vec1MPrintf(&rc, "%s_idx", argv[2]); 6255 pTab->db = db; 6256 pTab->mod.hdr.eDistance = VEC1_DISTANCE_L2; 6257 6258 pTab->nMeta = MAX(argc-4, 0); 6259 if( pTab->nMeta>VEC1_MAX_META_COLUMNS ){ 6260 *pzErr = sqlite3_mprintf( 6261 "too many meta-data columns (max is %d)", VEC1_MAX_META_COLUMNS 6262 ); 6263 rc = SQLITE_ERROR; 6264 } 6265 6266 if( rc==SQLITE_OK ){ 6267 rc = vec1DeclareVtab(db, argc, argv, pzErr); 6268 } 6269 6270 if( rc==SQLITE_OK && bCreate ){ 6271 char *zShadowSchema = vec1ShadowSchema(pTab->zDb, pTab->zName, pTab->nMeta); 6272 if( zShadowSchema==0 ){ 6273 rc = SQLITE_NOMEM; 6274 }else{ 6275 rc = sqlite3_exec(db, zShadowSchema, 0, 0, pzErr); 6276 sqlite3_free(zShadowSchema); 6277 } 6278 if( rc==SQLITE_OK ){ 6279 sqlite3_stmt *pStmt = 0; 6280 rc = vec1GetSql(pTab, VEC1_SQL_WRITE_CONFIG, &pStmt); 6281 if( rc==SQLITE_OK ){ 6282 sqlite3_bind_int(pStmt, 1, VEC1_CONFIG_FMTVERSION); 6283 sqlite3_bind_int(pStmt, 2, VEC1_CURRENT_FMTVERSION); 6284 sqlite3_step(pStmt); 6285 vec1StmtReset(&rc, pStmt); 6286 } 6287 } 6288 } 6289 6290 if( rc!=SQLITE_OK ){ 6291 if( pTab->base.zErrMsg ){ 6292 *pzErr = pTab->base.zErrMsg; 6293 pTab->base.zErrMsg = 0; 6294 } 6295 vec1DisconnectMethod((sqlite3_vtab*)pTab); 6296 return rc; 6297 } 6298 6299 /* Add the new table to the database handle list of vec1 tables. It 6300 ** will be eventually removed by vec1DisconnectMethod(). */ 6301 pTab->pTabList = pTabList; 6302 pTab->pTabNext = pTabList->pFirst; 6303 pTabList->pFirst = pTab; 6304 6305 *ppVtab = &pTab->base; 6306 return SQLITE_OK; 6307 } 6308 6309 /* 6310 ** xCreate / xConnect 6311 */ 6312 static int vec1ConnectMethod( 6313 sqlite3 *db, 6314 void *p, /* Pointer to Vec1TabList for this db */ 6315 int argc, 6316 const char *const *argv, 6317 sqlite3_vtab **ppVtab, 6318 char **pzErr 6319 ){ 6320 return vec1CreateConnect(0, (Vec1TabList*)p, db, argc, argv, ppVtab, pzErr); 6321 } 6322 6323 static int vec1CreateMethod( 6324 sqlite3 *db, 6325 void *p, /* Pointer to Vec1TabList for this db */ 6326 int argc, 6327 const char *const *argv, 6328 sqlite3_vtab **ppVtab, 6329 char **pzErr 6330 ){ 6331 return vec1CreateConnect(1, (Vec1TabList*)p, db, argc, argv, ppVtab, pzErr); 6332 } 6333 6334 static int vec1DestroyMethod(sqlite3_vtab *pVtab){ 6335 Vec1Tab *pTab = (Vec1Tab*)pVtab; 6336 int rc = SQLITE_OK; 6337 6338 char *zDrop = vec1DropShadowSchema(pTab->zDb, pTab->zName); 6339 if( zDrop==0 ){ 6340 rc = SQLITE_NOMEM; 6341 }else{ 6342 rc = sqlite3_exec(pTab->db, zDrop, 0, 0, 0); 6343 sqlite3_free(zDrop); 6344 } 6345 6346 if( rc==SQLITE_OK ){ 6347 vec1DisconnectMethod(pVtab); 6348 } 6349 6350 return rc; 6351 } 6352 6353 /* 6354 ** Cursor methods 6355 */ 6356 static int vec1Open( 6357 sqlite3_vtab *pVtab, 6358 sqlite3_vtab_cursor **ppCursor 6359 ){ 6360 Vec1Csr *pCur; 6361 6362 UNUSED_PARAMETER(pVtab); 6363 6364 pCur = sqlite3_malloc(sizeof(*pCur)); 6365 if( pCur==0 ){ 6366 return SQLITE_NOMEM; 6367 } 6368 memset(pCur, 0, sizeof(*pCur)); 6369 6370 *ppCursor = &pCur->base; 6371 return SQLITE_OK; 6372 } 6373 6374 static void vec1QueryFree(Vec1Query *pQuery){ 6375 if( pQuery ){ 6376 int ii; 6377 for(ii=0; iinFilter; ii++){ 6378 sqlite3_free(pQuery->aFilter[ii].pPtr); 6379 } 6380 sqlite3_free(pQuery->heap.aRes); 6381 sqlite3_free(pQuery->aBucket); 6382 sqlite3_free(pQuery); 6383 } 6384 } 6385 6386 static void vec1ResetCsr(Vec1Csr *pCsr){ 6387 vec1QueryFree(pCsr->pQuery); 6388 sqlite3_finalize(pCsr->pStmt); 6389 pCsr->pStmt = 0; 6390 pCsr->bSeek = 0; 6391 sqlite3_free(pCsr->zDistance); 6392 pCsr->zDistance = 0; 6393 pCsr->bSqlNNQuery = 0; 6394 } 6395 6396 static int vec1Close(sqlite3_vtab_cursor *cur){ 6397 Vec1Csr *pCsr = (Vec1Csr*)cur; 6398 vec1ResetCsr(pCsr); 6399 sqlite3_free(pCsr); 6400 return SQLITE_OK; 6401 } 6402 6403 static void vec1FlatIterNext(Vec1FlatIter *pIter){ 6404 while( 1 ){ 6405 pIter->ii++; 6406 if( pIter->ii>=pIter->nEntry ){ 6407 pIter->iRowid = 0; 6408 pIter->aVec = 0; 6409 break; 6410 }else{ 6411 i64 iRowid = 0; 6412 int iOff = VEC1_LIST_SZHDR + pIter->ii * pIter->szRowid; 6413 if( pIter->szRowid==4 ){ 6414 iRowid = (i64)vec1GetU32(&pIter->aBlob[iOff]); 6415 if( iRowid==VEC1_TOMBSTONE_32 ) continue; 6416 }else{ 6417 iRowid = (i64)vec1GetU64(&pIter->aBlob[iOff]); 6418 if( iRowid==VEC1_TOMBSTONE_64 ) continue; 6419 } 6420 6421 iOff = VEC1_LIST_SZHDR + 6422 (pIter->nEntry * pIter->szRowid) + 6423 (pIter->ii * pIter->szVec); 6424 pIter->aVec = &pIter->aBlob[iOff]; 6425 pIter->iRowid = iRowid; 6426 break; 6427 } 6428 } 6429 } 6430 6431 /* 6432 ** Return the encoded vector size for the model. Two cases: 6433 ** 6434 ** a) PQ encoding. In this case encoded vector size is hdr.nCodebook. 6435 ** 6436 ** b) Bitwise encoding. In this case encoded vector size is 4 bytes + 6437 ** 1 bit per dimension. 6438 */ 6439 static int vec1EncodedVectorSize(const Vec1Model *pMod){ 6440 int ret = (int)pMod->hdr.nCodebook; 6441 if( pMod->hdr.flags & VEC1_MODEL_BITQUANT ) ret += sizeof_f32; 6442 return ret; 6443 } 6444 6445 /* 6446 ** nBlob byte buffer aBlob[] contains a list read from the %_idx table. 6447 ** This function returns zero if the list size matches the embedded 6448 ** number-of-entries field, and so the list may be accessed safely without 6449 ** bounds checking, or non-zero otherwise. 6450 */ 6451 static int vec1CheckIdxSize(Vec1Tab *p, const u8 *aBlob, i64 nBlob){ 6452 int bRet = 1; 6453 6454 /* If the blob is smaller than 8 bytes, it must be corrupt */ 6455 if( nBlob>=VEC1_LIST_SZHDR ){ 6456 6457 /* Read the flags and number-of-entries fields */ 6458 u32 flags = vec1GetU32(&aBlob[0]); 6459 i64 nEntry = (int)vec1GetU32(&aBlob[4]); 6460 const i64 szRowid = ((flags & VEC1_LIST_64BIT) ? 8 : 4); 6461 6462 if( p->mod.hdr.nCodebook>0 ){ 6463 const i64 nBlk = ((nEntry+VEC1_PQ_BLOCKSIZE-1) / VEC1_PQ_BLOCKSIZE); 6464 const i64 szBlk = VEC1_PQ_BLOCKSIZE * vec1EncodedVectorSize(&p->mod); 6465 bRet = (nBlob!=(VEC1_LIST_SZHDR + nEntry*szRowid + nBlk*szBlk)); 6466 }else{ 6467 const i64 szVec = p->cfg.nElem*sizeof_f32; 6468 bRet = (nBlob!=(VEC1_LIST_SZHDR + nEntry*szRowid + nEntry*szVec)); 6469 } 6470 } 6471 return bRet; 6472 } 6473 6474 static int vec1FlatIterStart( 6475 Vec1Tab *pTab, 6476 Vec1FlatIter *pIter, 6477 const u8 *aBlob, 6478 int nBlob 6479 ){ 6480 u32 flags; 6481 6482 pIter->aBlob = aBlob; 6483 pIter->nBlob = nBlob; 6484 pIter->ii = 0; 6485 6486 if( vec1CheckIdxSize(pTab, aBlob, nBlob) ){ 6487 return VEC1_CORRUPT; 6488 } 6489 6490 flags = vec1GetU32(aBlob); 6491 pIter->szRowid = (flags & VEC1_LIST_64BIT) ? 8 : 4; 6492 pIter->nEntry = vec1GetU32(&aBlob[4]); 6493 pIter->szVec = (pTab->cfg.nElem * sizeof_f32); 6494 pIter->ii = -1; 6495 vec1FlatIterNext(pIter); 6496 return SQLITE_OK; 6497 } 6498 6499 /* 6500 ** Merge the two sorted subarrays a[p..q-1] and a[q..r-1] using 6501 ** the temporary buffer aTmp. 6502 */ 6503 static void vec1Merge( 6504 Vec1AnnResult *a, 6505 Vec1AnnResult *aTmp, 6506 int p, 6507 int q, 6508 int r 6509 ){ 6510 int i = p; 6511 int j = q; 6512 int k = p; 6513 6514 while( i1 ){ 6558 i64 nByte = sizeof(Vec1AnnResult) * n; 6559 Vec1AnnResult *aTmp = (Vec1AnnResult*)sqlite3_malloc64(nByte); 6560 if( aTmp==0 ){ 6561 rc = SQLITE_NOMEM; 6562 }else{ 6563 vec1MergeSort(a, aTmp, 0, (int)n); 6564 sqlite3_free(aTmp); 6565 } 6566 } 6567 6568 return rc; 6569 } 6570 6571 static int vec1DoKANNBucket(Vec1Query*,int,Vec1Buffer*,Vec1Buffer*,Vec1Buffer*); 6572 6573 static int vec1StreamingNext(Vec1Csr *pCsr){ 6574 int rc = SQLITE_OK; 6575 Vec1Query *pQuery = pCsr->pQuery; 6576 Vec1AnnHeap *pHeap = &pQuery->heap; 6577 6578 int ii; 6579 int nSort = (int)(pHeap->nRes - pCsr->nCurrentRes); 6580 6581 { 6582 i64 nRes = pHeap->nRes; 6583 pHeap->nRes = 0; 6584 for(ii=pCsr->nCurrentRes; iiaRes[ii].iRowid, pHeap->aRes[ii].fDist); 6586 } 6587 } 6588 6589 while( pQuery->nBucket>0 && nSort<=(pQuery->nOrigRes/2) ){ 6590 Vec1Buffer a = {0,0,0}; 6591 Vec1Buffer b = {0,0,0}; 6592 Vec1Buffer c = {0,0,0}; 6593 int iBest = 0; 6594 int iBucket = 0; 6595 6596 /* Find the nearest remaining bucket to the query vector. Remove it 6597 ** from the aBucket[] array. */ 6598 for(ii=1; iinBucket; ii++){ 6599 if( pQuery->aBucket[ii].fDistaBucket[iBest].fDist ){ 6600 iBest = ii; 6601 } 6602 } 6603 iBucket = pQuery->aBucket[iBest].iBucket; 6604 pQuery->nBucket--; 6605 if( iBest!=pQuery->nBucket ){ 6606 pQuery->aBucket[iBest] = pQuery->aBucket[pQuery->nBucket]; 6607 } 6608 6609 rc = vec1DoKANNBucket(pQuery, iBucket, &a, &b, &c); 6610 6611 vec1BufferFree(&a); 6612 vec1BufferFree(&b); 6613 vec1BufferFree(&c); 6614 if( rc!=SQLITE_OK ) return rc; 6615 } 6616 6617 nSort = (int)MIN(pHeap->nMax, pHeap->nRes); 6618 rc = vec1AnnResultSort(pHeap->aRes, nSort); 6619 if( rc==SQLITE_OK ){ 6620 pCsr->iCurrentRes = 0; 6621 pCsr->nCurrentRes = nSort; 6622 } 6623 6624 return rc; 6625 } 6626 6627 /* 6628 ** xNext() method for vec1 cursors. 6629 */ 6630 static int vec1NextMethod(sqlite3_vtab_cursor *cur){ 6631 int rc = SQLITE_OK; 6632 Vec1Csr *pCsr = (Vec1Csr *)cur; 6633 6634 if( pCsr->zDistance ){ 6635 sqlite3_free(pCsr->zDistance ); 6636 pCsr->zDistance = 0; 6637 } 6638 6639 if( pCsr->pQuery ){ 6640 pCsr->iCurrentRes++; 6641 pCsr->bSeek = 0; 6642 if( pCsr->iCurrentRes>=pCsr->nCurrentRes ){ 6643 /* If this is a streaming query, try to get some more results. */ 6644 if( pCsr->pQuery->bStreaming ){ 6645 rc = vec1StreamingNext(pCsr); 6646 } 6647 6648 /* If this was not a streaming query, or no further results are 6649 ** available, set pStmt to 0 to indicate EOF. */ 6650 if( pCsr->iCurrentRes>=pCsr->nCurrentRes ){ 6651 sqlite3_finalize(pCsr->pStmt); 6652 pCsr->pStmt = 0; 6653 } 6654 } 6655 sqlite3_reset(pCsr->pStmt); 6656 }else{ 6657 rc = sqlite3_step(pCsr->pStmt); 6658 if( rc!=SQLITE_ROW ){ 6659 rc = sqlite3_finalize(pCsr->pStmt); 6660 pCsr->pStmt = 0; 6661 }else{ 6662 rc = SQLITE_OK; 6663 } 6664 } 6665 return rc; 6666 } 6667 6668 static int vec1ModelTransform( 6669 Vec1Model *pMod, 6670 float **paOut 6671 ){ 6672 if( pMod->aModel ){ 6673 const int nCodebook = pMod->hdr.nCodebook; 6674 const int nCodeElem = pMod->nCodeElem; 6675 int M; 6676 6677 float *pOut = (float*)sqlite3_malloc( 6678 sizeof_f32 * nCodebook * nCodeElem * VEC1_PQ_CODEBOOK_SZ 6679 ); 6680 if( pOut==0 ) return SQLITE_NOMEM; 6681 *paOut = pOut; 6682 6683 /* For VEC1_TRANSPOSE_WIDTH==8, the order of elements in output is: 6684 ** 6685 ** aModel[M=0][d=0] [K=0..7] 6686 ** aModel[M=0][d=1] [K=0..7] 6687 ** aModel[M=0][d=2] [K=0..7] 6688 ** ... 6689 ** aModel[M=0][d=(nCodeElem-1)][K=0..7] 6690 ** aModel[M=0][d=0] [K=8..15] 6691 ** aModel[M=0][d=1] [K=8..15] 6692 ** aModel[M=0][d=2] [K=8..15] 6693 ** ... 6694 ** aModel[M=0][d=(nCodeElem-1)][K=248..255] 6695 ** aModel[M=1][d=0] [K=0..7] 6696 ** ... 6697 */ 6698 for(M=0; MaModel[ M * nCodeElem * VEC1_PQ_CODEBOOK_SZ ], 6701 nCodeElem, VEC1_TRANSPOSE_WIDTH, VEC1_PQ_CODEBOOK_SZ, 6702 &pOut[ M * nCodeElem * VEC1_PQ_CODEBOOK_SZ ] 6703 ); 6704 } 6705 } 6706 6707 return SQLITE_OK; 6708 } 6709 6710 6711 /* 6712 ** If it is not already loaded, load the PQ model from disk. 6713 */ 6714 static int vec1LoadModel(Vec1Tab *pTab){ 6715 int rc = SQLITE_OK; 6716 6717 sqlite3 *db = pTab->db; 6718 sqlite3_blob *pBlob = 0; 6719 6720 vec1UnloadModel(pTab); 6721 rc = sqlite3_blob_open(db, pTab->zDb, pTab->zTrainTbl, "val", 1, 0, &pBlob); 6722 if( rc==SQLITE_OK ){ 6723 int nByte = sqlite3_blob_bytes(pBlob); 6724 void *pData = sqlite3_malloc(nByte); 6725 if( pData==0 ){ 6726 rc = SQLITE_NOMEM; 6727 }else{ 6728 rc = sqlite3_blob_read(pBlob, pData, nByte, 0); 6729 } 6730 if( rc==SQLITE_OK ){ 6731 rc = vec1DecodeModel(pData, nByte, &pTab->mod, &pTab->base.zErrMsg); 6732 } 6733 if( rc==SQLITE_OK ){ 6734 pTab->pModBlob = pData; 6735 }else{ 6736 sqlite3_free(pData); 6737 } 6738 sqlite3_blob_close(pBlob); 6739 } 6740 6741 if( rc==SQLITE_OK ){ 6742 rc = vec1ModelTransform(&pTab->mod, &pTab->mod.aModelT); 6743 } 6744 6745 return rc; 6746 } 6747 6748 #if 0 6749 static int vec1AnnResultPartition(Vec1AnnResult *aArr, int iLeft, int iRight){ 6750 double fPivot = aArr[iRight].fDist; /* choose last element */ 6751 int iSmall = iLeft; /* Next small element goes here */ 6752 int ii; 6753 for(ii=iLeft; iiK ){ 6771 iRight = iPivot - 1; 6772 } else { 6773 iLeft = iPivot + 1; 6774 } 6775 } 6776 } 6777 #endif 6778 6779 /* 6780 ** Merge the two sorted subarrays a[p..q-1] and a[q..r-1] using 6781 ** the temporary buffer aTmp. 6782 */ 6783 static void vec1BucketMerge( 6784 Vec1BucketResult *a, 6785 Vec1BucketResult *aTmp, 6786 int p, 6787 int q, 6788 int r 6789 ){ 6790 int i = p; 6791 int j = q; 6792 int k = p; 6793 6794 while( i1 ){ 6838 i64 nByte = sizeof(Vec1BucketResult) * n; 6839 Vec1BucketResult *aTmp = (Vec1BucketResult*)sqlite3_malloc64(nByte); 6840 if( aTmp==0 ){ 6841 rc = SQLITE_NOMEM; 6842 }else{ 6843 vec1BucketMergeSort(a, aTmp, 0, (int)n); 6844 sqlite3_free(aTmp); 6845 } 6846 } 6847 6848 return rc; 6849 } 6850 6851 6852 /* 6853 ** Partition the part of the array between elements iLeft and iRight 6854 ** (inclusive). Return the index of the partition key. 6855 */ 6856 static int vec1BucketPartition(Vec1BucketResult *aArr, int iLeft, int iRight){ 6857 float fPivot = aArr[iRight].fDist; /* choose last element */ 6858 int iSmall = iLeft; /* Next small element goes here */ 6859 int ii; 6860 for(ii=iLeft; ii=0 ); 6879 while( 1 ){ 6880 int iPivot = vec1BucketPartition(aArr, iLeft, iRight); 6881 if( iPivot==K ){ 6882 return; 6883 }else if( iPivot>K ){ 6884 iRight = iPivot - 1; 6885 } else { 6886 iLeft = iPivot + 1; 6887 } 6888 } 6889 } 6890 6891 static int vec1FindBuckets( 6892 Vec1Tab *pTab, 6893 const float *aVec, 6894 int nProbe, 6895 Vec1BucketResult **paBucket 6896 ){ 6897 int nBucket = pTab->mod.hdr.nBucket; 6898 int nElem = pTab->mod.hdr.nElem; 6899 Vec1BucketResult *aRes = 0; 6900 int rc = SQLITE_OK; 6901 6902 aRes = (Vec1BucketResult*)sqlite3_malloc(sizeof(Vec1BucketResult) * nBucket); 6903 6904 if( aRes ){ 6905 int ii; 6906 for(ii=0; iimod.aCentroid[ii*nElem]; 6908 aRes[ii].iBucket = ii; 6909 aRes[ii].fDist = (float)vec1L2Dist(aVec, aCentroid, nElem); 6910 } 6911 6912 if( nProbe=aRes[nProbe].fDist ); 6921 } 6922 } 6923 #endif 6924 #if 0 6925 for(ii=0; iihdr.flags & VEC1_MODEL_ROTATE) ){ 6948 vec1RotateVector(pMod->hdr.nElem, pMod->aRotation, aInput, aTmp); 6949 if( pMod->hdr.eDistance==VEC1_DISTANCE_COS ){ 6950 vec1NormalizeVector(aTmp, pMod->hdr.nElem); 6951 } 6952 aRet = aTmp; 6953 }else{ 6954 const int nCodebook = pMod->hdr.nCodebook; 6955 if( 6956 (pMod->hdr.flags & VEC1_MODEL_WHT) 6957 || (pMod->hdr.eDistance==VEC1_DISTANCE_COS) 6958 || (nCodebook>0 && (nCodebook*pMod->nCodeElem)!=pMod->hdr.nElem) 6959 ){ 6960 memcpy(aTmp, aRet, pMod->hdr.nElem * sizeof_f32); 6961 /* If distance=cos, normalize the vector before applying the WHT 6962 ** transform. This is because the WHT transform scales the vector 6963 ** by sqrt(nElem). But so long as training, building and querying 6964 ** all do the normalization first, and not after WHT, things work 6965 ** out fine. */ 6966 if( pMod->hdr.eDistance==VEC1_DISTANCE_COS ){ 6967 vec1NormalizeVector(aTmp, pMod->hdr.nElem); 6968 } 6969 if( (pMod->hdr.flags & VEC1_MODEL_WHT) ){ 6970 vec1ApplyWHT(aTmp, pMod->hdr.nElem); 6971 } 6972 aRet = aTmp; 6973 } 6974 } 6975 6976 return aRet; 6977 } 6978 6979 /* 6980 ** Return true if vec1TransformRequired() is not a no-op. i.e. if any 6981 ** transformation is required for input vectors. 6982 */ 6983 static int vec1TransformRequired(const Vec1Model *pMod){ 6984 Vec1ModelHeader const *p = &pMod->hdr; 6985 return 6986 (p->flags & (VEC1_MODEL_ROTATE|VEC1_MODEL_WHT)) 6987 || (p->eDistance==VEC1_DISTANCE_COS); 6988 } 6989 6990 6991 /* 6992 ** This routine is the core of both the LUT builder and the vector encoder. 6993 ** 6994 ** pIn: 6995 ** pIn is an array of VEC1_TRANSPOSE_WIDTH nCodeElem-dimension vectors in 6996 ** column major format. That is to say, pIn[0] is the first element of 6997 ** the first vector, pIn[1] is the first element of the second vector, 6998 ** and so on. 6999 ** 7000 ** In other words, to find element i of vector v: 7001 ** 7002 ** pIn[i * VEC1_TRANSPOSE_WIDTH + v] 7003 ** 7004 ** aVec: 7005 ** A single vector with nCodeElem elements.. 7006 ** 7007 ** nCodeElem: 7008 ** Size of vectors in elements. 7009 ** 7010 ** aOut: 7011 ** Array of VEC1_TRANSPOSE_WIDTH. Populated with the square of the L2 distance 7012 ** between aVec[] and each of the vectors in pIn. 7013 */ 7014 static void vec1ModelTDist( 7015 const float *pIn, 7016 const float *aVec, 7017 int nCodeElem, 7018 float *aOut 7019 ){ 7020 int d; 7021 7022 #if defined(VEC1_HAVE_AVX2) 7023 __m256 acc[ VEC1_TRANSPOSE_WIDTH / 8 ]; 7024 const int nAcc = (VEC1_TRANSPOSE_WIDTH / 8); 7025 int c; 7026 7027 for(c=0; c>7)&0x7f)|0x80; 7078 aBuf[1] = v&0x7f; 7079 return 2; 7080 } 7081 { 7082 u8 a[10]; 7083 int ii; 7084 int nRet; 7085 for(nRet=0; v; nRet++){ 7086 a[nRet] = (v&0x7F); 7087 v = v >> 7; 7088 } 7089 for(ii=0; iimod.hdr.nCodebook; 7125 const int nCodeElem = pTab->mod.nCodeElem; 7126 int M, K; 7127 float *pIn = pTab->mod.aModelT; 7128 7129 for(M=0; Mcfg.nElem; 7160 int nCodebook = pTab->mod.hdr.nCodebook; 7161 const int nCodeElem = pTab->mod.nCodeElem; 7162 7163 int M; 7164 float c = 1.0f / (float)sqrt((double)nVec); 7165 7166 assert( nCodeElem==8 || nCodeElem==16 ); 7167 7168 for(M=0; M=0 && iMetan = 0; 7220 sqlite3_bind_int64(pStmt, 1, iMetaId); 7221 if( SQLITE_ROW==sqlite3_step(pStmt) ){ 7222 int nByte = sqlite3_column_bytes(pStmt, 0); 7223 rc = vec1BufferGrow(pBuf, nByte + VEC1_META_PADDING); 7224 if( rc==SQLITE_OK ){ 7225 const u8 *a = sqlite3_column_blob(pStmt, 0); 7226 memcpy(pBuf->a, a, nByte); 7227 memset(&pBuf->a[nByte], 0, VEC1_META_PADDING); 7228 pBuf->n = nByte; 7229 } 7230 } 7231 vec1StmtReset(&rc, pStmt); 7232 7233 /* Check, so far as is possible, that the meta-value blob is the 7234 ** expected size. It is not possible to check if the meta-value blob 7235 ** uses the GENERIC format, due to the variable length fields. Code 7236 ** that handles GENERIC meta-value blobs has to dynamically verify 7237 ** the buffer size. */ 7238 if( rc==SQLITE_OK ){ 7239 if( pBuf->na[0]) & VEC1_META_TYPEMASK); 7243 u32 nEntry = vec1GetU32(&pBuf->a[4]); 7244 i64 sz = 0; 7245 if( nEntry!=nExpect ){ 7246 rc = VEC1_CORRUPT; 7247 } 7248 if( tflag==VEC1_META_1BYTEINT ){ 7249 sz = 1; 7250 }else if( tflag==VEC1_META_4BYTEINT ){ 7251 sz = sizeof_u32; 7252 }else if( tflag==VEC1_META_REAL ){ 7253 sz = sizeof_f64; 7254 }else if( tflag!=VEC1_META_GENERIC ){ 7255 rc = VEC1_CORRUPT; 7256 } 7257 7258 if( sz && pBuf->n!=(VEC1_META_SZHDR + sz*nEntry) ){ 7259 rc = VEC1_CORRUPT; 7260 } 7261 } 7262 } 7263 7264 } 7265 7266 return rc; 7267 } 7268 7269 /* 7270 ** 0: NULL value. 0 byte payload. 7271 ** 1: Integer value. 1 byte payload. 7272 ** 2: Integer value. 4 byte payload. 7273 ** 3: Integer value. 8 byte payload. 7274 ** 4: Real value. 8 byte payload. 7275 */ 7276 static int vec1MetaValueRead( 7277 Vec1Buffer *pMeta, 7278 int *piOff, 7279 Vec1MetaValue *pVal 7280 ){ 7281 i64 iOff = (i64)*piOff; 7282 7283 switch( pMeta->a[iOff] ){ 7284 case 0: { 7285 pVal->eType = SQLITE_NULL; 7286 iOff++; 7287 break; 7288 } 7289 7290 case 1: { 7291 pVal->eType = SQLITE_INTEGER; 7292 pVal->iVal = (i64)(u8)pMeta->a[iOff+1]; 7293 iOff += 2; 7294 break; 7295 } 7296 7297 case 2: { 7298 pVal->eType = SQLITE_INTEGER; 7299 pVal->iVal = (int)vec1GetU32(&pMeta->a[iOff+1]); 7300 iOff += 5; 7301 break; 7302 } 7303 7304 case 3: { 7305 pVal->eType = SQLITE_INTEGER; 7306 pVal->iVal = (i64)vec1GetU64(&pMeta->a[iOff+1]); 7307 iOff += 9; 7308 break; 7309 } 7310 7311 case 4: { 7312 u64 iVal = vec1GetU64(&pMeta->a[iOff+1]); 7313 memcpy(&pVal->fVal, &iVal, sizeof(u64)); 7314 pVal->eType = SQLITE_FLOAT; 7315 iOff += 9; 7316 break; 7317 } 7318 7319 default: { 7320 u64 eType = 0; 7321 iOff += vec1GetVarint(&pMeta->a[iOff], &eType); 7322 pVal->pPtr = &pMeta->a[iOff]; 7323 pVal->iVal = (((eType-5) / 2) & (u64)0xFFFFFFFF); 7324 iOff += pVal->iVal; 7325 pVal->eType = (eType & 0x01) ? SQLITE_TEXT : SQLITE_BLOB; 7326 break; 7327 } 7328 } 7329 7330 if( iOff>pMeta->n || iOff<0 ){ 7331 return VEC1_CORRUPT; 7332 } 7333 7334 *piOff = (int)iOff; 7335 return SQLITE_OK; 7336 } 7337 7338 /* 7339 ** Compare numeric values a and b. Return -1, 0 or +1 if a is smaller than, 7340 ** equal to, or greater than b, respectively. i.e. (a) - (b). 7341 */ 7342 #define COMPARE(a, b) ((a)==(b) ? 0 : ((a)>(b) ? +1 : -1)) 7343 7344 /* 7345 ** Return 0 if the meta value passes the filter, or 1 if it is excluded 7346 ** by the filter. This is the slow path that can do any operator for 7347 ** any types of values. 7348 */ 7349 static int vec1MetaValueFilter(Vec1Filter *pFilter, Vec1MetaValue *pMeta){ 7350 int cmp = 0; 7351 7352 if( pFilter->vop==VEC1_OP_IN ){ 7353 int ii; 7354 for(ii=0; iiiVal; ii++){ 7355 if( vec1MetaValueFilter(&pFilter[ii+1], pMeta)==0 ) return 0; 7356 } 7357 return 1; 7358 } 7359 7360 if( pMeta->eType==SQLITE_INTEGER ){ 7361 switch( pFilter->eType ){ 7362 case SQLITE_NULL: return 1; 7363 7364 case SQLITE_INTEGER: { 7365 cmp = COMPARE(pFilter->iVal, pMeta->iVal); 7366 break; 7367 } 7368 case SQLITE_FLOAT: { 7369 cmp = COMPARE(pFilter->fVal, (double)pMeta->iVal); 7370 break; 7371 } 7372 default: { 7373 /* All text and blob are bigger than all numbers */ 7374 cmp = +1; 7375 break; 7376 } 7377 } 7378 } 7379 else if( pMeta->eType==SQLITE_FLOAT ){ 7380 switch( pFilter->eType ){ 7381 case SQLITE_NULL: return 1; 7382 7383 case SQLITE_INTEGER: { 7384 cmp = COMPARE((double)pFilter->iVal, pMeta->fVal); 7385 break; 7386 } 7387 case SQLITE_FLOAT: { 7388 cmp = COMPARE(pFilter->fVal, pMeta->fVal); 7389 break; 7390 } 7391 default: { 7392 /* All text and blob are bigger than all numbers */ 7393 cmp = +1; 7394 break; 7395 } 7396 } 7397 }else if( pMeta->eType==SQLITE_NULL ){ 7398 if( pFilter->vop==VEC1_OP_IS && pFilter->eType==SQLITE_NULL ) return 0; 7399 return 1; 7400 }else if( pMeta->eType==SQLITE_TEXT ){ 7401 switch( pFilter->eType ){ 7402 case SQLITE_NULL: return 1; 7403 7404 case SQLITE_INTEGER: 7405 case SQLITE_FLOAT: { 7406 cmp = -1; 7407 break; 7408 } 7409 7410 case SQLITE_TEXT: { 7411 i64 n = MIN(pMeta->iVal, pFilter->iVal); 7412 if( n>0 ){ 7413 cmp = memcmp(pFilter->pPtr, pMeta->pPtr, n); 7414 } 7415 if( cmp==0 ) cmp = COMPARE(pFilter->iVal, pMeta->iVal); 7416 break; 7417 } 7418 7419 default: { 7420 assert( pFilter->eType==SQLITE_BLOB ); 7421 cmp = 1; 7422 break; 7423 } 7424 } 7425 }else{ 7426 assert( pMeta->eType==SQLITE_BLOB ); 7427 switch( pFilter->eType ){ 7428 case SQLITE_NULL: return 1; 7429 7430 case SQLITE_INTEGER: 7431 case SQLITE_FLOAT: 7432 case SQLITE_TEXT: { 7433 cmp = -1; 7434 break; 7435 } 7436 7437 default: { 7438 i64 n = MIN(pMeta->iVal, pFilter->iVal); 7439 if( n>0 ) cmp = memcmp(pFilter->pPtr, pMeta->pPtr, n); 7440 if( cmp==0 ) cmp = COMPARE(pFilter->iVal, pMeta->iVal); 7441 assert( pFilter->eType==SQLITE_BLOB ); 7442 break; 7443 } 7444 } 7445 } 7446 7447 switch( pFilter->vop ){ 7448 case VEC1_OP_IS: 7449 case VEC1_OP_EQ: return !(cmp==0); 7450 case VEC1_OP_LT: return !(cmp>0); 7451 case VEC1_OP_LE: return !(cmp>=0); 7452 case VEC1_OP_GT: return !(cmp<0); 7453 case VEC1_OP_GE: return !(cmp<=0); 7454 } 7455 7456 assert( pFilter->vop==VEC1_OP_NOTNULL ); 7457 return 0; 7458 } 7459 7460 /* 7461 ** This is called as part of meta-data filtering when the meta-data field 7462 ** in question is stored in either VEC1_META_1BYTEINT or VEC1_META_4BYTEINT 7463 ** format. 7464 ** 7465 ** iMin, iMax, eNull: 7466 ** These three parameters describe the integer format used to store 7467 ** the meta-data field (either VEC1_META_1BYTEINT or VEC1_META_4BYTEINT). 7468 ** They pass the minimum integer value, maximum possible integer value 7469 ** and the value used to indicate NULL. So, for the two formats, they 7470 ** are: 7471 ** 7472 ** VEC1_META_1BYTEINT: 0, 254, 255. 7473 ** VEC1_META_4BYTEINT: -`2147483648`, +`2147483646`, +`2147483647` 7474 ** 7475 ** pOp: 7476 ** Output parameter. If it is guaranteed that no entries in the meta-data 7477 ** field will match the filter (i.e. so zero rows will be returned), set 7478 ** this to 0. Otherwise, set it to one of the VEC1_OP_XXX constants to 7479 ** indicate the operation that should be used to test each value in the 7480 ** meta-data field. 7481 ** 7482 ** pRval: 7483 ** OUTPUT parameter. If (*pOp) is VEC1_OP_IN, then this is set to the 7484 ** number of entries in the (*paRval) array output. Otherwise, it is 7485 ** set to the integer value to use as the RHS of the comparison when 7486 ** testing each meta-data value. 7487 ** 7488 ** paRval: 7489 ** OUTPUT parameter. If (*pOp) is VEC1_OP_IN, an array of values to 7490 ** compare each meta-data value to. Otherwise, 0. 7491 ** 7492 ** Return SQLITE_OK if successful, or an SQLite error code (SQLITE_NOMEM) 7493 ** if an error occurs. 7494 */ 7495 static int vec1FilterToIntOp( 7496 Vec1Filter *pFilter, /* The constraint doing the filtering */ 7497 i64 iMin, i64 iMax, i64 eNull, /* Meta-data format description */ 7498 int *pRval, 7499 int **paRval, 7500 u8 *pOp 7501 ){ 7502 /* Set the following three values as follows: 7503 ** 7504 ** res: 0 if the result can be determined to be false for all list 7505 ** entries. 1 if it is true for all non-null list entries. Or 7506 ** -1 if scanning the list using op and rval is required to 7507 ** determine which list entries match the condition. 7508 ** 7509 ** op: If res is -1, one of VEC1_OP_EQ, VEC1_OP_GT, VEC1_OP_GE, 7510 ** VEC1_OP_LT or VEC1_OP_LE. 7511 ** 7512 ** rval: A value to compare using op with all list entries. 7513 ** 7514 ** Then, if res is not 0 or 1, run through the list comparing each 7515 ** list value with value rval using operation op. 7516 */ 7517 int res = -1; 7518 int rval = 0; 7519 u8 op = 0; 7520 7521 assert( (iMin==0 && iMax==254 && eNull==255) || ( 7522 iMin==VEC1_META_4BYTEMIN 7523 && iMax==VEC1_META_4BYTEMAX 7524 && eNull==VEC1_META_4BYTENULL 7525 )); 7526 7527 if( pFilter->vop==VEC1_OP_IN ){ 7528 int *aRval = (int*)vec1MallocZero(sizeof_u32 * (pFilter->iVal+1)); 7529 if( aRval==0 ){ 7530 return SQLITE_NOMEM; 7531 }else{ 7532 int ii; 7533 int nRval = 0; 7534 for(ii=0; iiiVal; ii++){ 7535 vec1FilterToIntOp(&pFilter[ii+1], iMin, iMax, eNull, &rval, 0, &op); 7536 if( op==VEC1_OP_EQ ){ 7537 aRval[nRval++] = rval; 7538 } 7539 } 7540 op = VEC1_OP_IN; 7541 rval = nRval; 7542 *paRval = aRval; 7543 } 7544 }else if( pFilter->vop==VEC1_OP_NOTNULL ){ 7545 res = 1; 7546 }else if( pFilter->eType==SQLITE_NULL && pFilter->vop==VEC1_OP_IS ){ 7547 rval = (int)eNull; 7548 op = VEC1_OP_EQ; 7549 7550 }else if( pFilter->eType!=SQLITE_NULL ){ 7551 i64 iVal = pFilter->iVal; 7552 7553 if( pFilter->eType==SQLITE_TEXT || pFilter->eType==SQLITE_BLOB ){ 7554 /* All text and blob values are greater than all 1-byte ints */ 7555 iVal = iMax+10; 7556 }else if( pFilter->eType==SQLITE_FLOAT ){ 7557 iVal = (i64)pFilter->fVal; 7558 if( (double)iVal!=pFilter->fVal ){ 7559 if( pFilter->vop==VEC1_OP_EQ || pFilter->vop==VEC1_OP_IS ){ 7560 iVal = iMin-10; 7561 }else if( pFilter->vop==VEC1_OP_LT || pFilter->vop==VEC1_OP_GE ){ 7562 iVal = iVal+1; 7563 } 7564 } 7565 } 7566 7567 if( iValvop==VEC1_OP_GT || pFilter->vop==VEC1_OP_GE); 7569 }else if( iVal>iMax ){ 7570 res = (pFilter->vop==VEC1_OP_LT || pFilter->vop==VEC1_OP_LE); 7571 }else{ 7572 rval = (int)iVal; 7573 op = (pFilter->vop==VEC1_OP_IS ? VEC1_OP_EQ : pFilter->vop); 7574 } 7575 } 7576 7577 if( res>0 ){ 7578 assert( eNull==(iMax+1) ); 7579 op = VEC1_OP_LT; 7580 rval = (int)eNull; 7581 } 7582 7583 *pRval = rval; 7584 *pOp = op; 7585 return SQLITE_OK; 7586 } 7587 7588 7589 static void vec1MetaFilterIntTail( 7590 const u8 *aMeta, 7591 int iBitOff, 7592 u8 *aBitmask, 7593 int nEntry, 7594 int szInt, 7595 int rval, 7596 int *aRval, 7597 u8 op 7598 ){ 7599 const int eNull = szInt==1 ? VEC1_META_1BYTENULL : VEC1_META_4BYTENULL; 7600 int jj; 7601 assert( szInt==1 || szInt==4 ); 7602 for(jj=0; jjrval) && iVal!=eNull; 7618 break; 7619 7620 case VEC1_OP_LT: 7621 bSet = (iVal=rval) && iVal!=eNull; 7626 break; 7627 7628 case VEC1_OP_LE: 7629 bSet = (iVal<=rval); 7630 break; 7631 7632 default: { 7633 int ii; 7634 assert( op==VEC1_OP_IN ); 7635 for(ii=0; ii0x01 */ 7792 hi = vshr_n_u8(hi, 7); 7793 m1 = (u16)vaddlvq_u16(vmull_u8(lo, w)); 7794 m2 = (u16)vaddlvq_u16(vmull_u8(hi, w)); 7795 } 7796 7797 aBitmask[(jj/8)] |= ~m1; 7798 aBitmask[(jj/8)+1] |= ~m2; 7799 } 7800 #endif 7801 7802 vec1MetaFilterIntTail( 7803 &a[jj], jj, aBitmask, nEntry-jj, 1, rval, aRval, op 7804 ); 7805 } 7806 7807 static void vec1MetaFilterScan4ByteArray( 7808 const int *a, 7809 u8 *aBitmask, 7810 int nEntry, 7811 int rval, int *aRval, u8 op 7812 ){ 7813 int jj = 0; 7814 7815 #if defined(VEC1_HAVE_AVX2) 7816 const __m256i rhs = _mm256_set1_epi32(rval); 7817 const __m256i null = _mm256_set1_epi32(VEC1_META_4BYTENULL); 7818 7819 /* Shuffle mask used to swap the byte-order of the 32-bit integers 7820 ** in this meta-data list if required. There are no big-endian AVX2 7821 ** systems, so no need for a runtime check here. */ 7822 const __m256i swap = _mm256_setr_epi8( 7823 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12, 7824 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12 7825 ); 7826 7827 for(; jj<(nEntry-7); jj+=8){ 7828 __m256i lhs = _mm256_loadu_si256((__m256i*)&a[jj]); 7829 u8 mask = 0; 7830 7831 /* Shuffle the 8 32-bit int values to little-endian order */ 7832 lhs = _mm256_shuffle_epi8(lhs, swap); 7833 7834 switch( op ){ 7835 7836 case VEC1_OP_EQ: { 7837 __m256i cmp = _mm256_cmpeq_epi32(lhs, rhs); 7838 mask = (u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7839 break; 7840 } 7841 7842 case VEC1_OP_GT: { 7843 __m256i cmp = _mm256_cmpgt_epi32(lhs, rhs); 7844 mask = (u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7845 cmp = _mm256_cmpeq_epi32(lhs, null); 7846 mask &= ~(u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7847 break; 7848 } 7849 7850 case VEC1_OP_LT: { 7851 __m256i cmp = _mm256_cmpgt_epi32(rhs, lhs); 7852 mask = (u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7853 break; 7854 } 7855 7856 case VEC1_OP_GE: { 7857 __m256i cmp = _mm256_cmpgt_epi32(rhs, lhs); 7858 mask = ~(u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7859 cmp = _mm256_cmpeq_epi32(lhs, null); 7860 mask &= ~(u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7861 break; 7862 } 7863 7864 case VEC1_OP_LE: { 7865 __m256i cmp = _mm256_cmpgt_epi32(lhs, rhs); 7866 mask = ~(u8)_mm256_movemask_ps(_mm256_castsi256_ps(cmp)); 7867 break; 7868 } 7869 7870 default: { 7871 int ii; 7872 assert( op==VEC1_OP_IN ); 7873 for(ii=0; iin<(VEC1_META_SZHDR+(nEntry*szInt)) ){ 7972 rc = VEC1_CORRUPT; 7973 }else{ 7974 int *aRval = 0; 7975 int rval = 0; 7976 u8 op = 0; 7977 7978 rc = vec1FilterToIntOp(pFilter, 7979 (szInt==4 ? VEC1_META_4BYTEMIN : 0), 7980 (szInt==4 ? VEC1_META_4BYTEMAX : 254), 7981 (szInt==4 ? VEC1_META_4BYTENULL : VEC1_META_1BYTENULL), 7982 &rval, &aRval, &op 7983 ); 7984 if( rc==SQLITE_OK ){ 7985 if( op==0 ){ 7986 /* No entries will match. Set the "filtered-out" bit for all rows. */ 7987 memset(pBitmask->a, 0xFF, pBitmask->n); 7988 }else if( szInt==4 ){ 7989 const int *a = (const int*)&pMeta->a[VEC1_META_SZHDR]; 7990 vec1MetaFilterScan4ByteArray(a, pBitmask->a, nEntry, rval, aRval, op); 7991 }else{ 7992 const u8 *a = (const u8*)&pMeta->a[VEC1_META_SZHDR]; 7993 assert( szInt==1 ); 7994 vec1MetaFilterScan1ByteArray(a, pBitmask->a, nEntry, rval, aRval, op); 7995 } 7996 } 7997 sqlite3_free(aRval); 7998 } 7999 8000 return rc; 8001 } 8002 8003 static VEC1_NOINLINE int vec1DoMetaFilters( 8004 Vec1Tab *pTab, 8005 Vec1Query *pQuery, 8006 i64 iId, 8007 int nEntry, 8008 Vec1Buffer *pMeta, 8009 Vec1Buffer *pBitmask 8010 ){ 8011 int rc = SQLITE_OK; 8012 int ii; 8013 8014 /* Grow and zero the bitmask array. */ 8015 int nByte = (nEntry+7)/8; 8016 pBitmask->n = 0; 8017 rc = vec1BufferGrow(pBitmask, nByte); 8018 if( rc==SQLITE_OK ){ 8019 memset(pBitmask->a, 0, nByte); 8020 } 8021 pBitmask->n = nByte; 8022 8023 assert( pQuery->nFilter>0 ); 8024 8025 for(ii=0; rc==SQLITE_OK && iinFilter; ii++){ 8026 Vec1Filter *pFilter = &pQuery->aFilter[ii]; 8027 VEC1_QINSTR_START(pTab, VEC1_QINSTR_METAREAD); 8028 rc = vec1ReadMeta(pTab, nEntry, pMeta, iId, pFilter->iMeta); 8029 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_METAREAD); 8030 8031 VEC1_QINSTR_START(pTab, VEC1_QINSTR_METASCAN); 8032 if( rc==SQLITE_OK ){ 8033 int jj = 0; 8034 u32 f = vec1GetU32(pMeta->a); 8035 8036 if( f & VEC1_META_1BYTEINT ){ 8037 /* Single-byte integer format */ 8038 rc = vec1MetaFilterIntList(pFilter, 1, nEntry, pMeta, pBitmask); 8039 }else if( f & VEC1_META_4BYTEINT ){ 8040 /* 4-byte integer format */ 8041 rc = vec1MetaFilterIntList(pFilter, 4, nEntry, pMeta, pBitmask); 8042 }else if( f & VEC1_META_REAL ){ 8043 Vec1MetaValue val = {0, 0, 0, 0}; 8044 for(jj=0; jja[VEC1_META_SZHDR+jj*sizeof_f64] 8047 ); 8048 8049 if( iVal==VEC1_META_REALNULL ){ 8050 val.eType = SQLITE_NULL; 8051 }else{ 8052 val.eType = SQLITE_FLOAT; 8053 memcpy(&val.fVal, &iVal, sizeof(u64)); 8054 } 8055 8056 if( vec1MetaValueFilter(pFilter, &val) ){ 8057 pBitmask->a[jj / 8] |= (1 << (jj % 8)); 8058 } 8059 } 8060 }else{ 8061 /* Generic format */ 8062 int iOff = VEC1_META_SZHDR; 8063 for(jj=0; jja[jj / 8] |= (1 << (jj % 8)); 8069 } 8070 } 8071 } 8072 } 8073 8074 if( pFilter->vop==VEC1_OP_IN ){ 8075 ii += (int)pFilter->iVal; 8076 } 8077 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_METASCAN); 8078 } 8079 return rc; 8080 } 8081 8082 static void vec1EncodeVectorBit( 8083 const Vec1Model *pMod, /* Model */ 8084 const float *aVec, /* Input vector */ 8085 u8 *aCode /* OUT: Encoded vector */ 8086 ){ 8087 const int nElem = (int)pMod->hdr.nElem; 8088 float norm; 8089 int ii; 8090 u8 *pOut; 8091 8092 assert( pMod->hdr.flags & VEC1_MODEL_BITQUANT ); 8093 norm = (float)vec1VectorNorm2(aVec, nElem); 8094 norm = (float)sqrt(norm); 8095 memcpy(aCode, &norm, sizeof_f32); 8096 8097 assert( pMod->nCodeElem==8 || pMod->nCodeElem==16 ); 8098 8099 pOut = &aCode[4]; 8100 for(ii=0; iinCodeElem){ 8101 u8 v = 0; 8102 int jj; 8103 if( pMod->nCodeElem==8 ){ 8104 for(jj=0; jj<8; jj++){ 8105 if( aVec[ii+jj]>0.0 ){ 8106 v |= (1<0.0 ){ 8112 v |= (1<hdr.nCodebook; 8128 const int nCodeElem = pMod->nCodeElem; 8129 const float *pIn = pMod->aModelT; 8130 int M, K; 8131 8132 for(M=0; Mhdr.flags & VEC1_MODEL_BITQUANT ){ 8157 vec1EncodeVectorBit(pMod, aVec, aCode); 8158 }else{ 8159 vec1EncodeVectorPQ(pMod, aVec, aCode); 8160 } 8161 } 8162 8163 /* 8164 ** Buffer aCode[] contains a vector quantized according to model pMod. 8165 ** This function (lossily) reconstructs the original vector and writes 8166 ** it to buffer aVec[] before returning. 8167 */ 8168 static void vec1DecodeVector( 8169 const Vec1Model *pMod, /* Model used to encode vector */ 8170 const u8 *aCode, /* Encoded vector */ 8171 float *aVec /* Populate this buffer with full vector */ 8172 ){ 8173 const int nElem = (int)pMod->hdr.nElem; 8174 if( pMod->hdr.flags & VEC1_MODEL_BITQUANT ){ 8175 float fNorm = 0.0; 8176 float fVal = 0.0; 8177 int ii; 8178 8179 /* The first 4 bytes of the encoded vector store the norm of the vector, 8180 ** as a 32-bit float. */ 8181 memcpy(&fNorm, aCode, sizeof_f32); 8182 8183 /* The reconstructed vector uses the following value as the magnitude 8184 ** of each dimension. The value is -ve if the corresponding bit is clear, 8185 ** or +ve if it is set. */ 8186 fVal = (float)sqrt((fNorm*fNorm) / nElem); 8187 8188 assert( pMod->nCodeElem==8 || pMod->nCodeElem==16 ); 8189 for(ii=0; iinCodeElem==8 ){ 8191 if( aCode[sizeof_f32 + (ii/8)] & (1 << (ii%8)) ){ 8192 aVec[ii] = fVal; 8193 }else{ 8194 aVec[ii] = -1 * fVal; 8195 } 8196 }else{ 8197 if( aCode[sizeof_f32 + (ii/16)] & (1 << ((ii/2)%8)) ){ 8198 aVec[ii] = fVal; 8199 }else{ 8200 aVec[ii] = -1 * fVal; 8201 } 8202 } 8203 } 8204 }else{ 8205 int ii; 8206 for(ii=0; ii<(int)pMod->hdr.nCodebook; ii++){ 8207 const float *aCopy = &pMod->aModel[ 8208 (ii * VEC1_PQ_CODEBOOK_SZ + aCode[ii]) * pMod->nCodeElem 8209 ]; 8210 int nCopy = MIN(pMod->nCodeElem, nElem - ii*pMod->nCodeElem); 8211 memcpy(&aVec[ii * pMod->nCodeElem], aCopy, nCopy*sizeof_f32); 8212 } 8213 } 8214 } 8215 8216 /* 8217 ** Return true if any value in aAcc[] is less than fMin. False otherwise. 8218 */ 8219 static int vec1AnyLessThan(const float aAcc[16], float fMin){ 8220 #if defined(VEC1_HAVE_AVX2) 8221 __m256 vMin = _mm256_set1_ps(fMin); 8222 __m256 cmp0 = _mm256_cmp_ps(_mm256_loadu_ps(aAcc), vMin, _CMP_LT_OQ); 8223 __m256 cmp1 = _mm256_cmp_ps(_mm256_loadu_ps(aAcc+8), vMin, _CMP_LT_OQ); 8224 __m256 mask = _mm256_or_ps(cmp0, cmp1); 8225 return _mm256_movemask_ps(mask)!=0; 8226 #elif defined(VEC1_HAVE_NEON) 8227 float32x4_t vMin = vdupq_n_f32(fMin); 8228 uint32x4_t cmp0 = vcltq_f32(vld1q_f32(aAcc), vMin); 8229 uint32x4_t cmp1 = vcltq_f32(vld1q_f32(aAcc+4), vMin); 8230 uint32x4_t cmp2 = vcltq_f32(vld1q_f32(aAcc+8), vMin); 8231 uint32x4_t cmp3 = vcltq_f32(vld1q_f32(aAcc+12), vMin); 8232 uint32x4_t mask = vorrq_u32(vorrq_u32(cmp0, cmp1), vorrq_u32(cmp2, cmp3)); 8233 return vmaxvq_u32(mask)!=0; 8234 #else 8235 int ii; 8236 for(ii=0; ii<16; ii++){ 8237 if( aAcc[ii]bStreaming==0 ){ 8260 iEarly = (nCodebook/4); 8261 } 8262 8263 assert( nNorm==sizeof_f32 || nNorm==0 ); 8264 8265 /* One iteration of this loop for each block in the blob. */ 8266 for(iOff=VEC1_LIST_SZHDR + nEntry*szRowid; 8267 iOff=iEarly && (iBook & 0x03)==0x03 8289 && vec1AnyLessThan(aAcc, (float)pHeap->fMin)==0 8290 ){ 8291 goto skip; 8292 } 8293 } 8294 8295 if( nNorm ){ 8296 int jj; 8297 for(jj=0; jjfMin 8308 && (aMask==0 || (aMask[(iBlk*VEC1_PQ_BLOCKSIZE+ii)/8] & (1 << (ii%8)))==0) 8309 ){ 8310 i64 iRowid = 0; 8311 if( szRowid==4 ){ 8312 iRowid = vec1GetU32(&aRowid[ii * szRowid]); 8313 if( iRowid==VEC1_TOMBSTONE_32 ) continue; 8314 }else{ 8315 iRowid = vec1GetU64(&aRowid[ii * szRowid]); 8316 if( iRowid==VEC1_TOMBSTONE_64 ) continue; 8317 } 8318 vec1HeapInsert(pHeap, iRowid, dist); 8319 } 8320 } 8321 8322 skip:; /* semi-colon required to avoid C23 warning/error */ 8323 } 8324 } 8325 8326 static int vec1DoKANNBucket( 8327 Vec1Query *pQuery, 8328 int iBucket, 8329 Vec1Buffer *pDist, 8330 Vec1Buffer *pMeta, 8331 Vec1Buffer *pBitmask 8332 ){ 8333 Vec1Tab *pTab = pQuery->pTab; 8334 Vec1AnnHeap *pHeap = &pQuery->heap; 8335 8336 const int nElem = pTab->cfg.nElem; 8337 const int bUseBQ = (pTab->mod.hdr.flags & VEC1_MODEL_BITQUANT) ? 1 : 0; 8338 const int nCodebook = (int)pTab->mod.hdr.nCodebook; 8339 const int bUsePQ = (nCodebook>0 && bUseBQ==0); 8340 8341 sqlite3_stmt *pScanIdx = 0; 8342 int rc = SQLITE_OK; 8343 float *aDist = 0; 8344 float fResidualNorm2 = 0.0; 8345 8346 if( iBucket<0 ){ 8347 rc = vec1GetSql(pTab, VEC1_SQL_SCAN_IDX, &pScanIdx); 8348 }else{ 8349 rc = vec1GetSql(pTab, VEC1_SCAN_BUCKET, &pScanIdx); 8350 if( rc==SQLITE_OK ){ 8351 sqlite3_bind_int(pScanIdx, 1, iBucket); 8352 } 8353 } 8354 8355 assert( 0==pDist->n || 0==(pTab->mod.hdr.flags & VEC1_MODEL_RESIDUAL) ); 8356 if( (bUsePQ || bUseBQ) ){ 8357 /* If using PQ or BQ codes, build a LUT for this bucket. */ 8358 if( rc==SQLITE_OK && pDist->n==0 ){ 8359 const float *aEncode = pQuery->aTransform; 8360 int nByte = (bUsePQ ? 8361 vec1PQLUTSize(nCodebook) : /* Product quant */ 8362 vec1BinaryQuantSize(nElem) /* Binary quant */ 8363 ); 8364 8365 rc = vec1BufferSize(pDist, nByte); 8366 if( rc!=SQLITE_OK ) return rc; 8367 aDist = (float*)pDist->a; 8368 8369 VEC1_QINSTR_START(pTab, VEC1_QINSTR_LUT); 8370 if( pTab->mod.hdr.flags & VEC1_MODEL_RESIDUAL ){ 8371 float *aTmp = pTab->aTmpVec; 8372 assert( iBucket>=0 && iBucket<(int)pTab->mod.hdr.nBucket ); 8373 vec1Sub(aTmp, aEncode, &pTab->mod.aCentroid[iBucket*nElem], nElem); 8374 aEncode = aTmp; 8375 } 8376 if( bUsePQ ){ 8377 vec1PQLUTBuild(pTab, aEncode, aDist); 8378 }else{ 8379 vec1BinaryQuantLUTBuild(pTab, aEncode, aDist); 8380 fResidualNorm2 = (float)vec1VectorNorm2(aEncode, pTab->cfg.nElem); 8381 vec1EncodeVectorBit(&pTab->mod, aEncode, pQuery->aBit); 8382 } 8383 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_LUT); 8384 pDist->n = nByte; 8385 } 8386 aDist = (float*)pDist->a; 8387 } 8388 8389 while( rc==SQLITE_OK ){ 8390 i64 iId = 0; 8391 int res; 8392 const u8 *aBlob; 8393 int nBlob; 8394 int nEntry = 0; 8395 int flags = 0; 8396 int ii; 8397 int szRowid = 4; 8398 8399 /* Load the next index entry from the %_idx table */ 8400 VEC1_QINSTR_START(pTab, VEC1_QINSTR_IDXREAD); 8401 res = sqlite3_step(pScanIdx); 8402 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_IDXREAD); 8403 if( res!=SQLITE_ROW ) break; 8404 8405 aBlob = (const u8*)sqlite3_column_blob(pScanIdx, 0); 8406 nBlob = sqlite3_column_bytes(pScanIdx, 0); 8407 8408 if( vec1CheckIdxSize(pTab, aBlob, nBlob) ){ 8409 rc = VEC1_CORRUPT; 8410 break; 8411 } 8412 8413 nEntry = vec1GetU32(&aBlob[4]); 8414 iId = sqlite3_column_int64(pScanIdx, 2); 8415 if( pQuery->nFilter>0 ){ 8416 rc = vec1DoMetaFilters(pTab, pQuery, iId, nEntry, pMeta, pBitmask); 8417 if( rc!=SQLITE_OK ) break; 8418 } 8419 8420 /* Loop through each of the PQ vectors in aBlob[] */ 8421 VEC1_QINSTR_START(pTab, VEC1_QINSTR_PQSCAN); 8422 flags = vec1GetU32(&aBlob[0]); 8423 if( flags & VEC1_LIST_64BIT ) szRowid = 8; 8424 if( aDist ){ 8425 vec1ScanBlocked( 8426 pHeap, pBitmask->a, aDist, nCodebook, aBlob, nBlob, szRowid, 8427 nEntry, (bUseBQ ? sizeof_f32 : 0), fResidualNorm2 8428 ); 8429 }else{ 8430 const int szVec = sizeof_f32*nElem; 8431 assert( bUseBQ==0 && bUsePQ==0 ); 8432 for(ii=0; iin>0 && (pBitmask->a[ii/8] & (1 << (ii % 8))) ){ 8442 continue; 8443 } 8444 8445 if( szRowid==4 ){ 8446 iRowid = vec1GetU32(&aBlob[iRowidOff]); 8447 if( iRowid==VEC1_TOMBSTONE_32 ) continue; 8448 }else{ 8449 iRowid = vec1GetU64(&aBlob[iRowidOff]); 8450 if( iRowid==VEC1_TOMBSTONE_64 ) continue; 8451 } 8452 8453 if( pTab->mod.hdr.eDistance==VEC1_DISTANCE_COS ){ 8454 fDist = vec1CosDist(pQuery->aVector, aFull, nElem); 8455 }else{ 8456 fDist = vec1L2Dist(pQuery->aVector, aFull, nElem); 8457 } 8458 8459 vec1HeapInsert(pHeap, iRowid, fDist); 8460 } 8461 } 8462 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_PQSCAN); 8463 } 8464 8465 vec1StmtReset(&rc, pScanIdx); 8466 if( rc==SQLITE_OK ) rc = pHeap->rc; 8467 return rc; 8468 } 8469 8470 static int vec1DoKANNQuery(Vec1Csr *pCsr){ 8471 int rc = SQLITE_OK; 8472 Vec1Tab *pTab = (Vec1Tab*)(pCsr->base.pVtab); 8473 Vec1Query *pQuery = pCsr->pQuery; 8474 Vec1AnnHeap *pHeap = &pQuery->heap; 8475 8476 /* Table of distances used for ANN queries against the PQ quantized 8477 ** vectors in the %_idx table. This is an array of (nCodebook * 256) 8478 ** float values. The 256 distances for each codebook are stored 8479 ** contiguously, so to lookup code iCode in codebook iBook: 8480 ** 8481 ** aDist[(iBook * 256) + iCode] 8482 */ 8483 8484 Vec1BucketResult *aBucket = 0; 8485 const float *aVector = pQuery->aVector; 8486 int iProbe = 0; 8487 8488 Vec1Buffer meta = {0, 0, 0}; /* Buffer to load meta arrays */ 8489 Vec1Buffer bitmask = {0, 0, 0}; /* Buffer for meta filter bitmask */ 8490 Vec1Buffer dist = {0, 0, 0}; /* Buffer for LUT */ 8491 8492 VEC1_QINSTR_START(pTab, VEC1_QINSTR_INITQUERY); 8493 8494 /* Transform the input vector if required. If no transformation is 8495 ** required, then pQuery->aTransform already points to the same buffer 8496 ** as pQuery->aVector. */ 8497 assert( vec1TransformRequired(&pTab->mod)==(pQuery->aTransform!=aVector) ); 8498 vec1TransformInputVector(&pTab->mod, pQuery->aTransform, aVector); 8499 8500 rc = vec1HeapInit(pHeap, pQuery->K, pQuery->bStreaming); 8501 8502 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_INITQUERY); 8503 8504 /* Do the coarse quantizer step. If nbucket is not 0, this block allocates 8505 ** the aBucket[] array. The first nProbe elements of which are the ones 8506 ** that should be scanned by this call. The others may be used later if 8507 ** this is a streaming query, but are usually ignored. */ 8508 VEC1_QINSTR_START(pTab, VEC1_QINSTR_COARSE); 8509 if( rc==SQLITE_OK ){ 8510 if( pTab->mod.hdr.nBucket==0 ){ 8511 assert( pQuery->nProbe==1 ); 8512 }else{ 8513 assert( pQuery->nProbe>=1 && pQuery->nProbe<=(int)pTab->mod.hdr.nBucket ); 8514 rc = vec1FindBuckets(pTab, pQuery->aTransform, pQuery->nProbe, &aBucket); 8515 } 8516 } 8517 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_COARSE); 8518 8519 for(iProbe=0; iProbenProbe && rc==SQLITE_OK; iProbe++){ 8520 int iBucket = -1; 8521 if( pTab->mod.hdr.nBucket>0 ){ 8522 iBucket = aBucket[iProbe].iBucket; 8523 if( pQuery->nProbeSlack>0.0 8524 && aBucket[iProbe].fDist>aBucket[0].fDist*(1.0+pQuery->nProbeSlack) 8525 ){ 8526 break; 8527 } 8528 } 8529 if( pTab->mod.hdr.flags & VEC1_MODEL_RESIDUAL ){ 8530 dist.n = 0; 8531 } 8532 rc = vec1DoKANNBucket(pQuery, iBucket, &dist, &meta, &bitmask); 8533 } 8534 8535 VEC1_QINSTR_START(pTab, VEC1_QINSTR_FINALSORT); 8536 8537 if( rc==SQLITE_OK ){ 8538 i64 nSort = MIN( pHeap->nRes, pQuery->K ); 8539 8540 if( pQuery->bStreaming ){ 8541 /* For a streaming query, set the pQuery->aBucket[] array to contain 8542 ** the remaining buckets - the ones that have not yet been scanned. */ 8543 pQuery->nBucket = pTab->mod.hdr.nBucket - iProbe; 8544 if( pQuery->nBucket>0 ){ 8545 int nCopy = sizeof(Vec1BucketResult) * pQuery->nBucket; 8546 memmove(aBucket, &aBucket[iProbe], nCopy); 8547 pQuery->aBucket = aBucket; 8548 aBucket = 0; 8549 } 8550 8551 pQuery->nOrigRes = (int)MAX(16, pHeap->nRes); 8552 } 8553 8554 /* For a streaming query, all candidate vectors were added to the 8555 ** aRes[] array. The heap has guaranteed that the first nSort elements 8556 ** of the Vec1AnnHeap.aRes[] array have distances <= than the remaining 8557 ** elements. So it is still correct just to sort the first nSort 8558 ** elements of aRes[] and set nCurrentRes=nSort to configure the first 8559 ** block of rows to return. */ 8560 rc = vec1AnnResultSort(pHeap->aRes, nSort); 8561 pCsr->nCurrentRes = (int)nSort; 8562 } 8563 sqlite3_free(aBucket); 8564 vec1BufferFree(&meta); 8565 vec1BufferFree(&bitmask); 8566 vec1BufferFree(&dist); 8567 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_FINALSORT); 8568 8569 return rc; 8570 } 8571 8572 /* 8573 ** Load the contents of the %_config table into the pTab->cfg structure. 8574 ** if the iModelVersion field has changed since %_config was last loaded, 8575 ** also load the model from the %_model table. 8576 */ 8577 static int vec1LoadConfig(Vec1Tab *pTab){ 8578 sqlite3_stmt *pStmt = 0; 8579 int rc = SQLITE_OK; 8580 int nReq = 0; 8581 8582 pTab->cfg.nBlocksize = VEC1_BLOCKSIZE_DEFAULT; 8583 pTab->cfg.nBlocksizeMin = VEC1_BLOCKSIZE_MIN_DEFAULT; 8584 pTab->cfg.nElem = 0; 8585 8586 rc = vec1GetSql(pTab, VEC1_SQL_LOAD_CONFIG, &pStmt); 8587 if( rc==SQLITE_OK ){ 8588 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8589 int iField = sqlite3_column_int(pStmt, 0); 8590 switch( iField ){ 8591 case VEC1_CONFIG_MODEL: { 8592 i64 iNew = sqlite3_column_int64(pStmt, 1); 8593 if( pTab->cfg.iModelVersion!=iNew ){ 8594 rc = vec1LoadModel(pTab); 8595 if( rc==SQLITE_OK ){ 8596 pTab->cfg.iModelVersion = iNew; 8597 } 8598 } 8599 break; 8600 } 8601 8602 case VEC1_CONFIG_BLOCKSIZE: { 8603 pTab->cfg.nBlocksize = sqlite3_column_int(pStmt, 1); 8604 pTab->cfg.nBlocksize = MAX(VEC1_BLOCKSIZE_MIN, pTab->cfg.nBlocksize); 8605 pTab->cfg.nBlocksize = MIN(VEC1_BLOCKSIZE_MAX, pTab->cfg.nBlocksize); 8606 break; 8607 } 8608 8609 case VEC1_CONFIG_BLOCKSIZE_MIN: { 8610 int nMin = sqlite3_column_int(pStmt, 1); 8611 nMin = MAX(VEC1_BLOCKSIZE_MIN, nMin); 8612 nMin = MIN(VEC1_BLOCKSIZE_MAX, nMin); 8613 pTab->cfg.nBlocksizeMin = nMin; 8614 break; 8615 } 8616 8617 case VEC1_CONFIG_NELEM: { 8618 i64 nElem = sqlite3_column_int(pStmt, 1); 8619 if( nElemVEC1_VECSIZE_MAX ){ 8620 vec1VtabError(pTab, "invalid vector size in config"); 8621 rc = VEC1_CORRUPT; 8622 }else{ 8623 pTab->cfg.nElem = (int)nElem; 8624 } 8625 break; 8626 } 8627 8628 case VEC1_CONFIG_FMTVERSION: { 8629 int iVersion = sqlite3_column_int(pStmt, 1); 8630 if( iVersionVEC1_CURRENT_FMTVERSION ){ 8634 vec1VtabError(pTab, 8635 "unsupported index version - requires vec1 %d.%d", 8636 (iVersion / 1000), (iVersion % 1000) 8637 ); 8638 rc = SQLITE_ERROR; 8639 } 8640 break; 8641 } 8642 8643 default: { 8644 vec1VtabError(pTab, "unrecognized config entry: %d", iField); 8645 rc = SQLITE_ERROR; 8646 break; 8647 } 8648 } 8649 } 8650 8651 vec1StmtReset(&rc, pStmt); 8652 } 8653 8654 nReq = MAX(pTab->mod.hdr.nElem, pTab->mod.nCodeElem*pTab->mod.hdr.nCodebook); 8655 if( (rc==SQLITE_OK) && nReq>0 && nReq!=pTab->nTmpVec ){ 8656 sqlite3_free(pTab->aTmpVec); 8657 pTab->aTmpVec = (float*)vec1MallocZero(nReq * sizeof_f32); 8658 if( pTab->aTmpVec ){ 8659 pTab->nTmpVec = nReq; 8660 }else{ 8661 pTab->nTmpVec = 0; 8662 rc = SQLITE_NOMEM; 8663 } 8664 } 8665 8666 if( rc==SQLITE_OK 8667 && pTab->mod.hdr.nElem!=0 8668 && (u32)pTab->cfg.nElem!=pTab->mod.hdr.nElem 8669 ){ 8670 vec1VtabError(pTab, "model/data vector size mismatch: %d/%d", 8671 pTab->mod.hdr.nElem, pTab->cfg.nElem 8672 ); 8673 vec1UnloadModel(pTab); 8674 rc = SQLITE_ERROR; 8675 } 8676 8677 return rc; 8678 } 8679 8680 /* 8681 ** Load the configuration if it is not already loaded. The configuration 8682 ** is assumed not to be loaded if cfg.nElem==0. 8683 ** 8684 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If 8685 ** an error occurs, this function may leave an error message in the virtual 8686 ** table object. 8687 */ 8688 static int vec1LoadConfigIfRequired(Vec1Tab *pTab){ 8689 int rc = SQLITE_OK; 8690 if( pTab->cfg.nElem==0 ){ 8691 rc = vec1LoadConfig(pTab); 8692 if( rc!=SQLITE_OK ){ 8693 pTab->cfg.nElem = 0; 8694 } 8695 } 8696 return rc; 8697 } 8698 8699 static int vec1InterpretNProbe(Vec1Tab *pTab, double fVal){ 8700 int nProbe; 8701 if( fVal>=1.0 ){ 8702 nProbe = (int)fVal; 8703 }else{ 8704 nProbe = (int)(fVal * pTab->mod.hdr.nBucket); 8705 } 8706 nProbe = MIN(nProbe, (int)pTab->mod.hdr.nBucket); 8707 nProbe = MAX(nProbe, 1); 8708 return nProbe; 8709 } 8710 8711 static int vec1ParseQueryParamCb( 8712 void *pCtx, 8713 const char *zOpt, 8714 int eType, 8715 i64 iVal, 8716 double fVal, 8717 const char *zVal, 8718 char **pzErr 8719 ){ 8720 Vec1Query *pQuery = (Vec1Query*)pCtx; 8721 const char *azOpt[] = { 8722 "nprobe", /* 0 */ 8723 "K", /* 1 */ 8724 "streaming", /* 2 */ 8725 "nprobe_slack", /* 3 */ 8726 0 8727 }; 8728 int iOpt = 0; 8729 int rc; 8730 8731 UNUSED_PARAMETER2(iVal, eType); 8732 UNUSED_PARAMETER2(pzErr, zVal); 8733 8734 rc = vec1ConfigEnum(&iOpt, zOpt, azOpt, "option", pzErr); 8735 if( rc==SQLITE_OK ){ 8736 switch( iOpt ){ 8737 case 0: assert( sqlite3_stricmp("nprobe", zOpt)==0 ); 8738 if( fVal<=0.0 ){ 8739 *pzErr = sqlite3_mprintf( 8740 "vec1: nprobe must be a numeric value greater than 0.0" 8741 ); 8742 rc = SQLITE_ERROR; 8743 } 8744 pQuery->nProbe = vec1InterpretNProbe(pQuery->pTab, fVal); 8745 break; 8746 8747 case 1: assert( sqlite3_stricmp("K", zOpt)==0 ); 8748 if( eType==SQLITE_INTEGER ){ 8749 pQuery->K = iVal; 8750 }else{ 8751 pQuery->K = -1; 8752 } 8753 break; 8754 8755 case 2: assert( sqlite3_stricmp("streaming", zOpt)==0 ); 8756 pQuery->bStreaming = ((int)fVal) ? 1 : 0; 8757 break; 8758 8759 default: assert( sqlite3_stricmp("nprobe_slack", zOpt)==0 ); 8760 pQuery->nProbeSlack = fVal; 8761 break; 8762 } 8763 } 8764 8765 return rc; 8766 } 8767 8768 static int vec1ModelIsFlat(Vec1Model *pMod){ 8769 return ((pMod->hdr.flags & VEC1_MODEL_INDEX) && pMod->hdr.nCodebook==0); 8770 } 8771 8772 static const char aHexDigit[] = { 8773 '0', '1', '2', '3', '4', '5', '6', '7', 8774 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 8775 }; 8776 8777 static int vec1DecodeMetaIdx(const char *z){ 8778 int iRet = 0; 8779 assert( (z[0]>='0' && z[0]<='9') || (z[0]>='a' && z[0]<='f') ); 8780 assert( (z[1]>='0' && z[1]<='9') || (z[1]>='a' && z[1]<='f') ); 8781 8782 if( z[0]<='9' ){ 8783 iRet = (int)(z[0] - '0'); 8784 }else{ 8785 iRet = (int)(10 + z[0] - 'a'); 8786 } 8787 iRet = iRet << 4; 8788 if( z[1]<='9' ){ 8789 iRet |= (int)(z[1] - '0'); 8790 }else{ 8791 iRet |= (int)(10 + z[1] - 'a'); 8792 } 8793 return iRet; 8794 } 8795 8796 /* 8797 ** This is invoked when a value of type eType (which is not SQLITE_BLOB) 8798 ** has been passed to vec1 as a vector. This is an error. Configure the 8799 ** table with an error message and return SQLITE_ERROR. 8800 */ 8801 static int vec1VectorTypeError(Vec1Tab *pTab, int eType){ 8802 const char *azType[] = {0, "INTEGER", "FLOAT", "TEXT", "BLOB", "NULL"}; 8803 assert( eType!=SQLITE_BLOB && eType>=1 && eType<=5 ); 8804 vec1VtabError(pTab, 8805 "vec1: unexpected vector type %s, expected BLOB", azType[eType] 8806 ); 8807 return SQLITE_ERROR; 8808 } 8809 8810 /* 8811 ** This is invoked when a blob nHave bytes in size has been passed to vec1 8812 ** as a vector when a (pTab->cfg.nElem*sizeof_f32) blob was expected. 8813 ** Configure the table with an error message and return SQLITE_ERROR. 8814 */ 8815 static int vec1VectorSizeError(Vec1Tab *pTab, int nHave){ 8816 assert( pTab->cfg.nElem>0 && (pTab->cfg.nElem*sizeof_f32)!=nHave ); 8817 vec1VtabError(pTab, 8818 "vec1: unexpected vector blob size %d bytes, expected %d", 8819 nHave, pTab->cfg.nElem*sizeof_f32 8820 ); 8821 return SQLITE_ERROR; 8822 } 8823 8824 static int vec1FilterArraySize( 8825 const char *idxStr, 8826 sqlite3_value **argv, 8827 int *pnFilter 8828 ){ 8829 int ii; 8830 int nFilter = 0; 8831 int iArg = 1; 8832 int rc = SQLITE_OK; 8833 8834 for(ii=0; idxStr[ii]; ii++){ 8835 char c = idxStr[ii]; 8836 if( c==VEC1_OP_IN ){ 8837 sqlite3_value *pDummy = 0; 8838 sqlite3_value *pList = argv[iArg]; 8839 nFilter++; 8840 for(rc=sqlite3_vtab_in_first(pList, &pDummy); 8841 rc==SQLITE_OK; 8842 rc=sqlite3_vtab_in_next(pList, &pDummy) 8843 ){ 8844 assert( pDummy!=0 ); 8845 nFilter++; 8846 } 8847 if( rc==SQLITE_DONE ) rc = SQLITE_OK; 8848 ii += 2; 8849 }else if( c!=VEC1_OP_PARAMS && c!=VEC1_OP_LIMIT ){ 8850 ii += 2; 8851 nFilter++; 8852 } 8853 iArg++; 8854 } 8855 8856 *pnFilter = nFilter; 8857 return rc; 8858 } 8859 8860 static void *vec1Dup(int *pRc, const void *p, int n){ 8861 void *pRet = 0; 8862 assert( *pRc==SQLITE_OK ); 8863 if( p==0 ){ 8864 *pRc = SQLITE_NOMEM; 8865 }else{ 8866 pRet = vec1MallocZero(n+1); 8867 if( pRet==0 ){ 8868 *pRc = SQLITE_NOMEM; 8869 }else if( n>0 ){ 8870 memcpy(pRet, p, n); 8871 } 8872 } 8873 return pRet; 8874 } 8875 8876 static void vec1ValueToFilter( 8877 int *pRc, 8878 sqlite3_value *pVal, 8879 Vec1Filter *pFilter 8880 ){ 8881 pFilter->eType = sqlite3_value_type(pVal); 8882 switch( pFilter->eType ){ 8883 case SQLITE_NULL: 8884 break; 8885 case SQLITE_INTEGER: 8886 pFilter->iVal = sqlite3_value_int64(pVal); 8887 break; 8888 case SQLITE_FLOAT: 8889 pFilter->fVal = sqlite3_value_double(pVal); 8890 break; 8891 case SQLITE_TEXT: 8892 pFilter->iVal = sqlite3_value_bytes(pVal); 8893 pFilter->pPtr = (u8*)vec1Dup( 8894 pRc, sqlite3_value_text(pVal), (int)pFilter->iVal 8895 ); 8896 break; 8897 default: { 8898 int nByte = sqlite3_value_bytes(pVal); 8899 assert( pFilter->eType==SQLITE_BLOB ); 8900 pFilter->iVal = (i64)nByte; 8901 pFilter->pPtr = (u8*)vec1Dup( 8902 pRc, nByte? sqlite3_value_blob(pVal) : (const void*)"", nByte 8903 ); 8904 break; 8905 } 8906 } 8907 } 8908 8909 /* 8910 ** Return true if value pVal contains an integer - either an SQL integer, 8911 ** text that looks like an integer, or a double that can be converted 8912 ** to an integer without loss of data. 8913 */ 8914 static int vecIsIntegerValue(sqlite3_value *pVal){ 8915 if( sqlite3_value_numeric_type(pVal)==SQLITE_INTEGER ) return 1; 8916 if( sqlite3_value_numeric_type(pVal)==SQLITE_FLOAT ){ 8917 double fVal = sqlite3_value_double(pVal); 8918 if( fVal==(double)((i64)fVal) ) return 1; 8919 } 8920 return 0; 8921 } 8922 8923 static int vec1SetupKANNQuery( 8924 Vec1Tab *pTab, 8925 const char *idxStr, /* idxStr passed to xFilter */ 8926 sqlite3_value **argv, /* Parameter values passed to xFilter */ 8927 Vec1Query **ppOut /* OUT: Query object */ 8928 ){ 8929 const int nElem = pTab->cfg.nElem; 8930 const int nSpace = MAX(pTab->cfg.nElem, pTab->nTmpVec); 8931 int nMax = 0; /* Max possible meta-data filters */ 8932 int nVec = sqlite3_value_bytes(argv[0]); 8933 const u8 *aVec = sqlite3_value_blob(argv[0]); 8934 8935 int iArg = 1; 8936 int iIdxStr = 0; 8937 int rc = SQLITE_OK; 8938 Vec1Query *p = 0; 8939 8940 int bTransform = vec1TransformRequired(&pTab->mod); 8941 int nBit = 0; 8942 8943 if( pTab->mod.hdr.flags & VEC1_MODEL_BITQUANT ){ 8944 nBit = sizeof_f32 + pTab->mod.hdr.nCodebook; 8945 } 8946 8947 /* Determine the required size of the Vec1Query.aFilter[] array. */ 8948 rc = vec1FilterArraySize(idxStr, argv, &nMax); 8949 8950 p = (Vec1Query*)vec1MallocZero( 8951 sizeof(Vec1Query) /* Vec1Query object itself */ 8952 + nMax * sizeof(Vec1Filter) /* Vec1Query.aFilter[] */ 8953 + nSpace * sizeof_f32 /* Vec1Query.aVector[] */ 8954 + bTransform * (nSpace * sizeof_f32) /* aTransform[] */ 8955 + nBit /* aBit[] */ 8956 ); 8957 if( p==0 ) return SQLITE_NOMEM; 8958 p->aFilter = (Vec1Filter*)&p[1]; 8959 p->aVector = (float*)&p->aFilter[nMax]; 8960 if( bTransform ){ 8961 p->aTransform = &p->aVector[nSpace]; 8962 }else{ 8963 p->aTransform = p->aVector; 8964 } 8965 if( nBit ){ 8966 p->aBit = (u8*)&p->aTransform[nSpace]; 8967 } 8968 8969 /* Initialize default query parameters. 8970 ** 8971 ** Use VEC1_SMALLEST_INT64 to signify that no K value has been supplied 8972 ** If somebody specifies this value via a JSON query parameter, they 8973 ** may get a slightly inaccurate error message. So be it. */ 8974 p->pTab = pTab; 8975 p->K = VEC1_SMALLEST_INT64; 8976 p->nProbe = vec1InterpretNProbe(pTab, pTab->pTabList->nProbeArg); 8977 p->bStreaming = 0; 8978 8979 /* Check the query vector is the right size and copy it into the 8980 ** aVector[] buffer. 8981 ** 8982 ** Omit this check if nElem==0. This occurs when the table has not yet 8983 ** received the first vector. So carry on checking the remainder of the 8984 ** parameters, but don't worry about checking the input vector or 8985 ** copying it into aVector[], as the query will return zero rows in 8986 ** any case. */ 8987 if( nElem!=0 ){ 8988 if( nVec!=(nElem*sizeof_f32) ){ 8989 rc = vec1VectorSizeError(pTab, nVec); 8990 }else{ 8991 memcpy(p->aVector, aVec, nVec); 8992 } 8993 } 8994 8995 /* Check that the query vector does not contain any NaN or Infinity values */ 8996 if( rc==SQLITE_OK ){ 8997 rc = vec1VectorIsNonFinite((float*)aVec, (nVec/sizeof_f32)); 8998 if( rc!=SQLITE_OK ){ 8999 vec1VtabError(pTab, "vec1: non-finite value not allowed in vector"); 9000 } 9001 } 9002 9003 /* Check if parameters where supplied via hidden column "arg". If so, 9004 ** the first character of idxStr is 'P' - parameters. */ 9005 if( rc==SQLITE_OK && idxStr[0]==VEC1_OP_PARAMS ){ 9006 sqlite3_value *pVal = argv[iArg++]; 9007 if( vecIsIntegerValue(pVal) ){ 9008 p->K = sqlite3_value_int64(pVal); 9009 }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){ 9010 assert( pTab->base.zErrMsg==0 ); 9011 rc = vec1ParseJsonConfig(pTab->db, 9012 (const char*)sqlite3_value_text(pVal), vec1ParseQueryParamCb, 9013 (void*)p, &pTab->base.zErrMsg 9014 ); 9015 }else{ 9016 p->K = -1; 9017 } 9018 iIdxStr = 1; 9019 } 9020 9021 /* Process remaining constraints, if any. */ 9022 if( rc==SQLITE_OK && idxStr[iIdxStr]!='\0' ){ 9023 char c; 9024 while( (c = idxStr[iIdxStr++])!='\0' ){ 9025 sqlite3_value *pVal = argv[iArg++]; 9026 if( c==VEC1_OP_LIMIT ){ 9027 int iVal = sqlite3_value_int(pVal); 9028 if( iVal>=0 && (p->K==VEC1_SMALLEST_INT64 || p->K>0) ){ 9029 /* A non-negative LIMIT clause. If no K value was specified, use 9030 ** this value as K. Or, if a K value was specified, use the 9031 ** minimum of K and this value. */ 9032 p->K = ((p->K < 0) ? iVal : MIN(p->K, iVal)); 9033 } 9034 }else{ 9035 /* Filter on a meta value. The operand character is followed by 9036 ** 2 hexadecimal digits encoding the index of the meta column 9037 ** on the LHS of the constraint. */ 9038 Vec1Filter *pFilter = &p->aFilter[p->nFilter++]; 9039 pFilter->vop = c; 9040 pFilter->iMeta = vec1DecodeMetaIdx(&idxStr[iIdxStr]); 9041 iIdxStr += 2; 9042 if( c==VEC1_OP_IN ){ 9043 sqlite3_value *pInVal = 0; 9044 assert( pFilter->iVal==0 ); 9045 for(rc=sqlite3_vtab_in_first(pVal, &pInVal); 9046 rc==SQLITE_OK; 9047 rc=sqlite3_vtab_in_next(pVal, &pInVal) 9048 ){ 9049 Vec1Filter *pInFilter = &p->aFilter[p->nFilter++]; 9050 vec1ValueToFilter(&rc, pInVal, pInFilter); 9051 if( rc!=SQLITE_OK ) break; 9052 pInFilter->vop = VEC1_OP_EQ; 9053 pInFilter->iMeta = pFilter->iMeta; 9054 pFilter->iVal++; 9055 } 9056 if( rc==SQLITE_DONE ) rc = SQLITE_OK; 9057 9058 }else if( c==VEC1_OP_NOTNULL ){ 9059 pFilter->eType = SQLITE_BLOB; 9060 pFilter->iVal = 0; 9061 }else if( c==VEC1_OP_ISNULL ){ 9062 pFilter->eType = SQLITE_NULL; 9063 pFilter->vop = VEC1_OP_IS; 9064 9065 }else{ 9066 vec1ValueToFilter(&rc, pVal, pFilter); 9067 } 9068 } 9069 } 9070 } 9071 assert( rc!=SQLITE_OK || p->nFilter==nMax ); 9072 9073 /* Check that a usable K value has been specified. Either explicitly or 9074 ** via a visible LIMIT clause. */ 9075 if( rc==SQLITE_OK ){ 9076 if( p->K==VEC1_SMALLEST_INT64 ){ 9077 vec1VtabError(pTab, "vec1: no K value or visible LIMIT clause"); 9078 rc = SQLITE_ERROR; 9079 }else if( p->K<0 || p->K>VEC1_MAX_K ){ 9080 vec1VtabError(pTab, 9081 "vec1: K must be an integer value between 0 and %d", VEC1_MAX_K 9082 ); 9083 rc = SQLITE_ERROR; 9084 } 9085 } 9086 9087 /* If an error occurred, free any dynamic allocations and zero the output 9088 ** structure before returning. Otherwise, sort the aFilter[] array by 9089 ** iMeta value. */ 9090 if( rc!=SQLITE_OK ){ 9091 vec1QueryFree(p); 9092 p = 0; 9093 }else if( 0 ){ 9094 /* Sort aFilter[] by Vec1Filter.iMeta value. The sort must be stable, 9095 ** in order to avoid disrupting the arguments to a VEC1_OP_IN filter. */ 9096 int i1, i2; 9097 for(i1=0; i1nFilter; i1++){ 9098 Vec1Filter tmp = p->aFilter[i1]; 9099 for(i2=i1-1; i2>=0 && p->aFilter[i2].iMeta>tmp.iMeta; i2--){ 9100 p->aFilter[i2+1] = p->aFilter[i2]; 9101 } 9102 p->aFilter[i2+1] = tmp; 9103 } 9104 9105 #ifndef NDEBUG 9106 /* Assert() that the sort worked. */ 9107 for(i1=1; i1nFilter; i1++){ 9108 assert( p->aFilter[i1-1].iMeta<=p->aFilter[i1].iMeta ); 9109 } 9110 #endif 9111 } 9112 9113 *ppOut = p; 9114 return rc; 9115 } 9116 9117 /* 9118 ** This function is called in index:"none" mode. 9119 */ 9120 static int vec1QueryToSql(Vec1Csr *pCsr){ 9121 Vec1Tab *pTab = (Vec1Tab*)(pCsr->base.pVtab); 9122 Vec1Query *pQuery = pCsr->pQuery; 9123 int ii; 9124 int rc = SQLITE_OK; 9125 char *zWhere = 0; 9126 9127 int iNextVar = 1; 9128 9129 sqlite3_str *pWhere = sqlite3_str_new(pTab->db); 9130 const char *zAnd = ""; 9131 9132 for(ii=0; iinFilter; ii++){ 9133 Vec1Filter *p = &pQuery->aFilter[ii]; 9134 int bRhs = 1; 9135 const char *zOp = ""; 9136 if( p->vop==VEC1_OP_IN ){ 9137 int jj; 9138 sqlite3_str_appendf(pWhere, "%sc%d IN(?%d", zAnd, p->iMeta, iNextVar++); 9139 for(jj=2; jj<=p->iVal; jj++){ 9140 sqlite3_str_appendf(pWhere, ", ?%d", iNextVar++); 9141 } 9142 ii += (int)p->iVal; 9143 sqlite3_str_appendf(pWhere, ")"); 9144 }else{ 9145 switch( p->vop ){ 9146 case VEC1_OP_EQ: zOp = "="; break; 9147 case VEC1_OP_LT: zOp = "<"; break; 9148 case VEC1_OP_GT: zOp = ">"; break; 9149 case VEC1_OP_LE: zOp = "<="; break; 9150 case VEC1_OP_GE: zOp = ">="; break; 9151 case VEC1_OP_IS: zOp = "IS"; break; 9152 default: 9153 assert( p->vop==VEC1_OP_NOTNULL ); 9154 zOp = "IS NOT NULL"; 9155 bRhs = 0; 9156 break; 9157 } 9158 9159 sqlite3_str_appendf(pWhere, "%sc%d %s", zAnd, p->iMeta, zOp); 9160 9161 if( bRhs ){ 9162 sqlite3_str_appendf(pWhere, " ?%d", iNextVar++); 9163 } 9164 } 9165 zAnd = " AND "; 9166 } 9167 9168 rc = sqlite3_str_errcode(pWhere); 9169 zWhere = sqlite3_str_finish(pWhere); 9170 9171 if( rc==SQLITE_OK ){ 9172 const char *zDistance = "vec1_l2_distance"; 9173 if( pTab->mod.hdr.eDistance==VEC1_DISTANCE_COS ){ 9174 zDistance = "vec1_cos_distance"; 9175 } 9176 9177 rc = vec1PrepareSql(pTab, &pCsr->pStmt, 9178 "SELECT *, %s(?%d, vector) AS d FROM %Q.'%q_base'%s%s " 9179 "ORDER BY d LIMIT %lld", 9180 zDistance, iNextVar, 9181 pTab->zDb, pTab->zName, 9182 zWhere ? " WHERE " : "", zWhere, 9183 pQuery->K 9184 ); 9185 } 9186 if( rc==SQLITE_OK ){ 9187 int n = pTab->cfg.nElem * sizeof_f32; 9188 rc = sqlite3_bind_blob( 9189 pCsr->pStmt, iNextVar, pQuery->aVector, n, SQLITE_TRANSIENT 9190 ); 9191 iNextVar = 1; 9192 for(ii=0; rc==SQLITE_OK && iinFilter; ii++){ 9193 Vec1Filter *p = &pQuery->aFilter[ii]; 9194 if( p->vop!=VEC1_OP_IN && p->vop!=VEC1_OP_NOTNULL ){ 9195 switch( p->eType ){ 9196 case SQLITE_NULL: 9197 break; 9198 case SQLITE_INTEGER: 9199 sqlite3_bind_int64(pCsr->pStmt, iNextVar, p->iVal); 9200 break; 9201 case SQLITE_FLOAT: 9202 sqlite3_bind_double(pCsr->pStmt, iNextVar, p->fVal); 9203 break; 9204 case SQLITE_TEXT: 9205 rc = sqlite3_bind_text(pCsr->pStmt, 9206 iNextVar, (const char*)p->pPtr, (int)p->iVal, SQLITE_TRANSIENT 9207 ); 9208 break; 9209 default: 9210 assert( p->eType==SQLITE_BLOB ); 9211 rc = sqlite3_bind_blob( 9212 pCsr->pStmt, iNextVar, p->pPtr, (int)p->iVal, SQLITE_TRANSIENT 9213 ); 9214 break; 9215 } 9216 9217 iNextVar++; 9218 } 9219 } 9220 } 9221 9222 vec1QueryFree(pQuery); 9223 pCsr->pQuery = 0; 9224 pCsr->bSqlNNQuery = 1; 9225 sqlite3_free(zWhere); 9226 return rc; 9227 } 9228 9229 static int vec1EofMethod(sqlite3_vtab_cursor *cur){ 9230 Vec1Csr *pCur = (Vec1Csr *)cur; 9231 return (pCur->pStmt==0); 9232 } 9233 9234 static int vec1SeekCsr(Vec1Csr *pCsr){ 9235 int rc = SQLITE_OK; 9236 if( pCsr->pQuery && pCsr->bSeek==0 ){ 9237 i64 iRowid = pCsr->pQuery->heap.aRes[pCsr->iCurrentRes].iRowid; 9238 sqlite3_bind_int64(pCsr->pStmt, 1, iRowid); 9239 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ 9240 rc = sqlite3_finalize(pCsr->pStmt); 9241 if( rc==SQLITE_OK ){ 9242 rc = VEC1_CORRUPT; 9243 } 9244 pCsr->pStmt = 0; 9245 } 9246 pCsr->bSeek = 1; 9247 } 9248 return rc; 9249 } 9250 9251 typedef struct Vec1RowidLocation Vec1RowidLocation; 9252 struct Vec1RowidLocation { 9253 int iEntry; 9254 int nEntry; 9255 int nTombstone; 9256 int szRowid; 9257 9258 Vec1ListBuilder *pList; 9259 sqlite3_blob *pBlob; 9260 i64 iIdx; 9261 }; 9262 9263 static int vec1FindByRowid( 9264 Vec1Tab *pTab, 9265 int iBucket, /* Row belongs to this bucket */ 9266 int bWrite, /* Use writable blob-handle */ 9267 i64 iRowid, /* Rowid to locate */ 9268 Vec1RowidLocation *pOut /* OUT: Result */ 9269 ){ 9270 int rc = SQLITE_OK; 9271 Vec1Buffer buf = {0, 0, 0}; 9272 sqlite3_stmt *pSearch = 0; /* For looping through index entries */ 9273 sqlite3_blob *pBlob = 0; 9274 9275 assert( (pTab->mod.hdr.flags & VEC1_MODEL_INDEX) ); 9276 9277 memset(pOut, 0, sizeof(*pOut)); 9278 9279 /* Check to see if the index entry for this vector is currently 9280 ** in main memory. */ 9281 if( pTab->pWriter ){ 9282 Vec1ListBuilder *pBld = &pTab->pWriter->aBld[iBucket]; 9283 if( (pBld->szRowid==4 && iRowid!=VEC1_TOMBSTONE_32) 9284 || (pBld->szRowid==8 && iRowid!=VEC1_TOMBSTONE_64) 9285 ){ 9286 int ii; 9287 for(ii=0; iibufRowid.n; ii+=pBld->szRowid){ 9288 i64 iRead; 9289 if( pBld->szRowid==4 ){ 9290 iRead = vec1GetU32(&pBld->bufRowid.a[ii]); 9291 }else{ 9292 iRead = vec1GetU64(&pBld->bufRowid.a[ii]); 9293 } 9294 if( iRead==iRowid ){ 9295 pOut->iEntry = (ii / pBld->szRowid); 9296 pOut->nEntry = (pBld->bufRowid.n / pBld->szRowid); 9297 pOut->nTombstone = pBld->nTombstone; 9298 pOut->szRowid = pBld->szRowid; 9299 pOut->pList = pBld; 9300 return SQLITE_OK; 9301 } 9302 } 9303 } 9304 } 9305 9306 rc = vec1GetSql(pTab, VEC1_SQL_SEARCH_IDX, &pSearch); 9307 if( rc==SQLITE_OK ){ 9308 sqlite3_bind_int(pSearch, 1, iBucket); 9309 sqlite3_bind_int64(pSearch, 2, iRowid); 9310 } 9311 9312 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSearch) ){ 9313 int nEntry = 0; 9314 u32 nTombstone = 0; 9315 u32 flags = 0; 9316 int szRowid = 4; 9317 i64 iIdx = sqlite3_column_int64(pSearch, 0); 9318 9319 rc = sqlite3_blob_open( 9320 pTab->db, pTab->zDb, pTab->zIdxTbl, "val", iIdx, bWrite, &pBlob 9321 ); 9322 if( rc==SQLITE_OK ){ 9323 u8 a[VEC1_LIST_SZHDR]; 9324 rc = sqlite3_blob_read(pBlob, a, VEC1_LIST_SZHDR, 0); 9325 flags = vec1GetU32(&a[0]); 9326 nEntry = (int)vec1GetU32(&a[4]); 9327 nTombstone = vec1GetU32(&a[8]); 9328 if( flags & VEC1_LIST_64BIT ) szRowid = 8; 9329 } 9330 9331 /* Now scan through the array of rowids at the start of the %_idx entry 9332 ** to find the rowid to be deleted. But, do not do this if the rowid 9333 ** happens to have the same value as the tombstone for this %_idx entry. */ 9334 if( (szRowid==4 && iRowid!=VEC1_TOMBSTONE_32) 9335 || (szRowid==8 && iRowid!=VEC1_TOMBSTONE_64) 9336 ){ 9337 if( rc==SQLITE_OK ){ 9338 buf.n = 0; 9339 rc = vec1BufferGrow(&buf, VEC1_LIST_SZHDR+szRowid*nEntry); 9340 } 9341 if( rc==SQLITE_OK ){ 9342 rc = sqlite3_blob_read( 9343 pBlob, &buf.a[VEC1_LIST_SZHDR], nEntry*szRowid, VEC1_LIST_SZHDR 9344 ); 9345 } 9346 9347 if( rc==SQLITE_OK ){ 9348 int ii; 9349 for(ii=0; iiiEntry = ii; 9358 pOut->nEntry = nEntry; 9359 pOut->nTombstone = nTombstone; 9360 pOut->szRowid = szRowid; 9361 pOut->pBlob = pBlob; 9362 pOut->iIdx = iIdx; 9363 pBlob = 0; 9364 goto findbyrowid_done; 9365 } 9366 } 9367 } 9368 } 9369 (void)sqlite3_blob_close(pBlob); 9370 } 9371 9372 findbyrowid_done: 9373 vec1StmtReset(&rc, pSearch); 9374 vec1BufferFree(&buf); 9375 return rc; 9376 } 9377 9378 /* 9379 ** Obtain the full vector associated with the current row of cursor pCsr. 9380 */ 9381 static int vec1GetVector( 9382 Vec1Csr *pCsr, 9383 const u8 **paVec, /* OUT: Pointer to vector buffer */ 9384 int *pnVec, /* OUT: Size of (*paVec) in bytes */ 9385 u8 **pFree /* OUT: Buffer for caller to free (or NULL) */ 9386 ){ 9387 int rc = SQLITE_OK; 9388 Vec1Tab *pTab = (Vec1Tab*)(pCsr->base.pVtab); 9389 rc = vec1SeekCsr(pCsr); 9390 if( rc==SQLITE_OK ){ 9391 if( vec1ModelIsFlat(&pTab->mod) ){ 9392 i64 iRowid = sqlite3_column_int64(pCsr->pStmt, 0); 9393 int iBucket = sqlite3_column_int(pCsr->pStmt, 1); 9394 Vec1RowidLocation loc; 9395 rc = vec1FindByRowid(pTab, iBucket, 0, iRowid, &loc); 9396 if( rc==SQLITE_OK ){ 9397 int nVec = sizeof_f32 * pTab->cfg.nElem; 9398 u8 *aVec = (u8*)sqlite3_malloc(nVec); 9399 if( aVec==0 ){ 9400 rc = SQLITE_NOMEM; 9401 }else if( loc.pList ){ 9402 memcpy(aVec, &loc.pList->bufData.a[nVec * loc.iEntry], nVec); 9403 }else if( loc.pBlob ){ 9404 rc = sqlite3_blob_read(loc.pBlob, aVec, nVec, 9405 VEC1_LIST_SZHDR + (loc.nEntry*loc.szRowid) + (loc.iEntry * nVec) 9406 ); 9407 }else{ 9408 sqlite3_free(aVec); 9409 nVec = 0; 9410 aVec = 0; 9411 } 9412 9413 if( rc!=SQLITE_OK ){ 9414 sqlite3_free(aVec); 9415 *paVec = 0; 9416 *pnVec = 0; 9417 *pFree = 0; 9418 }else{ 9419 *paVec = *pFree = aVec; 9420 *pnVec = nVec; 9421 } 9422 (void)sqlite3_blob_close(loc.pBlob); 9423 } 9424 }else{ 9425 *paVec = sqlite3_column_blob(pCsr->pStmt, 1); 9426 *pnVec = sqlite3_column_bytes(pCsr->pStmt, 1); 9427 *pFree = 0; 9428 } 9429 } 9430 return rc; 9431 } 9432 9433 /* 9434 ** This function quantizes vector aIn[], then dequantizes it and finds 9435 ** the squared L2 distance between the original and the round-tripped 9436 ** vector. If successful, output parameter (*prError) is set to the 9437 ** squared distance value and SQLITE_OK is returned. Or, if an error 9438 ** occurs, an SQLite error code (SQLITE_NOMEM) is returned. 9439 */ 9440 static int vec1QuantizeReconstructionError2( 9441 Vec1Model *pMod, /* Model to use for quantization */ 9442 const float *aIn, /* Input vector */ 9443 char **pzEnc, 9444 double *prError /* OUT: Round trip error */ 9445 ){ 9446 const int nElem = (int)pMod->hdr.nElem; 9447 float *aRound = 0; 9448 u8 *aCode = 0; 9449 int nCode = vec1EncodedVectorSize(pMod); 9450 char *zEnc = 0; 9451 int iEnc = 0; 9452 int ii; 9453 9454 zEnc = (char*)vec1MallocZero( 9455 nElem * 8 + 9456 nElem * sizeof_f32 + /* aRound[] */ 9457 nCode /* aCode[] */ 9458 ); 9459 if( zEnc==0 ){ 9460 return SQLITE_NOMEM; 9461 } 9462 aRound = (float*)&zEnc[nElem * 8]; 9463 aCode = (u8*)&aRound[nElem]; 9464 9465 vec1EncodeVector(pMod, aIn, aCode); 9466 vec1DecodeVector(pMod, aCode, aRound); 9467 9468 *prError = vec1L2Dist(aIn, aRound, nElem); 9469 zEnc[iEnc++] = '['; 9470 for(ii=0; ii=100 ) zEnc[iEnc++] = (aCode[ii] / 100) + '0'; 9473 if( aCode[ii]>=10 ) zEnc[iEnc++] = ((aCode[ii] / 10) % 10) + '0'; 9474 zEnc[iEnc++] = (aCode[ii] % 10) + '0'; 9475 } 9476 zEnc[iEnc++] = ']'; 9477 9478 *pzEnc = zEnc; 9479 return SQLITE_OK; 9480 } 9481 9482 static void vec1DistanceStats(sqlite3_context *ctx, Vec1Csr *pCsr){ 9483 int rc = SQLITE_OK; 9484 9485 if( pCsr->zDistance==0 ){ 9486 const float *aVec = 0; 9487 int nVec = 0; 9488 u8 *pFree = 0; 9489 rc = vec1GetVector(pCsr, (const u8**)&aVec, &nVec, &pFree); 9490 if( rc==SQLITE_OK && aVec ){ 9491 Vec1Tab *pTab = (Vec1Tab*)(pCsr->base.pVtab); 9492 int nElem = pTab->cfg.nElem; 9493 Vec1Model *pMod = &pTab->mod; 9494 int iBucket = 0; 9495 double fCoarseError = 0.0; 9496 double fReconError = 0.0; 9497 double fNorm = 0.0; 9498 const float *aTransform = 0; 9499 char *zEnc = 0; 9500 9501 if( pMod->hdr.nBucket>1 || pMod->hdr.nCodebook>0 ){ 9502 aTransform = vec1TransformInputVector(pMod, pTab->aTmpVec, aVec); 9503 fNorm = vec1VectorNorm2(aTransform, nElem); 9504 } 9505 9506 /* Find bucket and coarse error if applicable. */ 9507 if( pMod->hdr.nBucket>1 ){ 9508 iBucket = vec1BestMatchSimple( 9509 pMod->aCentroid, pMod->hdr.nBucket, aVec, nElem, &fCoarseError 9510 ); 9511 if( aTransform!=pTab->aTmpVec ){ 9512 memcpy(pTab->aTmpVec, aTransform, nElem*sizeof_f32); 9513 aTransform = pTab->aTmpVec; 9514 } 9515 if( pTab->mod.hdr.flags & VEC1_MODEL_RESIDUAL ){ 9516 vec1SubInPlace(pTab->aTmpVec, &pMod->aCentroid[iBucket*nElem], nElem); 9517 } 9518 } 9519 9520 /* Find reconstruction error if applicable. */ 9521 if( pMod->hdr.nCodebook>0 ){ 9522 rc = vec1QuantizeReconstructionError2( 9523 pMod, aTransform, &zEnc, &fReconError 9524 ); 9525 } 9526 9527 pCsr->zDistance = vec1MPrintf(&rc, 9528 "{bucket:%d, coarse_error:%f, reconstruction_error:%f, code: %s}", 9529 iBucket, 9530 fNorm==0.0 ? 0.0 : sqrt(fCoarseError/fNorm), 9531 fNorm==0.0 ? 0.0 : sqrt(fReconError/fNorm), 9532 zEnc ? zEnc : "null" 9533 ); 9534 sqlite3_free(zEnc); 9535 } 9536 sqlite3_free(pFree); 9537 } 9538 9539 if( rc!=SQLITE_OK ){ 9540 sqlite3_result_error_code(ctx, rc); 9541 }else{ 9542 sqlite3_result_text(ctx, pCsr->zDistance, -1, SQLITE_TRANSIENT); 9543 } 9544 } 9545 9546 static int vec1ColumnMethod( 9547 sqlite3_vtab_cursor *cur, 9548 sqlite3_context *ctx, 9549 int iCol 9550 ){ 9551 Vec1Csr *pCsr = (Vec1Csr *)cur; 9552 int rc = SQLITE_OK; 9553 if( iCol==VEC1_COLUMN_DISTANCE ){ 9554 if( pCsr->pQuery ){ 9555 double fDist = pCsr->pQuery->heap.aRes[pCsr->iCurrentRes].fDist; 9556 sqlite3_result_double(ctx, fDist); 9557 }else if( pCsr->bSqlNNQuery ){ 9558 int ii = sqlite3_column_count(pCsr->pStmt)-1; 9559 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pStmt, ii)); 9560 }else{ 9561 vec1DistanceStats(ctx, pCsr); 9562 } 9563 }else if( iCol==VEC1_COLUMN_VECTOR ){ 9564 const u8 *aVec = 0; 9565 int nVec = 0; 9566 u8 *pFree = 0; 9567 rc = vec1GetVector(pCsr, &aVec, &nVec, &pFree); 9568 if( rc==SQLITE_OK ){ 9569 sqlite3_result_blob(ctx, aVec, nVec, SQLITE_TRANSIENT); 9570 }else{ 9571 sqlite3_result_error_code(ctx, rc); 9572 } 9573 sqlite3_free(pFree); 9574 }else if( iCol>VEC1_COLUMN_VECTOR ){ 9575 rc = vec1SeekCsr(pCsr); 9576 if( rc==SQLITE_OK ){ 9577 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pStmt, iCol-2)); 9578 } 9579 } 9580 9581 return rc; 9582 } 9583 9584 static int vec1Rowid( 9585 sqlite3_vtab_cursor *cur, 9586 sqlite3_int64 *pRowid 9587 ){ 9588 Vec1Csr *pCsr = (Vec1Csr *)cur; 9589 if( pCsr->pQuery ){ 9590 *pRowid = pCsr->pQuery->heap.aRes[pCsr->iCurrentRes].iRowid; 9591 }else{ 9592 *pRowid = sqlite3_column_int64(pCsr->pStmt, 0); 9593 } 9594 return SQLITE_OK; 9595 } 9596 9597 /* 9598 ** Return true if constraint iCons of pInfo uses the "binary" collation 9599 ** sequence. Or false it it uses anything else. 9600 */ 9601 static int vec1IsBinary(sqlite3_index_info *pInfo, int iCons){ 9602 return 0==sqlite3_stricmp("binary", sqlite3_vtab_collation(pInfo, iCons)); 9603 } 9604 9605 9606 /* 9607 ** xBestIndex implementation. Three plans are supported: 9608 ** 9609 ** + Full scan. (idxNum==0 or idxNum=1) 9610 ** + Lookup by rowid . (idxNum==2 or idxNum=3) 9611 ** + KANN search. (idxNum==5) 9612 ** 9613 ** For KANN search, meta-data constraints are supported. They are encoded 9614 ** in idxStr. Specifically, for each handled constraint, there is one 9615 ** character to identify the operation, usually followed by one or more 9616 ** characters to identify the column the constraint applies to. 9617 ** 9618 ** idxStr format: 9619 */ 9620 static int vec1BestIndexMethod( 9621 sqlite3_vtab *pVtab, 9622 sqlite3_index_info *pIdxInfo 9623 ){ 9624 struct Vec1IdxOp { 9625 int idxop; 9626 char vec1op; 9627 } aOp[] = { 9628 { SQLITE_INDEX_CONSTRAINT_EQ, VEC1_OP_EQ }, 9629 { SQLITE_INDEX_CONSTRAINT_LT, VEC1_OP_LT }, 9630 { SQLITE_INDEX_CONSTRAINT_GT, VEC1_OP_GT }, 9631 { SQLITE_INDEX_CONSTRAINT_LE, VEC1_OP_LE }, 9632 { SQLITE_INDEX_CONSTRAINT_GE, VEC1_OP_GE }, 9633 { SQLITE_INDEX_CONSTRAINT_IS, VEC1_OP_IS }, 9634 { SQLITE_INDEX_CONSTRAINT_ISNULL, VEC1_OP_ISNULL }, 9635 { SQLITE_INDEX_CONSTRAINT_ISNOTNULL, VEC1_OP_NOTNULL }, 9636 }; 9637 const int bDistance = ( 9638 pIdxInfo->colUsed & ((1<nConstraint; ii++){ 9650 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; 9651 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ 9652 if( p->usable ){ 9653 if( p->iColumn==VEC1_COLUMN_CMD ) iCmd = ii; 9654 else if( p->iColumn==VEC1_COLUMN_ARG ) iArg = ii; 9655 else if( p->iColumn<0 ) iRowid = ii; 9656 }else{ 9657 if( p->iColumn==VEC1_COLUMN_CMD || p->iColumn==VEC1_COLUMN_ARG ){ 9658 return SQLITE_CONSTRAINT; 9659 } 9660 } 9661 } 9662 } 9663 9664 if( iCmd>=0 ){ 9665 int iLimit = -1; 9666 char *idxStr = vec1MallocZero((pIdxInfo->nConstraint*8)+1); 9667 int iStr = 0; 9668 int argvIndex = 0; 9669 9670 if( idxStr==0 ) return SQLITE_NOMEM; 9671 pIdxInfo->idxNum = 5; 9672 pIdxInfo->needToFreeIdxStr = 1; 9673 pIdxInfo->idxStr = idxStr; 9674 pIdxInfo->aConstraintUsage[iCmd].argvIndex = (++argvIndex); 9675 pIdxInfo->aConstraintUsage[iCmd].omit = 1; 9676 if( iArg>=0 ){ 9677 pIdxInfo->aConstraintUsage[iArg].argvIndex = (++argvIndex); 9678 pIdxInfo->aConstraintUsage[iArg].omit = 1; 9679 idxStr[iStr++] = VEC1_OP_PARAMS; 9680 } 9681 9682 /* Meta-data constraints */ 9683 for(ii=0; iinConstraint; ii++){ 9684 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; 9685 if( p->usable==0 ) continue; 9686 if( p->iColumn>VEC1_COLUMN_VECTOR ){ 9687 int jj; 9688 if( 0==vec1IsBinary(pIdxInfo, ii) ) continue; 9689 for(jj=0; jjop==aOp[jj].idxop ){ 9691 int iMeta = (p->iColumn - 1 - VEC1_COLUMN_VECTOR); 9692 if( jj==0 && sqlite3_vtab_in(pIdxInfo, ii, -1) ){ 9693 idxStr[iStr++] = VEC1_OP_IN; 9694 sqlite3_vtab_in(pIdxInfo, ii, 1); 9695 }else{ 9696 idxStr[iStr++] = aOp[jj].vec1op; 9697 } 9698 idxStr[iStr++] = aHexDigit[iMeta>>4]; 9699 idxStr[iStr++] = aHexDigit[iMeta&0xF]; 9700 pIdxInfo->aConstraintUsage[ii].argvIndex = (++argvIndex); 9701 pIdxInfo->aConstraintUsage[ii].omit = 1; 9702 break; 9703 } 9704 } 9705 } 9706 if( p->op==SQLITE_INDEX_CONSTRAINT_LIMIT ){ 9707 iLimit = ii; 9708 } 9709 } 9710 9711 if( iLimit>=0 9712 && pIdxInfo->nOrderBy==0 9713 && argvIndex==(pIdxInfo->nConstraint-1) 9714 ){ 9715 idxStr[iStr++] = VEC1_OP_LIMIT; 9716 pIdxInfo->aConstraintUsage[iLimit].argvIndex = (++argvIndex); 9717 pIdxInfo->aConstraintUsage[iLimit].omit = 1; 9718 } 9719 }else if( iRowid>=0 ){ 9720 pIdxInfo->idxNum = (bDistance ? 3 : 2); 9721 pIdxInfo->aConstraintUsage[iRowid].argvIndex = 1; 9722 pIdxInfo->aConstraintUsage[iRowid].omit = 1; 9723 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; 9724 9725 pIdxInfo->estimatedCost = 10.0; 9726 pIdxInfo->estimatedRows = 1; 9727 }else if( bDistance ){ 9728 pIdxInfo->idxNum = 1; 9729 } 9730 9731 return SQLITE_OK; 9732 } 9733 9734 static void vec1ListBuilderInitMetaArray(Vec1ListBuilder *p){ 9735 const u32 flags = VEC1_META_1BYTEINT|VEC1_META_4BYTEINT|VEC1_META_REAL; 9736 int ii; 9737 for(ii=0; iipTab->nMeta; ii++){ 9738 p->aMeta[ii].flags = flags; 9739 p->aMeta[ii].format = VEC1_META_GENERIC; 9740 p->aMeta[ii].buf.n = VEC1_META_SZHDR; 9741 } 9742 } 9743 9744 static int vec1ListBuilderInit(Vec1ListBuilder *p, Vec1Tab *pTab, int iBucket){ 9745 int rc = SQLITE_OK; 9746 9747 p->pTab = pTab; 9748 p->iBucket = iBucket; 9749 p->szRowid = 4; 9750 p->bSorted = 1; 9751 9752 if( pTab->mod.hdr.nCodebook ){ 9753 if( pTab->mod.hdr.flags & VEC1_MODEL_BITQUANT ){ 9754 p->eBlocked = VEC1_BLOCKED_BIN; 9755 }else{ 9756 p->eBlocked = VEC1_BLOCKED_PQ; 9757 } 9758 p->nVectorSize = vec1EncodedVectorSize(&pTab->mod); 9759 }else{ 9760 p->nVectorSize = pTab->cfg.nElem * sizeof_f32; 9761 p->eBlocked = VEC1_BLOCKED_NONE; 9762 } 9763 9764 if( pTab->nMeta>0 ){ 9765 int nMeta = pTab->nMeta; 9766 p->aMeta = (Vec1MetaBuilder*)vec1MallocZero(sizeof(Vec1MetaBuilder)*nMeta); 9767 if( p->aMeta==0 ){ 9768 rc = SQLITE_NOMEM; 9769 }else{ 9770 vec1ListBuilderInitMetaArray(p); 9771 } 9772 } 9773 9774 return rc; 9775 } 9776 9777 static int vec1WriteMetaBlob( 9778 Vec1Tab *pTab, /* Vec1 virtual table */ 9779 Vec1Buffer *pBuf, /* Buffer to write from */ 9780 i64 iId, /* Id of %_idx row */ 9781 int iMeta /* Index of meta-column */ 9782 ){ 9783 sqlite3_stmt *pStmt = 0; 9784 int rc = vec1GetSql(pTab, VEC1_SQL_WRITE_META, &pStmt); 9785 9786 assert( iMeta>=0 && iMetaa, pBuf->n, SQLITE_STATIC); 9791 sqlite3_step(pStmt); 9792 vec1StmtReset(&rc, pStmt); 9793 sqlite3_bind_null(pStmt, 2); 9794 } 9795 9796 return rc; 9797 } 9798 9799 static int vec1WriteMeta( 9800 Vec1Tab *pTab, /* Vec1 virtual table */ 9801 Vec1MetaBuilder *p, /* Buffer to write from */ 9802 int nEntry, 9803 i64 iId, /* Id of %_idx row */ 9804 int iMeta /* Index of meta-column */ 9805 ){ 9806 u32 f = 0; 9807 9808 if( (p->format & VEC1_META_GENERIC) 9809 && (p->flags & (VEC1_META_1BYTEINT|VEC1_META_4BYTEINT|VEC1_META_REAL)) 9810 ){ 9811 int iIn = VEC1_META_SZHDR; 9812 int iOut = VEC1_META_SZHDR; 9813 Vec1MetaValue val = {0,0,0,0}; 9814 Vec1Buffer buf = {0, 0, 0}; 9815 9816 int rc = SQLITE_OK; 9817 int szElem; 9818 i64 iNull; 9819 if( p->flags & VEC1_META_1BYTEINT ){ 9820 szElem = 1; 9821 iNull = VEC1_META_1BYTENULL; 9822 p->format = VEC1_META_1BYTEINT; 9823 }else if( p->flags & VEC1_META_4BYTEINT ){ 9824 szElem = sizeof_u32; 9825 iNull = VEC1_META_4BYTENULL; 9826 p->format = VEC1_META_4BYTEINT; 9827 }else{ 9828 szElem = sizeof_f64; 9829 iNull = VEC1_META_REALNULL; 9830 p->format = VEC1_META_REAL; 9831 } 9832 9833 rc = vec1BufferSize(&buf, VEC1_META_SZHDR + nEntry * szElem); 9834 if( rc!=SQLITE_OK ) return rc; 9835 9836 while( iInbuf.n ){ 9837 rc = vec1MetaValueRead(&p->buf, &iIn, &val); 9838 if( rc!=SQLITE_OK ) break; 9839 if( val.eType==SQLITE_NULL ){ 9840 val.iVal = iNull; 9841 }else if( p->format==VEC1_META_REAL ){ 9842 if( val.eType==SQLITE_INTEGER ){ 9843 val.fVal = (double)val.iVal; 9844 } 9845 memcpy(&val.iVal, &val.fVal, sizeof_f64); 9846 } 9847 if( szElem==1 ){ 9848 buf.a[iOut] = (val.iVal & 0xFF); 9849 }else if( szElem==sizeof_u32 ){ 9850 vec1PutU32(&buf.a[iOut], (u32)val.iVal); 9851 }else{ 9852 vec1PutU64(&buf.a[iOut], (u64)val.iVal); 9853 } 9854 iOut += szElem; 9855 } 9856 buf.n = iOut; 9857 9858 SWAP(Vec1Buffer, p->buf, buf); 9859 vec1BufferFree(&buf); 9860 } 9861 9862 f = (p->format | (p->flags & VEC1_META_HASNULL)); 9863 vec1PutU32(&p->buf.a[0], f); 9864 vec1PutU32(&p->buf.a[4], nEntry); 9865 return vec1WriteMetaBlob(pTab, &p->buf, iId, iMeta); 9866 } 9867 9868 /* 9869 ** A serialized meta-value is stored in buffer aBuf. Return the size in 9870 ** bytes of the meta value. 9871 */ 9872 static i64 vec1MetaValueSize(const u8 *aBuf){ 9873 switch( aBuf[0] ){ 9874 case 0: return 1; /* NULL */ 9875 case 1: return 2; /* 1-byte integer */ 9876 case 2: return 5; /* 4-byte float */ 9877 case 3: return 9; /* 8-byte integer */ 9878 case 4: return 9; /* 8-byte real */ 9879 default: { 9880 /* Either a blob or text field. If the size of the value in bytes 9881 ** is N, then the varint value V is: 9882 ** 9883 ** text (odd V values) : V = (2N + 5) -> N = (V - 5) / 2 9884 ** blob (even V values): V = (2N + 6) -> N = (V - 6) / 2 9885 */ 9886 i64 V = 0; 9887 int n = vec1GetVarint(aBuf, (u64*)&V); 9888 return (((V-5)/2) & (i64)0xFFFFFFFF) + n; 9889 } 9890 } 9891 } 9892 9893 static int vec1ListBuilderLoad( 9894 Vec1ListBuilder *p, 9895 i64 iId, 9896 i64 iFirst, 9897 i64 iLast, 9898 const u8 *aVal, int nVal 9899 ){ 9900 Vec1Tab *pTab = p->pTab; 9901 int nEntry = 0; 9902 int flags = 0; 9903 int rc = SQLITE_OK; 9904 int nRowid = 0; 9905 int nData = 0; 9906 int ii; /* Iterator variable */ 9907 9908 assert( p->bufRowid.n==0 ); 9909 assert( p->szRowid==4 ); 9910 9911 if( vec1CheckIdxSize(pTab, aVal, nVal) ){ 9912 return VEC1_CORRUPT; 9913 } 9914 flags = vec1GetU32(&aVal[0]); 9915 nEntry = vec1GetU32(&aVal[4]); 9916 p->nTombstone = vec1GetU32(&aVal[8]); 9917 if( flags & VEC1_LIST_64BIT ) p->szRowid = 8; 9918 9919 /* Set Vec1ListBuilder.eBlocked */ 9920 if( pTab->mod.hdr.flags & VEC1_MODEL_BITQUANT ){ 9921 p->eBlocked = VEC1_BLOCKED_BIN; 9922 }else if( pTab->mod.hdr.nCodebook>0 ){ 9923 p->eBlocked = VEC1_BLOCKED_PQ; 9924 }else{ 9925 p->eBlocked = VEC1_BLOCKED_NONE; 9926 } 9927 9928 p->bSorted = ((flags & VEC1_LIST_SORTED)!=0); 9929 p->iFirst = iFirst; 9930 p->iLast = iLast; 9931 p->iId = iId; 9932 9933 nRowid = nEntry * p->szRowid; 9934 nData = nVal - VEC1_LIST_SZHDR - nRowid; 9935 rc = vec1BufferGrow(&p->bufRowid, nRowid); 9936 if( rc==SQLITE_OK ){ 9937 memcpy(p->bufRowid.a, &aVal[VEC1_LIST_SZHDR], nRowid); 9938 p->bufRowid.n = nRowid; 9939 rc = vec1BufferGrow(&p->bufData, nData); 9940 } 9941 if( rc==SQLITE_OK ){ 9942 memcpy(p->bufData.a, &aVal[VEC1_LIST_SZHDR+nRowid], nData); 9943 p->bufData.n = nData; 9944 } 9945 9946 /* Load the array for each meta-data column from the %_meta table */ 9947 for(ii=0; rc==SQLITE_OK && iinMeta; ii++){ 9948 Vec1MetaBuilder *pMeta = &p->aMeta[ii]; 9949 rc = vec1ReadMeta(pTab, nEntry, &pMeta->buf, iId, ii); 9950 if( rc==SQLITE_OK ){ 9951 u32 f = vec1GetU32(pMeta->buf.a); 9952 pMeta->format = (f & VEC1_META_TYPEMASK); 9953 pMeta->flags = f; 9954 } 9955 } 9956 9957 return rc; 9958 } 9959 9960 static int vec1ListBuilderFlush(Vec1ListBuilder *p){ 9961 int rc = SQLITE_OK; 9962 if( p->bufRowid.n>0 ){ 9963 int nEntry = p->bufRowid.n / p->szRowid; 9964 i64 iId = 0; 9965 int ii; 9966 sqlite3_stmt *pStmt = 0; 9967 u8 *aBlob = 0; 9968 int nBlob = 0; 9969 9970 nBlob = VEC1_LIST_SZHDR + p->bufRowid.n + p->bufData.n; 9971 aBlob = (u8*)sqlite3_malloc(nBlob); 9972 if( aBlob==0 ){ 9973 rc = SQLITE_NOMEM; 9974 }else{ 9975 int flags = 0; 9976 if( p->bSorted ) flags |= VEC1_LIST_SORTED; 9977 if( p->szRowid==8 ) flags |= VEC1_LIST_64BIT; 9978 vec1PutU32(&aBlob[0], flags); 9979 vec1PutU32(&aBlob[4], nEntry); 9980 vec1PutU32(&aBlob[8], p->nTombstone); 9981 memcpy(&aBlob[VEC1_LIST_SZHDR], p->bufRowid.a, p->bufRowid.n); 9982 memcpy(&aBlob[VEC1_LIST_SZHDR+p->bufRowid.n], p->bufData.a, p->bufData.n); 9983 9984 if( p->iId>0 ){ 9985 /* If there is an existing entry, remove it */ 9986 rc = vec1GetSql(p->pTab, VEC1_SQL_DELETE_FROM_IDX, &pStmt); 9987 if( rc==SQLITE_OK ){ 9988 sqlite3_bind_int64(pStmt, 1, p->iId); 9989 sqlite3_step(pStmt); 9990 vec1StmtReset(&rc, pStmt); 9991 } 9992 } 9993 9994 if( rc==SQLITE_OK ){ 9995 rc = vec1GetSql(p->pTab, VEC1_SQL_INSERT_IDX, &pStmt); 9996 } 9997 if( rc==SQLITE_OK ){ 9998 if( p->iId==0 ){ 9999 sqlite3_bind_null(pStmt, 1); 10000 }else{ 10001 sqlite3_bind_int64(pStmt, 1, p->iId); 10002 } 10003 sqlite3_bind_int(pStmt, 2, p->iBucket); 10004 sqlite3_bind_int64(pStmt, 3, p->iFirst); 10005 sqlite3_bind_int64(pStmt, 4, p->iLast); 10006 10007 rc = sqlite3_bind_blob(pStmt, 5, aBlob, nBlob, SQLITE_STATIC); 10008 sqlite3_step(pStmt); 10009 vec1StmtReset(&rc, pStmt); 10010 if( rc==SQLITE_OK ){ 10011 iId = sqlite3_last_insert_rowid(p->pTab->db); 10012 } 10013 } 10014 sqlite3_free(aBlob); 10015 10016 /* If an error occurred within the sqlite3_step() call above, then the 10017 ** transaction may have been rolled back and (*p) freed. So take 10018 ** care not to access it again if rc!=SQLITE_OK. */ 10019 if( rc==SQLITE_OK ){ 10020 p->bufRowid.n = 0; 10021 p->bufData.n = 0; 10022 p->iId = 0; 10023 p->iId = 0; 10024 } 10025 } 10026 10027 for(ii=0; rc==SQLITE_OK && iipTab->nMeta; ii++){ 10028 rc = vec1WriteMeta(p->pTab, &p->aMeta[ii], nEntry, iId, ii); 10029 if( rc==SQLITE_OK ) p->aMeta[ii].buf.n = VEC1_META_SZHDR; 10030 } 10031 10032 /* Same reasoning as above - if rc!=SQLITE_OK, then the transaction 10033 ** may have been rolled back and (*p) freed already. */ 10034 if( rc==SQLITE_OK ){ 10035 p->bSorted = 1; 10036 } 10037 }else if( p->iId>0 ){ 10038 sqlite3_stmt *pDelete = 0; 10039 rc = vec1GetSql(p->pTab, VEC1_SQL_DELETE_FROM_IDX, &pDelete); 10040 if( rc==SQLITE_OK ){ 10041 sqlite3_bind_int64(pDelete, 1, p->iId); 10042 sqlite3_step(pDelete); 10043 vec1StmtReset(&rc, pDelete); 10044 } 10045 if( p->pTab->nMeta>0 && rc==SQLITE_OK ){ 10046 rc = vec1GetSql(p->pTab, VEC1_SQL_DELETE_FROM_META, &pDelete); 10047 if( rc==SQLITE_OK ){ 10048 sqlite3_bind_int64(pDelete, 1, p->iId); 10049 sqlite3_step(pDelete); 10050 vec1StmtReset(&rc, pDelete); 10051 } 10052 } 10053 } 10054 return rc; 10055 } 10056 10057 10058 /* 10059 ** Return the offset of the first field of vector ii within a blocked 10060 ** storage buffer. Each vector is nVectorSize bytes in size (including 10061 ** the norm for binary-quantized vectors). szElem0 is the size of the 10062 ** first element in each vector (4 for binary-quant, 1 for product-quant). 10063 */ 10064 #define VEC1_LIST_BLOCKED_OFFSET(ii, nVectorSize) ( \ 10065 ((ii / VEC1_PQ_BLOCKSIZE) * VEC1_PQ_BLOCKSIZE * nVectorSize) + \ 10066 (ii % VEC1_PQ_BLOCKSIZE) \ 10067 ) 10068 10069 /* 10070 ** Return the offset of the norm field for vector ii within a blocked 10071 ** buffer containing binary quanitized vectors. Each quantized vector 10072 ** is nCodebook bytes in size, not including the 4 byte norm. 10073 */ 10074 #define VEC1_LIST_NORM_OFFSET(ii, nCodebook) ( \ 10075 ((ii / VEC1_PQ_BLOCKSIZE) * VEC1_PQ_BLOCKSIZE * (nCodebook+sizeof_f32)) + \ 10076 (ii % VEC1_PQ_BLOCKSIZE) * sizeof_f32 \ 10077 ) 10078 10079 #define VEC1_LIST_CODE_OFFSET(ii, nCodebook) ( \ 10080 ((ii / VEC1_PQ_BLOCKSIZE) * VEC1_PQ_BLOCKSIZE * (nCodebook+sizeof_f32)) + \ 10081 (VEC1_PQ_BLOCKSIZE * sizeof_f32) + \ 10082 (ii % VEC1_PQ_BLOCKSIZE) \ 10083 ) 10084 10085 /* 10086 ** Shuffle the contents of the list-builder around so that it 10087 ** contains 0 tombstones. 10088 */ 10089 static int vec1ListBuilderCompress( 10090 Vec1ListBuilder *p, 10091 i64 iDel 10092 ){ 10093 const int nMeta = p->pTab->nMeta; 10094 int ii; 10095 int iOut = 0; 10096 int nEntry = p->bufRowid.n / p->szRowid; 10097 int *aMetaIn = 0; /* Meta-data input offsets */ 10098 int *aMetaOut = 0; /* Meta-data output offsets */ 10099 10100 i64 tomb1 = p->szRowid==8 ? VEC1_TOMBSTONE_64 : VEC1_TOMBSTONE_32; 10101 i64 tomb2 = iDel; 10102 10103 /* Allocate space for aMetaIn[] and aMetaOut[] if requried */ 10104 if( nMeta>0 ){ 10105 aMetaIn = vec1MallocZero(nMeta * 2 * sizeof(int)); 10106 if( aMetaIn==0 ) return SQLITE_NOMEM; 10107 aMetaOut = &aMetaIn[nMeta]; 10108 for(ii=0; iiiFirst = VEC1_LARGEST_INT64; 10115 p->iLast = VEC1_SMALLEST_INT64; 10116 10117 for(ii=0; iiszRowid*ii; 10119 i64 iRowid; 10120 int bTombstone = 0; 10121 int iMeta; /* Iterator used for meta-data columns */ 10122 10123 if( p->szRowid==8 ){ 10124 iRowid = vec1GetU64(&p->bufRowid.a[iOff]); 10125 }else{ 10126 iRowid = vec1GetU32(&p->bufRowid.a[iOff]); 10127 } 10128 if( iRowid==tomb1 || iRowid==tomb2 ) bTombstone = 1; 10129 10130 if( bTombstone==0 ){ 10131 p->iFirst = MIN(p->iFirst, iRowid); 10132 p->iLast = MAX(p->iLast, iRowid); 10133 10134 if( ii!=iOut ){ 10135 int iOff2 = p->szRowid*iOut; 10136 u8 *a = p->bufData.a; 10137 int iFrom, iTo; 10138 10139 memcpy(&p->bufRowid.a[iOff2], &p->bufRowid.a[iOff], p->szRowid); 10140 if( p->eBlocked==VEC1_BLOCKED_NONE ){ 10141 int i1 = p->nVectorSize * iOut; 10142 int i2 = p->nVectorSize * ii; 10143 memcpy(&p->bufData.a[i1], &p->bufData.a[i2], p->nVectorSize); 10144 }else{ 10145 int nCodebook; /* Size of quantized vector without norm */ 10146 int jj; 10147 10148 if( p->eBlocked==VEC1_BLOCKED_BIN ){ 10149 nCodebook = p->nVectorSize - sizeof_f32; 10150 memcpy(&a[ VEC1_LIST_NORM_OFFSET(iOut, nCodebook) ], 10151 &a[ VEC1_LIST_NORM_OFFSET(ii, nCodebook) ], 10152 sizeof_f32 10153 ); 10154 iFrom = VEC1_LIST_CODE_OFFSET(ii, nCodebook); 10155 iTo = VEC1_LIST_CODE_OFFSET(iOut, nCodebook); 10156 }else{ 10157 assert( p->eBlocked==VEC1_BLOCKED_PQ ); 10158 nCodebook = p->nVectorSize; 10159 iFrom = VEC1_LIST_BLOCKED_OFFSET(ii, nCodebook); 10160 iTo = VEC1_LIST_BLOCKED_OFFSET(iOut, nCodebook); 10161 } 10162 10163 for(jj=0; jjbufData.a[iFrom + jj*VEC1_PQ_BLOCKSIZE]; 10165 p->bufData.a[iTo + jj*VEC1_PQ_BLOCKSIZE] = v; 10166 } 10167 } 10168 } 10169 iOut++; 10170 } 10171 10172 for(iMeta=0; iMetaaMeta[iMeta]; 10174 u8 *a = pMeta->buf.a; 10175 10176 if( pMeta->format==VEC1_META_GENERIC ){ 10177 i64 nIn = vec1MetaValueSize(&a[aMetaIn[iMeta]]); 10178 if( nIn<=0 || nIn>pMeta->buf.n-aMetaIn[iMeta] ){ 10179 sqlite3_free(aMetaIn); 10180 return VEC1_CORRUPT; 10181 } 10182 if( bTombstone==0 ){ 10183 if( aMetaIn[iMeta]!=aMetaOut[iMeta] ){ 10184 memmove(&a[ aMetaOut[iMeta] ], &a[ aMetaIn[iMeta] ], nIn); 10185 } 10186 aMetaOut[iMeta] += nIn; 10187 } 10188 aMetaIn[iMeta] += nIn; 10189 }else{ 10190 int szElem = 10191 (pMeta->format==VEC1_META_1BYTEINT) ? 1 : 10192 (pMeta->format==VEC1_META_4BYTEINT) ? sizeof_u32 : sizeof_f64 10193 ; 10194 if( bTombstone==0 ){ 10195 memmove(&a[ aMetaOut[iMeta] ], &a[ aMetaIn[iMeta] ], szElem); 10196 aMetaOut[iMeta] += szElem; 10197 } 10198 aMetaIn[iMeta] += szElem; 10199 } 10200 } 10201 } 10202 10203 p->nTombstone = 0; 10204 10205 p->bufRowid.n = iOut*p->szRowid; 10206 if( p->eBlocked==VEC1_BLOCKED_NONE ){ 10207 p->bufData.n = p->nVectorSize * iOut; 10208 }else{ 10209 p->bufData.n = p->nVectorSize * VEC1_PQ_BLOCKSIZE * ( 10210 ((iOut+VEC1_PQ_BLOCKSIZE-1)/VEC1_PQ_BLOCKSIZE) 10211 ); 10212 } 10213 for(ii=0; iiaMeta[ii].buf.n = aMetaOut[ii]; 10215 } 10216 10217 sqlite3_free(aMetaIn); 10218 return SQLITE_OK; 10219 } 10220 10221 /* 10222 ** Append a rowid/[PQ|vector] pair to a list builder object. 10223 */ 10224 static int vec1ListBuilderAdd( 10225 Vec1ListBuilder *p, 10226 i64 iRowid, /* Rowid value to add to builder */ 10227 const u8 *aPQ /* Pointer to buffer containing PQ enc. */ 10228 ){ 10229 int rc = SQLITE_OK; 10230 int nFinal = 0; 10231 const int vs = p->nVectorSize; 10232 10233 assert( p->szRowid==4 || p->szRowid==8 ); 10234 10235 /* Check if adding this entry would cause the final blob to be larger 10236 ** than the configured 'blocksize'. If so, flush it to disk. 10237 ** 10238 ** If the proposed rowid may not be added to the current list because 10239 ** it is too large or a tombstone value, flush the current list to disk 10240 ** in that case as well. 10241 */ 10242 nFinal = p->bufRowid.n + p->bufData.n + p->szRowid + p->nVectorSize; 10243 if( nFinal>p->pTab->cfg.nBlocksize 10244 || (p->szRowid==4 && (iRowid<0 || iRowid>=VEC1_TOMBSTONE_32)) 10245 || (p->szRowid==8 && iRowid==VEC1_TOMBSTONE_64) 10246 ){ 10247 rc = vec1ListBuilderFlush(p); 10248 if( rc!=SQLITE_OK ) return rc; 10249 p->szRowid = ((iRowid<0 || iRowid>=VEC1_TOMBSTONE_32) ? 8 : 4); 10250 p->bSorted = 1; 10251 p->iId = 0; 10252 p->nTombstone = 0; 10253 vec1ListBuilderInitMetaArray(p); 10254 } 10255 10256 /* Update Vec1ListBuilder.iFirst, iLast and bSorted to account for the 10257 ** rowid value being added by this call. */ 10258 if( p->bufRowid.n==0 ){ 10259 p->iLast = p->iFirst = iRowid; 10260 }else if( iRowidiLast ){ 10261 p->bSorted = 0; 10262 p->iFirst = MIN(p->iFirst, iRowid); 10263 }else{ 10264 p->iLast = iRowid; 10265 } 10266 10267 /* Ensure that there is room in the two buffers for this entry. The 10268 ** rowids buffer always grows by szRowid bytes. How much the data 10269 ** buffer grows by depends on whether it is blocked or not. */ 10270 rc = vec1BufferGrow(&p->bufRowid, p->szRowid); 10271 if( rc==SQLITE_OK ){ 10272 if( p->eBlocked==VEC1_BLOCKED_NONE ){ 10273 rc = vec1BufferGrow(&p->bufData, p->nVectorSize); 10274 }else{ 10275 int nEntry = (p->bufRowid.n / p->szRowid); 10276 if( (nEntry % VEC1_PQ_BLOCKSIZE)==0 ){ 10277 int nReq = (VEC1_PQ_BLOCKSIZE * p->nVectorSize); 10278 rc = vec1BufferGrow(&p->bufData, nReq); 10279 if( rc==SQLITE_OK ){ 10280 memset(&p->bufData.a[p->bufData.n], 0, nReq); 10281 p->bufData.n += nReq; 10282 } 10283 } 10284 } 10285 } 10286 10287 if( rc==SQLITE_OK ){ 10288 10289 /* Write the vector or PQ data */ 10290 if( p->eBlocked==VEC1_BLOCKED_NONE ){ 10291 memcpy(&p->bufData.a[p->bufData.n], aPQ, p->nVectorSize); 10292 p->bufData.n += p->nVectorSize; 10293 }else{ 10294 const int iEntry = (p->bufRowid.n / p->szRowid); 10295 const int iBlkOff = (iEntry / VEC1_PQ_BLOCKSIZE) * vs * VEC1_PQ_BLOCKSIZE; 10296 const int iBlkEntry = iEntry % VEC1_PQ_BLOCKSIZE; 10297 10298 int ii = 0; 10299 int iOff = iBlkOff + iBlkEntry; 10300 10301 if( p->eBlocked==VEC1_BLOCKED_BIN ){ 10302 /* In this case, the first 4 bytes of the encoded vector is its norm. 10303 ** Each block begins with an array of VEC1_PQ_BLOCKSIZE norm values. 10304 ** Copy the norm for this vector in now. */ 10305 const int iNorm = iBlkOff + (sizeof_f32 * iBlkEntry); 10306 memcpy(&p->bufData.a[iNorm], aPQ, sizeof_f32); 10307 ii = 4; 10308 iOff += (sizeof_f32 * VEC1_PQ_BLOCKSIZE) - ii*VEC1_PQ_BLOCKSIZE; 10309 } 10310 10311 /* Write each byte of the PQ or binary quant code */ 10312 for(/* no-op */; iinVectorSize; ii++){ 10313 p->bufData.a[iOff + ii*VEC1_PQ_BLOCKSIZE] = aPQ[ii]; 10314 } 10315 } 10316 10317 /* Write the rowid */ 10318 if( p->szRowid==8 ){ 10319 vec1PutU64(&p->bufRowid.a[p->bufRowid.n], iRowid); 10320 }else{ 10321 vec1PutU32(&p->bufRowid.a[p->bufRowid.n], (u32)iRowid); 10322 } 10323 p->bufRowid.n += p->szRowid; 10324 } 10325 10326 return rc; 10327 } 10328 10329 static void vec1ListBuilderFree(Vec1ListBuilder *p){ 10330 int ii; 10331 vec1BufferFree(&p->bufRowid); 10332 vec1BufferFree(&p->bufData); 10333 if( p->aMeta ){ 10334 for(ii=0; iipTab->nMeta; ii++){ 10335 vec1BufferFree(&p->aMeta[ii].buf); 10336 } 10337 } 10338 sqlite3_free(p->aMeta); 10339 } 10340 10341 /* 10342 ** Allocate a new writer object for vec1 table pTab. 10343 */ 10344 static int vec1WriterAlloc( 10345 Vec1Tab *pTab, /* Vec1 table */ 10346 int bRebuild, /* True if this is 'rebuild' op */ 10347 Vec1Writer **pp /* OUT: New writer object */ 10348 ){ 10349 int rc = SQLITE_OK; 10350 Vec1Writer *p = 0; 10351 int nBld = pTab->mod.hdr.nBucket ? pTab->mod.hdr.nBucket : 1; 10352 int nEncoded = vec1EncodedVectorSize(&pTab->mod); 10353 10354 int nByte = 10355 sizeof(Vec1Writer) + /* Vec1Writer */ 10356 sizeof(Vec1ListBuilder) * nBld + /* Vec1Writer.aBld */ 10357 sizeof_f32 * pTab->nTmpVec + /* Vec1Writer.aResidual */ 10358 nEncoded; /* Vec1Writer.aPQ */ 10359 10360 p = (Vec1Writer*)vec1MallocZero(nByte); 10361 if( p==0 ){ 10362 rc = SQLITE_NOMEM; 10363 }else{ 10364 memset(p, 0, nByte); 10365 p->aBld = (Vec1ListBuilder*)&p[1]; 10366 p->aResidual = (float*)&p->aBld[nBld]; 10367 p->aPQ = (u8*)&p->aResidual[pTab->nTmpVec]; 10368 p->pTab = pTab; 10369 p->bRebuild = bRebuild; 10370 p->nBld = nBld; 10371 if( bRebuild ){ 10372 int ii; 10373 for(ii=0; rc==SQLITE_OK && iiaBld[ii], pTab, ii); 10375 } 10376 } 10377 } 10378 *pp = p; 10379 10380 return rc; 10381 } 10382 10383 /* 10384 ** Quantize a vector so that it can be written to the index. 10385 */ 10386 static void vec1QuantizeVector( 10387 const Vec1Model *pMod, /* Current model */ 10388 float *aTmp, /* Temporary space - same dim as vectors */ 10389 const float *aVector, /* Vector to quantize */ 10390 int *piBucket, /* OUT: Bucket to put vector in */ 10391 u8 *aCode /* OUT: Write PQ code (if any) here */ 10392 ){ 10393 const int nBucket = pMod->hdr.nBucket; 10394 const float *aVec; 10395 int iBucket = 0; 10396 10397 aVec = vec1TransformInputVector(pMod, aTmp, aVector); 10398 if( nBucket>0 ){ 10399 int nElem = pMod->hdr.nElem; 10400 iBucket = vec1BestMatchSimple(pMod->aCentroid, nBucket, aVec, nElem, 0); 10401 if( pMod->hdr.nCodebook>0 && (pMod->hdr.flags & VEC1_MODEL_RESIDUAL) ){ 10402 vec1Sub(aTmp, aVec, &pMod->aCentroid[iBucket*nElem], nElem); 10403 aVec = aTmp; 10404 } 10405 } 10406 10407 if( pMod->hdr.nCodebook>0 ){ 10408 vec1EncodeVector(pMod, aVec, aCode); 10409 } 10410 10411 *piBucket = iBucket; 10412 } 10413 10414 10415 static int vec1WriterVector( 10416 Vec1Writer *p, /* Writer object to write to */ 10417 i64 iRowid, /* Rowid of new entry */ 10418 const float *aVector, /* New vector */ 10419 int *piBucket 10420 ){ 10421 Vec1Tab *pTab = p->pTab; 10422 const u8 *aStore; 10423 Vec1ListBuilder *pBld = 0; 10424 const Vec1Model *pMod = &pTab->mod; 10425 int rc = SQLITE_OK; 10426 int iBld = *piBucket; 10427 10428 /* Transform and quantize the vector */ 10429 if( iBld<0 ){ 10430 vec1QuantizeVector(pMod, p->aResidual, aVector, &iBld, p->aPQ); 10431 } 10432 10433 if( pMod->hdr.nCodebook>0 ){ 10434 aStore = p->aPQ; 10435 }else{ 10436 /* If the index is storing full vectors, not PQ codes, store the original, 10437 ** not the transformed vector. */ 10438 aStore = (const u8*)aVector; 10439 } 10440 10441 pBld = &p->aBld[iBld]; 10442 if( pBld->pTab==0 ){ 10443 /* Attempt to load blob smaller than 'blocksize-min' belonging to 10444 ** this bucket to append to. */ 10445 sqlite3_stmt *pSearch = 0; 10446 rc = vec1ListBuilderInit(pBld, pTab, iBld); 10447 if( rc==SQLITE_OK ){ 10448 rc = vec1GetSql(pTab, VEC1_SQL_SEARCH_IDX_FOR_INSERT, &pSearch); 10449 } 10450 if( rc==SQLITE_OK ){ 10451 sqlite3_bind_int(pSearch, 1, iBld); 10452 sqlite3_bind_int(pSearch, 2, pTab->cfg.nBlocksizeMin); 10453 if( SQLITE_ROW==sqlite3_step(pSearch) ){ 10454 i64 iId = sqlite3_column_int64(pSearch, 0); 10455 i64 iFirst = sqlite3_column_int64(pSearch, 1); 10456 i64 iLast = sqlite3_column_int64(pSearch, 2); 10457 const u8 *aVal = (const u8*)sqlite3_column_blob(pSearch, 3); 10458 int nVal = sqlite3_column_bytes(pSearch, 3); 10459 rc = vec1ListBuilderLoad(pBld, iId, iFirst, iLast, aVal, nVal); 10460 } 10461 vec1StmtReset(&rc, pSearch); 10462 } 10463 } 10464 10465 if( rc==SQLITE_OK ){ 10466 rc = vec1ListBuilderAdd(pBld, iRowid, aStore); 10467 } 10468 10469 *piBucket = iBld; 10470 return rc; 10471 } 10472 10473 /* 10474 ** Serialize value pVal and append it to buffer pBuf. Vec1 uses a serialization 10475 ** format based on SQLite's. First a varint indicating the type and size 10476 ** of the value, followed by the data for the value itself. Text values 10477 ** are always encoded using utf-8. 10478 ** 10479 ** 0: NULL value. 0 byte payload. 10480 ** 1: Integer value (unsigned). 1 byte payload. 10481 ** 2: Integer value (signed). 4 byte payload. 10482 ** 3: Integer value (signed). 8 byte payload. 10483 ** 4: Real value. 8 byte payload. 10484 ** 10485 ** Greater than 4 and odd is a text value. Payload size ((v-5)/2). Greater 10486 ** than 4 and even is a blob value. Payload size ((v-6)/2). 10487 */ 10488 static int vec1AppendMetaValue( 10489 Vec1Buffer *pBuf, 10490 sqlite3_value *pVal 10491 ){ 10492 int rc = SQLITE_OK; 10493 switch( sqlite3_value_type(pVal) ){ 10494 case SQLITE_NULL: { 10495 rc = vec1BufferGrow(pBuf, 1); 10496 if( rc==SQLITE_OK ){ 10497 pBuf->a[pBuf->n++] = 0x00; 10498 } 10499 break; 10500 } 10501 10502 case SQLITE_INTEGER: { 10503 i64 iVal = sqlite3_value_int64(pVal); 10504 rc = vec1BufferGrow(pBuf, 9); 10505 if( rc==SQLITE_OK ){ 10506 if( iVal>=0 && iVal<=254 ){ 10507 pBuf->a[pBuf->n++] = 0x01; 10508 pBuf->a[pBuf->n++] = (iVal & 0xFF); 10509 } 10510 else if( iVal>=VEC1_META_4BYTEMIN && iVal<=VEC1_META_4BYTEMAX ){ 10511 pBuf->a[pBuf->n++] = 0x02; 10512 vec1PutU32(&pBuf->a[pBuf->n], (int)iVal); 10513 pBuf->n += 4; 10514 }else{ 10515 pBuf->a[pBuf->n++] = 0x03; 10516 vec1PutU64(&pBuf->a[pBuf->n], iVal); 10517 pBuf->n += 8; 10518 } 10519 } 10520 break; 10521 } 10522 10523 case SQLITE_FLOAT: { 10524 double fVal = sqlite3_value_double(pVal); 10525 rc = vec1BufferGrow(pBuf, 9); 10526 if( rc==SQLITE_OK ){ 10527 i64 iVal; 10528 memcpy(&iVal, &fVal, sizeof(fVal)); 10529 pBuf->a[pBuf->n++] = 0x04; 10530 vec1PutU64(&pBuf->a[pBuf->n], iVal); 10531 pBuf->n += 8; 10532 } 10533 break; 10534 } 10535 10536 case SQLITE_TEXT: { 10537 const char *z = (const char*)sqlite3_value_text(pVal); 10538 int n = sqlite3_value_bytes(pVal); 10539 rc = vec1BufferGrow(pBuf, n+5); 10540 if( rc==SQLITE_OK ){ 10541 pBuf->n += vec1PutVarint(&pBuf->a[pBuf->n], (n*2 + 5)); 10542 memcpy(&pBuf->a[pBuf->n], z, n); 10543 pBuf->n += n; 10544 } 10545 break; 10546 } 10547 10548 default: { 10549 const u8 *z = (const u8*)sqlite3_value_blob(pVal); 10550 int n = sqlite3_value_bytes(pVal); 10551 rc = vec1BufferGrow(pBuf, n+5); 10552 if( rc==SQLITE_OK ){ 10553 pBuf->n += vec1PutVarint(&pBuf->a[pBuf->n], (n*2 + 6)); 10554 memcpy(&pBuf->a[pBuf->n], z, n); 10555 pBuf->n += n; 10556 } 10557 assert( sqlite3_value_type(pVal)==SQLITE_BLOB ); 10558 break; 10559 } 10560 } 10561 10562 return rc; 10563 } 10564 10565 static void vec1MetaValueUpdateFlags(const u8 *aMeta, u32 *pFlags){ 10566 switch( aMeta[0] ){ 10567 case 0: /* NULL value */ 10568 *pFlags |= VEC1_META_HASNULL; 10569 break; 10570 10571 case 1: /* 1-byte integer */ 10572 break; 10573 10574 case 2: /* 4-byte integer */ 10575 *pFlags &= ~(VEC1_META_1BYTEINT); 10576 break; 10577 10578 case 4: /* 8-byte real */ 10579 *pFlags &= ~(VEC1_META_1BYTEINT|VEC1_META_4BYTEINT); 10580 break; 10581 10582 default: 10583 *pFlags &= ~(VEC1_META_1BYTEINT|VEC1_META_4BYTEINT|VEC1_META_REAL); 10584 break; 10585 } 10586 } 10587 10588 /* 10589 ** The meta-list builder passed as the only argument currently contains 10590 ** a list of values in non-generic format (e.g. VEC1_META_1BYTEINT format). 10591 ** This function converts the list to generic format. 10592 ** 10593 ** Return SQLITE_OK if successful, or an SQLite error code (SQLITE_NOMEM) 10594 ** otherwise. 10595 */ 10596 static int vec1ExpandMetaValue(Vec1MetaBuilder *p){ 10597 Vec1Buffer orig; 10598 int rc = SQLITE_OK; 10599 int bHasNull = 0; 10600 10601 memcpy(&orig, &p->buf, sizeof(Vec1Buffer)); 10602 p->buf.a = 0; 10603 p->buf.n = VEC1_META_SZHDR; 10604 p->buf.nAlloc = 0; 10605 10606 assert( p->format==VEC1_META_1BYTEINT 10607 || p->format==VEC1_META_4BYTEINT 10608 || p->format==VEC1_META_REAL 10609 ); 10610 10611 rc = vec1BufferGrow(&p->buf, (orig.n * 2)); 10612 if( rc==SQLITE_OK ){ 10613 int iIn = VEC1_META_SZHDR; 10614 int iOut = VEC1_META_SZHDR; 10615 10616 while( iInformat==VEC1_META_1BYTEINT ){ 10618 int v = orig.a[iIn++]; 10619 if( v==VEC1_META_1BYTENULL ){ 10620 p->buf.a[iOut++] = 0x00; 10621 bHasNull = 1; 10622 }else{ 10623 p->buf.a[iOut++] = 0x01; 10624 p->buf.a[iOut++] = (v & 0xFF); 10625 } 10626 }else if( p->format==VEC1_META_4BYTEINT ){ 10627 u32 v = vec1GetU32(&orig.a[iIn]); 10628 iIn += sizeof_u32; 10629 if( v==VEC1_META_4BYTENULL ){ 10630 p->buf.a[iOut++] = 0x00; 10631 bHasNull = 1; 10632 }else{ 10633 p->buf.a[iOut++] = 0x02; 10634 vec1PutU32(&p->buf.a[iOut], (u32)v); 10635 iOut += sizeof_u32; 10636 } 10637 }else{ 10638 u64 v = vec1GetU64(&orig.a[iIn]); 10639 iIn += sizeof_f64; 10640 if( v==VEC1_META_REALNULL ){ 10641 p->buf.a[iOut++] = 0x00; 10642 bHasNull = 1; 10643 }else{ 10644 p->buf.a[iOut++] = 0x04; 10645 vec1PutU64(&p->buf.a[iOut], v); 10646 iOut += sizeof_f64; 10647 } 10648 } 10649 } 10650 10651 p->buf.n = iOut; 10652 } 10653 10654 if( p->format==VEC1_META_1BYTEINT ){ 10655 p->flags = VEC1_META_4BYTEINT | VEC1_META_1BYTEINT | VEC1_META_REAL; 10656 }else if( p->format==VEC1_META_4BYTEINT ){ 10657 p->flags = VEC1_META_4BYTEINT | VEC1_META_REAL; 10658 }else{ 10659 p->flags = VEC1_META_REAL; 10660 } 10661 p->format = VEC1_META_GENERIC; 10662 if( bHasNull ){ 10663 p->flags |= VEC1_META_HASNULL; 10664 } 10665 10666 vec1BufferFree(&orig); 10667 return rc; 10668 } 10669 10670 static int vec1WriterMetaFromArray( 10671 Vec1Writer *pWriter, /* Writer object accumulating changes */ 10672 int iBucket, /* Bucket to write to */ 10673 sqlite3_value **apMeta /* Meta values associated with prev vector */ 10674 ){ 10675 Vec1ListBuilder *p = &pWriter->aBld[iBucket]; 10676 int ii; 10677 int rc = SQLITE_OK; 10678 assert( p->pTab!=0 ); 10679 for(ii=0; rc==SQLITE_OK && iipTab->nMeta; ii++){ 10680 Vec1MetaBuilder *pMeta = &p->aMeta[ii]; 10681 Vec1Buffer *pBuf = &pMeta->buf; 10682 sqlite3_value *pVal = apMeta[ii]; 10683 10684 if( pMeta->format==VEC1_META_1BYTEINT 10685 || pMeta->format==VEC1_META_4BYTEINT 10686 || pMeta->format==VEC1_META_REAL 10687 ){ 10688 int eType = sqlite3_value_type(pVal); 10689 10690 rc = vec1BufferGrow(pBuf, sizeof_f64); 10691 if( rc!=SQLITE_OK ) continue; 10692 10693 if( eType==SQLITE_INTEGER ){ 10694 i64 iVal = sqlite3_value_int64(pVal); 10695 10696 if( pMeta->format==VEC1_META_1BYTEINT ){ 10697 if( iVal>=0 && iVal<=254 ){ 10698 pBuf->a[pBuf->n++] = (iVal & 0xFF); 10699 pVal = 0; 10700 } 10701 }else{ 10702 if( iVal>=VEC1_META_4BYTEMIN && iVal<=VEC1_META_4BYTEMAX ){ 10703 if( pMeta->format==VEC1_META_4BYTEINT ){ 10704 vec1PutU32(&pBuf->a[pBuf->n], (u32)iVal); 10705 pBuf->n += sizeof_u32; 10706 }else{ 10707 double fVal = (double)iVal; 10708 u64 v; 10709 memcpy(&v, &fVal, sizeof_f64); 10710 vec1PutU64(&pBuf->a[pBuf->n], v); 10711 pBuf->n += sizeof_f64; 10712 } 10713 pVal = 0; 10714 } 10715 } 10716 }else if( eType==SQLITE_FLOAT && pMeta->format==VEC1_META_REAL ){ 10717 double fVal = sqlite3_value_double(pVal); 10718 u64 v; 10719 memcpy(&v, &fVal, sizeof_f64); 10720 vec1PutU64(&pBuf->a[pBuf->n], v); 10721 pBuf->n += sizeof_f64; 10722 pVal = 0; 10723 }else if( eType==SQLITE_NULL ){ 10724 rc = vec1BufferGrow(pBuf, sizeof_f64); 10725 if( pMeta->format==VEC1_META_1BYTEINT ){ 10726 pBuf->a[pBuf->n++] = (VEC1_META_1BYTENULL & 0xFF); 10727 } 10728 else if( pMeta->format==VEC1_META_4BYTEINT ){ 10729 vec1PutU32(&pBuf->a[pBuf->n], (u32)VEC1_META_4BYTENULL); 10730 pBuf->n += sizeof_u32; 10731 }else{ 10732 vec1PutU64(&pBuf->a[pBuf->n], (u64)VEC1_META_REALNULL); 10733 pBuf->n += sizeof_f64; 10734 } 10735 pVal = 0; 10736 } 10737 10738 if( pVal ){ 10739 rc = vec1ExpandMetaValue(pMeta); 10740 } 10741 } 10742 10743 if( pMeta->format==VEC1_META_GENERIC ){ 10744 int iOff = pBuf->n; 10745 rc = vec1AppendMetaValue(pBuf, pVal); 10746 if( rc==SQLITE_OK ){ 10747 vec1MetaValueUpdateFlags(&pBuf->a[iOff], &pMeta->flags); 10748 } 10749 } 10750 } 10751 return rc; 10752 } 10753 10754 static int vec1WriterMetaFromStmt( 10755 Vec1Writer *pWriter, /* Writer object accumulating changes */ 10756 int iBucket, /* Bucket to write to */ 10757 sqlite3_stmt *pStmt 10758 ){ 10759 Vec1ListBuilder *p = &pWriter->aBld[iBucket]; 10760 int ii; 10761 int rc = SQLITE_OK; 10762 assert( p->pTab!=0 ); 10763 for(ii=0; rc==SQLITE_OK && iipTab->nMeta; ii++){ 10764 Vec1Buffer *pBuf = &p->aMeta[ii].buf; 10765 sqlite3_value *pVal = sqlite3_column_value(pStmt, ii+2); 10766 int iOff = pBuf->n; 10767 rc = vec1AppendMetaValue(pBuf, pVal); 10768 if( rc==SQLITE_OK ){ 10769 vec1MetaValueUpdateFlags(&pBuf->a[iOff], &p->aMeta[ii].flags); 10770 } 10771 } 10772 return rc; 10773 } 10774 10775 /* 10776 ** Read nMeta values from buffer pBuf. Use them as the meta values associated 10777 ** with the (compressed) vector just appended to bucket iBucket. 10778 ** 10779 ** This is only called on a buffer that has been constructed in process, 10780 ** not one loaded from disk, so it is safe to assume that pBuf really does 10781 ** contain nMeta well-formed values. 10782 */ 10783 static int vec1WriterMetaFromPacked( 10784 Vec1Writer *pWriter, /* Writer object accumulating changes */ 10785 int iBucket, /* Bucket to write to */ 10786 Vec1Buffer *pBuf, 10787 int *piOff /* IN/OUT: Buffer offset */ 10788 ){ 10789 int ii; 10790 int iOff = *piOff; 10791 for(ii=0; iipTab->nMeta; ii++){ 10792 Vec1MetaBuilder *pTo = &pWriter->aBld[iBucket].aMeta[ii]; 10793 i64 n = vec1MetaValueSize(&pBuf->a[iOff]); 10794 int rc = vec1BufferGrow(&pTo->buf, n); 10795 vec1MetaValueUpdateFlags(&pBuf->a[iOff], &pTo->flags); 10796 if( rc!=SQLITE_OK ) return rc; 10797 memcpy(&pTo->buf.a[pTo->buf.n], &pBuf->a[iOff], n); 10798 pTo->buf.n += n; 10799 iOff += n; 10800 } 10801 *piOff = iOff; 10802 return SQLITE_OK; 10803 } 10804 10805 static int vec1PackMetaValues( 10806 Vec1Tab *pTab, 10807 Vec1Buffer *pBuf, 10808 sqlite3_stmt *pStmt 10809 ){ 10810 int ii; 10811 int rc = SQLITE_OK; 10812 for(ii=0; rc==SQLITE_OK && iinMeta; ii++){ 10813 rc = vec1AppendMetaValue(pBuf, sqlite3_column_value(pStmt, 2+ii)); 10814 } 10815 return rc; 10816 } 10817 10818 static int vec1WriterQuantized( 10819 Vec1Writer *pWriter, 10820 i64 iRowid, 10821 int iBucket, 10822 const u8 *aStore 10823 ){ 10824 return vec1ListBuilderAdd(&pWriter->aBld[iBucket], iRowid, aStore); 10825 } 10826 10827 static int vec1WriterFinish(Vec1Writer *p, int rcin){ 10828 int rc = rcin; 10829 if( p ){ 10830 int ii; 10831 for(ii=0; iinBld; ii++){ 10832 if( rc==SQLITE_OK ){ 10833 rc = vec1ListBuilderFlush(&p->aBld[ii]); 10834 } 10835 vec1ListBuilderFree(&p->aBld[ii]); 10836 } 10837 sqlite3_free(p); 10838 } 10839 return rc; 10840 } 10841 10842 static void vec1EncodeVectorN( 10843 const Vec1Model *pMod, 10844 const float *aVec[VEC1_MULTIMATCH_NVEC], 10845 u8 *aCode 10846 ){ 10847 if( pMod->hdr.flags & VEC1_MODEL_BITQUANT ){ 10848 int nCode = vec1EncodedVectorSize(pMod); 10849 int vv; 10850 for(vv=0; vvhdr.nCodebook; 10855 const int nCodeElem = pMod->nCodeElem; 10856 const float *aSub[VEC1_MULTIMATCH_NVEC]; 10857 int vv; 10858 int k; 10859 for(k=0; kaModel[k * nCodeElem * VEC1_PQ_CODEBOOK_SZ], 10868 &pMod->aModelNT[k * nCodeElem * VEC1_PQ_CODEBOOK_SZ], 10869 VEC1_PQ_CODEBOOK_SZ, aSub, aBest, 0 10870 ); 10871 10872 for(vv=0; vvhdr.nElem; 10888 int vv; 10889 10890 for(vv=0; vvhdr.flags & (VEC1_MODEL_ROTATE|VEC1_MODEL_WHT)) 10895 || pMod->hdr.eDistance==VEC1_DISTANCE_COS 10896 || nStride!=nElem 10897 ){ 10898 10899 float *aRot[VEC1_MULTIMATCH_NVEC]; 10900 for(vv=0; vvhdr.flags & VEC1_MODEL_ROTATE ){ 10905 #if defined(VEC1_USE_TRANSPOSITION) 10906 vec1RotateVectorTransposeN( 10907 aRot, aOut, nElem, pMod->aRotation, pMod->aRotationNT 10908 ); 10909 #else 10910 vec1RotateVectorN(aRot, aOut, nElem, pMod->aRotation); 10911 #endif 10912 }else{ 10913 for(vv=0; vvhdr.eDistance==VEC1_DISTANCE_COS ){ 10919 for(vv=0; vvhdr.flags & VEC1_MODEL_WHT ){ 10925 for(vv=0; vvhdr.nElem; 10946 const int nBucket = pMod->hdr.nBucket; 10947 const int nStride = MAX(nElem, pMod->nCodeElem * (int)pMod->hdr.nCodebook); 10948 const float *aVec[VEC1_MULTIMATCH_NVEC]; 10949 int vv; 10950 10951 vec1TransformInputVectorN(pMod, aVector, aVec, aTmp, nStride); 10952 10953 if( nBucket>0 ){ 10954 vec1BestMatchPlatformN( 10955 nElem, pMod->aCentroid, pMod->aCentroidNT, nBucket, aVec, aBucket, 0 10956 ); 10957 10958 if( pMod->hdr.nCodebook>0 && (pMod->hdr.flags & VEC1_MODEL_RESIDUAL) ){ 10959 for(vv=0; vvaCentroid[aBucket[vv]*nElem], nElem); 10962 aVec[vv] = tmp; 10963 } 10964 } 10965 10966 for(vv=0; vv=0 && aBucket[vv]hdr.nCodebook>0 ){ 10974 vec1EncodeVectorN(pMod, aVec, aCode); 10975 } 10976 } 10977 10978 /* 10979 ** Each Vec1QuantizeJob has capacity for this many vectors. 10980 */ 10981 #define VEC1_QUANTIZE_JOB_SZ 1024 10982 10983 typedef struct Vec1QuantizeJob Vec1QuantizeJob; 10984 struct Vec1QuantizeJob { 10985 Vec1Model *pModel; 10986 Vec1Writer *pWriter; 10987 int nVector; /* Number of vectors to quantize */ 10988 i64 *aRowid; /* Array of nVector rowids */ 10989 float *aTmp; /* Temp space for one vector */ 10990 float *aVec; /* Packed vectors */ 10991 int *aBucket; /* OUT: Bucket for each vector */ 10992 u8 *aCode; /* OUT: Packed codes for vectors */ 10993 int nEncoded; /* Size of each encoded vector in bytes */ 10994 Vec1Buffer meta; /* Packed array of meta values */ 10995 }; 10996 10997 static void vec1QuantizeJob(void *pCtx){ 10998 Vec1QuantizeJob *p = (Vec1QuantizeJob*)pCtx; 10999 const int nQuant = VEC1_MULTIMATCH_NVEC; 11000 const int nElem = p->pModel->hdr.nElem; 11001 int ii = 0; 11002 11003 /* Handle the bulk of the vectors VEC1_QUANTIZE_JOB_QUANTA at a time. */ 11004 for(; ii<=(p->nVector-nQuant); ii += nQuant){ 11005 float *v = &p->aVec[nElem * ii]; 11006 u8 *a = &p->aCode[p->nEncoded * ii]; 11007 vec1QuantizeVectorN(p->pModel, p->aTmp, v, &p->aBucket[ii], a); 11008 } 11009 11010 /* Scalar tail - handle remaining vectors one at a time. */ 11011 for(; iinVector; ii++){ 11012 float *v = &p->aVec[nElem * ii]; 11013 u8 *a = &p->aCode[p->nEncoded * ii]; 11014 vec1QuantizeVector(p->pModel, p->aTmp, v, &p->aBucket[ii], a); 11015 } 11016 } 11017 11018 static int vec1UpdateBase( 11019 Vec1Tab *pTab, 11020 i64 iId, 11021 int iBucket 11022 ){ 11023 sqlite3_stmt *pStmt = 0; 11024 int rc = vec1GetSql(pTab, VEC1_SQL_UPDATE_BASE2, &pStmt); 11025 if( rc==SQLITE_OK ){ 11026 sqlite3_bind_int(pStmt, 1, iBucket); 11027 sqlite3_bind_int64(pStmt, 2, iId); 11028 sqlite3_step(pStmt); 11029 vec1StmtReset(&rc, pStmt); 11030 } 11031 return rc; 11032 } 11033 11034 11035 static int vec1QuantizeJobFinish(void *pCtx, int rcin){ 11036 Vec1QuantizeJob *p = (Vec1QuantizeJob*)pCtx; 11037 const int nElem = p->pModel->hdr.nElem; 11038 int rc = rcin; 11039 int ii; 11040 int bBucketBase = vec1ModelIsFlat(p->pModel); 11041 int iOffMeta = 0; 11042 11043 assert( bBucketBase==0 || p->pModel->hdr.nCodebook==0 ); 11044 11045 for(ii=0; rc==SQLITE_OK && iinVector; ii++){ 11046 int iBucket = p->aBucket[ii]; 11047 const u8 *aStore; 11048 if( p->nEncoded>0 ){ 11049 aStore = &p->aCode[ii * p->nEncoded]; 11050 }else{ 11051 aStore = (const u8*)&p->aVec[ii * nElem]; 11052 } 11053 rc = vec1WriterQuantized(p->pWriter, p->aRowid[ii], iBucket, aStore); 11054 if( bBucketBase && rc==SQLITE_OK ){ 11055 rc = vec1UpdateBase(p->pWriter->pTab, p->aRowid[ii], iBucket); 11056 } 11057 if( rc==SQLITE_OK ){ 11058 rc = vec1WriterMetaFromPacked(p->pWriter, iBucket, &p->meta, &iOffMeta); 11059 } 11060 } 11061 11062 vec1BufferFree(&p->meta); 11063 sqlite3_free(p); 11064 return rc; 11065 } 11066 11067 static int vec1UpdateBaseRows( 11068 Vec1Tab *pTab, 11069 i64 iFirst, 11070 i64 iLast 11071 ){ 11072 sqlite3_stmt *pStmt = 0; 11073 int rc = vec1GetSql(pTab, VEC1_SQL_ZERO_BASE_RANGE, &pStmt); 11074 if( rc==SQLITE_OK ){ 11075 sqlite3_bind_int64(pStmt, 1, iFirst); 11076 sqlite3_bind_int64(pStmt, 2, iLast); 11077 sqlite3_step(pStmt); 11078 vec1StmtReset(&rc, pStmt); 11079 } 11080 return rc; 11081 } 11082 11083 11084 #define VEC1_ROWS_PER_BASE_UPDATE 64 11085 11086 /* 11087 ** Rebuild the entire ANN index from scratch, based on the current contents 11088 ** of the %_base table. 11089 */ 11090 static int vec1RebuildIndex(Vec1Tab *pTab, int nThread){ 11091 const int nElem = pTab->cfg.nElem; 11092 sqlite3_stmt *pStmt = 0; 11093 int rc = SQLITE_OK; 11094 int bZeroBase = 0; /* True to set base.vector=0 */ 11095 11096 Vec1Writer *p = 0; /* Write buffer object */ 11097 Vec1JobQueue *pQueue = 0; /* Job queue for multi-threaded rebuilds */ 11098 Vec1QuantizeJob *pQJ = 0; 11099 int nRow = 0; 11100 i64 iFirstInRange = VEC1_SMALLEST_INT64; 11101 11102 assert( pTab->cfg.nElem==(int)pTab->mod.hdr.nElem || pTab->mod.hdr.nElem==0 ); 11103 11104 /* Clear any existing ANN index */ 11105 rc = vec1SqlExec(pTab, "DELETE FROM %Q.'%q_idx'", 0); 11106 if( rc==SQLITE_OK ){ 11107 rc = vec1SqlExec(pTab, "DELETE FROM %Q.'%q_meta'", 0); 11108 } 11109 11110 if( rc!=SQLITE_OK || (pTab->mod.hdr.flags & VEC1_MODEL_INDEX)==0 ) return rc; 11111 11112 11113 /* Allocate a writer object. Create transposed centroids if required. */ 11114 rc = vec1WriterAlloc(pTab, 1, &p); 11115 if( rc==SQLITE_OK ){ 11116 rc = vec1ModelAllocTCent(&pTab->mod); 11117 } 11118 11119 /* If multiple threads have been configured and the model is not 'flat', 11120 ** create a job queue so that the rebuild can use multiple threads. There 11121 ** is nothing for background threads to do for 'flat' indexes. */ 11122 if( vec1ModelIsFlat(&pTab->mod) && pTab->mod.hdr.nBucket==0 ){ 11123 bZeroBase = 1; 11124 } 11125 #if VEC1_THREADS 11126 if( rc==SQLITE_OK && nThread>1 && bZeroBase==0 ){ 11127 pQueue = vec1JobQueueNew(nThread-1); 11128 if( pQueue==0 ){ 11129 rc = SQLITE_NOMEM; 11130 } 11131 } 11132 #endif /* VEC1_THREADS */ 11133 11134 if( rc==SQLITE_OK ){ 11135 rc = vec1GetSql(pTab, VEC1_SQL_SCAN_BASE, &pStmt); 11136 } 11137 11138 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 11139 i64 id = sqlite3_column_int64(pStmt, 0); 11140 int nVec = 0; 11141 const float *aVec = 0; 11142 11143 nRow++; 11144 if( bZeroBase && nRow==VEC1_ROWS_PER_BASE_UPDATE ){ 11145 rc = vec1UpdateBaseRows(pTab, iFirstInRange, id); 11146 if( rc!=SQLITE_OK ) break; 11147 iFirstInRange = id+1; 11148 nRow = 0; 11149 } 11150 11151 nVec = sqlite3_column_bytes(pStmt, 1); 11152 aVec = (const float*)sqlite3_column_blob(pStmt, 1); 11153 11154 if( nVec!=(sizeof_f32*nElem) ){ 11155 rc = SQLITE_ERROR; 11156 vec1VtabError( 11157 pTab, "vec1: unexpected vector size in %q_base: %d", pTab->zName, nVec 11158 ); 11159 }else{ 11160 if( bZeroBase ){ 11161 int iBucket = -1; /* Must be -1 for vec1WriterVector()! */ 11162 rc = vec1WriterVector(p, id, aVec, &iBucket); 11163 if( rc==SQLITE_OK ){ 11164 rc = vec1WriterMetaFromStmt(p, iBucket, pStmt); 11165 } 11166 }else{ 11167 if( pQJ==0 ){ 11168 int nEncoded = vec1EncodedVectorSize(&pTab->mod); 11169 int nByte = sizeof(Vec1QuantizeJob) + 11170 sizeof(i64) * VEC1_QUANTIZE_JOB_SZ + /* aRowid */ 11171 pTab->nTmpVec * sizeof_f32 * VEC1_MULTIMATCH_NVEC +/* aTmp */ 11172 nElem * sizeof_f32 * VEC1_QUANTIZE_JOB_SZ + /* aVec */ 11173 sizeof(int) * VEC1_QUANTIZE_JOB_SZ + /* aBucket */ 11174 nEncoded * VEC1_QUANTIZE_JOB_SZ; /* aCode */ 11175 11176 pQJ = (Vec1QuantizeJob*)sqlite3_malloc(nByte); 11177 if( pQJ==0 ){ 11178 rc = SQLITE_NOMEM; 11179 break; 11180 }else{ 11181 memset(pQJ, 0, sizeof(Vec1QuantizeJob)); 11182 pQJ->pModel = &pTab->mod; 11183 pQJ->pWriter = p; 11184 pQJ->aRowid = (i64*)&pQJ[1]; 11185 pQJ->aTmp = (float*)&pQJ->aRowid[VEC1_QUANTIZE_JOB_SZ]; 11186 pQJ->aVec = &pQJ->aTmp[pTab->nTmpVec * VEC1_MULTIMATCH_NVEC]; 11187 pQJ->aBucket = (int*)&pQJ->aVec[nElem * VEC1_QUANTIZE_JOB_SZ]; 11188 pQJ->aCode = (u8*)&pQJ->aBucket[VEC1_QUANTIZE_JOB_SZ]; 11189 pQJ->nEncoded = nEncoded; 11190 memset(pQJ->aTmp, 0, sizeof_f32*pTab->nTmpVec*VEC1_MULTIMATCH_NVEC); 11191 } 11192 } 11193 11194 memcpy(&pQJ->aVec[nElem * pQJ->nVector], aVec, nVec); 11195 pQJ->aRowid[pQJ->nVector] = id; 11196 pQJ->nVector++; 11197 rc = vec1PackMetaValues(pTab, &pQJ->meta, pStmt); 11198 11199 if( rc==SQLITE_OK && pQJ->nVector==VEC1_QUANTIZE_JOB_SZ ){ 11200 rc = vec1JobQueueAddJob( 11201 pQueue, vec1QuantizeJob, vec1QuantizeJobFinish, (void*)pQJ 11202 ); 11203 pQJ = 0; 11204 } 11205 } 11206 } 11207 } 11208 11209 if( rc==SQLITE_OK && bZeroBase ){ 11210 rc = vec1UpdateBaseRows(pTab, iFirstInRange, VEC1_LARGEST_INT64); 11211 } 11212 11213 if( pQJ ){ 11214 if( rc==SQLITE_OK ){ 11215 rc = vec1JobQueueAddJob( 11216 pQueue, vec1QuantizeJob, vec1QuantizeJobFinish, (void*)pQJ 11217 ); 11218 }else{ 11219 vec1BufferFree(&pQJ->meta); 11220 sqlite3_free(pQJ); 11221 } 11222 } 11223 rc = vec1JobQueueFinishJobs(pQueue, rc); 11224 vec1JobQueueFree(pQueue); 11225 11226 rc = vec1WriterFinish(p, rc); 11227 vec1StmtReset(&rc, pStmt); 11228 vec1ModelFreeTCent(&pTab->mod); 11229 return rc; 11230 } 11231 11232 /* 11233 ** The table currently has a flat index installed - an index with 11234 ** nCodesize==0 - and bucket numbers instead of vectors in the %_base 11235 ** table. This function scans the index, copying full vectors back into 11236 ** the %_base table and deleting %_idx entries as it goes. 11237 ** 11238 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. 11239 */ 11240 static int vec1FlatToNone(Vec1Tab *pTab){ 11241 int rc = SQLITE_OK; 11242 sqlite3_stmt *pStmt = 0; 11243 sqlite3_stmt *pUp = 0; 11244 sqlite3_stmt *pDel = 0; 11245 11246 rc = vec1GetSql(pTab, VEC1_SQL_SCAN_IDX, &pStmt); 11247 if( rc==SQLITE_OK ){ 11248 rc = vec1GetSql(pTab, VEC1_SQL_UPDATE_BASE, &pUp); 11249 } 11250 if( rc==SQLITE_OK ){ 11251 rc = vec1GetSql(pTab, VEC1_SQL_DELETE_FROM_IDX, &pDel); 11252 } 11253 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 11254 Vec1FlatIter iter; 11255 const u8 *aBlob = (const u8*)sqlite3_column_blob(pStmt, 0); 11256 int nBlob = sqlite3_column_bytes(pStmt, 0); 11257 i64 iRowid = sqlite3_column_int64(pStmt, 2); 11258 rc = vec1FlatIterStart(pTab, &iter, aBlob, nBlob); 11259 11260 while( rc==SQLITE_OK && iter.aVec!=0 ){ 11261 rc = sqlite3_bind_blob(pUp, 1, iter.aVec, iter.szVec, SQLITE_STATIC); 11262 sqlite3_bind_int64(pUp, 2, iter.iRowid); 11263 sqlite3_step(pUp); 11264 vec1StmtReset(&rc, pUp); 11265 vec1FlatIterNext(&iter); 11266 } 11267 11268 if( rc==SQLITE_OK ){ 11269 sqlite3_bind_int64(pDel, 1, iRowid); 11270 sqlite3_step(pDel); 11271 vec1StmtReset(&rc, pDel); 11272 } 11273 } 11274 if( pUp ) sqlite3_clear_bindings(pUp); 11275 vec1StmtReset(&rc, pStmt); 11276 11277 return rc; 11278 } 11279 11280 /* 11281 ** Symbols for the commands the vtab accepts. These must match the array 11282 ** in vec1InterpretCmdName(). 11283 */ 11284 #define VEC1_CMD_BLOCKSIZE 0 11285 #define VEC1_CMD_REBUILD 1 11286 #define VEC1_CMD_BLOCKSIZE_MIN 2 11287 11288 static int vec1InterpretCmdName(Vec1Tab *pTab, const char *zCmd, int *piCmd){ 11289 const char *azCmd[] = { 11290 "blocksize", 11291 "rebuild", 11292 "blocksize-min", 11293 0 11294 }; 11295 int iCmd; 11296 11297 for(iCmd=0; iCmd=iMin && iVal<=iMax ) return SQLITE_OK; 11318 } 11319 11320 vec1VtabError( 11321 pTab, "'%s' requires an integer value between %lld and %lld", 11322 zName, iMin, iMax 11323 ); 11324 return SQLITE_ERROR; 11325 } 11326 11327 static int vec1WriteConfigI64(Vec1Tab *pTab, int iField, i64 iVal){ 11328 sqlite3_stmt *pStmt = 0; 11329 int rc = SQLITE_OK; 11330 11331 rc = vec1GetSql(pTab, VEC1_SQL_WRITE_CONFIG, &pStmt); 11332 if( rc==SQLITE_OK ){ 11333 sqlite3_bind_int(pStmt, 1, iField); 11334 sqlite3_bind_int64(pStmt, 2, iVal); 11335 sqlite3_step(pStmt); 11336 rc = sqlite3_reset(pStmt); 11337 } 11338 11339 return rc; 11340 } 11341 11342 /* 11343 ** Fix the vector size to nVec *bytes*. This is done when the first 11344 ** vector is inserted into the table. Return SQLITE_OK if successful, or 11345 ** an SQLite error code if an error occurs. 11346 */ 11347 static int vec1FixVectorSize(Vec1Tab *pTab, int nVec){ 11348 int rc = SQLITE_OK; 11349 char *zErr = 0; 11350 11351 rc = vec1CheckVectorSize(nVec, &zErr); 11352 if( rc!=SQLITE_OK ){ 11353 vec1VtabError(pTab, "vec1: %s", zErr); 11354 sqlite3_free(zErr); 11355 }else{ 11356 int nElem = nVec/sizeof_f32; 11357 rc = vec1WriteConfigI64(pTab, VEC1_CONFIG_NELEM, nElem); 11358 if( rc==SQLITE_OK ) pTab->cfg.nElem = nElem; 11359 } 11360 11361 return rc; 11362 } 11363 11364 static int vec1FinishWriter(Vec1Tab *pTab, int bDiscard){ 11365 int rc = SQLITE_OK; 11366 Vec1Writer *pWriter = pTab->pWriter; 11367 pTab->pWriter = 0; 11368 if( bDiscard ){ 11369 vec1WriterFinish(pWriter, SQLITE_ERROR); 11370 }else{ 11371 rc = vec1WriterFinish(pWriter, SQLITE_OK); 11372 } 11373 return rc; 11374 } 11375 11376 /* 11377 ** There are three basic query plans supported by xBestIndex: 11378 ** 11379 ** 0: Full table scan. 11380 ** 1: Lookup by rowid. 11381 ** 2: K-nearest-neighbours search. 11382 */ 11383 static int vec1FilterMethod( 11384 sqlite3_vtab_cursor *cur, 11385 int idxNum, 11386 const char *idxStr, 11387 int argc, 11388 sqlite3_value **argv 11389 ){ 11390 Vec1Csr *pCsr = (Vec1Csr *)cur; 11391 Vec1Tab *pTab = (Vec1Tab*)(cur->pVtab); 11392 int rc = SQLITE_OK; 11393 11394 UNUSED_PARAMETER(argc); 11395 assert( ((idxNum==0 || idxNum==1) && argc==0) 11396 || ((idxNum==2 || idxNum==3) && argc==1) 11397 || (idxNum==5 && argc>=1) 11398 ); 11399 vec1ResetCsr(pCsr); 11400 11401 if( pCsr->bLoadConfig==0 && (idxNum & 0x01) ){ 11402 rc = vec1LoadConfig(pTab); 11403 if( rc!=SQLITE_OK ) return rc; 11404 pCsr->bLoadConfig = 1; 11405 } 11406 11407 if( idxNum==0 || idxNum==1 ){ 11408 /* Full-table scan. */ 11409 rc = vec1PrepareSql(pTab, &pCsr->pStmt, 11410 "SELECT * FROM %Q.'%q_base'", pTab->zDb, pTab->zName 11411 ); 11412 }else if( idxNum==2 || idxNum==3 ){ 11413 /* Lookup by rowid */ 11414 rc = vec1PrepareSql(pTab, &pCsr->pStmt, 11415 "SELECT * FROM %Q.'%q_base' WHERE rowid=?", 11416 pTab->zDb, pTab->zName 11417 ); 11418 if( rc==SQLITE_OK ){ 11419 sqlite3_bind_value(pCsr->pStmt, 1, argv[0]); 11420 } 11421 }else{ 11422 /* ANN query */ 11423 Vec1Query *pQuery = 0; 11424 11425 assert( idxNum==5 ); 11426 11427 rc = vec1FinishWriter(pTab, 0); 11428 11429 VEC1_QINSTR_START(pTab, VEC1_QINSTR_TOTAL); 11430 11431 /* Parse the query parameters. */ 11432 if( rc==SQLITE_OK ){ 11433 rc = vec1SetupKANNQuery(pTab, idxStr, argv, &pQuery); 11434 pCsr->pQuery = pQuery; 11435 } 11436 11437 if( rc==SQLITE_OK ){ 11438 if( (pTab->mod.hdr.flags & VEC1_MODEL_INDEX)==0 ){ 11439 rc = vec1QueryToSql(pCsr); 11440 assert( pCsr->pQuery==0 ); 11441 assert( pCsr->bSqlNNQuery ); 11442 }else{ 11443 rc = vec1PrepareSql(pTab, &pCsr->pStmt, 11444 "SELECT * FROM %Q.'%q_base' WHERE id=?", 11445 pTab->zDb, pTab->zName 11446 ); 11447 if( rc==SQLITE_OK ){ 11448 rc = vec1DoKANNQuery(pCsr); 11449 pCsr->iCurrentRes = -1; 11450 } 11451 } 11452 } 11453 11454 VEC1_QINSTR_STOP(pTab, VEC1_QINSTR_TOTAL); 11455 } 11456 11457 if( rc==SQLITE_OK ){ 11458 rc = vec1NextMethod(cur); 11459 } 11460 return rc; 11461 } 11462 11463 11464 /* 11465 ** Handle a "special" INSERT command on a vec1 table. A special INSERT takes 11466 ** the form: 11467 ** 11468 ** INSERT INTO vec1_table(cmd, vector) VALUES('cmd-name', pArg); 11469 ** 11470 ** The zCmd argument to this function is the text value specified for column 11471 ** "cmd" in the INSERT statement. Parameter pArg is the pArg value from the 11472 ** INSERT. 11473 ** 11474 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If 11475 ** an error code is returned, an error message may be left in pTab. 11476 */ 11477 static int vec1SpecialInsert( 11478 Vec1Tab *pTab, 11479 const char *zCmd, 11480 sqlite3_value *pArg 11481 ){ 11482 int rc = SQLITE_OK; 11483 int iCmd = 0; 11484 11485 rc = vec1InterpretCmdName(pTab, zCmd, &iCmd); 11486 if( rc==SQLITE_OK ){ 11487 rc = vec1FinishWriter(pTab, 0); 11488 } 11489 11490 if( rc==SQLITE_OK ){ 11491 switch( iCmd ){ 11492 case VEC1_CMD_BLOCKSIZE: { 11493 rc = vec1InterpretInteger( 11494 pTab, pArg, "blocksize", VEC1_BLOCKSIZE_MIN, VEC1_BLOCKSIZE_MAX 11495 ); 11496 if( rc==SQLITE_OK ){ 11497 rc = vec1WriteConfigI64( 11498 pTab, VEC1_CONFIG_BLOCKSIZE, sqlite3_value_int64(pArg) 11499 ); 11500 } 11501 break; 11502 }; 11503 case VEC1_CMD_BLOCKSIZE_MIN: { 11504 rc = vec1InterpretInteger( 11505 pTab, pArg, "blocksize-min", VEC1_BLOCKSIZE_MIN, VEC1_BLOCKSIZE_MAX 11506 ); 11507 if( rc==SQLITE_OK ){ 11508 rc = vec1WriteConfigI64( 11509 pTab, VEC1_CONFIG_BLOCKSIZE_MIN, sqlite3_value_int64(pArg) 11510 ); 11511 } 11512 break; 11513 } 11514 11515 default: assert( iCmd==VEC1_CMD_REBUILD ); { 11516 11517 /* TODO: Should this be disallowed if there are active readers? */ 11518 if( rc==SQLITE_OK && sqlite3_value_type(pArg)!=SQLITE_NULL ){ 11519 u8 aFlat[VEC1_HEADER_SIZE]; 11520 Vec1Model mod; 11521 int nByte = 0; 11522 const u8 *aBlob = 0; 11523 sqlite3_stmt *pStmt = 0; 11524 11525 memset(&mod, 0, sizeof(mod)); 11526 if( sqlite3_value_type(pArg)==SQLITE_BLOB ){ 11527 nByte = sqlite3_value_bytes(pArg); 11528 aBlob = sqlite3_value_blob(pArg); 11529 }else{ 11530 Vec1FlatIndex idx = {0, 0}; 11531 const char *zText = (const char*)sqlite3_value_text(pArg); 11532 char *zErr = 0; 11533 11534 idx.eIndex = 0; 11535 idx.eDistance = VEC1_DISTANCE_L2; 11536 rc = vec1ParseJsonConfig( 11537 pTab->db, zText, vec1FlatIndexCfg, &idx, &zErr 11538 ); 11539 if( rc==SQLITE_OK && idx.eIndex==0 ){ 11540 zErr = sqlite3_mprintf("required parameter missing: index"); 11541 rc = SQLITE_ERROR; 11542 } 11543 if( zErr!=0 ){ 11544 vec1VtabError(pTab, "vec1: %z", zErr); 11545 } 11546 if( rc==SQLITE_OK ){ 11547 vec1HeaderWrite(aFlat, 11548 ((idx.eIndex==VEC1_INDEX_FLAT) ? VEC1_MODEL_INDEX : 0), 11549 0, 0, 0, idx.eDistance 11550 ); 11551 aBlob = aFlat; 11552 nByte = VEC1_HEADER_SIZE; 11553 } 11554 } 11555 11556 /* Decode the model blob here. Just to check if doing so causes any 11557 ** errors. If it does, refuse to store it. */ 11558 if( rc==SQLITE_OK ){ 11559 rc = vec1DecodeModel(aBlob, nByte, &mod, &pTab->base.zErrMsg); 11560 } 11561 11562 if( rc==SQLITE_OK && mod.hdr.nElem>0 ){ 11563 if( pTab->cfg.nElem==0 ){ 11564 rc = vec1FixVectorSize(pTab, mod.hdr.nElem*sizeof_f32); 11565 }else if( pTab->cfg.nElem!=(int)mod.hdr.nElem ){ 11566 vec1VtabError(pTab, 11567 "vec1: model/data vector size mismatch: %d/%d", 11568 (int)mod.hdr.nElem, pTab->cfg.nElem 11569 ); 11570 rc = SQLITE_ERROR; 11571 } 11572 } 11573 11574 /* Store the new model in the %_model table. */ 11575 if( rc==SQLITE_OK ){ 11576 const char zStore[] = "REPLACE INTO %Q.'%q_model' VALUES(1, ?)"; 11577 rc = vec1PrepareSql(pTab, &pStmt, zStore, pTab->zDb, pTab->zName); 11578 } 11579 if( rc==SQLITE_OK ){ 11580 rc = sqlite3_bind_blob(pStmt, 1, aBlob, nByte, SQLITE_STATIC); 11581 sqlite3_step(pStmt); 11582 vec1StmtFinalize(&rc, pStmt); 11583 } 11584 11585 /* Increment (or create) the model version number in %_config */ 11586 if( rc==SQLITE_OK ){ 11587 rc = vec1GetSql(pTab, VEC1_SQL_INCR_CONFIG, &pStmt); 11588 } 11589 if( rc==SQLITE_OK ){ 11590 sqlite3_bind_int(pStmt, 1, VEC1_CONFIG_MODEL); 11591 sqlite3_step(pStmt); 11592 rc = sqlite3_reset(pStmt); 11593 } 11594 } 11595 11596 if( rc==SQLITE_OK && vec1ModelIsFlat(&pTab->mod) ){ 11597 rc = vec1FlatToNone(pTab); 11598 } 11599 if( rc==SQLITE_OK ){ 11600 rc = vec1LoadConfig(pTab); 11601 } 11602 if( rc==SQLITE_OK ){ 11603 rc = vec1RebuildIndex(pTab, pTab->pTabList->nThread); 11604 } 11605 } 11606 } 11607 } 11608 11609 return rc; 11610 } 11611 11612 /* 11613 ** The maximum permitted number of tombstone entries in list containing 11614 ** nEntry entries. If this threshold is exceeded, the list is reorganized 11615 ** to reduce the number of tombstones to 0. 11616 */ 11617 #define VEC1_TOMBSTONE_THRESHOLD(nEntry) ((nEntry * 2) / 10) 11618 11619 /* 11620 ** Locate the index entry for row iRowid, for writing. Array aVec[] is the 11621 ** row's transformed vector. 11622 ** 11623 ** The bucket selected for aVec[] by vec1BestMatchSimple() is searched 11624 ** first. If the model has no buckets, this is bucket 0 and it is the only 11625 ** bucket searched. Otherwise, if the row is not found there, it may have 11626 ** been assigned to a different bucket by code that rounds differently - 11627 ** either a different routine, such as the batched routines used by 11628 ** 'rebuild', or the same routine on a different platform. In that case 11629 ** all other buckets that are near-ties with the selected bucket (see 11630 ** vec1BucketIsNearTie()) are searched, followed by all remaining buckets. 11631 ** 11632 ** If the row is found, (*pLoc) is populated and (*piBucket) is set to 11633 ** the bucket it was found in. If it is not found, (*pLoc) is zeroed and 11634 ** SQLITE_OK returned. The caller must then treat the row as missing. 11635 */ 11636 static int vec1DeleteFindRowid( 11637 Vec1Tab *pTab, /* Table to search */ 11638 const float *aVec, /* Transformed vector */ 11639 i64 iRowid, /* Rowid to locate */ 11640 int *piBucket, /* OUT: Bucket containing iRowid */ 11641 Vec1RowidLocation *pLoc /* OUT: Location of iRowid */ 11642 ){ 11643 const Vec1Model *pMod = &pTab->mod; 11644 const int nElem = (int)pMod->hdr.nElem; 11645 const int nBucket = (int)pMod->hdr.nBucket; 11646 int iBest = 0; 11647 double fBest = 0.0; 11648 int rc = SQLITE_OK; 11649 11650 int iPass; 11651 11652 if( nBucket>0 ){ 11653 iBest = vec1BestMatchSimple(pMod->aCentroid, nBucket, aVec, nElem, &fBest); 11654 } 11655 rc = vec1FindByRowid(pTab, iBest, 1, iRowid, pLoc); 11656 if( rc!=SQLITE_OK || pLoc->pList || pLoc->pBlob ){ 11657 *piBucket = iBest; 11658 return rc; 11659 } 11660 11661 /* Pass 0 searches buckets that are near-ties with iBest. Pass 1 searches 11662 ** all others. */ 11663 for(iPass=0; iPass<2; iPass++){ 11664 int ii; 11665 for(ii=0; iiaCentroid[ii*nElem], nElem); 11669 if( vec1BucketIsNearTie(fBest, fDist)==(iPass==0) ){ 11670 rc = vec1FindByRowid(pTab, ii, 1, iRowid, pLoc); 11671 if( rc!=SQLITE_OK || pLoc->pList || pLoc->pBlob ){ 11672 *piBucket = ii; 11673 return rc; 11674 } 11675 } 11676 } 11677 } 11678 } 11679 11680 return SQLITE_OK; 11681 } 11682 11683 /* 11684 ** Delete the %_base entry for the row with rowid=iRowid. Also zero-out 11685 ** the corresponding %_idx entry. 11686 */ 11687 static int vec1DeleteByRowid(Vec1Tab *pTab, i64 iRowid){ 11688 const u8 aTomb4[4] = {0xFF, 0xFF, 0xFF, 0xFF}; 11689 const u8 aTomb8[8] = {0, 0, 0, 0, 0, 0, 0, 0}; 11690 11691 sqlite3_stmt *pDelete = 0; 11692 int rc = SQLITE_OK; 11693 11694 rc = vec1GetSql(pTab, VEC1_SQL_DEL_LOOKUP_BASE, &pDelete); 11695 if( rc==SQLITE_OK ){ 11696 11697 /* Delete the row from the %_base table. Also set variable iBucket to 11698 ** the index of the bucket containing the vector. Statement pDelete is 11699 ** not reset until the end of this function, as aTransform[] may point 11700 ** to the vector it returns. */ 11701 sqlite3_bind_int64(pDelete, 1, iRowid); 11702 if( (SQLITE_ROW==sqlite3_step(pDelete)) 11703 && (pTab->mod.hdr.flags & VEC1_MODEL_INDEX) 11704 ){ 11705 int iBucket = 0; 11706 Vec1RowidLocation loc; 11707 11708 if( pTab->mod.hdr.nCodebook==0 ){ 11709 iBucket = sqlite3_column_int(pDelete, 0); 11710 rc = vec1FindByRowid(pTab, iBucket, 1, iRowid, &loc); 11711 }else{ 11712 const u8 *aVec = sqlite3_column_blob(pDelete, 0); 11713 int nVec = sqlite3_column_bytes(pDelete, 0); 11714 11715 if( nVec!=(pTab->cfg.nElem*sizeof_f32) ){ 11716 rc = VEC1_CORRUPT; 11717 }else{ 11718 const float *aTransform = vec1TransformInputVector( 11719 &pTab->mod, pTab->aTmpVec, (const float*)aVec 11720 ); 11721 rc = vec1DeleteFindRowid(pTab, aTransform, iRowid, &iBucket, &loc); 11722 } 11723 } 11724 11725 if( rc==SQLITE_OK ){ 11726 if( loc.pList==0 && loc.pBlob==0 ){ 11727 /* Missing row. This is an error. */ 11728 rc = VEC1_CORRUPT; 11729 }else if( (loc.nTombstone+1) > VEC1_TOMBSTONE_THRESHOLD(loc.nEntry) ){ 11730 /* This delete would cause the list's tombstone count to exceed 11731 ** the threshold. So reorganize the list and remove iRowid in 11732 ** one go. */ 11733 if( loc.pList ){ 11734 rc = vec1ListBuilderCompress(loc.pList, iRowid); 11735 }else{ 11736 /* Load the list into memory, compress it so there are no 11737 ** tombstones, then write it back to the database. */ 11738 Vec1ListBuilder list; 11739 int nVal = sqlite3_blob_bytes(loc.pBlob); 11740 u8 *aVal = sqlite3_malloc(nVal); 11741 memset(&list, 0, sizeof(list)); 11742 if( aVal==0 ){ 11743 rc = SQLITE_NOMEM; 11744 }else{ 11745 rc = sqlite3_blob_read(loc.pBlob, aVal, nVal, 0); 11746 } 11747 if( rc==SQLITE_OK ){ 11748 rc = vec1ListBuilderInit(&list, pTab, iBucket); 11749 } 11750 if( rc==SQLITE_OK ){ 11751 /* Initialize iFirst and iLast to 0. vec1ListBuilderCompress() 11752 ** will set the correct values. */ 11753 rc = vec1ListBuilderLoad(&list, loc.iIdx, 0, 0, aVal, nVal); 11754 } 11755 if( rc==SQLITE_OK ){ 11756 rc = vec1ListBuilderCompress(&list, iRowid); 11757 } 11758 if( rc==SQLITE_OK ){ 11759 rc = vec1ListBuilderFlush(&list); 11760 } 11761 vec1ListBuilderFree(&list); 11762 sqlite3_free(aVal); 11763 } 11764 }else{ 11765 /* Replace the rowid with a tombstone and increment the tombstone 11766 ** count. */ 11767 const u8 *aTomb = loc.szRowid==4 ? aTomb4 : aTomb8; 11768 if( loc.pList ){ 11769 int iOff = loc.iEntry * loc.szRowid; 11770 memcpy(&loc.pList->bufRowid.a[iOff], aTomb, loc.szRowid); 11771 loc.pList->nTombstone++; 11772 }else{ 11773 int iOff = VEC1_LIST_SZHDR + (loc.iEntry * loc.szRowid); 11774 rc = sqlite3_blob_write(loc.pBlob, aTomb, loc.szRowid, iOff); 11775 if( rc==SQLITE_OK ){ 11776 u8 aTS[4]; 11777 vec1PutU32(aTS, loc.nTombstone+1); 11778 rc = sqlite3_blob_write(loc.pBlob, aTS, sizeof(aTS), 8); 11779 } 11780 } 11781 } 11782 11783 if( loc.pBlob ){ 11784 int rc2 = sqlite3_blob_close(loc.pBlob); 11785 if( rc==SQLITE_OK ) rc = rc2; 11786 } 11787 } 11788 } 11789 11790 vec1StmtReset(&rc, pDelete); 11791 } 11792 11793 return rc; 11794 } 11795 11796 /* 11797 ** xUpdate 11798 ** 11799 ** argc/argv meanings: 11800 ** argc==1 DELETE 11801 ** argc>1 && argv[0]==NULL INSERT 11802 ** argc>1 && argv[0]!=NULL UPDATE 11803 ** 11804 ** argv[0] = old rowid (or NULL) 11805 ** argv[1] = new rowid (or NULL to auto-assign) 11806 ** argv[2+] = column values 11807 */ 11808 static int vec1UpdateMethod( 11809 sqlite3_vtab *pVtab, 11810 int argc, 11811 sqlite3_value **argv, 11812 sqlite3_int64 *pRowid 11813 ){ 11814 int rc = SQLITE_OK; 11815 Vec1Tab *pTab = (Vec1Tab*)pVtab; 11816 const int iCmd = 2 + VEC1_COLUMN_CMD; 11817 int bDeleteRow = (argc==1); /* Delete row at end of this function */ 11818 11819 /* Ensure the configuration has been loaded. */ 11820 if( (rc = vec1LoadConfigIfRequired(pTab))!=SQLITE_OK ) return rc; 11821 11822 if( argc>1 ){ 11823 int nVec = sqlite3_value_bytes(argv[2+VEC1_COLUMN_VECTOR]); 11824 const void *aVec = sqlite3_value_blob(argv[2+VEC1_COLUMN_VECTOR]); 11825 int eType = sqlite3_value_type(argv[2+VEC1_COLUMN_VECTOR]); 11826 11827 /* Check for a special INSERT. Handle these separately. */ 11828 if( sqlite3_value_type(argv[iCmd])!=SQLITE_NULL ){ 11829 const char *zCmd = (char*)sqlite3_value_text(argv[iCmd]); 11830 sqlite3_value *pVal = argv[2+VEC1_COLUMN_ARG]; 11831 if( sqlite3_value_type(pVal)==SQLITE_NULL ){ 11832 pVal = argv[2+VEC1_COLUMN_VECTOR]; 11833 } 11834 return vec1SpecialInsert(pTab, zCmd, pVal); 11835 } 11836 11837 /* Check that the supplied vector is the right type and size. If this 11838 ** is the first vector written to this table, fix the vector size 11839 ** now. */ 11840 if( eType!=SQLITE_BLOB ){ 11841 rc = vec1VectorTypeError(pTab, eType); 11842 }else if( pTab->cfg.nElem>0 ){ 11843 if( nVec!=pTab->cfg.nElem*sizeof_f32 ){ 11844 rc = vec1VectorSizeError(pTab, nVec); 11845 } 11846 }else{ 11847 rc = vec1FixVectorSize(pTab, nVec); 11848 } 11849 11850 /* Check that the new vector does not contain any NaN or Infinity values */ 11851 if( rc==SQLITE_OK ){ 11852 rc = vec1VectorIsNonFinite((float*)aVec, pTab->cfg.nElem); 11853 if( rc!=SQLITE_OK ){ 11854 vec1VtabError(pTab, "vec1: non-finite value not allowed in vector"); 11855 } 11856 } 11857 11858 /* If this is an UPDATE that does not modify the rowid, then delete 11859 ** the existing row now. Or, if it is an UPDATE that does modify 11860 ** the rowid, schedule deletion of the existing row at the end 11861 ** of this function. */ 11862 if( rc==SQLITE_OK && sqlite3_value_type(argv[0])==SQLITE_INTEGER ){ 11863 if( sqlite3_value_int64(argv[0])==sqlite3_value_int64(argv[1]) ){ 11864 rc = vec1DeleteByRowid(pTab, sqlite3_value_int64(argv[0])); 11865 }else{ 11866 bDeleteRow = 1; 11867 } 11868 } 11869 11870 /* If this is an INSERT or UPDATE, write the new row. */ 11871 if( rc==SQLITE_OK ){ 11872 int iBucket = 0; 11873 11874 /* If there is an index (i.e. not index:"none"), then allocate an 11875 ** index writer. */ 11876 if( rc==SQLITE_OK 11877 && (pTab->mod.hdr.flags & VEC1_MODEL_INDEX) 11878 && pTab->pWriter==0 11879 ){ 11880 rc = vec1WriterAlloc(pTab, 0, &pTab->pWriter); 11881 assert( rc!=SQLITE_OK || pTab->pWriter!=0 ); 11882 } 11883 11884 /* Write to the %_base table. */ 11885 if( rc==SQLITE_OK ){ 11886 sqlite3_stmt *pInsert = 0; 11887 11888 /* If required, quantize the vector. This is because in 11889 ** some configurations, the bucket is written into the %_base 11890 ** table, so it must be determined now, before the base table entry 11891 ** is written */ 11892 if( pTab->pWriter ){ 11893 Vec1Writer *p = pTab->pWriter; 11894 vec1QuantizeVector(&pTab->mod, p->aResidual, aVec, &iBucket, p->aPQ); 11895 } 11896 11897 *pRowid = 0; 11898 rc = vec1GetSql(pTab, VEC1_SQL_INSERT_BASE, &pInsert); 11899 if( rc==SQLITE_OK ){ 11900 int ii; 11901 sqlite3_bind_value(pInsert, 1, argv[1]); 11902 if( vec1ModelIsFlat(&pTab->mod) ){ 11903 sqlite3_bind_int(pInsert, 2, iBucket); 11904 }else{ 11905 sqlite3_bind_blob(pInsert, 2, aVec, nVec, SQLITE_STATIC); 11906 } 11907 for(ii=0; iinMeta; ii++){ 11908 sqlite3_bind_value(pInsert, 3+ii, argv[2+VEC1_COLUMN_VECTOR+1+ii]); 11909 } 11910 11911 sqlite3_step(pInsert); 11912 rc = sqlite3_reset(pInsert); 11913 *pRowid = sqlite3_last_insert_rowid(pTab->db); 11914 } 11915 } 11916 11917 /* If the table has been trained, write the %_idx entry. And, if 11918 ** there are any meta-data columns, the %_meta entries as well. */ 11919 if( pTab->mod.hdr.flags & VEC1_MODEL_INDEX ){ 11920 if( rc==SQLITE_OK ){ 11921 rc = vec1WriterVector(pTab->pWriter, *pRowid, aVec, &iBucket); 11922 } 11923 if( rc==SQLITE_OK ){ 11924 sqlite3_value **aMeta = &argv[2+VEC1_COLUMN_VECTOR+1]; 11925 rc = vec1WriterMetaFromArray(pTab->pWriter, iBucket, aMeta); 11926 } 11927 } 11928 } 11929 } 11930 11931 if( rc==SQLITE_OK && bDeleteRow ){ 11932 rc = vec1DeleteByRowid(pTab, sqlite3_value_int64(argv[0])); 11933 } 11934 11935 return rc; 11936 } 11937 11938 static int vec1SyncMethod(sqlite3_vtab *pVtab){ 11939 int rc = SQLITE_OK; 11940 Vec1Tab *pTab = (Vec1Tab*)pVtab; 11941 if( (rc = vec1LoadConfigIfRequired(pTab))!=SQLITE_OK ) return rc; 11942 return vec1FinishWriter(pTab, 0); 11943 } 11944 11945 static int vec1BeginMethod(sqlite3_vtab *pVtab){ 11946 Vec1Tab *pTab = (Vec1Tab*)pVtab; 11947 int rc = SQLITE_OK; 11948 rc = vec1LoadConfig(pTab); 11949 return rc; 11950 } 11951 11952 /* 11953 ** xRename method for vec1 virtual table. This renames all shadow tables 11954 ** and the %_idx_idx index on the %_idx table. 11955 */ 11956 static int vec1RenameMethod(sqlite3_vtab *pVtab, const char *zNew){ 11957 const char zFmt[] = 11958 "ALTER TABLE %Q.'%q_config' RENAME TO '%q_config';" 11959 "ALTER TABLE %Q.'%q_base' RENAME TO '%q_base';" 11960 "ALTER TABLE %Q.'%q_idx' RENAME TO '%q_idx';" 11961 "ALTER TABLE %Q.'%q_model' RENAME TO '%q_model';" 11962 "ALTER TABLE %Q.'%q_meta' RENAME TO '%q_meta';" 11963 "UPDATE %Q.sqlite_schema SET name = '%q_idx_idx', sql=" 11964 " 'CREATE INDEX ' || quote('%q_idx_idx') || " 11965 " ' ON ' || quote('%q_idx') || '(bucket, first, last)'" 11966 "WHERE type='index' AND name='%q_idx_idx';" 11967 ; 11968 11969 Vec1Tab *pTab = (Vec1Tab*)pVtab;/* Virtual table object */ 11970 int rc = SQLITE_OK; /* Return value */ 11971 int bDefensive = 0; /* Initial value of DEFENSIVE */ 11972 int bWritable = 0; /* Initial value of WRITABLE_SCHEMA */ 11973 char *zSql = 0; /* SQL script to rename shadow objects */ 11974 11975 /* Query the initial values of the DEFENSIVE and WRITABLE_SCHEMA db-config 11976 ** options. Then clear DEFENSIVE and set WRITABLE_SCHEMA so that we can 11977 ** UPDATE the sqlite_schema entry of the index directly. */ 11978 sqlite3_db_config(pTab->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefensive); 11979 sqlite3_db_config(pTab->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &bWritable); 11980 sqlite3_db_config(pTab->db, SQLITE_DBCONFIG_DEFENSIVE, 0, (int*)0); 11981 sqlite3_db_config(pTab->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, (int*)0); 11982 11983 /* Run the SQL script to rename the shadow tables and index */ 11984 zSql = sqlite3_mprintf(zFmt, 11985 pTab->zDb, pTab->zName, zNew, /* %_config */ 11986 pTab->zDb, pTab->zName, zNew, /* %_base */ 11987 pTab->zDb, pTab->zName, zNew, /* %_idx */ 11988 pTab->zDb, pTab->zName, zNew, /* %_model */ 11989 pTab->zDb, pTab->zName, zNew, /* %_meta */ 11990 pTab->zDb, zNew, zNew, zNew, pTab->zName 11991 ); 11992 if( zSql==0 ){ 11993 rc = SQLITE_NOMEM; 11994 }else{ 11995 rc = sqlite3_exec(pTab->db, zSql, 0, 0, &pTab->base.zErrMsg); 11996 sqlite3_free(zSql); 11997 } 11998 11999 /* Restore the values of DEFENSIVE and WRITABLE_SCHEMA */ 12000 sqlite3_db_config(pTab->db,SQLITE_DBCONFIG_DEFENSIVE, bDefensive, (int*)0); 12001 sqlite3_db_config(pTab->db,SQLITE_DBCONFIG_WRITABLE_SCHEMA,bWritable,(int*)0); 12002 12003 return rc; 12004 } 12005 12006 static int vec1RollbackMethod(sqlite3_vtab *pVtab){ 12007 Vec1Tab *pTab = (Vec1Tab*)pVtab; 12008 vec1UnloadModel(pTab); 12009 return vec1FinishWriter(pTab, 1); 12010 } 12011 static int vec1SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ 12012 Vec1Tab *pTab = (Vec1Tab*)pVtab; 12013 int rc = SQLITE_OK; 12014 UNUSED_PARAMETER(iSavepoint); 12015 if( (rc = vec1LoadConfigIfRequired(pTab))!=SQLITE_OK ) return rc; 12016 return vec1FinishWriter(pTab, 0); 12017 } 12018 static int vec1ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ 12019 Vec1Tab *pTab = (Vec1Tab*)pVtab; 12020 int rc = SQLITE_OK; 12021 UNUSED_PARAMETER(iSavepoint); 12022 if( (rc = vec1LoadConfigIfRequired(pTab))!=SQLITE_OK ) return rc; 12023 return vec1FinishWriter(pTab, 0); 12024 } 12025 static int vec1RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ 12026 Vec1Tab *pTab = (Vec1Tab*)pVtab; 12027 UNUSED_PARAMETER(iSavepoint); 12028 12029 /* Discard any cached writes */ 12030 vec1FinishWriter(pTab, 1); 12031 12032 /* Drop the in-memory cache of both the config and the model. The 12033 ** database ROLLBACK TO operation may have modified them on disk. */ 12034 vec1UnloadConfig(pTab); 12035 vec1UnloadModel(pTab); 12036 return SQLITE_OK; 12037 } 12038 12039 /* 12040 ** This function is used by the integrity-check code to handle meta-data. 12041 ** Argument pBuf contains a meta-data record, complete with VEC1_META_SZHDR 12042 ** byte header. When this function is called, (*piOff) contains the offset 12043 ** into this buffer of the next meta-data value to read. 12044 ** 12045 ** When called, this function reads one meta-data value from (*piOff) and 12046 ** advances (*piOff) to point to the next value. If pVal is NULL, it returns 12047 ** SQLITE_OK at that point. Or, if pVal is not NULL, it is compared to 12048 ** the value just read. If they match, SQLITE_OK is returned. Otherwise, 12049 ** SQLITE_ERROR. 12050 */ 12051 static int vec1IntegrityMetaValue( 12052 Vec1Buffer *pBuf, 12053 int *piOff, 12054 sqlite3_value *pVal 12055 ){ 12056 u32 f = vec1GetU32(pBuf->a); 12057 int iOff = *piOff; 12058 Vec1MetaValue val; 12059 int rc = SQLITE_OK; 12060 12061 memset(&val, 0, sizeof(val)); 12062 if( (f & VEC1_META_1BYTEINT) ){ 12063 val.iVal = pBuf->a[iOff++]; 12064 if( val.iVal==VEC1_META_1BYTENULL ){ 12065 val.eType = SQLITE_NULL; 12066 }else{ 12067 val.eType = SQLITE_INTEGER; 12068 } 12069 }else if( (f & VEC1_META_4BYTEINT) ){ 12070 val.iVal = (int)vec1GetU32(&pBuf->a[iOff]); 12071 iOff += sizeof_u32; 12072 if( (u32)val.iVal==VEC1_META_4BYTENULL ){ 12073 val.eType = SQLITE_NULL; 12074 }else{ 12075 val.eType = SQLITE_INTEGER; 12076 } 12077 }else if( (f & VEC1_META_REAL) ){ 12078 u64 v = vec1GetU64(&pBuf->a[iOff]); 12079 iOff += sizeof_f64; 12080 if( v==VEC1_META_REALNULL ){ 12081 val.eType = SQLITE_NULL; 12082 }else{ 12083 val.eType = SQLITE_FLOAT; 12084 memcpy(&val.fVal, &v, sizeof_f64); 12085 } 12086 }else{ 12087 vec1MetaValueRead(pBuf, &iOff, &val); 12088 } 12089 12090 if( rc==SQLITE_OK && pVal ){ 12091 int eType = sqlite3_value_type(pVal); 12092 int bMatch = 0; 12093 switch( eType ){ 12094 12095 case SQLITE_NULL: 12096 bMatch = (val.eType==SQLITE_NULL); 12097 break; 12098 12099 case SQLITE_INTEGER: { 12100 i64 iVal = sqlite3_value_int64(pVal); 12101 bMatch = ( 12102 (val.eType==SQLITE_INTEGER && val.iVal==iVal) 12103 || (val.eType==SQLITE_FLOAT && val.fVal==(double)iVal) 12104 ); 12105 break; 12106 } 12107 12108 case SQLITE_FLOAT: { 12109 double fVal = sqlite3_value_double(pVal); 12110 bMatch = (val.eType==SQLITE_FLOAT && val.fVal==fVal); 12111 break; 12112 } 12113 12114 case SQLITE_TEXT: { 12115 int nVal = sqlite3_value_bytes(pVal); 12116 if( val.eType==SQLITE_TEXT && val.iVal==nVal ){ 12117 const char *zVal = (const char*)sqlite3_value_text(pVal); 12118 bMatch = (0==memcmp(val.pPtr, zVal, nVal)); 12119 } 12120 break; 12121 } 12122 12123 default: { 12124 int nVal = sqlite3_value_bytes(pVal); 12125 if( val.eType==SQLITE_BLOB && val.iVal==nVal ){ 12126 const u8 *zVal = (const u8*)sqlite3_value_blob(pVal); 12127 bMatch = (0==memcmp(val.pPtr, zVal, nVal)); 12128 } 12129 assert( eType==SQLITE_BLOB ); 12130 break; 12131 } 12132 } 12133 12134 if( bMatch==0 ) rc = SQLITE_ERROR; 12135 } 12136 12137 *piOff = iOff; 12138 return rc; 12139 } 12140 12141 /* 12142 ** Return true if the difference between f1 and f2 is smaller than 12143 ** (fTol * max(f1, f2)). Or false if they differ by more than this. 12144 */ 12145 static int vec1FloatWithinTolerance(float f1, float f2, float fTol){ 12146 if( f1==0.0 || f2==0.0 ) return 0; 12147 if( f2>f1 ){ 12148 if( ((f2-f1) / f2) > fTol ) return 0; 12149 }else{ 12150 if( ((f1-f2) / f1) > fTol ) return 0; 12151 } 12152 return 1; 12153 } 12154 12155 /* 12156 ** Check that the encoded version of aVec[] matches the encoded vector 12157 ** stored at entry iEntry of aBlob[]. For BQ encodings, the bit-quantized 12158 ** vector must match exactly and the stored norm must be within a small 12159 ** tolerance of the calculated value. For PQ encodings, the encoded vectors 12160 ** are compared using their reconstruction errors, allowing for small 12161 ** differences in floating-point arithmetic. 12162 ** 12163 ** Return non-zero if the encoded vector is inconsistent with aVec[] or if 12164 ** an error occurs. Set *pRc to SQLITE_NOMEM if temporary space cannot be 12165 ** allocated. 12166 */ 12167 static int vec1IntegrityCheckEncoded( 12168 int *pRc, /* IN/OUT: Error code */ 12169 Vec1Model *pMod, /* Model used to quantize vectors */ 12170 const float *aVec, /* Vector to compare quantized entry to */ 12171 int iEntry, /* Entry of aBlob[] to compare to */ 12172 const u8 *aBlob, /* %_idx.val value */ 12173 Vec1Buffer *pBuf /* Buffer to use for temp space */ 12174 ){ 12175 const int nEnc = vec1EncodedVectorSize(pMod); 12176 const int nElem = (int)pMod->hdr.nElem; 12177 12178 /* Allocate the maximum amount of space required by this function - 12179 ** enough for one full vector and two encoded vectors. */ 12180 int nReq = (nElem * sizeof_f32) + nEnc*2; 12181 if( vec1BufferSize(pBuf, nReq) ){ 12182 *pRc = SQLITE_NOMEM; 12183 return 1; 12184 }else{ 12185 const int nCodebook = pMod->hdr.nCodebook; 12186 float *v1 = (float*)pBuf->a; /* Space for decoded vector */ 12187 u8 *aEnc = (u8*)&v1[nElem]; /* Encoded version of aVec[] */ 12188 u8 *aIdx = &aEnc[nEnc]; /* Encoded vector read from aBlob[] */ 12189 12190 u32 flags = vec1GetU32(&aBlob[0]); 12191 u32 nEntry = (int)vec1GetU32(&aBlob[4]); 12192 int iOut = 0; 12193 int iOff; 12194 int ii; 12195 12196 /* Encode the vector into aEnc */ 12197 vec1EncodeVector(pMod, aVec, aEnc); 12198 12199 /* Read the encoded version of the vector from aBlob[] into aIdx[] */ 12200 iOff = nEntry * ((flags & VEC1_LIST_64BIT) ? 8 : 4) + VEC1_LIST_SZHDR; 12201 if( pMod->hdr.flags & VEC1_MODEL_BITQUANT ){ 12202 int iNorm = iOff + VEC1_LIST_NORM_OFFSET(iEntry, nCodebook); 12203 memcpy(aIdx, &aBlob[iNorm], sizeof_f32); 12204 iOff += VEC1_LIST_CODE_OFFSET(iEntry, nCodebook); 12205 iOut = sizeof_f32; 12206 }else{ 12207 iOff += VEC1_LIST_BLOCKED_OFFSET(iEntry, nCodebook); 12208 } 12209 for(ii=0; iihdr.flags & VEC1_MODEL_BITQUANT ){ 12228 float norm1; 12229 float norm2; 12230 memcpy(&norm1, aEnc, sizeof_f32); 12231 memcpy(&norm2, aIdx, sizeof_f32); 12232 12233 /* Check the norms are close enough. If not, return 1. */ 12234 if( vec1FloatWithinTolerance(norm1, norm2, fTol)==0 ) return 1; 12235 12236 /* Check the arrays of bits are identical. If not, return 1. */ 12237 if( memcmp(&aEnc[sizeof_f32], &aIdx[sizeof_f32], nEnc-sizeof_f32) ){ 12238 return 1; 12239 } 12240 }else{ 12241 float e1 = 0.0; /* aEnc[] squared reconstruction error */ 12242 float e2 = 0.0; /* aIdx[] squared reconstruction error */ 12243 vec1DecodeVector(pMod, aEnc, v1); 12244 e1 = (float)vec1L2Dist(v1, aVec, nElem); 12245 vec1DecodeVector(pMod, aIdx, v1); 12246 e2 = (float)vec1L2Dist(v1, aVec, nElem); 12247 if( vec1FloatWithinTolerance(e1, e2, fTol)==0 ) return 1; 12248 } 12249 } 12250 } 12251 12252 return 0; 12253 } 12254 12255 /* 12256 ** Check that a vector with transformed value aVec[] may legitimately be 12257 ** stored in bucket iBucket. 12258 ** 12259 ** If vec1BestMatchSimple() selects bucket iBucket for aVec[], then it 12260 ** may. Otherwise, the vector may have been assigned to its bucket by 12261 ** different code - either a different routine, such as the batched 12262 ** routines used by 'rebuild', or the same routine on a different platform. 12263 ** Rounding differences mean such code may select a different bucket when 12264 ** aVec[] is (almost) equidistant from two or more centroids. So iBucket 12265 ** is also accepted if the distance from aVec[] to centroid iBucket is 12266 ** within a small tolerance of the distance to the centroid selected by 12267 ** vec1BestMatchSimple(). 12268 ** 12269 ** Return non-zero if aVec[] may not be stored in bucket iBucket, or zero 12270 ** otherwise. 12271 */ 12272 static int vec1IntegrityCheckBucket( 12273 const Vec1Model *pMod, /* Model used to quantize vectors */ 12274 const float *aVec, /* Transformed vector */ 12275 int iBucket /* Bucket the vector is stored in */ 12276 ){ 12277 const int nElem = (int)pMod->hdr.nElem; 12278 const int nBucket = (int)pMod->hdr.nBucket; 12279 double fBest = 0.0; 12280 double fDist = 0.0; 12281 int iBest = 0; 12282 12283 if( nBucket==0 ) return (iBucket!=0); 12284 if( iBucket<0 || iBucket>=nBucket ) return 1; 12285 12286 iBest = vec1BestMatchSimple(pMod->aCentroid, nBucket, aVec, nElem, &fBest); 12287 if( iBest==iBucket ) return 0; 12288 12289 fDist = vec1L2Dist(aVec, &pMod->aCentroid[iBucket*nElem], nElem); 12290 return vec1BucketIsNearTie(fBest, fDist)==0; 12291 } 12292 12293 /* 12294 ** The buffer passed as the only argument contains a meta-value array. If 12295 ** it is of type GENERIC, test that it is well-formed. Return VEC1_CORRUPT 12296 ** if it is not, or SQLITE_OK if it looks ok. 12297 */ 12298 static int vec1IntegrityCheckMetaArray(Vec1Buffer *pBuf){ 12299 int rc = SQLITE_OK; 12300 int bGeneric = vec1GetU32(pBuf->a) & VEC1_META_GENERIC; 12301 if( bGeneric ){ 12302 u32 nEntry = vec1GetU32(&pBuf->a[4]); 12303 u32 ii; 12304 int iOff = VEC1_META_SZHDR; 12305 for(ii=0; rc==SQLITE_OK && iimod.hdr.flags & VEC1_MODEL_INDEX) ){ 12339 int bFlat = vec1ModelIsFlat(&pTab->mod); 12340 Vec1Model *pMod = &pTab->mod; 12341 const int nCodebook = pMod->hdr.nCodebook; 12342 const int nElem = pTab->cfg.nElem; 12343 12344 int *aiOffMeta = 0; 12345 i64 nTotalEntry = 0; 12346 12347 if( nCodebook>0 && pMod->hdr.nBucket>0 ){ 12348 aResidual = vec1MallocZero(pTab->nTmpVec * sizeof_f32); 12349 if( aResidual==0 ){ 12350 rc = SQLITE_NOMEM; 12351 goto integrity_failed; 12352 } 12353 } 12354 12355 if( nCodebook>0 ){ 12356 aPQ = (u8*)vec1MallocZero((nCodebook+sizeof_f32) * 2); 12357 if( aPQ==0 ){ 12358 rc = SQLITE_NOMEM; 12359 goto integrity_failed; 12360 } 12361 } 12362 12363 rc = vec1GetSql(pTab, VEC1_SQL_SCAN_IDX, &pScan); 12364 if( rc==SQLITE_OK ){ 12365 rc = vec1GetSql(pTab, VEC1_SQL_LOOKUP_BASE, &pLookup); 12366 } 12367 12368 /* If there are one or more meta-value columns, allocate space for 12369 ** buffers to load each of them from the database */ 12370 if( rc==SQLITE_OK && pTab->nMeta>0 ){ 12371 int nByte = pTab->nMeta * (sizeof(Vec1Buffer) + sizeof(int)); 12372 aBufMeta = (Vec1Buffer*)vec1MallocZero(nByte); 12373 if( aBufMeta==0 ){ 12374 rc = SQLITE_NOMEM; 12375 }else{ 12376 aiOffMeta = (int*)&aBufMeta[pTab->nMeta]; 12377 } 12378 } 12379 12380 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){ 12381 const u8 *aBlob = sqlite3_column_blob(pScan, 0); 12382 int nBlob = sqlite3_column_bytes(pScan, 0); 12383 int iBucket = sqlite3_column_int(pScan, 1); 12384 i64 iId = sqlite3_column_int64(pScan, 2); 12385 int szRowid = 4; 12386 12387 int nEntry = 0; 12388 u32 flags = 0; 12389 int nTombstone = 0; 12390 int ii = 0; 12391 int iMeta = 0; 12392 int nNonTombstone = 0; 12393 12394 if( vec1CheckIdxSize(pTab, aBlob, nBlob) ){ 12395 const char *zFmt = "%s: %%_idx entry id=%lld is corrupt"; 12396 zErr = sqlite3_mprintf(zFmt, zTabName, sqlite3_column_int64(pScan, 2)); 12397 goto integrity_failed; 12398 } 12399 12400 flags = vec1GetU32(&aBlob[0]); 12401 nEntry = (int)vec1GetU32(&aBlob[4]); 12402 nTombstone = (int)vec1GetU32(&aBlob[8]); 12403 if( flags & VEC1_LIST_64BIT ){ 12404 szRowid = 8; 12405 } 12406 12407 /* Load the array for each meta-value column from disk */ 12408 for(iMeta=0; iMetanMeta; iMeta++){ 12409 rc = vec1ReadMeta(pTab, nEntry, &aBufMeta[iMeta], iId, iMeta); 12410 12411 if( rc==SQLITE_OK ){ 12412 rc = vec1IntegrityCheckMetaArray(&aBufMeta[iMeta]); 12413 } 12414 if( rc!=SQLITE_OK ){ 12415 if( rc==SQLITE_CORRUPT_VTAB ){ 12416 const char *zFmt = "%s: error reading meta-list id=%lld,meta=%d"; 12417 zErr = sqlite3_mprintf(zFmt, zTabName, iId, iMeta); 12418 rc = SQLITE_OK; 12419 } 12420 goto integrity_failed; 12421 } 12422 aiOffMeta[iMeta] = VEC1_META_SZHDR; 12423 } 12424 12425 for(ii=0; iinMeta; iMeta++){ 12442 vec1IntegrityMetaValue(&aBufMeta[iMeta], &aiOffMeta[iMeta], 0); 12443 } 12444 continue; 12445 } 12446 12447 nNonTombstone++; 12448 12449 sqlite3_bind_int64(pLookup, 1, iRowid); 12450 if( sqlite3_step(pLookup)==SQLITE_ROW ){ 12451 bExists = 1; 12452 12453 /* Check that the meta-value arrays contain the correct data */ 12454 for(iMeta=0; iMetanMeta; iMeta++){ 12455 Vec1Buffer *pBuf = &aBufMeta[iMeta]; 12456 sqlite3_value *pVal = sqlite3_column_value(pLookup, 2+iMeta); 12457 12458 if( vec1IntegrityMetaValue(pBuf, &aiOffMeta[iMeta], pVal) ){ 12459 const char *zFmt = "%s: meta-value value mismatch for row %lld"; 12460 zErr = sqlite3_mprintf(zFmt, zTabName, iRowid); 12461 goto integrity_failed; 12462 } 12463 } 12464 12465 if( bFlat ){ 12466 int iBaseBucket = sqlite3_column_int(pLookup, 1); 12467 if( iBaseBucket!=iBucket ){ 12468 const char *zFmt = 12469 "%s: bucket value in %%_base row %lld is incorrect"; 12470 zErr = sqlite3_mprintf(zFmt, zTabName, iRowid); 12471 goto integrity_failed; 12472 } 12473 }else{ 12474 const u8 *aBaseVec = sqlite3_column_blob(pLookup, 1); 12475 const float *aTransform = 0; 12476 int nBaseVec = sqlite3_column_bytes(pLookup, 1); 12477 12478 assert( nCodebook>0 ); 12479 12480 /* Check the vector is the right size. */ 12481 if( nBaseVec!=nElem*sizeof_f32 ){ 12482 const char *zFmt = "%s: vector in %%_base row %lld is wrong size"; 12483 zErr = sqlite3_mprintf(zFmt, zTabName, iRowid); 12484 goto integrity_failed; 12485 } 12486 12487 aTransform = vec1TransformInputVector( 12488 &pTab->mod, pTab->aTmpVec, (const float*)aBaseVec 12489 ); 12490 12491 /* Check the vector is in the right bucket. */ 12492 if( vec1IntegrityCheckBucket(pMod, aTransform, iBucket) ){ 12493 const char *zFmt = "%s: vector from row %lld is in wrong bucket"; 12494 zErr = sqlite3_mprintf(zFmt, zTabName, iRowid); 12495 goto integrity_failed; 12496 } 12497 12498 /* Check that the contents of the index entry look right. */ 12499 { 12500 /* Calculate a PQ code based on the transformed vector. Store 12501 ** this in aPQ[]. For binary quantization, aPQ[] contains the 12502 ** norm followed by nCodebook bytes of data. For PQ or OPQ, 12503 ** aPQ[] just contains the nCodebook bytes of encoded vector. */ 12504 const float *aEnc = (const float*)aTransform; 12505 if( (pMod->hdr.flags & VEC1_MODEL_RESIDUAL) ){ 12506 const float *aCent = &pMod->aCentroid[iBucket*nElem]; 12507 vec1Sub(aResidual, aEnc, aCent, nElem); 12508 aEnc = aResidual; 12509 } 12510 if( vec1IntegrityCheckEncoded(&rc, pMod, aEnc, ii, aBlob, &tmp) ){ 12511 const char *zType; 12512 const char *zFmt = 12513 "%s: %%_idx %s does not match calculated %s for row %lld"; 12514 zType = (pMod->hdr.flags & VEC1_MODEL_BITQUANT) ? "BQ" : "PQ"; 12515 zErr = sqlite3_mprintf(zFmt, zTabName, zType, zType, iRowid); 12516 goto integrity_failed; 12517 } 12518 } 12519 } 12520 } 12521 vec1StmtReset(&rc, pLookup); 12522 12523 if( rc==SQLITE_OK && bExists==0 ){ 12524 const char *zFmt = "%s: %%_idx row %lld missing from %%_base"; 12525 zErr = sqlite3_mprintf(zFmt, zTabName, iRowid); 12526 goto integrity_failed; 12527 } 12528 } 12529 12530 if( rc==SQLITE_OK && (nNonTombstone+nTombstone)!=nEntry ){ 12531 const char *zFmt = "%s: bad tombstone count"; 12532 zErr = sqlite3_mprintf(zFmt, zTabName); 12533 goto integrity_failed; 12534 } 12535 12536 nTotalEntry += nNonTombstone; 12537 } 12538 12539 if( rc==SQLITE_OK ){ 12540 i64 nGot = -1; 12541 sqlite3_stmt *pStmt = 0; 12542 const char *zCount = "SELECT count(*) FROM %Q.'%q_base'"; 12543 rc = vec1PrepareSql(pTab, &pStmt, zCount, pTab->zDb, pTab->zName); 12544 if( rc==SQLITE_OK ){ 12545 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 12546 nGot = sqlite3_column_int64(pStmt, 0); 12547 } 12548 } 12549 vec1StmtFinalize(&rc, pStmt); 12550 if( rc==SQLITE_OK && nGot!=nTotalEntry ){ 12551 const char *zFmt = 12552 "%s: wrong number of entries in %%_base - have %lld, expect %lld"; 12553 zErr = sqlite3_mprintf(zFmt, zTabName, nGot, nTotalEntry); 12554 goto integrity_failed; 12555 } 12556 } 12557 } 12558 12559 integrity_failed: 12560 *pzErr = zErr; 12561 sqlite3_free(aResidual); 12562 sqlite3_free(aPQ); 12563 vec1BufferFree(&tmp); 12564 if( aBufMeta ){ 12565 int ii; 12566 for(ii=0; iinMeta; ii++){ 12567 vec1BufferFree(&aBufMeta[ii]); 12568 } 12569 sqlite3_free(aBufMeta); 12570 } 12571 sqlite3_free(pTab->base.zErrMsg); 12572 pTab->base.zErrMsg = 0; 12573 vec1StmtReset(&rc, pScan); 12574 vec1StmtReset(&rc, pLookup); 12575 return rc; 12576 } 12577 12578 /************************************************************************* 12579 ** Start of vec1_cat virtual table. 12580 */ 12581 12582 #define VEC1CAT_SCHEMA \ 12583 "CREATE TABLE vec1cat(database, name, model, qprofile)" 12584 12585 typedef struct vec1cat_vtab vec1cat_vtab; 12586 struct vec1cat_vtab { 12587 sqlite3_vtab base; 12588 Vec1TabList *pList; 12589 }; 12590 12591 typedef struct vec1cat_cursor vec1cat_cursor; 12592 struct vec1cat_cursor { 12593 sqlite3_vtab_cursor base; 12594 sqlite3_int64 iRowid; 12595 }; 12596 12597 static int vec1catConnectMethod( 12598 sqlite3 *db, 12599 void *pAux, 12600 int argc, 12601 const char *const *argv, 12602 sqlite3_vtab **ppVtab, 12603 char **pzErr 12604 ){ 12605 vec1cat_vtab *pNew; 12606 int rc; 12607 12608 UNUSED_PARAMETER(pzErr); 12609 UNUSED_PARAMETER2(argv, argc); 12610 12611 rc = sqlite3_declare_vtab(db, VEC1CAT_SCHEMA); 12612 if( rc==SQLITE_OK ){ 12613 pNew = vec1MallocZero(sizeof(*pNew)); 12614 *ppVtab = (sqlite3_vtab*)pNew; 12615 if( pNew==0 ) return SQLITE_NOMEM; 12616 pNew->pList = (Vec1TabList*)pAux; 12617 } 12618 return rc; 12619 } 12620 12621 static int vec1catDisconnectMethod(sqlite3_vtab *pVtab){ 12622 vec1cat_vtab *p = (vec1cat_vtab *)pVtab; 12623 sqlite3_free(p); 12624 return SQLITE_OK; 12625 } 12626 12627 static int vec1catOpenMethod(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCur){ 12628 vec1cat_cursor *pCur; 12629 UNUSED_PARAMETER(pVtab); 12630 pCur = vec1MallocZero(sizeof(*pCur)); 12631 if( pCur==0 ) return SQLITE_NOMEM; 12632 *ppCur = &pCur->base; 12633 return SQLITE_OK; 12634 } 12635 12636 static int vec1catCloseMethod(sqlite3_vtab_cursor *cur){ 12637 vec1cat_cursor *pCur = (vec1cat_cursor *)cur; 12638 sqlite3_free(pCur); 12639 return SQLITE_OK; 12640 } 12641 12642 static int vec1catBestIndexMethod( 12643 sqlite3_vtab *pVtab, 12644 sqlite3_index_info *pIdxInfo 12645 ){ 12646 UNUSED_PARAMETER(pVtab); 12647 pIdxInfo->estimatedCost = (double)10; 12648 pIdxInfo->estimatedRows = 10; 12649 return SQLITE_OK; 12650 } 12651 12652 static int vec1catFilterMethod( 12653 sqlite3_vtab_cursor *cur, 12654 int idxNum, 12655 const char *idxStr, 12656 int argc, 12657 sqlite3_value **argv 12658 ){ 12659 Vec1TabList *pList = ((vec1cat_vtab*)(cur->pVtab))->pList; 12660 vec1cat_cursor *pCur = (vec1cat_cursor *)cur; 12661 sqlite3_stmt *pSql1 = 0; 12662 int rc = SQLITE_OK; 12663 12664 const char *zSql1 = "SELECT name FROM pragma_database_list"; 12665 const char *zSql2 = 12666 "WITH tables(name) AS (" 12667 " SELECT name FROM %Q.sqlite_schema " 12668 " WHERE sql LIKE 'CREATE%%VIRTUAL%%USING%%vec1%%'" 12669 ")" 12670 "SELECT * FROM tables CROSS JOIN pragma_table_info(tables.name, %Q)"; 12671 12672 UNUSED_PARAMETER2(argc, argv); 12673 UNUSED_PARAMETER2(idxStr, idxNum); 12674 12675 rc = sqlite3_prepare_v2(pList->db, zSql1, -1, &pSql1, 0); 12676 if( rc==SQLITE_OK ){ 12677 while( sqlite3_step(pSql1)==SQLITE_ROW ){ 12678 const char *zDb = (const char*)sqlite3_column_text(pSql1, 0); 12679 sqlite3_stmt *pSql2 = 0; 12680 char *z = vec1MPrintf(&rc, zSql2, zDb, zDb); 12681 if( rc==SQLITE_OK ){ 12682 rc = sqlite3_prepare(pList->db, z, -1, &pSql2, 0); 12683 sqlite3_free(z); 12684 } 12685 if( rc==SQLITE_OK ){ 12686 while( sqlite3_step(pSql2)==SQLITE_ROW ); 12687 vec1StmtFinalize(&rc, pSql2); 12688 } 12689 } 12690 vec1StmtFinalize(&rc, pSql1); 12691 } 12692 12693 pCur->iRowid = 1; 12694 return rc; 12695 } 12696 12697 static int vec1catNextMethod(sqlite3_vtab_cursor *cur){ 12698 vec1cat_cursor *pCur = (vec1cat_cursor *)cur; 12699 pCur->iRowid++; 12700 return SQLITE_OK; 12701 } 12702 12703 static Vec1Tab *vec1catGetTable(vec1cat_cursor *pCur){ 12704 Vec1TabList *pList = ((vec1cat_vtab*)(pCur->base.pVtab))->pList; 12705 Vec1Tab *pTab = pList->pFirst; 12706 int ii; 12707 12708 for(ii=1; pTab && iiiRowid; ii++){ 12709 pTab = pTab->pTabNext; 12710 } 12711 12712 return pTab; 12713 } 12714 12715 static int vec1catEofMethod(sqlite3_vtab_cursor *cur){ 12716 return vec1catGetTable((vec1cat_cursor*)cur)==0; 12717 } 12718 12719 /* 12720 ** xColumn() method for ephemeral virtual table vec1cat. 12721 */ 12722 static int vec1catColumnMethod( 12723 sqlite3_vtab_cursor *cur, 12724 sqlite3_context *ctx, 12725 int i 12726 ){ 12727 vec1cat_cursor *pCur = (vec1cat_cursor*)cur; 12728 Vec1Tab *pTab = vec1catGetTable(pCur); 12729 int rc = SQLITE_OK; 12730 12731 switch( i ){ 12732 case 0: /* database */ 12733 sqlite3_result_text(ctx, pTab->zDb, -1, SQLITE_TRANSIENT); 12734 break; 12735 12736 case 1: /* name */ 12737 sqlite3_result_text(ctx, pTab->zName, -1, SQLITE_TRANSIENT); 12738 break; 12739 12740 case 2: { /* model */ 12741 Vec1ModelHeader *pHdr = &pTab->mod.hdr; 12742 const char *zDist = 0; 12743 char *zRet = 0; 12744 12745 rc = vec1LoadConfig(pTab); 12746 zDist = ((pHdr->eDistance==VEC1_DISTANCE_L2) ? "l2" : "cos"); 12747 if( pHdr->nCodebook==0 && pHdr->nBucket==0 ){ 12748 zRet = vec1MPrintf(&rc, 12749 "{\"index\": \"%s\", \"distance\": \"%s\"}", 12750 ((pHdr->flags & VEC1_MODEL_INDEX) ? "flat" : "none"), zDist 12751 ); 12752 }else{ 12753 const char *zQuant = "none"; 12754 if( pHdr->nCodebook ){ 12755 if( pHdr->flags & VEC1_MODEL_BITQUANT ){ 12756 zQuant = "bq"; 12757 }else if( pHdr->flags & VEC1_MODEL_ROTATE ){ 12758 zQuant = "opq"; 12759 }else{ 12760 zQuant = "pq"; 12761 } 12762 } 12763 12764 zRet = vec1MPrintf(&rc, "{" 12765 "\"index\": \"trained\", " 12766 "\"distance\": \"%s\", " 12767 "\"nbucket\": %d, " 12768 "\"quantizer\": \"%s\", " 12769 "\"codesize\": %d, " 12770 "\"residual\": %s, " 12771 "\"wht\": %s}", 12772 zDist, pHdr->nBucket, zQuant, pHdr->nCodebook, 12773 (pHdr->flags & VEC1_MODEL_RESIDUAL) ? "true" : "false", 12774 (pHdr->flags & VEC1_MODEL_WHT) ? "true" : "false" 12775 ); 12776 } 12777 12778 if( rc==SQLITE_OK ){ 12779 sqlite3_result_text(ctx, zRet, -1, vec1SqliteFree); 12780 }else{ 12781 sqlite3_result_error_code(ctx, rc); 12782 } 12783 break; 12784 } 12785 12786 default: { /* qprofile */ 12787 const char *azName[VEC1_QINSTR_NCOUNTER] = { 12788 "total", /* VEC1_QINSTR_TOTAL */ 12789 "init", /* VEC1_QINSTR_INITQUERY */ 12790 "coarse", /* VEC1_QINSTR_COARSE */ 12791 "idxread", /* VEC1_QINSTR_IDXREAD */ 12792 "metaread", /* VEC1_QINSTR_METAREAD */ 12793 "metascan", /* VEC1_QINSTR_METASCAN */ 12794 "lut", /* VEC1_QINSTR_LUT */ 12795 "pqscan", /* VEC1_QINSTR_PQSCAN */ 12796 "finalsort" /* VEC1_QINSTR_FINALSORT */ 12797 }; 12798 12799 char *zRet = 0; 12800 int ii; 12801 12802 for(ii=0; iiaCount[ii], pTab->aCycle[ii] 12807 ); 12808 } 12809 zRet = vec1MPrintf(&rc, "{%z\n}", zRet); 12810 12811 if( rc==SQLITE_OK ){ 12812 sqlite3_result_text(ctx, zRet, -1, vec1SqliteFree); 12813 }else{ 12814 sqlite3_result_error_code(ctx, rc); 12815 } 12816 } 12817 } 12818 return SQLITE_OK; 12819 } 12820 12821 static int vec1catRowidMethod( 12822 sqlite3_vtab_cursor *cur, 12823 sqlite3_int64 *pRowid 12824 ){ 12825 vec1cat_cursor *pCur = (vec1cat_cursor *)cur; 12826 *pRowid = pCur->iRowid; 12827 return SQLITE_OK; 12828 } 12829 12830 /* 12831 ** End of vec1_cat virtual table. 12832 *************************************************************************/ 12833 12834 12835 /* 12836 ** Used to get/set per-connection transient parameters. Syntax: 12837 ** 12838 ** SELECT vec1_config(PARAM) 12839 ** SELECT vec1_config(PARAM, VALUE) 12840 ** 12841 ** There are currently two parameters: 12842 ** 12843 ** nthread: 12844 ** Default number of threads to use for training and rebuilding. 12845 ** 12846 ** nprobe: 12847 ** Default nprobe value for queries that do not specify one. 12848 ** 12849 */ 12850 static void vec1ConfigFunc( 12851 sqlite3_context *pCtx, 12852 int nVal, 12853 sqlite3_value **aVal 12854 ){ 12855 Vec1TabList *pList = (Vec1TabList*)sqlite3_user_data(pCtx); 12856 const char *zParam = (const char*)sqlite3_value_text(aVal[0]); 12857 12858 if( 0==sqlite3_stricmp(zParam, "nthread") ){ 12859 if( nVal==2 ){ 12860 int nNew = sqlite3_value_int(aVal[1]); 12861 if( nNew<1 || nNew>VEC1_MAX_NTHREAD ){ 12862 vec1ResultErrorF(pCtx, "vec1: " 12863 "nthread requires an integer value between 1 and %d", 12864 VEC1_MAX_NTHREAD 12865 ); 12866 return; 12867 } 12868 #if VEC1_THREADS 12869 pList->nThread = nNew; 12870 #endif 12871 } 12872 sqlite3_result_int(pCtx, pList->nThread); 12873 }else if( 0==sqlite3_stricmp(zParam, "nprobe") ){ 12874 if( nVal==2 ){ 12875 int eNumeric = sqlite3_value_numeric_type(aVal[1]); 12876 double fNew = 0.0; 12877 if( eNumeric==SQLITE_INTEGER || eNumeric==SQLITE_FLOAT ){ 12878 fNew = sqlite3_value_double(aVal[1]); 12879 } 12880 if( fNew<=0.0 ){ 12881 vec1ResultErrorF(pCtx, 12882 "vec1: nprobe must be a numeric value greater than 0.0" 12883 ); 12884 return; 12885 } 12886 pList->nProbeArg = fNew; 12887 } 12888 sqlite3_result_double(pCtx, pList->nProbeArg); 12889 }else{ 12890 vec1ResultErrorF(pCtx, "vec1: no such parameter: %s", zParam); 12891 } 12892 } 12893 12894 /* 12895 ** Destructor for the vec1 module registered using sqlite3_create_module_v2(). 12896 ** Free the Vec1TabList structure. SQLite should have ensured any virtual 12897 ** tables are closed before this is called. 12898 */ 12899 static void vec1ListFree(void *pCtx){ 12900 Vec1TabList *pList = (Vec1TabList*)pCtx; 12901 pList->nRef--; 12902 if( pList->nRef==0 ){ 12903 assert( pList->pFirst==0 ); 12904 sqlite3_free(pList); 12905 } 12906 } 12907 12908 static int initExtension( 12909 sqlite3 *db, 12910 char **pzErr, 12911 const sqlite3_api_routines *pApi 12912 ){ 12913 static sqlite3_module vec1catModule = { 12914 0, /* iVersion */ 12915 0, /* xCreate */ 12916 vec1catConnectMethod, /* xConnect */ 12917 vec1catBestIndexMethod, /* xBestIndex */ 12918 vec1catDisconnectMethod, /* xDisconnect */ 12919 0, /* xDestroy */ 12920 vec1catOpenMethod, /* xOpen */ 12921 vec1catCloseMethod, /* xClose */ 12922 vec1catFilterMethod, /* xFilter */ 12923 vec1catNextMethod, /* xNext */ 12924 vec1catEofMethod, /* xEof */ 12925 vec1catColumnMethod, /* xColumn */ 12926 vec1catRowidMethod, /* xRowid */ 12927 0, /* xUpdate */ 12928 0, /* xBegin */ 12929 0, /* xSync */ 12930 0, /* xCommit */ 12931 0, /* xRollback */ 12932 0, /* xFindMethod */ 12933 0, /* xRename */ 12934 0, /* xSavepoint */ 12935 0, /* xRelease */ 12936 0, /* xRollbackTo */ 12937 0, /* xShadowName */ 12938 0, /* xIntegrity */ 12939 }; 12940 12941 static sqlite3_module vec1Module = { 12942 4, /* iVersion */ 12943 vec1CreateMethod, /* xCreate */ 12944 vec1ConnectMethod, /* xConnect */ 12945 vec1BestIndexMethod, /* xBestIndex */ 12946 vec1DisconnectMethod, /* xDisconnect */ 12947 vec1DestroyMethod, /* xDestroy */ 12948 vec1Open, /* xOpen */ 12949 vec1Close, /* xClose */ 12950 vec1FilterMethod, /* xFilter */ 12951 vec1NextMethod, /* xNext */ 12952 vec1EofMethod, /* xEof */ 12953 vec1ColumnMethod, /* xColumn */ 12954 vec1Rowid, /* xRowid */ 12955 vec1UpdateMethod, /* xUpdate */ 12956 vec1BeginMethod, /* xBegin */ 12957 vec1SyncMethod, /* xSync */ 12958 0, /* xCommit */ 12959 vec1RollbackMethod, /* xRollback */ 12960 0, /* xFindFunction */ 12961 vec1RenameMethod, /* xRename */ 12962 vec1SavepointMethod, /* xSavepoint */ 12963 vec1ReleaseMethod, /* xRelease */ 12964 vec1RollbackToMethod, /* xRollbackTo */ 12965 0, /* xShadowName */ 12966 vec1IntegrityMethod /* xIntegrity */ 12967 }; 12968 12969 static struct Func { 12970 const char *zName; 12971 int nArg; 12972 void (*x)(sqlite3_context*,int,sqlite3_value**); 12973 } aFunc[] = { 12974 { "vec1_info", 0, vec1InfoFunc }, 12975 { "vec1_to_json", 1, vec1ToJsonFFunc }, 12976 { "vec1_from_json", 1, vec1FromJsonFunc }, 12977 12978 { "vec1_l2_distance", 2, vec1DistanceFuncL2 }, 12979 { "vec1_cos_distance", 2, vec1DistanceFuncCos }, 12980 12981 { "vec1_config", 1, vec1ConfigFunc }, 12982 { "vec1_config", 2, vec1ConfigFunc }, 12983 12984 /* Currently undocumented functions. These may become documented when 12985 ** datatypes other than 32-bit float are supported for vectors */ 12986 { "vec1_to_json_f", 1, vec1ToJsonFFunc }, 12987 { "vec1_to_json_i", 1, vec1ToJsonIFunc }, 12988 }; 12989 12990 static struct AggFunc { 12991 const char *zName; 12992 int nArg; 12993 void (*xStep)(sqlite3_context*,int,sqlite3_value**); 12994 void (*xFinal)(sqlite3_context*); 12995 } aAgg[] = { 12996 { "vec1_train", 1, vec1TrainStep, vec1TrainFinal }, 12997 { "vec1_train", 2, vec1TrainStep, vec1TrainFinal }, 12998 }; 12999 13000 int ii = 0; 13001 int rc = SQLITE_OK; 13002 Vec1TabList *pList = vec1MallocZero(sizeof(Vec1TabList)); 13003 13004 UNUSED_PARAMETER2(pApi, pzErr); 13005 13006 /* Assuming the Vec1TabList object was allocated without error, populate 13007 ** it and create the main virtual table module - vec1. */ 13008 if( pList==0 ){ 13009 rc = SQLITE_NOMEM; 13010 }else{ 13011 pList->nThread = 1; 13012 pList->db = db; 13013 pList->nProbeArg = VEC1_QUERY_DEFAULT_NPROBE; 13014 13015 pList->nRef = 1; 13016 rc = sqlite3_create_module_v2(db, "vec1", &vec1Module, pList, vec1ListFree); 13017 } 13018 13019 /* Create the other vtab module - vec1cat */ 13020 if( rc==SQLITE_OK ){ 13021 pList->nRef++; 13022 rc = sqlite3_create_module_v2( 13023 db, "vec1cat", &vec1catModule, pList, vec1ListFree 13024 ); 13025 } 13026 13027 /* Create the scalar functions */ 13028 for(ii=0; rc==SQLITE_OK && iizName, p->nArg, SQLITE_UTF8|SQLITE_DIRECTONLY, (void*)pList, 0, 13040 p->xStep, p->xFinal 13041 ); 13042 } 13043 13044 /* If an error occurred, unregister everything */ 13045 if( rc!=SQLITE_OK ){ 13046 sqlite3_create_module(db, "vec1", 0, 0); 13047 sqlite3_create_module(db, "vec1cat", 0, 0); 13048 13049 for(ii=0; ii 13095 static int vec1HasAvx2(void) 13096 { 13097 int regs[4]; 13098 __cpuid(regs, 1); 13099 int ecx = regs[2]; 13100 if (!(ecx & (1 << 28))) return 0; // AVX 13101 if (!(ecx & (1 << 27))) return 0; // OSXSAVE 13102 unsigned long long xcr0 = _xgetbv(0); 13103 if ((xcr0 & 0x6) != 0x6) return 0; 13104 __cpuidex(regs, 7, 0); 13105 int ebx = regs[1]; 13106 return (ebx & (1 << 5)) != 0; // AVX2 13107 } 13108 # else 13109 static int vec1HasAvx2(void){ 13110 /* Clang/GCC */ 13111 __builtin_cpu_init(); 13112 return __builtin_cpu_supports("avx2"); 13113 } 13114 # endif 13115 13116 static int initMultiExtension( 13117 sqlite3 *db, 13118 char **pzErr, 13119 const sqlite3_api_routines *pApi 13120 ){ 13121 int rc = SQLITE_OK; 13122 if( vec1HasAvx2() ){ 13123 /* Use AVX2 */ 13124 rc = sqlite3Vec1InitAVX2(db, pzErr, pApi); 13125 }else{ 13126 /* Fall back to scalar. */ 13127 rc = initExtension(db, pzErr, pApi); 13128 } 13129 13130 return rc; 13131 } 13132 # define initExtension initMultiExtension 13133 # endif /* VEC1SIMD==SCALAR */ 13134 #endif /* defined(VEC1SIMD) */ 13135 13136 #if !defined(VEC1SIMD) || VEC1SIMD==SCALAR 13137 13138 #ifndef VEC1_STATIC 13139 SQLITE_EXTENSION_INIT1 13140 #endif 13141 13142 #ifdef _WIN32 13143 __declspec(dllexport) 13144 #endif 13145 int sqlite3_extension_init( 13146 sqlite3 *db, 13147 char **pzErrMsg, 13148 const sqlite3_api_routines *pApi 13149 ){ 13150 #ifdef SQLITE_EXTENSION_INIT2 13151 SQLITE_EXTENSION_INIT2(pApi); 13152 #endif 13153 return initExtension(db, pzErrMsg, pApi); 13154 } 13155 13156 #ifdef VEC1_STATIC 13157 int sqlite3_vec1_extra_init(const char *z){ 13158 UNUSED_PARAMETER(z); 13159 sqlite3_auto_extension((void(*)(void))initExtension); 13160 return SQLITE_OK; 13161 } 13162 #endif 13163 13164 #endif /* !defined(VEC1SIMD) || VEC1SIMD==SCALAR */