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
| Classic | Rational / geometric | |
|---|---|---|
| Similarity | cos θ = 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 time | every vector scaled to length 1 (a square root each), f32 | every vector scaled to its own ±127 (int8) or ±32767 (int16) and rounded; Q(v) an exact integer, 1/Q in f64 |
| Search | f32 dot products (FMOPA on the matrix unit, GemmF32 on the GPU) are the cosines; top 10 | exact integer dot products (SMOPA int8 → int32, int16 → int64; GemmI32, int16 as four 8-bit-limb passes); key sign(x)·x²/Q; top 10 |
| Order | by f32 values; rounding decides near ties | exact: 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_cpurandomizedSvd, 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
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.
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.
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).
List<int> topKFloat(List<double> values, int n, int k)The k largest of values (first n), largest first, ties to the smaller index.
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).
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.
(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).
Float32List classicDots(SearchData s)The f32 dot products of the unit vectors (cosines) on the matrix unit (n × q, row-major).
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.
LaneRun runExactCpu(SearchData s, VectorWidth w, {int minMicros = 30000})An exact CPU lane: integer dots on the matrix unit, spread ranked exactly, top k.
LaneRun rankGpu(SearchData s, SearchLane lane, GpuDots g)Ranks a GPU lane's dot products (in a worker in the app) and measures it.
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.
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).
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).
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).
List<(int, int)> tiedPairs(int n)The tied pairs of a clusteredSet of n vectors: (i − 1, i) for every i ≡ −1 (mod tieEvery).
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.
PreparedCorpus prepareCorpus(LectureCorpus corpus)Builds the corpus's vectors and finds the example queries (pure work: run it in a worker).
Constants and variables
const stopwordsThe words the vectorizer skips (common English function words and caption filler).
const exampleQueriesQueries to pick from (and the corpus's recall sample): topics of the lectures and talks.
const searchSizes = [4096, 16384, 65536, 262144]Synthetic set sizes (d = 128, 32 queries, k = 10).
const tieEvery = 64Every 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.
const seriesColorsThe 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
Lecture
final class Lecture
One lecture of the corpus.
Constructors
const Lecture(this.title, this.series, this.videoId)Properties
final String titlefinal String videoIdPassage
final class Passage
A passage: about two minutes of one lecture, with its words counted.
Constructors
const Passage(this.lecture, this.start, this.snippet, this.terms, this.counts)Properties
final int lecturefinal Uint8List countsLectureCorpus
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
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
static const seriesNamesstatic LectureCorpus decode(ByteData data)Properties
final List<Lecture> lecturesfinal List<String> vocabularyfinal Uint32List dffinal Float32List wordScaleThe word vectors: word t's entry k is wordScalet · wordInts[t·dims + k] / 32767.
final Int16List wordIntsfinal List<Passage> passagesfinal int dimsfinal Float32List displayTwo directions in vector space (2 × dims) the map projects onto.
int get nMethods
({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).
(double, double) mapPoint(Float32List v, int offset)Where passage i sits on the map: its vector projected onto the two display directions (unscaled).
Uint8List encode()Hit
final class Hit
One found passage with what each way measured for it.
Constructors
const Hit(this.passage, {required this.cosine, required this.spread, required this.opposite})Properties
final int passagefinal double spreadS = 1 − (a·b)²/(Q(a)Q(b)) of the integer vectors, exact, rounded only for display.
FindResult
final class FindResult
One typed query both ways.
Constructors
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
final String textfinal double mapXWhere the query sits on the map (its unit vector projected like the passages).
final double mapYWhere the query sits on the map (its unit vector projected like the passages).
final int? exampleThe passage the query was made from ("more like this"), or null for typed words.
final List<String> knownfinal List<String> unknownfinal List<Hit> classicfinal List<Hit> rationalfinal VectorWidth widthfinal double classicMicrosMedian time of one search over the whole corpus: dot products (matrix unit) and the top k.
final double rationalMicrosMedian time of one search over the whole corpus: dot products (matrix unit) and the top k.
final double classicRecallfinal double rationalRecallbool get emptyMethods
FindResult withTimes(double classic, double rational)The same result with the measured times replaced (goldens: pixels must not depend on a stopwatch).
CorpusSearch
final class CorpusSearch
The lecture corpus as a searchable set: vectors built once (LSA), indexed both ways.
Constructors
CorpusSearch(this.corpus)Properties
final LectureCorpus corpusfinal VectorSet vectorslate final SearchData baselate final Float32List mapPointsThe map position of every passage (projection onto the corpus's two display directions).
Methods
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.
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).
SearchData examples({int k = 10})The example queries in one block (the corpus row of the race and its recall).
IvfIndex
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
static IvfIndex classic(SearchData s, int lists, {int rounds = 4, int seed = 3})Spherical k-means on the unit vectors of s.
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
final bool exactfinal int listsfinal int dfinal Int16List? intCentresSpread: lists × d int16 centres and their exact quadrances.
final Int64List? centreQuadrancefinal double buildMicrosHow long building took (k-means and grouping), microseconds.
Methods
IvfSearch search(SearchData s, int probe)Every query of s through the index, looking in the probe nearest groups.
IvfSearch
final class IvfSearch
What an index search found and what it cost.
Constructors
const IvfSearch({required this.probe, required this.results, required this.recall, required this.scannedShare, required this.microsPerQuery})Properties
final int probefinal List<List<int>> resultsfinal double microsPerQueryLaneState
enum LaneState
Where a lane is in the current round.
Values
waitingrunningdoneSearchRace
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
SearchRace({Future<VectorGpu?> Function()? gpu, SearchWorker? worker, SearchWorker? compare, this.minMicros = 30000})Properties
void Function()? onChangefinal Map<SearchLane, LaneState> statefinal Map<SearchLane, LaneRun> resultsfinal Map<SearchLane, Map<int, LaneRun>> historyEvery result so far, by lane, then size (the chart).
CpuSearchRound? lastThe last round's tie report, reorder check and data (null before a round).
IvfIndex? classicIndexThe index, both ways, on the last round's set (null until built).
IvfIndex? spreadIndexThe index, both ways, on the last round's set (null until built).
IvfSearch? classicIvfIvfSearch? spreadIvfint probebool indexingVectorGpu? gpuString? gpuMissingbool? nativeint featuresbool busyint roundsfinal List<int> sweepQueueint get largestThe largest size this device runs: 262,144 with a matrix unit, 16,384 on a portable loop.
int get listsMethods
void reset()void sweep()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.
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).
SpreadRanker
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
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 exactFallbacksHow many comparisons the f64 filter could not decide and were settled in big integers.
int comparisonsHow many exact key comparisons were made (candidates the fast reject could not dismiss).
Methods
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.
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).
SearchLane
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
const SearchLane({required this.gpu, required this.width})Properties
final bool gpufinal VectorWidth? widthbool get exactSearchData
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
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
static SearchData synthetic(int n, {int d = 128, int q = 32, int k = 10, int seed = 1})Properties
final VectorSet docsfinal VectorSet queriesfinal int kfinal VectorSet unitDocsThe classic index: every vector scaled to length 1 (one root each), so cosine is a dot product.
final VectorSet unitQueriesThe classic index: every vector scaled to length 1 (one root each), so cosine is a dot product.
final QuantizedSet docs8final QuantizedSet docs16final QuantizedSet queries8final QuantizedSet queries16Float64List get inverse81/Q(b) in f64 for the integer vectors (precomputed once; no root).
Float64List get inverse16final List<(int, int)> tiesPairs of vectors that point exactly the same way (a vector and 3 × it).
late final List<List<int>> truthint get nint get dint get qMethods
Float64List inverseOf(VectorWidth w)QuantizedSet docsOf(VectorWidth w)QuantizedSet queriesOf(VectorWidth w)Float32List queriesT()The unit queries transposed (d × q, row-major): the B of C = D·B on the graphics chip.
Int32List queriesTInt(VectorWidth w)LaneRun
final class LaneRun
One lane's measured search.
Constructors
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
final SearchLane lanefinal int nfinal int dfinal int qfinal double dotMicrosDot products for all q queries (median; GPU: kernel time), and ranking them (top k per query).
final double rankMicrosDot products for all q queries (median; GPU: kernel time), and ranking them (top k per query).
final int runsfinal int fallbacksSpread lanes: comparisons the f64 filter left to big integers, of all comparisons.
final int comparisonsSpread lanes: comparisons the f64 filter left to big integers, of all comparisons.
double get totalMicrosGpuDots
final class GpuDots
What the graphics chip hands back: the dot products (f32, or exact integers) and how long they took.
Constructors
const GpuDots({required this.micros, required this.runs, this.endToEndMicros, this.floats, this.ints, this.passes = 1})Properties
final double microsfinal int runsfinal double? endToEndMicrosfinal Float32List? floatsfinal List<int>? intsfinal int passesVectorGpu
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
String get nameMethods
Future<GpuDots> classic(Float32List docs, Float32List queriesT, int n, int d, int q)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.
CpuStandInVectorGpu
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
String get nameMethods
Future<GpuDots> classic(Float32List docs, Float32List queriesT, int n, int d, int q)Future<GpuDots> exact(Int32List docs, Int32List queriesT, int n, int d, int q, VectorWidth w)TieReport
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
const TieReport({required this.pairs, required this.f32Split, required this.spreadEqual8, required this.spreadEqual16})Properties
final int f32Splitfinal int spreadEqual8final int spreadEqual16CpuSearchRound
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
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
final SearchData datafinal Map<SearchLane, LaneRun> lanesfinal TieReport tiesfinal int reorderCheckedQueries 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 classicReorderedQueries 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 exactIdenticalfinal bool nativefinal int featuresSplitMix
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
SplitMix(int seed)Methods
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).
VectorSet
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
VectorSet(this.n, this.d, this.values)Properties
final int nfinal int dfinal Float32List valuesMethods
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.
Float32List norms()| v | = √(v·v) for every row, computed in f64 and stored in f32: what a classic index precomputes (one root a |
|---|
Vector).
VectorWidth
enum VectorWidth
How many bits the integer vectors keep.
Values
Constructors
const VectorWidth(this.top)Properties
String get labelQuantizedSet
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
static QuantizedSet of(VectorSet v, VectorWidth width)Properties
final VectorWidth widthfinal int nfinal int dfinal Int16List? i16Methods
VectorMode
enum VectorMode
What the lab shows.
Values
findThe lecture corpus: a typed (or picked) query, its nearest passages both ways on the map and in two lists.
raceSpeed and recall by set size: every lane on the CPU's matrix unit and the graphics chip.
ivfThe inverted-file index both ways: recall against the share of the set each query looks at.
PreparedCorpus
final class PreparedCorpus
The corpus, made searchable (a worker builds the vectors), and every example query already found.
Constructors
const PreparedCorpus(this.search, this.tour)Properties
final CorpusSearch searchfinal List<FindResult> tourVectorSearchScene
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
final SearchRace racePreparedCorpus? preparedString? corpusErrorFindResult? foundVectorWidth widthint? selectedThe rank selected in the lists (its passage is highlighted and its first words shown), or null.
VectorMode get modeset mode(VectorMode m)bool get loadingCorpusSearch? get searchMathsLabel get classicLabelMathsLabel get finiteLabelbool get showsClassicbool get showsRationalFindResult? get shownWhat the map and the lists show now: the lab's query, or the tile's tour stop.
bool get isIdleList<StageHotspot> get hotspotsMethods
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).
void findText(String text)Searches the corpus for text both ways (the panel's field and picks).
void setWidth(VectorWidth w)The integer width of the rational way (the search runs again).
void reset()void advance(int n)void animate(double dt)Timers run on real time (animate), not on simulation steps: the tile's tour, the lab's first round.
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).
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.
bool onPick(Offset screen, {required bool done})void draw(Canvas canvas, Size size)