interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / vec1 / tool / vec1bench.tcl

719 lines · 18380 bytes Raw Blame History
1
2package require sqlite3
3
4set DEFAULT(--nthread) 16
5set DEFAULT(--max-train) 100000
6set DEFAULT(--train-function) vec1_train
7set DEFAULT(--index) {nbucket 1024 codesize 32 opq 1}
8set DEFAULT(--query) ""
9set DEFAULT(--meta-data) 0
10set DEFAULT(--svd-verify) 0
11set DEFAULT(--report) ""
12set DEFAULT(--repeat) 1
13
14proc usage {} {
15 global DEFAULT
16 puts stderr "usage: $::argv0 ?OPTIONS? DATABASE ?SHLIB1...?"
17 puts stderr "options:"
18 foreach o [array names DEFAULT] {
19 set display $DEFAULT($o)
20 if { [string is integer $display]==0 } { set display "\"$display\"" }
21 puts stderr " [format {% -20s} $o](default: $display)"
22 }
23 exit 1
24}
25
26proc process_args {lArg} {
27 global C
28 global DEFAULT
29 array set C [array get DEFAULT]
30
31 for {set i 0} {$i < [expr [llength $lArg]-1]} {incr i} {
32 set a [lindex $lArg $i]
33 if {[string range $a 0 0]!="-"} break
34 if {[string range $a 1 1]!="-"} { set a "-$a" }
35
36 unset -nocomplain m
37 foreach o [array names C] {
38 if {[string match ${a}* $o]} {
39 if {[info exists m]} usage
40 set m $o
41 }
42 }
43 if {[info exists m]==0} usage
44
45 incr i
46 set C($m) [lindex $lArg $i]
47 }
48
49 lrange $lArg $i end
50}
51
52
53# Process command line arguments and open the database. And load the
54# vec1.so dynamic extension(s).
55#
56set lExt [process_args $argv]
57if {[llength $lExt]==0} usage
58set C(dbname) [lindex $lExt 0]
59set C(lExt) [lrange $lExt 1 end]
60
61proc open_db {fname} {
62 global C
63 set lExt $C(lExt);
64
65 sqlite3 db $fname
66 db enable_load_extension 1
67 if {[llength $lExt]==0 && [catch {db eval {SELECT vec1_info()}}]} {
68 set shlib [file join [file dirname [info nameofexecutable]] vec1]
69 db eval { SELECT load_extension($shlib) }
70 } else {
71 foreach shlib $lExt {
72 db eval { SELECT load_extension($shlib) }
73 }
74 }
75 db enable_load_extension 0
76}
77
78proc main { } {
79 global C
80
81 if {$C(dbname)=="release"} {
82 if {[catch release_test msg]} {
83 puts stderr "ERROR: $msg"
84 }
85 return
86 }
87
88 open_db $C(dbname)
89 check_db_looks_ok
90 summarize_db
91 build_nearest_if_required
92
93 set r $C(--repeat)
94 set lResult [list]
95 for {set i 0} {$i < $r} {incr i} {
96 if {$C(--index) != ""} {
97 test_build_index $C(--index)
98 }
99
100 if {$C(--query) != ""} {
101 lappend lResult [test_query_index {*}$C(--query)]
102 }
103 }
104 if {$C(--query) != ""} {
105 if {$r==1} {
106 print_query_timings
107 } else {
108 puts "recall: [lsort -integer $lResult]"
109 }
110 exit
111 }
112
113 array set I $C(--index)
114 if {[info exists I(codesize)] && $I(codesize)==0} {
115 # If the command-line specified a code-size of 0, then do not bother
116 # varying K, as reranking won't help anyway.
117 foreach nprobe {16 32 48 64} {
118 test_query_index 1 1 $nprobe
119 test_query_index 10 10 $nprobe
120 }
121 } else {
122 foreach nprobe {16 32 48 64} {
123 test_query_index 1 1 $nprobe
124 test_query_index 10 1 $nprobe
125 test_query_index 50 1 $nprobe
126 test_query_index 100 1 $nprobe
127 test_query_index 200 1 $nprobe
128 test_query_index 300 1 $nprobe
129 test_query_index 10 10 $nprobe
130 test_query_index 50 10 $nprobe
131 test_query_index 100 10 $nprobe
132 test_query_index 200 10 $nprobe
133 test_query_index 300 10 $nprobe
134 test_query_index 100 100 $nprobe
135 test_query_index 200 100 $nprobe
136 test_query_index 400 100 $nprobe
137 test_query_index 600 100 $nprobe
138 test_query_index 800 100 $nprobe
139 test_query_index 1000 100 $nprobe
140 }
141 }
142
143 print_report
144}
145
146proc release_test_one {varname name index lConfig} {
147 global T
148 upvar $varname lReport
149
150 test_build_index $index
151 foreach {K recall nprobe} $lConfig {
152 test_query_index $K $recall $nprobe
153 }
154
155 set times [format_us $T(train)]/[format_us $T(build)]
156 lappend lReport "$name {$index}: train/build: $times"
157 foreach {K recall nprobe} $lConfig {
158 set r $T(recall,$recall,$nprobe,$K)
159 set q $T(qps,$recall,$nprobe,$K)
160 set res "[format {% -6s} $nprobe/$K] -> ${r}@$recall ${q}qps "
161 lappend lReport " $res"
162 }
163}
164
165proc release_test {} {
166 global C
167 set C(--nthread) 8
168
169 set lReq [list \
170 sift1m.db \
171 landmark-dino-768-cosine.db \
172 agnews-mxbai-1024-euclidean.db \
173 ]
174
175 set nMinByte [expr 1024*1024]
176
177 # Check that all required databases are present in cwd
178 foreach f $lReq {
179 if {[file exists $f]==0 || [file size $f]<$nMinByte} {
180 error "missing required db file \"$f\""
181 }
182 }
183
184 open_db sift1m.db
185 build_nearest_if_required
186 release_test_one lRep SIFT1M "nbucket 1024 codesize 16 opq 0" {
187 1 1 16
188 100 1 16
189 1 1 48
190 100 1 48
191 }
192 release_test_one lRep SIFT1M "nbucket 0 codesize 16 opq 0" {
193 1 1 16
194 100 1 16
195 }
196 release_test_one lRep SIFT1M "nbucket 1024 codesize 0 opq 0" {
197 1 1 16
198 1 1 48
199 }
200
201 open_db landmark-dino-768-cosine.db
202 build_nearest_if_required
203 release_test_one lRep LANDMARK "nbucket 1024 codesize 48 opq 1" {
204 1 1 16
205 100 1 48
206 }
207
208 open_db agnews-mxbai-1024-euclidean.db
209 build_nearest_if_required
210 release_test_one lRep AGNEWS "nbucket 1024 codesize 32 opq 1" {
211 1 1 16
212 100 1 48
213 }
214
215 foreach ln $lRep { puts $ln }
216
217 set fd [open vec1.release.txt a+]
218 puts $fd "--------------------------------------------------------------"
219 foreach ln $lRep { puts $fd $ln }
220 close $fd
221}
222
223proc format_cycles {c} {
224 if {$c>(1000*1000*1000)} {
225 set ret "[format %.2f [expr $c/1000000000.0]]G"
226 } elseif {$c>(10*1000000)} {
227 set ret "[format %d [expr $c/1000000]]M"
228 } elseif {$c>(1000000)} {
229 set ret "[format %.2f [expr $c/1000000.0]]M"
230 } elseif {$c>(10*1000)} {
231 set ret "[format %d [expr $c/1000]]K"
232 } elseif {$c>1000} {
233 set ret "[format %.2f [expr $c/1000.0]]K"
234 } else {
235 set ret $c
236 }
237
238 return $ret
239}
240
241# Read the qprofile information for table "v1" from eponymous virtual
242# table vec1cat. Print a report to stdout based on the values read.
243#
244proc print_query_timings {} {
245
246 set lTopic [list]
247 db eval {
248 SELECT fullkey, value FROM json_tree(
249 (SELECT qprofile FROM vec1cat WHERE name='v1')
250 ) WHERE type='integer';
251 } {
252 if {$value>0} {
253 set key [string range $fullkey 2 end]
254 set A($key) $value
255
256 foreach {topic field} [split $key .] {
257 if {$field=="cnt" && $topic!="total"} { lappend lTopic $topic }
258 }
259 }
260 }
261
262 set nTotal $A(total.cycle);
263 set total_percent 0.0
264 set total_cycle 0
265 foreach name $lTopic {
266 set cnt $A(${name}.cnt)
267 set cycle $A(${name}.cycle)
268
269 set percent [expr (100.0 * $cycle) / $nTotal]
270 set total_percent [expr $total_percent + $percent]
271 set total_cycle [expr $total_cycle + $cycle]
272 set c [format_cycles $cycle]
273 puts "[format {% -12s%8s%6.2f%%} $name: $c $percent] ($cnt)"
274 }
275
276 set c [format_cycles $total_cycle]
277 puts "[format {% -12s%8s%6.2f%%} "total:" $c $total_percent]"
278}
279
280
281# Argument $t is some number of microseconds. Return a string making
282# this easy for humans to read - e.g. "123us" or "12.1ms".
283#
284proc format_us {t} {
285 set ret "${t}us"
286 if {$t>(10*1000000)} {
287 set ret "[format %.1f [expr $t/1000000.0]]s"
288 } elseif {$t>1000000} {
289 set ret "[format %.2f [expr $t/1000000.0]]s"
290 } elseif {$t>100000} {
291 set ret "[format %d [expr $t/1000]]ms"
292 } elseif {$t>10000} {
293 set ret "[format %.1f [expr $t/1000.0]]ms"
294 } elseif {$t>1000} {
295 set ret "[format %.2f [expr $t/1000.0]]ms"
296 } else {
297 set ret "${t}us"
298 }
299 return $ret
300}
301
302# Add commas to integer argument $i to make it easier to read.
303# e.g. 12345 -> "12,345"
304#
305proc format_int {i} {
306 set ret [list]
307 while {$i>0} {
308 if {$i>=1000} {
309 set ret [concat [format %.3d [expr $i % 1000]] $ret]
310 } else {
311 set ret [concat $i $ret]
312 }
313 set i [expr $i / 1000]
314 }
315 join $ret ,
316}
317
318proc my_time {caption script} {
319 puts -nonewline "$caption..."
320 flush stdout
321 set t [uplevel [list time $script]]
322 set t [lindex $t 0]
323
324 puts " [format_us $t]"
325
326 return $t
327}
328
329
330# Check that the __meta__ table looks ok. This command checks that there
331# are "train", "test", "neighbors" and "distances" tables, with types
332# float32, float32, int64 and float64, respectively, in the db. If not,
333# it prints out and error and exits.
334#
335proc check_db_looks_ok {} {
336 db eval {
337 WITH expect(nm, tp) AS (
338 SELECT 'train', 'float32' UNION ALL
339 SELECT 'test', 'float32' UNION ALL
340 SELECT 'neighbors', 'int64' UNION ALL
341 SELECT 'neighbors', 'int32'
342 ),
343 have(nm, tp) AS (
344 SELECT table_name, dtype
345 FROM __meta__
346 WHERE table_name IN ('train', 'test', 'neighbors')
347 )
348
349 SELECT (count(*)==3) as 'ok' FROM have WHERE (nm, tp) IN (
350 SELECT nm, tp FROM expect
351 );
352 } {
353 if {$ok==0} {
354 puts stderr "database does not look right. bailing out..."
355 exit -1
356 }
357 }
358}
359
360proc get_distance_function {} {
361 set dm [db one {SELECT value FROM meta WHERE field='distance'}]
362
363 set f(cosine) vec1_cos_distance
364 set f(angular) vec1_cos_distance
365 set f(euclidean) vec1_l2_distance
366 set f(normalized) vec1_cos_distance
367
368 if {[info exists f($dm)]==0} {
369 puts "Unrecognized distance metric: $dm"
370 exit 1
371 }
372 return $f($dm)
373}
374
375# Output a summary of the db for the user to read.
376#
377proc summarize_db {} {
378 set nQuery [db one {SELECT count(*) FROM test}]
379 set nVector [db one {SELECT count(*) FROM train}]
380 set nDim [db one {SELECT length(vec)/4 FROM train LIMIT 1}]
381 set dm [db one {SELECT 'dist=' || value FROM meta WHERE field='distance'}]
382 set cmp "$dm -> [get_distance_function]"
383 puts "Test is $nQuery queries against $nVector ${nDim}-d vectors ($cmp)"
384}
385
386proc vec_to_json_i64 {blob} {
387 binary scan $blob w* L
388 set ret "\[[join $L ,]\]"
389 return $ret
390}
391proc vec_to_json_i32 {blob} {
392 binary scan $blob i* L
393 set ret "\[[join $L ,]\]"
394 return $ret
395}
396
397proc myvar {var} {
398 upvar $var v
399 if {[info exists v]==0} { return "" }
400 return $v
401}
402
403proc print_report {} {
404 global T
405 global C
406
407 proc vkey_cmp {lhs rhs} {
408 foreach {lr lp} [split $lhs ,] {}
409 foreach {rr rp} [split $rhs ,] {}
410
411 if {$rr==$lr} {
412 if {$lp<$rp} { return -1 }
413 if {$lp>$rp} { return +1 }
414 }
415 return [expr $rr - $lr]
416 }
417
418 foreach k [array names T qps*] {
419 foreach {q recall nprobe k} [split $k ,] {}
420 set RECALL($recall) 1
421 set V($recall,$nprobe) 1
422 set H($k) 1
423 }
424
425 if {$C(--report)==""} {
426 set fd stdout
427 } else {
428 set fd [open $C(--report) a]
429 }
430
431 set nVector [format_int [db one {SELECT count(*) FROM train}]]
432 set nSample [format_int $T(nTrain)]
433 set nDim [db one {SELECT length(vec)/4 FROM train LIMIT 1}]
434 set zDataset [file tail $C(dbname)]
435 regsub {\..*} $zDataset {} zDataset
436
437 puts $fd "<!-- Report starts here!!! -->"
438
439 puts $fd "<h1>Dataset: $zDataset ($nVector ${nDim}d vectors)</h1>"
440 puts $fd "<table striped=1>"
441 puts $fd "<tr><th>Parameter<th>Value"
442 puts $fd "<tr><td>Vec1 Version<td>[db one {SELECT vec1_info()}]"
443 puts $fd "<tr><td>Index Parameters<td>$T(spec)"
444 puts $fd "<tr><td>Training time<td>[format_us $T(train)] ($nSample samples, $C(--nthread) threads)"
445 puts $fd "<tr><td>Build time<td>[format_us $T(build)] ($C(--nthread) threads)"
446 puts $fd "</table>"
447 puts $fd ""
448
449 foreach r [lsort -integer [array names RECALL]] {
450 puts $fd "<p>Recall@$r results:"
451 puts $fd ""
452 puts $fd "<table striped=1>"
453
454 catch { array unset K }
455 catch { array unset N }
456 foreach key [array names T qps*] {
457 foreach {q recall nprobe k} [split $key ,] {}
458 if {$r==$recall} {
459 set K($k) 1
460 set N($nprobe) 1
461 }
462 }
463
464 puts -nonewline $fd " <tr><th>"
465 foreach k [lsort -integer [array names K]] {
466 puts -nonewline $fd "<th colspan=2>K=$k"
467 }
468 puts $fd ""
469 puts $fd " <tr><th>nprobe"
470 foreach k [lsort -integer [array names K]] {
471 puts -nonewline $fd "<th>Recall<th>QPS"
472 }
473 puts $fd ""
474
475 foreach nprobe [lsort -integer [array names N]] {
476 puts -nonewline $fd " <tr><td>$nprobe"
477 foreach k [lsort -integer [array names K]] {
478 puts -nonewline $fd "<td>[format %.3f $T(recall,$r,$nprobe,$k)]"
479 puts -nonewline $fd "<td>$T(qps,$r,$nprobe,$k)"
480 }
481 puts $fd ""
482 }
483 puts $fd "</table>"
484 }
485
486 puts $fd "<!-- Report ends here!!! -->"
487 puts $fd ""
488 puts $fd ""
489
490 if {$fd!="stdout"} {
491 puts "Report output to $C(--report)"
492 close $fd
493 }
494}
495
496# See if the "nearest" table has been built yet. If not, create and
497# populate it now. It contains one row per test vector.
498#
499proc build_nearest_if_required {} {
500 set dm [db one {SELECT value FROM meta WHERE field='distance'}]
501
502 set fmt [db one {SELECT dtype FROM __meta__ WHERE table_name='neighbors'}]
503 if {$fmt=="int64"} {
504 db func ivec_to_json vec_to_json_i64
505 } else {
506 db func ivec_to_json vec_to_json_i32
507 }
508
509 set func [get_distance_function]
510 db eval BEGIN
511 if {[db one {SELECT count(*) FROM sqlite_schema WHERE name='nearest'}]==0} {
512 db eval "
513 CREATE TABLE nearest(
514 id INTEGER PRIMARY KEY, nn1 JSON, nn10 JSON, nn100 JSON
515 );
516
517 WITH groundtruth(qid, val, dist) AS (
518 SELECT q.id, j.value, $func (q.vec, b.vec)
519 FROM test q,
520 neighbors g,
521 json_each(ivec_to_json(g.vec)) j,
522 train b
523 WHERE q.id=g.id /* AND j.key<20 */ AND b.id=j.value
524 ),
525 ranked(qid, val, rank) AS (
526 SELECT qid, val, rank() OVER (
527 PARTITION BY qid ORDER BY dist
528 ) FROM groundtruth
529 )
530 INSERT INTO nearest
531 SELECT qid,
532 json_group_array(val) FILTER (WHERE rank=1),
533 json_group_array(val) FILTER (WHERE rank<=10),
534 json_group_array(val)
535 FROM ranked
536 GROUP BY qid
537 "
538 }
539 db eval COMMIT
540}
541
542proc test_build_index {lSpec} {
543 global C
544 global T
545
546 set func [get_distance_function]
547 set DIST(vec1_l2_distance) "\"L2\""
548 set DIST(vec1_cos_distance) "\"cos\""
549
550 set cols ""
551 set values ""
552 if {$C(--meta-data)==1} {
553 set cols ", m1"
554 set values ", 100"
555 } elseif {$C(--meta-data)==4} {
556 set cols ", m4"
557 set values ", 10000"
558 }
559
560 # Drop any old "v1" table that may exist. And create the new one.
561 #
562 db eval "
563 DROP TABLE IF EXISTS v1;
564 CREATE VIRTUAL TABLE v1 USING vec1(vector $cols);
565 SELECT vec1_config('nthread', $C(--nthread) );
566 INSERT INTO v1(rowid, vector $cols) SELECT id, vec $values FROM train;
567 "
568
569 if {$lSpec=="flat"} {
570 db eval "
571 INSERT INTO v1(cmd, arg)
572 VALUES('rebuild', '{index:\"flat\",distance: $DIST($func)}')
573 "
574 return
575 }
576
577 set pairs [list]
578 foreach {k v} $lSpec {
579 set val $v
580 if {[string is double $val]==0} {
581 set val "\"$v\""
582 }
583 lappend pairs "$k:$val"
584 }
585
586 # Unless the --index spec specifies a distance explicitly, use the
587 # distance metric of the dataset.
588 #
589 array set S $lSpec
590 if {[info exists S(distance)]==0} {
591 lappend pairs "distance:$DIST($func)"
592 }
593 set showspec "{[join $pairs {, }]}"
594 lappend pairs "svd_verify: $C(--svd-verify)"
595 lappend pairs "progress: \"myprogress\""
596 lappend pairs "profile: \"myprofile\""
597 set spec "{[join $pairs {, }]}"
598
599 # Command to handle vec1_train() progress callbacks.
600 #
601 unset -nocomplain ::myprogressms
602 proc myprogress {percent msg} {
603 catch {
604 if {[info exists ::myprogressms]==0} {
605 set ::myprogressms [clock milli]
606 }
607 set ms [expr [clock milli] - $::myprogressms]
608 puts "${ms}ms: $percent%: $msg"
609 } xyz
610 }
611 db func myprogress myprogress
612
613 # Command to handle vec1_train() profile callbacks.
614 #
615 proc myprofile {p} {
616 puts "profile: $p"
617 }
618 db func myprofile myprofile
619
620 # Check if a "learn" table exists. If it does not, use data from "train"
621 # to train the model.
622 #
623 if {[db one {SELECT count(*) FROM sqlite_schema WHERE name='learn'}]==0} {
624 set learn "train"
625 } else {
626 set learn "learn"
627 }
628 set nTotal [db one "SELECT count(*) FROM $learn"]
629 set nTrain [expr {$nTotal > $C(--max-train) ? $C(--max-train) : $nTotal}]
630
631 set caption "$C(--train-function)($spec) on $nTrain/$nTotal \"$learn\" rows"
632
633 set T(nTrain) $nTrain
634 set T(spec) $showspec
635 set T(train) [my_time "Training: $caption" {
636 puts ""
637 set model [db one [subst {
638 SELECT $C(--train-function)(vec, '$spec') FROM $learn
639 WHERE (
640 (abs(random()) / 9223372036854775807.0) * $nTotal <= $nTrain
641 )
642 }]]
643 }]
644
645 set T(build) [my_time "Building index" {
646 db eval {
647 INSERT INTO v1(cmd, vector) VALUES('rebuild', $model);
648 }
649 }]
650}
651
652proc test_query_index {K {recall 1} {nprobe 0.05} } {
653 global T
654 global C
655
656 set nMmap [db one { PRAGMA mmap_size = 20000000000 }]
657 puts "Using [expr ${nMmap}/(1024*1024)]MB mmap region"
658 db eval {
659 PRAGMA synchronous = off;
660 SELECT rowid FROM v1 LIMIT 1;
661 SELECT vec1_config('nprobe', $nprobe);
662 }
663
664 set func [get_distance_function]
665
666 set nn "nn$recall"
667 set sql1 [subst "
668 SELECT vec, $nn AS nn, test.id AS id
669 FROM test JOIN nearest ON (test.id=nearest.id)
670 "]
671
672 #set spec "{K:$K,nprobe:$nprobe,nprobe_slack:0.9}"
673 set spec "{K:$K,nprobe:$nprobe}"
674
675 set tail ""
676 if {$C(--meta-data)==1} {
677 append tail "WHERE m1=100"
678 } elseif {$C(--meta-data)==4} {
679 append tail "WHERE m4=10000"
680 }
681
682 if {$K!=$recall} {
683 append tail [subst -novar {
684 ORDER BY [set func] ($vec, v1.vector)
685 LIMIT [set recall]}]
686 }
687
688 set sql2 [subst -novar {
689 SELECT coalesce(sum( ans IN (SELECT value FROM json_each($nn) )), 0) FROM (
690 SELECT v1.rowid AS ans
691 FROM v1($vec, $spec) [set tail]
692 )
693 }]
694
695 set nQuery [db one {SELECT count(*) FROM test}]
696 set caption "Testing $nQuery recall@$recall queries $spec"
697
698 set s 0
699 set t [my_time $caption {
700 set nQuery 0
701 db eval $sql1 {
702 set nGood [db one $sql2]
703 # if {$nGood!=$recall} { puts "id=$id nGood=$nGood" }
704 incr s $nGood
705 incr nQuery
706 }
707 puts -nonewline "($s / [expr $recall*$nQuery]) "
708 }]
709
710 set qps [expr ($nQuery*1000000 / $t)]
711 set T(qps,$recall,$nprobe,$K) $qps
712 set T(recall,$recall,$nprobe,$K) [expr (($s * 1.0) / ($nQuery * $recall))]
713
714 return $s
715}
716
717main
718exit
719