← Back to Pull requests

Route device allocations through a CCCL memory resource #1147

Closed
unknown closed this pull request without merging on Nov 24, 2026 05:52 UTC
View on GitHub
unknown unknown commented on Sep 07, 2026 02:30 UTC
Author

Summary

Adopts CCCL memory resources for cuCIM's device allocations, following the guidance from @bdice in #swrapids-cucim: APIs accept a cuda::mr::resource_ref, memory is freed through the resource that allocated it, and there is no process-wide "current" resource.

This is the foundation plus the internal allocation sites. It deliberately stops short of output allocations, for the reason detailed below.

What this adds

cucim::memory::DeviceResource is a non-global handle to a device-accessible memory resource. It holds no stream: allocate() and deallocate() take the stream each call is ordered on, and an object that owns a buffer keeps that buffer's stream beside the handle. Built from a cuda::mr::any_resource, the handle owns the resource in a std::shared_ptr, so copies share one allocating instance rather than duplicating it. Built from a device_resource_ref, it borrows, and the caller keeps the resource alive. Every allocate and deallocate takes an alignment, matching the CCCL resource API.

cucim::memory::DeviceMemoryPoolResource is the default: the current device's CCCL default memory pool (cuda::device_default_memory_pool), which is stream-ordered. Each allocation first makes the device's primary context current, because the pool allocates through the driver API, which does not create a context on first use. Releases go through cudaFreeAsync, which frees by pointer and works on a thread that never used CUDA, so deallocation is noexcept throughout.

cucim::memory::CudaMemoryResource allocates with cudaMalloc and frees with cudaFree. It is used only where a buffer is later released with a bare cudaFree that knows nothing of its provenance (see below): a caller's resource need not hand out CUDA runtime allocations, and a stream-ordered allocation is only safe to cudaFree once its accesses have completed, which cudaFree does not wait for. It rejects alignments that do not divide 256 with std::invalid_argument, as CCCL's pools do.

What this converts

The sites where core both allocates and frees, so the pairing is provably correct:

  • Device tile cache (PerProcessImageCache). Its resource is fixed at construction. Tiles are allocated and released on the legacy default stream, because the plugins fill and read them with default-stream copies that are not ordered against any other stream; a configurable stream can follow once they are. Each cached value records the resource and the stream its buffer was allocated on, and frees through and on them, so an entry evicted while a reader still holds it is still returned correctly.

  • move_raster_from_host / move_raster_from_device gain overloads that take a DeviceResource, a stream and (for the download) the allocation's alignment. The copies run on that stream and are synchronized before the call returns. The existing signatures, which the plugins call, borrow a static CudaMemoryResource on the default stream, so plugin callers are unaffected and a no-op move allocates nothing.
  • What this does not convert, and why

    Output allocations are not converted, because cuCIM cannot currently do it correctly:

  • Device memory reaching the user is often allocated inside a plugin: cuslide2's ifd.cpp and nvimgcodec_decoder.cpp call cudaMalloc directly.

  • It is freed by core, in CuImage::~CuImage and CuImage::save, which call cudaFree regardless of where the buffer came from.

  • ImageDataDesc is {container, shm_name, loader}. There is no field through which a resource could cross the plugin boundary, and the boundary is a C ABI.
  • So converting CuImage's free today would hand a caller's resource pointers that a plugin allocated with a raw cudaMalloc, which that resource never issued. Getting output allocations onto a memory resource needs the plugin ABI to carry one first, which is a separate design change. Related: cuCIM has no DLManagedTensor deleter at all, so ownership of returned memory is implicit in CuImage rather than expressed in the DLPack container.

    Notes for reviewers

    CCCL comes from rapids-cmake. Building on #1241, CCCL is added with rapids_cpm_cccl(INSTALL_EXPORT_SET cucim-exports) at the version rapids-cmake pins, and installed with cuCIM. The installed cucim::cucim target links CCCL::CCCL, and cucim-config.cmake finds it with find_dependency(CCCL ... COMPONENTS libcudacxx) from the install prefix, so consumers of the installed device_resource.h get a CCCL with cuda::mr. The cccl conda package is not used.

    Include order is load-bearing. The CUDA toolkit bundles its own libcudacxx, older than cuda::mr for every CUDA version cuCIM supports. If the toolkit's include directory is searched first, CCCL's <cuda/memory_resource> still resolves but its cuda/std/* dependencies come from the toolkit, and cuda::mr silently disappears. The build-tree targets add CCCL with target_include_directories(... BEFORE ...).

    The CUDA runtime is exported static. CUDA::cudart_static is PUBLIC for build-tree and installed consumers, because CCCL emits runtime calls in the consumer's own objects. It is static because the conda package ignores cuda-cudart's run_exports; a plugin linking the shared runtime fails the overlinking check.

    cuda::buffer is not adopted here. It is still published under /unstable/ in the CCCL docs, and using it would change the ImageDataDesc/DLPack layout. Left as a follow-up rather than baking an unstable API into the public container.

    The aligned O_DIRECT tail fix moved upstream. An earlier version of this PR also fixed file offsets in aligned partial-page I/O. #1244 fixed the same bug, so after rebasing this PR no longer touches cufile_driver.cpp.

    Open question

    Whether the memory resource should control output allocations, temporary allocations, or both, and whether to accept a second resource for temporaries. This PR uses a single resource for the internal allocations it converts. If you want separate output and temporary resources, that shape is easier to change now than later.

    Testing

    cpp/tests/test_device_resource.cpp (new) covers:

  • cuCIM's resources and a user-written one satisfy cuda::mr::synchronous_resource, cuda::mr::resource and device_accessible, asserted statically.

  • Allocations reach the supplied resource with the requested alignment, zero-byte requests included, and every allocation is matched by a deallocation carrying the original size.

  • Allocation failure propagates whatever the resource throws, std::bad_alloc or a pool-style std::runtime_error.

  • Copies of an owning handle share one resource: a resource whose copies have distinct identities checks that a copy frees through the instance that allocated, including after the original is gone. A borrowing handle borrows.

  • Each call is ordered on the stream it is given, so allocating a second buffer on another stream cannot move an earlier buffer's release.

  • CudaMemoryResource rejects alignments that cudaMalloc cannot honor.
  • On an RTX A6000, a standalone probe confirmed that the first default-pool allocation in a fresh process succeeds, and that releasing a 1 MiB block from a thread that never used CUDA leaves 0 bytes in use in the pool. Before the context fix, that allocation failed with CUDA_ERROR_INVALID_CONTEXT and the release left the block in use.

    In CI, the conda Python tests on RTX PRO 6000 pass all 15 test_cuslide2_plugin.py tests, including the cached and batched reads that go through the per-process cache.

    Drive-by fixes

    A failed copy in move_raster_from_host / move_raster_from_device threw without releasing the buffer it had just allocated; both paths now free it. Also drops a dead <memory_resource> include in memory_manager.cpp that referred to std::pmr.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: gigony Review duration: 112521m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1147"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 56.8% · Lower = rushed or shallow review
    56.8%
    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: 22.5% · Safe to merge
    22.5%
    Repository