-
Notifications
You must be signed in to change notification settings - Fork 4
/
vector_store.go
322 lines (297 loc) · 6.97 KB
/
vector_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package bbq
import (
"fmt"
"math"
"strings"
"sync"
"github.com/RoaringBitmap/roaring"
"github.com/viterin/vek/vek32"
)
const defaultMaxSampling = 10000
type PrintfFunc func(string, ...any)
type VectorStore struct {
logger PrintfFunc
backend VectorBackend
dimensions int
nbasis int
bases []Basis
bms []map[int]*roaring.Bitmap
preSpill int
lastSaveToken uint64
}
type VectorStoreOption func(vs *VectorStore) error
func WithPrespill(prespill int) VectorStoreOption {
return func(vs *VectorStore) error {
if prespill <= 0 {
prespill = 1
} else if prespill > vs.dimensions {
prespill = vs.dimensions
}
vs.preSpill = prespill
return nil
}
}
func NewVectorStore(backend VectorBackend, nBasis int, opts ...VectorStoreOption) (*VectorStore, error) {
info := backend.Info()
v := &VectorStore{
dimensions: info.Dimensions,
nbasis: nBasis,
backend: backend,
bases: make([]Basis, nBasis),
bms: make([]map[int]*roaring.Bitmap, nBasis),
preSpill: 1,
}
for _, o := range opts {
err := o(v)
if err != nil {
return nil, err
}
}
if info.HasIndexData {
err := v.loadFromBackend()
return v, err
}
err := v.makeBasis()
if err != nil {
return nil, err
}
err = v.Sync()
if err != nil {
return nil, err
}
return v, nil
}
func (vs *VectorStore) Close() error {
err := vs.Sync()
if err != nil {
return err
}
return vs.backend.Close()
}
func (vs *VectorStore) SetLogger(printf PrintfFunc) {
vs.logger = printf
}
func (vs *VectorStore) log(s string, a ...any) {
if vs.logger != nil {
vs.logger(s, a...)
}
}
func (vs *VectorStore) AddVector(id ID, v Vector) error {
if vs.backend.Exists(id) {
vs.removeFromBitmaps(id)
}
err := vs.backend.PutVector(id, v)
if err != nil {
return err
}
return vs.addToBitmaps([]ID{id}, []Vector{v})
}
func (vs *VectorStore) AddVectorsWithOffset(offset ID, vecs []Vector) error {
ids := make([]ID, len(vecs))
for i, v := range vecs {
id := offset + ID(i)
ids[i] = id
if vs.backend.Exists(id) {
vs.removeFromBitmaps(id)
}
vs.backend.PutVector(id, v)
}
return vs.addToBitmaps(ids, vecs)
}
func (vs *VectorStore) AddVectorsWithIDs(ids []ID, vecs []Vector) error {
for i, v := range vecs {
id := ids[i]
if vs.backend.Exists(id) {
vs.removeFromBitmaps(id)
}
vs.backend.PutVector(id, v)
}
return vs.addToBitmaps(ids, vecs)
}
func (vs *VectorStore) FindNearest(vector Vector, k int, searchk int, spill int) (*ResultSet, error) {
if spill < 0 {
spill = 0
} else if spill >= vs.dimensions {
spill = vs.dimensions - 1
}
return vs.findNearestInternal(vector, k, searchk, spill)
}
func (vs *VectorStore) findNearestInternal(vector Vector, k int, searchk int, spill int) (*ResultSet, error) {
counts := NewCountingBitmap(vs.nbasis)
buf := make([]float32, vs.dimensions)
maxes := make([]int, spill+1)
for i, basis := range vs.bases {
spillClone := roaring.New()
vs.findIndexesForBasis(vector, basis, buf, maxes)
for _, m := range maxes {
if v, ok := vs.bms[i][m]; ok {
spillClone.Or(v)
}
}
counts.Or(spillClone)
}
elems := counts.TopK(searchk)
//vs.log("Actual searchK is: %s", counts.String())
// Rerank within the reduced set
rs := NewResultSet(k)
var err error
elems.Iterate(func(x uint32) bool {
// things that take closures should really return error, so that it can abort...
var sim float32
sim, err = vs.backend.ComputeSimilarity(vector, ID(x))
if err != nil {
return false
}
// On err, this will be the zero value of sum (but that's ok, we're going down)
rs.AddResult(ID(x), sim)
return true
})
return rs, err
}
func (vs *VectorStore) findIndexesForBasis(target Vector, basis Basis, buf []float32, maxes []int) {
for x, b := range basis {
dot := vek32.Dot(b, target)
buf[x] = dot
}
for i := 0; i < len(maxes); i++ {
big := vek32.ArgMax(buf)
small := vek32.ArgMin(buf)
idx := 0
if math.Abs(float64(buf[big])) >= math.Abs(float64(buf[small])) {
idx = big
} else {
idx = small
}
if buf[idx] > 0.0 {
maxes[i] = idx + 1
} else {
maxes[i] = -(idx + 1)
}
buf[idx] = 0.0
}
}
func (vs *VectorStore) Sync() error {
be, ok := vs.backend.(IndexBackend)
if !ok {
return nil
}
var err error
vs.lastSaveToken, err = be.SaveBases(vs.bases, vs.lastSaveToken)
if err != nil {
return err
}
for b, dimmap := range vs.bms {
for i, v := range dimmap {
err = be.SaveBitmap(b, i, v)
if err != nil {
return err
}
}
}
return be.Sync()
}
func (vs *VectorStore) makeBasis() error {
vs.log("Making basis set")
for n := 0; n < vs.nbasis; n++ {
basis := make(Basis, vs.dimensions)
for i := range vs.dimensions {
basis[i] = NewRandVector(vs.dimensions, nil)
}
for range 10 {
orthonormalize(basis)
}
vs.log("Completed basis %d", n)
vs.bases[n] = basis
}
vs.log("Completed basis set generation")
return nil
}
// Use Modified Gram-Schmidt (https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process)
// to turn our random vectors into an orthonormal basis.
func orthonormalize(basis Basis) {
buf := make([]float32, len(basis[0]))
cur := basis[0]
for i := 1; i < len(basis); i++ {
for j := i; j < len(basis); j++ {
dot := vek32.Dot(basis[j], cur)
vek32.MulNumber_Into(buf, cur, dot)
vek32.Sub_Inplace(basis[j], buf)
basis[j].Normalize()
}
cur = basis[i]
}
}
func debugPrintBasis(basis Basis) {
for i := 0; i < len(basis); i++ {
sim := make([]any, len(basis))
for j := 0; j < len(basis); j++ {
sim[j] = vek32.CosineSimilarity(basis[i], basis[j])
}
pattern := strings.Repeat("%+.15f ", len(basis))
fmt.Printf(pattern+"\n", sim...)
}
}
func (vs *VectorStore) removeFromBitmaps(id ID) {
for _, m := range vs.bms {
if m == nil {
continue
}
for _, bm := range m {
bm.Remove(uint32(id))
}
}
}
func (vs *VectorStore) addToBitmaps(ids []ID, vectors []Vector) error {
var wg sync.WaitGroup
for n, basis := range vs.bases {
wg.Add(1)
go func(n int, basis Basis, wg *sync.WaitGroup) {
if v := vs.bms[n]; v == nil {
vs.bms[n] = make(map[int]*roaring.Bitmap)
}
buf := make([]float32, vs.dimensions)
maxes := make([]int, vs.preSpill)
for i := range vectors {
id := ids[i]
v := vectors[i]
vs.findIndexesForBasis(v, basis, buf, maxes)
for _, m := range maxes {
if _, ok := vs.bms[n][m]; !ok {
vs.bms[n][m] = roaring.NewBitmap()
}
vs.bms[n][m].Add(uint32(id))
}
}
wg.Done()
}(n, basis, &wg)
}
wg.Wait()
return nil
}
func (vs *VectorStore) loadFromBackend() error {
var err error
be, ok := vs.backend.(IndexBackend)
if !ok {
panic("Backend suggested that it could store indexes, but it cannot")
}
vs.bases, err = be.LoadBases()
if err != nil {
return err
}
for b := 0; b < vs.nbasis; b++ {
dimmap := make(map[int]*roaring.Bitmap)
for i := 1; i <= vs.dimensions; i++ {
bm, err := be.LoadBitmap(b, i)
if err != nil {
return err
}
dimmap[i] = bm
bm, err = be.LoadBitmap(b, -i)
if err != nil {
return err
}
dimmap[-i] = bm
}
}
return nil
}