← Back to Pull requests

Add GPU-resident tile cache for cuslide2 #1145

Merged
cdinea merged 9 files (486 lines) on Sep 22, 2026 01:40 UTC
View on GitHub
cdinea cdinea commented on Sep 07, 2026 01:54 UTC
Author

Implements #1069, addressing the last open question from @mkepa-nv's review of #1034:

but from the perf perspective maybe it would be better to have caching tiles decoded in gpu memory? Or have two caches, one for CPU and one for GPU tiles?

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-row memcpy, then copied the finished region up with one cudaMemcpyHostToDevice.

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

ImageCacheManager now offers device_cache() alongside cache(). Keeping them separate rather than making a single cache device-aware means:

  • Host and device readers do not evict each other's tiles. A mixed workload would otherwise thrash one cache with two different residencies.

  • The device cache is built on first use, so a process that never requests GPU output never allocates device memory.
  • 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 configured memory_capacity, a workload mixing CPU and GPU output can hold that capacity twice over, once per memory space — documented on the accessor.

    A kSharedMemory configuration is downgraded to kPerProcess for 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 a cudaMalloc path for DeviceType::kCUDA and its value destructor already cudaFrees device allocations — the global cache simply was never constructed that way. Legacy cuslide's NvJpegProcessor has 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 cudaMemcpy2D device-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:

  • Cache values are created with the matching device type, otherwise a device allocation would be released through the host deallocator.

  • Background fills for tiles that cannot be allocated or decoded now go through one cudaMemset2D per tile instead of a loop of per-row memsets.
  • Observability

    CuImage.device_cache() exposes the new cache to Python. This is needed rather than optional: GPU reads no longer touch CuImage.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 own compile_commands.json so the real flags and include paths apply) of all four affected translation units — ifd.cpp, image_cache_manager.cpp, cuimage.cpp and cucim_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

  • #1143 adds the per-codec cache benchmark that answers the first half of the review feedback. Once both land, its CUDA rows should read CuImage.device_cache() rather than CuImage.cache(), otherwise they will report no hits. Kept out of this PR to avoid a conflict between the two branches.
  • Diff: 486 lines (+415 / -71) across 9 files Reviewer: gigony Review duration: 21586m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.52) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 486 lines diff across 9 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.370
    Real PR Conversation Timeline
    8 items
    copy-pr-bot[bot] copy-pr-bot[bot] commented on Sep 07, 2026 01:54 UTC
    Bot

    This pull request requires additional validation before any workflows can run on NVIDIA's runners.

    Pull request vetters can view their responsibilities here.

    Contributors can view more details about this message here.

    gigony gigony commented on code on Sep 15, 2026 22:59 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp:1
    @@ -620,7 +628,9 @@ bool IFD::read([[maybe_unused]] const TIFF* tiff,
     
         if (use_tile_caching)
         {
    -        cucim::cache::ImageCache& image_cache = cucim::CuImage::cache_manager().cache();
    +        cucim::cache::ImageCache& image_cache = assemble_on_device ?
    +                                                    cucim::CuImage::cache_manager().device_cache() :
    +                                                    cucim::CuImage::cache_manager().cache();

    [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

  • Race a paused GPU read with reconfiguration to both nocache and a new per_process configuration.

  • Exercise the race before the first lookup and between successive tile lookups.

  • Ensure the read consistently uses the selected cache, while later reads use the replacement.

  • Verify old device allocations are released after the final reader/explicit cache handle releases ownership, not during the read.

  • Retain lazy creation and the shared-memory downgrade tests.
  • </details>

    gigony gigony commented on Sep 15, 2026 22:59 UTC
    Reviewer

    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

  • Run cold and warm CUDA reads for supported codecs, tile-edge ROIs, 8/16-bit samples, and supported channel counts; compare pixels with CPU output.

  • Test cache eviction, insufficient capacity, decode failure/background fill, and caller-owned output buffers at the C++ layer.

  • Validate multiple CUDA devices explicitly before promising device-local cache isolation: this implementation has one device-cache slot and its cache identity does not contain a CUDA device ordinal. The surrounding decoder/device-selection behavior also requires inspection on hardware; no multi-GPU failure was reproduced here.

  • The Python CUDA array interface already publishes 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.

  • As the description notes, #1143 must use CuImage.device_cache() for GPU counters after these branches are integrated. Its cold-workload issues are documented separately in the review of #1143.
  • </details>

    gigony gigony approved these changes on Sep 20, 2026 18:59 UTC
    Approved Reviewer

    Thank you @cdinea for the update!

    It looks good to me.

    cdinea cdinea commented on Sep 21, 2026 18:49 UTC
    Author

    /ok to test b4298e8

    cdinea cdinea commented on Sep 22, 2026 00:57 UTC
    Author

    /ok to test 903fd49

    cdinea cdinea commented on Sep 22, 2026 01:40 UTC
    Author

    /merge

    Reviewers
    Assignees
    cdinea cdinea
    Labels
    risk: low confidence: 85.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 51.7% (MEDIUM) · Higher = larger blast radius
    51.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.7% · Lower = rushed or shallow review
    85.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.4% · Safe to merge
    7.4%
    Repository