-
Notifications
You must be signed in to change notification settings - Fork 682
/
insert.go
265 lines (222 loc) · 5.99 KB
/
insert.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
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
//
// CONTACT: hello@weaviate.io
//
package hnsw
import (
"context"
"fmt"
"math"
"sync/atomic"
"time"
"github.com/pkg/errors"
"github.com/weaviate/weaviate/adapters/repos/db/helpers"
"github.com/weaviate/weaviate/adapters/repos/db/vector/compressionhelpers"
)
func (h *hnsw) ValidateBeforeInsert(vector []float32) error {
dims := int(atomic.LoadInt32(&h.dims))
// no vectors exist
if dims == 0 {
return nil
}
// check if vector length is the same as existing nodes
if dims != len(vector) {
return fmt.Errorf("new node has a vector with length %v. "+
"Existing nodes have vectors with length %v", len(vector), dims)
}
return nil
}
func (h *hnsw) AddBatch(ctx context.Context, ids []uint64, vectors [][]float32) error {
if err := ctx.Err(); err != nil {
return err
}
if len(ids) != len(vectors) {
return errors.Errorf("ids and vectors sizes does not match")
}
if len(ids) == 0 {
return errors.Errorf("insertBatch called with empty lists")
}
h.trackDimensionsOnce.Do(func() {
atomic.StoreInt32(&h.dims, int32(len(vectors[0])))
})
levels := make([]int, len(ids))
maxId := uint64(0)
for i, id := range ids {
if maxId < id {
maxId = id
}
levels[i] = int(math.Floor(-math.Log(h.randFunc()) * h.levelNormalizer))
}
h.RLock()
if maxId >= uint64(len(h.nodes)) {
h.RUnlock()
h.Lock()
if maxId >= uint64(len(h.nodes)) {
err := h.growIndexToAccomodateNode(maxId, h.logger)
if err != nil {
h.Unlock()
return errors.Wrapf(err, "grow HNSW index to accommodate node %d", maxId)
}
}
h.Unlock()
} else {
h.RUnlock()
}
for i := range ids {
if err := ctx.Err(); err != nil {
return err
}
vector := vectors[i]
node := &vertex{
id: ids[i],
level: levels[i],
}
globalBefore := time.Now()
if len(vector) == 0 {
return errors.Errorf("insert called with nil-vector")
}
h.metrics.InsertVector()
vector = h.normalizeVec(vector)
err := h.addOne(vector, node)
if err != nil {
return err
}
h.insertMetrics.total(globalBefore)
}
return nil
}
func (h *hnsw) addOne(vector []float32, node *vertex) error {
h.compressActionLock.RLock()
h.deleteVsInsertLock.RLock()
before := time.Now()
defer func() {
h.deleteVsInsertLock.RUnlock()
h.compressActionLock.RUnlock()
h.insertMetrics.updateGlobalEntrypoint(before)
}()
wasFirst := false
var firstInsertError error
h.initialInsertOnce.Do(func() {
if h.isEmpty() {
wasFirst = true
firstInsertError = h.insertInitialElement(node, vector)
}
})
if wasFirst {
if firstInsertError != nil {
return firstInsertError
}
return nil
}
node.markAsMaintenance()
h.RLock()
// initially use the "global" entrypoint which is guaranteed to be on the
// currently highest layer
entryPointID := h.entryPointID
// initially use the level of the entrypoint which is the highest level of
// the h-graph in the first iteration
currentMaximumLayer := h.currentMaximumLayer
h.RUnlock()
targetLevel := node.level
node.connections = make([][]uint64, targetLevel+1)
for i := targetLevel; i >= 0; i-- {
capacity := h.maximumConnections
if i == 0 {
capacity = h.maximumConnectionsLayerZero
}
node.connections[i] = make([]uint64, 0, capacity)
}
if err := h.commitLog.AddNode(node); err != nil {
return err
}
nodeId := node.id
h.shardedNodeLocks.Lock(nodeId)
h.nodes[nodeId] = node
h.shardedNodeLocks.Unlock(nodeId)
if h.compressed.Load() {
h.compressor.Preload(node.id, vector)
} else {
h.cache.Preload(node.id, vector)
}
h.insertMetrics.prepareAndInsertNode(before)
before = time.Now()
var err error
var distancer compressionhelpers.CompressorDistancer
var returnFn compressionhelpers.ReturnDistancerFn
if h.compressed.Load() {
distancer, returnFn = h.compressor.NewDistancer(vector)
defer returnFn()
}
entryPointID, err = h.findBestEntrypointForNode(currentMaximumLayer, targetLevel,
entryPointID, vector, distancer)
if err != nil {
return errors.Wrap(err, "find best entrypoint")
}
h.insertMetrics.findEntrypoint(before)
before = time.Now()
// TODO: check findAndConnectNeighbors...
if err := h.findAndConnectNeighbors(node, entryPointID, vector, distancer,
targetLevel, currentMaximumLayer, helpers.NewAllowList()); err != nil {
return errors.Wrap(err, "find and connect neighbors")
}
h.insertMetrics.findAndConnectTotal(before)
before = time.Now()
node.unmarkAsMaintenance()
h.RLock()
if targetLevel > h.currentMaximumLayer {
h.RUnlock()
h.Lock()
// check again to avoid changes from RUnlock to Lock again
if targetLevel > h.currentMaximumLayer {
if err := h.commitLog.SetEntryPointWithMaxLayer(nodeId, targetLevel); err != nil {
h.Unlock()
return err
}
h.entryPointID = nodeId
h.currentMaximumLayer = targetLevel
}
h.Unlock()
} else {
h.RUnlock()
}
return nil
}
func (h *hnsw) Add(id uint64, vector []float32) error {
return h.AddBatch(context.TODO(), []uint64{id}, [][]float32{vector})
}
func (h *hnsw) insertInitialElement(node *vertex, nodeVec []float32) error {
h.Lock()
defer h.Unlock()
if err := h.commitLog.SetEntryPointWithMaxLayer(node.id, 0); err != nil {
return err
}
h.entryPointID = node.id
h.currentMaximumLayer = 0
node.connections = [][]uint64{
make([]uint64, 0, h.maximumConnectionsLayerZero),
}
node.level = 0
if err := h.commitLog.AddNode(node); err != nil {
return err
}
err := h.growIndexToAccomodateNode(node.id, h.logger)
if err != nil {
return errors.Wrapf(err, "grow HNSW index to accommodate node %d", node.id)
}
h.shardedNodeLocks.Lock(node.id)
h.nodes[node.id] = node
h.shardedNodeLocks.Unlock(node.id)
if h.compressed.Load() {
h.compressor.Preload(node.id, nodeVec)
} else {
h.cache.Preload(node.id, nodeVec)
}
// go h.insertHook(node.id, 0, node.connections)
return nil
}