-
Notifications
You must be signed in to change notification settings - Fork 14
[v17] MB-68591: GPU-Accelerated Vector Search #342
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
CascadingRadium
wants to merge
24
commits into
unstable-v17
Choose a base branch
from
gpu
base: unstable-v17
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
b28b519
Introducing Zapx V17
CascadingRadium d974de5
remove debug print statements
CascadingRadium 97898cc
Apply suggestions from code review
CascadingRadium 583d6dc
small error msg fix
CascadingRadium 187f4e9
remove redundant docvalue reader code
CascadingRadium 2a205bb
fix footer
CascadingRadium 2e1faac
small fix in zap.md
CascadingRadium 6b3309d
cleanup
CascadingRadium d34dd94
Add fieldsOptions to manage indexing options for fields
CascadingRadium afd61d6
Refactor field name retrieval
CascadingRadium 395dbed
Refactor field indexing logic to utilize fieldsOptions over updatedFi…
CascadingRadium f1a3e77
md changes
CascadingRadium b1a32aa
pass test
CascadingRadium 46d5600
fix merge conflict
CascadingRadium 0e23465
Support GPU-Accelerated Vector Search
CascadingRadium 4241192
Apply suggestions from code review
CascadingRadium a6aca22
fix divByZero
CascadingRadium 857cf02
fix bug
CascadingRadium 21eafbe
add a nil check
CascadingRadium 83276a0
use new options
CascadingRadium 074e13f
do not write options
CascadingRadium 00eeefc
fix
CascadingRadium 7ca0d80
add go tag
CascadingRadium 916481d
Merge branch 'unstable-v17' into gpu
CascadingRadium File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,207 @@ | ||
| // Copyright (c) 2025 Couchbase, Inc. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| //go:build vectors | ||
| // +build vectors | ||
|
|
||
| package zap | ||
|
|
||
| import ( | ||
| "math" | ||
| "math/rand/v2" | ||
| "sync" | ||
|
|
||
| faiss "github.com/blevesearch/go-faiss" | ||
| ) | ||
|
|
||
| var ( | ||
| // NumGPUs is the number of available GPU devices | ||
| NumGPUs int | ||
| // GPULocks is a slice of mutexes for synchronizing access to GPU resources | ||
| // Primarily used for synchronizing calls to TransferToGPU and TransferToCPU | ||
| GPULocks []*sync.Mutex | ||
| ) | ||
|
|
||
| func init() { | ||
| n, err := faiss.NumGPUs() | ||
| if err != nil { | ||
| NumGPUs = 0 | ||
| return | ||
| } | ||
| NumGPUs = n | ||
| GPULocks = make([]*sync.Mutex, NumGPUs) | ||
| for i := 0; i < NumGPUs; i++ { | ||
| GPULocks[i] = &sync.Mutex{} | ||
| } | ||
| } | ||
|
|
||
| const ( | ||
| // GPUIndexMinVectorsForTransfer is the minimum number of vectors | ||
| // required to consider transferring an IVF index to GPU for training | ||
| // Smaller indexes may not benefit from GPU acceleration | ||
| // due to transfer overheads | ||
| GPUIndexMinVectorsForTransfer = 30000 | ||
|
|
||
| // GPUTransferOverheadFactor accounts for additional | ||
| // memory overhead involved during GPU index transfer, | ||
| // such as data transfer costs and temporary allocations | ||
| GPUTransferOverheadFactor = 1.4 | ||
|
|
||
| // SoftmaxTemperature controls the sharpness of the probability distribution | ||
| // when selecting a GPU based on available free memory. | ||
| // Lower values (<1) make the selection more deterministic (favoring the GPU | ||
| // with the most free memory), while higher values (>1) make it more random | ||
| SoftmaxTemperature = 0.5 | ||
| ) | ||
|
|
||
| type gpuInfo struct { | ||
| id int | ||
| freeMem float64 // in bytes | ||
| } | ||
|
|
||
| // GetDeviceID returns a device ID between 0 and NumGPUs-1 (inclusive) to be used for distributing work across multiple GPUs. | ||
| // It returns -1 if no GPUs are available or an error occurs. The selection algorithm favors GPUs with more free memory, | ||
| // using a softmax-based probabilistic selection to help spread load across multiple GPUs when more than two GPUs are available. | ||
| func GetDeviceID() int { | ||
| // simple cases | ||
| // no GPUs available, return -1 | ||
| if NumGPUs == 0 { | ||
| return -1 | ||
| } | ||
|
|
||
| var gpus []*gpuInfo | ||
| for i := 0; i < NumGPUs; i++ { | ||
| freeMem, err := faiss.FreeMemory(i) | ||
| if err != nil { | ||
| continue | ||
| } | ||
| gpus = append(gpus, &gpuInfo{id: i, freeMem: float64(freeMem)}) | ||
| } | ||
|
|
||
| if len(gpus) == 0 { | ||
| // fallback if no memory info available | ||
| // return -1 to indicate no GPUs available | ||
| // even though NumGPUs > 0 as we couldn't | ||
| // get memory info and thus cannot provide a | ||
| // reliable device selection | ||
| return -1 | ||
| } | ||
|
|
||
| var maxGPU *gpuInfo | ||
| for _, g := range gpus { | ||
| if maxGPU == nil || g.freeMem > maxGPU.freeMem { | ||
| maxGPU = g | ||
| } | ||
| } | ||
|
|
||
| // if all the GPUs are full, return -1 | ||
| if maxGPU.freeMem == 0 { | ||
| return -1 | ||
| } | ||
|
|
||
| // if only two or fewer GPUs, just pick the one with the most free memory | ||
| if len(gpus) <= 2 { | ||
| return maxGPU.id | ||
| } | ||
|
|
||
| // more than two GPUs, do softmax weighting based on free memory | ||
| // to probabilistically pick a GPU, favoring those with more free memory | ||
| // this helps spread load more evenly across multiple GPUs, while still | ||
| // favoring those with more available resources, mainly to avoid | ||
| // always picking the same GPU when multiple GPUs have similar free memory | ||
| expVals := make([]float64, len(gpus)) | ||
| var sumExp float64 | ||
| for i, g := range gpus { | ||
| val := math.Exp((g.freeMem - maxGPU.freeMem) / (SoftmaxTemperature * maxGPU.freeMem)) | ||
| expVals[i] = val | ||
| sumExp += val | ||
| } | ||
|
|
||
| // Compute cumulative distribution and sample. | ||
| r := rand.Float64() | ||
| cumProb := 0.0 | ||
| for i, g := range gpus { | ||
| cumProb += expVals[i] / sumExp | ||
| if r <= cumProb { | ||
| return g.id | ||
| } | ||
| } | ||
|
|
||
| // Fallback to max GPU | ||
| return maxGPU.id | ||
| } | ||
|
|
||
CascadingRadium marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // TrainIndex trains the given FAISS index using the provided vectors and dimensions. | ||
| // If useGPU is true and a suitable GPU is available, training is performed on the GPU; | ||
| // otherwise, training falls back to the CPU. The function returns the trained index, | ||
| // which may be a new instance if GPU training and transfer back to CPU succeed. | ||
| func TrainIndex(index *faiss.IndexImpl, vecs []float32, dims int, useGPU bool) (*faiss.IndexImpl, error) { | ||
| // function to train index on CPU used as fallback on GPU failures | ||
| TrainCPU := func() (*faiss.IndexImpl, error) { | ||
| err := index.Train(vecs) | ||
| return index, err | ||
| } | ||
| // decide whether to use GPU for training | ||
| if !useGPU || NumGPUs == 0 || len(vecs)/dims < GPUIndexMinVectorsForTransfer { | ||
CascadingRadium marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // use CPU training | ||
| return TrainCPU() | ||
| } | ||
| // attempt GPU training | ||
| deviceID := GetDeviceID() | ||
| if deviceID == -1 { | ||
| // no GPUs available, fallback to CPU training | ||
| return TrainCPU() | ||
| } | ||
| // lock the selected GPU for the duration of the transfer | ||
| GPULocks[deviceID].Lock() | ||
| // check if enough free memory is available | ||
| estimatedMemNeeded := uint64(float64(len(vecs)*SizeOfFloat32) * GPUTransferOverheadFactor) // input vectors + overhead | ||
| freeMem, err := faiss.FreeMemory(deviceID) | ||
| if err != nil || freeMem < estimatedMemNeeded { | ||
| // unable to get free memory info or not enough free memory, | ||
| // fallback to CPU training | ||
| GPULocks[deviceID].Unlock() | ||
| return TrainCPU() | ||
| } | ||
| // transfer index to GPU | ||
| gpuIndex, err := faiss.TransferToGPU(index, deviceID) | ||
| if err != nil { | ||
| // transfer failed, fallback to CPU training | ||
| GPULocks[deviceID].Unlock() | ||
| return TrainCPU() | ||
| } | ||
| GPULocks[deviceID].Unlock() | ||
| // train on GPU | ||
| err = gpuIndex.Train(vecs) | ||
| if err != nil { | ||
| // training failed, fallback to CPU training | ||
| gpuIndex.Close() | ||
| return TrainCPU() | ||
CascadingRadium marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| // acquire lock again for transfer back to CPU | ||
| GPULocks[deviceID].Lock() | ||
| // transfer back to CPU | ||
| cpuIndex, err := faiss.TransferToCPU(gpuIndex) | ||
| gpuIndex.Close() | ||
| if err != nil { | ||
| GPULocks[deviceID].Unlock() | ||
| // transfer back failed, fallback to CPU training | ||
| return TrainCPU() | ||
CascadingRadium marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| GPULocks[deviceID].Unlock() | ||
| // successful GPU training and transfer back to CPU | ||
| // now free the original index and return the new trained index | ||
| index.Close() | ||
| return cpuIndex, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| // Copyright (c) 2025 Couchbase, Inc. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| //go:build vectors | ||
| // +build vectors | ||
|
|
||
| package zap | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/blevesearch/go-faiss" | ||
| ) | ||
|
|
||
| func TestNumGPUs(t *testing.T) { | ||
| _, err := faiss.NumGPUs() | ||
| if err != nil { | ||
| t.Fatalf("unexpected error: %v", err) | ||
| } | ||
| } | ||
|
|
||
| func TestGetDeviceID(t *testing.T) { | ||
| id := GetDeviceID() | ||
| if NumGPUs == 0 { | ||
| if id != -1 { | ||
| t.Fatalf("expected -1 device ID when no GPUs available, got: %d", id) | ||
| } | ||
CascadingRadium marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } else if id < 0 || id >= NumGPUs { | ||
| t.Fatalf("expected device ID between 0 and %d, got: %d", NumGPUs-1, id) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.