-
Notifications
You must be signed in to change notification settings - Fork 22
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
Use max heap for building query result #54
Merged
Merged
Conversation
This file contains 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
philippgille
force-pushed
the
use-max-heap
branch
from
March 17, 2024 15:01
f282f94
to
7874004
Compare
ℹ️ , just using the max heap without limiting to n elements is much worse. Diff: diff --git a/query.go b/query.go
index 240060c..2d6187c 100644
--- a/query.go
+++ b/query.go
@@ -1,12 +1,10 @@
package chromem
import (
- "cmp"
"container/heap"
"context"
"fmt"
"runtime"
- "slices"
"strings"
"sync"
)
@@ -23,7 +21,7 @@ type docSim struct {
type docMaxHeap []docSim
func (h docMaxHeap) Len() int { return len(h) }
-func (h docMaxHeap) Less(i, j int) bool { return h[i].similarity < h[j].similarity }
+func (h docMaxHeap) Less(i, j int) bool { return h[i].similarity > h[j].similarity }
func (h docMaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *docMaxHeap) Push(x any) {
@@ -40,48 +38,6 @@ func (h *docMaxHeap) Pop() any {
return x
}
-// maxDocSims manages a max-heap of docSims with a fixed size, keeping the n highest
-// similarities. It's safe for concurrent use, but not the result of values().
-// In our benchmarks this was faster than sorting a slice of docSims at the end.
-type maxDocSims struct {
- h docMaxHeap
- lock sync.RWMutex
- size int
-}
-
-// newMaxDocSims creates a new nMaxDocs with a fixed size.
-func newMaxDocSims(size int) *maxDocSims {
- return &maxDocSims{
- h: make(docMaxHeap, 0, size),
- size: size,
- }
-}
-
-// add inserts a new docSim into the heap, keeping only the top n similarities.
-func (mds *maxDocSims) add(doc docSim) {
- mds.lock.Lock()
- defer mds.lock.Unlock()
- if mds.h.Len() < mds.size {
- heap.Push(&mds.h, doc)
- } else if mds.h.Len() > 0 && mds.h[0].similarity < doc.similarity {
- // Replace the smallest similarity if the new doc's similarity is higher
- heap.Pop(&mds.h)
- heap.Push(&mds.h, doc)
- }
-}
-
-// values returns the docSims in the heap, sorted by similarity (descending).
-// The call itself is safe for concurrent use with add(), but the result isn't.
-// Only work with the result after all calls to add() have finished.
-func (d *maxDocSims) values() []docSim {
- d.lock.RLock()
- defer d.lock.RUnlock()
- slices.SortFunc(d.h, func(i, j docSim) int {
- return cmp.Compare(j.similarity, i.similarity)
- })
- return d.h
-}
-
// filterDocs filters a map of documents by metadata and content.
// It does this concurrently.
func filterDocs(docs map[string]*Document, where, whereDocument map[string]string) []*Document {
@@ -163,7 +119,8 @@ func documentMatchesFilters(document *Document, where, whereDocument map[string]
}
func getMostSimilarDocs(ctx context.Context, queryVectors []float32, docs []*Document, n int) ([]docSim, error) {
- nMaxDocs := newMaxDocSims(n)
+ sortedDocs := &docMaxHeap{}
+ sortedDocksLock := sync.Mutex{}
// Determine concurrency. Use number of docs or CPUs, whichever is smaller.
numCPUs := runtime.NumCPU()
@@ -218,7 +175,10 @@ func getMostSimilarDocs(ctx context.Context, queryVectors []float32, docs []*Doc
return
}
- nMaxDocs.add(docSim{docID: doc.ID, similarity: sim})
+ sortedDocksLock.Lock()
+ // We don't defer the unlock because we want to do it much earlier
+ heap.Push(sortedDocs, docSim{docID: doc.ID, similarity: sim})
+ sortedDocksLock.Unlock()
}
}(docs[start:end])
}
@@ -229,5 +189,11 @@ func getMostSimilarDocs(ctx context.Context, queryVectors []float32, docs []*Doc
return nil, sharedErr
}
- return nMaxDocs.values(), nil
+ // Pop the n most similar documents from the max-heap.
+ res := make([]docSim, n)
+ for i := 0; i < n; i++ {
+ res[i] = heap.Pop(sortedDocs).(docSim)
+ }
+
+ return res, nil
} Benchmark:
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
It requires more allocations (not constant anymore), but is 1) faster and 2) requires much smaller allocations, so overall a win.