Skip to content

Tracking: device-side CUDA runtime API (cudadevrt) support in the Rust device compiler #1071

Open

Description

@lucifer1004

Background

The Rust→NVVM IR→nvJitLink pipeline currently cannot call CUDA device-runtime APIs from kernels, because those symbols are not defined in any Rust crate and must be resolved at the final device link. We have a local, not-yet-PR'd commit that adds exactly one such API — cudaGraphSetConditional — to support explicit CUDA Graph conditional nodes. We would like to agree on the general design before the PR series grows.

This issue tracks the design discussion for device-side CUDA runtime API support as a whole.

What we have working today

A single-symbol vertical slice, ~370 lines across 16 files:

  • cuda-device: unsafe extern "C" fn cudaGraphSetConditional(handle: u64, value: u32) declaration
  • collector: leaves this exact symbol unresolved during monomorphization collection
  • mir-lower: declares it at the call site, like __nv_* libdevice externs
  • codegen pipeline: detects the call in typed MIR, sets requires_cuda_device_runtime, and forces the NVVM IR / external-link route
  • finalizer: discovers libcudadevrt.a, fingerprints it (SHA-256 handshake with the cargo-oxide driver), and feeds it to nvJitLink as an InputType::Library alongside the LTOIR inputs

This produces a working sm_120a cubin whose selector kernel drives a real conditional node, loaded and exercised on hardware.

Empirical findings that should shape the design

All observed with the CUDA 13.3 toolchain (libNVVM 2.0 / nvJitLink 13.3), sm_120a:

  1. cudaGraphSetConditional does not need the archive. nvJitLink recognizes it and lowers the call to the driver service ABI (CALL.ABS.NOINC via c[0x4][0x28]); with and without libcudadevrt.a on the link, the kernel's SASS is instruction-identical. This reserved-symbol behavior appears to be undocumented — the nvJitLink user guide never mentions cudadevrt or reserved symbols.
  2. cudaMalloc and cudaGraphLaunch do need the archive. Without it, nvJitLink returns success but silently drops every kernel of the offending module, producing a valid but empty cubin (~2.2 KB). With the archive, real device code from cuda_device_runtime.cu is linked in and all entries survive. (Consistent with --keep-system-libraries docs: the device linker GCs unreferenced system-library code.)
  3. Symbol naming splits by family. The classic CDP families (device malloc/free, streams, events, async memcpy/memset, introspection) are declared under CDP2-internal __cudaCDP2* names, which the header explicitly marks private ("Symbols beginning with __cudaCDP* should not be used outside this header file"). The graph family is exempt: cudaGraphLaunch and cudaGraphSetConditional are plain extern __device__ under their public names. So a curated symbol table can use stable public names for the graph family, while the classic CDP surface would mean depending on internal symbols.

Scope of the API family (CUDA 13.3 headers + docs)

Roughly 40+ extern "C" __device__ entry points in 8 families:

Family Examples Resolution Public name?
Device mgmt / introspection cudaGetLastError, cudaDeviceGetAttribute archive no (__cudaCDP2*)
Streams cudaStreamCreateWithFlags, cudaStreamWaitEvent, tail/fire-and-forget stream constants archive no (__cudaCDP2*)
Events cudaEventCreateWithFlags, cudaEventRecordWithFlags archive no (__cudaCDP2*)
Memory device cudaMalloc/cudaFree, cudaMemcpy*Async, cudaMemset*Async archive no (__cudaCDP2*)
CDP kernel launch cudaGetParameterBufferV2, cudaLaunchDeviceV2 archive no (__cudaCDP2*)
Device graph launch / node updates cudaGraphLaunch, cudaGraphKernelNodeSetParam/SetEnabled/SetGridDim archive (verified for cudaGraphLaunch) yes
Conditional nodes cudaGraphSetConditional nvJitLink reserved symbol (empirical) yes
PDL cudaTriggerProgrammaticLaunchCompletion, cudaGridDependencySynchronize header-inline PTX, no symbol n/a

Design questions

  1. Symbol modeling. Should the compiler recognize device-runtime symbols from a curated table (each entry added with a qualifying consumer and a link test), or generically from unresolved externs? We lean curated: deriving the link requirement from any unresolved symbol would mask typos and, combined with finding (2), defer real errors to runtime.
  2. Scope. Given finding (3), should device-runtime support be scoped to the graph family (stable public names) and leave the classic CDP surface out, unless there is a documented way to reference it without private __cudaCDP2* symbols?
  3. Silent-drop guard. Should the finalizer verify that expected entry kernels survived the link (or that no requested device-runtime symbol remains undefined) so finding (2) becomes a build-time error?
  4. Archive provenance. Is the SHA-256 digest handshake for libcudadevrt.a (cargo-oxide fingerprints, rustc verifies at materialization) worth keeping, given the archive participates in real resolution for most of the family?
  5. PR structure. One PR per symbol family with its own tests, or the mechanism + conditional-node slice first?

cc @nihalpasham — would appreciate your take on the direction before we start sending PRs.

Activity

  1. nihalpasham commented on Aug 21, 2026

    @nihalpasham
    Collaborator

    Thanks. I went through the issue, your implementation, and the current compiler, artifact, finalizer, and runtime-loading paths. I think the direction is right.

    The compiler model should be:

    kernel -> CUDA runtime API
    

    and:

    kernel -> helper -> CUDA runtime API
    

    Both produce the same result:

    whole reachable device module
            |
            v
    NVVM IR -> libNVVM -> LTOIR -> nvJitLink
                                          |
                                  + libcudadevrt
                                    when required
    

    This does not require changing the public host APIs. However, it does affect host-executed tooling because cargo-oxide, the shared finalizer, and deferred cuda-host loading perform the device link.

    I see seven design requirements:

    1. Use a curated registry of supported CUDA device APIs, not “any unresolved extern”.
    2. Detect calls across all device-reachable functions, including helper functions.
    3. Carry device-link requirements in the artifact so build-time and deferred loading behave identically.
    4. Verify that every expected kernel survives nvJitLink.
    5. Include libcudadevrt in the provenance, handshake, and cache recipe.
    6. Start with a narrow, documented Graph API and complete safety contract.
    7. Add direct, indirect, negative, missing-archive, cache, and end-to-end tests.

    I would not make these seven separate PRs because several are parts of the same contract. I also would not put everything into one PR. My preference is this three-PR stack:

    PR 1: final-link safety
              |
              v
    PR 2: complete device-runtime link contract
              |
              v
    PR 3: first public Graph API
    

    PR 1 — Final-link safety

    Make expected-kernel retention a general finalizer invariant.

    • Pass the expected kernel names into finalization.
    • Root them during nvJitLink.
    • Inspect the final PTX/cubin entry inventory.
    • Fail if any expected kernel disappeared.
    • Add deliberate empty-cubin and missing-entry regressions.

    The invariant should be:

    nvJitLink success + missing expected kernel = error
    

    This is useful independently of CUDA Graphs and gives the later work a safe foundation.

    PR 2 — Complete device-runtime link contract

    Add the reusable linking mechanism, but keep it dormant—no public Graph API yet.

    The following pieces should land together because splitting them could leave one loading path or cache unsound:

    • Ordered typed inputs such as LTOIR and Library.
    • Coherent libcudadevrt discovery.
    • Versioned device-link requirements in artifacts.
    • A new provenance/handshake/cache recipe containing the exact archive.
    • Support in both immediate cubin materialization and deferred cuda-host finalization.
    • Fail-closed handling for unknown requirements or unsupported output routes.
    • A test fixture or documented API that genuinely requires the archive.

    The result should be:

    Rust LTOIR + required archive
            |
            v
    cubin containing every expected kernel
    

    PR 3 — First public Graph API

    Once all finalization paths understand the contract, expose cudaGraphSetConditional.

    • Add one curated registry entry with its exact ABI and resolution route.
    • Select NVVM for both direct and reachable helper calls.
    • Record its CUDA 12.3 minimum.
    • Use a typed conditional handle, or clearly document the raw-handle boundary.
    • Document the same-context, lifetime, and no-racing requirements.
    • Add a real conditional-graph example and GPU test.

    For example:

    selector kernel
          |
    set conditional value
          |
          v
    graph runs or skips its body
    

    One important test point: the CUDA 13.3 experiment shows that nvJitLink resolves cudaGraphSetConditional without libcudadevrt. Since this is not a documented contract, that function alone cannot prove the archive path. PR 2 must exercise something that actually requires the archive.

    After these three PRs, additional documented Graph APIs can be added in small families. Device Graph Launch can have its own focused follow-up. Classic Dynamic Parallelism and private __cudaCDP2* symbols should remain a separate design discussion.

    If three PRs create too much contributor overhead, two PRs are acceptable:

    PR 1: finalizer safety + complete link infrastructure
    PR 2: curated public API + end-to-end example
    

    I do not recommend one all-in-one PR. It would combine finalizer correctness, artifact/provenance protocol changes, compiler recognition, public API safety, and GPU behavior—and cudaGraphSetConditional could accidentally hide a broken archive path.

    Tests should land with the PR that introduces each rule, rather than in a later cleanup PR.

  2. added
    enhancement
    tracking
    epic
    cuda-feature
    codegen
    device-apis
    build-related
    cargo-oxide
    tests
    examples
    on Aug 21, 2026
  3. lucifer1004 commented on Sep 30, 2026

    @lucifer1004
    ContributorAuthor

    Thanks for the detailed review — we'll follow the three-PR stack (final-link safety → dormant device-runtime link contract → first public Graph API), with each PR's tests landing in that PR. A few design points before we send PR 1, and one question for PR 2.

    PR 1 (final-link safety) — planned shape

    • Expected kernels: for embedded bundles, from the collector's kernel entries (the exact export names, including generic _TID_<hash> names). The sidecar routes (.ll/.target/.options consumed by cargo oxide interop and cuda-host's file loader) carry no kernel list today, so we'd add a <name>.kernels sidecar written by the compiler, rather than falling back to a weaker "non-empty inventory" check.
    • Rooting: kernels are already rooted through @llvm.used, so we'd keep that and not pass nvJitLink -kernels-used, since that option also lets nvJitLink drop kernels not in the list.
    • Inventory: after the link, collect entries from the output (PTX through ptx-parse; cubin through an ELF symbol-table walk for entry functions), and fail with a MissingKernels error naming the lost entries. Cached finalization only publishes an image after the check passes.
    • Regressions: synthetic empty and missing-entry cubins in unit tests, plus a live test.

    PR 2 question: carrying device-link requirements

    oxide-artifacts is the one piece consumed from crates.io (0.2.1), because cutile-rs cuda-core reads bundles through it, and check-oxide-artifacts-parity.sh keeps the in-tree copy equal to that release. Recording "requires the device runtime" inside .oxart in a way old readers reject (e.g. a new bit in KNOWN_COMPILE_OPTIONS) therefore means publishing a new oxide-artifacts version and bumping cutile-rs cuda-core. Since there's no regular release process for this yet, how would you like format changes handled?

    1. A small preparatory PR that bumps oxide-artifacts (new compile-option bit, fail-closed on older readers), published by a maintainer ahead of PR 2; or
    2. keep the requirement out of .oxart for now (e.g. only in sidecars and the finalizer's link request), accepting that embedded bundles can't declare it until a format bump; or
    3. another mechanism you prefer.

    For the sidecar routes we'd extend the .options header version (or add a .requires sidecar) with the same fail-closed rule.

    Two smaller PR 2 points, unless you'd prefer otherwise:

    • Coherent discovery: have nvjitlink-sys expose the toolkit root it actually loaded from, and take libcudadevrt.a from that same root (CUDA_OXIDE_CUDADEVRT as an explicit override), so the archive and the linker can't come from different toolkits. The archive is pinned in a new materializer handshake and recipe version, and the load-time cache key includes it.
    • The fixture that genuinely requires the archive would call cudaGraphLaunch, because cudaGraphSetConditional alone links without it.
  4. lucifer1004 commented on Sep 30, 2026

    @lucifer1004
    ContributorAuthor

    An update from implementing PR 3 (cudaGraphSetConditional), with one change to the plan and one correction to my earlier comment.

    cudaGraphSetConditional doesn't need the NVVM route. The plan said to select NVVM for direct and reachable helper calls. Measured with CUDA 13.3 on sm_120:

    • nvcc -ptx (whole-program, no -rdc) emits a plain .extern .func cudaGraphSetConditional. ptxas without -c accepts it and records it as a driver-resolved extern (externs: cudaGraphSetConditional), not as an unresolved-symbol error. The header declares it __cudart_builtin__.
    • A cuda-oxide graph example with an IF conditional node gives the right result on both routes: flag 1 runs the body, 0 skips it, 7 runs it. The routes are ordinary PTX JIT-loaded by the driver, and NVVM IR → LTOIR → nvJitLink cubin.
    • Forcing NVVM also broke the smoketest's --full-debug census, which builds through the direct LLVM PTX route.

    So the PR keeps the curated registry (exact C ABI, resolution route, CUDA 12.3 minimum), but the only route is "driver-resolved at module load". A listed call:

    • is declared and checked against its ABI, so a mistyped declaration fails at lowering with call to CUDA device runtime API ... does not match its C signature;
    • changes neither the output route nor the link;
    • is accepted by standalone PTX.

    Any other extern keeps its current meaning. This also means PR 3 no longer depends on PR 2. It sits directly on main, so the artifact-format question above only matters for PR 2 and any later archive-resolved API.

    Correction for PR 2. I said its archive fixture would call cudaGraphLaunch. That's wrong: libcudadevrt.a doesn't define cudaGraphLaunch (the driver resolves it too). The archive does define cudaMalloc and similar (via __cudaCDP2*); without it, ptxas fails with "Unresolved extern function". So PR 2's fixture calls cudaMalloc.

    The PR 3 branch is ready: https://github.com/lucifer1004/cuda-oxide/tree/feat/graph-set-conditional. It adds the registry, the ABI check, cuda_device::graph::{ConditionalHandle, set_conditional} with the same-graph/context and no-racing safety contract, the graph_conditional GPU example (standard smoketest lane, compile-only and full-debug pass), and book updates. I'll open it once PR 1 settles, unless you'd rather see it now.

  5. added
    cuda-oxide
    on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    build-relatedcargo-oxidecodegencuda-featurecuda-oxidedevice-apisenhancementepicexamplesteststracking

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions