RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Geometry, physics and speed

Vector search

Nearest neighbours by cosine similarity beside exact search by spread, on the CPU and the GPU.

import 'package:riptide_vector_search/riptide_vector_search.ray';
import 'package:riptide_vector_search/model.ray';
26 classes135 functions and methods171 of 320 documented

Overview

Vector search, two ways: nearest-neighbour search over vectors by cosine similarity (dot products over square-root lengths, f32) beside Wildberger's spread (exact, by quadrance and spread: integer dot products, compared exactly), on the CPU's matrix unit and on the graphics chip, measured live on the device, with what each way finds. The app hosts it.

The two ways

ClassicRational / geometric
Similaritycos θ = a·b / (\|a\|\|b\|)spread s = 1 − (a·b)² / (Q(a)Q(b)), Q(v) = v·v, with the sign of a·b kept
Index timeevery vector scaled to length 1 (a square root each), f32every vector scaled to its own ±127 (int8) or ±32767 (int16) and rounded; Q(v) an exact integer, 1/Q in f64
Searchf32 dot products (FMOPA on the matrix unit, GemmF32 on the GPU) are the cosines; top 10exact integer dot products (SMOPA int8 → int32, int16 → int64; GemmI32, int16 as four 8-bit-limb passes); key sign(x)·x²/Q; top 10
Orderby f32 values; rounding decides near tiesexact: key₁ > key₂ ⇔ x₁²Q₂ > x₂²Q₁, filtered in f64 (Shewchuk 1997), settled in big integers within 2⁻⁵⁰; ties to the smaller id

For a·b ≥ 0 the spread key orders exactly as cosine does (spread is one minus the cross); the sign handles opposite directions, which spread alone cannot see. Q(a) is the same for every candidate and drops out. Spread does not see a positive scale, so per-vector integer scaling changes the vectors only by rounding.

Ranking, both ways, the same shape: one sweep over the n × q dot-product matrix in memory order, one bounded heap per query, and a fast reject against the heap's worst. For spread the reject compares the magnitude x²·(1/Q) (never below the signed key) with a threshold lowered by 2⁻⁴⁹ relative, so it is exact-safe; anything closer is compared in integers. (The JIT made a conditional on a double cost 8× the rest of the loop; the magnitude test avoids it.)

Data

  • Captions as YouTube gives them (so "Maxwell" finds the maxel lectures: the captions hear "maxel" as "Maxwell").
  • The vectorizer is latent semantic analysis (Deerwester et al. JASIS 41(6), 1990), not a neural embedding model (none ships in the repo): sublinear tf-idf w = (1 + ln c)·ln(N/df) (Manning, Raghavan and Schütze 2008, §6.2–6.4) over the 9,570 words in at least two passages, rows scaled to length 1, truncated SVD of rank 256 (randomized, Halko, Martinsson and Tropp 2011; riptide_numerics_cpu randomizedSvd, 2.1 s on the Mac). Each word's 256 numbers ship as int16 with an f32 scale; a passage or a typed query is the tf-idf-weighted sum of its words' vectors. Both ways search these same vectors. (A hashed tf-idf of 256 or 1,024 buckets was tried first and dropped: its top 10 overlapped exact tf-idf's by only 23 % and 59 %.)
  • Synthetic sets (synthetic.ray): clustered vectors, d = 128, 64 bell-shaped centres plus noise, from SplitMix64 (seed 1): the same numbers on every machine. Every 64th vector is 3 × the one before it, an exact tie. 32 queries near random members. Sizes 4,096 to 262,144.

Functions and constants

Functions

tokenizefunction
List<String> tokenize(String text)

Lower-case runs of ASCII letters and digits; apostrophes join ("don't" → "dont"); stop words and one-letter tokens dropped.

spreadOffunction
double spreadOf(int x, int qa, int qb)

S = 1 − x²/(Q(a)Q(b)), computed exactly in integers and rounded once to f64 for display (1 when a vector is 0).

Future<T> isolateWorker<T>(T Function() work)

The default worker: Isolate.run, so a 262,144-vector search never blocks a frame. A browser build can't spawn an isolate, so on the web the work runs on the page's thread after the current frame.

inlineWorkerfunction
Future<T> inlineWorker<T>(T Function() work)

Runs work on this isolate.

List<List<int>> cosineTopKAll(Float32List scores, int n, int queries, int k)

The classic ranking: cosine similarity, largest first; ties (equal floats) to the smaller id. The vectors were scaled to length 1 when the index was built (one square root a vector), so the cosine is the f32 dot product itself: scores holds n × queries of them row-major (doc i, query j at i·queries + j). One sweep over the rows, one heap per query, a value at or below a full heap's worst dismissed at once (the same shape as SpreadRanker.topKAll).

topKFloatfunction
List<int> topKFloat(List<double> values, int n, int k)

The k largest of values (first n), largest first, ties to the smaller index.

recallAtfunction
double recallAt(List<int> found, List<int> truth, int k)

Recall@k: the share of truth's first k that found's first k contains (order inside the k not counted).

meanRecallfunction
double meanRecall(List<List<int>> found, List<List<int>> truth, int k)

The mean recall@k over queries.

int orderDifferences(List<List<int>> a, List<List<int>> b)

How many queries' ordered result lists differ between two searches (the same set in another order counts).

List<List<int>> exactCosineTopK(VectorSet docs, VectorSet queries, int k)

The exact answer: for each query the k largest a·b / (|a||b|) in f64 arithmetic on the stored f32 numbers (plain loops, one root a vector), ties to the smaller id.

medianMicrosfunction
(double, int) medianMicros(void Function() run, {int minMicros = 30000, int maxRuns = 40})

The median time of run in microseconds: one warm-up, then at least three runs and until minMicros have passed (at most maxRuns).

classicDotsfunction
Float32List classicDots(SearchData s)

The f32 dot products of the unit vectors (cosines) on the matrix unit (n × q, row-major).

exactDotsfunction
List<int> exactDots(SearchData s, VectorWidth w)

The exact integer dot products D·Aᵀ on the matrix unit (Int32List for int8, Int64List for int16).

LaneRun runClassicCpu(SearchData s, {int minMicros = 30000})

The classic CPU lane: f32 dots on the matrix unit, cosine, top k. minMicros is the timing budget.

runExactCpufunction
LaneRun runExactCpu(SearchData s, VectorWidth w, {int minMicros = 30000})

An exact CPU lane: integer dots on the matrix unit, spread ranked exactly, top k.

rankGpufunction
LaneRun rankGpu(SearchData s, SearchLane lane, GpuDots g)

Ranks a GPU lane's dot products (in a worker in the app) and measures it.

tieReportfunction
TieReport tieReport(SearchData s, Float32List f32Dots, List<int> dots8, List<int> dots16)

Looks at every tied pair of s for every query, from the lanes' dot products.

runCpuRoundfunction
CpuSearchRound runCpuRound(SearchData data, {int minMicros = 30000, int reorderQueries = 4})

The CPU lanes of a round on data (pure work: run it in a worker isolate).

clusteredSetfunction
VectorSet clusteredSet(int n, int d, {int clusters = 64, double noise = 0.45, int seed = 1})

A deterministic clustered set: clusters centres drawn bell-shaped in d dimensions, each vector a centre plus noise × a bell-shaped offset; every tieEvery-th vector 3 × its predecessor. The same seed gives the same numbers on every machine (SplitMix64, + − × only).

queriesNearfunction
VectorSet queriesNear(VectorSet data, int count, {double noise = 0.3, int seed = 2})

count queries near the set: a random member plus noise × a bell-shaped offset (never a member itself).

tiedPairsfunction
List<(int, int)> tiedPairs(int n)

The tied pairs of a clusteredSet of n vectors: (i − 1, i) for every i ≡ −1 (mod tieEvery).

laneColorfunction
int laneColor(SearchLane l)

Classic in the classic method colour (rose), spread in Cayley green (LabCanvasColorTokens.methods, as everywhere in the Lab); the int8 lanes lighter, GPU lanes their CPU twin's colour, dimmer.

laneNamefunction
String laneName(SearchLane l)

A lane's short name.

PreparedCorpus prepareCorpus(LectureCorpus corpus)

Builds the corpus's vectors and finds the example queries (pure work: run it in a worker).

durationfunction
String duration(double micros)

"245 µs" or "1.01 ms".

Constants and variables

stopwordsconstant
const stopwords

The words the vectorizer skips (common English function words and caption filler).

const exampleQueries

Queries to pick from (and the corpus's recall sample): topics of the lectures and talks.

searchSizesconstant
const searchSizes = [4096, 16384, 65536, 262144]

Synthetic set sizes (d = 128, 32 queries, k = 10).

tieEveryconstant
const tieEvery = 64

Every tieEvery-th vector of a synthetic set is 3 × the one before it: the same direction, so cosine and spread tie exactly in exact arithmetic. f32 rounds 3x, and every lane then has to decide what to do with the tie.

seriesColorsconstant
const seriesColors

The colours of the six lecture collections on the map (quiet blues and violets; rose and green are the methods').

Typedefs

typedef SearchWorker = Future<T> Function<T>(T Function() work)

Runs work somewhere: a worker isolate in the app (isolateWorker), right here in tests (inlineWorker).

Classes

class

Lecture

final class Lecture

One lecture of the corpus.

Constructors

Lectureconstructor
const Lecture(this.title, this.series, this.videoId)

Properties

titlefield
final String title
seriesfield
final int series

Which collection it came from (LectureCorpus.seriesNames).

videoIdfield
final String videoId
class

Passage

final class Passage

A passage: about two minutes of one lecture, with its words counted.

Constructors

Passageconstructor
const Passage(this.lecture, this.start, this.snippet, this.terms, this.counts)

Properties

lecturefield
final int lecture
startfield
final int start

Where it starts in the video, seconds.

snippetfield
final String snippet

Its first words, for the result list.

termsfield
final Uint16List terms

Vocabulary indices and how many times each occurs.

countsfield
final Uint8List counts
final class LectureCorpus

The lecture corpus that ships with the lab: passages of lecture transcripts as word counts over a fixed vocabulary, and the vectorizer that turns any passage or typed query into a dims-number vector.

Row t of V is word t's vector. A passage's or a query's vector is the tf-idf-weighted sum of its words' vectors, x ↦ xV. No neural embedding model: none ships in the repo, and this one can be read off the page.

Binary format (little-endian), encode and decode: RVS2, then u32 lectures, vocabulary, passages, dims; each lecture u8 series, u16-prefixed UTF-8 title and video id; each word u8-prefixed UTF-8, u32 df, f32 scale and dims × i16 (its vector = scale × the integers / 32767); each passage u16 lecture, u32 start, u16-prefixed UTF-8 snippet, u16 term count, then (u16 term, u8 count) pairs; finally 2 × dims f32: the two display directions (principal components of the passage vectors, for the map).

Constructors

LectureCorpusconstructor
LectureCorpus({required this.lectures, required this.vocabulary, required this.df, required this.wordScale, required this.wordInts, required this.passages, required this.dims, required this.display})

Static

seriesNamesconstant
static const seriesNames
clockstaticmethod
static String clock(int seconds)

"12:34" or "1:02:03".

decodestaticmethod
static LectureCorpus decode(ByteData data)

Properties

final List<Lecture> lectures
final List<String> vocabulary
dffield
final Uint32List df
final Float32List wordScale

The word vectors: word t's entry k is wordScalet · wordInts[t·dims + k] / 32767.

final Int16List wordInts
final List<Passage> passages
dimsfield
final int dims
displayfield
final Float32List display

Two directions in vector space (2 × dims) the map projects onto.

ngetter
int get n

Methods

knowsmethod
bool knows(String word)

Whether word is in the vocabulary.

idfmethod
double idf(int term)

The inverse document frequency ln(N / df) of a word.

weightmethod
double weight(int term, int count)

The tf-idf weight of count occurrences of term.

vectorsmethod
VectorSet vectors()

Every passage as a vector (n × dims f32).

querymethod
({VectorSet vector, List<String> known, List<String> unknown}) query(String text)

A typed query as a vector, and the words of it the corpus knows (the rest are not in the vocabulary and add nothing).

sharedmethod
List<String> shared(int i, String q)

The words of q that passage i contains (LSA also finds passages that share none: related words).

mapPointmethod
(double, double) mapPoint(Float32List v, int offset)

Where passage i sits on the map: its vector projected onto the two display directions (unscaled).

encodemethod
Uint8List encode()
class

Hit

final class Hit

One found passage with what each way measured for it.

Constructors

Hitconstructor
const Hit(this.passage, {required this.cosine, required this.spread, required this.opposite})

Properties

passagefield
final int passage
cosinefield
final double cosine

Cos θ from the f32 unit vectors (classic).

spreadfield
final double spread

S = 1 − (a·b)²/(Q(a)Q(b)) of the integer vectors, exact, rounded only for display.

final bool opposite

A·b < 0: the opposite side (spread alone does not tell).

final class FindResult

One typed query both ways.

Constructors

FindResultconstructor
const FindResult({required this.text, required this.known, required this.unknown, required this.classic, required this.rational, required this.width, required this.truth, required this.classicMicros, required this.rationalMicros, required this.classicRecall, required this.rationalRecall, this.mapX = 0, this.mapY = 0, this.example})

Properties

textfield
final String text
mapXfield
final double mapX

Where the query sits on the map (its unit vector projected like the passages).

mapYfield
final double mapY

Where the query sits on the map (its unit vector projected like the passages).

examplefield
final int? example

The passage the query was made from ("more like this"), or null for typed words.

knownfield
final List<String> known
unknownfield
final List<String> unknown
classicfield
final List<Hit> classic
final List<Hit> rational
widthfield
final VectorWidth width
truthfield
final List<int> truth

The exact answer (f64 cosine on the stored vectors).

final double classicMicros

Median time of one search over the whole corpus: dot products (matrix unit) and the top k.

final double rationalMicros

Median time of one search over the whole corpus: dot products (matrix unit) and the top k.

final double classicRecall
final double rationalRecall
emptygetter
bool get empty
int get samePlaces

Passages both ways found in the same place.

Methods

withTimesmethod
FindResult withTimes(double classic, double rational)

The same result with the measured times replaced (goldens: pixels must not depend on a stopwatch).

final class CorpusSearch

The lecture corpus as a searchable set: vectors built once (LSA), indexed both ways.

Constructors

CorpusSearchconstructor
CorpusSearch(this.corpus)

Properties

corpusfield
final LectureCorpus corpus
vectorsfield
final VectorSet vectors
basefield
late final SearchData base
late final Float32List mapPoints

The map position of every passage (projection onto the corpus's two display directions).

Methods

findmethod
FindResult find(String text, {int k = 10, VectorWidth width = VectorWidth.b16, int minMicros = 3000})

text both ways, top k, the rational way at width. minMicros is the timing budget per way.

findLikemethod
FindResult findLike(int i, {int k = 10, VectorWidth width = VectorWidth.b16, int minMicros = 3000})

"More like this": passage i's own vector as the query (it finds itself first).

examplesmethod
SearchData examples({int k = 10})

The example queries in one block (the corpus row of the race and its recall).

final class IvfIndex

An inverted-file index (IVF; Jégou, Douze and Schmid, "Product quantization for nearest neighbor search", IEEE TPAMI 33(1), 2011, §IV): the vectors split into lists groups around centres found by a few rounds of k-means; a query looks only in the IvfSearch.probe groups whose centres are nearest.

  • Classic (IvfIndex.classic): spherical k-means on the unit f32 vectors; a centre is its members' unit vectors summed and scaled to length 1 (a root a centre); nearest by cosine.
  • Spread (IvfIndex.spread): the same on the int16 vectors with no root anywhere: a vector joins the centre of largest spread key sign(v·c)(v·c)²/Q(c), exactly; a centre is its members summed in integers and rescaled to int16 (spread does not see the scale).

Both start from the same members (chosen by seed) and run the same number of rounds.

Static

classicstaticmethod
static IvfIndex classic(SearchData s, int lists, {int rounds = 4, int seed = 3})

Spherical k-means on the unit vectors of s.

spreadstaticmethod
static IvfIndex spread(SearchData s, int lists, {int rounds = 4, int seed = 3})

k-means by spread on the int16 vectors of s: integers throughout, no root.

Properties

exactfield
final bool exact
listsfield
final int lists
dfield
final int d
membersfield
final List<Int32List> members

The ids in each group.

final Float32List? unitCentres

Classic: lists × d unit f32 centres.

final Int16List? intCentres

Spread: lists × d int16 centres and their exact quadrances.

final Int64List? centreQuadrance
final double buildMicros

How long building took (k-means and grouping), microseconds.

Methods

searchmethod
IvfSearch search(SearchData s, int probe)

Every query of s through the index, looking in the probe nearest groups.

final class IvfSearch

What an index search found and what it cost.

Constructors

IvfSearchconstructor
const IvfSearch({required this.probe, required this.results, required this.recall, required this.scannedShare, required this.microsPerQuery})

Properties

probefield
final int probe
resultsfield
final List<List<int>> results
recallfield
final double recall

Mean recall@k against the exact answer (the whole set, f64 cosine).

final double scannedShare

The share of the set each query looked at.

final double microsPerQuery
enum LaneState

Where a lane is in the current round.

Values

waitingvalue
waiting
runningvalue
running
donevalue
done
unavailable
final class SearchRace

The vector-search race: the same queries over the same set on the CPU's matrix unit and the graphics chip, classic f32 cosine and exact int8 / int16 spread, each timed and scored against the exact answer. One round at a time, the lanes in turn (never two at once).

Constructors

SearchRaceconstructor
SearchRace({Future<VectorGpu?> Function()? gpu, SearchWorker? worker, SearchWorker? compare, this.minMicros = 30000})

Properties

int minMicros

The timing budget per CPU lane.

nfield
int n

The set size of the next round.

void Function()? onChange
statefield
final Map<SearchLane, LaneState> state
resultsfield
final Map<SearchLane, LaneRun> results
historyfield
final Map<SearchLane, Map<int, LaneRun>> history

Every result so far, by lane, then size (the chart).

lastfield
CpuSearchRound? last

The last round's tie report, reorder check and data (null before a round).

IvfIndex? classicIndex

The index, both ways, on the last round's set (null until built).

IvfIndex? spreadIndex

The index, both ways, on the last round's set (null until built).

IvfSearch? classicIvf
IvfSearch? spreadIvf
probefield
int probe
bool indexing
gpufield
VectorGpu? gpu
String? gpuMissing
nativefield
bool? native
int features
busyfield
bool busy
roundsfield
int rounds
final List<int> sweepQueue
largestgetter
int get largest

The largest size this device runs: 262,144 with a matrix unit, 16,384 on a portable loop.

listsgetter
int get lists

Methods

resetmethod
void reset()
sweepmethod
void sweep()
roundmethod
Future<void> round()

One round on a synthetic set of n vectors: the CPU lanes in a worker, then the GPU lanes. Nothing while a round runs.

Future<void> buildIndex()

Builds the index both ways on the last round's set and searches it with probe groups.

Future<void> searchIndex()

Searches the built index again with probe groups.

speedupmethod
double? speedup(SearchLane a, SearchLane b)

How many times faster lane a was than lane b in the last round (null until both ran).

int? crossChipReorders(SearchLane cpu, SearchLane gpuLane)

Queries whose ordered results differ between the CPU and GPU lanes of one kind (null until both ran).

final class SpreadRanker

Exact ranking by spread.

For a query a and a vector b, Wildberger's spread is s(a, b) = 1 − (a·b)² / (Q(a) Q(b)), Q(v) = v·v. It is one minus the cross: the smaller the spread, the closer the directions. Spread forgets the sign of a·b (b and −b have the same spread to a), so the ranking key keeps it:

key(b) = sign(a·b) · (a·b)² / Q(b) (Q(a) is the same for every b, so it drops out)

For a·b ≥ 0 a larger key is a smaller spread and a larger cos θ: the same order as cosine similarity. With integer vectors a·b and Q(b) are exact integers, and two keys compare exactly by cross-multiplying: x₁²·Q₂ against x₂²·Q₁. Those products reach 2¹¹⁶ for 16-bit vectors, past 64 bits, so the comparison is filtered (Shewchuk 1997): f64 decides when the two sides differ by more than its worst rounding, and only near-ties are settled in arbitrary-precision integers (exactFallbacks counts them). Either way the answer is exact.

Ties (equal keys, exactly) go to the smaller id, so an order is the same on every machine.

Static

inverseQuadrancesstaticmethod
static Float64List inverseQuadrances(Int64List q)

1/Q(b) in f64 for every b (0 for the zero vector). Precomputed once, like a classic index's norms.

Properties

int exactFallbacks

How many comparisons the f64 filter could not decide and were settled in big integers.

int comparisons

How many exact key comparisons were made (candidates the fast reject could not dismiss).

Methods

comparemethod
int compare(int x1, int q1, int x2, int q2)
0 when (x₁, q₁) ranks above (x₂, q₂), < 0 below, 0 when their keys are exactly equal.
topKAllmethod
List<List<int>> topKAll(List<int> dots, Int64List quadrance, int n, int queries, int k, {Float64List? inverseQuadrance})

The k best candidates for each of queries queries, best first (ties to the smaller id). dots holds n × queries exact a·b row-major (doc i, query j at i·queries + j), as the matrix unit writes C = D·Aᵀ; quadrance Q(b); inverseQuadrance 1/Q(b) in f64 (computed when not given).

One sweep over the rows (memory order), one heap per query. Per candidate the f64 key x·|x|·(1/Q) is formed, as cheap as reading a cosine, and dismissed when it lies below the heap's worst by more than f64's rounding could explain (2⁻⁴⁹ relative: exact-safe). Candidates closer than that are compared exactly (compare).

enum SearchLane

The lanes of a search: classic f32 cosine and exact integer spread, on the CPU's matrix unit and on the graphics chip; the integer lanes at 8 or 16 bits.

Values

cpuClassic(gpu: false, width: null)

Unit f32 vectors (scaled once at index time, a root each); f32 dot products on the matrix unit (FMOPA) are the cosines.

cpuExact8(gpu: false, width: VectorWidth.b8)

Int8 vectors, exact int32 dot products on the matrix unit (SMOPA), ranked by spread exactly.

cpuExact16(gpu: false, width: VectorWidth.b16)

Int16 vectors, exact int64 dot products (SMOPA), ranked by spread exactly.

gpuClassic(gpu: true, width: null)

F32 dot products on the graphics chip (GemmF32), cosine on the CPU.

gpuExact8(gpu: true, width: VectorWidth.b8)

Int8 vectors, exact int32 dot products on the graphics chip (GemmI32).

gpuExact16(gpu: true, width: VectorWidth.b16)

Int16 vectors as two 8-bit limbs, four exact GemmI32 passes combined in int64.

Constructors

SearchLaneconstructor
const SearchLane({required this.gpu, required this.width})

Properties

gpufield
final bool gpu
widthfield
final VectorWidth? width
exactgetter
bool get exact
final class SearchData

A set to search and the queries to search it with, with everything both ways precompute: the classic unit vectors (one root a vector) and the integer vectors with their exact quadrances (no root). truth is the exact answer: the top kTruth by cosine in f64 arithmetic on the f32 vectors.

Constructors

SearchDataconstructor
SearchData(this.docs, this.queries, {this.k = 10, this.ties = const []})
SearchData.withQueries(SearchData set, this.queries, {int? k})

New queries against the same set: everything precomputed for the set is shared, not redone.

Static

syntheticstaticmethod
static SearchData synthetic(int n, {int d = 128, int q = 32, int k = 10, int seed = 1})

A clustered synthetic set of n vectors in d dimensions with q queries near it (synthetic.ray).

Properties

docsfield
final VectorSet docs
queriesfield
final VectorSet queries
kfield
final int k
final VectorSet unitDocs

The classic index: every vector scaled to length 1 (one root each), so cosine is a dot product.

final VectorSet unitQueries

The classic index: every vector scaled to length 1 (one root each), so cosine is a dot product.

docs8field
final QuantizedSet docs8
docs16field
final QuantizedSet docs16
final QuantizedSet queries8
final QuantizedSet queries16
inverse8getter
Float64List get inverse8

1/Q(b) in f64 for the integer vectors (precomputed once; no root).

inverse16getter
Float64List get inverse16
tiesfield
final List<(int, int)> ties

Pairs of vectors that point exactly the same way (a vector and 3 × it).

truthfield
late final List<List<int>> truth
ngetter
int get n
dgetter
int get d
qgetter
int get q

Methods

inverseOfmethod
Float64List inverseOf(VectorWidth w)
docsOfmethod
QuantizedSet docsOf(VectorWidth w)
queriesOfmethod
QuantizedSet queriesOf(VectorWidth w)
queriesTmethod
Float32List queriesT()

The unit queries transposed (d × q, row-major): the B of C = D·B on the graphics chip.

Int32List queriesTInt(VectorWidth w)
class

LaneRun

final class LaneRun

One lane's measured search.

Constructors

LaneRunconstructor
LaneRun({required this.lane, required this.n, required this.d, required this.q, required this.dotMicros, required this.rankMicros, required this.runs, required this.results, required this.recall, this.endToEndMicros, this.passes = 1, this.fallbacks = 0, this.comparisons = 0})

Properties

lanefield
final SearchLane lane
nfield
final int n
dfield
final int d
qfield
final int q
final double dotMicros

Dot products for all q queries (median; GPU: kernel time), and ranking them (top k per query).

final double rankMicros

Dot products for all q queries (median; GPU: kernel time), and ranking them (top k per query).

runsfield
final int runs
final double? endToEndMicros

GPU: upload, dot products and read-back, once.

passesfield
final int passes

GPU dispatches a product takes (four for int16 limbs).

resultsfield
final List<List<int>> results

The ids found, best first, one list per query.

recallfield
final double recall

Mean recall@k against the exact answer.

final int fallbacks

Spread lanes: comparisons the f64 filter left to big integers, of all comparisons.

final int comparisons

Spread lanes: comparisons the f64 filter left to big integers, of all comparisons.

double get totalMicros
perQuerygetter
double get perQuery

Microseconds a query.

double get vectorsPerSecond

Vectors searched a second (n × q / total time).

class

GpuDots

final class GpuDots

What the graphics chip hands back: the dot products (f32, or exact integers) and how long they took.

Constructors

GpuDotsconstructor
const GpuDots({required this.micros, required this.runs, this.endToEndMicros, this.floats, this.ints, this.passes = 1})

Properties

microsfield
final double micros
runsfield
final int runs
final double? endToEndMicros
floatsfield
final Float32List? floats
intsfield
final List<int>? ints
passesfield
final int passes
abstract interface class VectorGpu

The graphics chip, as vector search needs it: C = D·B for n × d vectors D and a d × q block of queries B. The app implements it on riptide_numerics_gpu (GemmF32, GemmI32); tests use CpuStandInVectorGpu.

Properties

namegetter
String get name

Methods

classicmethod
Future<GpuDots> classic(Float32List docs, Float32List queriesT, int n, int d, int q)
exactmethod
Future<GpuDots> exact(Int32List docs, Int32List queriesT, int n, int d, int q, VectorWidth w)

Exact: int8 entries in one GemmI32 pass, int16 entries as two 8-bit limbs in four.

final class CpuStandInVectorGpu implements VectorGpu

A stand-in for the graphics chip on the CPU (tests): the answers a GPU must give, by plain loops, honestly timed. The f32 sums run in a different order from the matrix unit's (one running f32 sum), as a GPU's do.

Properties

namegetter
String get name

Methods

classicmethod
Future<GpuDots> classic(Float32List docs, Float32List queriesT, int n, int d, int q)
exactmethod
Future<GpuDots> exact(Int32List docs, Int32List queriesT, int n, int d, int q, VectorWidth w)
final class TieReport

What the exact tie pairs did: how often f32 cosine scored the two members of a tie differently (rounding chose the order), and how often the spread keys were exactly equal (the tie kept; the smaller id first, everywhere).

Constructors

TieReportconstructor
const TieReport({required this.pairs, required this.f32Split, required this.spreadEqual8, required this.spreadEqual16})

Properties

pairsfield
final int pairs

Tied pairs × queries looked at.

final int f32Split
final int spreadEqual8
final int spreadEqual16
final class CpuSearchRound

The CPU half of a round: the data, the three CPU lanes, the tie report, and whether another summation order (the stand-in's loop) reorders the classic results on the first few queries while the integers stay identical.

Constructors

CpuSearchRoundconstructor
CpuSearchRound({required this.data, required this.lanes, required this.ties, required this.reorderChecked, required this.classicReordered, required this.exactIdentical, required this.native, required this.features})

Properties

datafield
final SearchData data
lanesfield
final Map<SearchLane, LaneRun> lanes
tiesfield
final TieReport ties
final int reorderChecked

Queries compared against a plain-loop sum in another order; how many of them came back in another order (classic), and whether the integer dot products were bit for bit the same (exact).

final int classicReordered

Queries compared against a plain-loop sum in another order; how many of them came back in another order (classic), and whether the integer dot products were bit for bit the same (exact).

final bool exactIdentical
nativefield
final bool native
final int features
final class SplitMix

SplitMix64 (Steele, Lea and Flood, "Fast splittable pseudorandom number generators", OOPSLA 2014): the same numbers from the same seed on every machine, so a synthetic set is the same set everywhere.

Constructors

SplitMixconstructor
SplitMix(int seed)

Methods

nextmethod
int next()

The next 64 random bits.

double nextDouble()

Uniform in [0, 1): the top 53 bits over 2⁵³.

nextBellmethod
double nextBell()

Bell-shaped, mean 0, variance 1: four uniforms summed, centred, and scaled by the constant √3 (Irwin–Hall; no log or root at run time).

nextIntmethod
int nextInt(int n)

Uniform in [0, n).

final class VectorSet

N vectors of d numbers, row-major, as stored: f32. These are the "original" vectors; everything is measured against exact (f64) arithmetic on them.

Constructors

VectorSetconstructor
VectorSet(this.n, this.d, this.values)

Properties

nfield
final int n
dfield
final int d
valuesfield
final Float32List values

Methods

rowmethod
Float32List row(int i)

Row i as a view.

pickmethod
VectorSet pick(List<int> ids)

The rows ids, copied, as a new set.

unitmethod
VectorSet unit()

Every row scaled to length 1 (f64 arithmetic, stored in f32): what a classic index stores, so that the cosine is a plain dot product. One square root a vector, once.

normsmethod
Float32List norms()
v= √(v·v) for every row, computed in f64 and stored in f32: what a classic index precomputes (one root a

Vector).

enum VectorWidth

How many bits the integer vectors keep.

Values

b8value
b8(127)

Int8: |q| ≤ 127; dot products int8 → int32 on the matrix unit (exact while d < 2¹⁷).

b16value
b16(32767)

Int16: |q| ≤ 32767; dot products int16 → int64 (exact).

Constructors

VectorWidthconstructor
const VectorWidth(this.top)

Properties

topfield
final int top

The largest integer an entry may take.

labelgetter
String get label
final class QuantizedSet

Vectors as integers: each row scaled by its own positive factor so its largest entry is ±VectorWidth.top, then rounded. Spread (and cosine) do not see a positive scale, so the scale is dropped: only the rounding changes the vectors. Every row's quadrance Q(v) = v·v is an exact integer.

Static

ofstaticmethod
static QuantizedSet of(VectorSet v, VectorWidth width)

Properties

widthfield
final VectorWidth width
nfield
final int n
dfield
final int d
i8field
final Int8List? i8

The entries (one of the two, by width).

i16field
final Int16List? i16
final Int64List quadrance

Q(v) = Σ vₖ², exactly.

Methods

toInt32method
Int32List toInt32()

The entries as int32 (what the GPU kernel reads).

atmethod
int at(int i, int k)

Entry k of row i.

enum VectorMode

What the lab shows.

Values

findvalue
find

The lecture corpus: a typed (or picked) query, its nearest passages both ways on the map and in two lists.

racevalue
race

Speed and recall by set size: every lane on the CPU's matrix unit and the graphics chip.

ivfvalue
ivf

The inverted-file index both ways: recall against the share of the set each query looks at.

final class PreparedCorpus

The corpus, made searchable (a worker builds the vectors), and every example query already found.

Constructors

PreparedCorpusconstructor
const PreparedCorpus(this.search, this.tour)

Properties

searchfield
final CorpusSearch search
tourfield
final List<FindResult> tour
class VectorSearchScene extends CalcScene

Vector search, two ways: nearest neighbours by cosine (f32) beside spread (exact integers), on the lecture corpus and on synthetic sets, measured on this device.

Constructors

VectorSearchScene({Future<LectureCorpus> Function()? corpus, Future<VectorGpu?> Function()? gpu, SearchWorker? worker, SearchWorker? compare})

Properties

racefield
final SearchRace race
PreparedCorpus? prepared
String? corpusError
queryfield
String query

The query in the lab and what it found.

foundfield
FindResult? found
widthfield
VectorWidth width
int? selected

The rank selected in the lists (its passage is highlighted and its first words shown), or null.

tourAtfield
int tourAt

The tile's tour through the example queries.

modegetter
VectorMode get mode
modesetter
set mode(VectorMode m)
loadinggetter
bool get loading
searchgetter
CorpusSearch? get search
MathsLabel get classicLabel
MathsLabel get finiteLabel
bool get showsClassic
bool get showsRational
lanesgetter
List<SearchLane> get lanes

Lanes the way shows.

showngetter
FindResult? get shown

What the map and the lists show now: the lab's query, or the tile's tour stop.

isIdlegetter
bool get isIdle
hotspotsgetter
List<StageHotspot> get hotspots

Methods

settlemethod
void settle()

Finishes the beams' grow-in now (Reduce Motion, still frames: goldens, screenshots).

Future<void> ensureCorpus()

Loads and prepares the corpus once (the first frame that needs it).

findTextmethod
void findText(String text)

Searches the corpus for text both ways (the panel's field and picks).

findLikemethod
void findLike(int i)

"More like this": passage i as the query.

setWidthmethod
void setWidth(VectorWidth w)

The integer width of the rational way (the search runs again).

runRoundmethod
void runRound()

Runs one race round now.

resetmethod
void reset()
advancemethod
void advance(int n)
animatemethod
void animate(double dt)

Timers run on real time (animate), not on simulation steps: the tile's tour, the lab's first round.

linemethod
Size line(Canvas canvas, String s, Offset at, double maxWidth, {int color = LabCanvasColorTokens.muted, bool bold = false})

One line of text cut with an ellipsis to maxWidth (result rows: a title never runs into the line below).

textmethod
Size text(Canvas canvas, String s, Offset at, {double size = TypeTokens.bodyXs, int color = LabCanvasColorTokens.muted, bool bold = false, double align = 0, double? maxWidth})

Text never asks for less than a few points of width.

onPickmethod
bool onPick(Offset screen, {required bool done})
drawmethod
void draw(Canvas canvas, Size size)