Add GPU-resident tile cache for cuslide2 #1145
[P1] Retain ownership of the selected device cache for the entire read
AI-assisted review comment (finding 1/1).
The new accessor returns a borrowed ImageCache& after releasing the manager mutex. A concurrent CuImage.cache(...) can then reset the manager's last owning shared pointer while this read still calls into the cache, leaving the cache object/mutex pool dangling. Please obtain one get_device_cache() owning snapshot before the type check and retain it throughout the read; the accessor already provides the needed locked shared-pointer copy.
Validation: Validation during report preparation used a compiled C++17 ownership model, not the full cuCIM/GPU implementation. The proposed patch passed git apply --check without being applied. Full project, sanitizer integration, decoding, and performance tests were not run.
<details>
<summary>Detailed reasoning, proposed patch, and regression coverage</summary>
Locations
cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp:616-633: obtains borrowed references twice without keeping the cache alive.cpp/src/cache/image_cache_manager.cpp:79-88: distinguishes the reference-returning accessor from the owning accessor.cpp/src/cache/image_cache_manager.cpp:95-101: reconfiguration resets the owning shared pointer.Root cause and impact
The mutex protects access to the manager's shared pointer, but an ImageCache& does not increment its reference count. Normally the manager is the only owner unless Python or another caller has explicitly retained CuImage.device_cache().
A valid interleaving is:
1. Thread A enters a GPU tile read and obtains image_cache through device_cache().
2. The accessor returns and releases device_cache_mutex_.
3. Thread B calls CuImage.cache(...) to change the cache configuration.
4. device_cache_.reset() destroys the old cache because A holds only a reference.
5. A calls create_key, lock, find, allocate, insert, or unlock through the destroyed object.
This is use-after-free of the cache object and potentially its mutex pool and tile storage. The second configuration can be identical to the first; rebuilding is sufficient to trigger the lifetime problem. A cached tile's own shared pointer can protect that tile after lookup, but does not protect the cache object used for subsequent operations.
The interleaving is reachable from Python: read_region releases the GIL (python/pybind11/cucim_py.cpp:148), so another Python thread can configure the cache while the native read is in progress.
Acquiring the cache twice also permits the cache-type check to inspect one cache and the assembly block to use a different cache after reconfiguration. One owning snapshot solves both problems for the new device path.
Reproduction / validation
Compiled and ran a minimal C++17 ownership test with the same shared-pointer, mutex, reference-returning accessor, and reset pattern. It deliberately did not dereference freed memory. A weak_ptr demonstrated that:
borrowed accessor + manager reset: old cache is already destroyed
owning accessor + manager reset: old cache stays alive until reader releases it
This validates the C++ lifetime reasoning, not the complete cuCIM runtime. A deterministic project regression test should pause a reader immediately after selecting its cache, reconfigure from another thread, then resume it under AddressSanitizer. The old cache must remain alive until the read completes.
Suggested fix
Use the owning accessors already supplied by the implementation. Acquire one shared pointer before checking the type, retain it for the entire tile-read scope, and use its pointee for all subsequent operations. get_device_cache() copies the shared pointer while holding the same mutex used by reset, so the acquisition itself is protected.
diff --git a/cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp b/cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp
--- a/cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp
+++ b/cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp
@@ -613,12 +613,13 @@
// warm cached read slower than an uncached one for CUDA output (#1069).
const bool assemble_on_device = (out_device.type() == cucim::io::DeviceType::kCUDA);
+ std::shared_ptr<cucim::cache::ImageCache> image_cache_owner;
if (use_tile_caching)
{
- cucim::cache::ImageCache& image_cache = assemble_on_device ?
- cucim::CuImage::cache_manager().device_cache() :
- cucim::CuImage::cache_manager().cache();
- cucim::cache::CacheType cache_type = image_cache.type();
+ image_cache_owner = assemble_on_device ?
+ cucim::CuImage::cache_manager().get_device_cache() :
+ cucim::CuImage::cache_manager().get_cache();
+ cucim::cache::CacheType cache_type = image_cache_owner->type();
if (cache_type == cucim::cache::CacheType::kNoCache)
{
@@ -628,9 +629,7 @@
if (use_tile_caching)
{
- cucim::cache::ImageCache& image_cache = assemble_on_device ?
- cucim::CuImage::cache_manager().device_cache() :
- cucim::CuImage::cache_manager().cache();
+ cucim::cache::ImageCache& image_cache = *image_cache_owner;
const uint32_t tw = tile_width_;
const uint32_t th = tile_height_;
The host cache's unsynchronized pointer acquisition/reconfiguration is an analogous pre-existing concern; this proposal is not a claim to make all host cache-manager operations concurrently safe. The new device accessor already provides the necessary locked owning acquisition.
Regression coverage
nocache and a new per_process configuration.</details>
Thank you @cdinea for the change!
AI-assisted review. Sharing 1 AI-assisted inline finding from the prepared review report.
Reviewed commit: b608e6525ef37e6969317d558a399ef486f730ae. The PR description was read before the diff; the current head and inline locations were rechecked before publication.
Validation and limitations: Validation during report preparation used a compiled C++17 ownership model, not the full cuCIM/GPU implementation. The proposed patch passed git apply --check without being applied. Full project, sanitizer integration, decoding, and performance tests were not run.
This is a non-blocking COMMENT review, not an approval or formal request for changes. No implementation changes or fixes were applied.
<details>
<summary>Review scope and additional context</summary>
Scope and method
Ran gh pr checkout 1145, read gh pr view 1145, then reviewed gh pr diff 1145 --color never. Traced the new manager accessors through the cuslide2 tile reader, cache allocation/value destruction, Python bindings, and nvImageCodec decoder. The two-cache design, independent capacities, lazy creation, and shared-memory-to-per-process downgrade are intentional according to the description.
Source locations refer to the reviewed head. PR diff excerpts are contextual excerpts, not complete patches. The suggested fix is a proposal only; no implementation files were changed.
Additional integration checks, not established findings
stream=1 (cucim_py.cpp:640-643). An asynchronous device-copy concern must account for that stream contract; this review does not assert that every CuPy consumer races the new copies.CuImage.device_cache() for GPU counters after these branches are integrated. Its cold-workload issues are documented separately in the review of #1143.</details>
Thank you @cdinea for the update!
It looks good to me.
/ok to test b4298e8
/ok to test 903fd49
/merge
gigony
cdinea
Implements #1069, addressing the last open question from @mkepa-nv's review of #1034:
This implements the two-cache form.
Why this was worse than a missing optimization
The tile cache was unconditionally host-resident. That is not just "a CPU cache where a GPU one would be nicer" — for GPU output it actively defeated a faster path that already existed.
With the cache off, nvImageCodec decodes straight into device memory (
STRIDED_DEVICE). With the cache on, cuslide2 decoded tiles to host, assembled them there with a single-threaded per-rowmemcpy, then copied the finished region up with onecudaMemcpyHostToDevice.So enabling the cache did not merely add a host round-trip, it also gave up direct-to-device decode. A warm cached read could lose to an uncached one for
device="cuda"— which is the sharper version of the concern originally raised about light codecs, since it applies regardless of how cheap the codec is.Two caches, not one device-aware cache
ImageCacheManagernow offersdevice_cache()alongsidecache(). Keeping them separate rather than making a single cache device-aware means:Both are built from the configuration passed to
cache(config), and reconfiguring drops the device cache so new settings take effect and its device memory is released. Since each may independently grow to the configuredmemory_capacity, a workload mixing CPU and GPU output can hold that capacity twice over, once per memory space — documented on the accessor.A
kSharedMemoryconfiguration is downgraded tokPerProcessfor the device cache only, because device pointers cannot live in a Boost.Interprocess segment. Downgrading beats throwing: the caller asked for GPU output, not for a particular cache backend.The infrastructure needed almost nothing new.
PerProcessImageCache::allocate()already had acudaMallocpath forDeviceType::kCUDAand its value destructor alreadycudaFrees device allocations — the global cache simply was never constructed that way. Legacy cuslide'sNvJpegProcessorhas kept a private device-resident tile cache all along, so this pattern already has a working in-tree precedent.cuslide2 read path
The tile path now selects both its cache and its assembly memory space from the requested output device. GPU reads decode tiles directly to device, assemble with strided
cudaMemcpy2Ddevice-to-device copies, and publish the raster with no transfer at all. The host path is byte-for-byte unchanged in behaviour.Two details worth a reviewer's eye:
cudaMemset2Dper tile instead of a loop of per-rowmemsets.Observability
CuImage.device_cache()exposes the new cache to Python. This is needed rather than optional: GPU reads no longer touchCuImage.cache(), so without it a warm GPU read would report zero hits and look broken. The two caches keep separate statistics.Verification status
Please read this honestly — the runtime behaviour is unmeasured.
What I did verify: full semantic analysis (
-fsyntax-only, using the project's owncompile_commands.jsonso the real flags and include paths apply) of all four affected translation units —ifd.cpp,image_cache_manager.cpp,cuimage.cppandcucim_py.cpp. All clean.What I could not do: build or run cuCIM, as no build was available in my environment. So the correctness of GPU reads and the size of the resulting speedup are both unproven. Specifically worth checking on real hardware:
1. That GPU-output reads return pixel-identical results to the host path.
2. That nvImageCodec decodes correctly into the cache's
cudaMalloc'd tile buffers at tile granularity.3. Peak device memory under a GPU-heavy workload, given the per-cache capacity note above.
Related
CuImage.device_cache()rather thanCuImage.cache(), otherwise they will report no hits. Kept out of this PR to avoid a conflict between the two branches.