Multi segment cagra search - #133
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
97ef8e7 to
62f6302
Compare
|
I manually re-triggered CI here, it was failing with the issues fixed by rapidsai/ci-imgs#437 |
imotov
left a comment
There was a problem hiding this comment.
Sorry it took me a while. I'm still trying to wrap my head around this codebase. I left a few suggestions.
| * @throws IOException if the vector values cannot be read | ||
| */ | ||
| public int ordToDoc(String field, int ordinal) throws IOException { | ||
| return flatVectorsReader.getFloatVectorValues(field).ordToDoc(ordinal); |
There was a problem hiding this comment.
This is a minor nit, but ordToDoc() is called for every result. Although getFloatVectorValues() is fairly inexpensive, it still performs some allocations. Since the number of results may be significantly larger than the number of underlying segments, it could be worth stashing the FloatVectorValues per segment instead of repeatedly creating and discarding them.
There was a problem hiding this comment.
Updated as suggested. Thanks.
|
|
||
| @Override | ||
| public int advance(int target) { | ||
| while (pos < n && sortedDocs[pos] < target) pos++; |
There was a problem hiding this comment.
This might cause NPE if advance(int target) is called before nextDoc(), which sometimes happens when you iterate over multiple DocIdSetIterators at the same time.
| FilterBitsetHandle cached = FilterBitsetCache.get(filter, segReaderKeys, field); | ||
| if (cached != null) return cached; | ||
|
|
||
| FilterBitsetHandle handle = buildFilterHandle(indexSearcher, leaves, gpuReaders); | ||
| FilterBitsetCache.put(filter, segReaderKeys, field, handle); |
There was a problem hiding this comment.
I think there are a few potential race conditions in this cache that we should address. Because get() and put() are synchronized independently, it's possible for two threads operating on the same key to reach buildFilterHandle() at roughly the same time. In that case, both threads will perform the work and create a FilterBitsetHandle, which is somewhat wasteful. A bigger problem though is that when the second thread calls put(), it will overwrite the FilterBitsetHandle in the CACHE created by the first thread. Unless the replaced handle is explicitly closed, this appears to create a potential resource leak.
There was a problem hiding this comment.
Implemented reference counting as resolution.
| @Override | ||
| protected boolean removeEldestEntry(Map.Entry<FilterCacheKey, FilterBitsetHandle> eldest) { | ||
| if (size() > MAX_HOST_ENTRIES) { | ||
| eldest.getValue().close(); |
There was a problem hiding this comment.
What will happen if this handle is still in use?
There was a problem hiding this comment.
Resolved with ref counting solution.
| public Explanation explain(LeafReaderContext ctx, int doc) { | ||
| for (ScoreDoc sd : scoreDocs) { | ||
| if (sd.doc == ctx.docBase + doc) { | ||
| return Explanation.match(sd.score, "GPU multi-segment CAGRA search"); |
There was a problem hiding this comment.
Since we're applying the boost to the score earlier, we should probably include that boost in the explanation as well. One option is to make it part of the explanation details; alternatively, we could simply use: return Explanation.match(sd.score * boost, "GPU multi-segment CAGRA search");
There was a problem hiding this comment.
Added "boost" to explanation details.
|
|
||
| @Override | ||
| public float getMaxScore(int upTo) { | ||
| return Float.MAX_VALUE; |
There was a problem hiding this comment.
We can probably do a bit better here without much overhead by returning a real max value and ignoring upTo.
There was a problem hiding this comment.
Indeed. Updated as suggested.
| if (t instanceof IOException) throw (IOException) t; | ||
| if (t instanceof RuntimeException) throw (RuntimeException) t; | ||
| throw new RuntimeException("Multi-segment GPU search failed", t); |
There was a problem hiding this comment.
I think, for now, this can be replaced with Utils.handleThrowable. More generally, though, I don't think this is a great pattern. We shouldn't indiscriminately wrap everything in a RuntimeException, as that prevents applications using this library from handling serious conditions such as OutOfMemoryError or AssertionError appropriately. In general, it's better to propagate Error subclasses unchanged and only wrap exceptions that are actually intended to be converted into unchecked exceptions.
There was a problem hiding this comment.
Replaced with handleThrowable for now as a proper fix as suggested would be too pervasive for the scope of this PR.
There was a problem hiding this comment.
Can one of you create a GitHub issue to follow up on this, just so it doesn't get lost in the noise?
| for (int i = 0; i < numSegments; i++) { | ||
| segBitOffsets[i] = totalBits; | ||
| int numOrds = gpuReaders.get(i).getFloatVectorValues(field).size(); | ||
| totalBits += ((long) (numOrds + 63) / 64) * 64; |
There was a problem hiding this comment.
I think, + here might cause an int overflow.
There was a problem hiding this comment.
Thanks for the spot. Updated to upcast numOrds before any subsequent arithmetic.
| return new Bits() { | ||
| @Override | ||
| public boolean get(int i) { | ||
| return false; | ||
| } | ||
|
|
||
| @Override | ||
| public int length() { | ||
| return maxDoc; | ||
| } | ||
| }; |
There was a problem hiding this comment.
return new Bits.MatchNoBits(maxDoc);
There was a problem hiding this comment.
Updated as suggested. Thanks.
|
@jamxia155 I spent some time thinking more about the concerns I shared with you on Friday, and after reflecting on them over the weekend, I still feel quite uneasy about this cache introduction. While I can certainly see scenarios where it could deliver significant performance improvements, I can also think of several cases where it might actually have a negative impact. My main concern is that Lucene already has a query caching layer that has been carefully tuned over time and is further augmented by Elasticsearch at higher levels of the stack. As far as I know, Solr does not even use Lucene's query cache directly, instead relying on its own caching framework. In other words, downstream consumers of Lucene tend to be very opinionated about when query caches should be used and how they should be managed. This PR makes several decisions on behalf of downstream consumers that they may not appreciate. Specifically:
The cache implementation itself uses the full set of segments as the cache key, which introduces additional concerns. This works well for static indexes, but indexes are frequently updated in many real-world deployments. In those situations, the segment set changes continuously. Consider a simple scenario where documents are periodically added to the index and a single search is executed after each update. Over time, the cache would accumulate entries associated with obsolete segment configurations, resulting in a cache that entierly consists of stale results. Lucene's own caching infrastructure, as well as Elasticsearch's cache implementations, are integrated with the segment lifecycle and merge process. They can therefore invalidate cache entries as soon as segment changes occur. Our implementation does not do that, which makes the cache substantially less useful for non-static indexes and increases the risk of wasting memory on entries that are unlikely to be reused. More broadly, I am concerned that we are introducing a mandatory caching layer without providing the controls, invalidation mechanisms, and configurability that downstream consumers typically expect from Lucene. So, my recommendation would be to either spend a bit more time on addressing these issues or if we want to release it now make this cache configurable and disable it by default, enabling users who want it to work with it, but not force it on the rest of the users. |
Thank you, @imotov, for the detailed comment and suggestions. I appreciate your leniency in offering the alternative of a short-term crutch, but I decided to try my hand at making the proper fix (we can always fall back to disabling by default if things are found wanting). These changes sit on top of the recently added reference-counting implementation prompted by your other comments, so an eviction concurrent with an in-flight search can never free a handle still in use. Core concerns and resolutions:
Other items as in your comment:
|
| // Prefer this over the neighbor-index sentinel: the index sentinel is not uniform across | ||
| // CAGRA search algorithms (single-CTA emits 0x7FFFFFFF, multi-CTA 0xFFFFFFFF), so the | ||
| // distance is the reliable, algorithm-independent signal for an empty slot. | ||
| if (score == Float.MAX_VALUE) { |
There was a problem hiding this comment.
I think that check alone should be enough, but I would still keep ord < 0 as an extra check just to harden it a bit.
There was a problem hiding this comment.
Updated as suggested. Thanks.
| // ---- Configuration (guarded by FilterBitsetCache.class) ---- | ||
|
|
||
| private static boolean enabled = | ||
| Boolean.parseBoolean(System.getProperty(PROP_ENABLED, "true")); |
There was a problem hiding this comment.
It is very uncommon for Lucene to rely on System.getProperty(), except when obtaining OS configuration parameters or in tests, benchmarks, and build scripts. Instead, I think this cache should be encapsulated within the codec and configured through codec parameters. When loaded via SPI, the codec can use reasonable defaults, while applications that need different behavior can explicitly instantiate and configure the codec with the desired settings and then provide it for SPI with their desired defaults. This keeps the configuration local to the codec and avoids introducing global JVM-level state.
There was a problem hiding this comment.
Thanks for the comment. I refactored the filter-bitset cache so its configuration and state are local to the codec/format rather than JVM-global.
FilterBitsetCache is now an instance class with no mutable static state or System.getProperty() configuration. An immutable FilterBitsetCacheConfig carries enabled and maxBytes; SPI-created codecs use DEFAULT (enabled=true, maxBytes=0, where zero lazily derives the budget), while explicitly instantiated codecs can provide a different configuration.
Each CuVS2510GPUVectorsFormat owns one cache and passes it to every reader it creates. The query obtains the cache from each reader and groups working-set accounting by cache identity, so the accounting also remains correct if readers backed by different format instances are encountered.
The default SPI codec still has one cache shared by the readers created from that SPI singleton, which is expected under Lucene’s SPI lifecycle. The change is that the cache configuration is now encapsulated in that codec/format instance rather than controlled through JVM properties or mutable cache statics.
I also removed the cache's automatic write to com.nvidia.cuvs.filterBitsetPoolSize. Device-pool policy is now owned independently by cuvs-java (updated in the cuVS PR), which supplies its own conservative 4 MB growable default; applications can explicitly size it or set it to zero to opt out.
imotov
left a comment
There was a problem hiding this comment.
Left a couple of small comments. Other than than LGTM.
| * | ||
| * @param enabled whether filter bitsets are cached between searches | ||
| * @param maxBytes maximum bytes cached by this format; {@code 0} derives a budget from the first | ||
| * filtered search |
There was a problem hiding this comment.
Sorry for not catching this earlier. I think this could lead to some fairly strange scenarios. Imagine a search engine cluster with many nodes where a query with a very small working set is routed to one subset of nodes, while a much heavier query is routed to another subset of nodes. In that case, the first set of nodes could become inexplicably less responsive than the second, leaving users scratching their heads trying to understand why. The nodes are the same, the mixture of queries that they send now are the same, but some nodes are very fast and some nodes are constantly threshing the cache and slow to respond. I think reacting to whatever happened to be the first query may not be the best strategy here. I'd lean toward either a fixed value or a conservative percentage of the available resources. That would provide more predictable behavior and make the system easier to reason about and troubleshoot.
| CuVSResources resources = CuVSResources.create(); | ||
| String poolSizeProp = System.getProperty(WORKSPACE_POOL_SIZE_PROPERTY); | ||
| if (poolSizeProp != null) { | ||
| long poolBytes = Long.parseLong(poolSizeProp); |
There was a problem hiding this comment.
I would add a separate handling for NumberFormatException here in case somebody sets that to "1024M" or something causing already allocated resources to silently leak.
There was a problem hiding this comment.
Added NumberFormatException and additional handling (negative values, values that could overflow) in separate helper. For even more confidence, deferred CuVSResources creation till after poolBytes has been validated.
|
/ok to test 9c55185 |
|
/ok to test 9c55185 |
|
/ok to test 083887e |
|
/ok to test 1a34e4d |
|
/ok to test a7b3760 |
|
/ok to test 14afe00 |
|
/ok to test 6b87d53 |
e9b45a8 to
1fad50f
Compare
This PR adds a CAGRA search API and associated implementation for batching workloads involving a single query and multiple indexes (e.g. index segments built from one dataset by cuvs-lucene). This promotes GPU utilization for non-batched queries by parallelizing work over multiple CTAs, while minimizing the number of concurrent kernels for potential host-side parallelism. Addresses cuvs-lucene [issue 124](NVIDIA/cuvs-lucene#124), [issue 158](NVIDIA/cuvs-lucene#158), [issue 159](NVIDIA/cuvs-lucene#159), and cuvs [issue 2166](#2166). Associated cuvs-lucene PR: NVIDIA/cuvs-lucene#133. Authors: - James Xia (https://github.com/jamxia155) Approvers: - Corey J. Nolet (https://github.com/cjnolet) - Kyle Edwards (https://github.com/KyleFromNVIDIA) URL: #2035
|
/merge |
Companion PR to cuvs!2035, addresses #124.
Existing CAGRA search code path for each search query:
Proposed change: