Skip to content

Add cp.async copy intrinsics for global-to-shared transfers - #179

Closed
honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:upstream-cp-async-copy
Closed

honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:upstream-cp-async-copy

Conversation

@honeyspoon

Copy link
Copy Markdown
Contributor

Summary

Adds cp.async copy intrinsics for asynchronous global-to-shared memory transfers. These are the Ampere (SM80+) async copy primitives that bypass L1 cache and enable overlapping compute with memory transfers.

Variants added:

  • cp_async_cg_16 — copy 16 bytes, cache at global level (L2 only)
  • cp_async_ca_16 — copy 16 bytes, cache at all levels (L1 + L2)

Full 4-layer pipeline for each variant:

  1. cuda-device: Public safe Rust API (async_copy module)
  2. dialect-nvvm: Pliron IR operations (CpAsyncCg16Op, CpAsyncCa16Op)
  3. mir-importer: MIR → IR translation with pointer validation
  4. mir-lower: IR → LLVM inline asm lowering (cp.async.cg.shared.global, cp.async.ca.shared.global)

Design notes:

  • Both variants take (dst_smem_ptr, src_global_ptr) — shared memory destination, global source
  • Lowering emits PTX inline assembly with correct address space constraints
  • The cg vs ca distinction controls L1 cache behavior (bypass vs cache)

Test plan

  • Lowering tests: test_cp_async_cg_16, test_cp_async_ca_16
  • Verify inline asm contains correct PTX mnemonics
  • cargo clippy clean
  • cargo fmt clean

Runs rustfmt, clippy, and unit tests on packages that don't need the
CUDA toolkit. Triggers on every push to PR branches.
Add unit tests for CpAsyncCg16Op and CpAsyncCa16Op using the new
mir-lower testing framework. Also fix dialect_llvm → llvm_export
import in cp_async.rs.
- Escape bare args[N] brackets in rustdoc comments
- Run rustfmt on interface_impls
- Add cross-references between cg/ca cache policy variants
@honeyspoon honeyspoon closed this Jun 12, 2026
@honeyspoon
honeyspoon deleted the upstream-cp-async-copy branch June 12, 2026 18:51
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
…VIDIA#258)

Soundness and correctness fixes from the 2026-09 code and documentation
audit, plus the documentation corrections. The cuda-oxide `simt` surface and
the VMM modules are in a separate PR.

cuda-core / cuda-bindings
- Device::load_module_from_bytes (and the cuda-async wrapper) are unsafe fn:
  cuModuleLoadData takes no length, so a truncated cubin reads past the slice.
- Stream::launch_host_function{,_with_sync_mode} require F: 'static and
  reclaim the boxed closure when the enqueue fails.
- Streams of borrowed devices never enter the process-wide stream pool; a
  later owned device could reuse a handle from a destroyed external context.
- The async memory wrappers return Result instead of panicking; callers
  propagate, Drop impls ignore. get_device_attribute returns Err and
  api_version surfaces its CUresult.
- Host copies build their Vec with Vec::with_capacity instead of a raw
  allocation that was never null-checked and could be zero-sized.
- curand generators bind to the executing stream (RNG::set_stream,
  RNG::new_on_stream); random tensors no longer race the legacy default
  stream against stream-ordered allocation.
- DType is an unsafe trait carrying the bit-validity contract; the
  foreign-borrow constructors state it.
- The driver-unavailable hint is attached to CUDA_ERROR_NOT_INITIALIZED, the
  code the shims actually return; cu_launch_host_func falls back to
  cuLaunchHostFunc when the driver lacks the _v2 entry point; device ordinals
  that do not fit c_int are rejected.

cuda-async
- DeviceFuture has a Drop: an in-flight result is released only after the
  stream proves completion (idle: one query; busy: synchronize; capturing or
  faulted: leak loudly). Supersedes the approach in NVIDIA#179.
- Execute-once ops (shared, unzip) use a mutex and condvar and give a
  consumer on another stream an event dependency on the producer; the
  manual Send/Sync impls over UnsafeCells are gone.
- AsyncKernelLaunch frees its arguments with the type they were boxed as.
- A device fault after registration resolves the future with the error
  instead of hanging it and spinning the reactor.
- ExecutionContext::alloc_async returns Result; Tensor::uninitialized and the
  copy constructors surface a failed allocation as the operation's error so
  callers can retry instead of aborting.
- The execution lock is an RAII guard, and then_unchecked really releases it
  for its closure.
- GraphLaunch shares the instantiated graph through an Arc; CudaGraph::update
  is restricted to unit-output GraphNodes under the lock; capture ends the
  capture on panic and error; the thread-local device map survives failed
  init and lookups; the completion flag uses Release/Acquire.

cutile / cutile-macro
- Prelude reshape on an owned tensor validates the element count (it built
  shapes larger than their storage); .generics() overrides are checked
  against the tensors' element types; mutable partitions of &mut Tensor
  require unique storage; try_partition returns Err as documented.
- api::memcpy borrows its tensors for the lifetime of the op.
- atomic_rmw_tko and atomic_cas_tko are unsafe fn like load_ptr_tko and
  store_ptr_tko.
- Generated launchers are GraphNodes only over GraphNode inputs, which needs
  a nameable argument op (KernelArgs, PrepareInput, PrepareOutput,
  implemented for up to 64 arguments); compile()/specialize() run under the
  execution lock and drain the stream; reshape and view use checked
  arithmetic; the trial log is keyed on source hash and tileiras
  fingerprint; #[cutile::entry] keys and literal kinds are validated at
  expansion and a bare boolean key means true; an unwritable dump dir fails
  the launch instead of panicking.

cutile-compiler / cutile-ir
- A return below the function body and a break inside for are spanned
  errors instead of silently falling through or producing IR the assembler
  rejects. The prefill GQA kernel's early-exit guards become one conditional.
- Integer / rounds toward zero (Rust semantics); u8 and u16 are unsigned in
  every signedness-carrying op; && and || short-circuit.
- Module-level consts resolve in the scope of the module that names them.
- Bounds-check hoisting stays sound under continue, step_by and extents near
  i32::MAX; in-place checks test the actual index.
- Bytecode floor 13.2 with loud version negotiation; print_tko encodes its
  token correctly; frontend panics on valid input are spanned errors;
  CUDA_HOME and targets/ layouts are honored at run time.

Docs: tutorials and references match the code (signatures, imports, tile
size types, deprecated APIs, dump stages, env vars, cache keys), the
changelog leads with the 0.3.1 breaking changes and the 0.3.0 fallback, covers
everything since 0.3.0, and stale claims in crate and
module docs are corrected. The root README is unchanged.

Verified on an RTX 5090 with CUDA 13.3: cargo fmt, cargo clippy
--all-features with no new warnings, the CPU test script and the GPU test
script; new regression tests cover every behavioral fix.

Signed-off-by: Melih Elibol <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant