diff --git a/content/cuda/docs/async-copy/DOC.md b/content/cuda/docs/async-copy/DOC.md new file mode 100644 index 00000000..354b8cfe --- /dev/null +++ b/content/cuda/docs/async-copy/DOC.md @@ -0,0 +1,117 @@ +--- +name: async-copy +description: "CUDA async copy essentials: cooperative_groups::memcpy_async, cuda::pipeline, wait rules, and the bridge to cp.async/TMA." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,async-copy,memcpy_async,cuda::pipeline,cuda::barrier,cp.async,tma,shared-memory" +--- + +# CUDA Async Copy (C++) + +Use this page for the CUDA C++ view of asynchronous copies from global memory to shared memory and the synchronization rules around them. + +## What Problem It Solves + +A conventional copy into shared memory: + +```cpp +shared[idx] = global[idx]; +``` + +typically expands into: + +1. load from global memory into a register +2. store from register into shared memory + +Async copy can avoid that register staging path on supported hardware and can overlap data movement with computation. + +## Main CUDA C++ Entry Points + +Two common interfaces appear in NVIDIA documentation: + +- `cooperative_groups::memcpy_async(...)` +- `cuda::memcpy_async(...)` together with `cuda::pipeline` or `cuda::barrier` + +At a high level, both start an async transfer and require an explicit wait before the data in shared memory is consumed. + +## Fundamental Safety Rule + +After initiating the async copy: + +- do not read the destination shared memory until the corresponding wait completes +- do not modify the source or destination participating region while the transfer is in flight + +Until the wait completes, reading or writing the participating data can create a data race. + +## Cooperative Groups Pattern + +```cpp +namespace cg = cooperative_groups; + +auto block = cg::this_thread_block(); +extern __shared__ float smem[]; + +cg::memcpy_async(block, smem, gmem_ptr, bytes); +cg::wait(block); +block.sync(); +``` + +Use `cg::wait(group)` before consuming the copied shared-memory data. + +## Pipeline Pattern + +For newer CUDA C++ paths, `cuda::pipeline` can express staged copy/compute overlap. + +The common structure is: + +1. acquire / start pipeline stage +2. issue `cuda::memcpy_async` +3. commit or advance the stage +4. wait for the prior stage +5. compute on the completed shared-memory tile + +This is the higher-level CUDA C++ bridge to lower-level async copy hardware behavior. + +## When Hardware Acceleration Matters + +NVIDIA documents that on compute capability 8.0 and higher, async copies from global to shared memory can benefit from hardware acceleration that avoids an intermediate register path. + +That does not remove the need for: + +- alignment discipline +- correct wait behavior +- sensible shared-memory layout + +## When To Escalate To PTX / TMA + +Stay in CUDA C++ docs when: + +- you are using `memcpy_async` +- you need pipeline-level copy/compute overlap +- you want a supported C++ interface + +Drop to PTX / TMA docs when: + +- you need precise `cp.async` group semantics +- you need bulk async copies or TMA +- you need `mbarrier` or cluster-scope completion behavior + +## Related Topics + +- Shared memory usage: `../shared-memory/DOC.md` +- Synchronization rules: `../synchronization/DOC.md` +- Cooperative Groups: `../cooperative-groups/DOC.md` +- PTX `cp.async`: `../ptx/instructions/data-movement/references/cp-async.md` +- PTX TMA: `../ptx/instructions/tma/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Programming Guide, Asynchronous Data Copies: https://docs.nvidia.com/cuda/archive/13.1.1/cuda-programming-guide/04-special-topics/async-copies.html +- CUDA Programming Guide, Cooperative Groups async copy examples: https://docs.nvidia.com/cuda/archive/11.8.0/cuda-c-programming-guide/index.html +- CUDA Programming Guide, `memcpy_async` and `cuda::pipeline`: https://docs.nvidia.com/cuda/archive/11.6.2/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/atomics-and-reductions/DOC.md b/content/cuda/docs/atomics-and-reductions/DOC.md new file mode 100644 index 00000000..aa8b6b91 --- /dev/null +++ b/content/cuda/docs/atomics-and-reductions/DOC.md @@ -0,0 +1,94 @@ +--- +name: atomics-and-reductions +description: "CUDA atomics and reduction essentials: atomicAdd, shared/global scope, warp-first reduction, and common tradeoffs." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,atomics,reduction,atomicAdd,atomicCAS,shared-memory,warp-reduction" +--- + +# CUDA Atomics And Reductions (C++) + +Use this page when deciding between direct atomics, shared-memory reductions, and warp-first reduction patterns. + +## Atomic Basics + +An atomic operation performs a read-modify-write sequence as one atomic transaction on a word in global or shared memory. + +Common examples: + +- `atomicAdd` +- `atomicCAS` +- `atomicMax` +- `atomicMin` + +Atomics are correct tools for contention-sensitive updates, but they can serialize hot spots. + +## Scope Choice + +- shared-memory atomics are useful for contention within one block +- global-memory atomics are visible across blocks but usually cost more under heavy contention + +A common pattern is: + +1. reduce within a warp +2. reduce within a block using shared memory +3. emit one global atomic per block + +## Preferred Reduction Structure + +For many reductions, do not start with one atomic per thread. + +Better default: + +- first use warp shuffle reduction +- then combine warp results in shared memory +- then write one value per block or one atomic per block + +This reduces contention and memory traffic. + +## When Direct Atomics Are Fine + +Direct global atomics are often acceptable when: + +- the output has low contention +- the kernel is not dominated by the atomic path +- simplicity matters more than peak throughput + +Examples: + +- histogram with many bins and good distribution +- sparse accumulation with low collision probability + +## When Atomics Become A Problem + +Expect trouble when: + +- many threads update the same location +- the output space is very small +- the kernel becomes serialization-bound + +In those cases, switch to hierarchical reduction or privatization. + +## Minimal Strategy Guide + +- one scalar result per block: block reduction in shared memory +- one scalar result for the whole grid: block reduction plus final stage +- many bins with moderate collisions: shared-memory privatization, then flush +- warp-local aggregation: use shuffle before touching shared or global memory + +## Related Topics + +- Shared memory staging: `../shared-memory/DOC.md` +- Warp-level collectives: `../warp-primitives/DOC.md` +- Synchronization rules: `../synchronization/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, atomic functions: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, reduction and shared-memory patterns: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/benchmarking-methodology/DOC.md b/content/cuda/docs/benchmarking-methodology/DOC.md new file mode 100644 index 00000000..4a41274b --- /dev/null +++ b/content/cuda/docs/benchmarking-methodology/DOC.md @@ -0,0 +1,74 @@ +--- +name: benchmarking-methodology +description: "CUDA benchmarking methodology essentials: warmup, synchronization discipline, stable inputs, percentile reporting, and fair comparisons." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,benchmark,methodology,warmup,timing,percentile,variance,fair-comparison" +--- + +# CUDA Benchmarking Methodology (C++) + +Use this page when you need benchmark numbers that are comparable and reproducible. + +## Core Rules + +1. measure steady state, not cold start. +2. use correct synchronization for the scope being measured. +3. keep input shapes and distributions fixed across variants. +4. report variability, not just one best run. + +## Warmup + +Always include warmup iterations before measurement to absorb: + +- JIT or first-use overheads +- cache/allocator/transient startup effects + +## Timing Discipline + +For kernel timing: + +- use event-based timing around the measured stream segment +- avoid mixing host wall-clock timing with unsynchronized device work + +For end-to-end latency: + +- include all relevant host/device stages intentionally +- document what is excluded + +## Comparison Hygiene + +- same hardware and driver/toolkit +- same input set and batch strategy +- same precision and algorithm settings +- same determinism flags where relevant + +Any mismatch here can invalidate claimed speedups. + +## Reporting + +Report at least: + +- median +- p90/p95 (or similar tail percentile) +- run-to-run variance + +Single minimum time is not sufficient for production-facing claims. + +## Related Topics + +- Streams and events: `../streams-and-events/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` +- NVTX profiling workflow: `../nvtx-and-profiling-workflow/DOC.md` +- Regression testing and CI: `../regression-testing-and-ci/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, measurement and optimization workflow context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA Runtime API, event timing APIs: https://docs.nvidia.com/cuda/cuda-runtime-api/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/blackwell-mx-numerical-formats/DOC.md b/content/cuda/docs/blackwell-mx-numerical-formats/DOC.md new file mode 100644 index 00000000..2aaaa552 --- /dev/null +++ b/content/cuda/docs/blackwell-mx-numerical-formats/DOC.md @@ -0,0 +1,67 @@ +--- +name: blackwell-mx-numerical-formats +description: "Blackwell microscaling (MX) numeric formats essentials: MXFP8, MXFP4, MXINT8 layout requirements, scale factor management, and precision trade-offs." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,blackwell,mx,mx-formats,mxfp8,mxfp4,mxint8,microscaling,scale-factor,tcgen05" +--- + +# Blackwell MX Numerical Formats (C++) + +Use this page when designing kernels that leverage Blackwell's Microscaling (MX) formats for extreme memory bandwidth efficiency and high-throughput inference/training. + +## The Microscaling (MX) Paradigm + +Standard floating-point formats use one exponent per element. Microscaling formats group multiple elements (typically a vector of 32 values) under a shared scale factor (often an E8M0 representation). + +- **Benefit:** Drastically reduces memory footprint and increases effective memory bandwidth. +- **Cost:** Requires careful dynamic range analysis and block-level quantization awareness. + +## Supported MX Formats + +Blackwell Tensor Cores (`tcgen05`) introduce robust support for several block-scaled formats: + +- **MXFP8:** Microscaled 8-bit floating point (E4M3 or E5M2 underlying data) +- **MXFP4:** Microscaled 4-bit floating point (E2M1 underlying data) +- **MXINT8:** Microscaled 8-bit integer +- **MXFP6:** (Where applicable in specialized paths) + +## Memory Layout and Scale Factors + +The layout of MX tensors is highly constrained by the hardware matrix instruction interfaces: + +- Elements are stored contiguously in memory. +- The shared scale factor is typically laid out alongside or explicitly interleaved depending on the PTX instruction (`wgmma` or `tma` paths) requirements. +- Standard sizes: a 1-byte scale factor usually applies to a block of 32 individual elements. + +## Scale Factor Management + +Scale factors must be computed prior to the MMA operation, usually during the quantization phase of a previous operator (e.g., inside an activation fusion kernel). + +**Anti-Pattern:** Computing the scale factor dynamically within the inner loop of the GEMM. This introduces massive dependency stalls. + +**Best Practice:** +- Fuse the max-reduction and scale-factor extraction into the preceding LayerNorm/RMSNorm, saving the scale factors to a separate tensor. +- Use TMA to load both the quantized data and the scale factors into shared memory concurrently. + +## Accuracy vs Throughput + +MXFP4 provides the highest throughput but risks underflow/overflow if outlier values dominate the scale factor for a block of 32. MXFP8 provides a safer dynamic range for early training phases or activation tensors with higher variance. + +## Related Topics + +- PTX tcgen05 instructions: `../ptx/instructions/tcgen05/DOC.md` +- Numerics and precision: `../numerics-and-precision/DOC.md` +- Tensor Core pipeline patterns: `../tensor-core-pipeline-patterns/DOC.md` +- FP8 training and inference: `../fp8-training-and-inference-playbook/DOC.md` + +## Official Source Links (Fact Check) + +- Compute Data Formats (NVIDIA): https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#compute-data-formats +- PTX ISA, tcgen05 mma instructions: https://docs.nvidia.com/cuda/parallel-thread-execution/#tcgen05-mma + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/build-and-abi-compatibility/DOC.md b/content/cuda/docs/build-and-abi-compatibility/DOC.md new file mode 100644 index 00000000..2c69e868 --- /dev/null +++ b/content/cuda/docs/build-and-abi-compatibility/DOC.md @@ -0,0 +1,72 @@ +--- +name: build-and-abi-compatibility +description: "CUDA build and ABI compatibility essentials: arch targets, PTX/SASS forward-compat strategy, runtime/driver constraints, and packaging hygiene." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,build,abi,compatibility,sm-arch,ptx,sass,nvcc,driver-runtime" +--- + +# CUDA Build And ABI Compatibility (C++) + +Use this page when shipping CUDA binaries across different GPU architectures and deployment environments. + +## Targeting Strategy + +Build artifacts can include: + +- SASS for specific SM architectures +- PTX for forward compatibility via JIT on newer compatible drivers + +A common practical strategy is to include both: + +- native SASS for known deployment GPUs +- PTX fallback for future-compatible targets + +## Why Compatibility Breaks + +Typical mismatch classes: + +- runtime-toolkit vs driver capability mismatch +- missing arch target in build flags +- ABI or dependency mismatch in host integration + +Treat compatibility as part of release engineering, not a last-minute fix. + +## NVCC Arch Hygiene + +Use explicit arch targets and document them in build config. + +- keep `-gencode` matrix aligned with actual fleet GPUs +- avoid shipping only one narrow arch unless environment is fixed + +## Runtime/Driver Considerations + +- new toolkits can require minimum driver versions +- deployment systems may lag driver updates + +Validate on representative driver/toolkit combinations before release. + +## Package-Level Practices + +- pin toolkit version in CI +- record compile flags in build metadata +- verify cold-start JIT overhead if PTX fallback is expected +- add smoke tests per target GPU class + +## Related Topics + +- Error handling and debug build: `../error-handling-and-debug-build/DOC.md` +- Runtime API overview: `../runtime/DOC.md` +- PTX ISA overview: `../ptx/DOC.md` + +## Official Source Links (Fact Check) + +- NVCC Compiler Driver documentation: https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html +- CUDA Compatibility documentation: https://docs.nvidia.com/deploy/cuda-compatibility/index.html +- CUDA Installation Guide (version/driver context): https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/cache-behavior-and-access-policy/DOC.md b/content/cuda/docs/cache-behavior-and-access-policy/DOC.md new file mode 100644 index 00000000..24ca3df3 --- /dev/null +++ b/content/cuda/docs/cache-behavior-and-access-policy/DOC.md @@ -0,0 +1,73 @@ +--- +name: cache-behavior-and-access-policy +description: "CUDA cache-behavior essentials: locality patterns, read-only paths, L2 persistence windows, and access-policy tradeoffs." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cache,l2,access-policy,persistence-window,read-only-cache,locality,stream-attributes" +--- + +# CUDA Cache Behavior And Access Policy (C++) + +Use this page when kernels are bandwidth-limited and cache behavior is the next bottleneck. + +## First Principle + +No cache hint compensates for fundamentally poor locality. + +Always fix: + +- coalescing +- reuse distance +- working set shape + +before tuning cache policy knobs. + +## Read-Only And Locality-Aware Access + +Read-only paths and locality-aware layouts can reduce memory traffic pressure. + +- group neighboring accesses by neighboring threads +- avoid random scatter in the hottest loops +- keep reused regions compact when possible + +## L2 Access Policy Window + +CUDA exposes stream-level access-policy controls for L2 persistence behavior. + +- set stream attributes for persistence windows +- use them only for demonstrably reused regions +- tune hit ratio assumptions carefully + +Overusing persistence windows can hurt other traffic and reduce global efficiency. + +## Practical Workflow + +1. identify hotspot kernels. +2. confirm memory-bound behavior with profiling. +3. improve layout/coalescing first. +4. test cache/access-policy changes incrementally. +5. keep only changes that improve end-to-end latency. + +## Common Pitfalls + +- setting cache policy globally without per-kernel evidence +- treating cache hints as deterministic guarantees +- ignoring multi-stream interference in shared cache resources + +## Related Topics + +- Coalescing: `../coalescing/DOC.md` +- Data layout and alignment: `../data-layout-and-alignment/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, L2 persistence/access-policy window APIs: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, memory-system optimization context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/coalescing/DOC.md b/content/cuda/docs/coalescing/DOC.md new file mode 100644 index 00000000..296a5271 --- /dev/null +++ b/content/cuda/docs/coalescing/DOC.md @@ -0,0 +1,132 @@ +--- +name: coalescing +description: "CUDA global-memory coalescing essentials: contiguous access, pitch, striding, and when shared memory helps." +metadata: + languages: "cpp" + versions: "13.0" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,coalescing,memory-coalescing,coalesced-access,uncoalesced-access,global-memory,memory-bandwidth,stride,pitch,shared-memory,transpose" +--- + +# CUDA Memory Coalescing (C++) + +Use this page for global-memory access-pattern rules that determine whether a kernel uses bandwidth efficiently. + +## What Coalescing Means + +Coalescing is the hardware combining a warp's global-memory accesses into as few memory transactions as possible. + +At a high level: + +- adjacent threads should usually access adjacent addresses +- strided or scattered access wastes bandwidth +- good coalescing matters most in memory-bound kernels + +## Best Default Pattern + +For a 1D array, prefer: + +```cpp +int i = blockIdx.x * blockDim.x + threadIdx.x; +value = input[i]; +``` + +This maps neighboring threads to neighboring elements. + +## Common Bad Pattern + +Patterns like this often destroy coalescing: + +```cpp +int i = blockIdx.x * blockDim.x + threadIdx.x; +value = input[i * stride]; +``` + +Large stride across a warp usually turns one efficient transaction pattern into many inefficient ones. + +## 2D Arrays and Pitch + +For 2D row-major arrays, accesses are most efficient when: + +- threads move along the row dimension together +- row width is aligned well for warp-based access + +If width is not naturally aligned for the hardware, use pitched allocation: + +- `cudaMallocPitch` +- `cudaMemcpy2D` + +This is the standard fix when row width is awkward and rows need padding. + +## Shared Memory As A Reordering Tool + +Shared memory is often used together with coalescing: + +- load from global memory in a coalesced pattern +- reorder in shared memory +- consume in the algorithm's preferred order + +This is a common pattern for: + +- transpose +- tiled GEMM +- stencil halos +- gather/scatter restructuring + +## Coalescing vs Bank Conflicts + +These are different problems: + +- coalescing concerns global-memory transactions +- bank conflicts concern shared-memory accesses + +A kernel can have good coalescing and bad shared-memory banking, or the reverse. + +## Practical Heuristics + +- if a warp reads a row of contiguous elements, that is usually good +- if a warp reads a column from a row-major array directly, that is usually bad +- if a transpose-like pattern is needed, use shared memory to convert the access pattern +- align vectorized loads when using `float2` / `float4` + +## Minimal Tiling Pattern + +```cpp +__shared__ float tile[32][33]; + +int x = blockIdx.x * 32 + threadIdx.x; +int y = blockIdx.y * 32 + threadIdx.y; + +tile[threadIdx.y][threadIdx.x] = input[y * width + x]; +__syncthreads(); +``` + +This style is common because: + +- the global load can be coalesced +- the padded shared tile helps avoid bank conflicts during transposed access + +## When To Suspect Coalescing Problems + +- bandwidth is far below expectation +- profiling shows many global-memory transactions per requested byte +- a transpose or gather/scatter kernel is unexpectedly slow +- changing block shape changes performance dramatically + +## Related Topics + +- Shared memory usage: `../shared-memory/DOC.md` +- Synchronization rules: `../synchronization/DOC.md` +- Memory-space selection: `../memory-hierarchy/DOC.md` +- Runtime API overview: `../runtime/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, optimizing memory access: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA C++ Best Practices Guide, coalesced access to global memory: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html#coalesced-access-to-global-memory +- CUDA C++ Best Practices Guide, shared memory and matrix multiplication examples: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html#shared-memory +- CUDA C++ Programming Guide, 2D arrays and pitched allocation: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/collective-communication-patterns/DOC.md b/content/cuda/docs/collective-communication-patterns/DOC.md new file mode 100644 index 00000000..f7d55132 --- /dev/null +++ b/content/cuda/docs/collective-communication-patterns/DOC.md @@ -0,0 +1,66 @@ +--- +name: collective-communication-patterns +description: "CUDA collective communication essentials: reductions, scans, histogram-like updates, and hierarchical aggregation patterns." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,collective,reduction,scan,histogram,aggregation,warp-collective,block-collective" +--- + +# CUDA Collective Communication Patterns (C++) + +Use this page for patterns where many threads combine, distribute, or summarize values. + +## Common Collective Types + +- reduction (sum/max/min/etc.) +- scan/prefix sum +- histogram and bucketized accumulation +- vote/ballot-based filtering + +## Hierarchical Strategy + +A standard high-performance pattern is hierarchical: + +1. intra-warp collective (shuffle/vote) +2. intra-block collective (shared memory) +3. cross-block aggregation (global memory or multi-stage kernel) + +This minimizes global contention. + +## Reduction Pattern + +- reduce in warp first with `__shfl*_sync` +- write one value per warp to shared memory +- final block reduction +- optionally one global write/atomic per block + +## Scan Pattern + +- use block-local scan primitives +- stitch block boundaries in a second phase when global prefix is required + +Avoid forcing a single global synchronization model in one monolithic kernel. + +## Histogram-Like Pattern + +- privatize bins per warp/block when feasible +- merge privately accumulated bins later + +Direct global atomics on a small bin set are usually the worst-case path. + +## Related Topics + +- Warp primitives: `../warp-primitives/DOC.md` +- Atomics and reductions: `../atomics-and-reductions/DOC.md` +- Synchronization: `../synchronization/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, warp intrinsics and synchronization primitives: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, reduction and memory optimization context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/compute-bound-kernel-optimization-playbook/DOC.md b/content/cuda/docs/compute-bound-kernel-optimization-playbook/DOC.md new file mode 100644 index 00000000..9a6ae433 --- /dev/null +++ b/content/cuda/docs/compute-bound-kernel-optimization-playbook/DOC.md @@ -0,0 +1,65 @@ +--- +name: compute-bound-kernel-optimization-playbook +description: "Compute-bound kernel optimization playbook: instruction mix, occupancy/ILP balance, register pressure control, and path selection." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,compute-bound,optimization,instruction-mix,occupancy,ilp,register-pressure,cuda-core,tensor-core" +--- + +# Compute-Bound Kernel Optimization Playbook (C++) + +Use this page after profiling indicates arithmetic throughput is the dominant limiter. + +## Primary Objectives + +- Improve useful instruction issue rate. +- Reduce dependency and scheduling stalls. +- Select the right arithmetic path (CUDA Core vs Tensor Core). + +## High-Impact Levers + +- Improve instruction mix in hot loops. +- Balance occupancy and ILP. +- Control register usage to avoid spill-driven regressions. +- Evaluate Tensor Core migration only when workload shape supports it. + +## Triage Sequence + +1. Confirm the kernel is truly compute-bound after memory cleanup. +2. Inspect stall reasons related to dependencies and issue efficiency. +3. Tune unroll depth and block geometry together. +4. Re-evaluate path selection (`cuda-core` vs `wmma`/Tensor Core). + +## Common Failure Modes + +- Aggressive unrolling increases spills and slows kernel. +- Occupancy chasing hurts per-warp progress. +- Tensor Core migration applied to non-matrix-like workloads. + +## Verification Checklist + +- Throughput metrics improve with stable correctness. +- Register spills do not increase unexpectedly. +- End-to-end runtime improves for production-representative shapes. + +## Related Topics + +- Compute throughput: `../compute-throughput/DOC.md` +- CUDA Core path: `../cuda-core/DOC.md` +- CUDA Core optimization checklist: `../cuda-core-optimization-checklist/DOC.md` +- Tensor Cores: `../tensor-cores/DOC.md` +- CUDA Core vs Tensor Core path selection: `../cuda-core-vs-tensor-core-path-selection/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, arithmetic throughput context: https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- CUDA C++ Best Practices Guide: https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/compute-throughput/DOC.md b/content/cuda/docs/compute-throughput/DOC.md new file mode 100644 index 00000000..1c4e9d3a --- /dev/null +++ b/content/cuda/docs/compute-throughput/DOC.md @@ -0,0 +1,105 @@ +--- +name: compute-throughput +description: "CUDA compute-throughput essentials: arithmetic throughput tables, latency hiding, and when Tensor Cores beat ordinary arithmetic paths." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,throughput,compute-bound,fp32,fp16,int32,cuda-core,tensor-core,latency-hiding" +--- + +# CUDA Compute Throughput (C++) + +Use this page to reason about whether a kernel is limited by ordinary arithmetic throughput, Tensor Core throughput, or memory behavior. + +## The First Split + +Ask this first: + +- is the kernel memory-bound? +- or is it compute-bound? + +If memory traffic dominates, moving from ordinary arithmetic to Tensor Cores may not help much until memory behavior is fixed. + +## Ordinary Arithmetic Path + +The CUDA Programming Guide publishes per-SM throughput tables for native arithmetic instructions. + +These tables show that: + +- throughput depends strongly on architecture +- FP32, FP16, INT32, and FP64 do not have the same peak rates +- per-SM throughput must be multiplied by SM count for whole-device peak + +So a generic "CUDA Core throughput" number is not enough by itself. The relevant question is which instruction family the kernel actually uses. + +## Tensor Core Path + +Tensor Cores can provide much higher matrix-multiply-accumulate throughput than ordinary scalar arithmetic paths when: + +- the algorithm is matrix-multiply-like +- supported data types are acceptable +- tile shapes and layouts match the API and hardware requirements +- data staging overhead does not erase the gains + +This is why GEMM, attention, and convolution-like kernels are common Tensor Core candidates, while control-heavy kernels usually are not. + +## Throughput Is Not Just Peak Math + +A kernel can miss peak throughput because of: + +- dependency chains that the scheduler cannot hide +- low occupancy +- poor instruction mix +- register pressure +- memory stalls before arithmetic units are saturated + +So "Tensor Core capable" does not imply "Tensor Core efficient". + +## Practical Decision Rule + +Stay on the ordinary arithmetic path when: + +- the operation is elementwise or irregular +- there is too much branching or indexing complexity +- supported Tensor Core types or layouts do not fit the problem + +Move toward Tensor Cores when: + +- the kernel is dominated by dense matrix multiply-accumulate +- the math can be tiled at warp granularity +- data movement can be organized cleanly + +## What To Check In Practice + +- achieved memory bandwidth +- achieved occupancy +- instruction mix +- whether warp-level matrix instructions are present +- whether the kernel is actually compute-bound after memory optimization + +## Related Topics + +- Execution model: `../execution-model/DOC.md` +- CUDA Core path: `../cuda-core/DOC.md` +- CUDA Core optimization checklist: `../cuda-core-optimization-checklist/DOC.md` +- Occupancy tuning: `../occupancy/DOC.md` +- Tensor Core API usage: `../tensor-cores/DOC.md` +- WMMA debugging checklist: `../wmma-debugging-checklist/DOC.md` +- Tensor Core pipeline patterns: `../tensor-core-pipeline-patterns/DOC.md` +- Tensor Core numerical validation: `../tensor-core-numerical-validation/DOC.md` +- CUDA Core vs Tensor Core path selection: `../cuda-core-vs-tensor-core-path-selection/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` +- Shared memory staging: `../shared-memory/DOC.md` +- Numerics and precision: `../numerics-and-precision/DOC.md` +- Fused kernel design patterns: `../fused-kernel-design-patterns/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, arithmetic instruction throughput tables: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, instruction-throughput interpretation: https://docs.nvidia.com/cuda/archive/11.7.0/cuda-c-programming-guide/index.html +- Turing Tuning Guide, SM execution resources and latency hiding discussion: https://docs.nvidia.com/cuda/archive/12.4.0/turing-tuning-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/cooperative-groups/DOC.md b/content/cuda/docs/cooperative-groups/DOC.md new file mode 100644 index 00000000..1a775076 --- /dev/null +++ b/content/cuda/docs/cooperative-groups/DOC.md @@ -0,0 +1,104 @@ +--- +name: cooperative-groups +description: "CUDA Cooperative Groups essentials: thread_block, tiled_partition, coalesced_threads, cluster groups, and collective participation rules." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cooperative-groups,thread_block,tiled_partition,coalesced_threads,this_grid,this_cluster,group-sync" +--- + +# CUDA Cooperative Groups (C++) + +Use this page when kernels need explicit group objects rather than hard-coding assumptions about blocks and warps. + +## Why Cooperative Groups Exists + +Cooperative Groups makes the participating set of threads explicit. + +Instead of assuming "all threads in the block" or "one warp", code can pass a group object into a helper and make the collective scope explicit. + +This improves: + +- software composition +- readability +- portability across newer GPU behaviors + +## Common Group Handles + +Frequently used accessors include: + +- `this_thread_block()` +- `this_grid()` +- `coalesced_threads()` +- `this_cluster()` + +Common types and concepts include: + +- `thread_group` +- `thread_block` +- tiled partitions +- cluster groups + +## Basic Thread Block Example + +```cpp +namespace cg = cooperative_groups; + +cg::thread_block block = cg::this_thread_block(); +block.sync(); +``` + +`block.sync()` is the Cooperative Groups form of block-wide synchronization. + +## Tiled Partition + +Use `tiled_partition()` to decompose a block into smaller groups: + +```cpp +auto block = cg::this_thread_block(); +auto tile32 = cg::tiled_partition(block, 32); +``` + +This is useful for warp-sized or sub-warp collectives without manually reasoning about lane groups everywhere in the code. + +## Participation Rule + +Collective operations require correct participation. + +- all threads in the group must participate in collective operations +- the group handle should be created consistently +- it is best to obtain implicit groups early, before divergence + +Violating participation assumptions leads to undefined behavior. + +## Practical Guidance + +- pass group handles by reference into helper functions +- prefer specialized groups instead of over-generic abstractions when performance matters +- create implicit handles early in the kernel + +## Where It Connects To Other Features + +Cooperative Groups is the user-facing bridge for several advanced CUDA features: + +- tiled warp/block decomposition +- async copy collectives like `memcpy_async` +- cluster groups with `this_cluster()` + +## Related Topics + +- Synchronization rules: `../synchronization/DOC.md` +- Warp primitives: `../warp-primitives/DOC.md` +- Async copy: `../async-copy/DOC.md` +- Thread Block Clusters: `../thread-block-clusters/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Programming Guide, Cooperative Groups: https://docs.nvidia.com/cuda/cuda-programming-guide/04-special-topics/cooperative-groups.html +- CUDA Programming Guide, classic Cooperative Groups overview: https://docs.nvidia.com/cuda/archive/9.2/cuda-c-programming-guide/ +- CUDA Programming Guide, modern cluster and implicit-group accessors: https://docs.nvidia.com/cuda/archive/13.1.1/cuda-programming-guide/01-introduction/programming-model.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/cublas-cudnn-integration-patterns/DOC.md b/content/cuda/docs/cublas-cudnn-integration-patterns/DOC.md new file mode 100644 index 00000000..9c486942 --- /dev/null +++ b/content/cuda/docs/cublas-cudnn-integration-patterns/DOC.md @@ -0,0 +1,71 @@ +--- +name: cublas-cudnn-integration-patterns +description: "CUDA library integration essentials: cuBLAS/cuDNN handle lifecycle, stream binding, workspace policy, and mixed custom-kernel pipelines." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cublas,cudnn,integration,handle,stream-binding,workspace,mixed-pipeline" +--- + +# cuBLAS/cuDNN Integration Patterns (C++) + +Use this page when combining custom CUDA kernels with cuBLAS or cuDNN calls. + +## Handle Lifecycle + +Library handles should usually be: + +- created once per host thread/context +- reused across iterations +- destroyed at controlled shutdown + +Frequent create/destroy in hot paths adds overhead. + +## Stream Binding Rule + +Bind library handles to the correct stream before issuing calls. + +- cuBLAS/cuDNN work should run in the intended stream +- stream mismatch causes accidental serialization or race-like ordering bugs + +## Workspace Strategy + +Many cuDNN and some cuBLAS paths use temporary workspace. + +- allocate and reuse workspace buffers where possible +- avoid repeated malloc/free during steady-state loops +- keep workspace sizing policy consistent with algorithm selection + +## Mixed Pipelines + +Common pattern: + +1. pre/post-processing in custom kernels +2. dense math in cuBLAS/cuDNN +3. follow-up custom kernels + +Use events/stream ordering rather than global synchronization between stages. + +## Determinism And Performance + +Algorithm choices can trade determinism and speed. + +- production training/inference pipelines should explicitly document determinism expectations +- benchmark with the exact settings that production will use + +## Related Topics + +- Streams and events: `../streams-and-events/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- cuBLAS documentation: https://docs.nvidia.com/cuda/cublas/index.html +- cuDNN documentation: https://docs.nvidia.com/deeplearning/cudnn/latest/ +- CUDA Runtime API (stream interoperability): https://docs.nvidia.com/cuda/cuda-runtime-api/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/cuda-core-optimization-checklist/DOC.md b/content/cuda/docs/cuda-core-optimization-checklist/DOC.md new file mode 100644 index 00000000..71d9ed4f --- /dev/null +++ b/content/cuda/docs/cuda-core-optimization-checklist/DOC.md @@ -0,0 +1,73 @@ +--- +name: cuda-core-optimization-checklist +description: "CUDA Core optimization checklist: coalescing, divergence control, occupancy/ILP balancing, and measurement-first tuning." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cuda-core,optimization,checklist,coalescing,divergence,occupancy,ilp,register-pressure,latency-hiding" +--- + +# CUDA Core Optimization Checklist (C++) + +Use this page when a kernel is intentionally on the ordinary arithmetic path and needs systematic optimization. + +## Step 1: Confirm The Bottleneck Class + +Before changing code, classify the kernel: + +- memory-bound +- compute-bound +- launch/orchestration-bound + +Use profiling first. Do not optimize blind. + +## Step 2: Memory Access Quality + +- Ensure global-memory accesses are coalesced. +- Reduce redundant loads with reuse (register/shared memory where appropriate). +- Avoid severe shared-memory bank conflicts in staging buffers. + +## Step 3: Control Flow Quality + +- Reduce divergence in hot warps. +- Make branch conditions uniform where possible. +- Move rare-path logic off hot loops when feasible. + +## Step 4: Occupancy And ILP Balance + +- Avoid maximizing occupancy as a standalone goal. +- Tune block size, unroll depth, and register footprint together. +- Improve ILP when scoreboard/dependency stalls dominate. + +## Step 5: Validate Every Optimization + +- Reprofile after each major change. +- Track throughput, stall mix, occupancy, and memory metrics together. +- Keep correctness checks and numerical checks in the loop. + +## Common Anti-Patterns + +- Chasing one metric (for example occupancy) while total throughput worsens. +- Heavy unrolling that increases register spills. +- Introducing shared memory without fixing access pattern quality. + +## Related Topics + +- CUDA Core path overview: `../cuda-core/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Occupancy: `../occupancy/DOC.md` +- Coalescing: `../coalescing/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` +- Bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide: https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- CUDA C++ Best Practices Guide: https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/cuda-core-vs-tensor-core-path-selection/DOC.md b/content/cuda/docs/cuda-core-vs-tensor-core-path-selection/DOC.md new file mode 100644 index 00000000..9bf072b5 --- /dev/null +++ b/content/cuda/docs/cuda-core-vs-tensor-core-path-selection/DOC.md @@ -0,0 +1,92 @@ +--- +name: cuda-core-vs-tensor-core-path-selection +description: "Path selection guide: deciding between CUDA Core and Tensor Core execution using workload shape, dtype, layout, and numerical constraints." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cuda-core,tensor-core,path-selection,wmma,wgmma,dtype,layout,precision,fallback" +--- + +# CUDA Core vs Tensor Core Path Selection (C++) + +Use this page when deciding whether to implement or keep a kernel on ordinary arithmetic pipelines or move it to Tensor Core matrix instructions. + +## Fast Decision Matrix + +Choose CUDA Core path first when: + +- operation is elementwise, reduction-heavy, sparse, or control-heavy +- matrix structure is weak or tile reuse is poor +- required dtype/layout does not map cleanly to Tensor Core-supported combinations + +Choose Tensor Core path first when: + +- workload is dominated by dense matrix-multiply-accumulate +- shape and layout can be tiled consistently at warp or warpgroup granularity +- allowed dtype/accumulation policy matches supported Tensor Core paths + +## Data-Type And Numerics Gate + +Before migration, verify: + +- multiplicand and accumulator types are supported by the target path +- error budget tolerates the chosen precision policy +- baseline parity tests pass with realistic input distributions + +If these checks fail, forcing Tensor Core instructions can create unstable numerics or hidden fallback behavior. + +## Layout And Staging Gate + +Tensor Core speedups depend on movement cost. + +Require: + +- consistent layout contracts (`row_major`/`col_major`, leading dimensions) +- efficient shared-memory staging plan +- synchronization protocol that does not serialize hot loops + +If memory behavior remains dominant after staging optimization, keep CUDA Core path and optimize arithmetic/memory overlap there. + +## Performance Validation Protocol + +1. Build a correctness baseline. +2. Profile CUDA Core implementation to identify real bottlenecks. +3. Implement Tensor Core path candidate. +4. Compare throughput, memory pressure, occupancy, and stall behavior. +5. Keep the faster path under expected production shapes, not just synthetic peak cases. + +## Fallback Strategy + +Production kernels should keep explicit fallback behavior: + +- capability checks for architecture/toolchain support +- shape or dtype guards for unsupported combinations +- deterministic fallback to CUDA Core implementation + +This avoids silent behavior drift across deployment environments. + +## Practical Rule Of Thumb + +- Default to CUDA Core path for generality and low complexity. +- Move to Tensor Core path for matrix-dense hotspots after profiling confirms arithmetic throughput is the limiting factor. +- Keep both paths when workload diversity is high. + +## Related Topics + +- CUDA Core path: `../cuda-core/DOC.md` +- Tensor Core overview: `../tensor-cores/DOC.md` +- WMMA practical patterns: `../wmma-kernel-patterns/DOC.md` +- Tensor Core pipeline patterns: `../tensor-core-pipeline-patterns/DOC.md` +- Fallback/capability detection: `../fallback-strategies-and-capability-detection/DOC.md` +- Numerics and precision: `../numerics-and-precision/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide (execution model, WMMA, memory model): https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- CUDA C++ Best Practices Guide (memory and throughput guidance): https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/cuda-core/DOC.md b/content/cuda/docs/cuda-core/DOC.md new file mode 100644 index 00000000..e63a79b8 --- /dev/null +++ b/content/cuda/docs/cuda-core/DOC.md @@ -0,0 +1,91 @@ +--- +name: cuda-core +description: "CUDA Core path essentials: SIMT arithmetic pipelines, warp scheduling, ILP/occupancy tradeoffs, and practical optimization workflow." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cuda-core,simt,fp32,int32,warp,scheduler,ilp,occupancy,latency-hiding" +--- + +# CUDA Core Path (C++) + +Use this page for kernels that run on ordinary SM arithmetic pipelines (the path developers usually call "CUDA Core path"), not Tensor Core matrix instructions. + +## What This Means In Practice + +For CUDA C++ kernels, "CUDA Core path" usually means: + +- ordinary scalar or vector arithmetic instructions (FP32, INT32, FP64, and related ops) +- SIMT warp execution on standard SM arithmetic pipelines +- no explicit warp-matrix API (`wmma`) and no PTX warpgroup matrix instructions (`wgmma`) + +There is no separate CUDA C++ API named "CUDA Core". The distinction is a performance and execution-model distinction. + +## Typical Workloads + +Kernels that usually remain on this path: + +- elementwise transforms +- reductions and scans with limited matrix structure +- indexing-heavy or branch-heavy kernels +- irregular sparse kernels + +Even in ML workloads, many preprocessing, activation, normalization, and indexing phases are CUDA Core dominated. + +## Optimization Checklist + +1. Make global memory access coalesced. +2. Remove avoidable divergence in hot warps. +3. Balance occupancy and register pressure instead of maximizing occupancy blindly. +4. Increase instruction-level parallelism where dependency chains are long. +5. Validate cache and shared-memory behavior before deep unrolling. + +## Occupancy vs ILP Tradeoff + +Two common failure modes: + +- **High occupancy, low per-warp progress:** too little ILP, frequent dependency stalls. +- **High ILP, low occupancy:** register usage or shared-memory usage blocks enough resident warps. + +Tune block size, unroll factors, and register usage together. Treat occupancy as a means to hide latency, not as the final objective. + +## How To Verify You Are On This Path + +In profiler output, check whether runtime is dominated by ordinary arithmetic instruction activity and not matrix instruction activity. Also check: + +- warp stall reasons (dependency, memory throttling, execution dependency) +- achieved occupancy +- memory throughput utilization +- instruction mix consistency with kernel intent + +If your intended Tensor Core kernel shows only ordinary arithmetic activity, the path selection is wrong. + +## When To Escalate To Tensor Cores + +Move to Tensor Cores when all are true: + +- workload is dominated by dense matrix-multiply-accumulate +- data types and layouts match supported matrix instruction paths +- staging and synchronization overhead can be controlled +- numerical policy is acceptable (for example FP16/BF16/TF32 with chosen accumulation) + +## Related Topics + +- Execution model: `../execution-model/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Occupancy: `../occupancy/DOC.md` +- Warp primitives: `../warp-primitives/DOC.md` +- Tensor Cores: `../tensor-cores/DOC.md` +- Path selection guide: `../cuda-core-vs-tensor-core-path-selection/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, SIMT and warp execution: https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- CUDA C++ Programming Guide, arithmetic instruction throughput interpretation: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- Turing Tuning Guide, latency hiding and scheduler behavior: https://docs.nvidia.com/cuda/archive/12.4.0/turing-tuning-guide/index.html + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/cuda-graphs/DOC.md b/content/cuda/docs/cuda-graphs/DOC.md new file mode 100644 index 00000000..027478a1 --- /dev/null +++ b/content/cuda/docs/cuda-graphs/DOC.md @@ -0,0 +1,104 @@ +--- +name: cuda-graphs +description: "CUDA Graphs essentials: definition, instantiation, execution, stream capture, cross-stream event capture, and update rules." +metadata: + languages: "cpp" + versions: "12.6" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,cuda-graphs,graph,stream-capture,cudaStreamBeginCapture,cudaGraphLaunch,cudaGraphInstantiate" +--- + +# CUDA Graphs (C++) + +Use this page when the same workflow launches repeatedly and CPU launch overhead from streams becomes significant. + +## Why Graphs Exist + +CUDA Graphs separate work submission into: + +1. definition +2. instantiation +3. execution + +This amortizes setup work and can reduce CPU launch overhead compared with issuing many short kernels one by one into streams. + +## Two Creation Paths + +Graphs can be created by: + +- explicit graph APIs +- stream capture + +Stream capture is often the easiest migration path for existing stream-based code. + +## Stream Capture + +Typical pattern: + +```cpp +cudaGraph_t graph; + +cudaStreamBeginCapture(stream); +kernelA<<>>(...); +kernelB<<>>(...); +cudaStreamEndCapture(stream, &graph); +``` + +During capture, work is appended to a graph instead of being immediately enqueued for execution. + +## Event-Based Cross-Stream Capture + +CUDA documents that stream capture can preserve cross-stream dependencies expressed with: + +- `cudaEventRecord()` +- `cudaStreamWaitEvent()` + +provided the waited-on event belongs to the same capture graph. + +## Execution Lifecycle + +After a graph is defined: + +- instantiate it into an executable graph +- launch the executable graph into a stream +- reuse it many times if the workflow is stable + +Graphs help most when the structure is repeated often enough to amortize instantiation. + +## Common Capture Hazards + +- using unsupported APIs during capture +- mixing captured and non-captured dependencies incorrectly +- synchronizing captured streams or captured events in invalid ways +- relying on legacy default stream behavior during capture + +When a capture is invalidated, the graph becomes unusable and capture must be ended. + +## When Graphs Help + +Graphs are especially useful when: + +- kernels are short and launch overhead is material +- the workflow topology repeats +- stream orchestration logic is otherwise host-heavy + +They are less useful when: + +- the workload shape changes every iteration +- the overhead is dominated by kernel execution, not launch + +## Related Topics + +- Streams and events: `../streams-and-events/DOC.md` +- Runtime API overview: `../runtime/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, CUDA Graphs overview: https://docs.nvidia.com/cuda/archive/12.6.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, stream capture and cross-stream events: https://docs.nvidia.com/cuda/archive/11.7.0/cuda-c-programming-guide/index.html +- CUDA Programming Guide, earlier graph API examples: https://docs.nvidia.com/cuda/archive/12.2.0/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/cute-layout-and-tensor-primer/DOC.md b/content/cuda/docs/cute-layout-and-tensor-primer/DOC.md new file mode 100644 index 00000000..969b47ae --- /dev/null +++ b/content/cuda/docs/cute-layout-and-tensor-primer/DOC.md @@ -0,0 +1,68 @@ +--- +name: cute-layout-and-tensor-primer +description: "CUTLASS 3.x / CuTe core abstractions: Layouts (Shape + Stride hierarchy), Tensors, and mappings to TMA / WGMMA instructions." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,cpp,cute,cutlass,layout,tensor,hopper,sm90,blackwell,sm100,wgmma,tma" +--- + +# CuTe Layout and Tensor Primer (C++) + +Use this page to understand `CuTe` (the core abstraction engine behind CUTLASS 3.x/4.x), which is the modern standard for writing Hopper (SM90) and Blackwell (SM100) kernels. + +## The Abstraction Gap + +Writing bare PTX (`wgmma`, `cp.async.bulk`) or relying purely on `nvcuda::wmma` creates brittle code when moving between tile shapes or architectures. + +CuTe solves this using algebraic concepts: +- **Layout:** A function mapping a logical multidimensional index (Shape) to a 1D physical offset (Stride). +- **Tensor:** A Memory Pointer coupled with a `Layout`. + +## Core Mechanics + +### 1. Hierarchical Shapes and Strides +In CuTe, shapes and strides are represented as `std::tuple`-like nested integers. +`Layout, Stride<_8, _1>>` describes a $4 \times 8$ row-major matrix. + +Because these are often compile-time constants (e.g., `_4`), the compiler aggressively optimizes the index algebra into bit-shifts and fast ALUs, eliminating integer modulo/division overhead in the inner loop. + +### 2. Tensors Everywhere +Everything in CuTe is a Tensor: global memory arrays, shared memory buffers, and even registers. By mapping a `Layout` to a register array, CuTe abstracts away the opaque "fragment" problem of `wmma`. + +```cpp +using namespace cute; +// Define a register tensor for the accumulator +Tensor acc = make_tensor(Shape<_16, _16>{}); +``` + +## Mapping to Hardware Instructions + +Hardware like TMA (Tensor Memory Accelerator) and WGMMA natively expect extremely specific memory alignments, strides, and thread-to-data distributions. + +CuTe bridges this via **TiledCopy** and **TiledMMA**: +- A `TiledCopy` takes a hardware capability (e.g., `SM90_TMA_LOAD`) and applies it to a layout. +- A `TiledMMA` takes a hardware capability (e.g., `SM90_64x64x16_F16F16F16F16_TN`) and defines how a thread block iterates over a larger algorithmic tile. + +## Why Agents Should Emit CuTe + +When automatically generating high-performance kernels, emitting CuTe C++ code is generally superior to emitting pure PTX: +1. CuTe handles the register coalescing and shared memory bank-conflict avoidance automatically through Swizzle templates. +2. It compiles down to the exact same SASS output as perfectly hand-tuned PTX. +3. Provides forward compatibility with newer SM architectures. + +## Related Topics + +- PTX WGMMA: `../ptx/instructions/wgmma/DOC.md` +- PTX TMA: `../ptx/instructions/tma/DOC.md` +- Tensor Core pipeline patterns: `../tensor-core-pipeline-patterns/DOC.md` + +## Official Source Links (Fact Check) + +- CUTLASS 3.0 CuTe Documentation: https://github.com/NVIDIA/cutlass/tree/main/media/docs/cute +- GTC 2023 CuTe Tutorial: https://github.com/NVIDIA/cutlass/tree/main/examples/cute/tutorial + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/data-layout-and-alignment/DOC.md b/content/cuda/docs/data-layout-and-alignment/DOC.md new file mode 100644 index 00000000..05281964 --- /dev/null +++ b/content/cuda/docs/data-layout-and-alignment/DOC.md @@ -0,0 +1,80 @@ +--- +name: data-layout-and-alignment +description: "CUDA data-layout and alignment essentials: struct packing, vectorized loads/stores, pitch/stride choices, and alignment-driven performance." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,data-layout,alignment,vectorized-load,vectorized-store,pitch,stride,coalescing" +--- + +# CUDA Data Layout And Alignment (C++) + +Use this page when kernel performance depends on memory layout details. + +## Why Layout Matters + +On CUDA GPUs, layout affects: + +- coalescing behavior +- transaction count +- shared-memory bank behavior +- feasibility of vectorized loads/stores + +Poor layout can dominate runtime even when arithmetic is optimized. + +## Alignment Basics + +Prefer natural alignment for data types and vectorized access. + +- align pointers and base addresses to vector width +- keep struct fields ordered to reduce padding surprises +- avoid accidental misalignment from custom allocators or byte offsets + +## AoS vs SoA + +For many throughput-oriented kernels: + +- SoA (structure of arrays) is often better for coalesced parallel access +- AoS (array of structs) can be easier semantically but may scatter accessed fields + +Choose based on the access pattern of active threads, not only code convenience. + +## Vectorized Access + +Vectorized loads/stores (`float2`, `float4`, etc.) are useful when: + +- data is aligned to the vector width +- adjacent threads follow contiguous access +- vectorization does not introduce awkward tail handling overhead + +Always verify achieved bandwidth after vectorization; assumptions are often wrong. + +## 2D Layouts + +For 2D tensors/arrays: + +- row-major contiguous row access is usually easiest to coalesce +- use pitched allocation when row width alignment is problematic +- treat logical shape and physical stride as separate concepts in APIs + +## Common Pitfalls + +- hidden misalignment from packed/byte-offset structs +- mixing row-major assumptions with column-oriented access +- forcing vectorized access on unaligned data + +## Related Topics + +- Coalescing: `../coalescing/DOC.md` +- Shared memory: `../shared-memory/DOC.md` +- Memory hierarchy: `../memory-hierarchy/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, memory access patterns and alignment context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA C++ Programming Guide, memory model and type/layout background: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/driver-checkpoint/DOC.md b/content/cuda/docs/driver-checkpoint/DOC.md new file mode 100644 index 00000000..f45996fe --- /dev/null +++ b/content/cuda/docs/driver-checkpoint/DOC.md @@ -0,0 +1,153 @@ +--- +name: driver-checkpoint +description: '**Source:** group__CUDA__CHECKPOINT.html#group__CUDA__CHECKPOINT' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.37. CUDA Checkpointing + +**Source:** group__CUDA__CHECKPOINT.html#group__CUDA__CHECKPOINT + + +### Functions + +CUresult cuCheckpointProcessCheckpoint ( int pid, CUcheckpointCheckpointArgs* args ) + + +Checkpoint a CUDA process's GPU memory contents. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`args` + \- Optional checkpoint operation arguments + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_ILLEGAL_STATECUDA_ERROR_NOT_SUPPORTED + +###### Description + +Checkpoints a CUDA process specified by `pid` that is in the LOCKED state. The GPU memory contents will be brought into host memory and all underlying references will be released. Process must be in the LOCKED state to checkpoint. + +Upon successful return the process will be in the CHECKPOINTED state. + +CUresult cuCheckpointProcessGetRestoreThreadId ( int pid, int* tid ) + + +Returns the restore thread ID for a CUDA process. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`tid` + \- Returned restore thread ID + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_NOT_SUPPORTED + +###### Description + +Returns in `*tid` the thread ID of the CUDA restore thread for the process specified by `pid`. + +CUresult cuCheckpointProcessGetState ( int pid, CUprocessState* state ) + + +Returns the process state of a CUDA process. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`state` + \- Returned CUDA process state + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_NOT_SUPPORTED + +###### Description + +Returns in `*state` the current state of the CUDA process specified by `pid`. + +CUresult cuCheckpointProcessLock ( int pid, CUcheckpointLockArgs* args ) + + +Lock a running CUDA process. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`args` + \- Optional lock operation arguments + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_ILLEGAL_STATECUDA_ERROR_NOT_SUPPORTEDCUDA_ERROR_NOT_READY + +###### Description + +Lock the CUDA process specified by `pid` which will block further CUDA API calls. Process must be in the RUNNING state in order to lock. + +Upon successful return the process will be in the LOCKED state. + +If timeoutMs is specified and the timeout is reached the process will be left in the RUNNING state upon return. + +CUresult cuCheckpointProcessRestore ( int pid, CUcheckpointRestoreArgs* args ) + + +Restore a CUDA process's GPU memory contents from its last checkpoint. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`args` + \- Optional restore operation arguments + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_ILLEGAL_STATECUDA_ERROR_NOT_SUPPORTED + +###### Description + +Restores a CUDA process specified by `pid` from its last checkpoint. Process must be in the CHECKPOINTED state to restore. + +GPU UUID pairs can be specified in `args` to remap the process old GPUs onto new GPUs. The GPU to restore onto needs to have enough memory and be of the same chip type as the old GPU. If an array of GPU UUID pairs is specified, it must contain every checkpointed GPU. + +Upon successful return the process will be in the LOCKED state. + +CUDA process restore requires persistence mode to be enabled or cuInit has not been called, any function from the driver API will return CUDA_ERROR_NOT_INITIALIZED.") to have been called before execution. + +CUresult cuCheckpointProcessUnlock ( int pid, CUcheckpointUnlockArgs* args ) + + +Unlock a CUDA process to allow CUDA API calls. + +###### Parameters + +`pid` + \- The process ID of the CUDA process +`args` + \- Optional unlock operation arguments + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUECUDA_ERROR_NOT_INITIALIZEDCUDA_ERROR_ILLEGAL_STATECUDA_ERROR_NOT_SUPPORTED + +###### Description + +Unlocks a process specified by `pid` allowing it to resume making CUDA API calls. Process must be in the LOCKED state. + +Upon successful return the process will be in the RUNNING state. + diff --git a/content/cuda/docs/driver-coredump/DOC.md b/content/cuda/docs/driver-coredump/DOC.md new file mode 100644 index 00000000..ea027fbc --- /dev/null +++ b/content/cuda/docs/driver-coredump/DOC.md @@ -0,0 +1,197 @@ +--- +name: driver-coredump +description: '**Source:** group__CUDA__COREDUMP.html#group__CUDA__COREDUMP' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.34. Coredump Attributes Control API + +**Source:** group__CUDA__COREDUMP.html#group__CUDA__COREDUMP + + +### Enumerations + +enum CUCoredumpGenerationFlags + +enum CUcoredumpSettings + + +### Functions + +CUresult cuCoredumpGetAttribute ( CUcoredumpSettings attrib, void* value, size_t* size ) + + +Allows caller to fetch a coredump attribute value for the current context. + +###### Parameters + +`attrib` + \- The enum defining which value to fetch. +`value` + \- void* containing the requested data. +`size` + \- The size of the memory region `value` points to. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Returns in `*value` the requested value specified by `attrib`. It is up to the caller to ensure that the data type and size of `*value` matches the request. + +If the caller calls this function with `*value` equal to NULL, the size of the memory region (in bytes) expected for `attrib` will be placed in `size`. + +The supported attributes are: + + * CU_COREDUMP_ENABLE_ON_EXCEPTION: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CU_COREDUMP_FILE. The default value is false unless set to true globally or locally, or the CU_CTX_USER_COREDUMP_ENABLE flag was set during context creation. + + * CU_COREDUMP_TRIGGER_HOST: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CU_COREDUMP_SKIP_ABORT flag to disable host device abort() if needed. + + * CU_COREDUMP_LIGHTWEIGHT: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false unless set to true globally or locally. This attribute is deprecated as of CUDA 12.5, please use CU_COREDUMP_GENERATION_FLAGS instead. + + * CU_COREDUMP_ENABLE_USER_TRIGGER: Bool where true means that a coredump can be created by writing to the system pipe specified by CU_COREDUMP_PIPE. The default value is false unless set to true globally or locally. + + * CU_COREDUMP_FILE: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application. + + * CU_COREDUMP_PIPE: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application. + + * CU_COREDUMP_GENERATION_FLAGS: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: + CU_COREDUMP_DEFAULT_FLAGS - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access + CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES \- Coredump will not include the data from CUDA source modules that are not relocated at runtime. + CU_COREDUMP_SKIP_GLOBAL_MEMORY \- Coredump will not include device-side global data that does not belong to any context. + CU_COREDUMP_SKIP_SHARED_MEMORY \- Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. + CU_COREDUMP_SKIP_LOCAL_MEMORY \- Coredump will not include local memory from the kernel. + CU_COREDUMP_LIGHTWEIGHT_FLAGS - Enables all of the above options. Equiavlent to setting the CU_COREDUMP_LIGHTWEIGHT attribute to true. + CU_COREDUMP_SKIP_ABORT - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CU_COREDUMP_TRIGGER_HOST but better reflects the default behavior. + + +CUresult cuCoredumpGetAttributeGlobal ( CUcoredumpSettings attrib, void* value, size_t* size ) + + +Allows caller to fetch a coredump attribute value for the entire application. + +###### Parameters + +`attrib` + \- The enum defining which value to fetch. +`value` + \- void* containing the requested data. +`size` + \- The size of the memory region `value` points to. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*value` the requested value specified by `attrib`. It is up to the caller to ensure that the data type and size of `*value` matches the request. + +If the caller calls this function with `*value` equal to NULL, the size of the memory region (in bytes) expected for `attrib` will be placed in `size`. + +The supported attributes are: + + * CU_COREDUMP_ENABLE_ON_EXCEPTION: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CU_COREDUMP_FILE. The default value is false. + + * CU_COREDUMP_TRIGGER_HOST: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CU_COREDUMP_SKIP_ABORT flag to disable host device abort() if needed. + + * CU_COREDUMP_LIGHTWEIGHT: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CU_COREDUMP_GENERATION_FLAGS instead. + + * CU_COREDUMP_ENABLE_USER_TRIGGER: Bool where true means that a coredump can be created by writing to the system pipe specified by CU_COREDUMP_PIPE. The default value is false. + + * CU_COREDUMP_FILE: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application. + + * CU_COREDUMP_PIPE: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application. + + * CU_COREDUMP_GENERATION_FLAGS: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: + CU_COREDUMP_DEFAULT_FLAGS - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access + CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES \- Coredump will not include the data from CUDA source modules that are not relocated at runtime. + CU_COREDUMP_SKIP_GLOBAL_MEMORY \- Coredump will not include device-side global data that does not belong to any context. + CU_COREDUMP_SKIP_SHARED_MEMORY \- Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. + CU_COREDUMP_SKIP_LOCAL_MEMORY \- Coredump will not include local memory from the kernel. + CU_COREDUMP_LIGHTWEIGHT_FLAGS - Enables all of the above options. Equiavlent to setting the CU_COREDUMP_LIGHTWEIGHT attribute to true. + CU_COREDUMP_SKIP_ABORT - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CU_COREDUMP_TRIGGER_HOST but better reflects the default behavior. + + +CUresult cuCoredumpSetAttribute ( CUcoredumpSettings attrib, void* value, size_t* size ) + + +Allows caller to set a coredump attribute value for the current context. + +###### Parameters + +`attrib` + \- The enum defining which value to set. +`value` + \- void* containing the requested data. +`size` + \- The size of the memory region `value` points to. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +This function should be considered an alternate interface to the CUDA-GDB environment variables defined in this document: + +An important design decision to note is that any coredump environment variable values set before CUDA initializes will take permanent precedence over any values set with this function. This decision was made to ensure no change in behavior for any users that may be currently using these variables to get coredumps. + +`*value` shall contain the requested value specified by `set`. It is up to the caller to ensure that the data type and size of `*value` matches the request. + +If the caller calls this function with `*value` equal to NULL, the size of the memory region (in bytes) expected for `set` will be placed in `size`. + +/note This function will return CUDA_ERROR_NOT_SUPPORTED if the caller attempts to set CU_COREDUMP_ENABLE_ON_EXCEPTION on a GPU of with Compute Capability < 6.0. cuCoredumpSetAttributeGlobal works on those platforms as an alternative. + +/note CU_COREDUMP_ENABLE_USER_TRIGGER and CU_COREDUMP_PIPE cannot be set on a per-context basis. + +The supported attributes are: + + * CU_COREDUMP_ENABLE_ON_EXCEPTION: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CU_COREDUMP_FILE. The default value is false. + + * CU_COREDUMP_TRIGGER_HOST: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CU_COREDUMP_SKIP_ABORT flag to disable host device abort() if needed. + + * CU_COREDUMP_LIGHTWEIGHT: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CU_COREDUMP_GENERATION_FLAGS instead. + + * CU_COREDUMP_FILE: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application. + + * CU_COREDUMP_GENERATION_FLAGS: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: + CU_COREDUMP_DEFAULT_FLAGS - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access + CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES \- Coredump will not include the data from CUDA source modules that are not relocated at runtime. + CU_COREDUMP_SKIP_GLOBAL_MEMORY \- Coredump will not include device-side global data that does not belong to any context. + CU_COREDUMP_SKIP_SHARED_MEMORY \- Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. + CU_COREDUMP_SKIP_LOCAL_MEMORY \- Coredump will not include local memory from the kernel. + CU_COREDUMP_LIGHTWEIGHT_FLAGS - Enables all of the above options. Equiavlent to setting the CU_COREDUMP_LIGHTWEIGHT attribute to true. + CU_COREDUMP_SKIP_ABORT - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CU_COREDUMP_TRIGGER_HOST but better reflects the default behavior. + + +CUresult cuCoredumpSetAttributeGlobal ( CUcoredumpSettings attrib, void* value, size_t* size ) + + +Allows caller to set a coredump attribute value globally. + +###### Parameters + +`attrib` + \- The enum defining which value to set. +`value` + \- void* containing the requested data. +`size` + \- The size of the memory region `value` points to. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED + +###### Description + +This function should be considered an alternate interface to the CUDA-GDB environment variables defined in this document: + +An important design decision to note is that any coredump environment variable values set before CUDA initializes will take permanent precedence over any values set with this function. This decision was made to ensure no change in behavior for any users that may be currently using these variables to get coredumps. + +`*value` shall contain the requested value specified by `set`. It is up to the caller to ensure that the data type and size of `*value` matches the request. + +If the caller calls this function with `*value` equal to NULL, the size of the memory region (in bytes) expected for `set` will be placed in `size`. + +The supported attributes are: + + * CU_COREDUMP_ENABLE_ON_EXCEPTION: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CU_COREDUMP_FILE. The default value is false. + + * CU_COREDUMP_TRIGGER_HOST: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CU_COREDUMP_SKIP_ABORT flag to disable host device abort() if needed. + + * CU_COREDUMP_LIGHTWEIGHT: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CU_COREDUMP_GENERATION_FLAGS instead. + + * CU_COREDUMP_ENABLE_USER_TRIGGER: Bool where true means that a coredump can be created by writing to the system pipe specified by CU_COREDUMP_PIPE. The default value is false. + + * CU_COREDUMP_FILE: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application. + + * CU_COREDUMP_PIPE: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. This value may not be changed after CU_COREDUMP_ENABLE_USER_TRIGGER is set to true. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application. + + * CU_COREDUMP_GENERATION_FLAGS: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: + CU_COREDUMP_DEFAULT_FLAGS - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access + CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES \- Coredump will not include the data from CUDA source modules that are not relocated at runtime. + CU_COREDUMP_SKIP_GLOBAL_MEMORY \- Coredump will not include device-side global data that does not belong to any context. + CU_COREDUMP_SKIP_SHARED_MEMORY \- Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. + CU_COREDUMP_SKIP_LOCAL_MEMORY \- Coredump will not include local memory from the kernel. + CU_COREDUMP_LIGHTWEIGHT_FLAGS - Enables all of the above options. Equiavlent to setting the CU_COREDUMP_LIGHTWEIGHT attribute to true. + CU_COREDUMP_SKIP_ABORT - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CU_COREDUMP_TRIGGER_HOST but better reflects the default behavior. + diff --git a/content/cuda/docs/driver-ctx--deprecated/DOC.md b/content/cuda/docs/driver-ctx--deprecated/DOC.md new file mode 100644 index 00000000..57e82a94 --- /dev/null +++ b/content/cuda/docs/driver-ctx--deprecated/DOC.md @@ -0,0 +1,129 @@ +--- +name: driver-ctx--deprecated +description: '**Source:** group__CUDA__CTX__DEPRECATED.html#group__CUDA__CTX__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.9. Context Management [DEPRECATED] + +**Source:** group__CUDA__CTX__DEPRECATED.html#group__CUDA__CTX__DEPRECATED + + +### Functions + +CUresult cuCtxAttach ( CUcontext* pctx, unsigned int flags ) + + +Increment a context's usage-count. + +###### Parameters + +`pctx` + \- Returned context handle of the current context +`flags` + \- Context attach flags (must be 0) + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +Note that this function is deprecated and should not be used. + +###### Description + +Increments the usage count of the context and passes back a context handle in `*pctx` that must be passed to cuCtxDetach() when the application is done with the context. cuCtxAttach() fails if there is no context current to the thread. + +Currently, the `flags` parameter must be 0. + +CUresult cuCtxDetach ( CUcontext ctx ) + + +Decrement a context's usage-count. + +###### Parameters + +`ctx` + \- Context to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Deprecated + +Note that this function is deprecated and should not be used. + +###### Description + +Decrements the usage count of the context `ctx`, and destroys the context if the usage count goes to 0. The context must be a handle that was passed back by cuCtxCreate() or cuCtxAttach(), and must be current to the calling thread. + +CUresult cuCtxGetSharedMemConfig ( CUsharedconfig* pConfig ) + + +Returns the current shared memory configuration for the current context. + +###### Parameters + +`pConfig` + \- returned shared memory configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +This function will return in `pConfig` the current size of shared memory banks in the current context. On devices with configurable shared memory banks, cuCtxSetSharedMemConfig can be used to change this setting, so that all subsequent kernel launches will by default use the new bank size. When cuCtxGetSharedMemConfig is called on devices without configurable shared memory, it will return the fixed bank size of the hardware. + +The returned bank configurations can be either: + + * CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: shared memory bank width is four bytes. + + * CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: shared memory bank width will eight bytes. + + +CUresult cuCtxSetSharedMemConfig ( CUsharedconfig config ) + + +Sets the shared memory configuration for the current context. + +###### Parameters + +`config` + \- requested shared memory configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +On devices with configurable shared memory banks, this function will set the context's shared memory bank size which is used for subsequent kernel launches. + +Changed the shared memory configuration between launches may insert a device side synchronization point between those launches. + +Changing the shared memory bank size will not increase shared memory usage or affect occupancy of kernels, but may have major effects on performance. Larger bank sizes will allow for greater potential bandwidth to shared memory, but will change what kinds of accesses to shared memory will result in bank conflicts. + +This function will do nothing on devices with fixed shared memory bank size. + +The supported bank configurations are: + + * CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE: set bank width to the default initial setting (currently, four bytes). + + * CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: set shared memory bank width to be natively four bytes. + + * CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: set shared memory bank width to be natively eight bytes. + + diff --git a/content/cuda/docs/driver-ctx/DOC.md b/content/cuda/docs/driver-ctx/DOC.md new file mode 100644 index 00000000..c64ea33b --- /dev/null +++ b/content/cuda/docs/driver-ctx/DOC.md @@ -0,0 +1,591 @@ +--- +name: driver-ctx +description: '**Source:** group__CUDA__CTX.html#group__CUDA__CTX' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.8. Context Management + +**Source:** group__CUDA__CTX.html#group__CUDA__CTX + + +### Functions + +CUresult cuCtxCreate ( CUcontext* pctx, CUctxCreateParams* ctxCreateParams, unsigned int flags, CUdevice dev ) + + +Create a CUDA context. + +###### Parameters + +`pctx` + \- Returned context handle of the new context +`ctxCreateParams` + \- Context creation parameters +`flags` + \- Context creation flags +`dev` + \- Device to create context on + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a new CUDA context and associates it with the calling thread. The `flags` parameter is described below. The context is created with a usage count of 1 and the caller of cuCtxCreate() must call cuCtxDestroy() when done using the context. If a context is already current to the thread, it is supplanted by the newly created context and may be restored by a subsequent call to cuCtxPopCurrent(). + +CUDA context can be created with execution affinity. The type and the amount of execution resource the context can use is limited by `paramsArray` and `numExecAffinityParams` in `execAffinity`. The `paramsArray` is an array of `CUexecAffinityParam` and the `numExecAffinityParams` describes the size of the paramsArray. If two `CUexecAffinityParam` in the array have the same type, the latter execution affinity parameter overrides the former execution affinity parameter. The supported execution affinity types are: + + * CU_EXEC_AFFINITY_TYPE_SM_COUNT limits the portion of SMs that the context can use. The portion of SMs is specified as the number of SMs via `CUexecAffinitySmCount`. This limit will be internally rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution affinity of the context via `cuCtxGetExecAffinity` after context creation. Currently, this attribute is only supported under Volta+ MPS. + + +CUDA context can be created in CIG(CUDA in Graphics) mode by setting `cigParams`. Data from graphics client is shared with CUDA via the `sharedData` in `cigParams`. Support for D3D12 graphics client can be determined using cuDeviceGetAttribute() with CU_DEVICE_ATTRIBUTE_D3D12_CIG_SUPPORTED. `sharedData` is a ID3D12CommandQueue handle. Support for Vulkan graphics client can be determined using cuDeviceGetAttribute() with CU_DEVICE_ATTRIBUTE_VULKAN_CIG_SUPPORTED. `sharedData` is a Nvidia specific data blob populated by calling vkGetExternalComputeQueueDataNV(). Either `execAffinityParams` or `cigParams` can be set to a non-null value. Setting both to a non-null value will result in an undefined behavior. + +The three LSBs of the `flags` parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context. + + * CU_CTX_SCHED_SPIN: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread. + + + * CU_CTX_SCHED_YIELD: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU. + + + * CU_CTX_SCHED_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. + + + * CU_CTX_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. + +**Deprecated:** This flag was deprecated as of CUDA 4.0 and was replaced with CU_CTX_SCHED_BLOCKING_SYNC. + + + * CU_CTX_SCHED_AUTO: The default value if the `flags` parameter is zero, uses a heuristic based on the number of active CUDA contexts in the process C and the number of logical processors in the system P. If C > P, then CUDA will yield to other OS threads when waiting for the GPU (CU_CTX_SCHED_YIELD), otherwise CUDA will not yield while waiting for results and actively spin on the processor (CU_CTX_SCHED_SPIN). Additionally, on Tegra devices, CU_CTX_SCHED_AUTO uses a heuristic based on the power profile of the platform and may choose CU_CTX_SCHED_BLOCKING_SYNC for low-powered devices. + + + * CU_CTX_MAP_HOST: Instruct CUDA to support mapped pinned allocations. This flag must be set in order to allocate pinned host memory that is accessible to the GPU. + + + * CU_CTX_LMEM_RESIZE_TO_MAX: Instruct CUDA to not reduce local memory after resizing local memory for a kernel. This can prevent thrashing by local memory allocations when launching many kernels with high local memory usage at the cost of potentially increased memory usage. + +**Deprecated:** This flag is deprecated and the behavior enabled by this flag is now the default and cannot be disabled. Instead, the per-thread stack size can be controlled with cuCtxSetLimit(). + + + * CU_CTX_COREDUMP_ENABLE: If GPU coredumps have not been enabled globally with cuCoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the "GPU core dump support" section. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling cuCoredumpSetAttribute from the created context after it becomes current. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode. + + + * CU_CTX_USER_COREDUMP_ENABLE: If user-triggered GPU coredumps have not been enabled globally with cuCoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the "GPU core dump support" section. It is important to note that the pipe name *must* be set with cuCoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CU_CTX_COREDUMP_ENABLE is set. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling cuCoredumpSetAttribute from the created context after it becomes current. Setting this flag on any context creation is equivalent to setting the CU_COREDUMP_ENABLE_USER_TRIGGER attribute to `true` globally. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode. + + + * CU_CTX_SYNC_MEMOPS: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled "API Synchronization behavior" to learn more about cases when synchronous memory operations can exhibit asynchronous behavior. + + +Context creation will fail with CUDA_ERROR_UNKNOWN if the compute mode of the device is CU_COMPUTEMODE_PROHIBITED. The function cuDeviceGetAttribute() can be used with CU_DEVICE_ATTRIBUTE_COMPUTE_MODE to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for * devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. + +Context creation will fail with :: CUDA_ERROR_INVALID_VALUE if invalid parameter was passed by client to create the CUDA context. + +Context creation in CIG mode will fail with CUDA_ERROR_NOT_SUPPORTED if CIG is not supported by the device or the driver. + +CUresult cuCtxDestroy ( CUcontext ctx ) + + +Destroy a CUDA context. + +###### Parameters + +`ctx` + \- Context to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Destroys the CUDA context specified by `ctx`. The context `ctx` will be destroyed regardless of how many threads it is current to. It is the responsibility of the calling function to ensure that no API call issues using `ctx` while cuCtxDestroy() is executing. + +Destroys and cleans up all resources associated with the context. It is the caller's responsibility to ensure that the context or its resources are not accessed or passed in subsequent API calls and doing so will result in undefined behavior. These resources include CUDA types CUmodule, CUfunction, CUstream, CUevent, CUarray, CUmipmappedArray, CUtexObject, CUsurfObject, CUtexref, CUsurfref, CUgraphicsResource, CUlinkState, CUexternalMemory and CUexternalSemaphore. These resources also include memory allocations by cuMemAlloc(), cuMemAllocHost(), cuMemAllocManaged() and cuMemAllocPitch(). + +If `ctx` is current to the calling thread then `ctx` will also be popped from the current thread's context stack (as though cuCtxPopCurrent() were called). If `ctx` is current to other threads, then `ctx` will remain current to those threads, and attempting to access `ctx` from those threads will result in the error CUDA_ERROR_CONTEXT_IS_DESTROYED. + +cuCtxDestroy() will not destroy memory allocations by cuMemCreate(), cuMemAllocAsync() and cuMemAllocFromPoolAsync(). These memory allocations are not associated with any CUDA context and need to be destroyed explicitly. + +CUresult cuCtxGetApiVersion ( CUcontext ctx, unsigned int* version ) + + +Gets the context's API version. + +###### Parameters + +`ctx` + \- Context to check +`version` + \- Pointer to version + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +Returns a version number in `version` corresponding to the capabilities of the context (e.g. 3010 or 3020), which library developers can use to direct callers to a specific API version. If `ctx` is NULL, returns the API version used to create the currently bound context. + +Note that new API versions are only introduced when context capabilities are changed that break binary compatibility, so the API version and driver version may be different. For example, it is valid for the API version to be 3020 while the driver version is 4020. + +CUresult cuCtxGetCacheConfig ( CUfunc_cache* pconfig ) + + +Returns the preferred cache configuration for the current context. + +###### Parameters + +`pconfig` + \- Returned cache configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +On devices where the L1 cache and shared memory use the same hardware resources, this function returns through `pconfig` the preferred cache configuration for the current context. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute functions. + +This will return a `pconfig` of CU_FUNC_CACHE_PREFER_NONE on devices where the size of the L1 cache and shared memory are fixed. + +The supported cache configurations are: + + * CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) + + * CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache + + * CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory + + * CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory + + +CUresult cuCtxGetCurrent ( CUcontext* pctx ) + + +Returns the CUDA context bound to the calling CPU thread. + +###### Parameters + +`pctx` + \- Returned context handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED + +###### Description + +Returns in `*pctx` the CUDA context bound to the calling CPU thread. If no context is bound to the calling CPU thread then `*pctx` is set to NULL and CUDA_SUCCESS is returned. + +CUresult cuCtxGetDevice ( CUdevice* device ) + + +Returns the device handle for the current context. + +###### Parameters + +`device` + \- Returned device handle for the current context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*device` the handle of the current context's device. + +CUresult cuCtxGetDevice_v2 ( CUdevice* device, CUcontext ctx ) + + +Returns the device handle for the specified context. + +###### Parameters + +`device` + \- Returned device handle for the specified context +`ctx` + \- Context for which to obtain the device + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*device` the handle of the specified context's device. If the specified context is NULL, the API will return the current context's device. + +CUresult cuCtxGetExecAffinity ( CUexecAffinityParam* pExecAffinity, CUexecAffinityType type ) + + +Returns the execution affinity setting for the current context. + +###### Parameters + +`pExecAffinity` + \- Returned execution affinity +`type` + \- Execution affinity type to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY + +###### Description + +Returns in `*pExecAffinity` the current value of `type`. The supported CUexecAffinityType values are: + + * CU_EXEC_AFFINITY_TYPE_SM_COUNT: number of SMs the context is limited to use. + + +CUresult cuCtxGetFlags ( unsigned int* flags ) + + +Returns the flags for the current context. + +###### Parameters + +`flags` + \- Pointer to store flags of current context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*flags` the flags of the current context. See cuCtxCreate for flag values. + +CUresult cuCtxGetId ( CUcontext ctx, unsigned long long* ctxId ) + + +Returns the unique Id associated with the context supplied. + +###### Parameters + +`ctx` + \- Context for which to obtain the Id +`ctxId` + \- Pointer to store the Id of the context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_CONTEXT_IS_DESTROYED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `ctxId` the unique Id which is associated with a given context. The Id is unique for the life of the program for this instance of CUDA. If context is supplied as NULL and there is one current, the Id of the current context is returned. + +CUresult cuCtxGetLimit ( size_t* pvalue, CUlimit limit ) + + +Returns resource limits. + +###### Parameters + +`pvalue` + \- Returned size of limit +`limit` + \- Limit to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNSUPPORTED_LIMIT + +###### Description + +Returns in `*pvalue` the current size of `limit`. The supported CUlimit values are: + + * CU_LIMIT_STACK_SIZE: stack size in bytes of each GPU thread. + + * CU_LIMIT_PRINTF_FIFO_SIZE: size in bytes of the FIFO used by the printf() device system call. + + * CU_LIMIT_MALLOC_HEAP_SIZE: size in bytes of the heap used by the malloc() and free() device system calls. + + * CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH: maximum grid depth at which a thread can issue the device runtime call cudaDeviceSynchronize() to wait on child grid launches to complete. + + * CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT: maximum number of outstanding device runtime launches that can be made from this context. + + * CU_LIMIT_MAX_L2_FETCH_GRANULARITY: L2 cache fetch granularity. + + * CU_LIMIT_PERSISTING_L2_CACHE_SIZE: Persisting L2 cache size in bytes + + +CUresult cuCtxGetStreamPriorityRange ( int* leastPriority, int* greatestPriority ) + + +Returns numerical values that correspond to the least and greatest stream priorities. + +###### Parameters + +`leastPriority` + \- Pointer to an int in which the numerical value for least stream priority is returned +`greatestPriority` + \- Pointer to an int in which the numerical value for greatest stream priority is returned + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*leastPriority` and `*greatestPriority` the numerical values that correspond to the least and greatest stream priorities respectively. Stream priorities follow a convention where lower numbers imply greater priorities. The range of meaningful stream priorities is given by [`*greatestPriority`, `*leastPriority`]. If the user attempts to create a stream with a priority value that is outside the meaningful range as specified by this API, the priority is automatically clamped down or up to either `*leastPriority` or `*greatestPriority` respectively. See cuStreamCreateWithPriority for details on creating a priority stream. A NULL may be passed in for `*leastPriority` or `*greatestPriority` if the value is not desired. + +This function will return '0' in both `*leastPriority` and `*greatestPriority` if the current context's device does not support stream priorities (see cuDeviceGetAttribute). + +CUresult cuCtxPopCurrent ( CUcontext* pctx ) + + +Pops the current CUDA context from the current CPU thread. + +###### Parameters + +`pctx` + \- Returned popped context handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Pops the current CUDA context from the CPU thread and passes back the old context handle in `*pctx`. That context may then be made current to a different CPU thread by calling cuCtxPushCurrent(). + +If a context was current to the CPU thread before cuCtxCreate() or cuCtxPushCurrent() was called, this function makes that context current to the CPU thread again. + +CUresult cuCtxPushCurrent ( CUcontext ctx ) + + +Pushes a context on the current CPU thread. + +###### Parameters + +`ctx` + \- Context to push + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Pushes the given context `ctx` onto the CPU thread's stack of current contexts. The specified context becomes the CPU thread's current context, so all CUDA functions that operate on the current context are affected. + +The previous current context may be made current again by calling cuCtxDestroy() or cuCtxPopCurrent(). + +CUresult cuCtxRecordEvent ( CUcontext hCtx, CUevent hEvent ) + + +Records an event. + +###### Parameters + +`hCtx` + \- Context to record event for +`hEvent` + \- Event to record + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Captures in `hEvent` all the activities of the context `hCtx` at the time of this call. `hEvent` and `hCtx` must be from the same CUDA context, otherwise CUDA_ERROR_INVALID_HANDLE will be returned. Calls such as cuEventQuery() or cuCtxWaitEvent() will then examine or wait for completion of the work that was captured. Uses of `hCtx` after this call do not modify `hEvent`. If the context passed to `hCtx` is the primary context, `hEvent` will capture all the activities of the primary context and its green contexts. If the context passed to `hCtx` is a context converted from green context via cuCtxFromGreenCtx(), `hEvent` will capture only the activities of the green context. + +The API will return CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED if the specified context `hCtx` has a stream in the capture mode. In such a case, the call will invalidate all the conflicting captures. + +CUresult cuCtxResetPersistingL2Cache ( void ) + + +Resets all persisting lines in cache to normal status. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +cuCtxResetPersistingL2Cache Resets all persisting lines in cache to normal status. Takes effect on function return. + +CUresult cuCtxSetCacheConfig ( CUfunc_cache config ) + + +Sets the preferred cache configuration for the current context. + +###### Parameters + +`config` + \- Requested cache configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +On devices where the L1 cache and shared memory use the same hardware resources, this sets through `config` the preferred cache configuration for the current context. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute the function. Any function preference set via cuFuncSetCacheConfig() or cuKernelSetCacheConfig() will be preferred over this context-wide setting. Setting the context-wide cache configuration to CU_FUNC_CACHE_PREFER_NONE will cause subsequent kernel launches to prefer to not change the cache configuration unless required to launch the kernel. + +This setting does nothing on devices where the size of the L1 cache and shared memory are fixed. + +Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point. + +The supported cache configurations are: + + * CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) + + * CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache + + * CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory + + * CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory + + +CUresult cuCtxSetCurrent ( CUcontext ctx ) + + +Binds the specified CUDA context to the calling CPU thread. + +###### Parameters + +`ctx` + \- Context to bind to the calling CPU thread + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Binds the specified CUDA context to the calling CPU thread. If `ctx` is NULL then the CUDA context previously bound to the calling CPU thread is unbound and CUDA_SUCCESS is returned. + +If there exists a CUDA context stack on the calling CPU thread, this will replace the top of that stack with `ctx`. If `ctx` is NULL then this will be equivalent to popping the top of the calling CPU thread's CUDA context stack (or a no-op if the calling CPU thread's CUDA context stack is empty). + +CUresult cuCtxSetFlags ( unsigned int flags ) + + +Sets the flags for the current context. + +###### Parameters + +`flags` + \- Flags to set on the current context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the flags for the current context overwriting previously set ones. See cuDevicePrimaryCtxSetFlags for flag values. + +CUresult cuCtxSetLimit ( CUlimit limit, size_t value ) + + +Set resource limits. + +###### Parameters + +`limit` + \- Limit to set +`value` + \- Size of limit + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNSUPPORTED_LIMIT, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Setting `limit` to `value` is a request by the application to update the current limit maintained by the context. The driver is free to modify the requested value to meet h/w requirements (this could be clamping to minimum or maximum values, rounding up to nearest element size, etc). The application can use cuCtxGetLimit() to find out exactly what the limit has been set to. + +Setting each CUlimit has its own specific restrictions, so each is discussed here. + + * CU_LIMIT_STACK_SIZE controls the stack size in bytes of each GPU thread. The driver automatically increases the per-thread stack size for each kernel launch as needed. This size isn't reset back to the original value after each launch. Setting this value will take effect immediately, and if necessary, the device will block until all preceding requested tasks are complete. + + + * CU_LIMIT_PRINTF_FIFO_SIZE controls the size in bytes of the FIFO used by the printf() device system call. Setting CU_LIMIT_PRINTF_FIFO_SIZE must be performed before launching any kernel that uses the printf() device system call, otherwise CUDA_ERROR_INVALID_VALUE will be returned. + + + * CU_LIMIT_MALLOC_HEAP_SIZE controls the size in bytes of the heap used by the malloc() and free() device system calls. Setting CU_LIMIT_MALLOC_HEAP_SIZE must be performed before launching any kernel that uses the malloc() or free() device system calls, otherwise CUDA_ERROR_INVALID_VALUE will be returned. + + + * CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH controls the maximum nesting depth of a grid at which a thread can safely call cudaDeviceSynchronize(). Setting this limit must be performed before any launch of a kernel that uses the device runtime and calls cudaDeviceSynchronize() above the default sync depth, two levels of grids. Calls to cudaDeviceSynchronize() will fail with error code cudaErrorSyncDepthExceeded if the limitation is violated. This limit can be set smaller than the default or up the maximum launch depth of 24. When setting this limit, keep in mind that additional levels of sync depth require the driver to reserve large amounts of device memory which can no longer be used for user allocations. If these reservations of device memory fail, cuCtxSetLimit() will return CUDA_ERROR_OUT_OF_MEMORY, and the limit can be reset to a lower value. This limit is only applicable to devices of compute capability < 9.0. Attempting to set this limit on devices of other compute capability versions will result in the error CUDA_ERROR_UNSUPPORTED_LIMIT being returned. + + + * CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT controls the maximum number of outstanding device runtime launches that can be made from the current context. A grid is outstanding from the point of launch up until the grid is known to have been completed. Device runtime launches which violate this limitation fail and return cudaErrorLaunchPendingCountExceeded when cudaGetLastError() is called after launch. If more pending launches than the default (2048 launches) are needed for a module using the device runtime, this limit can be increased. Keep in mind that being able to sustain additional pending launches will require the driver to reserve larger amounts of device memory upfront which can no longer be used for allocations. If these reservations fail, cuCtxSetLimit() will return CUDA_ERROR_OUT_OF_MEMORY, and the limit can be reset to a lower value. This limit is only applicable to devices of compute capability 3.5 and higher. Attempting to set this limit on devices of compute capability less than 3.5 will result in the error CUDA_ERROR_UNSUPPORTED_LIMIT being returned. + + + * CU_LIMIT_MAX_L2_FETCH_GRANULARITY controls the L2 cache fetch granularity. Values can range from 0B to 128B. This is purely a performance hint and it can be ignored or clamped depending on the platform. + + + * CU_LIMIT_PERSISTING_L2_CACHE_SIZE controls size in bytes available for persisting L2 cache. This is purely a performance hint and it can be ignored or clamped depending on the platform. + + +CUresult cuCtxSynchronize ( void ) + + +Block for the current context's tasks to complete. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Blocks until the current context has completed all preceding requested tasks. If the current context is the primary context, green contexts that have been created will also be synchronized. cuCtxSynchronize() returns an error if one of the preceding tasks failed. If the context was created with the CU_CTX_SCHED_BLOCKING_SYNC flag, the CPU thread will block until the GPU context has finished its work. + +CUresult cuCtxSynchronize_v2 ( CUcontext ctx ) + + +Block for the specified context's tasks to complete. + +###### Parameters + +`ctx` + \- Context to synchronize + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Blocks until the specified context has completed all preceding requested tasks. If the specified context is the primary context, green contexts that have been created will also be synchronized. The API returns an error if one of the preceding tasks failed. + +If the context was created with the CU_CTX_SCHED_BLOCKING_SYNC flag, the CPU thread will block until the GPU context has finished its work. + +If the specified context is NULL, the API will operate on the current context. + +CUresult cuCtxWaitEvent ( CUcontext hCtx, CUevent hEvent ) + + +Make a context wait on an event. + +###### Parameters + +`hCtx` + \- Context to wait +`hEvent` + \- Event to wait on + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Makes all future work submitted to context `hCtx` wait for all work captured in `hEvent`. The synchronization will be performed on the device and will not block the calling CPU thread. See cuCtxRecordEvent() for details on what is captured by an event. If the context passed to `hCtx` is the primary context, the primary context and its green contexts will wait for `hEvent`. If the context passed to `hCtx` is a context converted from green context via cuCtxFromGreenCtx(), the green context will wait for `hEvent`. + + * `hEvent` may be from a different context or device than `hCtx`. + + * The API will return CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED and invalidate the capture if the specified event `hEvent` is part of an ongoing capture sequence or if the specified context `hCtx` has a stream in the capture mode. + diff --git a/content/cuda/docs/driver-d3d10--deprecated/DOC.md b/content/cuda/docs/driver-d3d10--deprecated/DOC.md new file mode 100644 index 00000000..4a573a10 --- /dev/null +++ b/content/cuda/docs/driver-d3d10--deprecated/DOC.md @@ -0,0 +1,453 @@ +--- +name: driver-d3d10--deprecated +description: '**Source:** group__CUDA__D3D10__DEPRECATED.html#group__CUDA__D3D10__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.42.1. Direct3D 10 Interoperability [DEPRECATED] + +**Source:** group__CUDA__D3D10__DEPRECATED.html#group__CUDA__D3D10__DEPRECATED + + +### Enumerations + +enum CUD3D10map_flags + +enum CUD3D10register_flags + + +### Functions + +CUresult cuD3D10CtxCreate ( CUcontext* pCtx, CUdevice* pCudaDevice, unsigned int Flags, ID3D10Device* pD3DDevice ) + + +Create a CUDA context for interoperability with Direct3D 10. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`pCudaDevice` + \- Returned pointer to the device on which the context was created +`Flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D10 device in order to achieve maximum interoperability performance. + +CUresult cuD3D10CtxCreateOnDevice ( CUcontext* pCtx, unsigned int flags, ID3D10Device* pD3DDevice, CUdevice cudaDevice ) + + +Create a CUDA context for interoperability with Direct3D 10. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with +`cudaDevice` + \- The CUDA device on which to create the context. This device must be among the devices returned when querying CU_D3D10_DEVICES_ALL from cuD3D10GetDevices. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D10 device in order to achieve maximum interoperability performance. + +CUresult cuD3D10GetDirect3DDevice ( ID3D10Device** ppD3DDevice ) + + +Get the Direct3D 10 device against which the current CUDA context was created. + +###### Parameters + +`ppD3DDevice` + \- Returned Direct3D device corresponding to CUDA context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D10 device in order to achieve maximum interoperability performance. + +CUresult cuD3D10MapResources ( unsigned int count, ID3D10Resource** ppResources ) + + +Map Direct3D resources for access by CUDA. + +###### Parameters + +`count` + \- Number of resources to map for CUDA +`ppResources` + \- Resources to map for CUDA + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Maps the `count` Direct3D resources in `ppResources` for access by CUDA. + +The resources in `ppResources` may be accessed in CUDA kernels until they are unmapped. Direct3D should not access any resources while they are mapped by CUDA. If an application does so, the results are undefined. + +This function provides the synchronization guarantee that any Direct3D calls issued before cuD3D10MapResources() will complete before any CUDA kernels issued after cuD3D10MapResources() begin. + +If any of `ppResources` have not been registered for use with CUDA or if `ppResources` contains any duplicate entries, then CUDA_ERROR_INVALID_HANDLE is returned. If any of `ppResources` are presently mapped for access by CUDA, then CUDA_ERROR_ALREADY_MAPPED is returned. + +CUresult cuD3D10RegisterResource ( ID3D10Resource* pResource, unsigned int Flags ) + + +Register a Direct3D resource for access by CUDA. + +###### Parameters + +`pResource` + \- Resource to register +`Flags` + \- Parameters for resource registration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Registers the Direct3D resource `pResource` for access by CUDA. + +If this call is successful, then the application will be able to map and unmap this resource until it is unregistered through cuD3D10UnregisterResource(). Also on success, this call will increase the internal reference count on `pResource`. This reference count will be decremented when this resource is unregistered through cuD3D10UnregisterResource(). + +This call is potentially high-overhead and should not be called every frame in interactive applications. + +The type of `pResource` must be one of the following. + + * ID3D10Buffer: Cannot be used with `Flags` set to CU_D3D10_REGISTER_FLAGS_ARRAY. + + * ID3D10Texture1D: No restrictions. + + * ID3D10Texture2D: No restrictions. + + * ID3D10Texture3D: No restrictions. + + +The `Flags` argument specifies the mechanism through which CUDA will access the Direct3D resource. The following values are allowed. + + * CU_D3D10_REGISTER_FLAGS_NONE: Specifies that CUDA will access this resource through a CUdeviceptr. The pointer, size, and (for textures), pitch for each subresource of this allocation may be queried through cuD3D10ResourceGetMappedPointer(), cuD3D10ResourceGetMappedSize(), and cuD3D10ResourceGetMappedPitch() respectively. This option is valid for all resource types. + + * CU_D3D10_REGISTER_FLAGS_ARRAY: Specifies that CUDA will access this resource through a CUarray queried on a sub-resource basis through cuD3D10ResourceGetMappedArray(). This option is only valid for resources of type ID3D10Texture1D, ID3D10Texture2D, and ID3D10Texture3D. + + +Not all Direct3D resources of the above types may be used for interoperability with CUDA. The following are some limitations. + + * The primary rendertarget may not be registered with CUDA. + + * Resources allocated as shared may not be registered with CUDA. + + * Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or floating-point data cannot be shared. + + * Surfaces of depth or stencil formats cannot be shared. + + +If Direct3D interoperability is not initialized on this context then CUDA_ERROR_INVALID_CONTEXT is returned. If `pResource` is of incorrect type or is already registered, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` cannot be registered, then CUDA_ERROR_UNKNOWN is returned. + +CUresult cuD3D10ResourceGetMappedArray ( CUarray* pArray, ID3D10Resource* pResource, unsigned int SubResource ) + + +Get an array through which to access a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pArray` + \- Returned array corresponding to subresource +`pResource` + \- Mapped resource to access +`SubResource` + \- Subresource of pResource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pArray` an array through which the subresource of the mapped Direct3D resource `pResource`, which corresponds to `SubResource` may be accessed. The value set in `pArray` may change every time that `pResource` is mapped. + +If `pResource` is not registered, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D10_REGISTER_FLAGS_ARRAY, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped, then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of the `SubResource` parameter, see cuD3D10ResourceGetMappedPointer(). + +CUresult cuD3D10ResourceGetMappedPitch ( size_t* pPitch, size_t* pPitchSlice, ID3D10Resource* pResource, unsigned int SubResource ) + + +Get the pitch of a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pPitch` + \- Returned pitch of subresource +`pPitchSlice` + \- Returned Z-slice pitch of subresource +`pResource` + \- Mapped resource to access +`SubResource` + \- Subresource of pResource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pPitch` and `*pPitchSlice` the pitch and Z-slice pitch of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `SubResource`. The values set in `pPitch` and `pPitchSlice` may change every time that `pResource` is mapped. + +The pitch and Z-slice pitch values may be used to compute the location of a sample on a surface as follows. + +For a 2D surface, the byte offset of the sample at position **x** , **y** from the base pointer of the surface is: + +**y** * **pitch** \+ (**bytes per pixel**) * **x** + +For a 3D surface, the byte offset of the sample at position **x** , **y** , **z** from the base pointer of the surface is: + +**z*** **slicePitch** \+ **y** * **pitch** \+ (**bytes per pixel**) * **x** + +Both parameters `pPitch` and `pPitchSlice` are optional and may be set to NULL. + +If `pResource` is not of type IDirect3DBaseTexture10 or one of its sub-types or if `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D10_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped for access by CUDA, then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of the `SubResource` parameter, see cuD3D10ResourceGetMappedPointer(). + +CUresult cuD3D10ResourceGetMappedPointer ( CUdeviceptr* pDevPtr, ID3D10Resource* pResource, unsigned int SubResource ) + + +Get a pointer through which to access a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pDevPtr` + \- Returned pointer corresponding to subresource +`pResource` + \- Mapped resource to access +`SubResource` + \- Subresource of pResource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pDevPtr` the base pointer of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `SubResource`. The value set in `pDevPtr` may change every time that `pResource` is mapped. + +If `pResource` is not registered, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D10_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped, then CUDA_ERROR_NOT_MAPPED is returned. + +If `pResource` is of type ID3D10Buffer, then `SubResource` must be 0. If `pResource` is of any other type, then the value of `SubResource` must come from the subresource calculation in D3D10CalcSubResource(). + +CUresult cuD3D10ResourceGetMappedSize ( size_t* pSize, ID3D10Resource* pResource, unsigned int SubResource ) + + +Get the size of a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pSize` + \- Returned size of subresource +`pResource` + \- Mapped resource to access +`SubResource` + \- Subresource of pResource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pSize` the size of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `SubResource`. The value set in `pSize` may change every time that `pResource` is mapped. + +If `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D10_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped for access by CUDA, then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of the `SubResource` parameter, see cuD3D10ResourceGetMappedPointer(). + +CUresult cuD3D10ResourceGetSurfaceDimensions ( size_t* pWidth, size_t* pHeight, size_t* pDepth, ID3D10Resource* pResource, unsigned int SubResource ) + + +Get the dimensions of a registered surface. + +###### Parameters + +`pWidth` + \- Returned width of surface +`pHeight` + \- Returned height of surface +`pDepth` + \- Returned depth of surface +`pResource` + \- Registered resource to access +`SubResource` + \- Subresource of pResource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pWidth`, `*pHeight`, and `*pDepth` the dimensions of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `SubResource`. + +Because anti-aliased surfaces may have multiple samples per pixel, it is possible that the dimensions of a resource will be an integer factor larger than the dimensions reported by the Direct3D runtime. + +The parameters `pWidth`, `pHeight`, and `pDepth` are optional. For 2D surfaces, the value returned in `*pDepth` will be 0. + +If `pResource` is not of type IDirect3DBaseTexture10 or IDirect3DSurface10 or if `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. + +For usage requirements of the `SubResource` parameter, see cuD3D10ResourceGetMappedPointer(). + +CUresult cuD3D10ResourceSetMapFlags ( ID3D10Resource* pResource, unsigned int Flags ) + + +Set usage flags for mapping a Direct3D resource. + +###### Parameters + +`pResource` + \- Registered resource to set flags for +`Flags` + \- Parameters for resource mapping + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Set flags for mapping the Direct3D resource `pResource`. + +Changes to flags will take effect the next time `pResource` is mapped. The `Flags` argument may be any of the following. + + * CU_D3D10_MAPRESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA kernels. This is the default value. + + * CU_D3D10_MAPRESOURCE_FLAGS_READONLY: Specifies that CUDA kernels which access this resource will not write to this resource. + + * CU_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD: Specifies that CUDA kernels which access this resource will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +If `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is presently mapped for access by CUDA then CUDA_ERROR_ALREADY_MAPPED is returned. + +CUresult cuD3D10UnmapResources ( unsigned int count, ID3D10Resource** ppResources ) + + +Unmap Direct3D resources. + +###### Parameters + +`count` + \- Number of resources to unmap for CUDA +`ppResources` + \- Resources to unmap for CUDA + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Unmaps the `count` Direct3D resources in `ppResources`. + +This function provides the synchronization guarantee that any CUDA kernels issued before cuD3D10UnmapResources() will complete before any Direct3D calls issued after cuD3D10UnmapResources() begin. + +If any of `ppResources` have not been registered for use with CUDA or if `ppResources` contains any duplicate entries, then CUDA_ERROR_INVALID_HANDLE is returned. If any of `ppResources` are not presently mapped for access by CUDA, then CUDA_ERROR_NOT_MAPPED is returned. + +CUresult cuD3D10UnregisterResource ( ID3D10Resource* pResource ) + + +Unregister a Direct3D resource. + +###### Parameters + +`pResource` + \- Resources to unregister + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Unregisters the Direct3D resource `pResource` so it is not accessible by CUDA unless registered again. + +If `pResource` is not registered, then CUDA_ERROR_INVALID_HANDLE is returned. + + diff --git a/content/cuda/docs/driver-d3d10/DOC.md b/content/cuda/docs/driver-d3d10/DOC.md new file mode 100644 index 00000000..39564eed --- /dev/null +++ b/content/cuda/docs/driver-d3d10/DOC.md @@ -0,0 +1,168 @@ +--- +name: driver-d3d10 +description: '**Source:** group__CUDA__D3D10.html#group__CUDA__D3D10' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.42. Direct3D 10 Interoperability + +**Source:** group__CUDA__D3D10.html#group__CUDA__D3D10 + + +### Modules + +[Direct3D 10 Interoperability [DEPRECATED]](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__D3D10__DEPRECATED.html#group__CUDA__D3D10__DEPRECATED) + + + +### Enumerations + +enum CUd3d10DeviceList + + +### Functions + +CUresult cuD3D10GetDevice ( CUdevice* pCudaDevice, IDXGIAdapter* pAdapter ) + + +Gets the CUDA device corresponding to a display adapter. + +###### Parameters + +`pCudaDevice` + \- Returned CUDA device corresponding to `pAdapter` +`pAdapter` + \- Adapter to query for CUDA device + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDevice` the CUDA-compatible device corresponding to the adapter `pAdapter` obtained from IDXGIFactory::EnumAdapters. + +If no device on `pAdapter` is CUDA-compatible then the call will fail. + +CUresult cuD3D10GetDevices ( unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, ID3D10Device* pD3D10Device, CUd3d10DeviceList deviceList ) + + +Gets the CUDA devices corresponding to a Direct3D 10 device. + +###### Parameters + +`pCudaDeviceCount` + \- Returned number of CUDA devices corresponding to `pD3D10Device` +`pCudaDevices` + \- Returned CUDA devices corresponding to `pD3D10Device` +`cudaDeviceCount` + \- The size of the output device array `pCudaDevices` +`pD3D10Device` + \- Direct3D 10 device to query for CUDA devices +`deviceList` + \- The set of devices to return. This set may be CU_D3D10_DEVICE_LIST_ALL for all devices, CU_D3D10_DEVICE_LIST_CURRENT_FRAME for the devices used to render the current frame (in SLI), or CU_D3D10_DEVICE_LIST_NEXT_FRAME for the devices used to render the next frame (in SLI). + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDeviceCount` the number of CUDA-compatible device corresponding to the Direct3D 10 device `pD3D10Device`. Also returns in `*pCudaDevices` at most `cudaDeviceCount` of the CUDA-compatible devices corresponding to the Direct3D 10 device `pD3D10Device`. + +If any of the GPUs being used to render `pDevice` are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. + +CUresult cuGraphicsD3D10RegisterResource ( CUgraphicsResource* pCudaResource, ID3D10Resource* pD3DResource, unsigned int Flags ) + + +Register a Direct3D 10 resource for access by CUDA. + +###### Parameters + +`pCudaResource` + \- Returned graphics resource handle +`pD3DResource` + \- Direct3D resource to register +`Flags` + \- Parameters for resource registration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Registers the Direct3D 10 resource `pD3DResource` for access by CUDA and returns a CUDA handle to `pD3Dresource` in `pCudaResource`. The handle returned in `pCudaResource` may be used to map and unmap this resource until it is unregistered. On success this call will increase the internal reference count on `pD3DResource`. This reference count will be decremented when this resource is unregistered through cuGraphicsUnregisterResource(). + +This call is potentially high-overhead and should not be called every frame in interactive applications. + +The type of `pD3DResource` must be one of the following. + + * ID3D10Buffer: may be accessed through a device pointer. + + * ID3D10Texture1D: individual subresources of the texture may be accessed via arrays + + * ID3D10Texture2D: individual subresources of the texture may be accessed via arrays + + * ID3D10Texture3D: individual subresources of the texture may be accessed via arrays + + +The `Flags` argument may be used to specify additional parameters at register time. The valid values for this parameter are + + * CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this resource will be used. + + * CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST: Specifies that CUDA will bind this resource to a surface reference. + + * CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER: Specifies that CUDA will perform texture gather operations on this resource. + + +Not all Direct3D resources of the above types may be used for interoperability with CUDA. The following are some limitations. + + * The primary rendertarget may not be registered with CUDA. + + * Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or floating-point data cannot be shared. + + * Surfaces of depth or stencil formats cannot be shared. + + +A complete list of supported DXGI formats is as follows. For compactness the notation A_{B,C,D} represents A_B, A_C, and A_D. + + * DXGI_FORMAT_A8_UNORM + + * DXGI_FORMAT_B8G8R8A8_UNORM + + * DXGI_FORMAT_B8G8R8X8_UNORM + + * DXGI_FORMAT_R16_FLOAT + + * DXGI_FORMAT_R16G16B16A16_{FLOAT,SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R16G16_{FLOAT,SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R16_{SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R32_FLOAT + + * DXGI_FORMAT_R32G32B32A32_{FLOAT,SINT,UINT} + + * DXGI_FORMAT_R32G32_{FLOAT,SINT,UINT} + + * DXGI_FORMAT_R32_{SINT,UINT} + + * DXGI_FORMAT_R8G8B8A8_{SINT,SNORM,UINT,UNORM,UNORM_SRGB} + + * DXGI_FORMAT_R8G8_{SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R8_{SINT,SNORM,UINT,UNORM} + + +If `pD3DResource` is of incorrect type or is already registered then CUDA_ERROR_INVALID_HANDLE is returned. If `pD3DResource` cannot be registered then CUDA_ERROR_UNKNOWN is returned. If `Flags` is not one of the above specified value then CUDA_ERROR_INVALID_VALUE is returned. + +### Direct3D 10 Interoperability [DEPRECATED] + diff --git a/content/cuda/docs/driver-d3d11--deprecated/DOC.md b/content/cuda/docs/driver-d3d11--deprecated/DOC.md new file mode 100644 index 00000000..ebe7703f --- /dev/null +++ b/content/cuda/docs/driver-d3d11--deprecated/DOC.md @@ -0,0 +1,98 @@ +--- +name: driver-d3d11--deprecated +description: '**Source:** group__CUDA__D3D11__DEPRECATED.html#group__CUDA__D3D11__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.43.1. Direct3D 11 Interoperability [DEPRECATED] + +**Source:** group__CUDA__D3D11__DEPRECATED.html#group__CUDA__D3D11__DEPRECATED + + +### Functions + +CUresult cuD3D11CtxCreate ( CUcontext* pCtx, CUdevice* pCudaDevice, unsigned int Flags, ID3D11Device* pD3DDevice ) + + +Create a CUDA context for interoperability with Direct3D 11. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`pCudaDevice` + \- Returned pointer to the device on which the context was created +`Flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D11 device in order to achieve maximum interoperability performance. + +CUresult cuD3D11CtxCreateOnDevice ( CUcontext* pCtx, unsigned int flags, ID3D11Device* pD3DDevice, CUdevice cudaDevice ) + + +Create a CUDA context for interoperability with Direct3D 11. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with +`cudaDevice` + \- The CUDA device on which to create the context. This device must be among the devices returned when querying CU_D3D11_DEVICES_ALL from cuD3D11GetDevices. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D11 device in order to achieve maximum interoperability performance. + +CUresult cuD3D11GetDirect3DDevice ( ID3D11Device** ppD3DDevice ) + + +Get the Direct3D 11 device against which the current CUDA context was created. + +###### Parameters + +`ppD3DDevice` + \- Returned Direct3D device corresponding to CUDA context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Deprecated + +This function is deprecated as of CUDA 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with a D3D11 device in order to achieve maximum interoperability performance. + + diff --git a/content/cuda/docs/driver-d3d11/DOC.md b/content/cuda/docs/driver-d3d11/DOC.md new file mode 100644 index 00000000..1c8ca4d3 --- /dev/null +++ b/content/cuda/docs/driver-d3d11/DOC.md @@ -0,0 +1,168 @@ +--- +name: driver-d3d11 +description: '**Source:** group__CUDA__D3D11.html#group__CUDA__D3D11' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.43. Direct3D 11 Interoperability + +**Source:** group__CUDA__D3D11.html#group__CUDA__D3D11 + + +### Modules + +[Direct3D 11 Interoperability [DEPRECATED]](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__D3D11__DEPRECATED.html#group__CUDA__D3D11__DEPRECATED) + + + +### Enumerations + +enum CUd3d11DeviceList + + +### Functions + +CUresult cuD3D11GetDevice ( CUdevice* pCudaDevice, IDXGIAdapter* pAdapter ) + + +Gets the CUDA device corresponding to a display adapter. + +###### Parameters + +`pCudaDevice` + \- Returned CUDA device corresponding to `pAdapter` +`pAdapter` + \- Adapter to query for CUDA device + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDevice` the CUDA-compatible device corresponding to the adapter `pAdapter` obtained from IDXGIFactory::EnumAdapters. + +If no device on `pAdapter` is CUDA-compatible the call will return CUDA_ERROR_NO_DEVICE. + +CUresult cuD3D11GetDevices ( unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, ID3D11Device* pD3D11Device, CUd3d11DeviceList deviceList ) + + +Gets the CUDA devices corresponding to a Direct3D 11 device. + +###### Parameters + +`pCudaDeviceCount` + \- Returned number of CUDA devices corresponding to `pD3D11Device` +`pCudaDevices` + \- Returned CUDA devices corresponding to `pD3D11Device` +`cudaDeviceCount` + \- The size of the output device array `pCudaDevices` +`pD3D11Device` + \- Direct3D 11 device to query for CUDA devices +`deviceList` + \- The set of devices to return. This set may be CU_D3D11_DEVICE_LIST_ALL for all devices, CU_D3D11_DEVICE_LIST_CURRENT_FRAME for the devices used to render the current frame (in SLI), or CU_D3D11_DEVICE_LIST_NEXT_FRAME for the devices used to render the next frame (in SLI). + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDeviceCount` the number of CUDA-compatible device corresponding to the Direct3D 11 device `pD3D11Device`. Also returns in `*pCudaDevices` at most `cudaDeviceCount` of the CUDA-compatible devices corresponding to the Direct3D 11 device `pD3D11Device`. + +If any of the GPUs being used to render `pDevice` are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. + +CUresult cuGraphicsD3D11RegisterResource ( CUgraphicsResource* pCudaResource, ID3D11Resource* pD3DResource, unsigned int Flags ) + + +Register a Direct3D 11 resource for access by CUDA. + +###### Parameters + +`pCudaResource` + \- Returned graphics resource handle +`pD3DResource` + \- Direct3D resource to register +`Flags` + \- Parameters for resource registration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Registers the Direct3D 11 resource `pD3DResource` for access by CUDA and returns a CUDA handle to `pD3Dresource` in `pCudaResource`. The handle returned in `pCudaResource` may be used to map and unmap this resource until it is unregistered. On success this call will increase the internal reference count on `pD3DResource`. This reference count will be decremented when this resource is unregistered through cuGraphicsUnregisterResource(). + +This call is potentially high-overhead and should not be called every frame in interactive applications. + +The type of `pD3DResource` must be one of the following. + + * ID3D11Buffer: may be accessed through a device pointer. + + * ID3D11Texture1D: individual subresources of the texture may be accessed via arrays + + * ID3D11Texture2D: individual subresources of the texture may be accessed via arrays + + * ID3D11Texture3D: individual subresources of the texture may be accessed via arrays + + +The `Flags` argument may be used to specify additional parameters at register time. The valid values for this parameter are + + * CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this resource will be used. + + * CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST: Specifies that CUDA will bind this resource to a surface reference. + + * CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER: Specifies that CUDA will perform texture gather operations on this resource. + + +Not all Direct3D resources of the above types may be used for interoperability with CUDA. The following are some limitations. + + * The primary rendertarget may not be registered with CUDA. + + * Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or floating-point data cannot be shared. + + * Surfaces of depth or stencil formats cannot be shared. + + +A complete list of supported DXGI formats is as follows. For compactness the notation A_{B,C,D} represents A_B, A_C, and A_D. + + * DXGI_FORMAT_A8_UNORM + + * DXGI_FORMAT_B8G8R8A8_UNORM + + * DXGI_FORMAT_B8G8R8X8_UNORM + + * DXGI_FORMAT_R16_FLOAT + + * DXGI_FORMAT_R16G16B16A16_{FLOAT,SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R16G16_{FLOAT,SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R16_{SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R32_FLOAT + + * DXGI_FORMAT_R32G32B32A32_{FLOAT,SINT,UINT} + + * DXGI_FORMAT_R32G32_{FLOAT,SINT,UINT} + + * DXGI_FORMAT_R32_{SINT,UINT} + + * DXGI_FORMAT_R8G8B8A8_{SINT,SNORM,UINT,UNORM,UNORM_SRGB} + + * DXGI_FORMAT_R8G8_{SINT,SNORM,UINT,UNORM} + + * DXGI_FORMAT_R8_{SINT,SNORM,UINT,UNORM} + + +If `pD3DResource` is of incorrect type or is already registered then CUDA_ERROR_INVALID_HANDLE is returned. If `pD3DResource` cannot be registered then CUDA_ERROR_UNKNOWN is returned. If `Flags` is not one of the above specified value then CUDA_ERROR_INVALID_VALUE is returned. + +### Direct3D 11 Interoperability [DEPRECATED] + diff --git a/content/cuda/docs/driver-d3d9--deprecated/DOC.md b/content/cuda/docs/driver-d3d9--deprecated/DOC.md new file mode 100644 index 00000000..60393f17 --- /dev/null +++ b/content/cuda/docs/driver-d3d9--deprecated/DOC.md @@ -0,0 +1,389 @@ +--- +name: driver-d3d9--deprecated +description: '**Source:** group__CUDA__D3D9__DEPRECATED.html#group__CUDA__D3D9__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.41.1. Direct3D 9 Interoperability [DEPRECATED] + +**Source:** group__CUDA__D3D9__DEPRECATED.html#group__CUDA__D3D9__DEPRECATED + + +### Enumerations + +enum CUd3d9map_flags + +enum CUd3d9register_flags + + +### Functions + +CUresult cuD3D9MapResources ( unsigned int count, IDirect3DResource9** ppResource ) + + +Map Direct3D resources for access by CUDA. + +###### Parameters + +`count` + \- Number of resources in ppResource +`ppResource` + \- Resources to map for CUDA usage + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Maps the `count` Direct3D resources in `ppResource` for access by CUDA. + +The resources in `ppResource` may be accessed in CUDA kernels until they are unmapped. Direct3D should not access any resources while they are mapped by CUDA. If an application does so the results are undefined. + +This function provides the synchronization guarantee that any Direct3D calls issued before cuD3D9MapResources() will complete before any CUDA kernels issued after cuD3D9MapResources() begin. + +If any of `ppResource` have not been registered for use with CUDA or if `ppResource` contains any duplicate entries, then CUDA_ERROR_INVALID_HANDLE is returned. If any of `ppResource` are presently mapped for access by CUDA, then CUDA_ERROR_ALREADY_MAPPED is returned. + +CUresult cuD3D9RegisterResource ( IDirect3DResource9* pResource, unsigned int Flags ) + + +Register a Direct3D resource for access by CUDA. + +###### Parameters + +`pResource` + \- Resource to register for CUDA access +`Flags` + \- Flags for resource registration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Registers the Direct3D resource `pResource` for access by CUDA. + +If this call is successful, then the application will be able to map and unmap this resource until it is unregistered through cuD3D9UnregisterResource(). Also on success, this call will increase the internal reference count on `pResource`. This reference count will be decremented when this resource is unregistered through cuD3D9UnregisterResource(). + +This call is potentially high-overhead and should not be called every frame in interactive applications. + +The type of `pResource` must be one of the following. + + * IDirect3DVertexBuffer9: Cannot be used with `Flags` set to CU_D3D9_REGISTER_FLAGS_ARRAY. + + * IDirect3DIndexBuffer9: Cannot be used with `Flags` set to CU_D3D9_REGISTER_FLAGS_ARRAY. + + * IDirect3DSurface9: Only stand-alone objects of type IDirect3DSurface9 may be explicitly shared. In particular, individual mipmap levels and faces of cube maps may not be registered directly. To access individual surfaces associated with a texture, one must register the base texture object. For restrictions on the `Flags` parameter, see type IDirect3DBaseTexture9. + + * IDirect3DBaseTexture9: When a texture is registered, all surfaces associated with the all mipmap levels of all faces of the texture will be accessible to CUDA. + + +The `Flags` argument specifies the mechanism through which CUDA will access the Direct3D resource. The following values are allowed. + + * CU_D3D9_REGISTER_FLAGS_NONE: Specifies that CUDA will access this resource through a CUdeviceptr. The pointer, size, and (for textures), pitch for each subresource of this allocation may be queried through cuD3D9ResourceGetMappedPointer(), cuD3D9ResourceGetMappedSize(), and cuD3D9ResourceGetMappedPitch() respectively. This option is valid for all resource types. + + * CU_D3D9_REGISTER_FLAGS_ARRAY: Specifies that CUDA will access this resource through a CUarray queried on a sub-resource basis through cuD3D9ResourceGetMappedArray(). This option is only valid for resources of type IDirect3DSurface9 and subtypes of IDirect3DBaseTexture9. + + +Not all Direct3D resources of the above types may be used for interoperability with CUDA. The following are some limitations. + + * The primary rendertarget may not be registered with CUDA. + + * Resources allocated as shared may not be registered with CUDA. + + * Any resources allocated in D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED may not be registered with CUDA. + + * Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or floating-point data cannot be shared. + + * Surfaces of depth or stencil formats cannot be shared. + + +If Direct3D interoperability is not initialized on this context, then CUDA_ERROR_INVALID_CONTEXT is returned. If `pResource` is of incorrect type (e.g. is a non-stand-alone IDirect3DSurface9) or is already registered, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` cannot be registered then CUDA_ERROR_UNKNOWN is returned. + +CUresult cuD3D9ResourceGetMappedArray ( CUarray* pArray, IDirect3DResource9* pResource, unsigned int Face, unsigned int Level ) + + +Get an array through which to access a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pArray` + \- Returned array corresponding to subresource +`pResource` + \- Mapped resource to access +`Face` + \- Face of resource to access +`Level` + \- Level of resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pArray` an array through which the subresource of the mapped Direct3D resource `pResource` which corresponds to `Face` and `Level` may be accessed. The value set in `pArray` may change every time that `pResource` is mapped. + +If `pResource` is not registered then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D9_REGISTER_FLAGS_ARRAY then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of `Face` and `Level` parameters, see cuD3D9ResourceGetMappedPointer(). + +CUresult cuD3D9ResourceGetMappedPitch ( size_t* pPitch, size_t* pPitchSlice, IDirect3DResource9* pResource, unsigned int Face, unsigned int Level ) + + +Get the pitch of a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pPitch` + \- Returned pitch of subresource +`pPitchSlice` + \- Returned Z-slice pitch of subresource +`pResource` + \- Mapped resource to access +`Face` + \- Face of resource to access +`Level` + \- Level of resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pPitch` and `*pPitchSlice` the pitch and Z-slice pitch of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `Face` and `Level`. The values set in `pPitch` and `pPitchSlice` may change every time that `pResource` is mapped. + +The pitch and Z-slice pitch values may be used to compute the location of a sample on a surface as follows. + +For a 2D surface, the byte offset of the sample at position **x** , **y** from the base pointer of the surface is: + +**y** * **pitch** \+ (**bytes per pixel**) * **x** + +For a 3D surface, the byte offset of the sample at position **x** , **y** , **z** from the base pointer of the surface is: + +**z*** **slicePitch** \+ **y** * **pitch** \+ (**bytes per pixel**) * **x** + +Both parameters `pPitch` and `pPitchSlice` are optional and may be set to NULL. + +If `pResource` is not of type IDirect3DBaseTexture9 or one of its sub-types or if `pResource` has not been registered for use with CUDA, then cudaErrorInvalidResourceHandle is returned. If `pResource` was not registered with usage flags CU_D3D9_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped for access by CUDA then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of `Face` and `Level` parameters, see cuD3D9ResourceGetMappedPointer(). + +CUresult cuD3D9ResourceGetMappedPointer ( CUdeviceptr* pDevPtr, IDirect3DResource9* pResource, unsigned int Face, unsigned int Level ) + + +Get the pointer through which to access a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pDevPtr` + \- Returned pointer corresponding to subresource +`pResource` + \- Mapped resource to access +`Face` + \- Face of resource to access +`Level` + \- Level of resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pDevPtr` the base pointer of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `Face` and `Level`. The value set in `pDevPtr` may change every time that `pResource` is mapped. + +If `pResource` is not registered, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D9_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped, then CUDA_ERROR_NOT_MAPPED is returned. + +If `pResource` is of type IDirect3DCubeTexture9, then `Face` must one of the values enumerated by type D3DCUBEMAP_FACES. For all other types `Face` must be 0. If `Face` is invalid, then CUDA_ERROR_INVALID_VALUE is returned. + +If `pResource` is of type IDirect3DBaseTexture9, then `Level` must correspond to a valid mipmap level. At present only mipmap level 0 is supported. For all other types `Level` must be 0. If `Level` is invalid, then CUDA_ERROR_INVALID_VALUE is returned. + +CUresult cuD3D9ResourceGetMappedSize ( size_t* pSize, IDirect3DResource9* pResource, unsigned int Face, unsigned int Level ) + + +Get the size of a subresource of a Direct3D resource which has been mapped for access by CUDA. + +###### Parameters + +`pSize` + \- Returned size of subresource +`pResource` + \- Mapped resource to access +`Face` + \- Face of resource to access +`Level` + \- Level of resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pSize` the size of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `Face` and `Level`. The value set in `pSize` may change every time that `pResource` is mapped. + +If `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` was not registered with usage flags CU_D3D9_REGISTER_FLAGS_NONE, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is not mapped for access by CUDA, then CUDA_ERROR_NOT_MAPPED is returned. + +For usage requirements of `Face` and `Level` parameters, see cuD3D9ResourceGetMappedPointer. + +CUresult cuD3D9ResourceGetSurfaceDimensions ( size_t* pWidth, size_t* pHeight, size_t* pDepth, IDirect3DResource9* pResource, unsigned int Face, unsigned int Level ) + + +Get the dimensions of a registered surface. + +###### Parameters + +`pWidth` + \- Returned width of surface +`pHeight` + \- Returned height of surface +`pDepth` + \- Returned depth of surface +`pResource` + \- Registered resource to access +`Face` + \- Face of resource to access +`Level` + \- Level of resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Returns in `*pWidth`, `*pHeight`, and `*pDepth` the dimensions of the subresource of the mapped Direct3D resource `pResource`, which corresponds to `Face` and `Level`. + +Because anti-aliased surfaces may have multiple samples per pixel, it is possible that the dimensions of a resource will be an integer factor larger than the dimensions reported by the Direct3D runtime. + +The parameters `pWidth`, `pHeight`, and `pDepth` are optional. For 2D surfaces, the value returned in `*pDepth` will be 0. + +If `pResource` is not of type IDirect3DBaseTexture9 or IDirect3DSurface9 or if `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. + +For usage requirements of `Face` and `Level` parameters, see cuD3D9ResourceGetMappedPointer(). + +CUresult cuD3D9ResourceSetMapFlags ( IDirect3DResource9* pResource, unsigned int Flags ) + + +Set usage flags for mapping a Direct3D resource. + +###### Parameters + +`pResource` + \- Registered resource to set flags for +`Flags` + \- Parameters for resource mapping + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Set `Flags` for mapping the Direct3D resource `pResource`. + +Changes to `Flags` will take effect the next time `pResource` is mapped. The `Flags` argument may be any of the following: + + * CU_D3D9_MAPRESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA kernels. This is the default value. + + * CU_D3D9_MAPRESOURCE_FLAGS_READONLY: Specifies that CUDA kernels which access this resource will not write to this resource. + + * CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD: Specifies that CUDA kernels which access this resource will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +If `pResource` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `pResource` is presently mapped for access by CUDA, then CUDA_ERROR_ALREADY_MAPPED is returned. + +CUresult cuD3D9UnmapResources ( unsigned int count, IDirect3DResource9** ppResource ) + + +Unmaps Direct3D resources. + +###### Parameters + +`count` + \- Number of resources to unmap for CUDA +`ppResource` + \- Resources to unmap for CUDA + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Unmaps the `count` Direct3D resources in `ppResource`. + +This function provides the synchronization guarantee that any CUDA kernels issued before cuD3D9UnmapResources() will complete before any Direct3D calls issued after cuD3D9UnmapResources() begin. + +If any of `ppResource` have not been registered for use with CUDA or if `ppResource` contains any duplicate entries, then CUDA_ERROR_INVALID_HANDLE is returned. If any of `ppResource` are not presently mapped for access by CUDA, then CUDA_ERROR_NOT_MAPPED is returned. + +CUresult cuD3D9UnregisterResource ( IDirect3DResource9* pResource ) + + +Unregister a Direct3D resource. + +###### Parameters + +`pResource` + \- Resource to unregister + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of CUDA 3.0. + +###### Description + +Unregisters the Direct3D resource `pResource` so it is not accessible by CUDA unless registered again. + +If `pResource` is not registered, then CUDA_ERROR_INVALID_HANDLE is returned. + + diff --git a/content/cuda/docs/driver-d3d9/DOC.md b/content/cuda/docs/driver-d3d9/DOC.md new file mode 100644 index 00000000..e50a446b --- /dev/null +++ b/content/cuda/docs/driver-d3d9/DOC.md @@ -0,0 +1,250 @@ +--- +name: driver-d3d9 +description: '**Source:** group__CUDA__D3D9.html#group__CUDA__D3D9' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.41. Direct3D 9 Interoperability + +**Source:** group__CUDA__D3D9.html#group__CUDA__D3D9 + + +### Modules + +[Direct3D 9 Interoperability [DEPRECATED]](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__D3D9__DEPRECATED.html#group__CUDA__D3D9__DEPRECATED) + + + +### Enumerations + +enum CUd3d9DeviceList + + +### Functions + +CUresult cuD3D9CtxCreate ( CUcontext* pCtx, CUdevice* pCudaDevice, unsigned int Flags, IDirect3DDevice9* pD3DDevice ) + + +Create a CUDA context for interoperability with Direct3D 9. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`pCudaDevice` + \- Returned pointer to the device on which the context was created +`Flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a new CUDA context, enables interoperability for that context with the Direct3D device `pD3DDevice`, and associates the created CUDA context with the calling thread. The created CUcontext will be returned in `*pCtx`. Direct3D resources from this device may be registered and mapped through the lifetime of this CUDA context. If `pCudaDevice` is non-NULL then the CUdevice on which this CUDA context was created will be returned in `*pCudaDevice`. + +On success, this call will increase the internal reference count on `pD3DDevice`. This reference count will be decremented upon destruction of this context through cuCtxDestroy(). This context will cease to function if `pD3DDevice` is destroyed or encounters an error. + +Note that this function is never required for correct functionality. Use of this function will result in accelerated interoperability only when the operating system is Windows Vista or Windows 7, and the device `pD3DDdevice` is not an IDirect3DDevice9Ex. In all other circumstances, this function is not necessary. + +CUresult cuD3D9CtxCreateOnDevice ( CUcontext* pCtx, unsigned int flags, IDirect3DDevice9* pD3DDevice, CUdevice cudaDevice ) + + +Create a CUDA context for interoperability with Direct3D 9. + +###### Parameters + +`pCtx` + \- Returned newly created CUDA context +`flags` + \- Context creation flags (see cuCtxCreate() for details) +`pD3DDevice` + \- Direct3D device to create interoperability context with +`cudaDevice` + \- The CUDA device on which to create the context. This device must be among the devices returned when querying CU_D3D9_DEVICES_ALL from cuD3D9GetDevices. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a new CUDA context, enables interoperability for that context with the Direct3D device `pD3DDevice`, and associates the created CUDA context with the calling thread. The created CUcontext will be returned in `*pCtx`. Direct3D resources from this device may be registered and mapped through the lifetime of this CUDA context. + +On success, this call will increase the internal reference count on `pD3DDevice`. This reference count will be decremented upon destruction of this context through cuCtxDestroy(). This context will cease to function if `pD3DDevice` is destroyed or encounters an error. + +Note that this function is never required for correct functionality. Use of this function will result in accelerated interoperability only when the operating system is Windows Vista or Windows 7, and the device `pD3DDdevice` is not an IDirect3DDevice9Ex. In all other circumstances, this function is not necessary. + +CUresult cuD3D9GetDevice ( CUdevice* pCudaDevice, const char* pszAdapterName ) + + +Gets the CUDA device corresponding to a display adapter. + +###### Parameters + +`pCudaDevice` + \- Returned CUDA device corresponding to pszAdapterName +`pszAdapterName` + \- Adapter name to query for device + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDevice` the CUDA-compatible device corresponding to the adapter name `pszAdapterName` obtained from EnumDisplayDevices() or IDirect3D9::GetAdapterIdentifier(). + +If no device on the adapter with name `pszAdapterName` is CUDA-compatible, then the call will fail. + +CUresult cuD3D9GetDevices ( unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, IDirect3DDevice9* pD3D9Device, CUd3d9DeviceList deviceList ) + + +Gets the CUDA devices corresponding to a Direct3D 9 device. + +###### Parameters + +`pCudaDeviceCount` + \- Returned number of CUDA devices corresponding to `pD3D9Device` +`pCudaDevices` + \- Returned CUDA devices corresponding to `pD3D9Device` +`cudaDeviceCount` + \- The size of the output device array `pCudaDevices` +`pD3D9Device` + \- Direct3D 9 device to query for CUDA devices +`deviceList` + \- The set of devices to return. This set may be CU_D3D9_DEVICE_LIST_ALL for all devices, CU_D3D9_DEVICE_LIST_CURRENT_FRAME for the devices used to render the current frame (in SLI), or CU_D3D9_DEVICE_LIST_NEXT_FRAME for the devices used to render the next frame (in SLI). + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*pCudaDeviceCount` the number of CUDA-compatible device corresponding to the Direct3D 9 device `pD3D9Device`. Also returns in `*pCudaDevices` at most `cudaDeviceCount` of the CUDA-compatible devices corresponding to the Direct3D 9 device `pD3D9Device`. + +If any of the GPUs being used to render `pDevice` are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. + +CUresult cuD3D9GetDirect3DDevice ( IDirect3DDevice9** ppD3DDevice ) + + +Get the Direct3D 9 device against which the current CUDA context was created. + +###### Parameters + +`ppD3DDevice` + \- Returned Direct3D device corresponding to CUDA context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXTCUDA_ERROR_INVALID_GRAPHICS_CONTEXT + +###### Description + +Returns in `*ppD3DDevice` the Direct3D device against which this CUDA context was created in cuD3D9CtxCreate(). + +CUresult cuGraphicsD3D9RegisterResource ( CUgraphicsResource* pCudaResource, IDirect3DResource9* pD3DResource, unsigned int Flags ) + + +Register a Direct3D 9 resource for access by CUDA. + +###### Parameters + +`pCudaResource` + \- Returned graphics resource handle +`pD3DResource` + \- Direct3D resource to register +`Flags` + \- Parameters for resource registration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Registers the Direct3D 9 resource `pD3DResource` for access by CUDA and returns a CUDA handle to `pD3Dresource` in `pCudaResource`. The handle returned in `pCudaResource` may be used to map and unmap this resource until it is unregistered. On success this call will increase the internal reference count on `pD3DResource`. This reference count will be decremented when this resource is unregistered through cuGraphicsUnregisterResource(). + +This call is potentially high-overhead and should not be called every frame in interactive applications. + +The type of `pD3DResource` must be one of the following. + + * IDirect3DVertexBuffer9: may be accessed through a device pointer + + * IDirect3DIndexBuffer9: may be accessed through a device pointer + + * IDirect3DSurface9: may be accessed through an array. Only stand-alone objects of type IDirect3DSurface9 may be explicitly shared. In particular, individual mipmap levels and faces of cube maps may not be registered directly. To access individual surfaces associated with a texture, one must register the base texture object. + + * IDirect3DBaseTexture9: individual surfaces on this texture may be accessed through an array. + + +The `Flags` argument may be used to specify additional parameters at register time. The valid values for this parameter are + + * CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this resource will be used. + + * CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST: Specifies that CUDA will bind this resource to a surface reference. + + * CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER: Specifies that CUDA will perform texture gather operations on this resource. + + +Not all Direct3D resources of the above types may be used for interoperability with CUDA. The following are some limitations. + + * The primary rendertarget may not be registered with CUDA. + + * Resources allocated as shared may not be registered with CUDA. + + * Textures which are not of a format which is 1, 2, or 4 channels of 8, 16, or 32-bit integer or floating-point data cannot be shared. + + * Surfaces of depth or stencil formats cannot be shared. + + +A complete list of supported formats is as follows: + + * D3DFMT_L8 + + * D3DFMT_L16 + + * D3DFMT_A8R8G8B8 + + * D3DFMT_X8R8G8B8 + + * D3DFMT_G16R16 + + * D3DFMT_A8B8G8R8 + + * D3DFMT_A8 + + * D3DFMT_A8L8 + + * D3DFMT_Q8W8V8U8 + + * D3DFMT_V16U16 + + * D3DFMT_A16B16G16R16F + + * D3DFMT_A16B16G16R16 + + * D3DFMT_R32F + + * D3DFMT_G16R16F + + * D3DFMT_A32B32G32R32F + + * D3DFMT_G32R32F + + * D3DFMT_R16F + + +If Direct3D interoperability is not initialized for this context using cuD3D9CtxCreate then CUDA_ERROR_INVALID_CONTEXT is returned. If `pD3DResource` is of incorrect type or is already registered then CUDA_ERROR_INVALID_HANDLE is returned. If `pD3DResource` cannot be registered then CUDA_ERROR_UNKNOWN is returned. If `Flags` is not one of the above specified value then CUDA_ERROR_INVALID_VALUE is returned. + +### Direct3D 9 Interoperability [DEPRECATED] + diff --git a/content/cuda/docs/driver-device--deprecated/DOC.md b/content/cuda/docs/driver-device--deprecated/DOC.md new file mode 100644 index 00000000..4f55bf5e --- /dev/null +++ b/content/cuda/docs/driver-device--deprecated/DOC.md @@ -0,0 +1,106 @@ +--- +name: driver-device--deprecated +description: '**Source:** group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.6. Device Management [DEPRECATED] + +**Source:** group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED + + +### Functions + +CUresult cuDeviceComputeCapability ( int* major, int* minor, CUdevice dev ) + + +Returns the compute capability of the device. + +###### Parameters + +`major` + \- Major revision number +`minor` + \- Minor revision number +`dev` + \- Device handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Deprecated + +This function was deprecated as of CUDA 5.0 and its functionality superseded by cuDeviceGetAttribute(). + +###### Description + +Returns in `*major` and `*minor` the major and minor revision numbers that define the compute capability of the device `dev`. + +CUresult cuDeviceGetProperties ( CUdevprop* prop, CUdevice dev ) + + +Returns properties for a selected device. + +###### Parameters + +`prop` + \- Returned properties of device +`dev` + \- Device to get properties for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Deprecated + +This function was deprecated as of CUDA 5.0 and replaced by cuDeviceGetAttribute(). + +###### Description + +Returns in `*prop` the properties of device `dev`. The CUdevprop structure is defined as: + + + ‎ typedef struct CUdevprop_st { + int maxThreadsPerBlock; + int maxThreadsDim[3]; + int maxGridSize[3]; + int sharedMemPerBlock; + int totalConstantMemory; + int SIMDWidth; + int memPitch; + int regsPerBlock; + int clockRate; + int textureAlign + } CUdevprop; + +where: + + * maxThreadsPerBlock is the maximum number of threads per block; + + * maxThreadsDim[3] is the maximum sizes of each dimension of a block; + + * maxGridSize[3] is the maximum sizes of each dimension of a grid; + + * sharedMemPerBlock is the total amount of shared memory available per block in bytes; + + * totalConstantMemory is the total amount of constant memory available on the device in bytes; + + * SIMDWidth is the warp size; + + * memPitch is the maximum pitch allowed by the memory copy functions that involve memory regions allocated through cuMemAllocPitch(); + + * regsPerBlock is the total number of registers available per block; + + * clockRate is the clock frequency in kilohertz; + + * textureAlign is the alignment requirement; texture base addresses that are aligned to textureAlign bytes do not need an offset applied to texture fetches. + + diff --git a/content/cuda/docs/driver-device/DOC.md b/content/cuda/docs/driver-device/DOC.md new file mode 100644 index 00000000..c72b2734 --- /dev/null +++ b/content/cuda/docs/driver-device/DOC.md @@ -0,0 +1,359 @@ +--- +name: driver-device +description: '**Source:** group__CUDA__DEVICE.html#group__CUDA__DEVICE' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.5. Device Management + +**Source:** group__CUDA__DEVICE.html#group__CUDA__DEVICE + + +### Functions + +CUresult cuDeviceGet ( CUdevice* device, int ordinal ) + + +Returns a handle to a compute device. + +###### Parameters + +`device` + \- Returned device handle +`ordinal` + \- Device number to get handle for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*device` a device handle given an ordinal in the range **0,[cuDeviceGetCount()-1]**. + +CUresult cuDeviceGetAttribute ( int* pi, CUdevice_attribute attrib, CUdevice dev ) + + +Returns information about the device. + +###### Parameters + +`pi` + \- Returned device attribute value +`attrib` + \- Device attribute to query +`dev` + \- Device handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*pi` the integer value of the attribute `attrib` on device `dev`. + +CUresult cuDeviceGetCount ( int* count ) + + +Returns the number of compute-capable devices. + +###### Parameters + +`count` + \- Returned number of compute-capable devices + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*count` the number of devices with compute capability greater than or equal to 2.0 that are available for execution. If there is no such device, cuDeviceGetCount() returns 0. + +CUresult cuDeviceGetDefaultMemPool ( CUmemoryPool* pool_out, CUdevice dev ) + + +Returns the default mempool of a device. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZEDCUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +The default mempool of a device contains device memory from that device. + +CUresult cuDeviceGetExecAffinitySupport ( int* pi, CUexecAffinityType type, CUdevice dev ) + + +Returns information about the execution affinity support of the device. + +###### Parameters + +`pi` + \- 1 if the execution affinity type `type` is supported by the device, or 0 if not +`type` + \- Execution affinity type to query +`dev` + \- Device handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*pi` whether execution affinity type `type` is supported by device `dev`. The supported types are: + + * CU_EXEC_AFFINITY_TYPE_SM_COUNT: 1 if context with limited SMs is supported by the device, or 0 if not; + + +CUresult cuDeviceGetHostAtomicCapabilities ( unsigned int* capabilities, const CUatomicOperation ** operations, unsigned int count, CUdevice dev ) + + +Queries details about atomic operations supported between the device and host. + +###### Parameters + +`capabilities` + \- Returned capability details of each requested operation +`operations` + \- Requested operations +`count` + \- Count of requested operations and size of capabilities +`dev` + \- Device handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*capabilities` the details about requested atomic `*operations` over the the link between `dev` and the host. The allocated size of `*operations` and `*capabilities` must be `count`. + +For each CUatomicOperation in `*operations`, the corresponding result in `*capabilities` will be a bitmask indicating which of CUatomicOperationCapability the link supports natively. + +Returns CUDA_ERROR_INVALID_DEVICE if `dev` is not valid. + +Returns CUDA_ERROR_INVALID_VALUE if `*capabilities` or `*operations` is NULL, if `count` is 0, or if any of `*operations` is not valid. + +CUresult cuDeviceGetLuid ( char* luid, unsigned int* deviceNodeMask, CUdevice dev ) + + +Return an LUID and device node mask for the device. + +###### Parameters + +`luid` + \- Returned LUID +`deviceNodeMask` + \- Returned device node mask +`dev` + \- Device to get identifier string for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Return identifying information (`luid` and `deviceNodeMask`) to allow matching device with graphics APIs. + +CUresult cuDeviceGetMemPool ( CUmemoryPool* pool, CUdevice dev ) + + +Gets the current mempool for a device. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the last pool provided to cuDeviceSetMemPool for this device or the device's default memory pool if cuDeviceSetMemPool has never been called. By default the current mempool is the default mempool for a device. Otherwise the returned pool must have been set with cuDeviceSetMemPool. + +CUresult cuDeviceGetName ( char* name, int len, CUdevice dev ) + + +Returns an identifier string for the device. + +###### Parameters + +`name` + \- Returned identifier string for the device +`len` + \- Maximum length of string to store in `name` +`dev` + \- Device to get identifier string for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns an ASCII string identifying the device `dev` in the NULL-terminated string pointed to by `name`. `len` specifies the maximum length of the string that may be returned. `name` is shortened to the specified `len`, if `len` is less than the device name + +CUresult cuDeviceGetNvSciSyncAttributes ( void* nvSciSyncAttrList, CUdevice dev, int flags ) + + +Return NvSciSync attributes that this device can support. + +###### Parameters + +`nvSciSyncAttrList` + \- Return NvSciSync attributes supported. +`dev` + \- Valid Cuda Device to get NvSciSync attributes for. +`flags` + \- flags describing NvSciSync usage. + +###### Description + +Returns in `nvSciSyncAttrList`, the properties of NvSciSync that this CUDA device, `dev` can support. The returned `nvSciSyncAttrList` can be used to create an NvSciSync object that matches this device's capabilities. + +If NvSciSyncAttrKey_RequiredPerm field in `nvSciSyncAttrList` is already set this API will return CUDA_ERROR_INVALID_VALUE. + +The applications should set `nvSciSyncAttrList` to a valid NvSciSyncAttrList failing which this API will return CUDA_ERROR_INVALID_HANDLE. + +The `flags` controls how applications intends to use the NvSciSync created from the `nvSciSyncAttrList`. The valid flags are: + + * CUDA_NVSCISYNC_ATTR_SIGNAL, specifies that the applications intends to signal an NvSciSync on this CUDA device. + + * CUDA_NVSCISYNC_ATTR_WAIT, specifies that the applications intends to wait on an NvSciSync on this CUDA device. + + +At least one of these flags must be set, failing which the API returns CUDA_ERROR_INVALID_VALUE. Both the flags are orthogonal to one another: a developer may set both these flags that allows to set both wait and signal specific attributes in the same `nvSciSyncAttrList`. + +Note that this API updates the input `nvSciSyncAttrList` with values equivalent to the following public attribute key-values: NvSciSyncAttrKey_RequiredPerm is set to + + * NvSciSyncAccessPerm_SignalOnly if CUDA_NVSCISYNC_ATTR_SIGNAL is set in `flags`. + + * NvSciSyncAccessPerm_WaitOnly if CUDA_NVSCISYNC_ATTR_WAIT is set in `flags`. + + * NvSciSyncAccessPerm_WaitSignal if both CUDA_NVSCISYNC_ATTR_WAIT and CUDA_NVSCISYNC_ATTR_SIGNAL are set in `flags`. NvSciSyncAttrKey_PrimitiveInfo is set to + + * NvSciSyncAttrValPrimitiveType_SysmemSemaphore on any valid `device`. + + * NvSciSyncAttrValPrimitiveType_Syncpoint if `device` is a Tegra device. + + * NvSciSyncAttrValPrimitiveType_SysmemSemaphorePayload64b if `device` is GA10X+. NvSciSyncAttrKey_GpuId is set to the same UUID that is returned for this `device` from cuDeviceGetUuid. + + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY + +CUresult cuDeviceGetTexture1DLinearMaxWidth ( size_t* maxWidthInElements, CUarray_format format, unsigned numChannels, CUdevice dev ) + + +Returns the maximum number of elements allocatable in a 1D linear texture for a given texture element size. + +###### Parameters + +`maxWidthInElements` + \- Returned maximum number of texture elements allocatable for given `format` and `numChannels`. +`format` + \- Texture format. +`numChannels` + \- Number of channels per texture element. +`dev` + \- Device handle. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `maxWidthInElements` the maximum number of texture elements allocatable in a 1D linear texture for given `format` and `numChannels`. + +CUresult cuDeviceGetUuid ( CUuuid* uuid, CUdevice dev ) + + +Return an UUID for the device. + +###### Parameters + +`uuid` + \- Returned UUID +`dev` + \- Device to get identifier string for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns 16-octets identifying the device `dev` in the structure pointed by the `uuid`. If the device is in MIG mode, returns its MIG UUID which uniquely identifies the subscribed MIG compute instance. + +CUresult cuDeviceSetMemPool ( CUdevice dev, CUmemoryPool pool ) + + +Sets the current memory pool of a device. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +The memory pool must be local to the specified device. cuMemAllocAsync allocates from the current mempool of the provided stream's device. By default, a device's current memory pool is its default memory pool. + +Use cuMemAllocFromPoolAsync to specify asynchronous allocations from a device different than the one the stream runs on. + +CUresult cuDeviceTotalMem ( size_t* bytes, CUdevice dev ) + + +Returns the total amount of memory on the device. + +###### Parameters + +`bytes` + \- Returned memory available on device in bytes +`dev` + \- Device handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*bytes` the total amount of memory available on the device `dev` in bytes. + +CUresult cuFlushGPUDirectRDMAWrites ( CUflushGPUDirectRDMAWritesTarget target, CUflushGPUDirectRDMAWritesScope scope ) + + +Blocks until remote writes are visible to the specified scope. + +###### Parameters + +`target` + \- The target of the operation, see CUflushGPUDirectRDMAWritesTarget +`scope` + \- The scope of the operation, see CUflushGPUDirectRDMAWritesScope + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Blocks until GPUDirect RDMA writes to the target context via mappings created through APIs like nvidia_p2p_get_pages (see for more information), are visible to the specified scope. + +If the scope equals or lies within the scope indicated by CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING, the call will be a no-op and can be safely omitted for performance. This can be determined by comparing the numerical values between the two enums, with smaller scopes having smaller values. + +On platforms that support GPUDirect RDMA writes via more than one path in hardware (see CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE), the user should consider those paths as belonging to separate ordering domains. Note that in such cases CUDA driver will report both RDMA writes ordering and RDMA write scope as ALL_DEVICES and a call to cuFlushGPUDirectRDMA will be a no-op, but when these multiple paths are used simultaneously, it is the user's responsibility to ensure ordering by using mechanisms outside the scope of CUDA. + +Users may query support for this API via CU_DEVICE_ATTRIBUTE_FLUSH_FLUSH_GPU_DIRECT_RDMA_OPTIONS. + + + diff --git a/content/cuda/docs/driver-driver--entry--point/DOC.md b/content/cuda/docs/driver-driver--entry--point/DOC.md new file mode 100644 index 00000000..36223383 --- /dev/null +++ b/content/cuda/docs/driver-driver--entry--point/DOC.md @@ -0,0 +1,70 @@ +--- +name: driver-driver--entry--point +description: '**Source:** group__CUDA__DRIVER__ENTRY__POINT.html#group__CUDA__DRIVER__ENTRY__POINT' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.33. Driver Entry Point Access + +**Source:** group__CUDA__DRIVER__ENTRY__POINT.html#group__CUDA__DRIVER__ENTRY__POINT + + +### Functions + +CUresult cuGetProcAddress ( const char* symbol, void** pfn, int cudaVersion, cuuint64_t flags, CUdriverProcAddressQueryResult* symbolStatus ) + + +Returns the requested driver API function pointer. + +###### Parameters + +`symbol` + \- The base name of the driver API function to look for. As an example, for the driver API cuMemAlloc_v2, `symbol` would be cuMemAlloc and `cudaVersion` would be the ABI compatible CUDA version for the _v2 variant. +`pfn` + \- Location to return the function pointer to the requested driver function +`cudaVersion` + \- The CUDA version to look for the requested driver symbol +`flags` + \- Flags to specify search options. +`symbolStatus` + \- Optional location to store the status of the search for `symbol` based on `cudaVersion`. See CUdriverProcAddressQueryResult for possible values. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Returns in `**pfn` the address of the CUDA driver function for the requested CUDA version and flags. + +The CUDA version is specified as (1000 * major + 10 * minor), so CUDA 11.2 should be specified as 11020. For a requested driver symbol, if the specified CUDA version is greater than or equal to the CUDA version in which the driver symbol was introduced, this API will return the function pointer to the corresponding versioned function. If the specified CUDA version is greater than the driver version, the API will return CUDA_ERROR_INVALID_VALUE. + +The pointer returned by the API should be cast to a function pointer matching the requested driver function's definition in the API header file. The function pointer typedef can be picked up from the corresponding typedefs header file. For example, cudaTypedefs.h consists of function pointer typedefs for driver APIs defined in cuda.h. + +The API will return CUDA_SUCCESS and set the returned `pfn` to NULL if the requested driver function is not supported on the platform, no ABI compatible driver function exists for the specified `cudaVersion` or if the driver symbol is invalid. + +It will also set the optional `symbolStatus` to one of the values in CUdriverProcAddressQueryResult with the following meanings: + + * CU_GET_PROC_ADDRESS_SUCCESS \- The requested symbol was succesfully found based on input arguments and `pfn` is valid + + * CU_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND \- The requested symbol was not found + + * CU_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT \- The requested symbol was found but is not supported by cudaVersion specified + + +The requested flags can be: + + * CU_GET_PROC_ADDRESS_DEFAULT: This is the default mode. This is equivalent to CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM if the code is compiled with --default-stream per-thread compilation flag or the macro CUDA_API_PER_THREAD_DEFAULT_STREAM is defined; CU_GET_PROC_ADDRESS_LEGACY_STREAM otherwise. + + * CU_GET_PROC_ADDRESS_LEGACY_STREAM: This will enable the search for all driver symbols that match the requested driver symbol name except the corresponding per-thread versions. + + * CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM: This will enable the search for all driver symbols that match the requested driver symbol name including the per-thread versions. If a per-thread version is not found, the API will return the legacy version of the driver function. + + +Version mixing among CUDA-defined types and driver API versions is strongly discouraged and doing so can result in an undefined behavior. More here. diff --git a/content/cuda/docs/driver-egl/DOC.md b/content/cuda/docs/driver-egl/DOC.md new file mode 100644 index 00000000..3f3d8f3e --- /dev/null +++ b/content/cuda/docs/driver-egl/DOC.md @@ -0,0 +1,352 @@ +--- +name: driver-egl +description: '**Source:** group__CUDA__EGL.html#group__CUDA__EGL' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.45. EGL Interoperability + +**Source:** group__CUDA__EGL.html#group__CUDA__EGL + + +### Functions + +CUresult cuEGLStreamConsumerAcquireFrame ( CUeglStreamConnection* conn, CUgraphicsResource* pCudaResource, CUstream* pStream, unsigned int timeout ) + + +Acquire an image frame from the EGLStream with CUDA as a consumer. + +###### Parameters + +`conn` + \- Connection on which to acquire +`pCudaResource` + \- CUDA resource on which the stream frame will be mapped for use. +`pStream` + \- CUDA stream for synchronization and any data migrations implied by CUeglResourceLocationFlags. +`timeout` + \- Desired timeout in usec for a new frame to be acquired. If set as CUDA_EGL_INFINITE_TIMEOUT, acquire waits infinitely. After timeout occurs CUDA consumer tries to acquire an old frame if available and EGL_SUPPORT_REUSE_NV flag is set. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_LAUNCH_TIMEOUT + +###### Description + +Acquire an image frame from EGLStreamKHR. This API can also acquire an old frame presented by the producer unless explicitly disabled by setting EGL_SUPPORT_REUSE_NV flag to EGL_FALSE during stream initialization. By default, EGLStream is created with this flag set to EGL_TRUE. cuGraphicsResourceGetMappedEglFrame can be called on `pCudaResource` to get CUeglFrame. + +CUresult cuEGLStreamConsumerConnect ( CUeglStreamConnection* conn, EGLStreamKHR stream ) + + +Connect CUDA to EGLStream as a consumer. + +###### Parameters + +`conn` + \- Pointer to the returned connection handle +`stream` + \- EGLStreamKHR handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Connect CUDA as a consumer to EGLStreamKHR specified by `stream`. + +The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one API to another. + +CUresult cuEGLStreamConsumerConnectWithFlags ( CUeglStreamConnection* conn, EGLStreamKHR stream, unsigned int flags ) + + +Connect CUDA to EGLStream as a consumer with given flags. + +###### Parameters + +`conn` + \- Pointer to the returned connection handle +`stream` + \- EGLStreamKHR handle +`flags` + \- Flags denote intended location - system or video. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Connect CUDA as a consumer to EGLStreamKHR specified by `stream` with specified `flags` defined by CUeglResourceLocationFlags. + +The flags specify whether the consumer wants to access frames from system memory or video memory. Default is CU_EGL_RESOURCE_LOCATION_VIDMEM. + +CUresult cuEGLStreamConsumerDisconnect ( CUeglStreamConnection* conn ) + + +Disconnect CUDA as a consumer to EGLStream . + +###### Parameters + +`conn` + \- Conection to disconnect. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Disconnect CUDA as a consumer to EGLStreamKHR. + +CUresult cuEGLStreamConsumerReleaseFrame ( CUeglStreamConnection* conn, CUgraphicsResource pCudaResource, CUstream* pStream ) + + +Releases the last frame acquired from the EGLStream. + +###### Parameters + +`conn` + \- Connection on which to release +`pCudaResource` + \- CUDA resource whose corresponding frame is to be released +`pStream` + \- CUDA stream on which release will be done. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Release the acquired image frame specified by `pCudaResource` to EGLStreamKHR. If EGL_SUPPORT_REUSE_NV flag is set to EGL_TRUE, at the time of EGL creation this API doesn't release the last frame acquired on the EGLStream. By default, EGLStream is created with this flag set to EGL_TRUE. + +CUresult cuEGLStreamProducerConnect ( CUeglStreamConnection* conn, EGLStreamKHR stream, EGLint width, EGLint height ) + + +Connect CUDA to EGLStream as a producer. + +###### Parameters + +`conn` + \- Pointer to the returned connection handle +`stream` + \- EGLStreamKHR handle +`width` + \- width of the image to be submitted to the stream +`height` + \- height of the image to be submitted to the stream + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Connect CUDA as a producer to EGLStreamKHR specified by `stream`. + +The EGLStreamKHR is an EGL object that transfers a sequence of image frames from one API to another. + +CUresult cuEGLStreamProducerDisconnect ( CUeglStreamConnection* conn ) + + +Disconnect CUDA as a producer to EGLStream . + +###### Parameters + +`conn` + \- Conection to disconnect. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Disconnect CUDA as a producer to EGLStreamKHR. + +CUresult cuEGLStreamProducerPresentFrame ( CUeglStreamConnection* conn, CUeglFrame eglframe, CUstream* pStream ) + + +Present a CUDA eglFrame to the EGLStream with CUDA as a producer. + +###### Parameters + +`conn` + \- Connection on which to present the CUDA array +`eglframe` + \- CUDA Eglstream Proucer Frame handle to be sent to the consumer over EglStream. +`pStream` + \- CUDA stream on which to present the frame. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE + +###### Description + +When a frame is presented by the producer, it gets associated with the EGLStream and thus it is illegal to free the frame before the producer is disconnected. If a frame is freed and reused it may lead to undefined behavior. + +If producer and consumer are on different GPUs (iGPU and dGPU) then frametype CU_EGL_FRAME_TYPE_ARRAY is not supported. CU_EGL_FRAME_TYPE_PITCH can be used for such cross-device applications. + +The CUeglFrame is defined as: + + + ‎ typedef struct CUeglFrame_st { + union { + CUarray pArray[MAX_PLANES]; + void* pPitch[MAX_PLANES]; + } frame; + unsigned int width; + unsigned int height; + unsigned int depth; + unsigned int pitch; + unsigned int planeCount; + unsigned int numChannels; + CUeglFrameType frameType; + CUeglColorFormat eglColorFormat; + CUarray_format cuFormat; + } CUeglFrame; + +For CUeglFrame of type CU_EGL_FRAME_TYPE_PITCH, the application may present sub-region of a memory allocation. In that case, the pitched pointer will specify the start address of the sub-region in the allocation and corresponding CUeglFrame fields will specify the dimensions of the sub-region. + +CUresult cuEGLStreamProducerReturnFrame ( CUeglStreamConnection* conn, CUeglFrame* eglframe, CUstream* pStream ) + + +Return the CUDA eglFrame to the EGLStream released by the consumer. + +###### Parameters + +`conn` + \- Connection on which to return +`eglframe` + \- CUDA Eglstream Proucer Frame handle returned from the consumer over EglStream. +`pStream` + \- CUDA stream on which to return the frame. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_LAUNCH_TIMEOUT + +###### Description + +This API can potentially return CUDA_ERROR_LAUNCH_TIMEOUT if the consumer has not returned a frame to EGL stream. If timeout is returned the application can retry. + +CUresult cuEventCreateFromEGLSync ( CUevent* phEvent, EGLSyncKHR eglSync, unsigned int flags ) + + +Creates an event from EGLSync object. + +###### Parameters + +`phEvent` + \- Returns newly created event +`eglSync` + \- Opaque handle to EGLSync object +`flags` + \- Event creation flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates an event *phEvent from an EGLSyncKHR eglSync with the flags specified via `flags`. Valid flags include: + + * CU_EVENT_DEFAULT: Default event creation flag. + + * CU_EVENT_BLOCKING_SYNC: Specifies that the created event should use blocking synchronization. A CPU thread that uses cuEventSynchronize() to wait on an event created with this flag will block until the event has actually been completed. + + +Once the `eglSync` gets destroyed, cuEventDestroy is the only API that can be invoked on the event. + +cuEventRecord and TimingData are not supported for events created from EGLSync. + +The EGLSyncKHR is an opaque handle to an EGL sync object. typedef void* EGLSyncKHR + +CUresult cuGraphicsEGLRegisterImage ( CUgraphicsResource* pCudaResource, EGLImageKHR image, unsigned int flags ) + + +Registers an EGL image. + +###### Parameters + +`pCudaResource` + \- Pointer to the returned object handle +`image` + \- An EGLImageKHR image which can be used to create target resource. +`flags` + \- Map flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Registers the EGLImageKHR specified by `image` for access by CUDA. A handle to the registered object is returned as `pCudaResource`. Additional Mapping/Unmapping is not required for the registered resource and cuGraphicsResourceGetMappedEglFrame can be directly called on the `pCudaResource`. + +The application will be responsible for synchronizing access to shared objects. The application must ensure that any pending operation which access the objects have completed before passing control to CUDA. This may be accomplished by issuing and waiting for glFinish command on all GLcontexts (for OpenGL and likewise for other APIs). The application will be also responsible for ensuring that any pending operation on the registered CUDA resource has completed prior to executing subsequent commands in other APIs accesing the same memory objects. This can be accomplished by calling cuCtxSynchronize or cuEventSynchronize (preferably). + +The surface's intended usage is specified using `flags`, as follows: + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY: Specifies that CUDA will not write to this resource. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +The EGLImageKHR is an object which can be used to create EGLImage target resource. It is defined as a void pointer. typedef void* EGLImageKHR + +CUresult cuGraphicsResourceGetMappedEglFrame ( CUeglFrame* eglFrame, CUgraphicsResource resource, unsigned int index, unsigned int mipLevel ) + + +Get an eglFrame through which to access a registered EGL graphics resource. + +###### Parameters + +`eglFrame` + \- Returned eglFrame. +`resource` + \- Registered resource to access. +`index` + \- Index for cubemap surfaces. +`mipLevel` + \- Mipmap level for the subresource to access. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED + +###### Description + +Returns in `*eglFrame` an eglFrame pointer through which the registered graphics resource `resource` may be accessed. This API can only be called for registered EGL graphics resources. + +The CUeglFrame is defined as: + + + ‎ typedef struct CUeglFrame_st { + union { + CUarray pArray[MAX_PLANES]; + void* pPitch[MAX_PLANES]; + } frame; + unsigned int width; + unsigned int height; + unsigned int depth; + unsigned int pitch; + unsigned int planeCount; + unsigned int numChannels; + CUeglFrameType frameType; + CUeglColorFormat eglColorFormat; + CUarray_format cuFormat; + } CUeglFrame; + +If `resource` is not registered then CUDA_ERROR_NOT_MAPPED is returned. * diff --git a/content/cuda/docs/driver-error/DOC.md b/content/cuda/docs/driver-error/DOC.md new file mode 100644 index 00000000..44ef7662 --- /dev/null +++ b/content/cuda/docs/driver-error/DOC.md @@ -0,0 +1,63 @@ +--- +name: driver-error +description: '**Source:** group__CUDA__ERROR.html#group__CUDA__ERROR' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.2. Error Handling + +**Source:** group__CUDA__ERROR.html#group__CUDA__ERROR + + +### Functions + +CUresult cuGetErrorName ( CUresult error, const char** pStr ) + + +Gets the string representation of an error code enum name. + +###### Parameters + +`error` + \- Error code to convert to string +`pStr` + \- Address of the string pointer. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets `*pStr` to the address of a NULL-terminated string representation of the name of the enum error code `error`. If the error code is not recognized, CUDA_ERROR_INVALID_VALUE will be returned and `*pStr` will be set to the NULL address. + +CUresult, cudaGetErrorName + +CUresult cuGetErrorString ( CUresult error, const char** pStr ) + + +Gets the string description of an error code. + +###### Parameters + +`error` + \- Error code to convert to string +`pStr` + \- Address of the string pointer. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets `*pStr` to the address of a NULL-terminated string description of the error code `error`. If the error code is not recognized, CUDA_ERROR_INVALID_VALUE will be returned and `*pStr` will be set to the NULL address. + +CUresult, cudaGetErrorString + diff --git a/content/cuda/docs/driver-event/DOC.md b/content/cuda/docs/driver-event/DOC.md new file mode 100644 index 00000000..a41d2880 --- /dev/null +++ b/content/cuda/docs/driver-event/DOC.md @@ -0,0 +1,196 @@ +--- +name: driver-event +description: '**Source:** group__CUDA__EVENT.html#group__CUDA__EVENT' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.19. Event Management + +**Source:** group__CUDA__EVENT.html#group__CUDA__EVENT + + +### Functions + +CUresult cuEventCreate ( CUevent* phEvent, unsigned int Flags ) + + +Creates an event. + +###### Parameters + +`phEvent` + \- Returns newly created event +`Flags` + \- Event creation flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates an event *phEvent for the current context with the flags specified via `Flags`. Valid flags include: + + * CU_EVENT_DEFAULT: Default event creation flag. + + * CU_EVENT_BLOCKING_SYNC: Specifies that the created event should use blocking synchronization. A CPU thread that uses cuEventSynchronize() to wait on an event created with this flag will block until the event has actually been recorded. + + * CU_EVENT_DISABLE_TIMING: Specifies that the created event does not need to record timing data. Events created with this flag specified and the CU_EVENT_BLOCKING_SYNC flag not specified will provide the best performance when used with cuStreamWaitEvent() and cuEventQuery(). + + * CU_EVENT_INTERPROCESS: Specifies that the created event may be used as an interprocess event by cuIpcGetEventHandle(). CU_EVENT_INTERPROCESS must be specified along with CU_EVENT_DISABLE_TIMING. + + +CUresult cuEventDestroy ( CUevent hEvent ) + + +Destroys an event. + +###### Parameters + +`hEvent` + \- Event to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Destroys the event specified by `hEvent`. + +An event may be destroyed before it is complete (i.e., while cuEventQuery() would return CUDA_ERROR_NOT_READY). In this case, the call does not block on completion of the event, and any associated resources will automatically be released asynchronously at completion. + +CUresult cuEventElapsedTime ( float* pMilliseconds, CUevent hStart, CUevent hEnd ) + + +Computes the elapsed time between two events. + +###### Parameters + +`pMilliseconds` + \- Time between `hStart` and `hEnd` in ms +`hStart` + \- Starting event +`hEnd` + \- Ending event + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_READY, CUDA_ERROR_UNKNOWN + +###### Description + +Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds). Note this API is not guaranteed to return the latest errors for pending work. As such this API is intended to serve as an elapsed time calculation only and any polling for completion on the events to be compared should be done with cuEventQuery instead. + +If either event was last recorded in a non-NULL stream, the resulting time may be greater than expected (even if both used the same stream handle). This happens because the cuEventRecord() operation takes place asynchronously and there is no guarantee that the measured latency is actually just between the two events. Any number of other different stream operations could execute in between the two measured events, thus altering the timing in a significant way. + +If cuEventRecord() has not been called on either event then CUDA_ERROR_INVALID_HANDLE is returned. If cuEventRecord() has been called on both events but one or both of them has not yet been completed (that is, cuEventQuery() would return CUDA_ERROR_NOT_READY on at least one of the events), CUDA_ERROR_NOT_READY is returned. If either event was created with the CU_EVENT_DISABLE_TIMING flag, then this function will return CUDA_ERROR_INVALID_HANDLE. + +CUresult cuEventQuery ( CUevent hEvent ) + + +Queries an event's status. + +###### Parameters + +`hEvent` + \- Event to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_READY + +###### Description + +Queries the status of all work currently captured by `hEvent`. See cuEventRecord() for details on what is captured by an event. + +Returns CUDA_SUCCESS if all captured work has been completed, or CUDA_ERROR_NOT_READY if any captured work is incomplete. + +For the purposes of Unified Memory, a return value of CUDA_SUCCESS is equivalent to having called cuEventSynchronize(). + +CUresult cuEventRecord ( CUevent hEvent, CUstream hStream ) + + +Records an event. + +###### Parameters + +`hEvent` + \- Event to record +`hStream` + \- Stream to record event for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Captures in `hEvent` the contents of `hStream` at the time of this call. `hEvent` and `hStream` must be from the same context otherwise CUDA_ERROR_INVALID_HANDLE is returned. Calls such as cuEventQuery() or cuStreamWaitEvent() will then examine or wait for completion of the work that was captured. Uses of `hStream` after this call do not modify `hEvent`. See note on default stream behavior for what is captured in the default case. + +cuEventRecord() can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such as cuStreamWaitEvent() use the most recently captured state at the time of the API call, and are not affected by later calls to cuEventRecord(). Before the first call to cuEventRecord(), an event represents an empty set of work, so for example cuEventQuery() would return CUDA_SUCCESS. + + * This function uses standard default stream semantics. + + * +CUresult cuEventRecordWithFlags ( CUevent hEvent, CUstream hStream, unsigned int flags ) + + +Records an event. + +###### Parameters + +`hEvent` + \- Event to record +`hStream` + \- Stream to record event for +`flags` + \- See CUevent_capture_flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Captures in `hEvent` the contents of `hStream` at the time of this call. `hEvent` and `hStream` must be from the same context otherwise CUDA_ERROR_INVALID_HANDLE is returned. Calls such as cuEventQuery() or cuStreamWaitEvent() will then examine or wait for completion of the work that was captured. Uses of `hStream` after this call do not modify `hEvent`. See note on default stream behavior for what is captured in the default case. + +cuEventRecordWithFlags() can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such as cuStreamWaitEvent() use the most recently captured state at the time of the API call, and are not affected by later calls to cuEventRecordWithFlags(). Before the first call to cuEventRecordWithFlags(), an event represents an empty set of work, so for example cuEventQuery() would return CUDA_SUCCESS. + +flags include: + + * CU_EVENT_RECORD_DEFAULT: Default event creation flag. + + * CU_EVENT_RECORD_EXTERNAL: Event is captured in the graph as an external event node when performing stream capture. This flag is invalid outside of stream capture. + + + * This function uses standard default stream semantics. + + * +CUresult cuEventSynchronize ( CUevent hEvent ) + + +Waits for an event to complete. + +###### Parameters + +`hEvent` + \- Event to wait for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Waits until the completion of all work currently captured in `hEvent`. See cuEventRecord() for details on what is captured by an event. + +Waiting for an event that was created with the CU_EVENT_BLOCKING_SYNC flag will cause the calling CPU thread to block until the event has been completed by the device. If the CU_EVENT_BLOCKING_SYNC flag has not been set, then the CPU thread will busy-wait until the event has been completed by the device. + + diff --git a/content/cuda/docs/driver-exec--deprecated/DOC.md b/content/cuda/docs/driver-exec--deprecated/DOC.md new file mode 100644 index 00000000..272483e5 --- /dev/null +++ b/content/cuda/docs/driver-exec--deprecated/DOC.md @@ -0,0 +1,314 @@ +--- +name: driver-exec--deprecated +description: '**Source:** group__CUDA__EXEC__DEPRECATED.html#group__CUDA__EXEC__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.23. Execution Control [DEPRECATED] + +**Source:** group__CUDA__EXEC__DEPRECATED.html#group__CUDA__EXEC__DEPRECATED + + +### Functions + +CUresult cuFuncSetBlockShape ( CUfunction hfunc, int x, int y, int z ) + + +Sets the block-dimensions for the function. + +###### Parameters + +`hfunc` + \- Kernel to specify dimensions of +`x` + \- X dimension +`y` + \- Y dimension +`z` + \- Z dimension + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the `x`, `y`, and `z` dimensions of the thread blocks that are created when the kernel given by `hfunc` is launched. + +CUresult cuFuncSetSharedMemConfig ( CUfunction hfunc, CUsharedconfig config ) + + +Sets the shared memory configuration for a device function. + +###### Parameters + +`hfunc` + \- kernel to be given a shared memory config +`config` + \- requested shared memory configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Deprecated + +###### Description + +On devices with configurable shared memory banks, this function will force all subsequent launches of the specified device function to have the given shared memory bank size configuration. On any given launch of the function, the shared memory configuration of the device will be temporarily changed if needed to suit the function's preferred configuration. Changes in shared memory configuration between subsequent launches of functions, may introduce a device side synchronization point. + +Any per-function setting of shared memory bank size set via cuFuncSetSharedMemConfig will override the context wide setting set with cuCtxSetSharedMemConfig. + +Changing the shared memory bank size will not increase shared memory usage or affect occupancy of kernels, but may have major effects on performance. Larger bank sizes will allow for greater potential bandwidth to shared memory, but will change what kinds of accesses to shared memory will result in bank conflicts. + +This function will do nothing on devices with fixed shared memory bank size. + +The supported bank configurations are: + + * CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE: use the context's shared memory configuration when launching this function. + + * CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: set shared memory bank width to be natively four bytes when launching this function. + + * CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: set shared memory bank width to be natively eight bytes when launching this function. + + +CUresult cuFuncSetSharedSize ( CUfunction hfunc, unsigned int bytes ) + + +Sets the dynamic shared-memory size for the function. + +###### Parameters + +`hfunc` + \- Kernel to specify dynamic shared-memory size for +`bytes` + \- Dynamic shared-memory size per thread in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Sets through `bytes` the amount of dynamic shared memory that will be available to each thread block when the kernel given by `hfunc` is launched. + +CUresult cuLaunch ( CUfunction f ) + + +Launches a CUDA function. + +###### Parameters + +`f` + \- Kernel to launch + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED + +###### Deprecated + +###### Description + +Invokes the kernel `f` on a 1 x 1 x 1 grid of blocks. The block contains the number of threads specified by a previous call to cuFuncSetBlockShape(). + +The block shape, dynamic shared memory size, and parameter information must be set using cuFuncSetBlockShape(), cuFuncSetSharedSize(), cuParamSetSize(), cuParamSeti(), cuParamSetf(), and cuParamSetv() prior to calling this function. + +Launching a function via cuLaunchKernel() invalidates the function's block shape, dynamic shared memory size, and parameter information. After launching via cuLaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior. + +CUresult cuLaunchGrid ( CUfunction f, int grid_width, int grid_height ) + + +Launches a CUDA function. + +###### Parameters + +`f` + \- Kernel to launch +`grid_width` + \- Width of grid in blocks +`grid_height` + \- Height of grid in blocks + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED + +###### Deprecated + +###### Description + +Invokes the kernel `f` on a `grid_width` x `grid_height` grid of blocks. Each block contains the number of threads specified by a previous call to cuFuncSetBlockShape(). + +The block shape, dynamic shared memory size, and parameter information must be set using cuFuncSetBlockShape(), cuFuncSetSharedSize(), cuParamSetSize(), cuParamSeti(), cuParamSetf(), and cuParamSetv() prior to calling this function. + +Launching a function via cuLaunchKernel() invalidates the function's block shape, dynamic shared memory size, and parameter information. After launching via cuLaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior. + +CUresult cuLaunchGridAsync ( CUfunction f, int grid_width, int grid_height, CUstream hStream ) + + +Launches a CUDA function. + +###### Parameters + +`f` + \- Kernel to launch +`grid_width` + \- Width of grid in blocks +`grid_height` + \- Height of grid in blocks +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED + +###### Deprecated + +###### Description + +Invokes the kernel `f` on a `grid_width` x `grid_height` grid of blocks. Each block contains the number of threads specified by a previous call to cuFuncSetBlockShape(). + +The block shape, dynamic shared memory size, and parameter information must be set using cuFuncSetBlockShape(), cuFuncSetSharedSize(), cuParamSetSize(), cuParamSeti(), cuParamSetf(), and cuParamSetv() prior to calling this function. + +Launching a function via cuLaunchKernel() invalidates the function's block shape, dynamic shared memory size, and parameter information. After launching via cuLaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior. + + * In certain cases where cubins are created with no ABI (i.e., using `ptxas``--abi-compile``no`), this function may serialize kernel launches. The CUDA driver retains asynchronous behavior by growing the per-thread stack as needed per launch and not shrinking it afterwards. + + * This function uses standard default stream semantics. + + * +CUresult cuParamSetSize ( CUfunction hfunc, unsigned int numbytes ) + + +Sets the parameter size for the function. + +###### Parameters + +`hfunc` + \- Kernel to set parameter size for +`numbytes` + \- Size of parameter list in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Sets through `numbytes` the total size in bytes needed by the function parameters of the kernel corresponding to `hfunc`. + +CUresult cuParamSetTexRef ( CUfunction hfunc, int texunit, CUtexref hTexRef ) + + +Adds a texture-reference to the function's argument list. + +###### Parameters + +`hfunc` + \- Kernel to add texture-reference to +`texunit` + \- Texture unit (must be CU_PARAM_TR_DEFAULT) +`hTexRef` + \- Texture-reference to add to argument list + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Makes the CUDA array or linear memory bound to the texture reference `hTexRef` available to a device program as a texture. In this version of CUDA, the texture-reference must be obtained via cuModuleGetTexRef() and the `texunit` parameter must be set to CU_PARAM_TR_DEFAULT. + + + +CUresult cuParamSetf ( CUfunction hfunc, int offset, float value ) + + +Adds a floating-point parameter to the function's argument list. + +###### Parameters + +`hfunc` + \- Kernel to add parameter to +`offset` + \- Offset to add parameter to argument list +`value` + \- Value of parameter + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Sets a floating-point parameter that will be specified the next time the kernel corresponding to `hfunc` will be invoked. `offset` is a byte offset. + +CUresult cuParamSeti ( CUfunction hfunc, int offset, unsigned int value ) + + +Adds an integer parameter to the function's argument list. + +###### Parameters + +`hfunc` + \- Kernel to add parameter to +`offset` + \- Offset to add parameter to argument list +`value` + \- Value of parameter + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Sets an integer parameter that will be specified the next time the kernel corresponding to `hfunc` will be invoked. `offset` is a byte offset. + +CUresult cuParamSetv ( CUfunction hfunc, int offset, void* ptr, unsigned int numbytes ) + + +Adds arbitrary data to the function's argument list. + +###### Parameters + +`hfunc` + \- Kernel to add data to +`offset` + \- Offset to add data to argument list +`ptr` + \- Pointer to arbitrary data +`numbytes` + \- Size of data to copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Copies an arbitrary amount of data (specified in `numbytes`) from `ptr` into the parameter space of the kernel corresponding to `hfunc`. `offset` is a byte offset. + + diff --git a/content/cuda/docs/driver-exec/DOC.md b/content/cuda/docs/driver-exec/DOC.md new file mode 100644 index 00000000..b7bfb056 --- /dev/null +++ b/content/cuda/docs/driver-exec/DOC.md @@ -0,0 +1,730 @@ +--- +name: driver-exec +description: '**Source:** group__CUDA__EXEC.html#group__CUDA__EXEC' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.22. Execution Control + +**Source:** group__CUDA__EXEC.html#group__CUDA__EXEC + + +### Functions + +CUresult cuFuncGetAttribute ( int* pi, CUfunction_attribute attrib, CUfunction hfunc ) + + +Returns information about a function. + +###### Parameters + +`pi` + \- Returned attribute value +`attrib` + \- Attribute requested +`hfunc` + \- Function to query attribute of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_FUNCTION_NOT_LOADED + +###### Description + +Returns in `*pi` the integer value of the attribute `attrib` on the kernel given by `hfunc`. The supported attributes are: + + * CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK: The maximum number of threads per block, beyond which a launch of the function would fail. This number depends on both the function and the device on which the function is currently loaded. + + * CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES: The size in bytes of statically-allocated shared memory per block required by this function. This does not include dynamically-allocated shared memory requested by the user at runtime. + + * CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES: The size in bytes of user-allocated constant memory required by this function. + + * CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES: The size in bytes of local memory used by each thread of this function. + + * CU_FUNC_ATTRIBUTE_NUM_REGS: The number of registers used by each thread of this function. + + * CU_FUNC_ATTRIBUTE_PTX_VERSION: The PTX virtual architecture version for which the function was compiled. This value is the major PTX version * 10 + the minor PTX version, so a PTX version 1.3 function would return the value 13. Note that this may return the undefined value of 0 for cubins compiled prior to CUDA 3.0. + + * CU_FUNC_ATTRIBUTE_BINARY_VERSION: The binary architecture version for which the function was compiled. This value is the major binary version * 10 + the minor binary version, so a binary version 1.3 function would return the value 13. Note that this will return a value of 10 for legacy cubins that do not have a properly-encoded binary architecture version. + + * CU_FUNC_CACHE_MODE_CA: The attribute to indicate whether the function has been compiled with user specified option "-Xptxas \--dlcm=ca" set . + + * CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: The maximum size in bytes of dynamically-allocated shared memory. + + * CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: Preferred shared memory-L1 cache split ratio in percent of total shared memory. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET: If this attribute is set, the kernel must launch with a valid cluster size specified. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH: The required cluster width in blocks. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT: The required cluster height in blocks. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH: The required cluster depth in blocks. + + * CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. A non-portable cluster size may only function on the specific SKUs the program is tested on. The launch might fail if the program is run on a different hardware platform. CUDA API provides cudaOccupancyMaxActiveClusters to assist with checking whether the desired size can be launched on the current device. A portable cluster size is guaranteed to be functional on all compute capabilities higher than the target compute capability. The portable cluster size for sm_90 is 8 blocks per cluster. This value may increase for future compute capabilities. The specific hardware unit may support higher cluster sizes that’s not guaranteed to be portable. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE: The block scheduling policy of a function. The value type is CUclusterSchedulingPolicy. + + +With a few execeptions, function attributes may also be queried on unloaded function handles returned from cuModuleEnumerateFunctions. CUDA_ERROR_FUNCTION_NOT_LOADED is returned if the attribute requires a fully loaded function but the function is not loaded. The loading state of a function may be queried using cuFuncIsloaded. cuFuncLoad may be called to explicitly load a function before querying the following attributes that require the function to be loaded: + + * CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK + + * CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES + + * CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES + + +CUresult cuFuncGetModule ( CUmodule* hmod, CUfunction hfunc ) + + +Returns a module handle. + +###### Parameters + +`hmod` + \- Returned module handle +`hfunc` + \- Function to retrieve module for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `*hmod` the handle of the module that function `hfunc` is located in. The lifetime of the module corresponds to the lifetime of the context it was loaded in or until the module is explicitly unloaded. + +The CUDA runtime manages its own modules loaded into the primary context. If the handle returned by this API refers to a module loaded by the CUDA runtime, calling cuModuleUnload() on that module will result in undefined behavior. + + + +CUresult cuFuncGetName ( const char** name, CUfunction hfunc ) + + +Returns the function name for a CUfunction handle. + +###### Parameters + +`name` + \- The returned name of the function +`hfunc` + \- The function handle to retrieve the name for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `**name` the function name associated with the function handle `hfunc` . The function name is returned as a null-terminated string. The returned name is only valid when the function handle is valid. If the module is unloaded or reloaded, one must call the API again to get the updated name. This API may return a mangled name if the function is not declared as having C linkage. If either `**name` or `hfunc` is NULL, CUDA_ERROR_INVALID_VALUE is returned. + + + +CUresult cuFuncGetParamInfo ( CUfunction func, size_t paramIndex, size_t* paramOffset, size_t* paramSize ) + + +Returns the offset and size of a kernel parameter in the device-side parameter layout. + +###### Parameters + +`func` + \- The function to query +`paramIndex` + \- The parameter index to query +`paramOffset` + \- Returns the offset into the device-side parameter layout at which the parameter resides +`paramSize` + \- Optionally returns the size of the parameter in the device-side parameter layout + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Queries the kernel parameter at `paramIndex` into `func's` list of parameters, and returns in `paramOffset` and `paramSize` the offset and size, respectively, where the parameter will reside in the device-side parameter layout. This information can be used to update kernel node parameters from the device via cudaGraphKernelNodeSetParam() and cudaGraphKernelNodeUpdatesApply(). `paramIndex` must be less than the number of parameters that `func` takes. `paramSize` can be set to NULL if only the parameter offset is desired. + +CUresult cuFuncIsLoaded ( CUfunctionLoadingState* state, CUfunction function ) + + +Returns if the function is loaded. + +###### Parameters + +`state` + \- returned loading state +`function` + \- the function to check + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `state` the loading state of `function`. + +CUresult cuFuncLoad ( CUfunction function ) + + +Loads a function. + +###### Parameters + +`function` + \- the function to load + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Finalizes function loading for `function`. Calling this API with a fully loaded function has no effect. + +CUresult cuFuncSetAttribute ( CUfunction hfunc, CUfunction_attribute attrib, int value ) + + +Sets information about a function. + +###### Parameters + +`hfunc` + \- Function to query attribute of +`attrib` + \- Attribute requested +`value` + \- The value to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +This call sets the value of a specified attribute `attrib` on the kernel given by `hfunc` to an integer value specified by `val` This function returns CUDA_SUCCESS if the new value of the attribute could be successfully set. If the set fails, this call will return an error. Not all attributes can have values set. Attempting to set a value on a read-only attribute will result in an error (CUDA_ERROR_INVALID_VALUE) + +Supported attributes for the cuFuncSetAttribute call are: + + * CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: This maximum size in bytes of dynamically-allocated shared memory. The value should contain the requested maximum size of dynamically-allocated shared memory. The sum of this value and the function attribute CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES cannot exceed the device attribute CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN. The maximal size of requestable dynamic shared memory may differ by GPU architecture. + + * CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: On devices where the L1 cache and shared memory use the same hardware resources, this sets the shared memory carveout preference, in percent of the total shared memory. See CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR This is only a hint, and the driver can choose a different ratio if required to execute the function. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH: The required cluster width in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT: The required cluster height in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH: The required cluster depth in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE: The block scheduling policy of a function. The value type is CUclusterSchedulingPolicy. + + +CUresult cuFuncSetCacheConfig ( CUfunction hfunc, CUfunc_cache config ) + + +Sets the preferred cache configuration for a device function. + +###### Parameters + +`hfunc` + \- Kernel to configure cache for +`config` + \- Requested cache configuration + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +On devices where the L1 cache and shared memory use the same hardware resources, this sets through `config` the preferred cache configuration for the device function `hfunc`. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute `hfunc`. Any context-wide preference set via cuCtxSetCacheConfig() will be overridden by this per-function setting unless the per-function setting is CU_FUNC_CACHE_PREFER_NONE. In that case, the current context-wide setting will be used. + +This setting does nothing on devices where the size of the L1 cache and shared memory are fixed. + +Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point. + +The supported cache configurations are: + + * CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) + + * CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache + + * CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory + + * CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory + + +CUresult cuLaunchCooperativeKernel ( CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void** kernelParams ) + + +Launches a CUDA function CUfunction or a CUDA kernel CUkernel where thread blocks can cooperate and synchronize as they execute. + +###### Parameters + +`f` + \- Function CUfunction or Kernel CUkernel to launch +`gridDimX` + \- Width of grid in blocks +`gridDimY` + \- Height of grid in blocks +`gridDimZ` + \- Depth of grid in blocks +`blockDimX` + \- X dimension of each thread block +`blockDimY` + \- Y dimension of each thread block +`blockDimZ` + \- Z dimension of each thread block +`sharedMemBytes` + \- Dynamic shared-memory size per thread block in bytes +`hStream` + \- Stream identifier +`kernelParams` + \- Array of pointers to kernel parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_NOT_FOUND + +###### Description + +Invokes the function CUfunction or the kernel CUkernel`f` on a `gridDimX` x `gridDimY` x `gridDimZ` grid of blocks. Each block contains `blockDimX` x `blockDimY` x `blockDimZ` threads. + +`sharedMemBytes` sets the amount of dynamic shared memory that will be available to each thread block. + +The device on which this kernel is invoked must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH. + +The total number of blocks launched cannot exceed the maximum number of blocks per multiprocessor as returned by cuOccupancyMaxActiveBlocksPerMultiprocessor (or cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors as specified by the device attribute CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT. + +The kernel cannot make use of CUDA dynamic parallelism. + +Kernel parameters must be specified via `kernelParams`. If `f` has N parameters, then `kernelParams` needs to be an array of N pointers. Each of `kernelParams`[0] through `kernelParams`[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel's image. + +Calling cuLaunchCooperativeKernel() sets persistent function state that is the same as function state set through cuLaunchKernel API + +When the kernel `f` is launched via cuLaunchCooperativeKernel(), the previous block shape, shared size and parameter info associated with `f` is overwritten. + +Note that to use cuLaunchCooperativeKernel(), the kernel `f` must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then cuLaunchCooperativeKernel() will return CUDA_ERROR_INVALID_IMAGE. + +Note that the API can also be used to launch context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to launch the kernel on will either be taken from the specified stream `hStream` or the current context in case of NULL stream. + + * This function uses standard default stream semantics. + + * +CUresult cuLaunchCooperativeKernelMultiDevice ( CUDA_LAUNCH_PARAMS* launchParamsList, unsigned int numDevices, unsigned int flags ) + + +Launches CUDA functions on multiple devices where thread blocks can cooperate and synchronize as they execute. + +###### Parameters + +`launchParamsList` + \- List of launch parameters, one per device +`numDevices` + \- Size of the `launchParamsList` array +`flags` + \- Flags to control launch behavior + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED + +###### Deprecated + +This function is deprecated as of CUDA 11.3. + +###### Description + +Invokes kernels as specified in the `launchParamsList` array where each element of the array specifies all the parameters required to perform a single kernel launch. These kernels can cooperate and synchronize as they execute. The size of the array is specified by `numDevices`. + +No two kernels can be launched on the same device. All the devices targeted by this multi-device launch must be identical. All devices must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH. + +All kernels launched must be identical with respect to the compiled code. Note that any __device__, __constant__ or __managed__ variables present in the module that owns the kernel launched on each device, are independently instantiated on every device. It is the application's responsibility to ensure these variables are initialized and used appropriately. + +The size of the grids as specified in blocks, the size of the blocks themselves and the amount of shared memory used by each thread block must also match across all launched kernels. + +The streams used to launch these kernels must have been created via either cuStreamCreate or cuStreamCreateWithPriority. The NULL stream or CU_STREAM_LEGACY or CU_STREAM_PER_THREAD cannot be used. + +The total number of blocks launched per kernel cannot exceed the maximum number of blocks per multiprocessor as returned by cuOccupancyMaxActiveBlocksPerMultiprocessor (or cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors as specified by the device attribute CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT. Since the total number of blocks launched per device has to match across all devices, the maximum number of blocks that can be launched per device will be limited by the device with the least number of multiprocessors. + +The kernels cannot make use of CUDA dynamic parallelism. + +The CUDA_LAUNCH_PARAMS structure is defined as: + + + ‎ typedef struct CUDA_LAUNCH_PARAMS_st + { + CUfunction function; + unsigned int gridDimX; + unsigned int gridDimY; + unsigned int gridDimZ; + unsigned int blockDimX; + unsigned int blockDimY; + unsigned int blockDimZ; + unsigned int sharedMemBytes; + CUstream hStream; + void **kernelParams; + } CUDA_LAUNCH_PARAMS; + +where: + + * CUDA_LAUNCH_PARAMS::function specifies the kernel to be launched. All functions must be identical with respect to the compiled code. Note that you can also specify context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then casting to CUfunction. In this case, the context to launch the kernel on be taken from the specified stream CUDA_LAUNCH_PARAMS::hStream. + + * CUDA_LAUNCH_PARAMS::gridDimX is the width of the grid in blocks. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::gridDimY is the height of the grid in blocks. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::gridDimZ is the depth of the grid in blocks. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::blockDimX is the X dimension of each thread block. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::blockDimX is the Y dimension of each thread block. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::blockDimZ is the Z dimension of each thread block. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::sharedMemBytes is the dynamic shared-memory size per thread block in bytes. This must match across all kernels launched. + + * CUDA_LAUNCH_PARAMS::hStream is the handle to the stream to perform the launch in. This cannot be the NULL stream or CU_STREAM_LEGACY or CU_STREAM_PER_THREAD. The CUDA context associated with this stream must match that associated with CUDA_LAUNCH_PARAMS::function. + + * CUDA_LAUNCH_PARAMS::kernelParams is an array of pointers to kernel parameters. If CUDA_LAUNCH_PARAMS::function has N parameters, then CUDA_LAUNCH_PARAMS::kernelParams needs to be an array of N pointers. Each of CUDA_LAUNCH_PARAMS::kernelParams[0] through CUDA_LAUNCH_PARAMS::kernelParams[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel's image. + + +By default, the kernel won't begin execution on any GPU until all prior work in all the specified streams has completed. This behavior can be overridden by specifying the flag CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC. When this flag is specified, each kernel will only wait for prior work in the stream corresponding to that GPU to complete before it begins execution. + +Similarly, by default, any subsequent work pushed in any of the specified streams will not begin execution until the kernels on all GPUs have completed. This behavior can be overridden by specifying the flag CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC. When this flag is specified, any subsequent work pushed in any of the specified streams will only wait for the kernel launched on the GPU corresponding to that stream to complete before it begins execution. + +Calling cuLaunchCooperativeKernelMultiDevice() sets persistent function state that is the same as function state set through cuLaunchKernel API when called individually for each element in `launchParamsList`. + +When kernels are launched via cuLaunchCooperativeKernelMultiDevice(), the previous block shape, shared size and parameter info associated with each CUDA_LAUNCH_PARAMS::function in `launchParamsList` is overwritten. + +Note that to use cuLaunchCooperativeKernelMultiDevice(), the kernels must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then cuLaunchCooperativeKernelMultiDevice() will return CUDA_ERROR_INVALID_IMAGE. + + * This function uses standard default stream semantics. + + * +CUresult cuLaunchHostFunc ( CUstream hStream, CUhostFn fn, void* userData ) + + +Enqueues a host function call in a stream. + +###### Parameters + +`hStream` + \- Stream to enqueue function call in +`fn` + \- The function to call once preceding stream operations are complete +`userData` + \- User-specified data to be passed to the function + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Enqueues a host function to run in a stream. The function will be called after currently enqueued work and will block work added after it. + +The host function must not make any CUDA API calls. Attempting to use a CUDA API may result in CUDA_ERROR_NOT_PERMITTED, but this is not required. The host function must not perform any synchronization that may depend on outstanding CUDA work not mandated to run earlier. Host functions without a mandated order (such as in independent streams) execute in undefined order and may be serialized. + +For the purposes of Unified Memory, execution makes a number of guarantees: + + * The stream is considered idle for the duration of the function's execution. Thus, for example, the function may always use memory attached to the stream it was enqueued in. + + * The start of execution of the function has the same effect as synchronizing an event recorded in the same stream immediately prior to the function. It thus synchronizes streams which have been "joined" prior to the function. + + * Adding device work to any stream does not have the effect of making the stream active until all preceding host functions and stream callbacks have executed. Thus, for example, a function might use global attached memory even if work has been added to another stream, if the work has been ordered behind the function call with an event. + + * Completion of the function does not cause a stream to become active except as described above. The stream will remain idle if no device work follows the function, and will remain idle across consecutive host functions or stream callbacks without device work in between. Thus, for example, stream synchronization can be done by signaling from a host function at the end of the stream. + + +Note that, in contrast to cuStreamAddCallback, the function will not be called in the event of an error in the CUDA context. + + * This function uses standard default stream semantics. + + * +CUresult cuLaunchKernel ( CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void** kernelParams, void** extra ) + + +Launches a CUDA function CUfunction or a CUDA kernel CUkernel. + +###### Parameters + +`f` + \- Function CUfunction or Kernel CUkernel to launch +`gridDimX` + \- Width of grid in blocks +`gridDimY` + \- Height of grid in blocks +`gridDimZ` + \- Depth of grid in blocks +`blockDimX` + \- X dimension of each thread block +`blockDimY` + \- Y dimension of each thread block +`blockDimZ` + \- Z dimension of each thread block +`sharedMemBytes` + \- Dynamic shared-memory size per thread block in bytes +`hStream` + \- Stream identifier +`kernelParams` + \- Array of pointers to kernel parameters +`extra` + \- Extra options + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_NOT_FOUND + +###### Description + +Invokes the function CUfunction or the kernel CUkernel`f` on a `gridDimX` x `gridDimY` x `gridDimZ` grid of blocks. Each block contains `blockDimX` x `blockDimY` x `blockDimZ` threads. + +`sharedMemBytes` sets the amount of dynamic shared memory that will be available to each thread block. + +Kernel parameters to `f` can be specified in one of two ways: + +1) Kernel parameters can be specified via `kernelParams`. If `f` has N parameters, then `kernelParams` needs to be an array of N pointers. Each of `kernelParams`[0] through `kernelParams`[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel's image. + +2) Kernel parameters can also be packaged by the application into a single buffer that is passed in via the `extra` parameter. This places the burden on the application of knowing each kernel parameter's size and alignment/padding within the buffer. Here is an example of using the `extra` parameter in this manner: + + + ‎ size_t argBufferSize; + char argBuffer[256]; + + // populate argBuffer and argBufferSize + + void *config[] = { + CU_LAUNCH_PARAM_BUFFER_POINTER, argBuffer + CU_LAUNCH_PARAM_BUFFER_SIZE, &argBufferSize + CU_LAUNCH_PARAM_END + }; + status = cuLaunchKernel(f, gx, gy, gz, bx, by, bz, sh, s, NULL, config); + +The `extra` parameter exists to allow cuLaunchKernel to take additional less commonly used arguments. `extra` specifies a list of names of extra settings and their corresponding values. Each extra setting name is immediately followed by the corresponding value. The list must be terminated with either NULL or CU_LAUNCH_PARAM_END. + + * CU_LAUNCH_PARAM_END, which indicates the end of the `extra` array; + + * CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next value in `extra` will be a pointer to a buffer containing all the kernel parameters for launching kernel `f`; + + * CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next value in `extra` will be a pointer to a size_t containing the size of the buffer specified with CU_LAUNCH_PARAM_BUFFER_POINTER; + + +The error CUDA_ERROR_INVALID_VALUE will be returned if kernel parameters are specified with both `kernelParams` and `extra` (i.e. both `kernelParams` and `extra` are non-NULL). + +Calling cuLaunchKernel() invalidates the persistent function state set through the following deprecated APIs: cuFuncSetBlockShape(), cuFuncSetSharedSize(), cuParamSetSize(), cuParamSeti(), cuParamSetf(), cuParamSetv(). + +Note that to use cuLaunchKernel(), the kernel `f` must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then cuLaunchKernel() will return CUDA_ERROR_INVALID_IMAGE. + +Note that the API can also be used to launch context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to launch the kernel on will either be taken from the specified stream `hStream` or the current context in case of NULL stream. + + * This function uses standard default stream semantics. + + * +CUresult cuLaunchKernelEx ( const CUlaunchConfig* config, CUfunction f, void** kernelParams, void** extra ) + + +Launches a CUDA function CUfunction or a CUDA kernel CUkernel with launch-time configuration. + +###### Parameters + +`config` + \- Config to launch +`f` + \- Function CUfunction or Kernel CUkernel to launch +`kernelParams` + \- Array of pointers to kernel parameters +`extra` + \- Extra options + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_LAUNCH_FAILED, CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, CUDA_ERROR_LAUNCH_TIMEOUT, CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_NOT_FOUND + +###### Description + +Invokes the function CUfunction or the kernel CUkernel`f` with the specified launch-time configuration `config`. + +The CUlaunchConfig structure is defined as: + + + ‎ typedef struct CUlaunchConfig_st { + unsigned int gridDimX; + unsigned int gridDimY; + unsigned int gridDimZ; + unsigned int blockDimX; + unsigned int blockDimY; + unsigned int blockDimZ; + unsigned int sharedMemBytes; + CUstream hStream; + CUlaunchAttribute *attrs; + unsigned int numAttrs; + } CUlaunchConfig; + +where: + + * CUlaunchConfig::gridDimX is the width of the grid in blocks. + + * CUlaunchConfig::gridDimY is the height of the grid in blocks. + + * CUlaunchConfig::gridDimZ is the depth of the grid in blocks. + + * CUlaunchConfig::blockDimX is the X dimension of each thread block. + + * CUlaunchConfig::blockDimX is the Y dimension of each thread block. + + * CUlaunchConfig::blockDimZ is the Z dimension of each thread block. + + * CUlaunchConfig::sharedMemBytes is the dynamic shared-memory size per thread block in bytes. + + * CUlaunchConfig::hStream is the handle to the stream to perform the launch in. The CUDA context associated with this stream must match that associated with function f. + + * CUlaunchConfig::attrs is an array of CUlaunchConfig::numAttrs continguous CUlaunchAttribute elements. The value of this pointer is not considered if CUlaunchConfig::numAttrs is zero. However, in that case, it is recommended to set the pointer to NULL. + + * CUlaunchConfig::numAttrs is the number of attributes populating the first CUlaunchConfig::numAttrs positions of the CUlaunchConfig::attrs array. + + +Launch-time configuration is specified by adding entries to CUlaunchConfig::attrs. Each entry is an attribute ID and a corresponding attribute value. + +The CUlaunchAttribute structure is defined as: + + + ‎ typedef struct CUlaunchAttribute_st { + CUlaunchAttributeID id; + CUlaunchAttributeValue value; + } CUlaunchAttribute; + +where: + + * CUlaunchAttribute::id is a unique enum identifying the attribute. + + * CUlaunchAttribute::value is a union that hold the attribute value. + + +An example of using the `config` parameter: + + + ‎ CUlaunchAttribute coopAttr = {.id = CU_LAUNCH_ATTRIBUTE_COOPERATIVE + .value = 1}; + CUlaunchConfig config = {... // set block and grid dimensions + .attrs = &coopAttr + .numAttrs = 1}; + + cuLaunchKernelEx(&config, kernel, NULL, NULL); + +The CUlaunchAttributeID enum is defined as: + + + ‎ typedef enum CUlaunchAttributeID_enum { + CU_LAUNCH_ATTRIBUTE_IGNORE = 0 + CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW = 1 + CU_LAUNCH_ATTRIBUTE_COOPERATIVE = 2 + CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY = 3 + CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION = 4 + CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE = 5 + CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION = 6 + CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT = 7 + CU_LAUNCH_ATTRIBUTE_PRIORITY = 8 + CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN_MAP = 9 + CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN = 10 + CU_LAUNCH_ATTRIBUTE_PREFERRED_CLUSTER_DIMENSION = 11 + CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT = 12 + CU_LAUNCH_ATTRIBUTE_DEVICE_UPDATABLE_KERNEL_NODE = 13 + } CUlaunchAttributeID; + +and the corresponding CUlaunchAttributeValue union as : + + + ‎ typedef union CUlaunchAttributeValue_union { + CUaccessPolicyWindow accessPolicyWindow; + int cooperative; + CUsynchronizationPolicy syncPolicy; + struct { + unsigned int x; + unsigned int y; + unsigned int z; + } clusterDim; + CUclusterSchedulingPolicy clusterSchedulingPolicyPreference; + int programmaticStreamSerializationAllowed; + struct { + CUevent event; + int flags; + int triggerAtBlockStart; + } programmaticEvent; + int priority; + CUlaunchMemSyncDomainMap memSyncDomainMap; + CUlaunchMemSyncDomain memSyncDomain; + struct { + unsigned int x; + unsigned int y; + unsigned int z; + } preferredClusterDim; + struct { + CUevent event; + int flags; + } launchCompletionEvent; + struct { + int deviceUpdatable; + CUgraphDeviceNode devNode; + } deviceUpdatableKernelNode; + } CUlaunchAttributeValue; + +Setting CU_LAUNCH_ATTRIBUTE_COOPERATIVE to a non-zero value causes the kernel launch to be a cooperative launch, with exactly the same usage and semantics of cuLaunchCooperativeKernel. + +Setting CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION to a non-zero values causes the kernel to use programmatic means to resolve its stream dependency -- enabling the CUDA runtime to opportunistically allow the grid's execution to overlap with the previous kernel in the stream, if that kernel requests the overlap. + +CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT records an event along with the kernel launch. Event recorded through this launch attribute is guaranteed to only trigger after all block in the associated kernel trigger the event. A block can trigger the event through PTX launchdep.release or CUDA builtin function cudaTriggerProgrammaticLaunchCompletion(). A trigger can also be inserted at the beginning of each block's execution if triggerAtBlockStart is set to non-0. Note that dependents (including the CPU thread calling cuEventSynchronize()) are not guaranteed to observe the release precisely when it is released. For example, cuEventSynchronize() may only observe the event trigger long after the associated kernel has completed. This recording type is primarily meant for establishing programmatic dependency between device tasks. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. created with CU_EVENT_DISABLE_TIMING flag set). + +CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT records an event along with the kernel launch. Nominally, the event is triggered once all blocks of the kernel have begun execution. Currently this is a best effort. If a kernel B has a launch completion dependency on a kernel A, B may wait until A is complete. Alternatively, blocks of B may begin before all blocks of A have begun, for example: + + * If B can claim execution resources unavailable to A, for example if they run on different GPUs. + + * If B is a higher priority than A. + + +Exercise caution if such an ordering inversion could lead to deadlock. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. must be created with the CU_EVENT_DISABLE_TIMING flag set). + +Setting CU_LAUNCH_ATTRIBUTE_DEVICE_UPDATABLE_KERNEL_NODE to 1 on a captured launch causes the resulting kernel node to be device-updatable. This attribute is specific to graphs, and passing it to a launch in a non-capturing stream results in an error. Passing a value other than 0 or 1 is not allowed. + +On success, a handle will be returned via CUlaunchAttributeValue::deviceUpdatableKernelNode::devNode which can be passed to the various device-side update functions to update the node's kernel parameters from within another kernel. For more information on the types of device updates that can be made, as well as the relevant limitations thereof, see cudaGraphKernelNodeUpdatesApply. + +Kernel nodes which are device-updatable have additional restrictions compared to regular kernel nodes. Firstly, device-updatable nodes cannot be removed from their graph via cuGraphDestroyNode. Additionally, once opted-in to this functionality, a node cannot opt out, and any attempt to set the attribute to 0 will result in an error. Graphs containing one or more device-updatable node also do not allow multiple instantiation. + +CU_LAUNCH_ATTRIBUTE_PREFERRED_CLUSTER_DIMENSION allows the kernel launch to specify a preferred substitute cluster dimension. Blocks may be grouped according to either the dimensions specified with this attribute (grouped into a "preferred substitute cluster"), or the one specified with CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION attribute (grouped into a "regular cluster"). The cluster dimensions of a "preferred substitute cluster" shall be an integer multiple greater than zero of the regular cluster dimensions. The device will attempt - on a best-effort basis - to group thread blocks into preferred clusters over grouping them into regular clusters. When it deems necessary (primarily when the device temporarily runs out of physical resources to launch the larger preferred clusters), the device may switch to launch the regular clusters instead to attempt to utilize as much of the physical device resources as possible. + +Each type of cluster will have its enumeration / coordinate setup as if the grid consists solely of its type of cluster. For example, if the preferred substitute cluster dimensions double the regular cluster dimensions, there might be simultaneously a regular cluster indexed at (1,0,0), and a preferred cluster indexed at (1,0,0). In this example, the preferred substitute cluster (1,0,0) replaces regular clusters (2,0,0) and (3,0,0) and groups their blocks. + +This attribute will only take effect when a regular cluster dimension has been specified. The preferred substitute The preferred substitute cluster dimension must be an integer multiple greater than zero of the regular cluster dimension and must divide the grid. It must also be no more than `maxBlocksPerCluster`, if it is set in the kernel's `__launch_bounds__`. Otherwise it must be less than the maximum value the driver can support. Otherwise, setting this attribute to a value physically unable to fit on any particular device is permitted. + +The effect of other attributes is consistent with their effect when set via persistent APIs. + +See cuStreamSetAttribute for + + * CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW + + * CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY + + +See cuFuncSetAttribute for + + * CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION + + * CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE + + +Kernel parameters to `f` can be specified in the same ways that they can be using cuLaunchKernel. + +Note that the API can also be used to launch context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to launch the kernel on will either be taken from the specified stream CUlaunchConfig::hStream or the current context in case of NULL stream. + + * This function uses standard default stream semantics. + + * \ No newline at end of file diff --git a/content/cuda/docs/driver-extres--interop/DOC.md b/content/cuda/docs/driver-extres--interop/DOC.md new file mode 100644 index 00000000..ff674336 --- /dev/null +++ b/content/cuda/docs/driver-extres--interop/DOC.md @@ -0,0 +1,349 @@ +--- +name: driver-extres--interop +description: '**Source:** group__CUDA__EXTRES__INTEROP.html#group__CUDA__EXTRES__INTEROP' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.20. External Resource Interoperability + +**Source:** group__CUDA__EXTRES__INTEROP.html#group__CUDA__EXTRES__INTEROP + + +### Functions + +CUresult cuDestroyExternalMemory ( CUexternalMemory extMem ) + + +Destroys an external memory object. + +###### Parameters + +`extMem` + \- External memory object to be destroyed + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Destroys the specified external memory object. Any existing buffers and CUDA mipmapped arrays mapped onto this object must no longer be used and must be explicitly freed using cuMemFree and cuMipmappedArrayDestroy respectively. + +CUresult cuDestroyExternalSemaphore ( CUexternalSemaphore extSem ) + + +Destroys an external semaphore. + +###### Parameters + +`extSem` + \- External semaphore to be destroyed + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Destroys an external semaphore object and releases any references to the underlying resource. Any outstanding signals or waits must have completed before the semaphore is destroyed. + +CUresult cuExternalMemoryGetMappedBuffer ( CUdeviceptr* devPtr, CUexternalMemory extMem, const CUDA_EXTERNAL_MEMORY_BUFFER_DESC* bufferDesc ) + + +Maps a buffer onto an imported memory object. + +###### Parameters + +`devPtr` + \- Returned device pointer to buffer +`extMem` + \- Handle to external memory object +`bufferDesc` + \- Buffer descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Maps a buffer onto an imported memory object and returns a device pointer in `devPtr`. + +The properties of the buffer being mapped must be described in `bufferDesc`. The CUDA_EXTERNAL_MEMORY_BUFFER_DESC structure is defined as follows: + + + ‎ typedef struct CUDA_EXTERNAL_MEMORY_BUFFER_DESC_st { + unsigned long long offset; + unsigned long long size; + unsigned int flags; + } CUDA_EXTERNAL_MEMORY_BUFFER_DESC; + +where CUDA_EXTERNAL_MEMORY_BUFFER_DESC::offset is the offset in the memory object where the buffer's base address is. CUDA_EXTERNAL_MEMORY_BUFFER_DESC::size is the size of the buffer. CUDA_EXTERNAL_MEMORY_BUFFER_DESC::flags must be zero. + +The offset and size have to be suitably aligned to match the requirements of the external API. Mapping two buffers whose ranges overlap may or may not result in the same virtual address being returned for the overlapped portion. In such cases, the application must ensure that all accesses to that region from the GPU are volatile. Otherwise writes made via one address are not guaranteed to be visible via the other address, even if they're issued by the same thread. It is recommended that applications map the combined range instead of mapping separate buffers and then apply the appropriate offsets to the returned pointer to derive the individual buffers. + +The returned pointer `devPtr` must be freed using cuMemFree. + +CUresult cuExternalMemoryGetMappedMipmappedArray ( CUmipmappedArray* mipmap, CUexternalMemory extMem, const CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC* mipmapDesc ) + + +Maps a CUDA mipmapped array onto an external memory object. + +###### Parameters + +`mipmap` + \- Returned CUDA mipmapped array +`extMem` + \- Handle to external memory object +`mipmapDesc` + \- CUDA array descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Maps a CUDA mipmapped array onto an external object and returns a handle to it in `mipmap`. + +The properties of the CUDA mipmapped array being mapped must be described in `mipmapDesc`. The structure CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC is defined as follows: + + + ‎ typedef struct CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_st { + unsigned long long offset; + CUDA_ARRAY3D_DESCRIPTOR arrayDesc; + unsigned int numLevels; + } CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC; + +where CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::offset is the offset in the memory object where the base level of the mipmap chain is. CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::arrayDesc describes the format, dimensions and type of the base level of the mipmap chain. For further details on these parameters, please refer to the documentation for cuMipmappedArrayCreate. Note that if the mipmapped array is bound as a color target in the graphics API, then the flag CUDA_ARRAY3D_COLOR_ATTACHMENT must be specified in CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::arrayDesc::Flags. CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::numLevels specifies the total number of levels in the mipmap chain. + +If `extMem` was imported from a handle of type CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, then CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::numLevels must be equal to 1. + +Mapping `extMem` imported from a handle of type CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD, is not supported. + +The returned CUDA mipmapped array must be freed using cuMipmappedArrayDestroy. + +CUresult cuImportExternalMemory ( CUexternalMemory* extMem_out, const CUDA_EXTERNAL_MEMORY_HANDLE_DESC* memHandleDesc ) + + +Imports an external memory object. + +###### Parameters + +`extMem_out` + \- Returned handle to an external memory object +`memHandleDesc` + \- Memory import handle descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Imports an externally allocated memory object and returns a handle to that in `extMem_out`. + +The properties of the handle being imported must be described in `memHandleDesc`. The CUDA_EXTERNAL_MEMORY_HANDLE_DESC structure is defined as follows: + + + ‎ typedef struct CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st { + CUexternalMemoryHandleType type; + union { + int fd; + struct { + void *handle; + const void *name; + } win32; + const void *nvSciBufObject; + } handle; + unsigned long long size; + unsigned int flags; + } CUDA_EXTERNAL_MEMORY_HANDLE_DESC; + +where CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type specifies the type of handle being imported. CUexternalMemoryHandleType is defined as: + + + ‎ typedef enum CUexternalMemoryHandleType_enum { + CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD = 1 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 = 2 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP = 4 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE = 5 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE = 6 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT = 7 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF = 8 + CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD = 9 + } CUexternalMemoryHandleType; + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::fd must be a valid file descriptor referencing a memory object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32, then exactly one of CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a memory object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a memory object. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must be non-NULL and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must be NULL. The handle specified must be a globally shared KMT handle. This handle does not hold a reference to the underlying object, and thus will be invalid when all references to the memory object are destroyed. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP, then exactly one of CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Heap object. This handle holds a reference to the underlying object. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D12Heap object. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE, then exactly one of CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Resource object. This handle holds a reference to the underlying object. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D12Resource object. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must represent a valid shared NT handle that is returned by IDXGIResource1::CreateSharedHandle when referring to a ID3D11Resource object. If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D11Resource object. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must represent a valid shared KMT handle that is returned by IDXGIResource::GetSharedHandle when referring to a ID3D11Resource object and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must be NULL. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::nvSciBufObject must be non-NULL and reference a valid NvSciBuf object. If the NvSciBuf object imported into CUDA is also mapped by other drivers, then the application must use cuWaitExternalSemaphoresAsync or cuSignalExternalSemaphoresAsync as appropriate barriers to maintain coherence between CUDA and the other drivers. See CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC and CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC for memory synchronization. + +If CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD, then CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::fd must be a valid file descriptor referencing a dma_buf object and CUDA_EXTERNAL_MEMORY_HANDLE_DESC::flags must be zero. Importing a dma_buf object is supported only on Tegra Jetson platform starting with Thor series. Mapping an imported dma_buf object as CUDA mipmapped array using cuExternalMemoryGetMappedMipmappedArray is not supported. + +The size of the memory object must be specified in CUDA_EXTERNAL_MEMORY_HANDLE_DESC::size. + +Specifying the flag CUDA_EXTERNAL_MEMORY_DEDICATED in CUDA_EXTERNAL_MEMORY_HANDLE_DESC::flags indicates that the resource is a dedicated resource. The definition of what a dedicated resource is outside the scope of this extension. This flag must be set if CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is one of the following: CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCECU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCECU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT + + * * If the Vulkan memory imported into CUDA is mapped on the CPU then the application must use vkInvalidateMappedMemoryRanges/vkFlushMappedMemoryRanges as well as appropriate Vulkan pipeline barriers to maintain coherence between CPU and GPU. For more information on these APIs, please refer to "Synchronization and Cache Control" chapter from Vulkan specification. + + +CUresult cuImportExternalSemaphore ( CUexternalSemaphore* extSem_out, const CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC* semHandleDesc ) + + +Imports an external semaphore. + +###### Parameters + +`extSem_out` + \- Returned handle to an external semaphore +`semHandleDesc` + \- Semaphore import handle descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Imports an externally allocated synchronization object and returns a handle to that in `extSem_out`. + +The properties of the handle being imported must be described in `semHandleDesc`. The CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC is defined as follows: + + + ‎ typedef struct CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_st { + CUexternalSemaphoreHandleType type; + union { + int fd; + struct { + void *handle; + const void *name; + } win32; + const void* NvSciSyncObj; + } handle; + unsigned int flags; + } CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC; + +where CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type specifies the type of handle being imported. CUexternalSemaphoreHandleType is defined as: + + + ‎ typedef enum CUexternalSemaphoreHandleType_enum { + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD = 1 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32 = 2 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE = 4 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE = 5 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC = 6 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX = 7 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT = 8 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD = 9 + CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 = 10 + } CUexternalSemaphoreHandleType; + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::fd must be a valid file descriptor referencing a synchronization object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, then exactly one of CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a synchronization object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name is not NULL, then it must name a valid synchronization object. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle must be non-NULL and CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must be NULL. The handle specified must be a globally shared KMT handle. This handle does not hold a reference to the underlying object, and thus will be invalid when all references to the synchronization object are destroyed. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, then exactly one of CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Fence object. This handle holds a reference to the underlying object. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D12Fence object. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle represents a valid shared NT handle that is returned by ID3D11Fence::CreateSharedHandle. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D11Fence object. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::nvSciSyncObj represents a valid NvSciSyncObj. + +CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle represents a valid shared NT handle that is returned by IDXGIResource1::CreateSharedHandle when referring to a IDXGIKeyedMutex object. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name is not NULL, then it must name a valid synchronization object that refers to a valid IDXGIKeyedMutex object. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle represents a valid shared KMT handle that is returned by IDXGIResource::GetSharedHandle when referring to a IDXGIKeyedMutex object and CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must be NULL. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, then CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::fd must be a valid file descriptor referencing a synchronization object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior. + +If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32, then exactly one of CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be NULL. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a synchronization object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. If CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name is not NULL, then it must name a valid synchronization object. + +CUresult cuSignalExternalSemaphoresAsync ( const CUexternalSemaphore* extSemArray, const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS* paramsArray, unsigned int numExtSems, CUstream stream ) + + +Signals a set of external semaphore objects. + +###### Parameters + +`extSemArray` + \- Set of external semaphores to be signaled +`paramsArray` + \- Array of semaphore parameters +`numExtSems` + \- Number of semaphores to signal +`stream` + \- Stream to enqueue the signal operations in + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Enqueues a signal operation on a set of externally allocated semaphore object in the specified stream. The operations will be executed when all prior operations in the stream complete. + +The exact semantics of signaling a semaphore depends on the type of the object. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT then signaling the semaphore will set it to the signaled state. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 then the semaphore will be set to the value specified in CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::fence::value. + +If the semaphore object is of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC this API sets CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence to a value that can be used by subsequent waiters of the same NvSciSync object to order operations with those currently submitted in `stream`. Such an update will overwrite previous contents of CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence. By default, signaling such an external semaphore object causes appropriate memory synchronization operations to be performed over all external memory objects that are imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. This ensures that any subsequent accesses made by other importers of the same set of NvSciBuf memory object(s) are coherent. These operations can be skipped by specifying the flag CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC, which can be used as a performance optimization when data coherency is not required. But specifying this flag in scenarios where data coherency is required results in undefined behavior. Also, for semaphore object of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in cuDeviceGetNvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_SIGNAL, this API will return CUDA_ERROR_NOT_SUPPORTED. NvSciSyncFence associated with semaphore object of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC can be deterministic. For this the NvSciSyncAttrList used to create the semaphore object must have value of NvSciSyncAttrKey_RequireDeterministicFences key set to true. Deterministic fences allow users to enqueue a wait over the semaphore object even before corresponding signal is enqueued. For such a semaphore object, CUDA guarantees that each signal operation will increment the fence value by '1'. Users are expected to track count of signals enqueued on the semaphore object and insert waits accordingly. When such a semaphore object is signaled from multiple streams, due to concurrent stream execution, it is possible that the order in which the semaphore gets signaled is indeterministic. This could lead to waiters of the semaphore getting unblocked incorrectly. Users are expected to handle such situations, either by not using the same semaphore object with deterministic fence support enabled in different streams or by adding explicit dependency amongst such streams so that the semaphore is signaled in order. NvSciSyncFence associated with semaphore object of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC can be timestamp enabled. For this the NvSciSyncAttrList used to create the object must have the value of NvSciSyncAttrKey_WaiterRequireTimestamps key set to true. Timestamps are emitted asynchronously by the GPU and CUDA saves the GPU timestamp in the corresponding NvSciSyncFence at the time of signal on GPU. Users are expected to convert GPU clocks to CPU clocks using appropriate scaling functions. Users are expected to wait for the completion of the fence before extracting timestamp using appropriate NvSciSync APIs. Users are expected to ensure that there is only one outstanding timestamp enabled fence per Cuda-NvSciSync object at any point of time, failing which leads to undefined behavior. Extracting the timestamp before the corresponding fence is signalled could lead to undefined behaviour. Timestamp extracted via appropriate NvSciSync API would be in microseconds. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT then the keyed mutex will be released with the key specified in CUDA_EXTERNAL_SEMAPHORE_PARAMS::params::keyedmutex::key. + +CUresult cuWaitExternalSemaphoresAsync ( const CUexternalSemaphore* extSemArray, const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS* paramsArray, unsigned int numExtSems, CUstream stream ) + + +Waits on a set of external semaphore objects. + +###### Parameters + +`extSemArray` + \- External semaphores to be waited on +`paramsArray` + \- Array of semaphore parameters +`numExtSems` + \- Number of semaphores to wait on +`stream` + \- Stream to enqueue the wait operations in + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_TIMEOUT + +###### Description + +Enqueues a wait operation on a set of externally allocated semaphore object in the specified stream. The operations will be executed when all prior operations in the stream complete. + +The exact semantics of waiting on a semaphore depends on the type of the object. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT then waiting on the semaphore will wait until the semaphore reaches the signaled state. The semaphore will then be reset to the unsignaled state. Therefore for every signal operation, there can only be one wait operation. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 then waiting on the semaphore will wait until the value of the semaphore is greater than or equal to CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::fence::value. + +If the semaphore object is of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC then, waiting on the semaphore will wait until the CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence is signaled by the signaler of the NvSciSyncObj that was associated with this semaphore object. By default, waiting on such an external semaphore object causes appropriate memory synchronization operations to be performed over all external memory objects that are imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. This ensures that any subsequent accesses made by other importers of the same set of NvSciBuf memory object(s) are coherent. These operations can be skipped by specifying the flag CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC, which can be used as a performance optimization when data coherency is not required. But specifying this flag in scenarios where data coherency is required results in undefined behavior. Also, for semaphore object of the type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in cuDeviceGetNvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_WAIT, this API will return CUDA_ERROR_NOT_SUPPORTED. + +If the semaphore object is any one of the following types: CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT then the keyed mutex will be acquired when it is released with the key specified in CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::keyedmutex::key or until the timeout specified by CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::keyedmutex::timeoutMs has lapsed. The timeout interval can either be a finite value specified in milliseconds or an infinite value. In case an infinite value is specified the timeout never elapses. The windows INFINITE macro must be used to specify infinite timeout. + + diff --git a/content/cuda/docs/driver-gl--deprecated/DOC.md b/content/cuda/docs/driver-gl--deprecated/DOC.md new file mode 100644 index 00000000..f3ddbc70 --- /dev/null +++ b/content/cuda/docs/driver-gl--deprecated/DOC.md @@ -0,0 +1,267 @@ +--- +name: driver-gl--deprecated +description: '**Source:** group__CUDA__GL__DEPRECATED.html#group__CUDA__GL__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.40.1. OpenGL Interoperability [DEPRECATED] + +**Source:** group__CUDA__GL__DEPRECATED.html#group__CUDA__GL__DEPRECATED + + +### Enumerations + +enum CUGLmap_flags + + +### Functions + +CUresult cuGLCtxCreate ( CUcontext* pCtx, unsigned int Flags, CUdevice device ) + + +Create a CUDA context for interoperability with OpenGL. + +###### Parameters + +`pCtx` + \- Returned CUDA context +`Flags` + \- Options for CUDA context creation +`device` + \- Device on which to create the context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Deprecated + +This function is deprecated as of Cuda 5.0. + +###### Description + +This function is deprecated and should no longer be used. It is no longer necessary to associate a CUDA context with an OpenGL context in order to achieve maximum interoperability performance. + +CUresult cuGLInit ( void ) + + +Initializes OpenGL interoperability. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_UNKNOWN + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Initializes OpenGL interoperability. This function is deprecated and calling it is no longer required. It may fail if the needed OpenGL driver facilities are not available. + +CUresult cuGLMapBufferObject ( CUdeviceptr* dptr, size_t* size, GLuint buffer ) + + +Maps an OpenGL buffer object. + +###### Parameters + +`dptr` + \- Returned mapped base pointer +`size` + \- Returned size of mapping +`buffer` + \- The name of the buffer object to map + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_MAP_FAILED + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Maps the buffer object specified by `buffer` into the address space of the current CUDA context and returns in `*dptr` and `*size` the base pointer and size of the resulting mapping. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + +All streams in the current CUDA context are synchronized with the current GL context. + +CUresult cuGLMapBufferObjectAsync ( CUdeviceptr* dptr, size_t* size, GLuint buffer, CUstream hStream ) + + +Maps an OpenGL buffer object. + +###### Parameters + +`dptr` + \- Returned mapped base pointer +`size` + \- Returned size of mapping +`buffer` + \- The name of the buffer object to map +`hStream` + \- Stream to synchronize + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_MAP_FAILED + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Maps the buffer object specified by `buffer` into the address space of the current CUDA context and returns in `*dptr` and `*size` the base pointer and size of the resulting mapping. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + +Stream `hStream` in the current CUDA context is synchronized with the current GL context. + +CUresult cuGLRegisterBufferObject ( GLuint buffer ) + + +Registers an OpenGL buffer object. + +###### Parameters + +`buffer` + \- The name of the buffer object to register. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_ALREADY_MAPPED + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Registers the buffer object specified by `buffer` for access by CUDA. This function must be called before CUDA can map the buffer object. There must be a valid OpenGL context bound to the current thread when this function is called, and the buffer name is resolved by that context. + +CUresult cuGLSetBufferObjectMapFlags ( GLuint buffer, unsigned int Flags ) + + +Set the map flags for an OpenGL buffer object. + +###### Parameters + +`buffer` + \- Buffer object to unmap +`Flags` + \- Map flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Sets the map flags for the buffer object specified by `buffer`. + +Changes to `Flags` will take effect the next time `buffer` is mapped. The `Flags` argument may be any of the following: + + * CU_GL_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA kernels. This is the default value. + + * CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY: Specifies that CUDA kernels which access this resource will not write to this resource. + + * CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD: Specifies that CUDA kernels which access this resource will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +If `buffer` has not been registered for use with CUDA, then CUDA_ERROR_INVALID_HANDLE is returned. If `buffer` is presently mapped for access by CUDA, then CUDA_ERROR_ALREADY_MAPPED is returned. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + +CUresult cuGLUnmapBufferObject ( GLuint buffer ) + + +Unmaps an OpenGL buffer object. + +###### Parameters + +`buffer` + \- Buffer object to unmap + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Unmaps the buffer object specified by `buffer` for access by CUDA. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + +All streams in the current CUDA context are synchronized with the current GL context. + +CUresult cuGLUnmapBufferObjectAsync ( GLuint buffer, CUstream hStream ) + + +Unmaps an OpenGL buffer object. + +###### Parameters + +`buffer` + \- Name of the buffer object to unmap +`hStream` + \- Stream to synchronize + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Unmaps the buffer object specified by `buffer` for access by CUDA. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + +Stream `hStream` in the current CUDA context is synchronized with the current GL context. + +CUresult cuGLUnregisterBufferObject ( GLuint buffer ) + + +Unregister an OpenGL buffer object. + +###### Parameters + +`buffer` + \- Name of the buffer object to unregister + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +This function is deprecated as of Cuda 3.0. + +###### Description + +Unregisters the buffer object specified by `buffer`. This releases any resources associated with the registered buffer. After this call, the buffer may no longer be mapped for access by CUDA. + +There must be a valid OpenGL context bound to the current thread when this function is called. This must be the same context, or a member of the same shareGroup, as the context that was bound when the buffer was registered. + + diff --git a/content/cuda/docs/driver-gl/DOC.md b/content/cuda/docs/driver-gl/DOC.md new file mode 100644 index 00000000..7a05bd9a --- /dev/null +++ b/content/cuda/docs/driver-gl/DOC.md @@ -0,0 +1,169 @@ +--- +name: driver-gl +description: '**Source:** group__CUDA__GL.html#group__CUDA__GL' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.40. OpenGL Interoperability + +**Source:** group__CUDA__GL.html#group__CUDA__GL + + +### Modules + +[OpenGL Interoperability [DEPRECATED]](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GL__DEPRECATED.html#group__CUDA__GL__DEPRECATED) + + + +### Enumerations + +enum CUGLDeviceList + + +### Functions + +CUresult cuGLGetDevices ( unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList ) + + +Gets the CUDA devices associated with the current OpenGL context. + +###### Parameters + +`pCudaDeviceCount` + \- Returned number of CUDA devices. +`pCudaDevices` + \- Returned CUDA devices. +`cudaDeviceCount` + \- The size of the output device array pCudaDevices. +`deviceList` + \- The set of devices to return. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_GRAPHICS_CONTEXT, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Returns in `*pCudaDeviceCount` the number of CUDA-compatible devices corresponding to the current OpenGL context. Also returns in `*pCudaDevices` at most cudaDeviceCount of the CUDA-compatible devices corresponding to the current OpenGL context. If any of the GPUs being used by the current OpenGL context are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. + +The `deviceList` argument may be any of the following: + + * CU_GL_DEVICE_LIST_ALL: Query all devices used by the current OpenGL context. + + * CU_GL_DEVICE_LIST_CURRENT_FRAME: Query the devices used by the current OpenGL context to render the current frame (in SLI). + + * CU_GL_DEVICE_LIST_NEXT_FRAME: Query the devices used by the current OpenGL context to render the next frame (in SLI). Note that this is a prediction, it can't be guaranteed that this is correct in all cases. + + +CUresult cuGraphicsGLRegisterBuffer ( CUgraphicsResource* pCudaResource, GLuint buffer, unsigned int Flags ) + + +Registers an OpenGL buffer object. + +###### Parameters + +`pCudaResource` + \- Pointer to the returned object handle +`buffer` + \- name of buffer object to be registered +`Flags` + \- Register flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Registers the buffer object specified by `buffer` for access by CUDA. A handle to the registered object is returned as `pCudaResource`. The register flags `Flags` specify the intended usage, as follows: + + * CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value. + + * CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY: Specifies that CUDA will not write to this resource. + + * CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +CUresult cuGraphicsGLRegisterImage ( CUgraphicsResource* pCudaResource, GLuint image, GLenum target, unsigned int Flags ) + + +Register an OpenGL texture or renderbuffer object. + +###### Parameters + +`pCudaResource` + \- Pointer to the returned object handle +`image` + \- name of texture or renderbuffer object to be registered +`target` + \- Identifies the type of object specified by `image` +`Flags` + \- Register flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Registers the texture or renderbuffer object specified by `image` for access by CUDA. A handle to the registered object is returned as `pCudaResource`. + +`target` must match the type of the object, and must be one of GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_3D, GL_TEXTURE_2D_ARRAY, or GL_RENDERBUFFER. + +The register flags `Flags` specify the intended usage, as follows: + + * CU_GRAPHICS_REGISTER_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value. + + * CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY: Specifies that CUDA will not write to this resource. + + * CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + * CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST: Specifies that CUDA will bind this resource to a surface reference. + + * CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER: Specifies that CUDA will perform texture gather operations on this resource. + + +The following image formats are supported. For brevity's sake, the list is abbreviated. For ex., {GL_R, GL_RG} X {8, 16} would expand to the following 4 formats {GL_R8, GL_R16, GL_RG8, GL_RG16} : + + * GL_RED, GL_RG, GL_RGBA, GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY + + * {GL_R, GL_RG, GL_RGBA} X {8, 16, 16F, 32F, 8UI, 16UI, 32UI, 8I, 16I, 32I} + + * {GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY} X {8, 16, 16F_ARB, 32F_ARB, 8UI_EXT, 16UI_EXT, 32UI_EXT, 8I_EXT, 16I_EXT, 32I_EXT} + + +The following image classes are currently disallowed: + + * Textures with borders + + * Multisampled renderbuffers + + +CUresult cuWGLGetDevice ( CUdevice* pDevice, HGPUNV hGpu ) + + +Gets the CUDA device associated with hGpu. + +###### Parameters + +`pDevice` + \- Device associated with hGpu +`hGpu` + \- Handle to a GPU, as queried via WGL_NV_gpu_affinity() + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*pDevice` the CUDA device associated with a `hGpu`, if applicable. + +### OpenGL Interoperability [DEPRECATED] + diff --git a/content/cuda/docs/driver-graph/DOC.md b/content/cuda/docs/driver-graph/DOC.md new file mode 100644 index 00000000..2500e0bb --- /dev/null +++ b/content/cuda/docs/driver-graph/DOC.md @@ -0,0 +1,2598 @@ +--- +name: driver-graph +description: '**Source:** group__CUDA__GRAPH.html#group__CUDA__GRAPH' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.24. Graph Management + +**Source:** group__CUDA__GRAPH.html#group__CUDA__GRAPH + + +### Functions + +CUresult cuDeviceGetGraphMemAttribute ( CUdevice device, CUgraphMem_attribute attr, void* value ) + + +Query asynchronous allocation attributes related to graphs. + +###### Parameters + +`device` + \- Specifies the scope of the query +`attr` + \- attribute to get +`value` + \- retrieved value + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Valid attributes are: + + * CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT: Amount of memory, in bytes, currently associated with graphs + + * CU_GRAPH_MEM_ATTR_USED_MEM_HIGH: High watermark of memory, in bytes, associated with graphs since the last time it was reset. High watermark can only be reset to zero. + + * CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT: Amount of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator. + + * CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH: High watermark of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator. + + +CUresult cuDeviceGraphMemTrim ( CUdevice device ) + + +Free unused memory that was cached on the specified device for use with graphs back to the OS. + +###### Parameters + +`device` + \- The device for which cached memory should be freed. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Blocks which are not in use by a graph that is either currently executing or scheduled to execute are freed back to the operating system. + +CUresult cuDeviceSetGraphMemAttribute ( CUdevice device, CUgraphMem_attribute attr, void* value ) + + +Set asynchronous allocation attributes related to graphs. + +###### Parameters + +`device` + \- Specifies the scope of the query +`attr` + \- attribute to get +`value` + \- pointer to value to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Valid attributes are: + + * CU_GRAPH_MEM_ATTR_USED_MEM_HIGH: High watermark of memory, in bytes, associated with graphs since the last time it was reset. High watermark can only be reset to zero. + + * CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH: High watermark of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator. + + +CUresult cuGraphAddBatchMemOpNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_BATCH_MEM_OP_NODE_PARAMS* nodeParams ) + + +Creates a batch memory operation node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new batch memory operation node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +When the node is added, the paramArray inside `nodeParams` is copied and therefore it can be freed after the call returns. + +Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddChildGraphNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, CUgraph childGraph ) + + +Creates a child graph node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`childGraph` + \- The graph to clone into this node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new node which executes an embedded graph, and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +If `childGraph` contains allocation nodes, free nodes, or conditional nodes, this call will return an error. + +The node executes an embedded child graph. The child graph is cloned in this call. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddDependencies ( CUgraph hGraph, const CUgraphNode* from, const CUgraphNode* to, const CUgraphEdgeData* edgeData, size_t numDependencies ) + + +Adds dependency edges to a graph. + +###### Parameters + +`hGraph` + \- Graph to which dependencies are added +`from` + \- Array of nodes that provide the dependencies +`to` + \- Array of dependent nodes +`edgeData` + \- Optional array of edge data. If NULL, default (zeroed) edge data is assumed. +`numDependencies` + \- Number of dependencies to be added + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +The number of dependencies to be added is defined by `numDependencies` Elements in `from` and `to` at corresponding indices define a dependency. Each node in `from` and `to` must belong to `hGraph`. + +If `numDependencies` is 0, elements in `from` and `to` will be ignored. Specifying an existing dependency will return an error. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddEmptyNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies ) + + +Creates an empty node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new node which performs no operation, and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +An empty node performs no operation during execution, but can be used for transitive ordering. For example, a phased execution graph with 2 groups of n nodes with a barrier between them can be represented using an empty node and 2*n dependency edges, rather than no empty node and n^2 dependency edges. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddEventRecordNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, CUevent event ) + + +Creates an event record node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`event` + \- Event for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new event record node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and event specified in `event`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +Each launch of the graph will record `event` to capture execution of the node's dependencies. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddEventWaitNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, CUevent event ) + + +Creates an event wait node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`event` + \- Event for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new event wait node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and event specified in `event`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +The graph node will wait for all work captured in `event`. See cuEventRecord() for details on what is captured by an event. `event` may be from a different context or device than the launch stream. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddExternalSemaphoresSignalNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS* nodeParams ) + + +Creates an external semaphore signal node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new external semaphore signal node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +Performs a signal operation on a set of externally allocated semaphore objects when the node is launched. The operation(s) will occur after all of the node's dependencies have completed. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddExternalSemaphoresWaitNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_EXT_SEM_WAIT_NODE_PARAMS* nodeParams ) + + +Creates an external semaphore wait node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new external semaphore wait node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +Performs a wait operation on a set of externally allocated semaphore objects when the node is launched. The node's dependencies will not be launched until the wait operation has completed. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddHostNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_HOST_NODE_PARAMS* nodeParams ) + + +Creates a host execution node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the host node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new CPU execution node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +When the graph is launched, the node will invoke the specified CPU function. Host nodes are not supported under MPS with pre-Volta GPUs. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddKernelNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_KERNEL_NODE_PARAMS* nodeParams ) + + +Creates a kernel execution node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the GPU execution node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new kernel execution node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +The CUDA_KERNEL_NODE_PARAMS structure is defined as: + + + ‎ typedef struct CUDA_KERNEL_NODE_PARAMS_st { + CUfunction func; + unsigned int gridDimX; + unsigned int gridDimY; + unsigned int gridDimZ; + unsigned int blockDimX; + unsigned int blockDimY; + unsigned int blockDimZ; + unsigned int sharedMemBytes; + void **kernelParams; + void **extra; + CUkernel kern; + CUcontext ctx; + } CUDA_KERNEL_NODE_PARAMS; + +When the graph is launched, the node will invoke kernel `func` on a (`gridDimX` x `gridDimY` x `gridDimZ`) grid of blocks. Each block contains (`blockDimX` x `blockDimY` x `blockDimZ`) threads. + +`sharedMemBytes` sets the amount of dynamic shared memory that will be available to each thread block. + +Kernel parameters to `func` can be specified in one of two ways: + +1) Kernel parameters can be specified via `kernelParams`. If the kernel has N parameters, then `kernelParams` needs to be an array of N pointers. Each pointer, from `kernelParams`[0] to `kernelParams`[N-1], points to the region of memory from which the actual parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel's image. + +2) Kernel parameters for non-cooperative kernels can also be packaged by the application into a single buffer that is passed in via `extra`. This places the burden on the application of knowing each kernel parameter's size and alignment/padding within the buffer. The `extra` parameter exists to allow this function to take additional less commonly used arguments. `extra` specifies a list of names of extra settings and their corresponding values. Each extra setting name is immediately followed by the corresponding value. The list must be terminated with either NULL or CU_LAUNCH_PARAM_END. + + * CU_LAUNCH_PARAM_END, which indicates the end of the `extra` array; + + * CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next value in `extra` will be a pointer to a buffer containing all the kernel parameters for launching kernel `func`; + + * CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next value in `extra` will be a pointer to a size_t containing the size of the buffer specified with CU_LAUNCH_PARAM_BUFFER_POINTER; + + +The error CUDA_ERROR_INVALID_VALUE will be returned if kernel parameters are specified with both `kernelParams` and `extra` (i.e. both `kernelParams` and `extra` are non-NULL). CUDA_ERROR_INVALID_VALUE will be returned if `extra` is used for a cooperative kernel. + +The `kernelParams` or `extra` array, as well as the argument values it points to, are copied during this call. + +Kernels launched using graphs must not use texture and surface references. Reading or writing through any texture or surface reference is undefined behavior. This restriction does not apply to texture and surface objects. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddMemAllocNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, CUDA_MEM_ALLOC_NODE_PARAMS* nodeParams ) + + +Creates an allocation node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Parameters for the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new allocation node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +When cuGraphAddMemAllocNode creates an allocation node, it returns the address of the allocation in `nodeParams.dptr`. The allocation's address remains fixed across instantiations and launches. + +If the allocation is freed in the same graph, by creating a free node using cuGraphAddMemFreeNode, the allocation can be accessed by nodes ordered after the allocation node but before the free node. These allocations cannot be freed outside the owning graph, and they can only be freed once in the owning graph. + +If the allocation is not freed in the same graph, then it can be accessed not only by nodes in the graph which are ordered after the allocation node, but also by stream operations ordered after the graph's execution but before the allocation is freed. + +Allocations which are not freed in the same graph can be freed by: + + * passing the allocation to cuMemFreeAsync or cuMemFree; + + * launching a graph with a free node for that allocation; or + + * specifying CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH during instantiation, which makes each launch behave as though it called cuMemFreeAsync for every unfreed allocation. + + +It is not possible to free an allocation in both the owning graph and another graph. If the allocation is freed in the same graph, a free node cannot be added to another graph. If the allocation is freed in another graph, a free node can no longer be added to the owning graph. + +The following restrictions apply to graphs which contain allocation and/or memory free nodes: + + * Nodes and edges of the graph cannot be deleted. + + * The graph can only be used in a child node if the ownership is moved to the parent. + + * Only one instantiation of the graph may exist at any point in time. + + * The graph cannot be cloned. + + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddMemFreeNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, CUdeviceptr dptr ) + + +Creates a memory free node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`dptr` + \- Address of memory to free + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new memory free node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies` and arguments specified in `nodeParams`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +cuGraphAddMemFreeNode will return CUDA_ERROR_INVALID_VALUE if the user attempts to free: + + * an allocation twice in the same graph. + + * an address that was not returned by an allocation node. + + * an invalid address. + + +The following restrictions apply to graphs which contain allocation and/or memory free nodes: + + * Nodes and edges of the graph cannot be deleted. + + * The graph can only be used in a child node if the ownership is moved to the parent. + + * Only one instantiation of the graph may exist at any point in time. + + * The graph cannot be cloned. + + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddMemcpyNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_MEMCPY3D* copyParams, CUcontext ctx ) + + +Creates a memcpy node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`copyParams` + \- Parameters for the memory copy +`ctx` + \- Context on which to run the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a new memcpy node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +When the graph is launched, the node will perform the memcpy described by `copyParams`. See cuMemcpy3D() for a description of the structure and its restrictions. + +Memcpy nodes have some additional restrictions with regards to managed memory, if the system contains at least one device which has a zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. If one or more of the operands refer to managed memory, then using the memory type CU_MEMORYTYPE_UNIFIED is disallowed for those operand(s). The managed memory will be treated as residing on either the host or the device, depending on which memory type is specified. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddMemsetNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, size_t numDependencies, const CUDA_MEMSET_NODE_PARAMS* memsetParams, CUcontext ctx ) + + +Creates a memset node and adds it to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`numDependencies` + \- Number of dependencies +`memsetParams` + \- Parameters for the memory set +`ctx` + \- Context on which to run the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Creates a new memset node and adds it to `hGraph` with `numDependencies` dependencies specified via `dependencies`. It is possible for `numDependencies` to be 0, in which case the node will be placed at the root of the graph. `dependencies` may not have any duplicate entries. A handle to the new node will be returned in `phGraphNode`. + +The element size must be 1, 2, or 4 bytes. When the graph is launched, the node will perform the memset described by `memsetParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphAddNode ( CUgraphNode* phGraphNode, CUgraph hGraph, const CUgraphNode* dependencies, const CUgraphEdgeData* dependencyData, size_t numDependencies, CUgraphNodeParams* nodeParams ) + + +Adds a node of arbitrary type to a graph. + +###### Parameters + +`phGraphNode` + \- Returns newly created node +`hGraph` + \- Graph to which to add the node +`dependencies` + \- Dependencies of the node +`dependencyData` + \- Optional edge data for the dependencies. If NULL, the data is assumed to be default (zeroed) for all dependencies. +`numDependencies` + \- Number of dependencies +`nodeParams` + \- Specification of the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Creates a new node in `hGraph` described by `nodeParams` with `numDependencies` dependencies specified via `dependencies`. `numDependencies` may be 0. `dependencies` may be null if `numDependencies` is 0. `dependencies` may not have any duplicate entries. + +`nodeParams` is a tagged union. The node type should be specified in the `type` field, and type-specific parameters in the corresponding union member. All unused bytes - that is, `reserved0` and all bytes past the utilized union member - must be set to zero. It is recommended to use brace initialization or memset to ensure all bytes are initialized. + +Note that for some node types, `nodeParams` may contain "out parameters" which are modified during the call, such as `nodeParams->alloc.dptr`. + +A handle to the new node will be returned in `phGraphNode`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphBatchMemOpNodeGetParams ( CUgraphNode hNode, CUDA_BATCH_MEM_OP_NODE_PARAMS* nodeParams_out ) + + +Returns a batch mem op node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`nodeParams_out` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of batch mem op node `hNode` in `nodeParams_out`. The `paramArray` returned in `nodeParams_out` is owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use cuGraphBatchMemOpNodeSetParams to update the parameters of this node. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphBatchMemOpNodeSetParams ( CUgraphNode hNode, const CUDA_BATCH_MEM_OP_NODE_PARAMS* nodeParams ) + + +Sets a batch mem op node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the parameters of batch mem op node `hNode` to `nodeParams`. + +The paramArray inside `nodeParams` is copied and therefore it can be freed after the call returns. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphChildGraphNodeGetGraph ( CUgraphNode hNode, CUgraph* phGraph ) + + +Gets a handle to the embedded graph of a child graph node. + +###### Parameters + +`hNode` + \- Node to get the embedded graph for +`phGraph` + \- Location to store a handle to the graph + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Gets a handle to the embedded graph in a child graph node. This call does not clone the graph. Changes to the graph will be reflected in the node, and the node retains ownership of the graph. + +Allocation and free nodes cannot be added to the returned graph. Attempting to do so will return an error. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphClone ( CUgraph* phGraphClone, CUgraph originalGraph ) + + +Clones a graph. + +###### Parameters + +`phGraphClone` + \- Returns newly created cloned graph +`originalGraph` + \- Graph to clone + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +This function creates a copy of `originalGraph` and returns it in `phGraphClone`. All parameters are copied into the cloned graph. The original graph may be modified after this call without affecting the clone. + +Child graph nodes in the original graph are recursively copied into the clone. + +: Cloning is not supported for graphs which contain memory allocation nodes, memory free nodes, or conditional nodes. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphConditionalHandleCreate ( CUgraphConditionalHandle* pHandle_out, CUgraph hGraph, CUcontext ctx, unsigned int defaultLaunchValue, unsigned int flags ) + + +Create a conditional handle. + +###### Parameters + +`pHandle_out` + \- Pointer used to return the handle to the caller. +`hGraph` + \- Graph which will contain the conditional node using this handle. +`ctx` + \- Context for the handle and associated conditional node. +`defaultLaunchValue` + \- Optional initial value for the conditional variable. Applied at the beginning of each graph execution if CU_GRAPH_COND_ASSIGN_DEFAULT is set in `flags`. +`flags` + \- Currently must be CU_GRAPH_COND_ASSIGN_DEFAULT or 0. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Creates a conditional handle associated with `hGraph`. + +The conditional handle must be associated with a conditional node in this graph or one of its children. + +Handles not associated with a conditional node may cause graph instantiation to fail. + +Handles can only be set from the context with which they are associated. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphCreate ( CUgraph* phGraph, unsigned int flags ) + + +Creates a graph. + +###### Parameters + +`phGraph` + \- Returns newly created graph +`flags` + \- Graph creation flags, must be 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates an empty graph, which is returned via `phGraph`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphDebugDotPrint ( CUgraph hGraph, const char* path, unsigned int flags ) + + +Write a DOT file describing graph structure. + +###### Parameters + +`hGraph` + \- The graph to create a DOT file from +`path` + \- The path to write the DOT file to +`flags` + \- Flags from CUgraphDebugDot_flags for specifying which additional node information to write + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OPERATING_SYSTEM + +###### Description + +Using the provided `hGraph`, write to `path` a DOT formatted description of the graph. By default this includes the graph topology, node types, node id, kernel names and memcpy direction. `flags` can be specified to write more detailed information about each node type such as parameter values, kernel attributes, node and function handles. + +CUresult cuGraphDestroy ( CUgraph hGraph ) + + +Destroys a graph. + +###### Parameters + +`hGraph` + \- Graph to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Destroys the graph specified by `hGraph`, as well as all of its nodes. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphDestroyNode ( CUgraphNode hNode ) + + +Remove a node from the graph. + +###### Parameters + +`hNode` + \- Node to remove + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Removes `hNode` from its graph. This operation also severs any dependencies of other nodes on `hNode` and vice versa. + +Nodes which belong to a graph which contains allocation or free nodes cannot be destroyed. Any attempt to do so will return an error. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphEventRecordNodeGetEvent ( CUgraphNode hNode, CUevent* event_out ) + + +Returns the event associated with an event record node. + +###### Parameters + +`hNode` + \- Node to get the event for +`event_out` + \- Pointer to return the event + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the event of event record node `hNode` in `event_out`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphEventRecordNodeSetEvent ( CUgraphNode hNode, CUevent event ) + + +Sets an event record node's event. + +###### Parameters + +`hNode` + \- Node to set the event for +`event` + \- Event to use + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the event of event record node `hNode` to `event`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphEventWaitNodeGetEvent ( CUgraphNode hNode, CUevent* event_out ) + + +Returns the event associated with an event wait node. + +###### Parameters + +`hNode` + \- Node to get the event for +`event_out` + \- Pointer to return the event + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the event of event wait node `hNode` in `event_out`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphEventWaitNodeSetEvent ( CUgraphNode hNode, CUevent event ) + + +Sets an event wait node's event. + +###### Parameters + +`hNode` + \- Node to set the event for +`event` + \- Event to use + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the event of event wait node `hNode` to `event`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecBatchMemOpNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_BATCH_MEM_OP_NODE_PARAMS* nodeParams ) + + +Sets the parameters for a batch mem op node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Batch mem op node from the graph from which graphExec was instantiated +`nodeParams` + \- Updated Parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of a batch mem op node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +The following fields on operations may be modified on an executable graph: + +op.waitValue.address op.waitValue.value[64] op.waitValue.flags bits corresponding to wait type (i.e. CU_STREAM_WAIT_VALUE_FLUSH bit cannot be modified) op.writeValue.address op.writeValue.value[64] + +Other fields, such as the context, count or type of operations, and other types of operations such as membars, may not be modified. + +`hNode` must not have been removed from the original graph. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +The paramArray inside `nodeParams` is copied and therefore it can be freed after the call returns. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecChildGraphNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, CUgraph childGraph ) + + +Updates node parameters in the child graph node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Host node from the graph which was used to instantiate graphExec +`childGraph` + \- The graph supplying the updated parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Updates the work represented by `hNode` in `hGraphExec` as though the nodes contained in `hNode's` graph had the parameters contained in `childGraph's` nodes at instantiation. `hNode` must remain in the graph which was used to instantiate `hGraphExec`. Changed edges to and from `hNode` are ignored. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +The topology of `childGraph`, as well as the node insertion order, must match that of the graph contained in `hNode`. See cuGraphExecUpdate() for a list of restrictions on what can be updated in an instantiated graph. The update is recursive, so child graph nodes contained within the top level child graph will also be updated. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecDestroy ( CUgraphExec hGraphExec ) + + +Destroys an executable graph. + +###### Parameters + +`hGraphExec` + \- Executable graph to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Destroys the executable graph specified by `hGraphExec`, as well as all of its executable nodes. If the executable graph is in-flight, it will not be terminated, but rather freed asynchronously on completion. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecEventRecordNodeSetEvent ( CUgraphExec hGraphExec, CUgraphNode hNode, CUevent event ) + + +Sets the event for an event record node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- event record node from the graph from which graphExec was instantiated +`event` + \- Updated event to use + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the event of an event record node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecEventWaitNodeSetEvent ( CUgraphExec hGraphExec, CUgraphNode hNode, CUevent event ) + + +Sets the event for an event wait node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- event wait node from the graph from which graphExec was instantiated +`event` + \- Updated event to use + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the event of an event wait node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecExternalSemaphoresSignalNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS* nodeParams ) + + +Sets the parameters for an external semaphore signal node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- semaphore signal node from the graph from which graphExec was instantiated +`nodeParams` + \- Updated Parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of an external semaphore signal node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +`hNode` must not have been removed from the original graph. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +Changing `nodeParams->numExtSems` is not supported. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecExternalSemaphoresWaitNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_EXT_SEM_WAIT_NODE_PARAMS* nodeParams ) + + +Sets the parameters for an external semaphore wait node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- semaphore wait node from the graph from which graphExec was instantiated +`nodeParams` + \- Updated Parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of an external semaphore wait node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +`hNode` must not have been removed from the original graph. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +Changing `nodeParams->numExtSems` is not supported. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecGetFlags ( CUgraphExec hGraphExec, cuuint64_t* flags ) + + +Query the instantiation flags of an executable graph. + +###### Parameters + +`hGraphExec` + \- The executable graph to query +`flags` + \- Returns the instantiation flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the flags that were passed to instantiation for the given executable graph. CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD will not be returned by this API as it does not affect the resulting executable graph. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecGetId ( CUgraphExec hGraphExec, unsigned int* graphId ) + + +Returns the id of a given graph exec. + +###### Parameters + +`hGraphExec` + \- Graph to query +`graphId` + + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the id of `hGraphExec` in `*graphId`. The value in `*graphId` will match that referenced by cuGraphDebugDotPrint. + +CUresult cuGraphExecHostNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_HOST_NODE_PARAMS* nodeParams ) + + +Sets the parameters for a host node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Host node from the graph which was used to instantiate graphExec +`nodeParams` + \- The updated parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Updates the work represented by `hNode` in `hGraphExec` as though `hNode` had contained `nodeParams` at instantiation. hNode must remain in the graph which was used to instantiate `hGraphExec`. Changed edges to and from hNode are ignored. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. hNode is also not modified by this call. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecKernelNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_KERNEL_NODE_PARAMS* nodeParams ) + + +Sets the parameters for a kernel node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- kernel node from the graph from which graphExec was instantiated +`nodeParams` + \- Updated Parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of a kernel node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +`hNode` must not have been removed from the original graph. All `nodeParams` fields may change, but the following restrictions apply to `func` updates: + + * The owning context of the function cannot change. + + * A node whose function originally did not use CUDA dynamic parallelism cannot be updated to a function which uses CDP + + * A node whose function originally did not make device-side update calls cannot be updated to a function which makes device-side update calls. + + * If `hGraphExec` was not instantiated for device launch, a node whose function originally did not use device-side cudaGraphLaunch() cannot be updated to a function which uses device-side cudaGraphLaunch() unless the node resides on the same context as nodes which contained such calls at instantiate-time. If no such calls were present at instantiation, these updates cannot be performed at all. + + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +If `hNode` is a device-updatable kernel node, the next upload/launch of `hGraphExec` will overwrite any previous device-side updates. Additionally, applying host updates to a device-updatable kernel node while it is being updated from the device will result in undefined behavior. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecMemcpyNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_MEMCPY3D* copyParams, CUcontext ctx ) + + +Sets the parameters for a memcpy node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Memcpy node from the graph which was used to instantiate graphExec +`copyParams` + \- The updated parameters to set +`ctx` + \- Context on which to run the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Updates the work represented by `hNode` in `hGraphExec` as though `hNode` had contained `copyParams` at instantiation. hNode must remain in the graph which was used to instantiate `hGraphExec`. Changed edges to and from hNode are ignored. + +The source and destination memory in `copyParams` must be allocated from the same contexts as the original source and destination memory. Both the instantiation-time memory operands and the memory operands in `copyParams` must be 1-dimensional. Zero-length operations are not supported. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. hNode is also not modified by this call. + +Returns CUDA_ERROR_INVALID_VALUE if the memory operands' mappings changed or either the original or new memory operands are multidimensional. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecMemsetNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_MEMSET_NODE_PARAMS* memsetParams, CUcontext ctx ) + + +Sets the parameters for a memset node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Memset node from the graph which was used to instantiate graphExec +`memsetParams` + \- The updated parameters to set +`ctx` + \- Context on which to run the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Updates the work represented by `hNode` in `hGraphExec` as though `hNode` had contained `memsetParams` at instantiation. hNode must remain in the graph which was used to instantiate `hGraphExec`. Changed edges to and from hNode are ignored. + +Zero sized operations are not supported. + +The new destination pointer in memsetParams must be to the same kind of allocation as the original destination pointer and have the same context association and device mapping as the original destination pointer. + +Both the value and pointer address may be updated. Changing other aspects of the memset (width, height, element size or pitch) may cause the update to be rejected. Specifically, for 2d memsets, all dimension changes are rejected. For 1d memsets, changes in height are explicitly rejected and other changes are opportunistically allowed if the resulting work maps onto the work resources already allocated for the node. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. hNode is also not modified by this call. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecNodeSetParams ( CUgraphExec hGraphExec, CUgraphNode hNode, CUgraphNodeParams* nodeParams ) + + +Update's a graph node's parameters in an instantiated graph. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to update the specified node +`hNode` + \- Corresponding node from the graph from which graphExec was instantiated +`nodeParams` + \- Updated Parameters to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Sets the parameters of a node in an executable graph `hGraphExec`. The node is identified by the corresponding node `hNode` in the non-executable graph from which the executable graph was instantiated. `hNode` must not have been removed from the original graph. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +Allowed changes to parameters on executable graphs are as follows: + +Node type | Allowed changes +---|--- +kernel | See cuGraphExecKernelNodeSetParams +memcpy | Addresses for 1-dimensional copies if allocated in same context; see cuGraphExecMemcpyNodeSetParams +memset | Addresses for 1-dimensional memsets if allocated in same context; see cuGraphExecMemsetNodeSetParams +host | Unrestricted +child graph | Topology must match and restrictions apply recursively; see cuGraphExecUpdate +event wait | Unrestricted +event record | Unrestricted +external semaphore signal | Number of semaphore operations cannot change +external semaphore wait | Number of semaphore operations cannot change +memory allocation | API unsupported +memory free | API unsupported +batch memops | Addresses, values, and operation type for wait operations; see cuGraphExecBatchMemOpNodeSetParams + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExecUpdate ( CUgraphExec hGraphExec, CUgraph hGraph, CUgraphExecUpdateResultInfo* resultInfo ) + + +Check whether an executable graph can be updated with a graph and perform the update if possible. + +###### Parameters + +`hGraphExec` + The instantiated graph to be updated +`hGraph` + The graph containing the updated parameters +`resultInfo` + the error info structure + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE + +###### Description + +Updates the node parameters in the instantiated graph specified by `hGraphExec` with the node parameters in a topologically identical graph specified by `hGraph`. + +Limitations: + + * Kernel nodes: + * The owning context of the function cannot change. + + * A node whose function originally did not use CUDA dynamic parallelism cannot be updated to a function which uses CDP. + + * A node whose function originally did not make device-side update calls cannot be updated to a function which makes device-side update calls. + + * A cooperative node cannot be updated to a non-cooperative node, and vice-versa. + + * If the graph was instantiated with CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, the priority attribute cannot change. Equality is checked on the originally requested priority values, before they are clamped to the device's supported range. + + * If `hGraphExec` was not instantiated for device launch, a node whose function originally did not use device-side cudaGraphLaunch() cannot be updated to a function which uses device-side cudaGraphLaunch() unless the node resides on the same context as nodes which contained such calls at instantiate-time. If no such calls were present at instantiation, these updates cannot be performed at all. + + * Neither `hGraph` nor `hGraphExec` may contain device-updatable kernel nodes. + + * Memset and memcpy nodes: + * The CUDA device(s) to which the operand(s) was allocated/mapped cannot change. + + * The source/destination memory must be allocated from the same contexts as the original source/destination memory. + + * For 2d memsets, only address and assigned value may be updated. + + * For 1d memsets, updating dimensions is also allowed, but may fail if the resulting operation doesn't map onto the work resources already allocated for the node. + + * Additional memcpy node restrictions: + * Changing either the source or destination memory type(i.e. CU_MEMORYTYPE_DEVICE, CU_MEMORYTYPE_ARRAY, etc.) is not supported. + + * External semaphore wait nodes and record nodes: + * Changing the number of semaphores is not supported. + + * Conditional nodes: + * Changing node parameters is not supported. + + * Changing parameters of nodes within the conditional body graph is subject to the rules above. + + * Conditional handle flags and default values are updated as part of the graph update. + + +Note: The API may add further restrictions in future releases. The return code should always be checked. + +cuGraphExecUpdate sets the result member of `resultInfo` to CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED under the following conditions: + + * The count of nodes directly in `hGraphExec` and `hGraph` differ, in which case resultInfo->errorNode is set to NULL. + + * `hGraph` has more exit nodes than `hGraph`, in which case resultInfo->errorNode is set to one of the exit nodes in hGraph. + + * A node in `hGraph` has a different number of dependencies than the node from `hGraphExec` it is paired with, in which case resultInfo->errorNode is set to the node from `hGraph`. + + * A node in `hGraph` has a dependency that does not match with the corresponding dependency of the paired node from `hGraphExec`. resultInfo->errorNode will be set to the node from `hGraph`. resultInfo->errorFromNode will be set to the mismatched dependency. The dependencies are paired based on edge order and a dependency does not match when the nodes are already paired based on other edges examined in the graph. + + +cuGraphExecUpdate sets the result member of `resultInfo` to: + + * CU_GRAPH_EXEC_UPDATE_ERROR if passed an invalid value. + + * CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED if the graph topology changed + + * CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED if the type of a node changed, in which case `hErrorNode_out` is set to the node from `hGraph`. + + * CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE if the function changed in an unsupported way(see note above), in which case `hErrorNode_out` is set to the node from `hGraph` + + * CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED if any parameters to a node changed in a way that is not supported, in which case `hErrorNode_out` is set to the node from `hGraph`. + + * CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED if any attributes of a node changed in a way that is not supported, in which case `hErrorNode_out` is set to the node from `hGraph`. + + * CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED if something about a node is unsupported, like the node's type or configuration, in which case `hErrorNode_out` is set to the node from `hGraph` + + +If the update fails for a reason not listed above, the result member of `resultInfo` will be set to CU_GRAPH_EXEC_UPDATE_ERROR. If the update succeeds, the result member will be set to CU_GRAPH_EXEC_UPDATE_SUCCESS. + +cuGraphExecUpdate returns CUDA_SUCCESS when the updated was performed successfully. It returns CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE if the graph update was not performed because it included changes which violated constraints specific to instantiated graph update. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExternalSemaphoresSignalNodeGetParams ( CUgraphNode hNode, CUDA_EXT_SEM_SIGNAL_NODE_PARAMS* params_out ) + + +Returns an external semaphore signal node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`params_out` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of an external semaphore signal node `hNode` in `params_out`. The `extSemArray` and `paramsArray` returned in `params_out`, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use cuGraphExternalSemaphoresSignalNodeSetParams to update the parameters of this node. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExternalSemaphoresSignalNodeSetParams ( CUgraphNode hNode, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS* nodeParams ) + + +Sets an external semaphore signal node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the parameters of an external semaphore signal node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExternalSemaphoresWaitNodeGetParams ( CUgraphNode hNode, CUDA_EXT_SEM_WAIT_NODE_PARAMS* params_out ) + + +Returns an external semaphore wait node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`params_out` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of an external semaphore wait node `hNode` in `params_out`. The `extSemArray` and `paramsArray` returned in `params_out`, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use cuGraphExternalSemaphoresSignalNodeSetParams to update the parameters of this node. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphExternalSemaphoresWaitNodeSetParams ( CUgraphNode hNode, const CUDA_EXT_SEM_WAIT_NODE_PARAMS* nodeParams ) + + +Sets an external semaphore wait node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the parameters of an external semaphore wait node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphGetEdges ( CUgraph hGraph, CUgraphNode* from, CUgraphNode* to, CUgraphEdgeData* edgeData, size_t* numEdges ) + + +Returns a graph's dependency edges. + +###### Parameters + +`hGraph` + \- Graph to get the edges from +`from` + \- Location to return edge endpoints +`to` + \- Location to return edge endpoints +`edgeData` + \- Optional location to return edge data +`numEdges` + \- See description + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_LOSSY_QUERY, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns a list of `hGraph's` dependency edges. Edges are returned via corresponding indices in `from`, `to` and `edgeData`; that is, the node in `to`[i] has a dependency on the node in `from`[i] with data `edgeData`[i]. `from` and `to` may both be NULL, in which case this function only returns the number of edges in `numEdges`. Otherwise, `numEdges` entries will be filled in. If `numEdges` is higher than the actual number of edges, the remaining entries in `from` and `to` will be set to NULL, and the number of edges actually returned will be written to `numEdges`. `edgeData` may alone be NULL, in which case the edges must all have default (zeroed) edge data. Attempting a lossy query via NULL `edgeData` will result in CUDA_ERROR_LOSSY_QUERY. If `edgeData` is non-NULL then `from` and `to` must be as well. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphGetId ( CUgraph hGraph, unsigned int* graphId ) + + +Returns the id of a given graph. + +###### Parameters + +`hGraph` + \- Graph to query +`graphId` + + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the id of `hGraph` in `*graphId`. The value in `*graphId` will match that referenced by cuGraphDebugDotPrint. + +CUresult cuGraphGetNodes ( CUgraph hGraph, CUgraphNode* nodes, size_t* numNodes ) + + +Returns a graph's nodes. + +###### Parameters + +`hGraph` + \- Graph to query +`nodes` + \- Pointer to return the nodes +`numNodes` + \- See description + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns a list of `hGraph's` nodes. `nodes` may be NULL, in which case this function will return the number of nodes in `numNodes`. Otherwise, `numNodes` entries will be filled in. If `numNodes` is higher than the actual number of nodes, the remaining entries in `nodes` will be set to NULL, and the number of nodes actually obtained will be returned in `numNodes`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphGetRootNodes ( CUgraph hGraph, CUgraphNode* rootNodes, size_t* numRootNodes ) + + +Returns a graph's root nodes. + +###### Parameters + +`hGraph` + \- Graph to query +`rootNodes` + \- Pointer to return the root nodes +`numRootNodes` + \- See description + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns a list of `hGraph's` root nodes. `rootNodes` may be NULL, in which case this function will return the number of root nodes in `numRootNodes`. Otherwise, `numRootNodes` entries will be filled in. If `numRootNodes` is higher than the actual number of root nodes, the remaining entries in `rootNodes` will be set to NULL, and the number of nodes actually obtained will be returned in `numRootNodes`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphHostNodeGetParams ( CUgraphNode hNode, CUDA_HOST_NODE_PARAMS* nodeParams ) + + +Returns a host node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`nodeParams` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of host node `hNode` in `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphHostNodeSetParams ( CUgraphNode hNode, const CUDA_HOST_NODE_PARAMS* nodeParams ) + + +Sets a host node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of host node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphInstantiate ( CUgraphExec* phGraphExec, CUgraph hGraph, unsigned long long flags ) + + +Creates an executable graph from a graph. + +###### Parameters + +`phGraphExec` + \- Returns instantiated graph +`hGraph` + \- Graph to instantiate +`flags` + \- Flags to control instantiation. See CUgraphInstantiate_flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Instantiates `hGraph` as an executable graph. The graph is validated for any structural constraints or intra-node constraints which were not previously validated. If instantiation is successful, a handle to the instantiated graph is returned in `phGraphExec`. + +The `flags` parameter controls the behavior of instantiation and subsequent graph launches. Valid flags are: + + * CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, which configures a graph containing memory allocation nodes to automatically free any unfreed memory allocations before the graph is relaunched. + + + * CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH, which configures the graph for launch from the device. If this flag is passed, the executable graph handle returned can be used to launch the graph from both the host and device. This flag can only be used on platforms which support unified addressing. This flag cannot be used in conjunction with CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH. + + + * CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, which causes the graph to use the priorities from the per-node attributes rather than the priority of the launch stream during execution. Note that priorities are only available on kernel nodes, and are copied from stream priority during stream capture. + + +If `hGraph` contains any allocation or free nodes, there can be at most one executable graph in existence for that graph at a time. An attempt to instantiate a second executable graph before destroying the first with cuGraphExecDestroy will result in an error. The same also applies if `hGraph` contains any device-updatable kernel nodes. + +If `hGraph` contains kernels which call device-side cudaGraphLaunch() from multiple contexts, this will result in an error. + +Graphs instantiated for launch on the device have additional restrictions which do not apply to host graphs: + + * The graph's nodes must reside on a single context. + + * The graph can only contain kernel nodes, memcpy nodes, memset nodes, and child graph nodes. + + * The graph cannot be empty and must contain at least one kernel, memcpy, or memset node. Operation-specific restrictions are outlined below. + + * Kernel nodes: + * Use of CUDA Dynamic Parallelism is not permitted. + + * Cooperative launches are permitted as long as MPS is not in use. + + * Memcpy nodes: + * Only copies involving device memory and/or pinned device-mapped host memory are permitted. + + * Copies involving CUDA arrays are not permitted. + + * Both operands must be accessible from the current context, and the current context must match the context of other nodes in the graph. + + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphInstantiateWithParams ( CUgraphExec* phGraphExec, CUgraph hGraph, CUDA_GRAPH_INSTANTIATE_PARAMS* instantiateParams ) + + +Creates an executable graph from a graph. + +###### Parameters + +`phGraphExec` + \- Returns instantiated graph +`hGraph` + \- Graph to instantiate +`instantiateParams` + \- Instantiation parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Instantiates `hGraph` as an executable graph according to the `instantiateParams` structure. The graph is validated for any structural constraints or intra-node constraints which were not previously validated. If instantiation is successful, a handle to the instantiated graph is returned in `phGraphExec`. + +`instantiateParams` controls the behavior of instantiation and subsequent graph launches, as well as returning more detailed information in the event of an error. CUDA_GRAPH_INSTANTIATE_PARAMS is defined as: + + + ‎ typedef struct { + cuuint64_t flags; + CUstream hUploadStream; + CUgraphNode hErrNode_out; + CUgraphInstantiateResult result_out; + } CUDA_GRAPH_INSTANTIATE_PARAMS; + +The `flags` field controls the behavior of instantiation and subsequent graph launches. Valid flags are: + + * CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, which configures a graph containing memory allocation nodes to automatically free any unfreed memory allocations before the graph is relaunched. + + + * CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD, which will perform an upload of the graph into `hUploadStream` once the graph has been instantiated. + + + * CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH, which configures the graph for launch from the device. If this flag is passed, the executable graph handle returned can be used to launch the graph from both the host and device. This flag can only be used on platforms which support unified addressing. This flag cannot be used in conjunction with CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH. + + + * CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, which causes the graph to use the priorities from the per-node attributes rather than the priority of the launch stream during execution. Note that priorities are only available on kernel nodes, and are copied from stream priority during stream capture. + + +If `hGraph` contains any allocation or free nodes, there can be at most one executable graph in existence for that graph at a time. An attempt to instantiate a second executable graph before destroying the first with cuGraphExecDestroy will result in an error. The same also applies if `hGraph` contains any device-updatable kernel nodes. + +If `hGraph` contains kernels which call device-side cudaGraphLaunch() from multiple contexts, this will result in an error. + +Graphs instantiated for launch on the device have additional restrictions which do not apply to host graphs: + + * The graph's nodes must reside on a single context. + + * The graph can only contain kernel nodes, memcpy nodes, memset nodes, and child graph nodes. + + * The graph cannot be empty and must contain at least one kernel, memcpy, or memset node. Operation-specific restrictions are outlined below. + + * Kernel nodes: + * Use of CUDA Dynamic Parallelism is not permitted. + + * Cooperative launches are permitted as long as MPS is not in use. + + * Memcpy nodes: + * Only copies involving device memory and/or pinned device-mapped host memory are permitted. + + * Copies involving CUDA arrays are not permitted. + + * Both operands must be accessible from the current context, and the current context must match the context of other nodes in the graph. + + +In the event of an error, the `result_out` and `hErrNode_out` fields will contain more information about the nature of the error. Possible error reporting includes: + + * CUDA_GRAPH_INSTANTIATE_ERROR, if passed an invalid value or if an unexpected error occurred which is described by the return value of the function. `hErrNode_out` will be set to NULL. + + * CUDA_GRAPH_INSTANTIATE_INVALID_STRUCTURE, if the graph structure is invalid. `hErrNode_out` will be set to one of the offending nodes. + + * CUDA_GRAPH_INSTANTIATE_NODE_OPERATION_NOT_SUPPORTED, if the graph is instantiated for device launch but contains a node of an unsupported node type, or a node which performs unsupported operations, such as use of CUDA dynamic parallelism within a kernel node. `hErrNode_out` will be set to this node. + + * CUDA_GRAPH_INSTANTIATE_MULTIPLE_CTXS_NOT_SUPPORTED, if the graph is instantiated for device launch but a node’s context differs from that of another node. This error can also be returned if a graph is not instantiated for device launch and it contains kernels which call device-side cudaGraphLaunch() from multiple contexts. `hErrNode_out` will be set to this node. + + +If instantiation is successful, `result_out` will be set to CUDA_GRAPH_INSTANTIATE_SUCCESS, and `hErrNode_out` will be set to NULL. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphKernelNodeCopyAttributes ( CUgraphNode dst, CUgraphNode src ) + + +Copies attributes from source node to destination node. + +###### Parameters + +`dst` + Destination node +`src` + Source node For list of attributes see CUkernelNodeAttrID + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies attributes from source node `src` to destination node `dst`. Both node must have the same context. + +CUresult cuGraphKernelNodeGetAttribute ( CUgraphNode hNode, CUkernelNodeAttrID attr, CUkernelNodeAttrValue* value_out ) + + +Queries node attribute. + +###### Parameters + +`hNode` + +`attr` + +`value_out` + + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Queries attribute `attr` from node `hNode` and stores it in corresponding member of `value_out`. + +CUresult cuGraphKernelNodeGetParams ( CUgraphNode hNode, CUDA_KERNEL_NODE_PARAMS* nodeParams ) + + +Returns a kernel node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`nodeParams` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of kernel node `hNode` in `nodeParams`. The `kernelParams` or `extra` array returned in `nodeParams`, as well as the argument values it points to, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use cuGraphKernelNodeSetParams to update the parameters of this node. + +The params will contain either `kernelParams` or `extra`, according to which of these was most recently set on the node. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphKernelNodeSetAttribute ( CUgraphNode hNode, CUkernelNodeAttrID attr, const CUkernelNodeAttrValue* value ) + + +Sets node attribute. + +###### Parameters + +`hNode` + +`attr` + +`value` + + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Sets attribute `attr` on node `hNode` from corresponding attribute of `value`. + +CUresult cuGraphKernelNodeSetParams ( CUgraphNode hNode, const CUDA_KERNEL_NODE_PARAMS* nodeParams ) + + +Sets a kernel node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Sets the parameters of kernel node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphLaunch ( CUgraphExec hGraphExec, CUstream hStream ) + + +Launches an executable graph in a stream. + +###### Parameters + +`hGraphExec` + \- Executable graph to launch +`hStream` + \- Stream in which to launch the graph + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Executes `hGraphExec` in `hStream`. Only one instance of `hGraphExec` may be executing at a time. Each launch is ordered behind both any previous work in `hStream` and any previous launches of `hGraphExec`. To execute a graph concurrently, it must be instantiated multiple times into multiple executable graphs. + +If any allocations created by `hGraphExec` remain unfreed (from a previous launch) and `hGraphExec` was not instantiated with CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, the launch will fail with CUDA_ERROR_INVALID_VALUE. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemAllocNodeGetParams ( CUgraphNode hNode, CUDA_MEM_ALLOC_NODE_PARAMS* params_out ) + + +Returns a memory alloc node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`params_out` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of a memory alloc node `hNode` in `params_out`. The `poolProps` and `accessDescs` returned in `params_out`, are owned by the node. This memory remains valid until the node is destroyed. The returned parameters must not be modified. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemFreeNodeGetParams ( CUgraphNode hNode, CUdeviceptr* dptr_out ) + + +Returns a memory free node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`dptr_out` + \- Pointer to return the device address + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the address of a memory free node `hNode` in `dptr_out`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemcpyNodeGetParams ( CUgraphNode hNode, CUDA_MEMCPY3D* nodeParams ) + + +Returns a memcpy node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`nodeParams` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of memcpy node `hNode` in `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemcpyNodeSetParams ( CUgraphNode hNode, const CUDA_MEMCPY3D* nodeParams ) + + +Sets a memcpy node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of memcpy node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemsetNodeGetParams ( CUgraphNode hNode, CUDA_MEMSET_NODE_PARAMS* nodeParams ) + + +Returns a memset node's parameters. + +###### Parameters + +`hNode` + \- Node to get the parameters for +`nodeParams` + \- Pointer to return the parameters + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the parameters of memset node `hNode` in `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphMemsetNodeSetParams ( CUgraphNode hNode, const CUDA_MEMSET_NODE_PARAMS* nodeParams ) + + +Sets a memset node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the parameters of memset node `hNode` to `nodeParams`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeFindInClone ( CUgraphNode* phNode, CUgraphNode hOriginalNode, CUgraph hClonedGraph ) + + +Finds a cloned version of a node. + +###### Parameters + +`phNode` + \- Returns handle to the cloned node +`hOriginalNode` + \- Handle to the original node +`hClonedGraph` + \- Cloned graph to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +This function returns the node in `hClonedGraph` corresponding to `hOriginalNode` in the original graph. + +`hClonedGraph` must have been cloned from `hOriginalGraph` via cuGraphClone. `hOriginalNode` must have been in `hOriginalGraph` at the time of the call to cuGraphClone, and the corresponding cloned node in `hClonedGraph` must not have been removed. The cloned node is then returned via `phClonedNode`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeGetContainingGraph ( CUgraphNode hNode, CUgraph* phGraph ) + + +Returns the graph that contains a given graph node. + +###### Parameters + +`hNode` + \- Node to query +`phGraph` + + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the graph that contains `hNode` in `*phGraph`. If `hNode` is in a child graph, the child graph it is in is returned. + +CUresult cuGraphNodeGetDependencies ( CUgraphNode hNode, CUgraphNode* dependencies, CUgraphEdgeData* edgeData, size_t* numDependencies ) + + +Returns a node's dependencies. + +###### Parameters + +`hNode` + \- Node to query +`dependencies` + \- Pointer to return the dependencies +`edgeData` + \- Optional array to return edge data for each dependency +`numDependencies` + \- See description + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_LOSSY_QUERY, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns a list of `node's` dependencies. `dependencies` may be NULL, in which case this function will return the number of dependencies in `numDependencies`. Otherwise, `numDependencies` entries will be filled in. If `numDependencies` is higher than the actual number of dependencies, the remaining entries in `dependencies` will be set to NULL, and the number of nodes actually obtained will be returned in `numDependencies`. + +Note that if an edge has non-zero (non-default) edge data and `edgeData` is NULL, this API will return CUDA_ERROR_LOSSY_QUERY. If `edgeData` is non-NULL, then `dependencies` must be as well. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeGetDependentNodes ( CUgraphNode hNode, CUgraphNode* dependentNodes, CUgraphEdgeData* edgeData, size_t* numDependentNodes ) + + +Returns a node's dependent nodes. + +###### Parameters + +`hNode` + \- Node to query +`dependentNodes` + \- Pointer to return the dependent nodes +`edgeData` + \- Optional pointer to return edge data for dependent nodes +`numDependentNodes` + \- See description + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_LOSSY_QUERY, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns a list of `node's` dependent nodes. `dependentNodes` may be NULL, in which case this function will return the number of dependent nodes in `numDependentNodes`. Otherwise, `numDependentNodes` entries will be filled in. If `numDependentNodes` is higher than the actual number of dependent nodes, the remaining entries in `dependentNodes` will be set to NULL, and the number of nodes actually obtained will be returned in `numDependentNodes`. + +Note that if an edge has non-zero (non-default) edge data and `edgeData` is NULL, this API will return CUDA_ERROR_LOSSY_QUERY. If `edgeData` is non-NULL, then `dependentNodes` must be as well. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeGetEnabled ( CUgraphExec hGraphExec, CUgraphNode hNode, unsigned int* isEnabled ) + + +Query whether a node in the given graphExec is enabled. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Node from the graph from which graphExec was instantiated +`isEnabled` + \- Location to return the enabled status of the node + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets isEnabled to 1 if `hNode` is enabled, or 0 if `hNode` is disabled. + +The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +`hNode` must not have been removed from the original graph. + + * Currently only kernel, memset and memcpy nodes are supported. + + * This function will not reflect device-side updates for device-updatable kernel nodes. + + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeGetLocalId ( CUgraphNode hNode, unsigned int* nodeId ) + + +Returns the local node id of a given graph node. + +###### Parameters + +`hNode` + \- Node to query +`nodeId` + \- Pointer to return the nodeId + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the node id of `hNode` in `*nodeId`. The nodeId matches that referenced by cuGraphDebugDotPrint. The local nodeId and graphId together can uniquely identify the node. + +CUresult cuGraphNodeGetToolsId ( CUgraphNode hNode, unsigned long long* toolsNodeId ) + + +Returns an id used by tools to identify a given node. + +###### Parameters + +`hNode` + \- Node to query +`toolsNodeId` + + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +CUresult cuGraphNodeGetType ( CUgraphNode hNode, CUgraphNodeType* type ) + + +Returns a node's type. + +###### Parameters + +`hNode` + \- Node to query +`type` + \- Pointer to return the node type + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the node type of `hNode` in `type`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeSetEnabled ( CUgraphExec hGraphExec, CUgraphNode hNode, unsigned int isEnabled ) + + +Enables or disables the specified node in the given graphExec. + +###### Parameters + +`hGraphExec` + \- The executable graph in which to set the specified node +`hNode` + \- Node from the graph from which graphExec was instantiated +`isEnabled` + \- Node is enabled if != 0, otherwise the node is disabled + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets `hNode` to be either enabled or disabled. Disabled nodes are functionally equivalent to empty nodes until they are reenabled. Existing node parameters are not affected by disabling/enabling the node. + +The node is identified by the corresponding node `hNode` in the non-executable graph, from which the executable graph was instantiated. + +`hNode` must not have been removed from the original graph. + +The modifications only affect future launches of `hGraphExec`. Already enqueued or running launches of `hGraphExec` are not affected by this call. `hNode` is also not modified by this call. + +If `hNode` is a device-updatable kernel node, the next upload/launch of `hGraphExec` will overwrite any previous device-side updates. Additionally, applying host updates to a device-updatable kernel node while it is being updated from the device will result in undefined behavior. + +Currently only kernel, memset and memcpy nodes are supported. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphNodeSetParams ( CUgraphNode hNode, CUgraphNodeParams* nodeParams ) + + +Update's a graph node's parameters. + +###### Parameters + +`hNode` + \- Node to set the parameters for +`nodeParams` + \- Parameters to copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Sets the parameters of graph node `hNode` to `nodeParams`. The node type specified by `nodeParams->type` must match the type of `hNode`. `nodeParams` must be fully initialized and all unused bytes (reserved, padding) zeroed. + +Modifying parameters is not supported for node types CU_GRAPH_NODE_TYPE_MEM_ALLOC and CU_GRAPH_NODE_TYPE_MEM_FREE. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphReleaseUserObject ( CUgraph graph, CUuserObject object, unsigned int count ) + + +Release a user object reference from a graph. + +###### Parameters + +`graph` + \- The graph that will release the reference +`object` + \- The user object to release a reference for +`count` + \- The number of references to release, typically 1. Must be nonzero and not larger than INT_MAX. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Releases user object references owned by a graph. + +See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. + +CUresult cuGraphRemoveDependencies ( CUgraph hGraph, const CUgraphNode* from, const CUgraphNode* to, const CUgraphEdgeData* edgeData, size_t numDependencies ) + + +Removes dependency edges from a graph. + +###### Parameters + +`hGraph` + \- Graph from which to remove dependencies +`from` + \- Array of nodes that provide the dependencies +`to` + \- Array of dependent nodes +`edgeData` + \- Optional array of edge data. If NULL, edge data is assumed to be default (zeroed). +`numDependencies` + \- Number of dependencies to be removed + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +The number of `dependencies` to be removed is defined by `numDependencies`. Elements in `from` and `to` at corresponding indices define a dependency. Each node in `from` and `to` must belong to `hGraph`. + +If `numDependencies` is 0, elements in `from` and `to` will be ignored. Specifying an edge that does not exist in the graph, with data matching `edgeData`, results in an error. `edgeData` is nullable, which is equivalent to passing default (zeroed) data for each edge. + +Dependencies cannot be removed from graphs which contain allocation or free nodes. Any attempt to do so will return an error. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuGraphRetainUserObject ( CUgraph graph, CUuserObject object, unsigned int count, unsigned int flags ) + + +Retain a reference to a user object from a graph. + +###### Parameters + +`graph` + \- The graph to associate the reference with +`object` + \- The user object to retain a reference for +`count` + \- The number of references to add to the graph, typically 1. Must be nonzero and not larger than INT_MAX. +`flags` + \- The optional flag CU_GRAPH_USER_OBJECT_MOVE transfers references from the calling thread, rather than create new references. Pass 0 to create new references. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates or moves user object references that will be owned by a CUDA graph. + +See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. + +CUresult cuGraphUpload ( CUgraphExec hGraphExec, CUstream hStream ) + + +Uploads an executable graph in a stream. + +###### Parameters + +`hGraphExec` + \- Executable graph to upload +`hStream` + \- Stream in which to upload the graph + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Uploads `hGraphExec` to the device in `hStream` without executing it. Uploads of the same `hGraphExec` will be serialized. Each upload is ordered behind both any previous work in `hStream` and any previous launches of `hGraphExec`. Uses memory cached by `stream` to back the allocations owned by `hGraphExec`. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuUserObjectCreate ( CUuserObject* object_out, void* ptr, CUhostFn destroy, unsigned int initialRefcount, unsigned int flags ) + + +Create a user object. + +###### Parameters + +`object_out` + \- Location to return the user object handle +`ptr` + \- The pointer to pass to the destroy function +`destroy` + \- Callback to free the user object when it is no longer in use +`initialRefcount` + \- The initial refcount to create the object with, typically 1. The initial references are owned by the calling thread. +`flags` + \- Currently it is required to pass CU_USER_OBJECT_NO_DESTRUCTOR_SYNC, which is the only defined flag. This indicates that the destroy callback cannot be waited on by any CUDA API. Users requiring synchronization of the callback should signal its completion manually. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Create a user object with the specified destructor callback and initial reference count. The initial references are owned by the caller. + +Destructor callbacks cannot make CUDA API calls and should avoid blocking behavior, as they are executed by a shared internal thread. Another thread may be signaled to perform such actions, if it does not block forward progress of tasks scheduled through CUDA. + +See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. + +CUresult cuUserObjectRelease ( CUuserObject object, unsigned int count ) + + +Release a reference to a user object. + +###### Parameters + +`object` + \- The object to release +`count` + \- The number of references to release, typically 1. Must be nonzero and not larger than INT_MAX. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Releases user object references owned by the caller. The object's destructor is invoked if the reference count reaches zero. + +It is undefined behavior to release references not owned by the caller, or to use a user object handle after all references are released. + +See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. + +CUresult cuUserObjectRetain ( CUuserObject object, unsigned int count ) + + +Retain a reference to a user object. + +###### Parameters + +`object` + \- The object to retain +`count` + \- The number of references to retain, typically 1. Must be nonzero and not larger than INT_MAX. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Retains new references to a user object. The new references are owned by the caller. + +See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. diff --git a/content/cuda/docs/driver-graphics/DOC.md b/content/cuda/docs/driver-graphics/DOC.md new file mode 100644 index 00000000..fe46fd1b --- /dev/null +++ b/content/cuda/docs/driver-graphics/DOC.md @@ -0,0 +1,205 @@ +--- +name: driver-graphics +description: '**Source:** group__CUDA__GRAPHICS.html#group__CUDA__GRAPHICS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.32. Graphics Interoperability + +**Source:** group__CUDA__GRAPHICS.html#group__CUDA__GRAPHICS + + +### Functions + +CUresult cuGraphicsMapResources ( unsigned int count, CUgraphicsResource* resources, CUstream hStream ) + + +Map graphics resources for access by CUDA. + +###### Parameters + +`count` + \- Number of resources to map +`resources` + \- Resources to map for CUDA usage +`hStream` + \- Stream with which to synchronize + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_UNKNOWN + +###### Description + +Maps the `count` graphics resources in `resources` for access by CUDA. + +The resources in `resources` may be accessed by CUDA until they are unmapped. The graphics API from which `resources` were registered should not access any resources while they are mapped by CUDA. If an application does so, the results are undefined. + +This function provides the synchronization guarantee that any graphics calls issued before cuGraphicsMapResources() will complete before any subsequent CUDA work issued in `stream` begins. + +If `resources` includes any duplicate entries then CUDA_ERROR_INVALID_HANDLE is returned. If any of `resources` are presently mapped for access by CUDA then CUDA_ERROR_ALREADY_MAPPED is returned. + + * This function uses standard default stream semantics. + + * +CUresult cuGraphicsResourceGetMappedMipmappedArray ( CUmipmappedArray* pMipmappedArray, CUgraphicsResource resource ) + + +Get a mipmapped array through which to access a mapped graphics resource. + +###### Parameters + +`pMipmappedArray` + \- Returned mipmapped array through which `resource` may be accessed +`resource` + \- Mapped resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_NOT_MAPPED_AS_ARRAY + +###### Description + +Returns in `*pMipmappedArray` a mipmapped array through which the mapped graphics resource `resource`. The value set in `*pMipmappedArray` may change every time that `resource` is mapped. + +If `resource` is not a texture then it cannot be accessed via a mipmapped array and CUDA_ERROR_NOT_MAPPED_AS_ARRAY is returned. If `resource` is not mapped then CUDA_ERROR_NOT_MAPPED is returned. + +CUresult cuGraphicsResourceGetMappedPointer ( CUdeviceptr* pDevPtr, size_t* pSize, CUgraphicsResource resource ) + + +Get a device pointer through which to access a mapped graphics resource. + +###### Parameters + +`pDevPtr` + \- Returned pointer through which `resource` may be accessed +`pSize` + \- Returned size of the buffer accessible starting at `*pPointer` +`resource` + \- Mapped resource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_NOT_MAPPED_AS_POINTER + +###### Description + +Returns in `*pDevPtr` a pointer through which the mapped graphics resource `resource` may be accessed. Returns in `pSize` the size of the memory in bytes which may be accessed from that pointer. The value set in `pPointer` may change every time that `resource` is mapped. + +If `resource` is not a buffer then it cannot be accessed via a pointer and CUDA_ERROR_NOT_MAPPED_AS_POINTER is returned. If `resource` is not mapped then CUDA_ERROR_NOT_MAPPED is returned. * + +CUresult cuGraphicsResourceSetMapFlags ( CUgraphicsResource resource, unsigned int flags ) + + +Set usage flags for mapping a graphics resource. + +###### Parameters + +`resource` + \- Registered resource to set flags for +`flags` + \- Parameters for resource mapping + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED + +###### Description + +Set `flags` for mapping the graphics resource `resource`. + +Changes to `flags` will take effect the next time `resource` is mapped. The `flags` argument may be any of the following: + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA kernels. This is the default value. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_READONLY: Specifies that CUDA kernels which access this resource will not write to this resource. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITEDISCARD: Specifies that CUDA kernels which access this resource will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +If `resource` is presently mapped for access by CUDA then CUDA_ERROR_ALREADY_MAPPED is returned. If `flags` is not one of the above values then CUDA_ERROR_INVALID_VALUE is returned. + +CUresult cuGraphicsSubResourceGetMappedArray ( CUarray* pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel ) + + +Get an array through which to access a subresource of a mapped graphics resource. + +###### Parameters + +`pArray` + \- Returned array through which a subresource of `resource` may be accessed +`resource` + \- Mapped resource to access +`arrayIndex` + \- Array index for array textures or cubemap face index as defined by CUarray_cubemap_face for cubemap textures for the subresource to access +`mipLevel` + \- Mipmap level for the subresource to access + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_NOT_MAPPED_AS_ARRAY + +###### Description + +Returns in `*pArray` an array through which the subresource of the mapped graphics resource `resource` which corresponds to array index `arrayIndex` and mipmap level `mipLevel` may be accessed. The value set in `*pArray` may change every time that `resource` is mapped. + +If `resource` is not a texture then it cannot be accessed via an array and CUDA_ERROR_NOT_MAPPED_AS_ARRAY is returned. If `arrayIndex` is not a valid array index for `resource` then CUDA_ERROR_INVALID_VALUE is returned. If `mipLevel` is not a valid mipmap level for `resource` then CUDA_ERROR_INVALID_VALUE is returned. If `resource` is not mapped then CUDA_ERROR_NOT_MAPPED is returned. + +CUresult cuGraphicsUnmapResources ( unsigned int count, CUgraphicsResource* resources, CUstream hStream ) + + +Unmap graphics resources. + +###### Parameters + +`count` + \- Number of resources to unmap +`resources` + \- Resources to unmap +`hStream` + \- Stream with which to synchronize + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPED, CUDA_ERROR_UNKNOWN + +###### Description + +Unmaps the `count` graphics resources in `resources`. + +Once unmapped, the resources in `resources` may not be accessed by CUDA until they are mapped again. + +This function provides the synchronization guarantee that any CUDA work issued in `stream` before cuGraphicsUnmapResources() will complete before any subsequently issued graphics work begins. + +If `resources` includes any duplicate entries then CUDA_ERROR_INVALID_HANDLE is returned. If any of `resources` are not presently mapped for access by CUDA then CUDA_ERROR_NOT_MAPPED is returned. + + * This function uses standard default stream semantics. + + * +CUresult cuGraphicsUnregisterResource ( CUgraphicsResource resource ) + + +Unregisters a graphics resource for access by CUDA. + +###### Parameters + +`resource` + \- Resource to unregister + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_UNKNOWN + +###### Description + +Unregisters the graphics resource `resource` so it is not accessible by CUDA unless registered again. + +If `resource` is invalid then CUDA_ERROR_INVALID_HANDLE is returned. + + diff --git a/content/cuda/docs/driver-green--contexts/DOC.md b/content/cuda/docs/driver-green--contexts/DOC.md new file mode 100644 index 00000000..e6111c8a --- /dev/null +++ b/content/cuda/docs/driver-green--contexts/DOC.md @@ -0,0 +1,533 @@ +--- +name: driver-green--contexts +description: '**Source:** group__CUDA__GREEN__CONTEXTS.html#group__CUDA__GREEN__CONTEXTS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.35. Green Contexts + +**Source:** group__CUDA__GREEN__CONTEXTS.html#group__CUDA__GREEN__CONTEXTS + + +### Classes + +struct + +CU_DEV_SM_RESOURCE_GROUP_PARAMS + + +struct + +CUdevResource + + +struct + +CUdevSmResource + + +struct + +CUdevWorkqueueConfigResource + + +struct + +CUdevWorkqueueResource + + + +### Typedefs + +typedef CUdevResourceDesc_st * CUdevResourceDesc + + +### Enumerations + +enum CUdevResourceType + +enum CUdevWorkqueueConfigScope + + +### Functions + +CUresult cuCtxFromGreenCtx ( CUcontext* pContext, CUgreenCtx hCtx ) + + +Converts a green context into the primary context. + +###### Parameters + +`pContext` + Returned primary context with green context resources +`hCtx` + Green context to convert + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +The API converts a green context into the primary context returned in `pContext`. It is important to note that the converted context `pContext` is a normal primary context but with the resources of the specified green context `hCtx`. Once converted, it can then be used to set the context current with cuCtxSetCurrent or with any of the CUDA APIs that accept a CUcontext parameter. + +Users are expected to call this API before calling any CUDA APIs that accept a CUcontext. Failing to do so will result in the APIs returning CUDA_ERROR_INVALID_CONTEXT. + +CUresult cuCtxGetDevResource ( CUcontext hCtx, CUdevResource* resource, CUdevResourceType type ) + + +Get context resources. + +###### Parameters + +`hCtx` + \- Context to get resource for +`resource` + \- Output pointer to a CUdevResource structure +`type` + \- Type of resource to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Get the `type` resources available to the context represented by `hCtx` Note: The API is not supported on 32-bit platforms. + +CUresult cuDevResourceGenerateDesc ( CUdevResourceDesc* phDesc, CUdevResource* resources, unsigned int nbResources ) + + +Generate a resource descriptor. + +###### Parameters + +`phDesc` + \- Output descriptor +`resources` + \- Array of resources to be included in the descriptor +`nbResources` + \- Number of resources passed in `resources` + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION + +###### Description + +Generates a single resource descriptor with the set of resources specified in `resources`. The generated resource descriptor is necessary for the creation of green contexts via the cuGreenCtxCreate API. Resources of the same type can be passed in, provided they meet the requirements as noted below. + +A successful API call must have: + + * A valid output pointer for the `phDesc` descriptor as well as a valid array of `resources` pointers, with the array size passed in `nbResources`. If multiple resources are provided in `resources`, the device they came from must be the same, otherwise CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. If multiple resources are provided in `resources` and they are of type CU_DEV_RESOURCE_TYPE_SM, they must be outputs (whether `result` or `remaining`) from the same split API instance and have the same smCoscheduledAlignment values, otherwise CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. + + +Note: The API is not supported on 32-bit platforms. + +CUresult cuDevSmResourceSplit ( CUdevResource* result, unsigned int nbGroups, const CUdevResource* input, CUdevResource* remainder, unsigned int flags, CU_DEV_SM_RESOURCE_GROUP_PARAMS* groupParams ) + + +Splits a `CU_DEV_RESOURCE_TYPE_SM` resource into structured groups. + +###### Parameters + +`result` + \- Output array of `CUdevResource` resources. Can be NULL, alongside an smCount of 0, for discovery purpose. +`nbGroups` + \- Specifies the number of groups in `result` and `groupParams` +`input` + \- Input SM resource to be split. Must be a valid `CU_DEV_RESOURCE_TYPE_SM` resource. +`remainder` + \- If splitting the input resource leaves any SMs, the remainder is placed in here. +`flags` + \- Flags specifying how the API should behave. The value should be 0 for now. +`groupParams` + \- Description of how the SMs should be split and assigned to the corresponding result entry. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION + +###### Description + +This API will split a resource of CU_DEV_RESOURCE_TYPE_SM into `nbGroups` structured device resource groups (the `result` array), as well as an optional `remainder`, according to a set of requirements specified in the `groupParams` array. The term “structured” is a trait that specifies the `result` has SMs that are co-scheduled together. This co-scheduling can be specified via the `coscheduledSmCount` field of the `groupParams` structure, while the `smCount` will specify how many SMs are required in total for that result. The remainder is always “unstructured”, it does not have any set guarantees with respect to co-scheduling and those properties will need to either be queried via the occupancy set of APIs or further split into structured groups by this API. + +The API has a discovery mode for use cases where it is difficult to know ahead of time what the SM count should be. Discovery happens when the `smCount` field of a given `groupParams` array entry is set to 0 - the smCount will be filled in by the API with the derived SM count according to the provided `groupParams` fields and constraints. Discovery can be used with both a valid result array and with a NULL `result` pointer value. The latter is useful in situations where the smCount will end up being zero, which is an invalid value to create a result entry with, but allowed for discovery purposes when the `result` is NULL. + +The `groupParams` array is evaluated from index 0 to `nbGroups` \- 1. For each index in the `groupParams` array, the API will evaluate which SMs may be a good fit based on constraints and assign those SMs to `result`. This evaluation order is important to consider when using discovery mode, as it helps discover the remaining SMs. + +For a valid call: + + * `result` should point to a `CUdevResource` array of size `nbGroups`, or alternatively, may be NULL, if the developer wishes for only the groupParams entries to be updated + + + * `input` should be a valid CU_DEV_RESOURCE_TYPE_SM resource that originates from querying the green context, device context, or device. + + + * The `remainder` group may be NULL. + + + * There are no API `flags` at this time, so the value passed in should be 0. + + + * A CU_DEV_SM_RESOURCE_GROUP_PARAMS array of size `nbGroups`. Each entry must be zero-initialized. + * `smCount:` must be either 0 or in the range of [2,inputSmCount] where inputSmCount is the amount of SMs the `input` resource has. `smCount` must be a multiple of 2, as well as a multiple of `coscheduledSmCount`. When assigning SMs to a group (and if results are expected by having the `result` parameter set), `smCount` cannot end up with 0 or a value less than `coscheduledSmCount` otherwise CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION will be returned. + + * `coscheduledSmCount:` allows grouping SMs together in order to be able to launch clusters on Compute Architecture 9.0+. The default value may be queried from the device’s CU_DEV_RESOURCE_TYPE_SM resource (8 on Compute Architecture 9.0+ and 2 otherwise). The maximum is 32 on Compute Architecture 9.0+ and 2 otherwise. + + * `preferredCoscheduledSmCount:` Attempts to merge `coscheduledSmCount` groups into larger groups, in order to make use of `preferredClusterDimensions` on Compute Architecture 10.0+. The default value is set to `coscheduledSmCount`. + + * `flags:` + * `CU_DEV_SM_RESOURCE_SPLIT_BACKFILL:` lets `smCount` be a non-multiple of `coscheduledSmCount`, filling the difference between SM count and already assigned co-scheduled groupings with other SMs. This lets any resulting group behave similar to the `remainder` group for example. + + +**Example params and their effect:** + +A groupParams array element is defined in the following order: + + + ‎ { .smCount, .coscheduledSmCount, .preferredCoscheduledSmCount, .flags, \/\* .reserved \*\/ } + + + ‎// Example 1 + // Will discover how many SMs there are, that are co-scheduled in groups of smCoscheduledAlignment. + // The rest is placed in the optional remainder. + CU_DEV_SM_RESOURCE_GROUP_PARAMS params { 0, 0, 0, 0 }; + + + ‎// Example 2 + // Assuming the device has 10+ SMs, the result will have 10 SMs that are co-scheduled in groups of 2 SMs. + // The rest is placed in the optional remainder. + CU_DEV_SM_RESOURCE_GROUP_PARAMS params { 10, 2, 0, 0}; + // Setting the coscheduledSmCount to 2 guarantees that we can always have a valid result + // as long as the SM count is less than or equal to the input resource SM count. + + + ‎// Example 3 + // A single piece is split-off, but instead of assigning the rest to the remainder, a second group contains everything else + // This assumes the device has 10+ SMs (8 of which are coscheduled in groups of 4) + // otherwise the second group could end up with 0 SMs, which is not allowed. + CU_DEV_SM_RESOURCE_GROUP_PARAMS params { {8, 4, 0, 0}, {0, 2, 0, CU_DEV_SM_RESOURCE_SPLIT_BACKFILL } } + +The difference between a catch-all param group as the last entry and the remainder is in two aspects: + + * The remainder may be NULL / _TYPE_INVALID (if there are no SMs remaining), while a result group must always be valid. + + * The remainder does not have a structure, while the result group will always need to adhere to a structure of coscheduledSmCount (even if its just 2), and therefore must always have enough coscheduled SMs to cover that requirement (even with the `CU_DEV_SM_RESOURCE_SPLIT_BACKFILL` flag enabled). + + +Splitting an input into N groups, can be accomplished by repeatedly splitting off 1 group and re-splitting the remainder (a bisect operation). However, it's recommended to accomplish this with a single call wherever possible. + +CUresult cuDevSmResourceSplitByCount ( CUdevResource* result, unsigned int* nbGroups, const CUdevResource* input, CUdevResource* remainder, unsigned int flags, unsigned int minCount ) + + +Splits `CU_DEV_RESOURCE_TYPE_SM` resources. + +###### Parameters + +`result` + \- Output array of `CUdevResource` resources. Can be NULL to query the number of groups. +`nbGroups` + \- This is a pointer, specifying the number of groups that would be or should be created as described below. +`input` + \- Input SM resource to be split. Must be a valid `CU_DEV_RESOURCE_TYPE_SM` resource. +`remainder` + \- If the input resource cannot be cleanly split among `nbGroups`, the remainder is placed in here. Can be ommitted (NULL) if the user does not need the remaining set. +`flags` + \- Flags specifying how these partitions are used or which constraints to abide by when splitting the input. Zero is valid for default behavior. +`minCount` + \- Minimum number of SMs required + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION + +###### Description + +Splits `CU_DEV_RESOURCE_TYPE_SM` resources into `nbGroups`, adhering to the minimum SM count specified in `minCount` and the usage flags in `flags`. If `result` is NULL, the API simulates a split and provides the amount of groups that would be created in `nbGroups`. Otherwise, `nbGroups` must point to the amount of elements in `result` and on return, the API will overwrite `nbGroups` with the amount actually created. The groups are written to the array in `result`. `nbGroups` can be less than the total amount if a smaller number of groups is needed. + +This API is used to spatially partition the input resource. The input resource needs to come from one of cuDeviceGetDevResource, cuCtxGetDevResource, or cuGreenCtxGetDevResource. A limitation of the API is that the output results cannot be split again without first creating a descriptor and a green context with that descriptor. + +When creating the groups, the API will take into account the performance and functional characteristics of the input resource, and guarantee a split that will create a disjoint set of symmetrical partitions. This may lead to fewer groups created than purely dividing the total SM count by the `minCount` due to cluster requirements or alignment and granularity requirements for the minCount. These requirements can be queried with cuDeviceGetDevResource, cuCtxGetDevResource, and cuGreenCtxGetDevResource for CU_DEV_RESOURCE_TYPE_SM, using the `minSmPartitionSize` and `smCoscheduledAlignment` fields to determine minimum partition size and alignment granularity, respectively. + +The `remainder` set does not have the same functional or performance guarantees as the groups in `result`. Its use should be carefully planned and future partitions of the `remainder` set are discouraged. + +The following flags are supported: + + * `CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING` : Lower the minimum SM count and alignment, and treat each SM independent of its hierarchy. This allows more fine grained partitions but at the cost of advanced features (such as large clusters on compute capability 9.0+). + + * `CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE` : Compute Capability 9.0+ only. Attempt to create groups that may allow for maximally sized thread clusters. This can be queried post green context creation using cuOccupancyMaxPotentialClusterSize and launch configuration \(config\), return the maximum cluster size in *clusterSize."). + + +A successful API call must either have: + + * A valid array of `result` pointers of size passed in `nbGroups`, with `input` of type `CU_DEV_RESOURCE_TYPE_SM`. Value of `minCount` must be between 0 and the SM count specified in `input`. `remainder` may be NULL. + + * NULL passed in for `result`, with a valid integer pointer in `nbGroups` and `input` of type `CU_DEV_RESOURCE_TYPE_SM`. Value of `minCount` must be between 0 and the SM count specified in `input`. `remainder` may be NULL. This queries the number of groups that would be created by the API. + + +Note: The API is not supported on 32-bit platforms. + +CUresult cuDeviceGetDevResource ( CUdevice device, CUdevResource* resource, CUdevResourceType type ) + + +Get device resources. + +###### Parameters + +`device` + \- Device to get resource for +`resource` + \- Output pointer to a CUdevResource structure +`type` + \- Type of resource to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Get the `type` resources available to the `device`. This may often be the starting point for further partitioning or configuring of resources. + +Note: The API is not supported on 32-bit platforms. + +CUresult cuGreenCtxCreate ( CUgreenCtx* phCtx, CUdevResourceDesc desc, CUdevice dev, unsigned int flags ) + + +Creates a green context with a specified set of resources. + +###### Parameters + +`phCtx` + \- Pointer for the output handle to the green context +`desc` + \- Descriptor generated via cuDevResourceGenerateDesc which contains the set of resources to be used +`dev` + \- Device on which to create the green context. +`flags` + \- One of the supported green context creation flags. `CU_GREEN_CTX_DEFAULT_STREAM` is required. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +This API creates a green context with the resources specified in the descriptor `desc` and returns it in the handle represented by `phCtx`. This API will retain the primary context on device `dev`, which will is released when the green context is destroyed. It is advised to have the primary context active before calling this API to avoid the heavy cost of triggering primary context initialization and deinitialization multiple times. + +The API does not set the green context current. In order to set it current, you need to explicitly set it current by first converting the green context to a CUcontext using cuCtxFromGreenCtx and subsequently calling cuCtxSetCurrent / cuCtxPushCurrent. It should be noted that a green context can be current to only one thread at a time. There is no internal synchronization to make API calls accessing the same green context from multiple threads work. + +Note: The API is not supported on 32-bit platforms. + +The supported flags are: + + * `CU_GREEN_CTX_DEFAULT_STREAM` : Creates a default stream to use inside the green context. Required. + + +CUresult cuGreenCtxDestroy ( CUgreenCtx hCtx ) + + +Destroys a green context. + +###### Parameters + +`hCtx` + \- Green context to be destroyed + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Destroys the green context, releasing the primary context of the device that this green context was created for. Any resources provisioned for this green context (that were initially available via the resource descriptor) are released as well. The API does not destroy streams created via cuGreenCtxStreamCreate, cuStreamCreate, or cuStreamCreateWithPriority. Users are expected to destroy these streams explicitly using cuStreamDestroy to avoid resource leaks. Once the green context is destroyed, any subsequent API calls involving these streams will return CUDA_ERROR_STREAM_DETACHED with the exception of the following APIs: + + * cuStreamDestroy. + + +Additionally, the API will invalidate all active captures on these streams. + +CUresult cuGreenCtxGetDevResource ( CUgreenCtx hCtx, CUdevResource* resource, CUdevResourceType type ) + + +Get green context resources. + +###### Parameters + +`hCtx` + \- Green context to get resource for +`resource` + \- Output pointer to a CUdevResource structure +`type` + \- Type of resource to retrieve + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Get the `type` resources available to the green context represented by `hCtx` + +CUresult cuGreenCtxGetId ( CUgreenCtx greenCtx, unsigned long long* greenCtxId ) + + +Returns the unique Id associated with the green context supplied. + +###### Parameters + +`greenCtx` + \- Green context for which to obtain the Id +`greenCtxId` + \- Pointer to store the Id of the green context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_CONTEXT_IS_DESTROYED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `greenCtxId` the unique Id which is associated with a given green context. The Id is unique for the life of the program for this instance of CUDA. If green context is supplied as NULL and the current context is set to a green context, the Id of the current green context is returned. + +CUresult cuGreenCtxRecordEvent ( CUgreenCtx hCtx, CUevent hEvent ) + + +Records an event. + +###### Parameters + +`hCtx` + \- Green context to record event for +`hEvent` + \- Event to record + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Captures in `hEvent` all the activities of the green context of `hCtx` at the time of this call. `hEvent` and `hCtx` must be from the same primary context otherwise CUDA_ERROR_INVALID_HANDLE is returned. Calls such as cuEventQuery() or cuGreenCtxWaitEvent() will then examine or wait for completion of the work that was captured. Uses of `hCtx` after this call do not modify `hEvent`. + +The API will return CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED if the specified green context `hCtx` has a stream in the capture mode. In such a case, the call will invalidate all the conflicting captures. + +CUresult cuGreenCtxStreamCreate ( CUstream* phStream, CUgreenCtx greenCtx, unsigned int flags, int priority ) + + +Create a stream for use in the green context. + +###### Parameters + +`phStream` + \- Returned newly created stream +`greenCtx` + \- Green context for which to create the stream for +`flags` + \- Flags for stream creation. `CU_STREAM_NON_BLOCKING` must be specified. +`priority` + \- Stream priority. Lower numbers represent higher priorities. See cuCtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates a stream for use in the specified green context `greenCtx` and returns a handle in `phStream`. The stream can be destroyed by calling cuStreamDestroy(). Note that the API ignores the context that is current to the calling thread and creates a stream in the specified green context `greenCtx`. + +The supported values for `flags` are: + + * CU_STREAM_NON_BLOCKING: This must be specified. It indicates that work running in the created stream may run concurrently with work in the default stream, and that the created stream should perform no implicit synchronization with the default stream. + + +Specifying `priority` affects the scheduling priority of work in the stream. Priorities provide a hint to preferentially run work with higher priority when possible, but do not preempt already-running work or provide any other functional guarantee on execution order. `priority` follows a convention where lower numbers represent higher priorities. '0' represents default priority. The range of meaningful numerical priorities can be queried using cuCtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by cuCtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range. + + * * In the current implementation, only compute kernels launched in priority streams are affected by the stream's priority. Stream priorities have no effect on host-to-device and device-to-host memory operations. + + +CUresult cuGreenCtxWaitEvent ( CUgreenCtx hCtx, CUevent hEvent ) + + +Make a green context wait on an event. + +###### Parameters + +`hCtx` + \- Green context to wait +`hEvent` + \- Event to wait on + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED + +###### Description + +Makes all future work submitted to green context `hCtx` wait for all work captured in `hEvent`. The synchronization will be performed on the device and will not block the calling CPU thread. See cuGreenCtxRecordEvent() or cuEventRecord(), for details on what is captured by an event. + + * `hEvent` may be from a different context or device than `hCtx`. + + * The API will return CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED and invalidate the capture if the specified event `hEvent` is part of an ongoing capture sequence or if the specified green context `hCtx` has a stream in the capture mode. + + +CUresult cuStreamGetDevResource ( CUstream hStream, CUdevResource* resource, CUdevResourceType type ) + + +Get stream resources. + +###### Parameters + +`hStream` + \- Stream to get resource for +`resource` + \- Output pointer to a CUdevResource structure +`type` + \- Type of resource to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_RESOURCE_TYPE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Get the `type` resources available to the `hStream` and store them in `resource`. + +Note: The API will return CUDA_ERROR_INVALID_RESOURCE_TYPE is `type` is `CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG` or `CU_DEV_RESOURCE_TYPE_WORKQUEUE`. + +CUresult cuStreamGetGreenCtx ( CUstream hStream, CUgreenCtx* phCtx ) + + +Query the green context associated with a stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`phCtx` + \- Returned green context associated with the stream + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns the CUDA green context that the stream is associated with, or NULL if the stream is not associated with any green context. + +The stream handle `hStream` can refer to any of the following: + + * a stream created via any of the CUDA driver APIs such as cuStreamCreate, cuStreamCreateWithPriority and cuGreenCtxStreamCreate, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. If during stream creation the context that was active in the calling thread was obtained with cuCtxFromGreenCtx, that green context is returned in `phCtx`. Otherwise, `*phCtx` is set to NULL instead. + + * special stream such as the NULL stream or CU_STREAM_LEGACY. In that case if context that is active in the calling thread was obtained with cuCtxFromGreenCtx, that green context is returned. Otherwise, `*phCtx` is set to NULL instead. + + +Passing an invalid handle will result in undefined behavior. + + diff --git a/content/cuda/docs/driver-initialize/DOC.md b/content/cuda/docs/driver-initialize/DOC.md new file mode 100644 index 00000000..828aa5eb --- /dev/null +++ b/content/cuda/docs/driver-initialize/DOC.md @@ -0,0 +1,39 @@ +--- +name: driver-initialize +description: '**Source:** group__CUDA__INITIALIZE.html#group__CUDA__INITIALIZE' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.3. Initialization + +**Source:** group__CUDA__INITIALIZE.html#group__CUDA__INITIALIZE + + +### Functions + +CUresult cuInit ( unsigned int Flags ) + + +Initialize the CUDA driver API Initializes the driver API and must be called before any other function from the driver API in the current process. Currently, the `Flags` parameter must be 0. If cuInit() has not been called, any function from the driver API will return CUDA_ERROR_NOT_INITIALIZED. + +###### Parameters + +`Flags` + \- Initialization flag for CUDA. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_SYSTEM_DRIVER_MISMATCH, CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE + +###### Description + +Note: cuInit preloads various libraries needed for JIT compilation. To opt-out of this behavior, set the environment variable CUDA_FORCE_PRELOAD_LIBRARIES=0. CUDA will lazily load JIT libraries as needed. To disable JIT entirely, set the environment variable CUDA_DISABLE_JIT=1. + + + diff --git a/content/cuda/docs/driver-library/DOC.md b/content/cuda/docs/driver-library/DOC.md new file mode 100644 index 00000000..4b16af3f --- /dev/null +++ b/content/cuda/docs/driver-library/DOC.md @@ -0,0 +1,515 @@ +--- +name: driver-library +description: '**Source:** group__CUDA__LIBRARY.html#group__CUDA__LIBRARY' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.12. Library Management + +**Source:** group__CUDA__LIBRARY.html#group__CUDA__LIBRARY + + +### Functions + +CUresult cuKernelGetAttribute ( int* pi, CUfunction_attribute attrib, CUkernel kernel, CUdevice dev ) + + +Returns information about a kernel. + +###### Parameters + +`pi` + \- Returned attribute value +`attrib` + \- Attribute requested +`kernel` + \- Kernel to query attribute of +`dev` + \- Device to query attribute of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*pi` the integer value of the attribute `attrib` for the kernel `kernel` for the requested device `dev`. The supported attributes are: + + * CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK: The maximum number of threads per block, beyond which a launch of the kernel would fail. This number depends on both the kernel and the requested device. + + * CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES: The size in bytes of statically-allocated shared memory per block required by this kernel. This does not include dynamically-allocated shared memory requested by the user at runtime. + + * CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES: The size in bytes of user-allocated constant memory required by this kernel. + + * CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES: The size in bytes of local memory used by each thread of this kernel. + + * CU_FUNC_ATTRIBUTE_NUM_REGS: The number of registers used by each thread of this kernel. + + * CU_FUNC_ATTRIBUTE_PTX_VERSION: The PTX virtual architecture version for which the kernel was compiled. This value is the major PTX version * 10 + the minor PTX version, so a PTX version 1.3 function would return the value 13. Note that this may return the undefined value of 0 for cubins compiled prior to CUDA 3.0. + + * CU_FUNC_ATTRIBUTE_BINARY_VERSION: The binary architecture version for which the kernel was compiled. This value is the major binary version * 10 + the minor binary version, so a binary version 1.3 function would return the value 13. Note that this will return a value of 10 for legacy cubins that do not have a properly-encoded binary architecture version. + + * CU_FUNC_CACHE_MODE_CA: The attribute to indicate whether the kernel has been compiled with user specified option "-Xptxas \--dlcm=ca" set. + + * CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: The maximum size in bytes of dynamically-allocated shared memory. + + * CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: Preferred shared memory-L1 cache split ratio in percent of total shared memory. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET: If this attribute is set, the kernel must launch with a valid cluster size specified. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH: The required cluster width in blocks. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT: The required cluster height in blocks. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH: The required cluster depth in blocks. + + * CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. A non-portable cluster size may only function on the specific SKUs the program is tested on. The launch might fail if the program is run on a different hardware platform. CUDA API provides cudaOccupancyMaxActiveClusters to assist with checking whether the desired size can be launched on the current device. A portable cluster size is guaranteed to be functional on all compute capabilities higher than the target compute capability. The portable cluster size for sm_90 is 8 blocks per cluster. This value may increase for future compute capabilities. The specific hardware unit may support higher cluster sizes that’s not guaranteed to be portable. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE: The block scheduling policy of a function. The value type is CUclusterSchedulingPolicy. + + +If another thread is trying to set the same attribute on the same device using cuKernelSetAttribute() simultaneously, the attribute query will give the old or new value depending on the interleavings chosen by the OS scheduler and memory consistency. + +CUresult cuKernelGetFunction ( CUfunction* pFunc, CUkernel kernel ) + + +Returns a function handle. + +###### Parameters + +`pFunc` + \- Returned function handle +`kernel` + \- Kernel to retrieve function for the requested context + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Returns in `pFunc` the handle of the function for the requested kernel `kernel` and the current context. If function handle is not found, the call returns CUDA_ERROR_NOT_FOUND. + +CUresult cuKernelGetLibrary ( CUlibrary* pLib, CUkernel kernel ) + + +Returns a library handle. + +###### Parameters + +`pLib` + \- Returned library handle +`kernel` + \- Kernel to retrieve library handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `pLib` the handle of the library for the requested kernel `kernel` + +CUresult cuKernelGetName ( const char** name, CUkernel hfunc ) + + +Returns the function name for a CUkernel handle. + +###### Parameters + +`name` + \- The returned name of the function +`hfunc` + \- The function handle to retrieve the name for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `**name` the function name associated with the kernel handle `hfunc` . The function name is returned as a null-terminated string. The returned name is only valid when the kernel handle is valid. If the library is unloaded or reloaded, one must call the API again to get the updated name. This API may return a mangled name if the function is not declared as having C linkage. If either `**name` or `hfunc` is NULL, CUDA_ERROR_INVALID_VALUE is returned. + + + +CUresult cuKernelGetParamInfo ( CUkernel kernel, size_t paramIndex, size_t* paramOffset, size_t* paramSize ) + + +Returns the offset and size of a kernel parameter in the device-side parameter layout. + +###### Parameters + +`kernel` + \- The kernel to query +`paramIndex` + \- The parameter index to query +`paramOffset` + \- Returns the offset into the device-side parameter layout at which the parameter resides +`paramSize` + \- Optionally returns the size of the parameter in the device-side parameter layout + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Queries the kernel parameter at `paramIndex` into `kernel's` list of parameters, and returns in `paramOffset` and `paramSize` the offset and size, respectively, where the parameter will reside in the device-side parameter layout. This information can be used to update kernel node parameters from the device via cudaGraphKernelNodeSetParam() and cudaGraphKernelNodeUpdatesApply(). `paramIndex` must be less than the number of parameters that `kernel` takes. `paramSize` can be set to NULL if only the parameter offset is desired. + +CUresult cuKernelSetAttribute ( CUfunction_attribute attrib, int val, CUkernel kernel, CUdevice dev ) + + +Sets information about a kernel. + +###### Parameters + +`attrib` + \- Attribute requested +`val` + \- Value to set +`kernel` + \- Kernel to set attribute of +`dev` + \- Device to set attribute of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +This call sets the value of a specified attribute `attrib` on the kernel `kernel` for the requested device `dev` to an integer value specified by `val`. This function returns CUDA_SUCCESS if the new value of the attribute could be successfully set. If the set fails, this call will return an error. Not all attributes can have values set. Attempting to set a value on a read-only attribute will result in an error (CUDA_ERROR_INVALID_VALUE) + +Note that attributes set using cuFuncSetAttribute() will override the attribute set by this API irrespective of whether the call to cuFuncSetAttribute() is made before or after this API call. However, cuKernelGetAttribute() will always return the attribute value set by this API. + +Supported attributes are: + + * CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: This is the maximum size in bytes of dynamically-allocated shared memory. The value should contain the requested maximum size of dynamically-allocated shared memory. The sum of this value and the function attribute CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES cannot exceed the device attribute CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN. The maximal size of requestable dynamic shared memory may differ by GPU architecture. + + * CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: On devices where the L1 cache and shared memory use the same hardware resources, this sets the shared memory carveout preference, in percent of the total shared memory. See CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR This is only a hint, and the driver can choose a different ratio if required to execute the function. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH: The required cluster width in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT: The required cluster height in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH: The required cluster depth in blocks. The width, height, and depth values must either all be 0 or all be positive. The validity of the cluster dimensions is checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + * CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. + + * CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE: The block scheduling policy of a function. The value type is CUclusterSchedulingPolicy. + + +The API has stricter locking requirements in comparison to its legacy counterpart cuFuncSetAttribute() due to device-wide semantics. If multiple threads are trying to set the same attribute on the same device simultaneously, the attribute setting will depend on the interleavings chosen by the OS scheduler and memory consistency. + +CUresult cuKernelSetCacheConfig ( CUkernel kernel, CUfunc_cache config, CUdevice dev ) + + +Sets the preferred cache configuration for a device kernel. + +###### Parameters + +`kernel` + \- Kernel to configure cache for +`config` + \- Requested cache configuration +`dev` + \- Device to set attribute of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +On devices where the L1 cache and shared memory use the same hardware resources, this sets through `config` the preferred cache configuration for the device kernel `kernel` on the requested device `dev`. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute `kernel`. Any context-wide preference set via cuCtxSetCacheConfig() will be overridden by this per-kernel setting. + +Note that attributes set using cuFuncSetCacheConfig() will override the attribute set by this API irrespective of whether the call to cuFuncSetCacheConfig() is made before or after this API call. + +This setting does nothing on devices where the size of the L1 cache and shared memory are fixed. + +Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point. + +The supported cache configurations are: + + * CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) + + * CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache + + * CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory + + * CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory + + +The API has stricter locking requirements in comparison to its legacy counterpart cuFuncSetCacheConfig() due to device-wide semantics. If multiple threads are trying to set a config on the same device simultaneously, the cache config setting will depend on the interleavings chosen by the OS scheduler and memory consistency. + +CUresult cuLibraryEnumerateKernels ( CUkernel* kernels, unsigned int numKernels, CUlibrary lib ) + + +Retrieve the kernel handles within a library. + +###### Parameters + +`kernels` + \- Buffer where the kernel handles are returned to +`numKernels` + \- Maximum number of kernel handles may be returned to the buffer +`lib` + \- Library to query from + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `kernels` a maximum number of `numKernels` kernel handles within `lib`. The returned kernel handle becomes invalid when the library is unloaded. + +CUresult cuLibraryGetGlobal ( CUdeviceptr* dptr, size_t* bytes, CUlibrary library, const char* name ) + + +Returns a global device pointer. + +###### Parameters + +`dptr` + \- Returned global device pointer for the requested context +`bytes` + \- Returned global size in bytes +`library` + \- Library to retrieve global from +`name` + \- Name of global to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Returns in `*dptr` and `*bytes` the base pointer and size of the global with name `name` for the requested library `library` and the current context. If no global for the requested name `name` exists, the call returns CUDA_ERROR_NOT_FOUND. One of the parameters `dptr` or `bytes` (not both) can be NULL in which case it is ignored. + +CUresult cuLibraryGetKernel ( CUkernel* pKernel, CUlibrary library, const char* name ) + + +Returns a kernel handle. + +###### Parameters + +`pKernel` + \- Returned kernel handle +`library` + \- Library to retrieve kernel from +`name` + \- Name of kernel to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `pKernel` the handle of the kernel with name `name` located in library `library`. If kernel handle is not found, the call returns CUDA_ERROR_NOT_FOUND. + +CUresult cuLibraryGetKernelCount ( unsigned int* count, CUlibrary lib ) + + +Returns the number of kernels within a library. + +###### Parameters + +`count` + \- Number of kernels found within the library +`lib` + \- Library to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `count` the number of kernels in `lib`. + +CUresult cuLibraryGetManaged ( CUdeviceptr* dptr, size_t* bytes, CUlibrary library, const char* name ) + + +Returns a pointer to managed memory. + +###### Parameters + +`dptr` + \- Returned pointer to the managed memory +`bytes` + \- Returned memory size in bytes +`library` + \- Library to retrieve managed memory from +`name` + \- Name of managed memory to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `*dptr` and `*bytes` the base pointer and size of the managed memory with name `name` for the requested library `library`. If no managed memory with the requested name `name` exists, the call returns CUDA_ERROR_NOT_FOUND. One of the parameters `dptr` or `bytes` (not both) can be NULL in which case it is ignored. Note that managed memory for library `library` is shared across devices and is registered when the library is loaded into atleast one context. + +CUresult cuLibraryGetModule ( CUmodule* pMod, CUlibrary library ) + + +Returns a module handle. + +###### Parameters + +`pMod` + \- Returned module handle +`library` + \- Library to retrieve module from + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Returns in `pMod` the module handle associated with the current context located in library `library`. If module handle is not found, the call returns CUDA_ERROR_NOT_FOUND. + +CUresult cuLibraryGetUnifiedFunction ( void** fptr, CUlibrary library, const char* symbol ) + + +Returns a pointer to a unified function. + +###### Parameters + +`fptr` + \- Returned pointer to a unified function +`library` + \- Library to retrieve function pointer memory from +`symbol` + \- Name of function pointer to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `*fptr` the function pointer to a unified function denoted by `symbol`. If no unified function with name `symbol` exists, the call returns CUDA_ERROR_NOT_FOUND. If there is no device with attribute CU_DEVICE_ATTRIBUTE_UNIFIED_FUNCTION_POINTERS present in the system, the call may return CUDA_ERROR_NOT_FOUND. + +CUresult cuLibraryLoadData ( CUlibrary* library, const void* code, CUjit_option* jitOptions, void** jitOptionsValues, unsigned int numJitOptions, CUlibraryOption* libraryOptions, void** libraryOptionValues, unsigned int numLibraryOptions ) + + +Load a library with specified code and options. + +###### Parameters + +`library` + \- Returned library +`code` + \- Code to load +`jitOptions` + \- Options for JIT +`jitOptionsValues` + \- Option values for JIT +`numJitOptions` + \- Number of options +`libraryOptions` + \- Options for loading +`libraryOptionValues` + \- Option values for loading +`numLibraryOptions` + \- Number of options for loading + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Takes a pointer `code` and loads the corresponding library `library` based on the application defined library loading mode: + + * If module loading is set to EAGER, via the environment variables described in "Module loading", `library` is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with cuLibraryUnload(). + + * If the environment variables are set to LAZY, `library` is not immediately loaded onto all existent contexts and will only be loaded when a function is needed for that context, such as a kernel launch. + + +These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section. + +The `code` may be a cubin or fatbin as output by **nvcc** , or a NULL-terminated PTX, either as output by **nvcc** or hand-written, or Tile IR data. A fatbin should also contain relocatable code when doing separate compilation. + +Options are passed as an array via `jitOptions` and any corresponding parameters are passed in `jitOptionsValues`. The number of total JIT options is supplied via `numJitOptions`. Any outputs will be returned via `jitOptionsValues`. + +Library load options are passed as an array via `libraryOptions` and any corresponding parameters are passed in `libraryOptionValues`. The number of total library load options is supplied via `numLibraryOptions`. + +If the library contains managed variables and no device in the system supports managed variables this call is expected to return CUDA_ERROR_NOT_SUPPORTED + +CUresult cuLibraryLoadFromFile ( CUlibrary* library, const char* fileName, CUjit_option* jitOptions, void** jitOptionsValues, unsigned int numJitOptions, CUlibraryOption* libraryOptions, void** libraryOptionValues, unsigned int numLibraryOptions ) + + +Load a library with specified file and options. + +###### Parameters + +`library` + \- Returned library +`fileName` + \- File to load from +`jitOptions` + \- Options for JIT +`jitOptionsValues` + \- Option values for JIT +`numJitOptions` + \- Number of options +`libraryOptions` + \- Options for loading +`libraryOptionValues` + \- Option values for loading +`numLibraryOptions` + \- Number of options for loading + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Takes a pointer `code` and loads the corresponding library `library` based on the application defined library loading mode: + + * If module loading is set to EAGER, via the environment variables described in "Module loading", `library` is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with cuLibraryUnload(). + + * If the environment variables are set to LAZY, `library` is not immediately loaded onto all existent contexts and will only be loaded when a function is needed for that context, such as a kernel launch. + + +These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section. + +The file should be a cubin file as output by **nvcc** , or a PTX file either as output by **nvcc** or handwritten, or a fatbin file as output by **nvcc** or hand-written, or Tile IR file. A fatbin should also contain relocatable code when doing separate compilation. + +Options are passed as an array via `jitOptions` and any corresponding parameters are passed in `jitOptionsValues`. The number of total options is supplied via `numJitOptions`. Any outputs will be returned via `jitOptionsValues`. + +Library load options are passed as an array via `libraryOptions` and any corresponding parameters are passed in `libraryOptionValues`. The number of total library load options is supplied via `numLibraryOptions`. + +If the library contains managed variables and no device in the system supports managed variables this call is expected to return CUDA_ERROR_NOT_SUPPORTED + +CUresult cuLibraryUnload ( CUlibrary library ) + + +Unloads a library. + +###### Parameters + +`library` + \- Library to unload + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Unloads the library specified with `library` diff --git a/content/cuda/docs/driver-logs/DOC.md b/content/cuda/docs/driver-logs/DOC.md new file mode 100644 index 00000000..e831bd3e --- /dev/null +++ b/content/cuda/docs/driver-logs/DOC.md @@ -0,0 +1,131 @@ +--- +name: driver-logs +description: '**Source:** group__CUDA__LOGS.html#group__CUDA__LOGS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.36. Error Log Management Functions + +**Source:** group__CUDA__LOGS.html#group__CUDA__LOGS + + +### Functions + +CUresult cuLogsCurrent ( CUlogIterator* iterator_out, unsigned int flags ) + + +Sets log iterator to point to the end of log buffer, where the next message would be written. + +###### Parameters + +`iterator_out` + \- Location to store an iterator to the current tail of the logs +`flags` + \- Reserved for future use, must be 0 + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +CUresult cuLogsDumpToFile ( CUlogIterator* iterator, const char* pathToFile, unsigned int flags ) + + +Dump accumulated driver logs into a file. + +###### Parameters + +`iterator` + \- Optional auto-advancing iterator specifying the starting log to read. NULL value dumps all logs. +`pathToFile` + \- Path to output file for dumping logs +`flags` + \- Reserved for future use, must be 0 + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Logs generated by the driver are stored in an internal buffer and can be copied out using this API. This API dumps all driver logs starting from `iterator` into `pathToFile` provided. + + * `iterator` is auto-advancing. Dumping logs will update the value of `iterator` to receive the next generated log. + + * The driver reserves limited memory for storing logs. The oldest logs may be overwritten and become unrecoverable. An indication will appear in the destination outupt if the logs have been truncated. Call dump after each failed API to mitigate this risk. + + +CUresult cuLogsDumpToMemory ( CUlogIterator* iterator, char* buffer, size_t* size, unsigned int flags ) + + +Dump accumulated driver logs into a buffer. + +###### Parameters + +`iterator` + \- Optional auto-advancing iterator specifying the starting log to read. NULL value dumps all logs. +`buffer` + \- Pointer to dump logs +`size` + \- See description +`flags` + \- Reserved for future use, must be 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Logs generated by the driver are stored in an internal buffer and can be copied out using this API. This API dumps driver logs from `iterator` into `buffer` up to the size specified in `*size`. The driver will always null terminate the buffer but there will not be a null character between log entries, only a newline \n. The driver will then return the actual number of bytes written in `*size`, excluding the null terminator. If there are no messages to dump, `*size` will be set to 0 and the function will return CUDA_SUCCESS. If the provided `buffer` is not large enough to hold any messages, `*size` will be set to 0 and the function will return CUDA_ERROR_INVALID_VALUE. + + * `iterator` is auto-advancing. Dumping logs will update the value of `iterator` to receive the next generated log. + + * The driver reserves limited memory for storing logs. The maximum size of the buffer is 25600 bytes. The oldest logs may be overwritten and become unrecoverable. An indication will appear in the destination outupt if the logs have been truncated. Call dump after each failed API to mitigate this risk. + + * If the provided value in `*size` is not large enough to hold all buffered messages, a message will be added at the head of the buffer indicating this. The driver then computes the number of messages it is able to store in `buffer` and writes it out. The final message in `buffer` will always be the most recent log message as of when the API is called. + + +CUresult cuLogsRegisterCallback ( CUlogsCallback callbackFunc, void* userData, CUlogsCallbackHandle* callback_out ) + + +Register a callback function to receive error log messages. + +###### Parameters + +`callbackFunc` + \- The function to register as a callback +`userData` + \- A generic pointer to user data. This is passed into the callback function. +`callback_out` + \- Optional location to store the callback handle after it is registered + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +CUresult cuLogsUnregisterCallback ( CUlogsCallbackHandle callback ) + + +Unregister a log message callback. + +###### Parameters + +`callback` + \- The callback instance to unregister from receiving log messages + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + diff --git a/content/cuda/docs/driver-malloc--async/DOC.md b/content/cuda/docs/driver-malloc--async/DOC.md new file mode 100644 index 00000000..116d3830 --- /dev/null +++ b/content/cuda/docs/driver-malloc--async/DOC.md @@ -0,0 +1,425 @@ +--- +name: driver-malloc--async +description: '**Source:** group__CUDA__MALLOC__ASYNC.html#group__CUDA__MALLOC__ASYNC' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.15. Stream Ordered Memory Allocator + +**Source:** group__CUDA__MALLOC__ASYNC.html#group__CUDA__MALLOC__ASYNC + + +### Functions + +CUresult cuMemAllocAsync ( CUdeviceptr* dptr, size_t bytesize, CUstream hStream ) + + +Allocates memory with stream ordered semantics. + +###### Parameters + +`dptr` + \- Returned device pointer +`bytesize` + \- Number of bytes to allocate +`hStream` + \- The stream establishing the stream ordering contract and the memory pool to allocate from + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Inserts an allocation operation into `hStream`. A pointer to the allocated memory is returned immediately in *dptr. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the memory pool current to the stream's device. + + * The default memory pool of a device contains device memory from that device. + + * Basic stream ordering allows future work submitted into the same stream to use the allocation. Stream query, stream synchronize, and CUDA events can be used to guarantee that the allocation operation completes before work submitted in a separate stream runs. + + * During stream capture, this function results in the creation of an allocation node. In this case, the allocation is owned by the graph instead of the memory pool. The memory pool's properties are used to set the node's creation parameters. + + +CUresult cuMemAllocFromPoolAsync ( CUdeviceptr* dptr, size_t bytesize, CUmemoryPool pool, CUstream hStream ) + + +Allocates memory from a specified pool with stream ordered semantics. + +###### Parameters + +`dptr` + \- Returned device pointer +`bytesize` + \- Number of bytes to allocate +`pool` + \- The pool to allocate from +`hStream` + \- The stream establishing the stream ordering semantic + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Inserts an allocation operation into `hStream`. A pointer to the allocated memory is returned immediately in *dptr. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the specified memory pool. + + * The specified memory pool may be from a device different than that of the specified `hStream`. + + + * Basic stream ordering allows future work submitted into the same stream to use the allocation. Stream query, stream synchronize, and CUDA events can be used to guarantee that the allocation operation completes before work submitted in a separate stream runs. + + +During stream capture, this function results in the creation of an allocation node. In this case, the allocation is owned by the graph instead of the memory pool. The memory pool's properties are used to set the node's creation parameters. + +CUresult cuMemFreeAsync ( CUdeviceptr dptr, CUstream hStream ) + + +Frees memory with stream ordered semantics. + +###### Parameters + +`dptr` + \- memory to free +`hStream` + \- The stream establishing the stream ordering contract. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Inserts a free operation into `hStream`. The allocation must not be accessed after stream execution reaches the free. After this API returns, accessing the memory from any subsequent work launched on the GPU or querying its pointer attributes results in undefined behavior. + +During stream capture, this function results in the creation of a free node and must therefore be passed the address of a graph allocation. + +CUresult cuMemGetDefaultMemPool ( CUmemoryPool* pool_out, CUmemLocation* location, CUmemAllocationType type ) + + +Returns the default memory pool for a given location and allocation type. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZEDCUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +The memory location can be of one of CU_MEM_LOCATION_TYPE_DEVICE, CU_MEM_LOCATION_TYPE_HOST or CU_MEM_LOCATION_TYPE_HOST_NUMA. The allocation type can be one of CU_MEM_ALLOCATION_TYPE_PINNED or CU_MEM_ALLOCATION_TYPE_MANAGED. When the allocation type is CU_MEM_ALLOCATION_TYPE_MANAGED, the location type can also be CU_MEM_LOCATION_TYPE_NONE to indicate no preferred location for the managed memory pool. In all other cases, the call returns CUDA_ERROR_INVALID_VALUE. + +CUresult cuMemGetMemPool ( CUmemoryPool* pool, CUmemLocation* location, CUmemAllocationType type ) + + +Gets the current memory pool for a memory location and of a particular allocation type. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +The memory location can be of one of CU_MEM_LOCATION_TYPE_DEVICE, CU_MEM_LOCATION_TYPE_HOST or CU_MEM_LOCATION_TYPE_HOST_NUMA. The allocation type can be one of CU_MEM_ALLOCATION_TYPE_PINNED or CU_MEM_ALLOCATION_TYPE_MANAGED. When the allocation type is CU_MEM_ALLOCATION_TYPE_MANAGED, the location type can also be CU_MEM_LOCATION_TYPE_NONE to indicate no preferred location for the managed memory pool. In all other cases, the call returns CUDA_ERROR_INVALID_VALUE + +Returns the last pool provided to cuMemSetMemPool or cuDeviceSetMemPool for this location and allocation type or the location's default memory pool if cuMemSetMemPool or cuDeviceSetMemPool for that allocType and location has never been called. By default the current mempool of a location is the default mempool for a device. Otherwise the returned pool must have been set with cuDeviceSetMemPool. + +CUresult cuMemPoolCreate ( CUmemoryPool* pool, const CUmemPoolProps* poolProps ) + + +Creates a memory pool. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Creates a CUDA memory pool and returns the handle in `pool`. The `poolProps` determines the properties of the pool such as the backing device and IPC capabilities. + +To create a memory pool for HOST memory not targeting a specific NUMA node, applications must set set CUmemPoolProps::CUmemLocation::type to CU_MEM_LOCATION_TYPE_HOST. CUmemPoolProps::CUmemLocation::id is ignored for such pools. Pools created with the type CU_MEM_LOCATION_TYPE_HOST are not IPC capable and CUmemPoolProps::handleTypes must be 0, any other values will result in CUDA_ERROR_INVALID_VALUE. To create a memory pool targeting a specific host NUMA node, applications must set CUmemPoolProps::CUmemLocation::type to CU_MEM_LOCATION_TYPE_HOST_NUMA and CUmemPoolProps::CUmemLocation::id must specify the NUMA ID of the host memory node. Specifying CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT as the CUmemPoolProps::CUmemLocation::type will result in CUDA_ERROR_INVALID_VALUE. By default, the pool's memory will be accessible from the device it is allocated on. In the case of pools created with CU_MEM_LOCATION_TYPE_HOST_NUMA or CU_MEM_LOCATION_TYPE_HOST, their default accessibility will be from the host CPU. Applications can control the maximum size of the pool by specifying a non-zero value for CUmemPoolProps::maxSize. If set to 0, the maximum size of the pool will default to a system dependent value. + +Applications that intend to use CU_MEM_HANDLE_TYPE_FABRIC based memory sharing must ensure: (1) `nvidia-caps-imex-channels` character device is created by the driver and is listed under /proc/devices (2) have at least one IMEX channel file accessible by the user launching the application. + +When exporter and importer CUDA processes have been granted access to the same IMEX channel, they can securely share memory. + +The IMEX channel security model works on a per user basis. Which means all processes under a user can share memory if the user has access to a valid IMEX channel. When multi-user isolation is desired, a separate IMEX channel is required for each user. + +These channel files exist in /dev/nvidia-caps-imex-channels/channel* and can be created using standard OS native calls like mknod on Linux. For example: To create channel0 with the major number from /proc/devices users can execute the following command: `mknod /dev/nvidia-caps-imex-channels/channel0 c =""> 0` + +To create a managed memory pool, applications must set CUmemPoolProps::CUmemAllocationType to CU_MEM_ALLOCATION_TYPE_MANAGED. CUmemPoolProps::CUmemAllocationHandleType must also be set to CU_MEM_HANDLE_TYPE_NONE since IPC is not supported. For managed memory pools, CUmemPoolProps::CUmemLocation will be treated as the preferred location for all allocations created from the pool. An application can also set CU_MEM_LOCATION_TYPE_NONE to indicate no preferred location. CUmemPoolProps::maxSize must be set to zero for managed memory pools. CUmemPoolProps::usage should be zero as decompress for managed memory is not supported. For managed memory pools, all devices on the system must have non-zero concurrentManagedAccess. If not, this call returns CUDA_ERROR_NOT_SUPPORTED + +Specifying CU_MEM_HANDLE_TYPE_NONE creates a memory pool that will not support IPC. + +CUresult cuMemPoolDestroy ( CUmemoryPool pool ) + + +Destroys the specified memory pool. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +If any pointers obtained from this pool haven't been freed or the pool has free operations that haven't completed when cuMemPoolDestroy is invoked, the function will return immediately and the resources associated with the pool will be released automatically once there are no more outstanding allocations. + +Destroying the current mempool of a device sets the default mempool of that device as the current mempool for that device. + +A device's default memory pool cannot be destroyed. + +CUresult cuMemPoolExportPointer ( CUmemPoolPtrExportData* shareData_out, CUdeviceptr ptr ) + + +Export data to share a memory pool allocation between processes. + +###### Parameters + +`shareData_out` + \- Returned export data +`ptr` + \- pointer to memory being exported + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Constructs `shareData_out` for sharing a specific allocation from an already shared memory pool. The recipient process can import the allocation with the cuMemPoolImportPointer api. The data is not a handle and may be shared through any IPC mechanism. + +CUresult cuMemPoolExportToShareableHandle ( void* handle_out, CUmemoryPool pool, CUmemAllocationHandleType handleType, unsigned long long flags ) + + +Exports a memory pool to the requested handle type. + +###### Parameters + +`handle_out` + \- Returned OS handle +`pool` + \- pool to export +`handleType` + \- the type of handle to create +`flags` + \- must be 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Given an IPC capable mempool, create an OS handle to share the pool with another process. A recipient process can convert the shareable handle into a mempool with cuMemPoolImportFromShareableHandle. Individual pointers can then be shared with the cuMemPoolExportPointer and cuMemPoolImportPointer APIs. The implementation of what the shareable handle is and how it can be transferred is defined by the requested handle type. + +: To create an IPC capable mempool, create a mempool with a CUmemAllocationHandleType other than CU_MEM_HANDLE_TYPE_NONE. + +CUresult cuMemPoolGetAccess ( CUmemAccess_flags* flags, CUmemoryPool memPool, CUmemLocation* location ) + + +Returns the accessibility of a pool from a device. + +###### Parameters + +`flags` + \- the accessibility of the pool from the specified location +`memPool` + \- the pool being queried +`location` + \- the location accessing the pool + +###### Description + +Returns the accessibility of the pool's memory from the specified location. + +CUresult cuMemPoolGetAttribute ( CUmemoryPool pool, CUmemPool_attribute attr, void* value ) + + +Gets attributes of a memory pool. + +###### Parameters + +`pool` + \- The memory pool to get attributes of +`attr` + \- The attribute to get +`value` + \- Retrieved value + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Supported attributes are: + + * CU_MEMPOOL_ATTR_RELEASE_THRESHOLD: (value type = cuuint64_t) Amount of reserved memory in bytes to hold onto before trying to release memory back to the OS. When more than the release threshold bytes of memory are held by the memory pool, the allocator will try to release memory back to the OS on the next call to stream, event or context synchronize. (default 0) + + * CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES: (value type = int) Allow cuMemAllocAsync to use memory asynchronously freed in another stream as long as a stream ordering dependency of the allocating stream on the free action exists. Cuda events and null stream interactions can create the required stream ordered dependencies. (default enabled) + + * CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled) + + * CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES: (value type = int) Allow cuMemAllocAsync to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released by cuMemFreeAsync (default enabled). + + * CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT: (value type = cuuint64_t) Amount of backing memory currently allocated for the mempool + + * CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH: (value type = cuuint64_t) High watermark of backing memory allocated for the mempool since the last time it was reset. + + * CU_MEMPOOL_ATTR_USED_MEM_CURRENT: (value type = cuuint64_t) Amount of memory from the pool that is currently in use by the application. + + * CU_MEMPOOL_ATTR_USED_MEM_HIGH: (value type = cuuint64_t) High watermark of the amount of memory from the pool that was in use by the application. + + +CUresult cuMemPoolImportFromShareableHandle ( CUmemoryPool* pool_out, void* handle, CUmemAllocationHandleType handleType, unsigned long long flags ) + + +imports a memory pool from a shared handle. + +###### Parameters + +`pool_out` + \- Returned memory pool +`handle` + \- OS handle of the pool to open +`handleType` + \- The type of handle being imported +`flags` + \- must be 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Specific allocations can be imported from the imported pool with cuMemPoolImportPointer. + +If `handleType` is CU_MEM_HANDLE_TYPE_FABRIC and the importer process has not been granted access to the same IMEX channel as the exporter process, this API will error as CUDA_ERROR_NOT_PERMITTED. + +Imported memory pools do not support creating new allocations. As such imported memory pools may not be used in cuDeviceSetMemPool or cuMemAllocFromPoolAsync calls. + +CUresult cuMemPoolImportPointer ( CUdeviceptr* ptr_out, CUmemoryPool pool, CUmemPoolPtrExportData* shareData ) + + +Import a memory pool allocation from another process. + +###### Parameters + +`ptr_out` + \- pointer to imported memory +`pool` + \- pool from which to import +`shareData` + \- data specifying the memory to import + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Returns in `ptr_out` a pointer to the imported memory. The imported memory must not be accessed before the allocation operation completes in the exporting process. The imported memory must be freed from all importing processes before being freed in the exporting process. The pointer may be freed with cuMemFree or cuMemFreeAsync. If cuMemFreeAsync is used, the free must be completed on the importing process before the free operation on the exporting process. + +The cuMemFreeAsync api may be used in the exporting process before the cuMemFreeAsync operation completes in its stream as long as the cuMemFreeAsync in the exporting process specifies a stream with a stream dependency on the importing process's cuMemFreeAsync. + +CUresult cuMemPoolSetAccess ( CUmemoryPool pool, const CUmemAccessDesc* map, size_t count ) + + +Controls visibility of pools between devices. + +###### Parameters + +`pool` + \- The pool being modified +`map` + \- Array of access descriptors. Each descriptor instructs the access to enable for a single gpu. +`count` + \- Number of descriptors in the map array. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +CUresult cuMemPoolSetAttribute ( CUmemoryPool pool, CUmemPool_attribute attr, void* value ) + + +Sets attributes of a memory pool. + +###### Parameters + +`pool` + \- The memory pool to modify +`attr` + \- The attribute to modify +`value` + \- Pointer to the value to assign + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Supported attributes are: + + * CU_MEMPOOL_ATTR_RELEASE_THRESHOLD: (value type = cuuint64_t) Amount of reserved memory in bytes to hold onto before trying to release memory back to the OS. When more than the release threshold bytes of memory are held by the memory pool, the allocator will try to release memory back to the OS on the next call to stream, event or context synchronize. (default 0) + + * CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES: (value type = int) Allow cuMemAllocAsync to use memory asynchronously freed in another stream as long as a stream ordering dependency of the allocating stream on the free action exists. Cuda events and null stream interactions can create the required stream ordered dependencies. (default enabled) + + * CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled) + + * CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES: (value type = int) Allow cuMemAllocAsync to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released by cuMemFreeAsync (default enabled). + + * CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH: (value type = cuuint64_t) Reset the high watermark that tracks the amount of backing memory that was allocated for the memory pool. It is illegal to set this attribute to a non-zero value. + + * CU_MEMPOOL_ATTR_USED_MEM_HIGH: (value type = cuuint64_t) Reset the high watermark that tracks the amount of used memory that was allocated for the memory pool. + + +CUresult cuMemPoolTrimTo ( CUmemoryPool pool, size_t minBytesToKeep ) + + +Tries to release memory back to the OS. + +###### Parameters + +`pool` + \- The memory pool to trim +`minBytesToKeep` + \- If the pool has less than minBytesToKeep reserved, the TrimTo operation is a no-op. Otherwise the pool will be guaranteed to have at least minBytesToKeep bytes reserved after the operation. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Releases memory back to the OS until the pool contains fewer than minBytesToKeep reserved bytes, or there is no more memory that the allocator can safely release. The allocator cannot release OS allocations that back outstanding asynchronous allocations. The OS allocations may happen at different granularity from the user allocations. + + * : Allocations that have not been freed count as outstanding. + + * : Allocations that have been asynchronously freed but whose completion has not been observed on the host (eg. by a synchronize) can count as outstanding. + + +CUresult cuMemSetMemPool ( CUmemLocation* location, CUmemAllocationType type, CUmemoryPool pool ) + + +Sets the current memory pool for a memory location and allocation type. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +The memory location can be of one of CU_MEM_LOCATION_TYPE_DEVICE, CU_MEM_LOCATION_TYPE_HOST or CU_MEM_LOCATION_TYPE_HOST_NUMA. The allocation type can be one of CU_MEM_ALLOCATION_TYPE_PINNED or CU_MEM_ALLOCATION_TYPE_MANAGED. When the allocation type is CU_MEM_ALLOCATION_TYPE_MANAGED, the location type can also be CU_MEM_LOCATION_TYPE_NONE to indicate no preferred location for the managed memory pool. In all other cases, the call returns CUDA_ERROR_INVALID_VALUE. + +When a memory pool is set as the current memory pool, the location parameter should be the same as the location of the pool. The location and allocation type specified must match those of the pool otherwise CUDA_ERROR_INVALID_VALUE is returned. By default, a memory location's current memory pool is its default memory pool that can be obtained via cuMemGetDefaultMemPool. If the location type is CU_MEM_LOCATION_TYPE_DEVICE and the allocation type is CU_MEM_ALLOCATION_TYPE_PINNED, then this API is the equivalent of calling cuDeviceSetMemPool with the location id as the device. For further details on the implications, please refer to the documentation for cuDeviceSetMemPool. + +Use cuMemAllocFromPoolAsync to specify asynchronous allocations from a device different than the one the stream runs on. diff --git a/content/cuda/docs/driver-mem/DOC.md b/content/cuda/docs/driver-mem/DOC.md new file mode 100644 index 00000000..7db08e05 --- /dev/null +++ b/content/cuda/docs/driver-mem/DOC.md @@ -0,0 +1,2983 @@ +--- +name: driver-mem +description: '**Source:** group__CUDA__MEM.html#group__CUDA__MEM' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.13. Memory Management + +**Source:** group__CUDA__MEM.html#group__CUDA__MEM + + +### Classes + +struct + +CUmemDecompressParams + + Structure describing the parameters that compose a single decompression operation. + +### Enumerations + +enum CUmemDecompressAlgorithm + Bitmasks for CU_DEVICE_ATTRIBUTE_MEM_DECOMPRESS_ALGORITHM_MASK. + +### Functions + +CUresult cuArray3DCreate ( CUarray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pAllocateArray ) + + +Creates a 3D CUDA array. + +###### Parameters + +`pHandle` + \- Returned array +`pAllocateArray` + \- 3D array descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a CUDA array according to the CUDA_ARRAY3D_DESCRIPTOR structure `pAllocateArray` and returns a handle to the new CUDA array in `*pHandle`. The CUDA_ARRAY3D_DESCRIPTOR is defined as: + + + ‎ typedef struct { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + CUarray_format Format; + unsigned int NumChannels; + unsigned int Flags; + } CUDA_ARRAY3D_DESCRIPTOR; + +where: + + * `Width`, `Height`, and `Depth` are the width, height, and depth of the CUDA array (in elements); the following types of CUDA arrays can be allocated: + * A 1D array is allocated if `Height` and `Depth` extents are both zero. + + * A 2D array is allocated if only `Depth` extent is zero. + + * A 3D array is allocated if all three extents are non-zero. + + * A 1D layered CUDA array is allocated if only `Height` is zero and the CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 1D array. The number of layers is determined by the depth extent. + + * A 2D layered CUDA array is allocated if all three extents are non-zero and the CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 2D array. The number of layers is determined by the depth extent. + + * A cubemap CUDA array is allocated if all three extents are non-zero and the CUDA_ARRAY3D_CUBEMAP flag is set. `Width` must be equal to `Height`, and `Depth` must be six. A cubemap is a special type of 2D layered CUDA array, where the six layers represent the six faces of a cube. The order of the six layers in memory is the same as that listed in CUarray_cubemap_face. + + * A cubemap layered CUDA array is allocated if all three extents are non-zero, and both, CUDA_ARRAY3D_CUBEMAP and CUDA_ARRAY3D_LAYERED flags are set. `Width` must be equal to `Height`, and `Depth` must be a multiple of six. A cubemap layered CUDA array is a special type of 2D layered CUDA array that consists of a collection of cubemaps. The first six layers represent the first cubemap, the next six layers form the second cubemap, and so on. + + + * Format specifies the format of the elements; CUarray_format is defined as: + + ‎ typedef enum CUarray_format_enum { + CU_AD_FORMAT_UNSIGNED_INT8 = 0x01 + CU_AD_FORMAT_UNSIGNED_INT16 = 0x02 + CU_AD_FORMAT_UNSIGNED_INT32 = 0x03 + CU_AD_FORMAT_SIGNED_INT8 = 0x08 + CU_AD_FORMAT_SIGNED_INT16 = 0x09 + CU_AD_FORMAT_SIGNED_INT32 = 0x0a + CU_AD_FORMAT_HALF = 0x10 + CU_AD_FORMAT_FLOAT = 0x20 + CU_AD_FORMAT_NV12 = 0xb0 + CU_AD_FORMAT_UNORM_INT8X1 = 0xc0 + CU_AD_FORMAT_UNORM_INT8X2 = 0xc1 + CU_AD_FORMAT_UNORM_INT8X4 = 0xc2 + CU_AD_FORMAT_UNORM_INT16X1 = 0xc3 + CU_AD_FORMAT_UNORM_INT16X2 = 0xc4 + CU_AD_FORMAT_UNORM_INT16X4 = 0xc5 + CU_AD_FORMAT_SNORM_INT8X1 = 0xc6 + CU_AD_FORMAT_SNORM_INT8X2 = 0xc7 + CU_AD_FORMAT_SNORM_INT8X4 = 0xc8 + CU_AD_FORMAT_SNORM_INT16X1 = 0xc9 + CU_AD_FORMAT_SNORM_INT16X2 = 0xca + CU_AD_FORMAT_SNORM_INT16X4 = 0xcb + CU_AD_FORMAT_BC1_UNORM = 0x91 + CU_AD_FORMAT_BC1_UNORM_SRGB = 0x92 + CU_AD_FORMAT_BC2_UNORM = 0x93 + CU_AD_FORMAT_BC2_UNORM_SRGB = 0x94 + CU_AD_FORMAT_BC3_UNORM = 0x95 + CU_AD_FORMAT_BC3_UNORM_SRGB = 0x96 + CU_AD_FORMAT_BC4_UNORM = 0x97 + CU_AD_FORMAT_BC4_SNORM = 0x98 + CU_AD_FORMAT_BC5_UNORM = 0x99 + CU_AD_FORMAT_BC5_SNORM = 0x9a + CU_AD_FORMAT_BC6H_UF16 = 0x9b + CU_AD_FORMAT_BC6H_SF16 = 0x9c + CU_AD_FORMAT_BC7_UNORM = 0x9d + CU_AD_FORMAT_BC7_UNORM_SRGB = 0x9e + CU_AD_FORMAT_P010 = 0x9f + CU_AD_FORMAT_P016 = 0xa1 + CU_AD_FORMAT_NV16 = 0xa2 + CU_AD_FORMAT_P210 = 0xa3 + CU_AD_FORMAT_P216 = 0xa4 + CU_AD_FORMAT_YUY2 = 0xa5 + CU_AD_FORMAT_Y210 = 0xa6 + CU_AD_FORMAT_Y216 = 0xa7 + CU_AD_FORMAT_AYUV = 0xa8 + CU_AD_FORMAT_Y410 = 0xa9 + CU_AD_FORMAT_Y416 = 0xb1 + CU_AD_FORMAT_Y444_PLANAR8 = 0xb2 + CU_AD_FORMAT_Y444_PLANAR10 = 0xb3 + CU_AD_FORMAT_YUV444_8bit_SemiPlanar = 0xb4 + CU_AD_FORMAT_YUV444_16bit_SemiPlanar = 0xb5 + CU_AD_FORMAT_UNORM_INT_101010_2 = 0x50 + } CUarray_format; + + + * `NumChannels` specifies the number of packed components per CUDA array element; it may be 1, 2, or 4; + + + * Flags may be set to + * CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA arrays. If this flag is set, `Depth` specifies the number of layers, not the depth of a 3D array. + + * CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to the CUDA array. If this flag is not set, cuSurfRefSetArray will fail when attempting to bind the CUDA array to a surface reference. + + * CUDA_ARRAY3D_CUBEMAP to enable creation of cubemaps. If this flag is set, `Width` must be equal to `Height`, and `Depth` must be six. If the CUDA_ARRAY3D_LAYERED flag is also set, then `Depth` must be a multiple of six. + + * CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA array will be used for texture gather. Texture gather can only be performed on 2D CUDA arrays. + + +`Width`, `Height` and `Depth` must meet certain size requirements as listed in the following table. All values are specified in elements. Note that for brevity's sake, the full name of the device attribute is not specified. For ex., TEXTURE1D_WIDTH refers to the device attribute CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH. + +Note that 2D CUDA arrays have different size requirements if the CUDA_ARRAY3D_TEXTURE_GATHER flag is set. `Width` and `Height` must not be greater than CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH and CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT respectively, in that case. + +**CUDA array type** | **Valid extents that must always be met {(width range in elements), (height range), (depth range)}** | **Valid extents with CUDA_ARRAY3D_SURFACE_LDST set {(width range in elements), (height range), (depth range)}** +---|---|--- +1D | { (1,TEXTURE1D_WIDTH), 0, 0 } | { (1,SURFACE1D_WIDTH), 0, 0 } +2D | { (1,TEXTURE2D_WIDTH), (1,TEXTURE2D_HEIGHT), 0 } | { (1,SURFACE2D_WIDTH), (1,SURFACE2D_HEIGHT), 0 } +3D | { (1,TEXTURE3D_WIDTH), (1,TEXTURE3D_HEIGHT), (1,TEXTURE3D_DEPTH) } OR { (1,TEXTURE3D_WIDTH_ALTERNATE), (1,TEXTURE3D_HEIGHT_ALTERNATE), (1,TEXTURE3D_DEPTH_ALTERNATE) } | { (1,SURFACE3D_WIDTH), (1,SURFACE3D_HEIGHT), (1,SURFACE3D_DEPTH) } +1D Layered | { (1,TEXTURE1D_LAYERED_WIDTH), 0, (1,TEXTURE1D_LAYERED_LAYERS) } | { (1,SURFACE1D_LAYERED_WIDTH), 0, (1,SURFACE1D_LAYERED_LAYERS) } +2D Layered | { (1,TEXTURE2D_LAYERED_WIDTH), (1,TEXTURE2D_LAYERED_HEIGHT), (1,TEXTURE2D_LAYERED_LAYERS) } | { (1,SURFACE2D_LAYERED_WIDTH), (1,SURFACE2D_LAYERED_HEIGHT), (1,SURFACE2D_LAYERED_LAYERS) } +Cubemap | { (1,TEXTURECUBEMAP_WIDTH), (1,TEXTURECUBEMAP_WIDTH), 6 } | { (1,SURFACECUBEMAP_WIDTH), (1,SURFACECUBEMAP_WIDTH), 6 } +Cubemap Layered | { (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_LAYERS) } | { (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_LAYERS) } + +Here are examples of CUDA array descriptions: + +Description for a CUDA array of 2048 floats: + + + ‎ CUDA_ARRAY3D_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_FLOAT; + desc.NumChannels = 1; + desc.Width = 2048; + desc.Height = 0; + desc.Depth = 0; + +Description for a 64 x 64 CUDA array of floats: + + + ‎ CUDA_ARRAY3D_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_FLOAT; + desc.NumChannels = 1; + desc.Width = 64; + desc.Height = 64; + desc.Depth = 0; + +Description for a `width` x `height` x `depth` CUDA array of 64-bit, 4x16-bit float16's: + + + ‎ CUDA_ARRAY3D_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_HALF; + desc.NumChannels = 4; + desc.Width = width; + desc.Height = height; + desc.Depth = depth; + +CUresult cuArray3DGetDescriptor ( CUDA_ARRAY3D_DESCRIPTOR* pArrayDescriptor, CUarray hArray ) + + +Get a 3D CUDA array descriptor. + +###### Parameters + +`pArrayDescriptor` + \- Returned 3D array descriptor +`hArray` + \- 3D array to get descriptor of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Returns in `*pArrayDescriptor` a descriptor containing information on the format and dimensions of the CUDA array `hArray`. It is useful for subroutines that have been passed a CUDA array, but need to know the CUDA array parameters for validation or other purposes. + +This function may be called on 1D and 2D arrays, in which case the `Height` and/or `Depth` members of the descriptor struct will be set to 0. + +CUresult cuArrayCreate ( CUarray* pHandle, const CUDA_ARRAY_DESCRIPTOR* pAllocateArray ) + + +Creates a 1D or 2D CUDA array. + +###### Parameters + +`pHandle` + \- Returned array +`pAllocateArray` + \- Array descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a CUDA array according to the CUDA_ARRAY_DESCRIPTOR structure `pAllocateArray` and returns a handle to the new CUDA array in `*pHandle`. The CUDA_ARRAY_DESCRIPTOR is defined as: + + + ‎ typedef struct { + unsigned int Width; + unsigned int Height; + CUarray_format Format; + unsigned int NumChannels; + } CUDA_ARRAY_DESCRIPTOR; + +where: + + * `Width`, and `Height` are the width, and height of the CUDA array (in elements); the CUDA array is one-dimensional if height is 0, two-dimensional otherwise; + + * Format specifies the format of the elements; CUarray_format is defined as: + + ‎ typedef enum CUarray_format_enum { + CU_AD_FORMAT_UNSIGNED_INT8 = 0x01 + CU_AD_FORMAT_UNSIGNED_INT16 = 0x02 + CU_AD_FORMAT_UNSIGNED_INT32 = 0x03 + CU_AD_FORMAT_SIGNED_INT8 = 0x08 + CU_AD_FORMAT_SIGNED_INT16 = 0x09 + CU_AD_FORMAT_SIGNED_INT32 = 0x0a + CU_AD_FORMAT_HALF = 0x10 + CU_AD_FORMAT_FLOAT = 0x20 + CU_AD_FORMAT_NV12 = 0xb0 + CU_AD_FORMAT_UNORM_INT8X1 = 0xc0 + CU_AD_FORMAT_UNORM_INT8X2 = 0xc1 + CU_AD_FORMAT_UNORM_INT8X4 = 0xc2 + CU_AD_FORMAT_UNORM_INT16X1 = 0xc3 + CU_AD_FORMAT_UNORM_INT16X2 = 0xc4 + CU_AD_FORMAT_UNORM_INT16X4 = 0xc5 + CU_AD_FORMAT_SNORM_INT8X1 = 0xc6 + CU_AD_FORMAT_SNORM_INT8X2 = 0xc7 + CU_AD_FORMAT_SNORM_INT8X4 = 0xc8 + CU_AD_FORMAT_SNORM_INT16X1 = 0xc9 + CU_AD_FORMAT_SNORM_INT16X2 = 0xca + CU_AD_FORMAT_SNORM_INT16X4 = 0xcb + CU_AD_FORMAT_BC1_UNORM = 0x91 + CU_AD_FORMAT_BC1_UNORM_SRGB = 0x92 + CU_AD_FORMAT_BC2_UNORM = 0x93 + CU_AD_FORMAT_BC2_UNORM_SRGB = 0x94 + CU_AD_FORMAT_BC3_UNORM = 0x95 + CU_AD_FORMAT_BC3_UNORM_SRGB = 0x96 + CU_AD_FORMAT_BC4_UNORM = 0x97 + CU_AD_FORMAT_BC4_SNORM = 0x98 + CU_AD_FORMAT_BC5_UNORM = 0x99 + CU_AD_FORMAT_BC5_SNORM = 0x9a + CU_AD_FORMAT_BC6H_UF16 = 0x9b + CU_AD_FORMAT_BC6H_SF16 = 0x9c + CU_AD_FORMAT_BC7_UNORM = 0x9d + CU_AD_FORMAT_BC7_UNORM_SRGB = 0x9e + CU_AD_FORMAT_P010 = 0x9f + CU_AD_FORMAT_P016 = 0xa1 + CU_AD_FORMAT_NV16 = 0xa2 + CU_AD_FORMAT_P210 = 0xa3 + CU_AD_FORMAT_P216 = 0xa4 + CU_AD_FORMAT_YUY2 = 0xa5 + CU_AD_FORMAT_Y210 = 0xa6 + CU_AD_FORMAT_Y216 = 0xa7 + CU_AD_FORMAT_AYUV = 0xa8 + CU_AD_FORMAT_Y410 = 0xa9 + CU_AD_FORMAT_Y416 = 0xb1 + CU_AD_FORMAT_Y444_PLANAR8 = 0xb2 + CU_AD_FORMAT_Y444_PLANAR10 = 0xb3 + CU_AD_FORMAT_YUV444_8bit_SemiPlanar = 0xb4 + CU_AD_FORMAT_YUV444_16bit_SemiPlanar = 0xb5 + CU_AD_FORMAT_UNORM_INT_101010_2 = 0x50 + CU_AD_FORMAT_UINT8_PACKED_422 = 0x51 + CU_AD_FORMAT_UINT8_PACKED_444 = 0x52 + CU_AD_FORMAT_UINT8_SEMIPLANAR_420 = 0x53 + CU_AD_FORMAT_UINT16_SEMIPLANAR_420 = 0x54 + CU_AD_FORMAT_UINT8_SEMIPLANAR_422 = 0x55 + CU_AD_FORMAT_UINT16_SEMIPLANAR_422 = 0x56 + CU_AD_FORMAT_UINT8_SEMIPLANAR_444 = 0x57 + CU_AD_FORMAT_UINT16_SEMIPLANAR_444 = 0x58 + CU_AD_FORMAT_UINT8_PLANAR_420 = 0x59 + CU_AD_FORMAT_UINT16_PLANAR_420 = 0x5a + CU_AD_FORMAT_UINT8_PLANAR_422 = 0x5b + CU_AD_FORMAT_UINT16_PLANAR_422 = 0x5c + CU_AD_FORMAT_UINT8_PLANAR_444 = 0x5d + CU_AD_FORMAT_UINT16_PLANAR_444 = 0x5e + } CUarray_format; + + * `NumChannels` specifies the number of packed components per CUDA array element; it may be 1, 2, or 4; + + +Here are examples of CUDA array descriptions: + +Description for a CUDA array of 2048 floats: + + + ‎ CUDA_ARRAY_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_FLOAT; + desc.NumChannels = 1; + desc.Width = 2048; + desc.Height = 1; + +Description for a 64 x 64 CUDA array of floats: + + + ‎ CUDA_ARRAY_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_FLOAT; + desc.NumChannels = 1; + desc.Width = 64; + desc.Height = 64; + +Description for a `width` x `height` CUDA array of 64-bit, 4x16-bit float16's: + + + ‎ CUDA_ARRAY_DESCRIPTOR desc; + desc.Format = CU_AD_FORMAT_HALF; + desc.NumChannels = 4; + desc.Width = width; + desc.Height = height; + +Description for a `width` x `height` CUDA array of 16-bit elements, each of which is two 8-bit unsigned chars: + + + ‎ CUDA_ARRAY_DESCRIPTOR arrayDesc; + desc.Format = CU_AD_FORMAT_UNSIGNED_INT8; + desc.NumChannels = 2; + desc.Width = width; + desc.Height = height; + +CUresult cuArrayDestroy ( CUarray hArray ) + + +Destroys a CUDA array. + +###### Parameters + +`hArray` + \- Array to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ARRAY_IS_MAPPED, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Destroys the CUDA array `hArray`. + +CUresult cuArrayGetDescriptor ( CUDA_ARRAY_DESCRIPTOR* pArrayDescriptor, CUarray hArray ) + + +Get a 1D or 2D CUDA array descriptor. + +###### Parameters + +`pArrayDescriptor` + \- Returned array descriptor +`hArray` + \- Array to get descriptor of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns in `*pArrayDescriptor` a descriptor containing information on the format and dimensions of the CUDA array `hArray`. It is useful for subroutines that have been passed a CUDA array, but need to know the CUDA array parameters for validation or other purposes. + +CUresult cuArrayGetMemoryRequirements ( CUDA_ARRAY_MEMORY_REQUIREMENTS* memoryRequirements, CUarray array, CUdevice device ) + + +Returns the memory requirements of a CUDA array. + +###### Parameters + +`memoryRequirements` + \- Pointer to CUDA_ARRAY_MEMORY_REQUIREMENTS +`array` + \- CUDA array to get the memory requirements of +`device` + \- Device to get the memory requirements for + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the memory requirements of a CUDA array in `memoryRequirements` If the CUDA array is not allocated with flag CUDA_ARRAY3D_DEFERRED_MAPPINGCUDA_ERROR_INVALID_VALUE will be returned. + +The returned value in CUDA_ARRAY_MEMORY_REQUIREMENTS::size represents the total size of the CUDA array. The returned value in CUDA_ARRAY_MEMORY_REQUIREMENTS::alignment represents the alignment necessary for mapping the CUDA array. + +CUresult cuArrayGetPlane ( CUarray* pPlaneArray, CUarray hArray, unsigned int planeIdx ) + + +Gets a CUDA array plane from a CUDA array. + +###### Parameters + +`pPlaneArray` + \- Returned CUDA array referenced by the `planeIdx` +`hArray` + \- Multiplanar CUDA array +`planeIdx` + \- Plane index + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns in `pPlaneArray` a CUDA array that represents a single format plane of the CUDA array `hArray`. + +If `planeIdx` is greater than the maximum number of planes in this array or if the array does not have a multi-planar format e.g: CU_AD_FORMAT_NV12, then CUDA_ERROR_INVALID_VALUE is returned. + +Note that if the `hArray` has format CU_AD_FORMAT_NV12, then passing in 0 for `planeIdx` returns a CUDA array of the same size as `hArray` but with one channel and CU_AD_FORMAT_UNSIGNED_INT8 as its format. If 1 is passed for `planeIdx`, then the returned CUDA array has half the height and width of `hArray` with two channels and CU_AD_FORMAT_UNSIGNED_INT8 as its format. + +CUresult cuArrayGetSparseProperties ( CUDA_ARRAY_SPARSE_PROPERTIES* sparseProperties, CUarray array ) + + +Returns the layout properties of a sparse CUDA array. + +###### Parameters + +`sparseProperties` + \- Pointer to CUDA_ARRAY_SPARSE_PROPERTIES +`array` + \- CUDA array to get the sparse properties of + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the layout properties of a sparse CUDA array in `sparseProperties` If the CUDA array is not allocated with flag CUDA_ARRAY3D_SPARSECUDA_ERROR_INVALID_VALUE will be returned. + +If the returned value in CUDA_ARRAY_SPARSE_PROPERTIES::flags contains CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, then CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize represents the total size of the array. Otherwise, it will be zero. Also, the returned value in CUDA_ARRAY_SPARSE_PROPERTIES::miptailFirstLevel is always zero. Note that the `array` must have been allocated using cuArrayCreate or cuArray3DCreate. For CUDA arrays obtained using cuMipmappedArrayGetLevel, CUDA_ERROR_INVALID_VALUE will be returned. Instead, cuMipmappedArrayGetSparseProperties must be used to obtain the sparse properties of the entire CUDA mipmapped array to which `array` belongs to. + +CUresult cuDeviceGetByPCIBusId ( CUdevice* dev, const char* pciBusId ) + + +Returns a handle to a compute device. + +###### Parameters + +`dev` + \- Returned device handle +`pciBusId` + \- String in one of the following forms: [domain]:[bus]:[device].[function] [domain]:[bus]:[device] [bus]:[device].[function] where `domain`, `bus`, `device`, and `function` are all hexadecimal values + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*device` a device handle given a PCI bus ID string. + +CUresult cuDeviceGetPCIBusId ( char* pciBusId, int len, CUdevice dev ) + + +Returns a PCI Bus Id string for the device. + +###### Parameters + +`pciBusId` + \- Returned identifier string for the device in the following format [domain]:[bus]:[device].[function] where `domain`, `bus`, `device`, and `function` are all hexadecimal values. pciBusId should be large enough to store 13 characters including the NULL-terminator. +`len` + \- Maximum length of string to store in `name` +`dev` + \- Device to get identifier string for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns an ASCII string identifying the device `dev` in the NULL-terminated string pointed to by `pciBusId`. `len` specifies the maximum length of the string that may be returned. + +CUresult cuDeviceRegisterAsyncNotification ( CUdevice device, CUasyncCallback callbackFunc, void* userData, CUasyncCallbackHandle* callback ) + + +Registers a callback function to receive async notifications. + +###### Parameters + +`device` + \- The device on which to register the callback +`callbackFunc` + \- The function to register as a callback +`userData` + \- A generic pointer to user data. This is passed into the callback function. +`callback` + \- A handle representing the registered callback instance + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_UNKNOWN + +###### Description + +Registers `callbackFunc` to receive async notifications. + +The `userData` parameter is passed to the callback function at async notification time. Likewise, `callback` is also passed to the callback function to distinguish between multiple registered callbacks. + +The callback function being registered should be designed to return quickly (~10ms). Any long running tasks should be queued for execution on an application thread. + +Callbacks may not call cuDeviceRegisterAsyncNotification or cuDeviceUnregisterAsyncNotification. Doing so will result in CUDA_ERROR_NOT_PERMITTED. Async notification callbacks execute in an undefined order and may be serialized. + +Returns in `*callback` a handle representing the registered callback instance. + +CUresult cuDeviceUnregisterAsyncNotification ( CUdevice device, CUasyncCallbackHandle callback ) + + +Unregisters an async notification callback. + +###### Parameters + +`device` + \- The device from which to remove `callback`. +`callback` + \- The callback instance to unregister from receiving async notifications. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_UNKNOWN + +###### Description + +Unregisters `callback` so that the corresponding callback function will stop receiving async notifications. + +CUresult cuIpcCloseMemHandle ( CUdeviceptr dptr ) + + +Attempts to close memory mapped with cuIpcOpenMemHandle. + +###### Parameters + +`dptr` + \- Device pointer returned by cuIpcOpenMemHandle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_MAP_FAILED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Decrements the reference count of the memory returned by cuIpcOpenMemHandle by 1. When the reference count reaches 0, this API unmaps the memory. The original allocation in the exporting process as well as imported mappings in other processes will be unaffected. + +Any resources used to enable peer access will be freed if this is the last mapping using them. + +IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED + +CUresult cuIpcGetEventHandle ( CUipcEventHandle* pHandle, CUevent event ) + + +Gets an interprocess handle for a previously allocated event. + +###### Parameters + +`pHandle` + \- Pointer to a user allocated CUipcEventHandle in which to return the opaque event handle +`event` + \- Event allocated with CU_EVENT_INTERPROCESS and CU_EVENT_DISABLE_TIMING flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_MAP_FAILED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Takes as input a previously allocated event. This event must have been created with the CU_EVENT_INTERPROCESS and CU_EVENT_DISABLE_TIMING flags set. This opaque handle may be copied into other processes and opened with cuIpcOpenEventHandle to allow efficient hardware synchronization between GPU work in different processes. + +After the event has been opened in the importing process, cuEventRecord, cuEventSynchronize, cuStreamWaitEvent and cuEventQuery may be used in either process. Performing operations on the imported event after the exported event has been freed with cuEventDestroy will result in undefined behavior. + +IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED + +CUresult cuIpcGetMemHandle ( CUipcMemHandle* pHandle, CUdeviceptr dptr ) + + +Gets an interprocess memory handle for an existing device memory allocation. + +###### Parameters + +`pHandle` + \- Pointer to user allocated CUipcMemHandle to return the handle in. +`dptr` + \- Base pointer to previously allocated device memory + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_MAP_FAILED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Takes a pointer to the base of an existing device memory allocation created with cuMemAlloc and exports it for use in another process. This is a lightweight operation and may be called multiple times on an allocation without adverse effects. + +If a region of memory is freed with cuMemFree and a subsequent call to cuMemAlloc returns memory with the same device address, cuIpcGetMemHandle will return a unique handle for the new memory. + +IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED + +CUresult cuIpcOpenEventHandle ( CUevent* phEvent, CUipcEventHandle handle ) + + +Opens an interprocess event handle for use in the current process. + +###### Parameters + +`phEvent` + \- Returns the imported event +`handle` + \- Interprocess handle to open + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_MAP_FAILED, CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Opens an interprocess event handle exported from another process with cuIpcGetEventHandle. This function returns a CUevent that behaves like a locally created event with the CU_EVENT_DISABLE_TIMING flag specified. This event must be freed with cuEventDestroy. + +Performing operations on the imported event after the exported event has been freed with cuEventDestroy will result in undefined behavior. + +IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED + +CUresult cuIpcOpenMemHandle ( CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned int Flags ) + + +Opens an interprocess memory handle exported from another process and returns a device pointer usable in the local process. + +###### Parameters + +`pdptr` + \- Returned device pointer +`handle` + \- CUipcMemHandle to open +`Flags` + \- Flags for this operation. Must be specified as CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_MAP_FAILED, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_TOO_MANY_PEERS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Maps memory exported from another process with cuIpcGetMemHandle into the current device address space. For contexts on different devices cuIpcOpenMemHandle can attempt to enable peer access between the devices as if the user called cuCtxEnablePeerAccess. This behavior is controlled by the CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS flag. cuDeviceCanAccessPeer can determine if a mapping is possible. + +Contexts that may open CUipcMemHandles are restricted in the following way. CUipcMemHandles from each CUdevice in a given process may only be opened by one CUcontext per CUdevice per other process. + +If the memory handle has already been opened by the current context, the reference count on the handle is incremented by 1 and the existing device pointer is returned. + +Memory returned from cuIpcOpenMemHandle must be freed with cuIpcCloseMemHandle. + +Calling cuMemFree on an exported memory region before calling cuIpcCloseMemHandle in the importing context will result in undefined behavior. + +IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED + +No guarantees are made about the address returned in `*pdptr`. In particular, multiple processes may not receive the same address for the same `handle`. + +CUresult cuMemAlloc ( CUdeviceptr* dptr, size_t bytesize ) + + +Allocates device memory. + +###### Parameters + +`dptr` + \- Returned device pointer +`bytesize` + \- Requested allocation size in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Allocates `bytesize` bytes of linear memory on the device and returns in `*dptr` a pointer to the allocated memory. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. If `bytesize` is 0, cuMemAlloc() returns CUDA_ERROR_INVALID_VALUE. + +CUresult cuMemAllocHost ( void** pp, size_t bytesize ) + + +Allocates page-locked host memory. + +###### Parameters + +`pp` + \- Returned pointer to host memory +`bytesize` + \- Requested allocation size in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Allocates `bytesize` bytes of host memory that is page-locked and accessible to the device. The driver tracks the virtual memory ranges allocated with this function and automatically accelerates calls to functions such as cuMemcpy(). Since the memory can be accessed directly by the device, it can be read or written with much higher bandwidth than pageable memory obtained with functions such as malloc(). + +On systems where CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES is true, cuMemAllocHost may not page-lock the allocated memory. + +Page-locking excessive amounts of memory with cuMemAllocHost() may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to allocate staging areas for data exchange between host and device. + +Note all host memory allocated using cuMemAllocHost() will automatically be immediately accessible to all contexts on all devices which support unified addressing (as may be queried using CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING). The device pointer that may be used to access this host memory from those contexts is always equal to the returned host pointer `*pp`. See Unified Addressing for additional details. + +CUresult cuMemAllocManaged ( CUdeviceptr* dptr, size_t bytesize, unsigned int flags ) + + +Allocates memory that will be automatically managed by the Unified Memory system. + +###### Parameters + +`dptr` + \- Returned device pointer +`bytesize` + \- Requested allocation size in bytes +`flags` + \- Must be one of CU_MEM_ATTACH_GLOBAL or CU_MEM_ATTACH_HOST + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Allocates `bytesize` bytes of managed memory on the device and returns in `*dptr` a pointer to the allocated memory. If the device doesn't support allocating managed memory, CUDA_ERROR_NOT_SUPPORTED is returned. Support for managed memory can be queried using the device attribute CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. If `bytesize` is 0, cuMemAllocManaged returns CUDA_ERROR_INVALID_VALUE. The pointer is valid on the CPU and on all GPUs in the system that support managed memory. All accesses to this pointer must obey the Unified Memory programming model. + +`flags` specifies the default stream association for this allocation. `flags` must be one of CU_MEM_ATTACH_GLOBAL or CU_MEM_ATTACH_HOST. If CU_MEM_ATTACH_GLOBAL is specified, then this memory is accessible from any stream on any device. If CU_MEM_ATTACH_HOST is specified, then the allocation should not be accessed from devices that have a zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS; an explicit call to cuStreamAttachMemAsync will be required to enable access on such devices. + +If the association is later changed via cuStreamAttachMemAsync to a single stream, the default association as specified during cuMemAllocManaged is restored when that stream is destroyed. For __managed__ variables, the default association is always CU_MEM_ATTACH_GLOBAL. Note that destroying a stream is an asynchronous operation, and as a result, the change to default association won't happen until all work in the stream has completed. + +Memory allocated with cuMemAllocManaged should be released with cuMemFree. + +Device memory oversubscription is possible for GPUs that have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Managed memory on such GPUs may be evicted from device memory to host memory at any time by the Unified Memory driver in order to make room for other allocations. + +In a system where all GPUs have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, managed memory may not be populated when this API returns and instead may be populated on access. In such systems, managed memory can migrate to any processor's memory at any time. The Unified Memory driver will employ heuristics to maintain data locality and prevent excessive page faults to the extent possible. The application can also guide the driver about memory usage patterns via cuMemAdvise. The application can also explicitly migrate memory to a desired processor's memory via cuMemPrefetchAsync. + +In a multi-GPU system where all of the GPUs have a zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS and all the GPUs have peer-to-peer support with each other, the physical storage for managed memory is created on the GPU which is active at the time cuMemAllocManaged is called. All other GPUs will reference the data at reduced bandwidth via peer mappings over the PCIe bus. The Unified Memory driver does not migrate memory among such GPUs. + +In a multi-GPU system where not all GPUs have peer-to-peer support with each other and where the value of the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS is zero for at least one of those GPUs, the location chosen for physical storage of managed memory is system-dependent. + + * On Linux, the location chosen will be device memory as long as the current set of active contexts are on devices that either have peer-to-peer support with each other or have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. If there is an active context on a GPU that does not have a non-zero value for that device attribute and it does not have peer-to-peer support with the other devices that have active contexts on them, then the location for physical storage will be 'zero-copy' or host memory. Note that this means that managed memory that is located in device memory is migrated to host memory if a new context is created on a GPU that doesn't have a non-zero value for the device attribute and does not support peer-to-peer with at least one of the other devices that has an active context. This in turn implies that context creation may fail if there is insufficient host memory to migrate all managed allocations. + + * On Windows, the physical storage is always created in 'zero-copy' or host memory. All GPUs will reference the data at reduced bandwidth over the PCIe bus. In these circumstances, use of the environment variable CUDA_VISIBLE_DEVICES is recommended to restrict CUDA to only use those GPUs that have peer-to-peer support. Alternatively, users can also set CUDA_MANAGED_FORCE_DEVICE_ALLOC to a non-zero value to force the driver to always use device memory for physical storage. When this environment variable is set to a non-zero value, all contexts created in that process on devices that support managed memory have to be peer-to-peer compatible with each other. Context creation will fail if a context is created on a device that supports managed memory and is not peer-to-peer compatible with any of the other managed memory supporting devices on which contexts were previously created, even if those contexts have been destroyed. These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section. + + * On ARM, managed memory is not available on discrete gpu with Drive PX-2. + + +CUresult cuMemAllocPitch ( CUdeviceptr* dptr, size_t* pPitch, size_t WidthInBytes, size_t Height, unsigned int ElementSizeBytes ) + + +Allocates pitched device memory. + +###### Parameters + +`dptr` + \- Returned device pointer +`pPitch` + \- Returned pitch of allocation in bytes +`WidthInBytes` + \- Requested allocation width in bytes +`Height` + \- Requested allocation height in rows +`ElementSizeBytes` + \- Size of largest reads/writes for range + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Allocates at least `WidthInBytes` * `Height` bytes of linear memory on the device and returns in `*dptr` a pointer to the allocated memory. The function may pad the allocation to ensure that corresponding pointers in any given row will continue to meet the alignment requirements for coalescing as the address is updated from row to row. `ElementSizeBytes` specifies the size of the largest reads and writes that will be performed on the memory range. `ElementSizeBytes` may be 4, 8 or 16 (since coalesced memory transactions are not possible on other data sizes). If `ElementSizeBytes` is smaller than the actual read/write size of a kernel, the kernel will run correctly, but possibly at reduced speed. The pitch returned in `*pPitch` by cuMemAllocPitch() is the width in bytes of the allocation. The intended usage of pitch is as a separate parameter of the allocation, used to compute addresses within the 2D array. Given the row and column of an array element of type **T** , the address is computed as: + + + ‎ T* pElement = (T*)((char*)BaseAddress + Row * Pitch) + Column; + +The pitch returned by cuMemAllocPitch() is guaranteed to work with cuMemcpy2D() under all circumstances. For allocations of 2D arrays, it is recommended that programmers consider performing pitch allocations using cuMemAllocPitch(). Due to alignment restrictions in the hardware, this is especially true if the application will be performing 2D memory copies between different regions of device memory (whether linear memory or CUDA arrays). + +The byte alignment of the pitch returned by cuMemAllocPitch() is guaranteed to match or exceed the alignment requirement for texture binding with cuTexRefSetAddress2D(). + +CUresult cuMemBatchDecompressAsync ( CUmemDecompressParams* paramsArray, size_t count, unsigned int flags, size_t* errorIndex, CUstream stream ) + + +Submit a batch of `count` independent decompression operations. + +###### Parameters + +`paramsArray` + The array of structures describing the independent decompression operations. +`count` + The number of entries in `paramsArray` array. +`flags` + Must be 0. +`errorIndex` + The index into `paramsArray` of the decompression operation for which the error returned by this function pertains to. If `index` is SIZE_MAX and the value returned is not CUDA_SUCCESS, then the error returned by this function should be considered a general error that does not pertain to a particular decompression operation. May be `NULL`, in which case, no index will be recorded in the event of error. +`stream` + The stream where the work will be enqueued. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Each of the `count` decompression operations is described by a single entry in the `paramsArray` array. Once the batch has been submitted, the function will return, and decompression will happen asynchronously w.r.t. the CPU. To the work completion tracking mechanisms in the CUDA driver, the batch will be considered a single unit of work and processed according to stream semantics, i.e., it is not possible to query the completion of individual decompression operations within a batch. + +The memory pointed to by each of CUmemDecompressParams.src, CUmemDecompressParams.dst, and CUmemDecompressParams.dstActBytes, must be capable of usage with the hardware decompress feature. That is, for each of said pointers, the pointer attribute CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE should give a non-zero value. To ensure this, the memory backing the pointers should have been allocated using one of the following CUDA memory allocators: * cuMemAlloc() * cuMemCreate() with the usage flag CU_MEM_CREATE_USAGE_HW_DECOMPRESS * cuMemAllocFromPoolAsync() from a pool that was created with the usage flag CU_MEM_POOL_CREATE_USAGE_HW_DECOMPRESS Additionally, CUmemDecompressParams.src, CUmemDecompressParams.dst, and CUmemDecompressParams.dstActBytes, must all be accessible from the device associated with the context where `stream` was created. For information on how to ensure this, see the documentation for the allocator of interest. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemFree ( CUdeviceptr dptr ) + + +Frees device memory. + +###### Parameters + +`dptr` + \- Pointer to memory to free + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Frees the memory space pointed to by `dptr`, which must have been returned by a previous call to one of the following memory allocation APIs - cuMemAlloc(), cuMemAllocPitch(), cuMemAllocManaged(), cuMemAllocAsync(), cuMemAllocFromPoolAsync() + +Note - This API will not perform any implict synchronization when the pointer was allocated with cuMemAllocAsync or cuMemAllocFromPoolAsync. Callers must ensure that all accesses to these pointer have completed before invoking cuMemFree. For best performance and memory reuse, users should use cuMemFreeAsync to free memory allocated via the stream ordered memory allocator. For all other pointers, this API may perform implicit synchronization. + +CUresult cuMemFreeHost ( void* p ) + + +Frees page-locked host memory. + +###### Parameters + +`p` + \- Pointer to memory to free + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Frees the memory space pointed to by `p`, which must have been returned by a previous call to cuMemAllocHost(). + +CUresult cuMemGetAddressRange ( CUdeviceptr* pbase, size_t* psize, CUdeviceptr dptr ) + + +Get information on memory allocations. + +###### Parameters + +`pbase` + \- Returned base address +`psize` + \- Returned size of device memory allocation +`dptr` + \- Device pointer to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the base address in `*pbase` and size in `*psize` of the allocation that contains the input pointer `dptr`. Both parameters `pbase` and `psize` are optional. If one of them is NULL, it is ignored. + +CUresult cuMemGetHandleForAddressRange ( void* handle, CUdeviceptr dptr, size_t size, CUmemRangeHandleType handleType, unsigned long long flags ) + + +Retrieve handle for an address range. + +###### Parameters + +`handle` + \- Pointer to the location where the returned handle will be stored. +`dptr` + \- Pointer to a valid CUDA device allocation. Must be aligned to host page size. +`size` + \- Length of the address range. Must be aligned to host page size. +`handleType` + \- Type of handle requested (defines type and size of the `handle` output parameter) +`flags` + \- When requesting CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD the value could be CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE, otherwise 0. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Get a handle of the specified type to an address range. When requesting CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD, address range obtained by a prior call to either cuMemAlloc or cuMemAddressReserve is supported if the CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED device attribute returns true. If the address range was obtained via cuMemAddressReserve, it must also be fully mapped via cuMemMap. Address range obtained by a prior call to either cuMemAllocHost or cuMemHostAlloc is supported if the CU_DEVICE_ATTRIBUTE_HOST_ALLOC_DMA_BUF_SUPPORTED device attribute returns true. + +As of CUDA 13.0, querying support for address range obtained by calling cuMemAllocHost or cuMemHostAlloc using the CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED device attribute is deprecated. + +Users must ensure the `dptr` and `size` are aligned to the host page size. + +The `handle` will be interpreted as a pointer to an integer to store the dma_buf file descriptor. Users must ensure the entire address range is backed and mapped when the address range is allocated by cuMemAddressReserve. All the physical allocations backing the address range must be resident on the same device and have identical allocation properties. Users are also expected to retrieve a new handle every time the underlying physical allocation(s) corresponding to a previously queried VA range are changed. + +For CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD, users may set flags to CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE. Which when set on a supported platform, will give a DMA_BUF handle mapped via PCIE BAR1 or will return an error otherwise. + +CUresult cuMemGetInfo ( size_t* free, size_t* total ) + + +Gets free and total memory. + +###### Parameters + +`free` + \- Returned free memory in bytes +`total` + \- Returned total memory in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*total` the total amount of memory available to the the current context. Returns in `*free` the amount of memory on the device that is free according to the OS. CUDA is not guaranteed to be able to allocate all of the memory that the OS reports as free. In a multi-tenet situation, free estimate returned is prone to race condition where a new allocation/free done by a different process or a different thread in the same process between the time when free memory was estimated and reported, will result in deviation in free value reported and actual free memory. + +The integrated GPU on Tegra shares memory with CPU and other component of the SoC. The free and total values returned by the API excludes the SWAP memory space maintained by the OS on some platforms. The OS may move some of the memory pages into swap area as the GPU or CPU allocate or access memory. See Tegra app note on how to calculate total and free memory on Tegra. + +CUresult cuMemHostAlloc ( void** pp, size_t bytesize, unsigned int Flags ) + + +Allocates page-locked host memory. + +###### Parameters + +`pp` + \- Returned pointer to host memory +`bytesize` + \- Requested allocation size in bytes +`Flags` + \- Flags for allocation request + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Allocates `bytesize` bytes of host memory that is page-locked and accessible to the device. The driver tracks the virtual memory ranges allocated with this function and automatically accelerates calls to functions such as cuMemcpyHtoD(). Since the memory can be accessed directly by the device, it can be read or written with much higher bandwidth than pageable memory obtained with functions such as malloc(). + +On systems where CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES is true, cuMemHostAlloc may not page-lock the allocated memory. + +Page-locking excessive amounts of memory may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to allocate staging areas for data exchange between host and device. + +The `Flags` parameter enables different options to be specified that affect the allocation, as follows. + + * CU_MEMHOSTALLOC_PORTABLE: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation. + + + * CU_MEMHOSTALLOC_DEVICEMAP: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by calling cuMemHostGetDevicePointer(). + + + * CU_MEMHOSTALLOC_WRITECOMBINED: Allocates the memory as write-combined (WC). WC memory can be transferred across the PCI Express bus more quickly on some system configurations, but cannot be read efficiently by most CPUs. WC memory is a good option for buffers that will be written by the CPU and read by the GPU via mapped pinned memory or host->device transfers. + + +All of these flags are orthogonal to one another: a developer may allocate memory that is portable, mapped and/or write-combined with no restrictions. + +The CU_MEMHOSTALLOC_DEVICEMAP flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred to cuMemHostGetDevicePointer() because the memory may be mapped into other CUDA contexts via the CU_MEMHOSTALLOC_PORTABLE flag. + +The memory allocated by this function must be freed with cuMemFreeHost(). + +Note all host memory allocated using cuMemHostAlloc() will automatically be immediately accessible to all contexts on all devices which support unified addressing (as may be queried using CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING). Unless the flag CU_MEMHOSTALLOC_WRITECOMBINED is specified, the device pointer that may be used to access this host memory from those contexts is always equal to the returned host pointer `*pp`. If the flag CU_MEMHOSTALLOC_WRITECOMBINED is specified, then the function cuMemHostGetDevicePointer() must be used to query the device pointer, even if the context supports unified addressing. See Unified Addressing for additional details. + +CUresult cuMemHostGetDevicePointer ( CUdeviceptr* pdptr, void* p, unsigned int Flags ) + + +Passes back device pointer of mapped pinned memory. + +###### Parameters + +`pdptr` + \- Returned device pointer +`p` + \- Host pointer +`Flags` + \- Options (must be 0) + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Passes back the device pointer `pdptr` corresponding to the mapped, pinned host buffer `p` allocated by cuMemHostAlloc. + +cuMemHostGetDevicePointer() will fail if the CU_MEMHOSTALLOC_DEVICEMAP flag was not specified at the time the memory was allocated, or if the function is called on a GPU that does not support mapped pinned memory. + +For devices that have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, the memory can also be accessed from the device using the host pointer `p`. The device pointer returned by cuMemHostGetDevicePointer() may or may not match the original host pointer `p` and depends on the devices visible to the application. If all devices visible to the application have a non-zero value for the device attribute, the device pointer returned by cuMemHostGetDevicePointer() will match the original pointer `p`. If any device visible to the application has a zero value for the device attribute, the device pointer returned by cuMemHostGetDevicePointer() will not match the original host pointer `p`, but it will be suitable for use on all devices provided Unified Virtual Addressing is enabled. In such systems, it is valid to access the memory using either pointer on devices that have a non-zero value for the device attribute. Note however that such devices should access the memory using only one of the two pointers and not both. + +`Flags` provides for future releases. For now, it must be set to 0. + +CUresult cuMemHostGetFlags ( unsigned int* pFlags, void* p ) + + +Passes back flags that were used for a pinned allocation. + +###### Parameters + +`pFlags` + \- Returned flags word +`p` + \- Host pointer + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Passes back the flags `pFlags` that were specified when allocating the pinned host buffer `p` allocated by cuMemHostAlloc. + +cuMemHostGetFlags() will fail if the pointer does not reside in an allocation performed by cuMemAllocHost() or cuMemHostAlloc(). + +CUresult cuMemHostRegister ( void* p, size_t bytesize, unsigned int Flags ) + + +Registers an existing host memory range for use by CUDA. + +###### Parameters + +`p` + \- Host pointer to memory to page-lock +`bytesize` + \- Size in bytes of the address range to page-lock +`Flags` + \- Flags for allocation request + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Page-locks the memory range specified by `p` and `bytesize` and maps it for the device(s) as specified by `Flags`. This memory range also is added to the same tracking mechanism as cuMemHostAlloc to automatically accelerate calls to functions such as cuMemcpyHtoD(). Since the memory can be accessed directly by the device, it can be read or written with much higher bandwidth than pageable memory that has not been registered. Page-locking excessive amounts of memory may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to register staging areas for data exchange between host and device. + +On systems where CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES is true, cuMemHostRegister will not page-lock the memory range specified by `ptr` but only populate unpopulated pages. + +The `Flags` parameter enables different options to be specified that affect the allocation, as follows. + + * CU_MEMHOSTREGISTER_PORTABLE: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation. + + + * CU_MEMHOSTREGISTER_DEVICEMAP: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by calling cuMemHostGetDevicePointer(). + + + * CU_MEMHOSTREGISTER_IOMEMORY: The pointer is treated as pointing to some I/O memory space, e.g. the PCI Express resource of a 3rd party device. + + + * CU_MEMHOSTREGISTER_READ_ONLY: The pointer is treated as pointing to memory that is considered read-only by the device. On platforms without CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, this flag is required in order to register memory mapped to the CPU as read-only. Support for the use of this flag can be queried from the device attribute CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED. Using this flag with a current context associated with a device that does not have this attribute set will cause cuMemHostRegister to error with CUDA_ERROR_NOT_SUPPORTED. + + +All of these flags are orthogonal to one another: a developer may page-lock memory that is portable or mapped with no restrictions. + +The CU_MEMHOSTREGISTER_DEVICEMAP flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred to cuMemHostGetDevicePointer() because the memory may be mapped into other CUDA contexts via the CU_MEMHOSTREGISTER_PORTABLE flag. + +For devices that have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, the memory can also be accessed from the device using the host pointer `p`. The device pointer returned by cuMemHostGetDevicePointer() may or may not match the original host pointer `ptr` and depends on the devices visible to the application. If all devices visible to the application have a non-zero value for the device attribute, the device pointer returned by cuMemHostGetDevicePointer() will match the original pointer `ptr`. If any device visible to the application has a zero value for the device attribute, the device pointer returned by cuMemHostGetDevicePointer() will not match the original host pointer `ptr`, but it will be suitable for use on all devices provided Unified Virtual Addressing is enabled. In such systems, it is valid to access the memory using either pointer on devices that have a non-zero value for the device attribute. Note however that such devices should access the memory using only of the two pointers and not both. + +The memory page-locked by this function must be unregistered with cuMemHostUnregister(). + +CUresult cuMemHostUnregister ( void* p ) + + +Unregisters a memory range that was registered with cuMemHostRegister. + +###### Parameters + +`p` + \- Host pointer to memory to unregister + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED + +###### Description + +Unmaps the memory range whose base address is specified by `p`, and makes it pageable again. + +The base address must be the same one specified to cuMemHostRegister(). + +CUresult cuMemcpy ( CUdeviceptr dst, CUdeviceptr src, size_t ByteCount ) + + +Copies memory. + +###### Parameters + +`dst` + \- Destination unified virtual address space pointer +`src` + \- Source unified virtual address space pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies data between two pointers. `dst` and `src` are base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. Note that this function infers the type of the transfer (host to host, host to device, device to device, or device to host) from the pointer values. This function is only allowed in contexts which support unified addressing. + + * + + * This function exhibits synchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpy2D ( const CUDA_MEMCPY2D* pCopy ) + + +Copies memory for 2D arrays. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Perform a 2D memory copy according to the parameters specified in `pCopy`. The CUDA_MEMCPY2D structure is defined as: + + + ‎ typedef struct CUDA_MEMCPY2D_st { + unsigned int srcXInBytes, srcY; + CUmemorytype srcMemoryType; + const void *srcHost; + CUdeviceptr srcDevice; + CUarray srcArray; + unsigned int srcPitch; + + unsigned int dstXInBytes, dstY; + CUmemorytype dstMemoryType; + void *dstHost; + CUdeviceptr dstDevice; + CUarray dstArray; + unsigned int dstPitch; + + unsigned int WidthInBytes; + unsigned int Height; + } CUDA_MEMCPY2D; + +where: + + * srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively; CUmemorytype_enum is defined as: + + + + + ‎ typedef enum CUmemorytype_enum { + CU_MEMORYTYPE_HOST = 0x01 + CU_MEMORYTYPE_DEVICE = 0x02 + CU_MEMORYTYPE_ARRAY = 0x03 + CU_MEMORYTYPE_UNIFIED = 0x04 + } CUmemorytype; + +If srcMemoryType is CU_MEMORYTYPE_UNIFIED, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If srcMemoryType is CU_MEMORYTYPE_HOST, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_DEVICE, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_ARRAY, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. + +If dstMemoryType is CU_MEMORYTYPE_HOST, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_UNIFIED, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If dstMemoryType is CU_MEMORYTYPE_DEVICE, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_ARRAY, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored. + + * srcXInBytes and srcY specify the base address of the source data for the copy. + + +For host pointers, the starting address is + + + ‎ void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; + +For CUDA arrays, srcXInBytes must be evenly divisible by the array element size. + + * dstXInBytes and dstY specify the base address of the destination data for the copy. + + +For host pointers, the base address is + + + ‎ void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; + +For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. + + * WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + +cuMemcpy2D() returns an error if any pitch is greater than the maximum allowed (CU_DEVICE_ATTRIBUTE_MAX_PITCH). cuMemAllocPitch() passes back pitches that always work with cuMemcpy2D(). On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), cuMemcpy2D() may fail for pitches not computed by cuMemAllocPitch(). cuMemcpy2DUnaligned() does not have this restriction, but may run significantly slower in the cases where cuMemcpy2D() would have returned an error code. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpy2DAsync ( const CUDA_MEMCPY2D* pCopy, CUstream hStream ) + + +Copies memory for 2D arrays. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Perform a 2D memory copy according to the parameters specified in `pCopy`. The CUDA_MEMCPY2D structure is defined as: + + + ‎ typedef struct CUDA_MEMCPY2D_st { + unsigned int srcXInBytes, srcY; + CUmemorytype srcMemoryType; + const void *srcHost; + CUdeviceptr srcDevice; + CUarray srcArray; + unsigned int srcPitch; + unsigned int dstXInBytes, dstY; + CUmemorytype dstMemoryType; + void *dstHost; + CUdeviceptr dstDevice; + CUarray dstArray; + unsigned int dstPitch; + unsigned int WidthInBytes; + unsigned int Height; + } CUDA_MEMCPY2D; + +where: + + * srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively; CUmemorytype_enum is defined as: + + + + + ‎ typedef enum CUmemorytype_enum { + CU_MEMORYTYPE_HOST = 0x01 + CU_MEMORYTYPE_DEVICE = 0x02 + CU_MEMORYTYPE_ARRAY = 0x03 + CU_MEMORYTYPE_UNIFIED = 0x04 + } CUmemorytype; + +If srcMemoryType is CU_MEMORYTYPE_HOST, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_UNIFIED, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If srcMemoryType is CU_MEMORYTYPE_DEVICE, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_ARRAY, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. + +If dstMemoryType is CU_MEMORYTYPE_UNIFIED, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If dstMemoryType is CU_MEMORYTYPE_HOST, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_DEVICE, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_ARRAY, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored. + + * srcXInBytes and srcY specify the base address of the source data for the copy. + + +For host pointers, the starting address is + + + ‎ void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; + +For CUDA arrays, srcXInBytes must be evenly divisible by the array element size. + + * dstXInBytes and dstY specify the base address of the destination data for the copy. + + +For host pointers, the base address is + + + ‎ void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; + +For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. + + * WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + * If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height \+ dstY. + + +cuMemcpy2DAsync() returns an error if any pitch is greater than the maximum allowed (CU_DEVICE_ATTRIBUTE_MAX_PITCH). cuMemAllocPitch() passes back pitches that always work with cuMemcpy2D(). On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), cuMemcpy2DAsync() may fail for pitches not computed by cuMemAllocPitch(). + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemcpy2DUnaligned ( const CUDA_MEMCPY2D* pCopy ) + + +Copies memory for 2D arrays. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Perform a 2D memory copy according to the parameters specified in `pCopy`. The CUDA_MEMCPY2D structure is defined as: + + + ‎ typedef struct CUDA_MEMCPY2D_st { + unsigned int srcXInBytes, srcY; + CUmemorytype srcMemoryType; + const void *srcHost; + CUdeviceptr srcDevice; + CUarray srcArray; + unsigned int srcPitch; + unsigned int dstXInBytes, dstY; + CUmemorytype dstMemoryType; + void *dstHost; + CUdeviceptr dstDevice; + CUarray dstArray; + unsigned int dstPitch; + unsigned int WidthInBytes; + unsigned int Height; + } CUDA_MEMCPY2D; + +where: + + * srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively; CUmemorytype_enum is defined as: + + + + + ‎ typedef enum CUmemorytype_enum { + CU_MEMORYTYPE_HOST = 0x01 + CU_MEMORYTYPE_DEVICE = 0x02 + CU_MEMORYTYPE_ARRAY = 0x03 + CU_MEMORYTYPE_UNIFIED = 0x04 + } CUmemorytype; + +If srcMemoryType is CU_MEMORYTYPE_UNIFIED, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If srcMemoryType is CU_MEMORYTYPE_HOST, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_DEVICE, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_ARRAY, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. + +If dstMemoryType is CU_MEMORYTYPE_UNIFIED, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If dstMemoryType is CU_MEMORYTYPE_HOST, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_DEVICE, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_ARRAY, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored. + + * srcXInBytes and srcY specify the base address of the source data for the copy. + + +For host pointers, the starting address is + + + ‎ void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; + +For CUDA arrays, srcXInBytes must be evenly divisible by the array element size. + + * dstXInBytes and dstY specify the base address of the destination data for the copy. + + +For host pointers, the base address is + + + ‎ void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; + +For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. + + * WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + +cuMemcpy2D() returns an error if any pitch is greater than the maximum allowed (CU_DEVICE_ATTRIBUTE_MAX_PITCH). cuMemAllocPitch() passes back pitches that always work with cuMemcpy2D(). On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), cuMemcpy2D() may fail for pitches not computed by cuMemAllocPitch(). cuMemcpy2DUnaligned() does not have this restriction, but may run significantly slower in the cases where cuMemcpy2D() would have returned an error code. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpy3D ( const CUDA_MEMCPY3D* pCopy ) + + +Copies memory for 3D arrays. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Perform a 3D memory copy according to the parameters specified in `pCopy`. The CUDA_MEMCPY3D structure is defined as: + + + ‎ typedef struct CUDA_MEMCPY3D_st { + + unsigned int srcXInBytes, srcY, srcZ; + unsigned int srcLOD; + CUmemorytype srcMemoryType; + const void *srcHost; + CUdeviceptr srcDevice; + CUarray srcArray; + unsigned int srcPitch; // ignored when src is array + unsigned int srcHeight; // ignored when src is array; may be 0 if Depth==1 + + unsigned int dstXInBytes, dstY, dstZ; + unsigned int dstLOD; + CUmemorytype dstMemoryType; + void *dstHost; + CUdeviceptr dstDevice; + CUarray dstArray; + unsigned int dstPitch; // ignored when dst is array + unsigned int dstHeight; // ignored when dst is array; may be 0 if Depth==1 + + unsigned int WidthInBytes; + unsigned int Height; + unsigned int Depth; + } CUDA_MEMCPY3D; + +where: + + * srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively; CUmemorytype_enum is defined as: + + + + + ‎ typedef enum CUmemorytype_enum { + CU_MEMORYTYPE_HOST = 0x01 + CU_MEMORYTYPE_DEVICE = 0x02 + CU_MEMORYTYPE_ARRAY = 0x03 + CU_MEMORYTYPE_UNIFIED = 0x04 + } CUmemorytype; + +If srcMemoryType is CU_MEMORYTYPE_UNIFIED, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If srcMemoryType is CU_MEMORYTYPE_HOST, srcHost, srcPitch and srcHeight specify the (host) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_DEVICE, srcDevice, srcPitch and srcHeight specify the (device) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_ARRAY, srcArray specifies the handle of the source data. srcHost, srcDevice, srcPitch and srcHeight are ignored. + +If dstMemoryType is CU_MEMORYTYPE_UNIFIED, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If dstMemoryType is CU_MEMORYTYPE_HOST, dstHost and dstPitch specify the (host) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_DEVICE, dstDevice and dstPitch specify the (device) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_ARRAY, dstArray specifies the handle of the destination data. dstHost, dstDevice, dstPitch and dstHeight are ignored. + + * srcXInBytes, srcY and srcZ specify the base address of the source data for the copy. + + +For host pointers, the starting address is + + + ‎ void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes; + +For CUDA arrays, srcXInBytes must be evenly divisible by the array element size. + + * dstXInBytes, dstY and dstZ specify the base address of the destination data for the copy. + + +For host pointers, the base address is + + + ‎ void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes; + +For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. + + * WidthInBytes, Height and Depth specify the width (in bytes), height and depth of the 3D copy being performed. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + * If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height \+ dstY. + + +cuMemcpy3D() returns an error if any pitch is greater than the maximum allowed (CU_DEVICE_ATTRIBUTE_MAX_PITCH). + +The srcLOD and dstLOD members of the CUDA_MEMCPY3D structure must be set to 0. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpy3DAsync ( const CUDA_MEMCPY3D* pCopy, CUstream hStream ) + + +Copies memory for 3D arrays. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Perform a 3D memory copy according to the parameters specified in `pCopy`. The CUDA_MEMCPY3D structure is defined as: + + + ‎ typedef struct CUDA_MEMCPY3D_st { + + unsigned int srcXInBytes, srcY, srcZ; + unsigned int srcLOD; + CUmemorytype srcMemoryType; + const void *srcHost; + CUdeviceptr srcDevice; + CUarray srcArray; + unsigned int srcPitch; // ignored when src is array + unsigned int srcHeight; // ignored when src is array; may be 0 if Depth==1 + + unsigned int dstXInBytes, dstY, dstZ; + unsigned int dstLOD; + CUmemorytype dstMemoryType; + void *dstHost; + CUdeviceptr dstDevice; + CUarray dstArray; + unsigned int dstPitch; // ignored when dst is array + unsigned int dstHeight; // ignored when dst is array; may be 0 if Depth==1 + + unsigned int WidthInBytes; + unsigned int Height; + unsigned int Depth; + } CUDA_MEMCPY3D; + +where: + + * srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively; CUmemorytype_enum is defined as: + + + + + ‎ typedef enum CUmemorytype_enum { + CU_MEMORYTYPE_HOST = 0x01 + CU_MEMORYTYPE_DEVICE = 0x02 + CU_MEMORYTYPE_ARRAY = 0x03 + CU_MEMORYTYPE_UNIFIED = 0x04 + } CUmemorytype; + +If srcMemoryType is CU_MEMORYTYPE_UNIFIED, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If srcMemoryType is CU_MEMORYTYPE_HOST, srcHost, srcPitch and srcHeight specify the (host) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_DEVICE, srcDevice, srcPitch and srcHeight specify the (device) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. + +If srcMemoryType is CU_MEMORYTYPE_ARRAY, srcArray specifies the handle of the source data. srcHost, srcDevice, srcPitch and srcHeight are ignored. + +If dstMemoryType is CU_MEMORYTYPE_UNIFIED, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. + +If dstMemoryType is CU_MEMORYTYPE_HOST, dstHost and dstPitch specify the (host) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_DEVICE, dstDevice and dstPitch specify the (device) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. + +If dstMemoryType is CU_MEMORYTYPE_ARRAY, dstArray specifies the handle of the destination data. dstHost, dstDevice, dstPitch and dstHeight are ignored. + + * srcXInBytes, srcY and srcZ specify the base address of the source data for the copy. + + +For host pointers, the starting address is + + + ‎ void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes; + +For CUDA arrays, srcXInBytes must be evenly divisible by the array element size. + + * dstXInBytes, dstY and dstZ specify the base address of the destination data for the copy. + + +For host pointers, the base address is + + + ‎ void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes); + +For device pointers, the starting address is + + + ‎ CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes; + +For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. + + * WidthInBytes, Height and Depth specify the width (in bytes), height and depth of the 3D copy being performed. + + * If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes. + + * If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height \+ dstY. + + +cuMemcpy3DAsync() returns an error if any pitch is greater than the maximum allowed (CU_DEVICE_ATTRIBUTE_MAX_PITCH). + +The srcLOD and dstLOD members of the CUDA_MEMCPY3D structure must be set to 0. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemcpy3DBatchAsync ( size_t numOps, CUDA_MEMCPY3D_BATCH_OP* opList, unsigned long long flags, CUstream hStream ) + + +Performs a batch of 3D memory copies asynchronously. + +###### Parameters + +`numOps` + \- Total number of memcpy operations. +`opList` + \- Array of size `numOps` containing the actual memcpy operations. +`flags` + \- Flags for future use, must be zero now. +`hStream` + \- The stream to enqueue the operations in. Must not be default NULL stream. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. Note that this means specifying any dependent copies within a batch will result in undefined behavior. + +Performs memory copies as specified in the `opList` array. The length of this array is specified in `numOps`. Each entry in this array describes a copy operation. This includes among other things, the source and destination operands for the copy as specified in CUDA_MEMCPY3D_BATCH_OP::src and CUDA_MEMCPY3D_BATCH_OP::dst respectively. The source and destination operands of a copy can either be a pointer or a CUDA array. The width, height and depth of a copy is specified in CUDA_MEMCPY3D_BATCH_OP::extent. The width, height and depth of a copy are specified in elements and must not be zero. For pointer-to-pointer copies, the element size is considered to be 1. For pointer to CUDA array or vice versa copies, the element size is determined by the CUDA array. For CUDA array to CUDA array copies, the element size of the two CUDA arrays must match. + +For a given operand, if CUmemcpy3DOperand::type is specified as CU_MEMCPY_OPERAND_TYPE_POINTER, then CUmemcpy3DOperand::op::ptr will be used. The CUmemcpy3DOperand::op::ptr::ptr field must contain the pointer where the copy should begin. The CUmemcpy3DOperand::op::ptr::rowLength field specifies the length of each row in elements and must either be zero or be greater than or equal to the width of the copy specified in CUDA_MEMCPY3D_BATCH_OP::extent::width. The CUmemcpy3DOperand::op::ptr::layerHeight field specifies the height of each layer and must either be zero or be greater than or equal to the height of the copy specified in CUDA_MEMCPY3D_BATCH_OP::extent::height. When either of these values is zero, that aspect of the operand is considered to be tightly packed according to the copy extent. For managed memory pointers on devices where CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS is true or system-allocated pageable memory on devices where CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS is true, the CUmemcpy3DOperand::op::ptr::locHint field can be used to hint the location of the operand. + +If an operand's type is specified as CU_MEMCPY_OPERAND_TYPE_ARRAY, then CUmemcpy3DOperand::op::array will be used. The CUmemcpy3DOperand::op::array::array field specifies the CUDA array and CUmemcpy3DOperand::op::array::offset specifies the 3D offset into that array where the copy begins. + +The CUmemcpyAttributes::srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_STREAM, then the source will be accessed in stream order. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it's known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_ANY then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it's known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcopy operation in `opList` must have a valid srcAccessOrder setting, otherwise this API will return CUDA_ERROR_INVALID_VALUE. + +The CUmemcpyAttributes::flags field can be used to specify certain flags for copies. Setting the CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpy3DPeer ( const CUDA_MEMCPY3D_PEER* pCopy ) + + +Copies memory between contexts. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Perform a 3D memory copy according to the parameters specified in `pCopy`. See the definition of the CUDA_MEMCPY3D_PEER structure for documentation of its parameters. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpy3DPeerAsync ( const CUDA_MEMCPY3D_PEER* pCopy, CUstream hStream ) + + +Copies memory between contexts asynchronously. + +###### Parameters + +`pCopy` + \- Parameters for the memory copy +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Perform a 3D memory copy according to the parameters specified in `pCopy`. See the definition of the CUDA_MEMCPY3D_PEER structure for documentation of its parameters. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemcpyAsync ( CUdeviceptr dst, CUdeviceptr src, size_t ByteCount, CUstream hStream ) + + +Copies memory asynchronously. + +###### Parameters + +`dst` + \- Destination unified virtual address space pointer +`src` + \- Source unified virtual address space pointer +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies data between two pointers. `dst` and `src` are base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. Note that this function infers the type of the transfer (host to host, host to device, device to device, or device to host) from the pointer values. This function is only allowed in contexts which support unified addressing. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyAtoA ( CUarray dstArray, size_t dstOffset, CUarray srcArray, size_t srcOffset, size_t ByteCount ) + + +Copies memory from Array to Array. + +###### Parameters + +`dstArray` + \- Destination array +`dstOffset` + \- Offset in bytes of destination array +`srcArray` + \- Source array +`srcOffset` + \- Offset in bytes of source array +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from one 1D CUDA array to another. `dstArray` and `srcArray` specify the handles of the destination and source CUDA arrays for the copy, respectively. `dstOffset` and `srcOffset` specify the destination and source offsets in bytes into the CUDA arrays. `ByteCount` is the number of bytes to be copied. The size of the elements in the CUDA arrays need not be the same format, but the elements must be the same size; and count must be evenly divisible by that size. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpyAtoD ( CUdeviceptr dstDevice, CUarray srcArray, size_t srcOffset, size_t ByteCount ) + + +Copies memory from Array to Device. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`srcArray` + \- Source array +`srcOffset` + \- Offset in bytes of source array +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from one 1D CUDA array to device memory. `dstDevice` specifies the base pointer of the destination and must be naturally aligned with the CUDA array elements. `srcArray` and `srcOffset` specify the CUDA array handle and the offset in bytes into the array where the copy is to begin. `ByteCount` specifies the number of bytes to copy and must be evenly divisible by the array element size. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpyAtoH ( void* dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount ) + + +Copies memory from Array to Host. + +###### Parameters + +`dstHost` + \- Destination device pointer +`srcArray` + \- Source array +`srcOffset` + \- Offset in bytes of source array +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from one 1D CUDA array to host memory. `dstHost` specifies the base pointer of the destination. `srcArray` and `srcOffset` specify the CUDA array handle and starting offset in bytes of the source data. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyAtoHAsync ( void* dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount, CUstream hStream ) + + +Copies memory from Array to Host. + +###### Parameters + +`dstHost` + \- Destination pointer +`srcArray` + \- Source array +`srcOffset` + \- Offset in bytes of source array +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from one 1D CUDA array to host memory. `dstHost` specifies the base pointer of the destination. `srcArray` and `srcOffset` specify the CUDA array handle and starting offset in bytes of the source data. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyBatchAsync ( CUdeviceptr* dsts, CUdeviceptr* srcs, size_t* sizes, size_t count, CUmemcpyAttributes* attrs, size_t* attrsIdxs, size_t numAttrs, CUstream hStream ) + + +Performs a batch of memory copies asynchronously. + +###### Parameters + +`dsts` + \- Array of destination pointers. +`srcs` + \- Array of memcpy source pointers. +`sizes` + \- Array of sizes for memcpy operations. +`count` + \- Size of `dsts`, `srcs` and `sizes` arrays +`attrs` + \- Array of memcpy attributes. +`attrsIdxs` + \- Array of indices to specify which copies each entry in the `attrs` array applies to. The attributes specified in attrs[k] will be applied to copies starting from attrsIdxs[k] through attrsIdxs[k+1] \- 1. Also attrs[numAttrs-1] will apply to copies starting from attrsIdxs[numAttrs-1] through count - 1. +`numAttrs` + \- Size of `attrs` and `attrsIdxs` arrays. +`hStream` + \- The stream to enqueue the operations in. Must not be legacy NULL stream. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. This API only supports pointer-to-pointer copies. For copies involving CUDA arrays, please see cuMemcpy3DBatchAsync. + +Performs memory copies from source buffers specified in `srcs` to destination buffers specified in `dsts`. The size of each copy is specified in `sizes`. All three arrays must be of the same length as specified by `count`. Since there are no ordering guarantees for copies within a batch, specifying any dependent copies within a batch will result in undefined behavior. + +Every copy in the batch has to be associated with a set of attributes specified in the `attrs` array. Each entry in this array can apply to more than one copy. This can be done by specifying in the `attrsIdxs` array, the index of the first copy that the corresponding entry in the `attrs` array applies to. Both `attrs` and `attrsIdxs` must be of the same length as specified by `numAttrs`. For example, if a batch has 10 copies listed in dst/src/sizes, the first 6 of which have one set of attributes and the remaining 4 another, then `numAttrs` will be 2, `attrsIdxs` will be {0, 6} and `attrs` will contains the two sets of attributes. Note that the first entry in `attrsIdxs` must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than `count`. Furthermore, `numAttrs` must be lesser than or equal to `count`. + +The CUmemcpyAttributes::srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_STREAM, then the source will be accessed in stream order. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it's known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to CU_MEMCPY_SRC_ACCESS_ORDER_ANY then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it's known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcpy operation in the batch must have a valid CUmemcpyAttributes corresponding to it including the appropriate srcAccessOrder setting, otherwise the API will return CUDA_ERROR_INVALID_VALUE. + +The CUmemcpyAttributes::srcLocHint and CUmemcpyAttributes::dstLocHint allows applications to specify hint locations for operands of a copy when the operand doesn't have a fixed location. That is, these hints are only applicable for managed memory pointers on devices where CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS is true or system-allocated pageable memory on devices where CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS is true. For other cases, these hints are ignored. + +The CUmemcpyAttributes::flags field can be used to specify certain flags for copies. Setting the CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyDtoA ( CUarray dstArray, size_t dstOffset, CUdeviceptr srcDevice, size_t ByteCount ) + + +Copies memory from Device to Array. + +###### Parameters + +`dstArray` + \- Destination array +`dstOffset` + \- Offset in bytes of destination array +`srcDevice` + \- Source device pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from device memory to a 1D CUDA array. `dstArray` and `dstOffset` specify the CUDA array handle and starting index of the destination data. `srcDevice` specifies the base pointer of the source. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpyDtoD ( CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount ) + + +Copies memory from Device to Device. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`srcDevice` + \- Source device pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from device memory to device memory. `dstDevice` and `srcDevice` are the base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpyDtoDAsync ( CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream ) + + +Copies memory from Device to Device. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`srcDevice` + \- Source device pointer +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from device memory to device memory. `dstDevice` and `srcDevice` are the base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemcpyDtoH ( void* dstHost, CUdeviceptr srcDevice, size_t ByteCount ) + + +Copies memory from Device to Host. + +###### Parameters + +`dstHost` + \- Destination host pointer +`srcDevice` + \- Source device pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from device to host memory. `dstHost` and `srcDevice` specify the base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyDtoHAsync ( void* dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream ) + + +Copies memory from Device to Host. + +###### Parameters + +`dstHost` + \- Destination host pointer +`srcDevice` + \- Source device pointer +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from device to host memory. `dstHost` and `srcDevice` specify the base pointers of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyHtoA ( CUarray dstArray, size_t dstOffset, const void* srcHost, size_t ByteCount ) + + +Copies memory from Host to Array. + +###### Parameters + +`dstArray` + \- Destination array +`dstOffset` + \- Offset in bytes of destination array +`srcHost` + \- Source host pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from host memory to a 1D CUDA array. `dstArray` and `dstOffset` specify the CUDA array handle and starting offset in bytes of the destination data. `pSrc` specifies the base address of the source. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyHtoAAsync ( CUarray dstArray, size_t dstOffset, const void* srcHost, size_t ByteCount, CUstream hStream ) + + +Copies memory from Host to Array. + +###### Parameters + +`dstArray` + \- Destination array +`dstOffset` + \- Offset in bytes of destination array +`srcHost` + \- Source host pointer +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from host memory to a 1D CUDA array. `dstArray` and `dstOffset` specify the CUDA array handle and starting offset in bytes of the destination data. `srcHost` specifies the base address of the source. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyHtoD ( CUdeviceptr dstDevice, const void* srcHost, size_t ByteCount ) + + +Copies memory from Host to Device. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`srcHost` + \- Source host pointer +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from host memory to device memory. `dstDevice` and `srcHost` are the base addresses of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyHtoDAsync ( CUdeviceptr dstDevice, const void* srcHost, size_t ByteCount, CUstream hStream ) + + +Copies memory from Host to Device. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`srcHost` + \- Source host pointer +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from host memory to device memory. `dstDevice` and `srcHost` are the base addresses of the destination and source, respectively. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + * Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return CUDA_ERROR_INVALID_VALUE. + + +CUresult cuMemcpyPeer ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount ) + + +Copies device memory between two contexts. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstContext` + \- Destination context +`srcDevice` + \- Source device pointer +`srcContext` + \- Source context +`ByteCount` + \- Size of memory copy in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies from device memory in one context to device memory in another context. `dstDevice` is the base device pointer of the destination memory and `dstContext` is the destination context. `srcDevice` is the base device pointer of the source memory and `srcContext` is the source pointer. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemcpyPeerAsync ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream ) + + +Copies device memory between two contexts asynchronously. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstContext` + \- Destination context +`srcDevice` + \- Source device pointer +`srcContext` + \- Source context +`ByteCount` + \- Size of memory copy in bytes +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Copies from device memory in one context to device memory in another context. `dstDevice` is the base device pointer of the destination memory and `dstContext` is the destination context. `srcDevice` is the base device pointer of the source memory and `srcContext` is the source pointer. `ByteCount` specifies the number of bytes to copy. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD16 ( CUdeviceptr dstDevice, unsigned short us, size_t N ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`us` + \- Value to set +`N` + \- Number of elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 16-bit values to the specified value `us`. The `dstDevice` pointer must be two byte aligned. + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD16Async ( CUdeviceptr dstDevice, unsigned short us, size_t N, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`us` + \- Value to set +`N` + \- Number of elements +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 16-bit values to the specified value `us`. The `dstDevice` pointer must be two byte aligned. + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD2D16 ( CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`us` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 16-bit values to the specified value `us`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. The `dstDevice` pointer and `dstPitch` offset must be two byte aligned. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD2D16Async ( CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`us` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 16-bit values to the specified value `us`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. The `dstDevice` pointer and `dstPitch` offset must be two byte aligned. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD2D32 ( CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`ui` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 32-bit values to the specified value `ui`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. The `dstDevice` pointer and `dstPitch` offset must be four byte aligned. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD2D32Async ( CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`ui` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 32-bit values to the specified value `ui`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. The `dstDevice` pointer and `dstPitch` offset must be four byte aligned. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD2D8 ( CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`uc` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 8-bit values to the specified value `uc`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD2D8Async ( CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`dstPitch` + \- Pitch of destination device pointer(Unused if `Height` is 1) +`uc` + \- Value to set +`Width` + \- Width of row +`Height` + \- Number of rows +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the 2D memory range of `Width` 8-bit values to the specified value `uc`. `Height` specifies the number of rows to set, and `dstPitch` specifies the number of bytes between each row. This function performs fastest when the pitch is one that has been passed back by cuMemAllocPitch(). + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD32 ( CUdeviceptr dstDevice, unsigned int ui, size_t N ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`ui` + \- Value to set +`N` + \- Number of elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 32-bit values to the specified value `ui`. The `dstDevice` pointer must be four byte aligned. + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD32Async ( CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`ui` + \- Value to set +`N` + \- Number of elements +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 32-bit values to the specified value `ui`. The `dstDevice` pointer must be four byte aligned. + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMemsetD8 ( CUdeviceptr dstDevice, unsigned char uc, size_t N ) + + +Initializes device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`uc` + \- Value to set +`N` + \- Number of elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 8-bit values to the specified value `uc`. + + * + + * See also memset synchronization details. + + +CUresult cuMemsetD8Async ( CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream ) + + +Sets device memory. + +###### Parameters + +`dstDevice` + \- Destination device pointer +`uc` + \- Value to set +`N` + \- Number of elements +`hStream` + \- Stream identifier + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the memory range of `N` 8-bit values to the specified value `uc`. + + * + + * See also memset synchronization details. + + * This function uses standard default stream semantics. + + +CUresult cuMipmappedArrayCreate ( CUmipmappedArray* pHandle, const CUDA_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, unsigned int numMipmapLevels ) + + +Creates a CUDA mipmapped array. + +###### Parameters + +`pHandle` + \- Returned mipmapped array +`pMipmappedArrayDesc` + \- mipmapped array descriptor +`numMipmapLevels` + \- Number of mipmap levels + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Creates a CUDA mipmapped array according to the CUDA_ARRAY3D_DESCRIPTOR structure `pMipmappedArrayDesc` and returns a handle to the new CUDA mipmapped array in `*pHandle`. `numMipmapLevels` specifies the number of mipmap levels to be allocated. This value is clamped to the range [1, 1 + floor(log2(max(width, height, depth)))]. + +The CUDA_ARRAY3D_DESCRIPTOR is defined as: + + + ‎ typedef struct { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + CUarray_format Format; + unsigned int NumChannels; + unsigned int Flags; + } CUDA_ARRAY3D_DESCRIPTOR; + +where: + + * `Width`, `Height`, and `Depth` are the width, height, and depth of the CUDA array (in elements); the following types of CUDA arrays can be allocated: + * A 1D mipmapped array is allocated if `Height` and `Depth` extents are both zero. + + * A 2D mipmapped array is allocated if only `Depth` extent is zero. + + * A 3D mipmapped array is allocated if all three extents are non-zero. + + * A 1D layered CUDA mipmapped array is allocated if only `Height` is zero and the CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 1D array. The number of layers is determined by the depth extent. + + * A 2D layered CUDA mipmapped array is allocated if all three extents are non-zero and the CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 2D array. The number of layers is determined by the depth extent. + + * A cubemap CUDA mipmapped array is allocated if all three extents are non-zero and the CUDA_ARRAY3D_CUBEMAP flag is set. `Width` must be equal to `Height`, and `Depth` must be six. A cubemap is a special type of 2D layered CUDA array, where the six layers represent the six faces of a cube. The order of the six layers in memory is the same as that listed in CUarray_cubemap_face. + + * A cubemap layered CUDA mipmapped array is allocated if all three extents are non-zero, and both, CUDA_ARRAY3D_CUBEMAP and CUDA_ARRAY3D_LAYERED flags are set. `Width` must be equal to `Height`, and `Depth` must be a multiple of six. A cubemap layered CUDA array is a special type of 2D layered CUDA array that consists of a collection of cubemaps. The first six layers represent the first cubemap, the next six layers form the second cubemap, and so on. + + + * Format specifies the format of the elements; CUarray_format is defined as: + + ‎ typedef enum CUarray_format_enum { + CU_AD_FORMAT_UNSIGNED_INT8 = 0x01 + CU_AD_FORMAT_UNSIGNED_INT16 = 0x02 + CU_AD_FORMAT_UNSIGNED_INT32 = 0x03 + CU_AD_FORMAT_SIGNED_INT8 = 0x08 + CU_AD_FORMAT_SIGNED_INT16 = 0x09 + CU_AD_FORMAT_SIGNED_INT32 = 0x0a + CU_AD_FORMAT_HALF = 0x10 + CU_AD_FORMAT_FLOAT = 0x20 + CU_AD_FORMAT_NV12 = 0xb0 + CU_AD_FORMAT_UNORM_INT8X1 = 0xc0 + CU_AD_FORMAT_UNORM_INT8X2 = 0xc1 + CU_AD_FORMAT_UNORM_INT8X4 = 0xc2 + CU_AD_FORMAT_UNORM_INT16X1 = 0xc3 + CU_AD_FORMAT_UNORM_INT16X2 = 0xc4 + CU_AD_FORMAT_UNORM_INT16X4 = 0xc5 + CU_AD_FORMAT_SNORM_INT8X1 = 0xc6 + CU_AD_FORMAT_SNORM_INT8X2 = 0xc7 + CU_AD_FORMAT_SNORM_INT8X4 = 0xc8 + CU_AD_FORMAT_SNORM_INT16X1 = 0xc9 + CU_AD_FORMAT_SNORM_INT16X2 = 0xca + CU_AD_FORMAT_SNORM_INT16X4 = 0xcb + CU_AD_FORMAT_BC1_UNORM = 0x91 + CU_AD_FORMAT_BC1_UNORM_SRGB = 0x92 + CU_AD_FORMAT_BC2_UNORM = 0x93 + CU_AD_FORMAT_BC2_UNORM_SRGB = 0x94 + CU_AD_FORMAT_BC3_UNORM = 0x95 + CU_AD_FORMAT_BC3_UNORM_SRGB = 0x96 + CU_AD_FORMAT_BC4_UNORM = 0x97 + CU_AD_FORMAT_BC4_SNORM = 0x98 + CU_AD_FORMAT_BC5_UNORM = 0x99 + CU_AD_FORMAT_BC5_SNORM = 0x9a + CU_AD_FORMAT_BC6H_UF16 = 0x9b + CU_AD_FORMAT_BC6H_SF16 = 0x9c + CU_AD_FORMAT_BC7_UNORM = 0x9d + CU_AD_FORMAT_BC7_UNORM_SRGB = 0x9e + CU_AD_FORMAT_P010 = 0x9f + CU_AD_FORMAT_P016 = 0xa1 + CU_AD_FORMAT_NV16 = 0xa2 + CU_AD_FORMAT_P210 = 0xa3 + CU_AD_FORMAT_P216 = 0xa4 + CU_AD_FORMAT_YUY2 = 0xa5 + CU_AD_FORMAT_Y210 = 0xa6 + CU_AD_FORMAT_Y216 = 0xa7 + CU_AD_FORMAT_AYUV = 0xa8 + CU_AD_FORMAT_Y410 = 0xa9 + CU_AD_FORMAT_Y416 = 0xb1 + CU_AD_FORMAT_Y444_PLANAR8 = 0xb2 + CU_AD_FORMAT_Y444_PLANAR10 = 0xb3 + CU_AD_FORMAT_YUV444_8bit_SemiPlanar = 0xb4 + CU_AD_FORMAT_YUV444_16bit_SemiPlanar = 0xb5 + CU_AD_FORMAT_UNORM_INT_101010_2 = 0x50 + CU_AD_FORMAT_UINT8_PACKED_422 = 0x51 + CU_AD_FORMAT_UINT8_PACKED_444 = 0x52 + CU_AD_FORMAT_UINT8_SEMIPLANAR_420 = 0x53 + CU_AD_FORMAT_UINT16_SEMIPLANAR_420 = 0x54 + CU_AD_FORMAT_UINT8_SEMIPLANAR_422 = 0x55 + CU_AD_FORMAT_UINT16_SEMIPLANAR_422 = 0x56 + CU_AD_FORMAT_UINT8_SEMIPLANAR_444 = 0x57 + CU_AD_FORMAT_UINT16_SEMIPLANAR_444 = 0x58 + CU_AD_FORMAT_UINT8_PLANAR_420 = 0x59 + CU_AD_FORMAT_UINT16_PLANAR_420 = 0x5a + CU_AD_FORMAT_UINT8_PLANAR_422 = 0x5b + CU_AD_FORMAT_UINT16_PLANAR_422 = 0x5c + CU_AD_FORMAT_UINT8_PLANAR_444 = 0x5d + CU_AD_FORMAT_UINT16_PLANAR_444 = 0x5e + } CUarray_format; + + + * `NumChannels` specifies the number of packed components per CUDA array element; it may be 1, 2, or 4; + + + * Flags may be set to + * CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA mipmapped arrays. If this flag is set, `Depth` specifies the number of layers, not the depth of a 3D array. + + * CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to individual mipmap levels of the CUDA mipmapped array. If this flag is not set, cuSurfRefSetArray will fail when attempting to bind a mipmap level of the CUDA mipmapped array to a surface reference. + + * CUDA_ARRAY3D_CUBEMAP to enable creation of mipmapped cubemaps. If this flag is set, `Width` must be equal to `Height`, and `Depth` must be six. If the CUDA_ARRAY3D_LAYERED flag is also set, then `Depth` must be a multiple of six. + + * CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA mipmapped array will be used for texture gather. Texture gather can only be performed on 2D CUDA mipmapped arrays. + + +`Width`, `Height` and `Depth` must meet certain size requirements as listed in the following table. All values are specified in elements. Note that for brevity's sake, the full name of the device attribute is not specified. For ex., TEXTURE1D_MIPMAPPED_WIDTH refers to the device attribute CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH. + +**CUDA array type** | **Valid extents that must always be met {(width range in elements), (height range), (depth range)}** | **Valid extents with CUDA_ARRAY3D_SURFACE_LDST set {(width range in elements), (height range), (depth range)}** +---|---|--- +1D | { (1,TEXTURE1D_MIPMAPPED_WIDTH), 0, 0 } | { (1,SURFACE1D_WIDTH), 0, 0 } +2D | { (1,TEXTURE2D_MIPMAPPED_WIDTH), (1,TEXTURE2D_MIPMAPPED_HEIGHT), 0 } | { (1,SURFACE2D_WIDTH), (1,SURFACE2D_HEIGHT), 0 } +3D | { (1,TEXTURE3D_WIDTH), (1,TEXTURE3D_HEIGHT), (1,TEXTURE3D_DEPTH) } OR { (1,TEXTURE3D_WIDTH_ALTERNATE), (1,TEXTURE3D_HEIGHT_ALTERNATE), (1,TEXTURE3D_DEPTH_ALTERNATE) } | { (1,SURFACE3D_WIDTH), (1,SURFACE3D_HEIGHT), (1,SURFACE3D_DEPTH) } +1D Layered | { (1,TEXTURE1D_LAYERED_WIDTH), 0, (1,TEXTURE1D_LAYERED_LAYERS) } | { (1,SURFACE1D_LAYERED_WIDTH), 0, (1,SURFACE1D_LAYERED_LAYERS) } +2D Layered | { (1,TEXTURE2D_LAYERED_WIDTH), (1,TEXTURE2D_LAYERED_HEIGHT), (1,TEXTURE2D_LAYERED_LAYERS) } | { (1,SURFACE2D_LAYERED_WIDTH), (1,SURFACE2D_LAYERED_HEIGHT), (1,SURFACE2D_LAYERED_LAYERS) } +Cubemap | { (1,TEXTURECUBEMAP_WIDTH), (1,TEXTURECUBEMAP_WIDTH), 6 } | { (1,SURFACECUBEMAP_WIDTH), (1,SURFACECUBEMAP_WIDTH), 6 } +Cubemap Layered | { (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_LAYERS) } | { (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_LAYERS) } + +CUresult cuMipmappedArrayDestroy ( CUmipmappedArray hMipmappedArray ) + + +Destroys a CUDA mipmapped array. + +###### Parameters + +`hMipmappedArray` + \- Mipmapped array to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ARRAY_IS_MAPPED, CUDA_ERROR_CONTEXT_IS_DESTROYED + +###### Description + +Destroys the CUDA mipmapped array `hMipmappedArray`. + +CUresult cuMipmappedArrayGetLevel ( CUarray* pLevelArray, CUmipmappedArray hMipmappedArray, unsigned int level ) + + +Gets a mipmap level of a CUDA mipmapped array. + +###### Parameters + +`pLevelArray` + \- Returned mipmap level CUDA array +`hMipmappedArray` + \- CUDA mipmapped array +`level` + \- Mipmap level + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns in `*pLevelArray` a CUDA array that represents a single mipmap level of the CUDA mipmapped array `hMipmappedArray`. + +If `level` is greater than the maximum number of levels in this mipmapped array, CUDA_ERROR_INVALID_VALUE is returned. + +CUresult cuMipmappedArrayGetMemoryRequirements ( CUDA_ARRAY_MEMORY_REQUIREMENTS* memoryRequirements, CUmipmappedArray mipmap, CUdevice device ) + + +Returns the memory requirements of a CUDA mipmapped array. + +###### Parameters + +`memoryRequirements` + \- Pointer to CUDA_ARRAY_MEMORY_REQUIREMENTS +`mipmap` + \- CUDA mipmapped array to get the memory requirements of +`device` + \- Device to get the memory requirements for + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the memory requirements of a CUDA mipmapped array in `memoryRequirements` If the CUDA mipmapped array is not allocated with flag CUDA_ARRAY3D_DEFERRED_MAPPINGCUDA_ERROR_INVALID_VALUE will be returned. + +The returned value in CUDA_ARRAY_MEMORY_REQUIREMENTS::size represents the total size of the CUDA mipmapped array. The returned value in CUDA_ARRAY_MEMORY_REQUIREMENTS::alignment represents the alignment necessary for mapping the CUDA mipmapped array. + +CUresult cuMipmappedArrayGetSparseProperties ( CUDA_ARRAY_SPARSE_PROPERTIES* sparseProperties, CUmipmappedArray mipmap ) + + +Returns the layout properties of a sparse CUDA mipmapped array. + +###### Parameters + +`sparseProperties` + \- Pointer to CUDA_ARRAY_SPARSE_PROPERTIES +`mipmap` + \- CUDA mipmapped array to get the sparse properties of + +###### Returns + +CUDA_SUCCESSCUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the sparse array layout properties in `sparseProperties` If the CUDA mipmapped array is not allocated with flag CUDA_ARRAY3D_SPARSECUDA_ERROR_INVALID_VALUE will be returned. + +For non-layered CUDA mipmapped arrays, CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize returns the size of the mip tail region. The mip tail region includes all mip levels whose width, height or depth is less than that of the tile. For layered CUDA mipmapped arrays, if CUDA_ARRAY_SPARSE_PROPERTIES::flags contains CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, then CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize specifies the size of the mip tail of all layers combined. Otherwise, CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize specifies mip tail size per layer. The returned value of CUDA_ARRAY_SPARSE_PROPERTIES::miptailFirstLevel is valid only if CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize is non-zero. diff --git a/content/cuda/docs/driver-memop/DOC.md b/content/cuda/docs/driver-memop/DOC.md new file mode 100644 index 00000000..b130a17f --- /dev/null +++ b/content/cuda/docs/driver-memop/DOC.md @@ -0,0 +1,164 @@ +--- +name: driver-memop +description: '**Source:** group__CUDA__MEMOP.html#group__CUDA__MEMOP' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.21. Stream Memory Operations + +**Source:** group__CUDA__MEMOP.html#group__CUDA__MEMOP + + +### Functions + +CUresult cuStreamBatchMemOp ( CUstream stream, unsigned int count, CUstreamBatchMemOpParams* paramArray, unsigned int flags ) + + +Batch operations to synchronize the stream via memory operations. + +###### Parameters + +`stream` + The stream to enqueue the operations in. +`count` + The number of operations in the array. Must be less than 256. +`paramArray` + The types and parameters of the individual operations. +`flags` + Reserved for future expansion; must be 0. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +This is a batch version of cuStreamWaitValue32() and cuStreamWriteValue32(). Batching operations may avoid some performance overhead in both the API call and the device execution versus adding them to the stream in separate API calls. The operations are enqueued in the order they appear in the array. + +See CUstreamBatchMemOpType for the full set of supported operations, and cuStreamWaitValue32(), cuStreamWaitValue64(), cuStreamWriteValue32(), and cuStreamWriteValue64() for details of specific operations. + +See related APIs for details on querying support for specific operations. + +Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order. + +CUresult cuStreamWaitValue32 ( CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags ) + + +Wait on a memory location. + +###### Parameters + +`stream` + The stream to synchronize on the memory location. +`addr` + The memory location to wait on. +`value` + The value to compare with the memory location. +`flags` + See CUstreamWaitValue_flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Enqueues a synchronization of the stream on the given memory location. Work ordered after the operation will block until the given condition on the memory is satisfied. By default, the condition is to wait for (int32_t)(*addr - value) >= 0, a cyclic greater-or-equal. Other condition types can be specified via `flags`. + +If the memory was registered via cuMemHostRegister(), the device pointer should be obtained with cuMemHostGetDevicePointer(). This function cannot be used with managed memory (cuMemAllocManaged). + +Support for CU_STREAM_WAIT_VALUE_NOR can be queried with cuDeviceGetAttribute() and CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V2. + +Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order. + +CUresult cuStreamWaitValue64 ( CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags ) + + +Wait on a memory location. + +###### Parameters + +`stream` + The stream to synchronize on the memory location. +`addr` + The memory location to wait on. +`value` + The value to compare with the memory location. +`flags` + See CUstreamWaitValue_flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Enqueues a synchronization of the stream on the given memory location. Work ordered after the operation will block until the given condition on the memory is satisfied. By default, the condition is to wait for (int64_t)(*addr - value) >= 0, a cyclic greater-or-equal. Other condition types can be specified via `flags`. + +If the memory was registered via cuMemHostRegister(), the device pointer should be obtained with cuMemHostGetDevicePointer(). + +Support for this can be queried with cuDeviceGetAttribute() and CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. + +Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order. + +CUresult cuStreamWriteValue32 ( CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags ) + + +Write a value to memory. + +###### Parameters + +`stream` + The stream to do the write in. +`addr` + The device address to write to. +`value` + The value to write. +`flags` + See CUstreamWriteValue_flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Write a value to memory. + +If the memory was registered via cuMemHostRegister(), the device pointer should be obtained with cuMemHostGetDevicePointer(). This function cannot be used with managed memory (cuMemAllocManaged). + +CUresult cuStreamWriteValue64 ( CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags ) + + +Write a value to memory. + +###### Parameters + +`stream` + The stream to do the write in. +`addr` + The device address to write to. +`value` + The value to write. +`flags` + See CUstreamWriteValue_flags. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Write a value to memory. + +If the memory was registered via cuMemHostRegister(), the device pointer should be obtained with cuMemHostGetDevicePointer(). + +Support for this can be queried with cuDeviceGetAttribute() and CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. + + diff --git a/content/cuda/docs/driver-module--deprecated/DOC.md b/content/cuda/docs/driver-module--deprecated/DOC.md new file mode 100644 index 00000000..4977ebc5 --- /dev/null +++ b/content/cuda/docs/driver-module--deprecated/DOC.md @@ -0,0 +1,68 @@ +--- +name: driver-module--deprecated +description: '**Source:** group__CUDA__MODULE__DEPRECATED.html#group__CUDA__MODULE__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.11. Module Management [DEPRECATED] + +**Source:** group__CUDA__MODULE__DEPRECATED.html#group__CUDA__MODULE__DEPRECATED + + +### Functions + +CUresult cuModuleGetSurfRef ( CUsurfref* pSurfRef, CUmodule hmod, const char* name ) + + +Returns a handle to a surface reference. + +###### Parameters + +`pSurfRef` + \- Returned surface reference +`hmod` + \- Module to retrieve surface reference from +`name` + \- Name of surface reference to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND + +###### Deprecated + +###### Description + +Returns in `*pSurfRef` the handle of the surface reference of name `name` in the module `hmod`. If no surface reference of that name exists, cuModuleGetSurfRef() returns CUDA_ERROR_NOT_FOUND. + +CUresult cuModuleGetTexRef ( CUtexref* pTexRef, CUmodule hmod, const char* name ) + + +Returns a handle to a texture reference. + +###### Parameters + +`pTexRef` + \- Returned texture reference +`hmod` + \- Module to retrieve texture reference from +`name` + \- Name of texture reference to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND + +###### Deprecated + +###### Description + +Returns in `*pTexRef` the handle of the texture reference of name `name` in the module `hmod`. If no texture reference of that name exists, cuModuleGetTexRef() returns CUDA_ERROR_NOT_FOUND. This texture reference handle should not be destroyed, since it will be destroyed when the module is unloaded. + + diff --git a/content/cuda/docs/driver-module/DOC.md b/content/cuda/docs/driver-module/DOC.md new file mode 100644 index 00000000..fcd194d3 --- /dev/null +++ b/content/cuda/docs/driver-module/DOC.md @@ -0,0 +1,380 @@ +--- +name: driver-module +description: '**Source:** group__CUDA__MODULE.html#group__CUDA__MODULE' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.10. Module Management + +**Source:** group__CUDA__MODULE.html#group__CUDA__MODULE + + +### Enumerations + +enum CUmoduleLoadingMode + + +### Functions + +CUresult cuLinkAddData ( CUlinkState state, CUjitInputType type, void* data, size_t size, const char* name, unsigned int numOptions, CUjit_option* options, void** optionValues ) + + +Add an input to a pending linker invocation. + +###### Parameters + +`state` + A pending linker action. +`type` + The type of the input data. +`data` + The input data. PTX must be NULL-terminated. +`size` + The length of the input data. +`name` + An optional name for this input in log messages. +`numOptions` + Size of options. +`options` + Options to be applied only for this input (overrides options from cuLinkCreate). +`optionValues` + Array of option values, each cast to void *. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU + +###### Description + +Ownership of `data` is retained by the caller. No reference is retained to any inputs after this call returns. + +This method accepts only compiler options, which are used if the data must be compiled from PTX, and does not accept any of CU_JIT_WALL_TIME, CU_JIT_INFO_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER, CU_JIT_TARGET_FROM_CUCONTEXT, or CU_JIT_TARGET. + +For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted + +CUresult cuLinkAddFile ( CUlinkState state, CUjitInputType type, const char* path, unsigned int numOptions, CUjit_option* options, void** optionValues ) + + +Add a file input to a pending linker invocation. + +###### Parameters + +`state` + A pending linker action +`type` + The type of the input data +`path` + Path to the input file +`numOptions` + Size of options +`options` + Options to be applied only for this input (overrides options from cuLinkCreate) +`optionValues` + Array of option values, each cast to void * + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_FILE_NOT_FOUNDCUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_IMAGE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU + +###### Description + +No reference is retained to any inputs after this call returns. + +This method accepts only compiler options, which are used if the input must be compiled from PTX, and does not accept any of CU_JIT_WALL_TIME, CU_JIT_INFO_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER, CU_JIT_TARGET_FROM_CUCONTEXT, or CU_JIT_TARGET. + +This method is equivalent to invoking cuLinkAddData on the contents of the file. + +For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted + +CUresult cuLinkComplete ( CUlinkState state, void** cubinOut, size_t* sizeOut ) + + +Complete a pending linker invocation. + +###### Parameters + +`state` + A pending linker invocation +`cubinOut` + On success, this will point to the output image +`sizeOut` + Optional parameter to receive the size of the generated image + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Completes the pending linker action and returns the cubin image for the linked device code, which can be used with cuModuleLoadData. The cubin is owned by `state`, so it should be loaded before `state` is destroyed via cuLinkDestroy. This call does not destroy `state`. + +CUresult cuLinkCreate ( unsigned int numOptions, CUjit_option* options, void** optionValues, CUlinkState* stateOut ) + + +Creates a pending JIT linker invocation. + +###### Parameters + +`numOptions` + Size of options arrays +`options` + Array of linker and compiler options +`optionValues` + Array of option values, each cast to void * +`stateOut` + On success, this will contain a CUlinkState to specify and complete this action + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_JIT_COMPILER_NOT_FOUND + +###### Description + +If the call is successful, the caller owns the returned CUlinkState, which should eventually be destroyed with cuLinkDestroy. The device code machine size (32 or 64 bit) will match the calling application. + +Both linker and compiler options may be specified. Compiler options will be applied to inputs to this linker action which must be compiled from PTX. The options CU_JIT_WALL_TIME, CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, and CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES will accumulate data until the CUlinkState is destroyed. + +The data passed in via cuLinkAddData and cuLinkAddFile will be treated as relocatable (-rdc=true to nvcc) when linking the final cubin during cuLinkComplete and will have similar consequences as offline relocatable device code linking. + +`optionValues` must remain valid for the life of the CUlinkState if output options are used. No other references to inputs are maintained after this call returns. + +For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted + +CUresult cuLinkDestroy ( CUlinkState state ) + + +Destroys state for a JIT linker invocation. + +###### Parameters + +`state` + State object for the linker invocation + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE + +###### Description + +CUresult cuModuleEnumerateFunctions ( CUfunction* functions, unsigned int numFunctions, CUmodule mod ) + + +Returns the function handles within a module. + +###### Parameters + +`functions` + \- Buffer where the function handles are returned to +`numFunctions` + \- Maximum number of function handles may be returned to the buffer +`mod` + \- Module to query from + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `functions` a maximum number of `numFunctions` function handles within `mod`. When function loading mode is set to LAZY the function retrieved may be partially loaded. The loading state of a function can be queried using cuFunctionIsLoaded. CUDA APIs may load the function automatically when called with partially loaded function handle which may incur additional latency. Alternatively, cuFunctionLoad can be used to explicitly load a function. The returned function handles become invalid when the module is unloaded. + +CUresult cuModuleGetFunction ( CUfunction* hfunc, CUmodule hmod, const char* name ) + + +Returns a function handle. + +###### Parameters + +`hfunc` + \- Returned function handle +`hmod` + \- Module to retrieve function from +`name` + \- Name of function to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `*hfunc` the handle of the function of name `name` located in module `hmod`. If no function of that name exists, cuModuleGetFunction() returns CUDA_ERROR_NOT_FOUND. + +CUresult cuModuleGetFunctionCount ( unsigned int* count, CUmodule mod ) + + +Returns the number of functions within a module. + +###### Parameters + +`count` + \- Number of functions found within the module +`mod` + \- Module to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `count` the number of functions in `mod`. + +CUresult cuModuleGetGlobal ( CUdeviceptr* dptr, size_t* bytes, CUmodule hmod, const char* name ) + + +Returns a global pointer from a module. + +###### Parameters + +`dptr` + \- Returned global device pointer +`bytes` + \- Returned global size in bytes +`hmod` + \- Module to retrieve global from +`name` + \- Name of global to retrieve + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_FOUND + +###### Description + +Returns in `*dptr` and `*bytes` the base pointer and size of the global of name `name` located in module `hmod`. If no variable of that name exists, cuModuleGetGlobal() returns CUDA_ERROR_NOT_FOUND. One of the parameters `dptr` or `bytes` (not both) can be NULL in which case it is ignored. + +CUresult cuModuleGetLoadingMode ( CUmoduleLoadingMode* mode ) + + +Query lazy loading mode. + +###### Parameters + +`mode` + \- Returns the lazy loading mode + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns lazy loading mode Module loading mode is controlled by CUDA_MODULE_LOADING env variable + +CUresult cuModuleLoad ( CUmodule* module, const char* fname ) + + +Loads a compute module. + +###### Parameters + +`module` + \- Returned module +`fname` + \- Filename of module to load + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_FILE_NOT_FOUND, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND + +###### Description + +Takes a filename `fname` and loads the corresponding module `module` into the current context. The CUDA driver API does not attempt to lazily allocate the resources needed by a module; if the memory for functions and data (constant and global) needed by the module cannot be allocated, cuModuleLoad() fails. The file should be a cubin file as output by **nvcc** , or a PTX file either as output by **nvcc** or handwritten, or a fatbin file as output by **nvcc** from toolchain 4.0 or later, or a Tile IR file. + +CUresult cuModuleLoadData ( CUmodule* module, const void* image ) + + +Load a module's data. + +###### Parameters + +`module` + \- Returned module +`image` + \- Module data to load + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND + +###### Description + +Takes a pointer `image` and loads the corresponding module `module` into the current context. The `image` may be a cubin or fatbin as output by **nvcc** , or a NULL-terminated PTX, either as output by **nvcc** or hand-written, or Tile IR data. + +CUresult cuModuleLoadDataEx ( CUmodule* module, const void* image, unsigned int numOptions, CUjit_option* options, void** optionValues ) + + +Load a module's data with options. + +###### Parameters + +`module` + \- Returned module +`image` + \- Module data to load +`numOptions` + \- Number of options +`options` + \- Options for JIT +`optionValues` + \- Option values for JIT + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND + +###### Description + +Takes a pointer `image` and loads the corresponding module `module` into the current context. The `image` may be a cubin or fatbin as output by **nvcc** , or a NULL-terminated PTX, either as output by **nvcc** or hand-written, or Tile IR data. + +CUresult cuModuleLoadFatBinary ( CUmodule* module, const void* fatCubin ) + + +Load a module's data. + +###### Parameters + +`module` + \- Returned module +`fatCubin` + \- Fat binary to load + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_PTX, CUDA_ERROR_UNSUPPORTED_PTX_VERSION, CUDA_ERROR_NOT_FOUND, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NO_BINARY_FOR_GPU, CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, CUDA_ERROR_JIT_COMPILER_NOT_FOUND + +###### Description + +Takes a pointer `fatCubin` and loads the corresponding module `module` into the current context. The pointer represents a fat binary object, which is a collection of different cubin and/or PTX files, all representing the same device code, but compiled and optimized for different architectures. + +Prior to CUDA 4.0, there was no documented API for constructing and using fat binary objects by programmers. Starting with CUDA 4.0, fat binary objects can be constructed by providing the -fatbin option to **nvcc**. More information can be found in the **nvcc** document. + +CUresult cuModuleUnload ( CUmodule hmod ) + + +Unloads a module. + +###### Parameters + +`hmod` + \- Module to unload + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_PERMITTED + +###### Description + +Unloads a module `hmod` from the current context. Attempting to unload a module which was obtained from the Library Management API such as cuLibraryGetModule will return CUDA_ERROR_NOT_PERMITTED. + + * + + * Use of the handle after this call is undefined behavior. + diff --git a/content/cuda/docs/driver-multicast/DOC.md b/content/cuda/docs/driver-multicast/DOC.md new file mode 100644 index 00000000..6a58550f --- /dev/null +++ b/content/cuda/docs/driver-multicast/DOC.md @@ -0,0 +1,236 @@ +--- +name: driver-multicast +description: '**Source:** group__CUDA__MULTICAST.html#group__CUDA__MULTICAST' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.16. Multicast Object Management + +**Source:** group__CUDA__MULTICAST.html#group__CUDA__MULTICAST + + +### Functions + +CUresult cuMulticastAddDevice ( CUmemGenericAllocationHandle mcHandle, CUdevice dev ) + + +Associate a device to a multicast object. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`dev` + Device that will be associated to the multicast object. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Associates a device to a multicast object. The added device will be a part of the multicast team of size specified by CUmulticastObjectProp::numDevices during cuMulticastCreate. The association of the device to the multicast object is permanent during the life time of the multicast object. All devices must be added to the multicast team before any memory can be bound to any device in the team. Any calls to cuMulticastBindMem, cuMulticastBindMem_v2, cuMulticastBindAddr, or cuMulticastBindAddr_v2 will block until all devices have been added. Similarly all devices must be added to the multicast team before a virtual address range can be mapped to the multicast object. A call to cuMemMap will block until all devices have been added. + +CUresult cuMulticastBindAddr ( CUmemGenericAllocationHandle mcHandle, size_t mcOffset, CUdeviceptr memptr, size_t size, unsigned long long flags ) + + +Bind a memory allocation represented by a virtual address to a multicast object. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`mcOffset` + Offset into multicast va range for attachment. +`memptr` + Virtual address of the memory allocation. +`size` + Size of memory that will be bound to the multicast object. +`flags` + Flags for future use, must be zero now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_SYSTEM_NOT_READY, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Binds a memory allocation specified by its mapped address `memptr` to a multicast object represented by `mcHandle`. The memory must have been allocated via cuMemCreate or cudaMallocAsync. The intended `size` of the bind, the offset in the multicast range `mcOffset` and `memptr` must be a multiple of the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_MINIMUM. For best performance however, `size`, `mcOffset` and `memptr` should be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_RECOMMENDED. + +The `size` cannot be larger than the size of the allocated memory. Similarly the `size` \+ `mcOffset` cannot be larger than the total size of the multicast object. The memory allocation must have beeen created on one of the devices that was added to the multicast team via cuMulticastAddDevice. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if the necessary system software is not initialized or running. + +This call may return CUDA_ERROR_ILLEGAL_STATE if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. + +CUresult cuMulticastBindAddr_v2 ( CUmemGenericAllocationHandle mcHandle, CUdevice dev, size_t mcOffset, CUdeviceptr memptr, size_t size, unsigned long long flags ) + + +Bind a memory allocation represented by a virtual address to a multicast object. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`dev` + The device that for which the multicast memory binding will be applicable. +`mcOffset` + Offset into multicast va range for attachment. +`memptr` + Virtual address of the memory allocation. +`size` + Size of memory that will be bound to the multicast object. +`flags` + Flags for future use, must be zero now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_SYSTEM_NOT_READY, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Binds a memory allocation specified by its mapped address `memptr` to a multicast object represented by `mcHandle`. The binding will be applicable for the device `dev`. The memory must have been allocated via cuMemCreate or cudaMallocAsync. The intended `size` of the bind, the offset in the multicast range `mcOffset` and `memptr` must be a multiple of the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_MINIMUM. For best performance however, `size`, `mcOffset` and `memptr` should be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_RECOMMENDED. + +The `size` cannot be larger than the size of the allocated memory. Similarly the `size` \+ `mcOffset` cannot be larger than the total size of the multicast object. For device memory, i.e., type CU_MEM_LOCATION_TYPE_DEVICE, the memory allocation must have been created on the device specified by `dev`. For host NUMA memory, i.e., type CU_MEM_LOCATION_TYPE_HOST_NUMA, the memory allocation must have been created on the CPU NUMA node closest to `dev`. That is, the value returned when querying CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID for `dev`, must be the CPU NUMA node where the memory was allocated. In both cases, the device named by `dev` must have been added to the multicast team via cuMulticastAddDevice. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if the necessary system software is not initialized or running. + +This call may return CUDA_ERROR_ILLEGAL_STATE if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. + +CUresult cuMulticastBindMem ( CUmemGenericAllocationHandle mcHandle, size_t mcOffset, CUmemGenericAllocationHandle memHandle, size_t memOffset, size_t size, unsigned long long flags ) + + +Bind a memory allocation represented by a handle to a multicast object. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`mcOffset` + Offset into the multicast object for attachment. +`memHandle` + Handle representing a memory allocation. +`memOffset` + Offset into the memory for attachment. +`size` + Size of the memory that will be bound to the multicast object. +`flags` + Flags for future use, must be zero for now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_SYSTEM_NOT_READY, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Binds a memory allocation specified by `memHandle` and created via cuMemCreate to a multicast object represented by `mcHandle` and created via cuMulticastCreate. The intended `size` of the bind, the offset in the multicast range `mcOffset` as well as the offset in the memory `memOffset` must be a multiple of the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_MINIMUM. For best performance however, `size`, `mcOffset` and `memOffset` should be aligned to the granularity of the memory allocation(see ::cuMemGetAllocationGranularity) or to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_RECOMMENDED. + +The `size` \+ `memOffset` cannot be larger than the size of the allocated memory. Similarly the `size` \+ `mcOffset` cannot be larger than the size of the multicast object. The memory allocation must have beeen created on one of the devices that was added to the multicast team via cuMulticastAddDevice. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if the necessary system software is not initialized or running. + +This call may return CUDA_ERROR_ILLEGAL_STATE if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. + +CUresult cuMulticastBindMem_v2 ( CUmemGenericAllocationHandle mcHandle, CUdevice dev, size_t mcOffset, CUmemGenericAllocationHandle memHandle, size_t memOffset, size_t size, unsigned long long flags ) + + +Bind a memory allocation represented by a handle to a multicast object. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`dev` + The device that for which the multicast memory binding will be applicable. +`mcOffset` + Offset into the multicast object for attachment. +`memHandle` + Handle representing a memory allocation. +`memOffset` + Offset into the memory for attachment. +`size` + Size of the memory that will be bound to the multicast object. +`flags` + Flags for future use, must be zero for now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_SYSTEM_NOT_READY, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Binds a memory allocation specified by `memHandle` and created via cuMemCreate to a multicast object represented by `mcHandle` and created via cuMulticastCreate. The binding will be applicable for the device `dev`. The intended `size` of the bind, the offset in the multicast range `mcOffset` as well as the offset in the memory `memOffset` must be a multiple of the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_MINIMUM. For best performance however, `size`, `mcOffset` and `memOffset` should be aligned to the granularity of the memory allocation(see ::cuMemGetAllocationGranularity) or to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_RECOMMENDED. + +The `size` \+ `memOffset` cannot be larger than the size of the allocated memory. Similarly the `size` \+ `mcOffset` cannot be larger than the size of the multicast object. The memory allocation must have beeen created on one of the devices that was added to the multicast team via cuMulticastAddDevice. For device memory, i.e., type CU_MEM_LOCATION_TYPE_DEVICE, the memory allocation must have been created on the device specified by `dev`. For host NUMA memory, i.e., type CU_MEM_LOCATION_TYPE_HOST_NUMA, the memory allocation must have been created on the CPU NUMA node closest to `dev`. That is, the value returned when querying CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID for `dev`, must be the CPU NUMA node where the memory was allocated. In both cases, the device named by `dev` must have been added to the multicast team via cuMulticastAddDevice. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if the necessary system software is not initialized or running. + +This call may return CUDA_ERROR_ILLEGAL_STATE if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. + +CUresult cuMulticastCreate ( CUmemGenericAllocationHandle* mcHandle, const CUmulticastObjectProp* prop ) + + +Create a generic allocation handle representing a multicast object described by the given properties. + +###### Parameters + +`mcHandle` + Value of handle returned. +`prop` + Properties of the multicast object to create. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +This creates a multicast object as described by `prop`. The number of participating devices is specified by CUmulticastObjectProp::numDevices. Devices can be added to the multicast object via cuMulticastAddDevice. All participating devices must be added to the multicast object before memory can be bound to it. Memory is bound to the multicast object via cuMulticastBindMem, cuMulticastBindMem_v2, cuMulticastBindAddr, or cuMulticastBindAddr_v2. and can be unbound via cuMulticastUnbind. The total amount of memory that can be bound per device is specified by :CUmulticastObjectProp::size. This size must be a multiple of the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_MINIMUM. For best performance however, the size should be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_GRANULARITY_RECOMMENDED. + +After all participating devices have been added, multicast objects can also be mapped to a device's virtual address space using the virtual memory management APIs (see cuMemMap and cuMemSetAccess). Multicast objects can also be shared with other processes by requesting a shareable handle via cuMemExportToShareableHandle. Note that the desired types of shareable handles must be specified in the bitmask CUmulticastObjectProp::handleTypes. Multicast objects can be released using the virtual memory management API cuMemRelease. + +CUresult cuMulticastGetGranularity ( size_t* granularity, const CUmulticastObjectProp* prop, CUmulticastGranularity_flags option ) + + +Calculates either the minimal or recommended granularity for multicast object. + +###### Parameters + +`granularity` + Returned granularity. +`prop` + Properties of the multicast object. +`option` + Determines which granularity to return. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Calculates either the minimal or recommended granularity for a given set of multicast object properties and returns it in granularity. This granularity can be used as a multiple for size, bind offsets and address mappings of the multicast object. + +CUresult cuMulticastUnbind ( CUmemGenericAllocationHandle mcHandle, CUdevice dev, size_t mcOffset, size_t size ) + + +Unbind any memory allocations bound to a multicast object at a given offset and upto a given size. + +###### Parameters + +`mcHandle` + Handle representing a multicast object. +`dev` + Device that hosts the memory allocation. +`mcOffset` + Offset into the multicast object. +`size` + Desired size to unbind. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Unbinds any memory allocations hosted on `dev` and bound to a multicast object at `mcOffset` and upto a given `size`. The intended `size` of the unbind and the offset in the multicast range ( `mcOffset` ) must be a multiple of the value returned by cuMulticastGetGranularity flag CU_MULTICAST_GRANULARITY_MINIMUM. The `size` \+ `mcOffset` cannot be larger than the total size of the multicast object. + +Warning: The `mcOffset` and the `size` must match the corresponding values specified during the bind call. Any other values may result in undefined behavior. diff --git a/content/cuda/docs/driver-occupancy/DOC.md b/content/cuda/docs/driver-occupancy/DOC.md new file mode 100644 index 00000000..55e86827 --- /dev/null +++ b/content/cuda/docs/driver-occupancy/DOC.md @@ -0,0 +1,246 @@ +--- +name: driver-occupancy +description: '**Source:** group__CUDA__OCCUPANCY.html#group__CUDA__OCCUPANCY' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.25. Occupancy + +**Source:** group__CUDA__OCCUPANCY.html#group__CUDA__OCCUPANCY + + +### Functions + +CUresult cuOccupancyAvailableDynamicSMemPerBlock ( size_t* dynamicSmemSize, CUfunction func, int numBlocks, int blockSize ) + + +Returns dynamic shared memory available per block when launching `numBlocks` blocks on SM. + +###### Parameters + +`dynamicSmemSize` + \- Returned maximum dynamic shared memory +`func` + \- Kernel function for which occupancy is calculated +`numBlocks` + \- Number of blocks to fit on SM +`blockSize` + \- Size of the blocks + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*dynamicSmemSize` the maximum size of dynamic shared memory to allow `numBlocks` blocks per SM. + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will be the current context. + + + +CUresult cuOccupancyMaxActiveBlocksPerMultiprocessor ( int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize ) + + +Returns occupancy of a function. + +###### Parameters + +`numBlocks` + \- Returned occupancy +`func` + \- Kernel for which occupancy is calculated +`blockSize` + \- Block size the kernel is intended to be launched with +`dynamicSMemSize` + \- Per-block dynamic shared memory usage intended, in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*numBlocks` the number of the maximum active blocks per streaming multiprocessor. + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will be the current context. + +CUresult cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags ( int* numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned int flags ) + + +Returns occupancy of a function. + +###### Parameters + +`numBlocks` + \- Returned occupancy +`func` + \- Kernel for which occupancy is calculated +`blockSize` + \- Block size the kernel is intended to be launched with +`dynamicSMemSize` + \- Per-block dynamic shared memory usage intended, in bytes +`flags` + \- Requested behavior for the occupancy calculator + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*numBlocks` the number of the maximum active blocks per streaming multiprocessor. + +The `Flags` parameter controls how special cases are handled. The valid flags are: + + * CU_OCCUPANCY_DEFAULT, which maintains the default behavior as cuOccupancyMaxActiveBlocksPerMultiprocessor; + + + * CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE, which suppresses the default behavior on platform where global caching affects occupancy. On such platforms, if caching is enabled, but per-block SM resource usage would result in zero occupancy, the occupancy calculator will calculate the occupancy as if caching is disabled. Setting CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE makes the occupancy calculator to return 0 in such cases. More information can be found about this feature in the "Unified L1/Texture Cache" section of the Maxwell tuning guide. + + +Note that the API can also be with launch context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will be the current context. + +CUresult cuOccupancyMaxActiveClusters ( int* numClusters, CUfunction func, const CUlaunchConfig* config ) + + +Given the kernel function (`func`) and launch configuration (`config`), return the maximum number of clusters that could co-exist on the target device in `*numClusters`. + +###### Parameters + +`numClusters` + \- Returned maximum number of clusters that could co-exist on the target device +`func` + \- Kernel function for which maximum number of clusters are calculated +`config` + \- Launch configuration for the given kernel function + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_CLUSTER_SIZE, CUDA_ERROR_UNKNOWN + +###### Description + +If the function has required cluster size already set (see cudaFuncGetAttributes / cuFuncGetAttribute), the cluster size from config must either be unspecified or match the required size. Without required sizes, the cluster size must be specified in config, else the function will return an error. + +Note that various attributes of the kernel function may affect occupancy calculation. Runtime environment may affect how the hardware schedules the clusters, so the calculated occupancy is not guaranteed to be achievable. + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will either be taken from the specified stream `config->hStream` or the current context in case of NULL stream. + +CUresult cuOccupancyMaxPotentialBlockSize ( int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit ) + + +Suggest a launch configuration with reasonable occupancy. + +###### Parameters + +`minGridSize` + \- Returned minimum grid size needed to achieve the maximum occupancy +`blockSize` + \- Returned maximum block size that can achieve the maximum occupancy +`func` + \- Kernel for which launch configuration is calculated +`blockSizeToDynamicSMemSize` + \- A function that calculates how much per-block dynamic shared memory `func` uses based on the block size +`dynamicSMemSize` + \- Dynamic shared memory usage intended, in bytes +`blockSizeLimit` + \- The maximum block size `func` is designed to handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +Returns in `*blockSize` a reasonable block size that can achieve the maximum occupancy (or, the maximum number of active warps with the fewest blocks per multiprocessor), and in `*minGridSize` the minimum grid size to achieve the maximum occupancy. + +If `blockSizeLimit` is 0, the configurator will use the maximum block size permitted by the device / function instead. + +If per-block dynamic shared memory allocation is not needed, the user should leave both `blockSizeToDynamicSMemSize` and `dynamicSMemSize` as 0. + +If per-block dynamic shared memory allocation is needed, then if the dynamic shared memory size is constant regardless of block size, the size should be passed through `dynamicSMemSize`, and `blockSizeToDynamicSMemSize` should be NULL. + +Otherwise, if the per-block dynamic shared memory size varies with different block sizes, the user needs to provide a unary function through `blockSizeToDynamicSMemSize` that computes the dynamic shared memory needed by `func` for any given block size. `dynamicSMemSize` is ignored. An example signature is: + + + ‎ // Take block size, returns dynamic shared memory needed + size_t blockToSmem(int blockSize); + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will be the current context. + +CUresult cuOccupancyMaxPotentialBlockSizeWithFlags ( int* minGridSize, int* blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned int flags ) + + +Suggest a launch configuration with reasonable occupancy. + +###### Parameters + +`minGridSize` + \- Returned minimum grid size needed to achieve the maximum occupancy +`blockSize` + \- Returned maximum block size that can achieve the maximum occupancy +`func` + \- Kernel for which launch configuration is calculated +`blockSizeToDynamicSMemSize` + \- A function that calculates how much per-block dynamic shared memory `func` uses based on the block size +`dynamicSMemSize` + \- Dynamic shared memory usage intended, in bytes +`blockSizeLimit` + \- The maximum block size `func` is designed to handle +`flags` + \- Options + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +An extended version of cuOccupancyMaxPotentialBlockSize. In addition to arguments passed to cuOccupancyMaxPotentialBlockSize, cuOccupancyMaxPotentialBlockSizeWithFlags also takes a `Flags` parameter. + +The `Flags` parameter controls how special cases are handled. The valid flags are: + + * CU_OCCUPANCY_DEFAULT, which maintains the default behavior as cuOccupancyMaxPotentialBlockSize; + + + * CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE, which suppresses the default behavior on platform where global caching affects occupancy. On such platforms, the launch configurations that produces maximal occupancy might not support global caching. Setting CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE guarantees that the the produced launch configuration is global caching compatible at a potential cost of occupancy. More information can be found about this feature in the "Unified L1/Texture Cache" section of the Maxwell tuning guide. + + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will be the current context. + +CUresult cuOccupancyMaxPotentialClusterSize ( int* clusterSize, CUfunction func, const CUlaunchConfig* config ) + + +Given the kernel function (`func`) and launch configuration (`config`), return the maximum cluster size in `*clusterSize`. + +###### Parameters + +`clusterSize` + \- Returned maximum cluster size that can be launched for the given kernel function and launch configuration +`func` + \- Kernel function for which maximum cluster size is calculated +`config` + \- Launch configuration for the given kernel function + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_UNKNOWN + +###### Description + +The cluster dimensions in `config` are ignored. If func has a required cluster size set (see cudaFuncGetAttributes / cuFuncGetAttribute),`*clusterSize` will reflect the required cluster size. + +By default this function will always return a value that's portable on future hardware. A higher value may be returned if the kernel function allows non-portable cluster sizes. + +This function will respect the compile time launch bounds. + +Note that the API can also be used with context-less kernel CUkernel by querying the handle using cuLibraryGetKernel() and then passing it to the API by casting to CUfunction. Here, the context to use for calculations will either be taken from the specified stream `config->hStream` or the current context in case of NULL stream. + + diff --git a/content/cuda/docs/driver-peer--access/DOC.md b/content/cuda/docs/driver-peer--access/DOC.md new file mode 100644 index 00000000..5e3b2b44 --- /dev/null +++ b/content/cuda/docs/driver-peer--access/DOC.md @@ -0,0 +1,167 @@ +--- +name: driver-peer--access +description: '**Source:** group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.31. Peer Context Memory Access + +**Source:** group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS + + +### Functions + +CUresult cuCtxDisablePeerAccess ( CUcontext peerContext ) + + +Disables direct access to memory allocations in a peer context and unregisters any registered allocations. + +###### Parameters + +`peerContext` + \- Peer context to disable direct access to + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_PEER_ACCESS_NOT_ENABLED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Returns CUDA_ERROR_PEER_ACCESS_NOT_ENABLED if direct peer access has not yet been enabled from `peerContext` to the current context. + +Returns CUDA_ERROR_INVALID_CONTEXT if there is no current context, or if `peerContext` is not a valid context. + +CUresult cuCtxEnablePeerAccess ( CUcontext peerContext, unsigned int Flags ) + + +Enables direct access to memory allocations in a peer context. + +###### Parameters + +`peerContext` + \- Peer context to enable direct access to from the current context +`Flags` + \- Reserved for future use and must be set to 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED, CUDA_ERROR_TOO_MANY_PEERS, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, CUDA_ERROR_INVALID_VALUE + +###### Description + +If both the current context and `peerContext` are on devices which support unified addressing (as may be queried using CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING) and same major compute capability, then on success all allocations from `peerContext` will immediately be accessible by the current context. See Unified Addressing for additional details. + +Note that access granted by this call is unidirectional and that in order to access memory from the current context in `peerContext`, a separate symmetric call to cuCtxEnablePeerAccess() is required. + +Note that there are both device-wide and system-wide limitations per system configuration, as noted in the CUDA Programming Guide under the section "Peer-to-Peer Memory Access". + +Returns CUDA_ERROR_PEER_ACCESS_UNSUPPORTED if cuDeviceCanAccessPeer() indicates that the CUdevice of the current context cannot directly access memory from the CUdevice of `peerContext`. + +Returns CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED if direct access of `peerContext` from the current context has already been enabled. + +Returns CUDA_ERROR_TOO_MANY_PEERS if direct peer access is not possible because hardware resources required for peer access have been exhausted. + +Returns CUDA_ERROR_INVALID_CONTEXT if there is no current context, `peerContext` is not a valid context, or if the current context is `peerContext`. + +Returns CUDA_ERROR_INVALID_VALUE if `Flags` is not 0. + +CUresult cuDeviceCanAccessPeer ( int* canAccessPeer, CUdevice dev, CUdevice peerDev ) + + +Queries if a device may directly access a peer device's memory. + +###### Parameters + +`canAccessPeer` + \- Returned access capability +`dev` + \- Device from which allocations on `peerDev` are to be directly accessed. +`peerDev` + \- Device on which the allocations to be directly accessed by `dev` reside. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Returns in `*canAccessPeer` a value of 1 if contexts on `dev` are capable of directly accessing memory from contexts on `peerDev` and 0 otherwise. If direct access of `peerDev` from `dev` is possible, then access may be enabled on two specific contexts by calling cuCtxEnablePeerAccess(). + +CUresult cuDeviceGetP2PAtomicCapabilities ( unsigned int* capabilities, const CUatomicOperation ** operations, unsigned int count, CUdevice srcDevice, CUdevice dstDevice ) + + +Queries details about atomic operations supported between two devices. + +###### Parameters + +`capabilities` + \- Returned capability details of each requested operation +`operations` + \- Requested operations +`count` + \- Count of requested operations and size of capabilities +`srcDevice` + \- The source device of the target link +`dstDevice` + \- The destination device of the target link + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*capabilities` the details about requested atomic `*operations` over the the link between `srcDevice` and `dstDevice`. The allocated size of `*operations` and `*capabilities` must be `count`. + +For each CUatomicOperation in `*operations`, the corresponding result in `*capabilities` will be a bitmask indicating which of CUatomicOperationCapability the link supports natively. + +Returns CUDA_ERROR_INVALID_DEVICE if `srcDevice` or `dstDevice` are not valid or if they represent the same device. + +Returns CUDA_ERROR_INVALID_VALUE if `*capabilities` or `*operations` is NULL, if `count` is 0, or if any of `*operations` is not valid. + +CUresult cuDeviceGetP2PAttribute ( int* value, CUdevice_P2PAttribute attrib, CUdevice srcDevice, CUdevice dstDevice ) + + +Queries attributes of the link between two devices. + +###### Parameters + +`value` + \- Returned value of the requested attribute +`attrib` + \- The requested attribute of the link between `srcDevice` and `dstDevice`. +`srcDevice` + \- The source device of the target link. +`dstDevice` + \- The destination device of the target link. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*value` the value of the requested attribute `attrib` of the link between `srcDevice` and `dstDevice`. The supported attributes are: + + * CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK: A relative value indicating the performance of the link between two devices. + + * CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED P2P: 1 if P2P Access is enable. + + * CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED: 1 if all CUDA-valid atomic operations over the link are supported. + + * CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED: 1 if cudaArray can be accessed over the link. + + * CU_DEVICE_P2P_ATTRIBUTE_ONLY_PARTIAL_NATIVE_ATOMIC_SUPPORTED: 1 if some CUDA-valid atomic operations over the link are supported. Information about specific operations can be retrieved with cuDeviceGetP2PAtomicCapabilities. + + +Returns CUDA_ERROR_INVALID_DEVICE if `srcDevice` or `dstDevice` are not valid or if they represent the same device. + +Returns CUDA_ERROR_INVALID_VALUE if `attrib` is not valid or if `value` is a null pointer. + + diff --git a/content/cuda/docs/driver-primary--ctx/DOC.md b/content/cuda/docs/driver-primary--ctx/DOC.md new file mode 100644 index 00000000..b4390b86 --- /dev/null +++ b/content/cuda/docs/driver-primary--ctx/DOC.md @@ -0,0 +1,160 @@ +--- +name: driver-primary--ctx +description: '**Source:** group__CUDA__PRIMARY__CTX.html#group__CUDA__PRIMARY__CTX' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.7. Primary Context Management + +**Source:** group__CUDA__PRIMARY__CTX.html#group__CUDA__PRIMARY__CTX + + +### Functions + +CUresult cuDevicePrimaryCtxGetState ( CUdevice dev, unsigned int* flags, int* active ) + + +Get the state of the primary context. + +###### Parameters + +`dev` + \- Device to get primary context flags for +`flags` + \- Pointer to store flags +`active` + \- Pointer to store context state; 0 = inactive, 1 = active + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*flags` the flags for the primary context of `dev`, and in `*active` whether it is active. See cuDevicePrimaryCtxSetFlags for flag values. + +CUresult cuDevicePrimaryCtxRelease ( CUdevice dev ) + + +Release the primary context on the GPU. + +###### Parameters + +`dev` + \- Device which primary context is released + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Releases the primary context interop on the device. A retained context should always be released once the user is done using it. The context is automatically reset once the last reference to it is released. This behavior is different when the primary context was retained by the CUDA runtime from CUDA 4.0 and earlier. In this case, the primary context remains always active. + +Releasing a primary context that has not been previously retained will fail with CUDA_ERROR_INVALID_CONTEXT. + +Please note that unlike cuCtxDestroy() this method does not pop the context from stack in any circumstances. + +CUresult cuDevicePrimaryCtxReset ( CUdevice dev ) + + +Destroy all allocations and reset all state on the primary context. + +###### Parameters + +`dev` + \- Device for which primary context is destroyed + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE + +###### Description + +Explicitly destroys and cleans up all resources associated with the current device in the current process. + +Note that it is responsibility of the calling function to ensure that no other module in the process is using the device any more. For that reason it is recommended to use cuDevicePrimaryCtxRelease() in most cases. However it is safe for other modules to call cuDevicePrimaryCtxRelease() even after resetting the device. Resetting the primary context does not release it, an application that has retained the primary context should explicitly release its usage. + +CUresult cuDevicePrimaryCtxRetain ( CUcontext* pctx, CUdevice dev ) + + +Retain the primary context on the GPU. + +###### Parameters + +`pctx` + \- Returned context handle of the new context +`dev` + \- Device for which primary context is requested + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_UNKNOWN + +###### Description + +Retains the primary context on the device. Once the user successfully retains the primary context, the primary context will be active and available to the user until the user releases it with cuDevicePrimaryCtxRelease() or resets it with cuDevicePrimaryCtxReset(). Unlike cuCtxCreate() the newly retained context is not pushed onto the stack. + +Retaining the primary context for the first time will fail with CUDA_ERROR_UNKNOWN if the compute mode of the device is CU_COMPUTEMODE_PROHIBITED. The function cuDeviceGetAttribute() can be used with CU_DEVICE_ATTRIBUTE_COMPUTE_MODE to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. + +Please note that the primary context always supports pinned allocations. Other flags can be specified by cuDevicePrimaryCtxSetFlags(). + +CUresult cuDevicePrimaryCtxSetFlags ( CUdevice dev, unsigned int flags ) + + +Set flags for the primary context. + +###### Parameters + +`dev` + \- Device for which the primary context flags are set +`flags` + \- New flags for the device + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the flags for the primary context on the device overwriting perviously set ones. + +The three LSBs of the `flags` parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context. + + * CU_CTX_SCHED_SPIN: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread. + + + * CU_CTX_SCHED_YIELD: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU. + + + * CU_CTX_SCHED_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. + + + * CU_CTX_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. + +**Deprecated:** This flag was deprecated as of CUDA 4.0 and was replaced with CU_CTX_SCHED_BLOCKING_SYNC. + + + * CU_CTX_SCHED_AUTO: The default value if the `flags` parameter is zero, uses a heuristic based on the number of active CUDA contexts in the process C and the number of logical processors in the system P. If C > P, then CUDA will yield to other OS threads when waiting for the GPU (CU_CTX_SCHED_YIELD), otherwise CUDA will not yield while waiting for results and actively spin on the processor (CU_CTX_SCHED_SPIN). Additionally, on Tegra devices, CU_CTX_SCHED_AUTO uses a heuristic based on the power profile of the platform and may choose CU_CTX_SCHED_BLOCKING_SYNC for low-powered devices. + + + * CU_CTX_LMEM_RESIZE_TO_MAX: Instruct CUDA to not reduce local memory after resizing local memory for a kernel. This can prevent thrashing by local memory allocations when launching many kernels with high local memory usage at the cost of potentially increased memory usage. + +**Deprecated:** This flag is deprecated and the behavior enabled by this flag is now the default and cannot be disabled. + + + * CU_CTX_COREDUMP_ENABLE: If GPU coredumps have not been enabled globally with cuCoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the "GPU core dump support" section. The initial settings will be taken from the global settings at the time of context creation. The other settings that control coredump output can be modified by calling cuCoredumpSetAttribute from the created context after it becomes current. + + + * CU_CTX_USER_COREDUMP_ENABLE: If user-triggered GPU coredumps have not been enabled globally with cuCoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the "GPU core dump support" section. It is important to note that the pipe name *must* be set with cuCoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CU_CTX_COREDUMP_ENABLE is set. The initial settings will be taken from the global settings at the time of context creation. The other settings that control coredump output can be modified by calling cuCoredumpSetAttribute from the created context after it becomes current. + + + * CU_CTX_SYNC_MEMOPS: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled "API Synchronization behavior" to learn more about cases when synchronous memory operations can exhibit asynchronous behavior. + + diff --git a/content/cuda/docs/driver-profiler--deprecated/DOC.md b/content/cuda/docs/driver-profiler--deprecated/DOC.md new file mode 100644 index 00000000..23260fb5 --- /dev/null +++ b/content/cuda/docs/driver-profiler--deprecated/DOC.md @@ -0,0 +1,52 @@ +--- +name: driver-profiler--deprecated +description: '**Source:** group__CUDA__PROFILER__DEPRECATED.html#group__CUDA__PROFILER__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.38. Profiler Control [DEPRECATED] + +**Source:** group__CUDA__PROFILER__DEPRECATED.html#group__CUDA__PROFILER__DEPRECATED + + +### Functions + +CUresult cuProfilerInitialize ( const char* configFile, const char* outputFile, CUoutput_mode outputMode ) + + +Initialize the profiling. + +###### Parameters + +`configFile` + \- Name of the config file that lists the counters/options for profiling. +`outputFile` + \- Name of the outputFile where the profiling results will be stored. +`outputMode` + \- outputMode, can be CU_OUT_KEY_VALUE_PAIR or CU_OUT_CSV. + +###### Returns + +CUDA_ERROR_NOT_SUPPORTED + +###### Deprecated + +Note that this function is deprecated and should not be used. Starting with CUDA 12.0, it always returns error code CUDA_ERROR_NOT_SUPPORTED. + +###### Description + +Using this API user can initialize the CUDA profiler by specifying the configuration file, output file and output file format. This API is generally used to profile different set of counters by looping the kernel launch. The `configFile` parameter can be used to select profiling options including profiler counters. Refer to the "Compute Command Line Profiler User Guide" for supported profiler options and counters. + +Limitation: The CUDA profiler cannot be initialized with this API if another profiling tool is already active, as indicated by the CUDA_ERROR_PROFILER_DISABLED return code. + +Typical usage of the profiling APIs is as follows: + +for each set of counters/options { cuProfilerInitialize(); //Initialize profiling, set the counters or options in the config file ... cuProfilerStart(); // code to be profiled cuProfilerStop(); ... cuProfilerStart(); // code to be profiled cuProfilerStop(); ... } + + diff --git a/content/cuda/docs/driver-profiler/DOC.md b/content/cuda/docs/driver-profiler/DOC.md new file mode 100644 index 00000000..98c3ae4e --- /dev/null +++ b/content/cuda/docs/driver-profiler/DOC.md @@ -0,0 +1,50 @@ +--- +name: driver-profiler +description: '**Source:** group__CUDA__PROFILER.html#group__CUDA__PROFILER' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.39. Profiler Control + +**Source:** group__CUDA__PROFILER.html#group__CUDA__PROFILER + + +### Functions + +CUresult cuProfilerStart ( void ) + + +Enable profiling. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Enables profile collection by the active profiling tool for the current context. If profiling is already enabled, then cuProfilerStart() has no effect. + +cuProfilerStart and cuProfilerStop APIs are used to programmatically control the profiling granularity by allowing profiling to be done only on selective pieces of code. + +CUresult cuProfilerStop ( void ) + + +Disable profiling. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Disables profile collection by the active profiling tool for the current context. If profiling is already disabled, then cuProfilerStop() has no effect. + +cuProfilerStart and cuProfilerStop APIs are used to programmatically control the profiling granularity by allowing profiling to be done only on selective pieces of code. + + diff --git a/content/cuda/docs/driver-stream/DOC.md b/content/cuda/docs/driver-stream/DOC.md new file mode 100644 index 00000000..71599396 --- /dev/null +++ b/content/cuda/docs/driver-stream/DOC.md @@ -0,0 +1,700 @@ +--- +name: driver-stream +description: '**Source:** group__CUDA__STREAM.html#group__CUDA__STREAM' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.18. Stream Management + +**Source:** group__CUDA__STREAM.html#group__CUDA__STREAM + + +### Functions + +CUresult cuStreamAddCallback ( CUstream hStream, CUstreamCallback callback, void* userData, unsigned int flags ) + + +Add a callback to a compute stream. + +###### Parameters + +`hStream` + \- Stream to add callback to +`callback` + \- The function to call once preceding stream operations are complete +`userData` + \- User specified data to be passed to the callback function +`flags` + \- Reserved for future use, must be 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +This function is slated for eventual deprecation and removal. If you do not require the callback to execute in case of a device error, consider using cuLaunchHostFunc. Additionally, this function is not supported with cuStreamBeginCapture and cuStreamEndCapture, unlike cuLaunchHostFunc. + +Adds a callback to be called on the host after all currently enqueued items in the stream have completed. For each cuStreamAddCallback call, the callback will be executed exactly once. The callback will block later work in the stream until it is finished. + +The callback may be passed CUDA_SUCCESS or an error code. In the event of a device error, all subsequently executed callbacks will receive an appropriate CUresult. + +Callbacks must not make any CUDA API calls. Attempting to use a CUDA API will result in CUDA_ERROR_NOT_PERMITTED. Callbacks must not perform any synchronization that may depend on outstanding device work or other callbacks that are not mandated to run earlier. Callbacks without a mandated order (in independent streams) execute in undefined order and may be serialized. + +For the purposes of Unified Memory, callback execution makes a number of guarantees: + + * The callback stream is considered idle for the duration of the callback. Thus, for example, a callback may always use memory attached to the callback stream. + + * The start of execution of a callback has the same effect as synchronizing an event recorded in the same stream immediately prior to the callback. It thus synchronizes streams which have been "joined" prior to the callback. + + * Adding device work to any stream does not have the effect of making the stream active until all preceding host functions and stream callbacks have executed. Thus, for example, a callback might use global attached memory even if work has been added to another stream, if the work has been ordered behind the callback with an event. + + * Completion of a callback does not cause a stream to become active except as described above. The callback stream will remain idle if no device work follows the callback, and will remain idle across consecutive callbacks without device work in between. Thus, for example, stream synchronization can be done by signaling from a callback at the end of the stream. + + + * This function uses standard default stream semantics. + + * +CUresult cuStreamAttachMemAsync ( CUstream hStream, CUdeviceptr dptr, size_t length, unsigned int flags ) + + +Attach memory to a stream asynchronously. + +###### Parameters + +`hStream` + \- Stream in which to enqueue the attach operation +`dptr` + \- Pointer to memory (must be a pointer to managed memory or to a valid host-accessible region of system-allocated pageable memory) +`length` + \- Length of memory +`flags` + \- Must be one of CUmemAttach_flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Enqueues an operation in `hStream` to specify stream association of `length` bytes of memory starting from `dptr`. This function is a stream-ordered operation, meaning that it is dependent on, and will only take effect when, previous work in stream has completed. Any previous association is automatically replaced. + +`dptr` must point to one of the following types of memories: + + * managed memory declared using the __managed__ keyword or allocated with cuMemAllocManaged. + + * a valid host-accessible region of system-allocated pageable memory. This type of memory may only be specified if the device associated with the stream reports a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. + + +For managed allocations, `length` must be either zero or the entire allocation's size. Both indicate that the entire allocation's stream association is being changed. Currently, it is not possible to change stream association for a portion of a managed allocation. + +For pageable host allocations, `length` must be non-zero. + +The stream association is specified using `flags` which must be one of CUmemAttach_flags. If the CU_MEM_ATTACH_GLOBAL flag is specified, the memory can be accessed by any stream on any device. If the CU_MEM_ATTACH_HOST flag is specified, the program makes a guarantee that it won't access the memory on the device from any stream on a device that has a zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. If the CU_MEM_ATTACH_SINGLE flag is specified and `hStream` is associated with a device that has a zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, the program makes a guarantee that it will only access the memory on the device from `hStream`. It is illegal to attach singly to the NULL stream, because the NULL stream is a virtual global stream and not a specific stream. An error will be returned in this case. + +When memory is associated with a single stream, the Unified Memory system will allow CPU access to this memory region so long as all operations in `hStream` have completed, regardless of whether other streams are active. In effect, this constrains exclusive ownership of the managed memory region by an active GPU to per-stream activity instead of whole-GPU activity. + +Accessing memory on the device from streams that are not associated with it will produce undefined results. No error checking is performed by the Unified Memory system to ensure that kernels launched into other streams do not access this region. + +It is a program's responsibility to order calls to cuStreamAttachMemAsync via events, synchronization or other means to ensure legal access to memory at all times. Data visibility and coherency will be changed appropriately for all kernels which follow a stream-association change. + +If `hStream` is destroyed while data is associated with it, the association is removed and the association reverts to the default visibility of the allocation as specified at cuMemAllocManaged. For __managed__ variables, the default association is always CU_MEM_ATTACH_GLOBAL. Note that destroying a stream is an asynchronous operation, and as a result, the change to default association won't happen until all work in the stream has completed. + + * This function uses standard default stream semantics. + + * +CUresult cuStreamBeginCapture ( CUstream hStream, CUstreamCaptureMode mode ) + + +Begins graph capture on a stream. + +###### Parameters + +`hStream` + \- Stream in which to initiate capture +`mode` + \- Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details see cuThreadExchangeStreamCaptureMode. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Begin graph capture on `hStream`. When a stream is in capture mode, all operations pushed into the stream will not be executed, but will instead be captured into a graph, which will be returned via cuStreamEndCapture. Capture may not be initiated if `stream` is CU_STREAM_LEGACY. Capture must be ended on the same stream in which it was initiated, and it may only be initiated if the stream is not already in capture mode. The capture mode may be queried via cuStreamIsCapturing. A unique id representing the capture sequence may be queried via cuStreamGetCaptureInfo. + +If `mode` is not CU_STREAM_CAPTURE_MODE_RELAXED, cuStreamEndCapture must be called on this stream from the same thread. + +Kernels captured using this API must not use texture and surface references. Reading or writing through any texture or surface reference is undefined behavior. This restriction does not apply to texture and surface objects. + +CUresult cuStreamBeginCaptureToGraph ( CUstream hStream, CUgraph hGraph, const CUgraphNode* dependencies, const CUgraphEdgeData* dependencyData, size_t numDependencies, CUstreamCaptureMode mode ) + + +Begins graph capture on a stream to an existing graph. + +###### Parameters + +`hStream` + \- Stream in which to initiate capture. +`hGraph` + \- Graph to capture into. +`dependencies` + \- Dependencies of the first node captured in the stream. Can be NULL if numDependencies is 0. +`dependencyData` + \- Optional array of data associated with each dependency. +`numDependencies` + \- Number of dependencies. +`mode` + \- Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details see cuThreadExchangeStreamCaptureMode. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Begin graph capture on `hStream`, placing new nodes into an existing graph. When a stream is in capture mode, all operations pushed into the stream will not be executed, but will instead be captured into `hGraph`. The graph will not be instantiable until the user calls cuStreamEndCapture. + +Capture may not be initiated if `stream` is CU_STREAM_LEGACY. Capture must be ended on the same stream in which it was initiated, and it may only be initiated if the stream is not already in capture mode. The capture mode may be queried via cuStreamIsCapturing. A unique id representing the capture sequence may be queried via cuStreamGetCaptureInfo. + +If `mode` is not CU_STREAM_CAPTURE_MODE_RELAXED, cuStreamEndCapture must be called on this stream from the same thread. + +Kernels captured using this API must not use texture and surface references. Reading or writing through any texture or surface reference is undefined behavior. This restriction does not apply to texture and surface objects. + +CUresult cuStreamCopyAttributes ( CUstream dst, CUstream src ) + + +Copies attributes from source stream to destination stream. + +###### Parameters + +`dst` + Destination stream +`src` + Source stream For list of attributes see CUstreamAttrID + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Copies attributes from source stream `src` to destination stream `dst`. Both streams must have the same context. + +CUresult cuStreamCreate ( CUstream* phStream, unsigned int Flags ) + + +Create a stream. + +###### Parameters + +`phStream` + \- Returned newly created stream +`Flags` + \- Parameters for stream creation + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates a stream and returns a handle in `phStream`. The `Flags` argument determines behaviors of the stream. + +Valid values for `Flags` are: + + * CU_STREAM_DEFAULT: Default stream creation flag. + + * CU_STREAM_NON_BLOCKING: Specifies that work running in the created stream may run concurrently with work in stream 0 (the NULL stream), and that the created stream should perform no implicit synchronization with stream 0. + + +CUresult cuStreamCreateWithPriority ( CUstream* phStream, unsigned int flags, int priority ) + + +Create a stream with the given priority. + +###### Parameters + +`phStream` + \- Returned newly created stream +`flags` + \- Flags for stream creation. See cuStreamCreate for a list of valid flags +`priority` + \- Stream priority. Lower numbers represent higher priorities. See cuCtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates a stream with the specified priority and returns a handle in `phStream`. This affects the scheduling priority of work in the stream. Priorities provide a hint to preferentially run work with higher priority when possible, but do not preempt already-running work or provide any other functional guarantee on execution order. + +`priority` follows a convention where lower numbers represent higher priorities. '0' represents default priority. The range of meaningful numerical priorities can be queried using cuCtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by cuCtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range. + + * * Stream priorities are supported only on GPUs with compute capability 3.5 or higher. + + * In the current implementation, only compute kernels launched in priority streams are affected by the stream's priority. Stream priorities have no effect on host-to-device and device-to-host memory operations. + + +CUresult cuStreamDestroy ( CUstream hStream ) + + +Destroys a stream. + +###### Parameters + +`hStream` + \- Stream to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Destroys the stream specified by `hStream`. + +In case the device is still doing work in the stream `hStream` when cuStreamDestroy() is called, the function will return immediately and the resources associated with `hStream` will be released automatically once the device has completed all work in `hStream`. + +CUresult cuStreamEndCapture ( CUstream hStream, CUgraph* phGraph ) + + +Ends capture on a stream, returning the captured graph. + +###### Parameters + +`hStream` + \- Stream to query +`phGraph` + \- The captured graph + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD + +###### Description + +End capture on `hStream`, returning the captured graph via `phGraph`. Capture must have been initiated on `hStream` via a call to cuStreamBeginCapture. If capture was invalidated, due to a violation of the rules of stream capture, then a NULL graph will be returned. + +If the `mode` argument to cuStreamBeginCapture was not CU_STREAM_CAPTURE_MODE_RELAXED, this call must be from the same thread as cuStreamBeginCapture. + +CUresult cuStreamGetAttribute ( CUstream hStream, CUstreamAttrID attr, CUstreamAttrValue* value_out ) + + +Queries stream attribute. + +###### Parameters + +`hStream` + +`attr` + +`value_out` + + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Queries attribute `attr` from `hStream` and stores it in corresponding member of `value_out`. + +CUresult cuStreamGetCaptureInfo ( CUstream hStream, CUstreamCaptureStatus* captureStatus_out, cuuint64_t* id_out, CUgraph* graph_out, const CUgraphNode** dependencies_out, const CUgraphEdgeData** edgeData_out, size_t* numDependencies_out ) + + +Query a stream's capture state. + +###### Parameters + +`hStream` + \- The stream to query +`captureStatus_out` + \- Location to return the capture status of the stream; required +`id_out` + \- Optional location to return an id for the capture sequence, which is unique over the lifetime of the process +`graph_out` + \- Optional location to return the graph being captured into. All operations other than destroy and node removal are permitted on the graph while the capture sequence is in progress. This API does not transfer ownership of the graph, which is transferred or destroyed at cuStreamEndCapture. Note that the graph handle may be invalidated before end of capture for certain errors. Nodes that are or become unreachable from the original stream at cuStreamEndCapture due to direct actions on the graph do not trigger CUDA_ERROR_STREAM_CAPTURE_UNJOINED. +`dependencies_out` + \- Optional location to store a pointer to an array of nodes. The next node to be captured in the stream will depend on this set of nodes, absent operations such as event wait which modify this set. The array pointer is valid until the next API call which operates on the stream or until the capture is terminated. The node handles may be copied out and are valid until they or the graph is destroyed. The driver-owned array may also be passed directly to APIs that operate on the graph (not the stream) without copying. +`edgeData_out` + \- Optional location to store a pointer to an array of graph edge data. This array parallels `dependencies_out`; the next node to be added has an edge to `dependencies_out`[i] with annotation `edgeData_out`[i] for each `i`. The array pointer is valid until the next API call which operates on the stream or until the capture is terminated. +`numDependencies_out` + \- Optional location to store the size of the array returned in dependencies_out. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_STREAM_CAPTURE_IMPLICIT, CUDA_ERROR_LOSSY_QUERY + +###### Description + +Query stream state related to stream capture. + +If called on CU_STREAM_LEGACY (the "null stream") while a stream not created with CU_STREAM_NON_BLOCKING is capturing, returns CUDA_ERROR_STREAM_CAPTURE_IMPLICIT. + +Valid data (other than capture status) is returned only if both of the following are true: + + * the call returns CUDA_SUCCESS + + * the returned capture status is CU_STREAM_CAPTURE_STATUS_ACTIVE + + +If `edgeData_out` is non-NULL then `dependencies_out` must be as well. If `dependencies_out` is non-NULL and `edgeData_out` is NULL, but there is non-zero edge data for one or more of the current stream dependencies, the call will return CUDA_ERROR_LOSSY_QUERY. + + * Graph objects are not threadsafe. More here. + + * +CUresult cuStreamGetCtx ( CUstream hStream, CUcontext* pctx ) + + +Query the context associated with a stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`pctx` + \- Returned context associated with the stream + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Returns the CUDA context that the stream is associated with. + +If the stream was created via the API cuGreenCtxStreamCreate, the returned context is equivalent to the one returned by cuCtxFromGreenCtx() on the green context associated with the stream at creation time. + +The stream handle `hStream` can refer to any of the following: + + * a stream created via any of the CUDA driver APIs such as cuStreamCreate and cuStreamCreateWithPriority, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. The returned context is the context that was active in the calling thread when the stream was created. Passing an invalid handle will result in undefined behavior. + + * any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. Specifying any of the special handles will return the context current to the calling thread. If no context is current to the calling thread, CUDA_ERROR_INVALID_CONTEXT is returned. + + +CUresult cuStreamGetCtx_v2 ( CUstream hStream, CUcontext* pCtx, CUgreenCtx* pGreenCtx ) + + +Query the contexts associated with a stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`pCtx` + \- Returned regular context associated with the stream +`pGreenCtx` + \- Returned green context if the stream is associated with a green context or NULL if not + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns the contexts that the stream is associated with. + +If the stream is associated with a green context, the API returns the green context in `pGreenCtx` and the primary context of the associated device in `pCtx`. + +If the stream is associated with a regular context, the API returns the regular context in `pCtx` and NULL in `pGreenCtx`. + +The stream handle `hStream` can refer to any of the following: + + * a stream created via any of the CUDA driver APIs such as cuStreamCreate, cuStreamCreateWithPriority and cuGreenCtxStreamCreate, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. Passing an invalid handle will result in undefined behavior. + + * any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. If any of the special handles are specified, the API will operate on the context current to the calling thread. If a green context (that was converted via cuCtxFromGreenCtx() before setting it current) is current to the calling thread, the API will return the green context in `pGreenCtx` and the primary context of the associated device in `pCtx`. If a regular context is current, the API returns the regular context in `pCtx` and NULL in `pGreenCtx`. Note that specifying CU_STREAM_PER_THREAD or cudaStreamPerThread will return CUDA_ERROR_INVALID_HANDLE if a green context is current to the calling thread. If no context is current to the calling thread, CUDA_ERROR_INVALID_CONTEXT is returned. + + +CUresult cuStreamGetDevice ( CUstream hStream, CUdevice* device ) + + +Returns the device handle of the stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`device` + \- Returns the device to which a stream belongs + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Returns in `*device` the device handle of the stream + +CUresult cuStreamGetFlags ( CUstream hStream, unsigned int* flags ) + + +Query the flags of a given stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`flags` + \- Pointer to an unsigned integer in which the stream's flags are returned The value returned in `flags` is a logical 'OR' of all flags that were used while creating this stream. See cuStreamCreate for the list of valid flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Query the flags of a stream created using cuStreamCreate, cuStreamCreateWithPriority or cuGreenCtxStreamCreate and return the flags in `flags`. + +CUresult cuStreamGetId ( CUstream hStream, unsigned long long* streamId ) + + +Returns the unique Id associated with the stream handle supplied. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`streamId` + \- Pointer to store the Id of the stream + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Returns in `streamId` the unique Id which is associated with the given stream handle. The Id is unique for the life of the program. + +The stream handle `hStream` can refer to any of the following: + + * a stream created via any of the CUDA driver APIs such as cuStreamCreate and cuStreamCreateWithPriority, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. Passing an invalid handle will result in undefined behavior. + + * any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. + + +CUresult cuStreamGetPriority ( CUstream hStream, int* priority ) + + +Query the priority of a given stream. + +###### Parameters + +`hStream` + \- Handle to the stream to be queried +`priority` + \- Pointer to a signed integer in which the stream's priority is returned + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Query the priority of a stream created using cuStreamCreate, cuStreamCreateWithPriority or cuGreenCtxStreamCreate and return the priority in `priority`. Note that if the stream was created with a priority outside the numerical range returned by cuCtxGetStreamPriorityRange, this function returns the clamped priority. See cuStreamCreateWithPriority for details about priority clamping. + +CUresult cuStreamIsCapturing ( CUstream hStream, CUstreamCaptureStatus* captureStatus ) + + +Returns a stream's capture status. + +###### Parameters + +`hStream` + \- Stream to query +`captureStatus` + \- Returns the stream's capture status + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_STREAM_CAPTURE_IMPLICIT + +###### Description + +Return the capture status of `hStream` via `captureStatus`. After a successful call, `*captureStatus` will contain one of the following: + + * CU_STREAM_CAPTURE_STATUS_NONE: The stream is not capturing. + + * CU_STREAM_CAPTURE_STATUS_ACTIVE: The stream is capturing. + + * CU_STREAM_CAPTURE_STATUS_INVALIDATED: The stream was capturing but an error has invalidated the capture sequence. The capture sequence must be terminated with cuStreamEndCapture on the stream where it was initiated in order to continue using `hStream`. + + +Note that, if this is called on CU_STREAM_LEGACY (the "null stream") while a blocking stream in the same context is capturing, it will return CUDA_ERROR_STREAM_CAPTURE_IMPLICIT and `*captureStatus` is unspecified after the call. The blocking stream capture is not invalidated. + +When a blocking stream is capturing, the legacy stream is in an unusable state until the blocking stream capture is terminated. The legacy stream is not supported for stream capture, but attempted use would have an implicit dependency on the capturing stream(s). + +CUresult cuStreamQuery ( CUstream hStream ) + + +Determine status of a compute stream. + +###### Parameters + +`hStream` + \- Stream to query status of + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_READY + +###### Description + +Returns CUDA_SUCCESS if all operations in the stream specified by `hStream` have completed, or CUDA_ERROR_NOT_READY if not. + +For the purposes of Unified Memory, a return value of CUDA_SUCCESS is equivalent to having called cuStreamSynchronize(). + + * This function uses standard default stream semantics. + + * +CUresult cuStreamSetAttribute ( CUstream hStream, CUstreamAttrID attr, const CUstreamAttrValue* value ) + + +Sets stream attribute. + +###### Parameters + +`hStream` + +`attr` + +`value` + + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Sets attribute `attr` on `hStream` from corresponding attribute of `value`. The updated attribute will be applied to subsequent work submitted to the stream. It will not affect previously submitted work. + +CUresult cuStreamSynchronize ( CUstream hStream ) + + +Wait until a stream's tasks are completed. + +###### Parameters + +`hStream` + \- Stream to wait for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Waits until the device has completed all operations in the stream specified by `hStream`. If the context was created with the CU_CTX_SCHED_BLOCKING_SYNC flag, the CPU thread will block until the stream is finished with all of its tasks. + + * This function uses standard default stream semantics. + + * +CUresult cuStreamUpdateCaptureDependencies ( CUstream hStream, CUgraphNode* dependencies, const CUgraphEdgeData* dependencyData, size_t numDependencies, unsigned int flags ) + + +Update the set of dependencies in a capturing stream. + +###### Parameters + +`hStream` + \- The stream to update +`dependencies` + \- The set of dependencies to add +`dependencyData` + \- Optional array of data associated with each dependency. +`numDependencies` + \- The size of the dependencies array +`flags` + \- See above + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Modifies the dependency set of a capturing stream. The dependency set is the set of nodes that the next captured node in the stream will depend on along with the edge data for those dependencies. + +Valid flags are CU_STREAM_ADD_CAPTURE_DEPENDENCIES and CU_STREAM_SET_CAPTURE_DEPENDENCIES. These control whether the set passed to the API is added to the existing set or replaces it. A flags value of 0 defaults to CU_STREAM_ADD_CAPTURE_DEPENDENCIES. + +Nodes that are removed from the dependency set via this API do not result in CUDA_ERROR_STREAM_CAPTURE_UNJOINED if they are unreachable from the stream at cuStreamEndCapture. + +Returns CUDA_ERROR_ILLEGAL_STATE if the stream is not capturing. + +CUresult cuStreamWaitEvent ( CUstream hStream, CUevent hEvent, unsigned int Flags ) + + +Make a compute stream wait on an event. + +###### Parameters + +`hStream` + \- Stream to wait +`hEvent` + \- Event to wait on (may not be NULL) +`Flags` + \- See CUevent_capture_flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Makes all future work submitted to `hStream` wait for all work captured in `hEvent`. See cuEventRecord() for details on what is captured by an event. The synchronization will be performed efficiently on the device when applicable. `hEvent` may be from a different context or device than `hStream`. + +flags include: + + * CU_EVENT_WAIT_DEFAULT: Default event creation flag. + + * CU_EVENT_WAIT_EXTERNAL: Event is captured in the graph as an external event node when performing stream capture. This flag is invalid outside of stream capture. + + + * This function uses standard default stream semantics. + + * +CUresult cuThreadExchangeStreamCaptureMode ( CUstreamCaptureMode* mode ) + + +Swaps the stream capture interaction mode for a thread. + +###### Parameters + +`mode` + \- Pointer to mode value to swap with the current mode + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE + +###### Description + +Sets the calling thread's stream capture interaction mode to the value contained in `*mode`, and overwrites `*mode` with the previous mode for the thread. To facilitate deterministic behavior across function or module boundaries, callers are encouraged to use this API in a push-pop fashion: + + + ‎ CUstreamCaptureMode mode = desiredMode; + cuThreadExchangeStreamCaptureMode(&mode); + ... + cuThreadExchangeStreamCaptureMode(&mode); // restore previous mode + +During stream capture (see cuStreamBeginCapture), some actions, such as a call to cudaMalloc, may be unsafe. In the case of cudaMalloc, the operation is not enqueued asynchronously to a stream, and is not observed by stream capture. Therefore, if the sequence of operations captured via cuStreamBeginCapture depended on the allocation being replayed whenever the graph is launched, the captured graph would be invalid. + +Therefore, stream capture places restrictions on API calls that can be made within or concurrently to a cuStreamBeginCapture-cuStreamEndCapture sequence. This behavior can be controlled via this API and flags to cuStreamBeginCapture. + +A thread's mode is one of the following: + + * `CU_STREAM_CAPTURE_MODE_GLOBAL:` This is the default mode. If the local thread has an ongoing capture sequence that was not initiated with `CU_STREAM_CAPTURE_MODE_RELAXED` at `cuStreamBeginCapture`, or if any other thread has a concurrent capture sequence initiated with `CU_STREAM_CAPTURE_MODE_GLOBAL`, this thread is prohibited from potentially unsafe API calls. + + * `CU_STREAM_CAPTURE_MODE_THREAD_LOCAL:` If the local thread has an ongoing capture sequence not initiated with `CU_STREAM_CAPTURE_MODE_RELAXED`, it is prohibited from potentially unsafe API calls. Concurrent capture sequences in other threads are ignored. + + * `CU_STREAM_CAPTURE_MODE_RELAXED:` The local thread is not prohibited from potentially unsafe API calls. Note that the thread is still prohibited from API calls which necessarily conflict with stream capture, for example, attempting cuEventQuery on an event that was last recorded inside a capture sequence. + + diff --git a/content/cuda/docs/driver-struct-cu--dev--sm--resource--group--params/DOC.md b/content/cuda/docs/driver-struct-cu--dev--sm--resource--group--params/DOC.md new file mode 100644 index 00000000..b9e9dfc9 --- /dev/null +++ b/content/cuda/docs/driver-struct-cu--dev--sm--resource--group--params/DOC.md @@ -0,0 +1,57 @@ +--- +name: driver-struct-cu--dev--sm--resource--group--params +description: '**Source:** structCU__DEV__SM__RESOURCE__GROUP__PARAMS.html' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# Next > + +**Source:** structCU__DEV__SM__RESOURCE__GROUP__PARAMS.html + + +### Public Variables + +unsigned int coscheduledSmCount + +unsigned int flags + +unsigned int preferredCoscheduledSmCount + +unsigned int reserved[12] + +unsigned int smCount + + +### Variables + +unsigned int CU_DEV_SM_RESOURCE_GROUP_PARAMS::coscheduledSmCount + + +The amount of co-scheduled SMs grouped together for locality purposes. + +unsigned int CU_DEV_SM_RESOURCE_GROUP_PARAMS::flags + + +Combination of `CUdevSmResourceGroup_flags` values to indicate this this group is created. + +unsigned int CU_DEV_SM_RESOURCE_GROUP_PARAMS::preferredCoscheduledSmCount + + +When possible, combine co-scheduled groups together into larger groups of this size. + +unsigned int CU_DEV_SM_RESOURCE_GROUP_PARAMS::reserved[12] + + +Reserved for future use - ensure this is is zero initialized. + +unsigned int CU_DEV_SM_RESOURCE_GROUP_PARAMS::smCount + + +The amount of SMs available in this resource. + diff --git a/content/cuda/docs/driver-struct-cuaccesspolicywindow--v1/DOC.md b/content/cuda/docs/driver-struct-cuaccesspolicywindow--v1/DOC.md new file mode 100644 index 00000000..317a1173 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuaccesspolicywindow--v1/DOC.md @@ -0,0 +1,20 @@ +--- +name: driver-struct-cuaccesspolicywindow--v1 +description: '**Source:** structCUaccessPolicyWindow__v1.html#structCUaccessPolicyWindow__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.2. CUaccessPolicyWindow_v1 + +**Source:** structCUaccessPolicyWindow__v1.html#structCUaccessPolicyWindow__v1 + + +### Public Variables + +void * base_ptr diff --git a/content/cuda/docs/driver-struct-cuarraymapinfo--v1/DOC.md b/content/cuda/docs/driver-struct-cuarraymapinfo--v1/DOC.md new file mode 100644 index 00000000..f0eeb727 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuarraymapinfo--v1/DOC.md @@ -0,0 +1,32 @@ +--- +name: driver-struct-cuarraymapinfo--v1 +description: '**Source:** structCUarrayMapInfo__v1.html#structCUarrayMapInfo__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.3. CUarrayMapInfo_v1 + +**Source:** structCUarrayMapInfo__v1.html#structCUarrayMapInfo__v1 + + +### Public Variables + +unsigned int deviceBitMask + +unsigned int extentDepth + +unsigned int extentHeight + +unsigned int extentWidth + +unsigned int flags + +unsigned int layer + +unsigned int level diff --git a/content/cuda/docs/driver-struct-cuasyncnotificationinfo/DOC.md b/content/cuda/docs/driver-struct-cuasyncnotificationinfo/DOC.md new file mode 100644 index 00000000..cc9cbf2f --- /dev/null +++ b/content/cuda/docs/driver-struct-cuasyncnotificationinfo/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuasyncnotificationinfo +description: '**Source:** structCUasyncNotificationInfo.html#structCUasyncNotificationInfo' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.4. CUasyncNotificationInfo + +**Source:** structCUasyncNotificationInfo.html#structCUasyncNotificationInfo + + +### Public Variables + +unsigned long long bytesOverBudget + +CUasyncNotificationInfo::@4 info + +CUasyncNotificationInfo::@4::@5 overBudget diff --git a/content/cuda/docs/driver-struct-cucheckpointcheckpointargs/DOC.md b/content/cuda/docs/driver-struct-cucheckpointcheckpointargs/DOC.md new file mode 100644 index 00000000..d295b45c --- /dev/null +++ b/content/cuda/docs/driver-struct-cucheckpointcheckpointargs/DOC.md @@ -0,0 +1,29 @@ +--- +name: driver-struct-cucheckpointcheckpointargs +description: '**Source:** structCUcheckpointCheckpointArgs.html#structCUcheckpointCheckpointArgs' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.5. CUcheckpointCheckpointArgs + +**Source:** structCUcheckpointCheckpointArgs.html#structCUcheckpointCheckpointArgs + + +### Public Variables + +cuuint64_t reserved[8] + + +### Variables + +cuuint64_t CUcheckpointCheckpointArgs::reserved[8] + + +Reserved for future use, must be zeroed + diff --git a/content/cuda/docs/driver-struct-cucheckpointgpupair/DOC.md b/content/cuda/docs/driver-struct-cucheckpointgpupair/DOC.md new file mode 100644 index 00000000..a12e2582 --- /dev/null +++ b/content/cuda/docs/driver-struct-cucheckpointgpupair/DOC.md @@ -0,0 +1,36 @@ +--- +name: driver-struct-cucheckpointgpupair +description: '**Source:** structCUcheckpointGpuPair.html#structCUcheckpointGpuPair' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.6. CUcheckpointGpuPair + +**Source:** structCUcheckpointGpuPair.html#structCUcheckpointGpuPair + + +### Public Variables + +CUuuid newUuid + +CUuuid oldUuid + + +### Variables + +CUuuid CUcheckpointGpuPair::newUuid + + +UUID of the GPU to restore onto + +CUuuid CUcheckpointGpuPair::oldUuid + + +UUID of the GPU that was checkpointed + diff --git a/content/cuda/docs/driver-struct-cucheckpointlockargs/DOC.md b/content/cuda/docs/driver-struct-cucheckpointlockargs/DOC.md new file mode 100644 index 00000000..f42eb436 --- /dev/null +++ b/content/cuda/docs/driver-struct-cucheckpointlockargs/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cucheckpointlockargs +description: '**Source:** structCUcheckpointLockArgs.html#structCUcheckpointLockArgs' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.7. CUcheckpointLockArgs + +**Source:** structCUcheckpointLockArgs.html#structCUcheckpointLockArgs + + +### Public Variables + +unsigned int reserved0 + +cuuint64_t reserved1[7] + +unsigned int timeoutMs + + +### Variables + +unsigned int CUcheckpointLockArgs::reserved0 + + +Reserved for future use, must be zero + +cuuint64_t CUcheckpointLockArgs::reserved1[7] + + +Reserved for future use, must be zeroed + +unsigned int CUcheckpointLockArgs::timeoutMs + + +Timeout in milliseconds to attempt to lock the process, 0 indicates no timeout + diff --git a/content/cuda/docs/driver-struct-cucheckpointrestoreargs/DOC.md b/content/cuda/docs/driver-struct-cucheckpointrestoreargs/DOC.md new file mode 100644 index 00000000..aa720451 --- /dev/null +++ b/content/cuda/docs/driver-struct-cucheckpointrestoreargs/DOC.md @@ -0,0 +1,50 @@ +--- +name: driver-struct-cucheckpointrestoreargs +description: '**Source:** structCUcheckpointRestoreArgs.html#structCUcheckpointRestoreArgs' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.8. CUcheckpointRestoreArgs + +**Source:** structCUcheckpointRestoreArgs.html#structCUcheckpointRestoreArgs + + +### Public Variables + +CUcheckpointGpuPair * gpuPairs + +unsigned int gpuPairsCount + +char reserved[52-sizeof(CUcheckpointGpuPair *)] + +cuuint64_t reserved1 + + +### Variables + +CUcheckpointGpuPair * CUcheckpointRestoreArgs::gpuPairs + + +Pointer to array of gpu pairs that indicate how to remap GPUs during restore + +unsigned int CUcheckpointRestoreArgs::gpuPairsCount + + +Number of gpu pairs to remap + +char CUcheckpointRestoreArgs::reserved[52-sizeof(CUcheckpointGpuPair *)] + + +Reserved for future use, must be zeroed + +cuuint64_t CUcheckpointRestoreArgs::reserved1 + + +Reserved for future use, must be zeroed + diff --git a/content/cuda/docs/driver-struct-cucheckpointunlockargs/DOC.md b/content/cuda/docs/driver-struct-cucheckpointunlockargs/DOC.md new file mode 100644 index 00000000..416e7702 --- /dev/null +++ b/content/cuda/docs/driver-struct-cucheckpointunlockargs/DOC.md @@ -0,0 +1,29 @@ +--- +name: driver-struct-cucheckpointunlockargs +description: '**Source:** structCUcheckpointUnlockArgs.html#structCUcheckpointUnlockArgs' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.9. CUcheckpointUnlockArgs + +**Source:** structCUcheckpointUnlockArgs.html#structCUcheckpointUnlockArgs + + +### Public Variables + +cuuint64_t reserved[8] + + +### Variables + +cuuint64_t CUcheckpointUnlockArgs::reserved[8] + + +Reserved for future use, must be zeroed + diff --git a/content/cuda/docs/driver-struct-cuctxcigparam/DOC.md b/content/cuda/docs/driver-struct-cuctxcigparam/DOC.md new file mode 100644 index 00000000..077a0c1c --- /dev/null +++ b/content/cuda/docs/driver-struct-cuctxcigparam/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuctxcigparam +description: '**Source:** structCUctxCigParam.html#structCUctxCigParam' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.10. CUctxCigParam + +**Source:** structCUctxCigParam.html#structCUctxCigParam + + diff --git a/content/cuda/docs/driver-struct-cuctxcreateparams/DOC.md b/content/cuda/docs/driver-struct-cuctxcreateparams/DOC.md new file mode 100644 index 00000000..8d97b473 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuctxcreateparams/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuctxcreateparams +description: '**Source:** structCUctxCreateParams.html#structCUctxCreateParams' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.11. CUctxCreateParams + +**Source:** structCUctxCreateParams.html#structCUctxCreateParams + + diff --git a/content/cuda/docs/driver-struct-cuda--array--descriptor--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--array--descriptor--v2/DOC.md new file mode 100644 index 00000000..ecc43ff4 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--array--descriptor--v2/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--array--descriptor--v2 +description: '**Source:** structCUDA__ARRAY__DESCRIPTOR__v2.html#structCUDA__ARRAY__DESCRIPTOR__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.13. CUDA_ARRAY_DESCRIPTOR_v2 + +**Source:** structCUDA__ARRAY__DESCRIPTOR__v2.html#structCUDA__ARRAY__DESCRIPTOR__v2 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--array--memory--requirements--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--array--memory--requirements--v1/DOC.md new file mode 100644 index 00000000..b3a43c60 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--array--memory--requirements--v1/DOC.md @@ -0,0 +1,36 @@ +--- +name: driver-struct-cuda--array--memory--requirements--v1 +description: '**Source:** structCUDA__ARRAY__MEMORY__REQUIREMENTS__v1.html#structCUDA__ARRAY__MEMORY__REQUIREMENTS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.14. CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 + +**Source:** structCUDA__ARRAY__MEMORY__REQUIREMENTS__v1.html#structCUDA__ARRAY__MEMORY__REQUIREMENTS__v1 + + +### Public Variables + +size_t alignment + +size_t size + + +### Variables + +size_t CUDA_ARRAY_MEMORY_REQUIREMENTS_v1::alignment + + +alignment requirement + +size_t CUDA_ARRAY_MEMORY_REQUIREMENTS_v1::size + + +Total required memory size + diff --git a/content/cuda/docs/driver-struct-cuda--array--sparse--properties--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--array--sparse--properties--v1/DOC.md new file mode 100644 index 00000000..fe8d77f2 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--array--sparse--properties--v1/DOC.md @@ -0,0 +1,64 @@ +--- +name: driver-struct-cuda--array--sparse--properties--v1 +description: '**Source:** structCUDA__ARRAY__SPARSE__PROPERTIES__v1.html#structCUDA__ARRAY__SPARSE__PROPERTIES__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.15. CUDA_ARRAY_SPARSE_PROPERTIES_v1 + +**Source:** structCUDA__ARRAY__SPARSE__PROPERTIES__v1.html#structCUDA__ARRAY__SPARSE__PROPERTIES__v1 + + +### Public Variables + +unsigned int depth + +unsigned int flags + +unsigned int height + +unsigned int miptailFirstLevel + +unsigned long long miptailSize + +unsigned int width + + +### Variables + +unsigned int CUDA_ARRAY_SPARSE_PROPERTIES_v1::depth + + +Depth of sparse tile in elements + +unsigned int CUDA_ARRAY_SPARSE_PROPERTIES_v1::flags + + +Flags will either be zero or CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL + +unsigned int CUDA_ARRAY_SPARSE_PROPERTIES_v1::height + + +Height of sparse tile in elements + +unsigned int CUDA_ARRAY_SPARSE_PROPERTIES_v1::miptailFirstLevel + + +First mip level at which the mip tail begins. + +unsigned long long CUDA_ARRAY_SPARSE_PROPERTIES_v1::miptailSize + + +Total size of the mip tail. + +unsigned int CUDA_ARRAY_SPARSE_PROPERTIES_v1::width + + +Width of sparse tile in elements + diff --git a/content/cuda/docs/driver-struct-cuda--array3d--descriptor--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--array3d--descriptor--v2/DOC.md new file mode 100644 index 00000000..5f83ee17 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--array3d--descriptor--v2/DOC.md @@ -0,0 +1,22 @@ +--- +name: driver-struct-cuda--array3d--descriptor--v2 +description: '**Source:** structCUDA__ARRAY3D__DESCRIPTOR__v2.html#structCUDA__ARRAY3D__DESCRIPTOR__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.12. CUDA_ARRAY3D_DESCRIPTOR_v2 + +**Source:** structCUDA__ARRAY3D__DESCRIPTOR__v2.html#structCUDA__ARRAY3D__DESCRIPTOR__v2 + + +### Public Variables + +size_t Depth + +unsigned int Flags diff --git a/content/cuda/docs/driver-struct-cuda--batch--mem--op--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--batch--mem--op--node--params--v1/DOC.md new file mode 100644 index 00000000..95758308 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--batch--mem--op--node--params--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuda--batch--mem--op--node--params--v1 +description: '**Source:** structCUDA__BATCH__MEM__OP__NODE__PARAMS__v1.html#structCUDA__BATCH__MEM__OP__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.16. CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 + +**Source:** structCUDA__BATCH__MEM__OP__NODE__PARAMS__v1.html#structCUDA__BATCH__MEM__OP__NODE__PARAMS__v1 + + diff --git a/content/cuda/docs/driver-struct-cuda--child--graph--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--child--graph--node--params/DOC.md new file mode 100644 index 00000000..6823069f --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--child--graph--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--child--graph--node--params +description: '**Source:** structCUDA__CHILD__GRAPH__NODE__PARAMS.html#structCUDA__CHILD__GRAPH__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.18. CUDA_CHILD_GRAPH_NODE_PARAMS + +**Source:** structCUDA__CHILD__GRAPH__NODE__PARAMS.html#structCUDA__CHILD__GRAPH__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--conditional--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--conditional--node--params/DOC.md new file mode 100644 index 00000000..b77ae54b --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--conditional--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--conditional--node--params +description: '**Source:** structCUDA__CONDITIONAL__NODE__PARAMS.html#structCUDA__CONDITIONAL__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.19. CUDA_CONDITIONAL_NODE_PARAMS + +**Source:** structCUDA__CONDITIONAL__NODE__PARAMS.html#structCUDA__CONDITIONAL__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--event--record--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--event--record--node--params/DOC.md new file mode 100644 index 00000000..048ebd3f --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--event--record--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--event--record--node--params +description: '**Source:** structCUDA__EVENT__RECORD__NODE__PARAMS.html#structCUDA__EVENT__RECORD__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.20. CUDA_EVENT_RECORD_NODE_PARAMS + +**Source:** structCUDA__EVENT__RECORD__NODE__PARAMS.html#structCUDA__EVENT__RECORD__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--event--wait--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--event--wait--node--params/DOC.md new file mode 100644 index 00000000..bb934539 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--event--wait--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--event--wait--node--params +description: '**Source:** structCUDA__EVENT__WAIT__NODE__PARAMS.html#structCUDA__EVENT__WAIT__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.21. CUDA_EVENT_WAIT_NODE_PARAMS + +**Source:** structCUDA__EVENT__WAIT__NODE__PARAMS.html#structCUDA__EVENT__WAIT__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v1/DOC.md new file mode 100644 index 00000000..863623c8 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v1/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cuda--ext--sem--signal--node--params--v1 +description: '**Source:** structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v1.html#structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.22. CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 + +**Source:** structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v1.html#structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v1 + + +### Public Variables + +CUexternalSemaphore* * extSemArray + +unsigned int numExtSems + +const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS * paramsArray + + +### Variables + +CUexternalSemaphore* * CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1::extSemArray + + +Array of external semaphore handles. + +unsigned int CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1::numExtSems + + +Number of handles and parameters supplied in extSemArray and paramsArray. + +const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS * CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1::paramsArray + + +Array of external semaphore signal parameters. + diff --git a/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v2/DOC.md new file mode 100644 index 00000000..d86081c6 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--ext--sem--signal--node--params--v2/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cuda--ext--sem--signal--node--params--v2 +description: '**Source:** structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v2.html#structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.23. CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 + +**Source:** structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v2.html#structCUDA__EXT__SEM__SIGNAL__NODE__PARAMS__v2 + + +### Public Variables + +CUexternalSemaphore* * extSemArray + +unsigned int numExtSems + +const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS * paramsArray + + +### Variables + +CUexternalSemaphore* * CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2::extSemArray + + +Array of external semaphore handles. + +unsigned int CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2::numExtSems + + +Number of handles and parameters supplied in extSemArray and paramsArray. + +const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS * CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2::paramsArray + + +Array of external semaphore signal parameters. + diff --git a/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v1/DOC.md new file mode 100644 index 00000000..65daf62a --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v1/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cuda--ext--sem--wait--node--params--v1 +description: '**Source:** structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v1.html#structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.24. CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 + +**Source:** structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v1.html#structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v1 + + +### Public Variables + +CUexternalSemaphore* * extSemArray + +unsigned int numExtSems + +const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS * paramsArray + + +### Variables + +CUexternalSemaphore* * CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1::extSemArray + + +Array of external semaphore handles. + +unsigned int CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1::numExtSems + + +Number of handles and parameters supplied in extSemArray and paramsArray. + +const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS * CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1::paramsArray + + +Array of external semaphore wait parameters. + diff --git a/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v2/DOC.md new file mode 100644 index 00000000..262764bf --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--ext--sem--wait--node--params--v2/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cuda--ext--sem--wait--node--params--v2 +description: '**Source:** structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v2.html#structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.25. CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 + +**Source:** structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v2.html#structCUDA__EXT__SEM__WAIT__NODE__PARAMS__v2 + + +### Public Variables + +CUexternalSemaphore* * extSemArray + +unsigned int numExtSems + +const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS * paramsArray + + +### Variables + +CUexternalSemaphore* * CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2::extSemArray + + +Array of external semaphore handles. + +unsigned int CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2::numExtSems + + +Number of handles and parameters supplied in extSemArray and paramsArray. + +const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS * CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2::paramsArray + + +Array of external semaphore wait parameters. + diff --git a/content/cuda/docs/driver-struct-cuda--external--memory--buffer--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--memory--buffer--desc--v1/DOC.md new file mode 100644 index 00000000..447731c5 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--memory--buffer--desc--v1/DOC.md @@ -0,0 +1,43 @@ +--- +name: driver-struct-cuda--external--memory--buffer--desc--v1 +description: '**Source:** structCUDA__EXTERNAL__MEMORY__BUFFER__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__BUFFER__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.26. CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 + +**Source:** structCUDA__EXTERNAL__MEMORY__BUFFER__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__BUFFER__DESC__v1 + + +### Public Variables + +unsigned int flags + +unsigned long long offset + +unsigned long long size + + +### Variables + +unsigned int CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1::flags + + +Flags reserved for future use. Must be zero. + +unsigned long long CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1::offset + + +Offset into the memory object where the buffer's base is + +unsigned long long CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1::size + + +Size of the buffer + diff --git a/content/cuda/docs/driver-struct-cuda--external--memory--handle--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--memory--handle--desc--v1/DOC.md new file mode 100644 index 00000000..5f9b8f31 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--memory--handle--desc--v1/DOC.md @@ -0,0 +1,30 @@ +--- +name: driver-struct-cuda--external--memory--handle--desc--v1 +description: '**Source:** structCUDA__EXTERNAL__MEMORY__HANDLE__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__HANDLE__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.27. CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 + +**Source:** structCUDA__EXTERNAL__MEMORY__HANDLE__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__HANDLE__DESC__v1 + + +### Public Variables + +int fd + +unsigned int flags + +void * handle + +const void * name + +const void * nvSciBufObject + +unsigned long long size diff --git a/content/cuda/docs/driver-struct-cuda--external--memory--mipmapped--array--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--memory--mipmapped--array--desc--v1/DOC.md new file mode 100644 index 00000000..f121fede --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--memory--mipmapped--array--desc--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--external--memory--mipmapped--array--desc--v1 +description: '**Source:** structCUDA__EXTERNAL__MEMORY__MIPMAPPED__ARRAY__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__MIPMAPPED__ARRAY__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.28. CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 + +**Source:** structCUDA__EXTERNAL__MEMORY__MIPMAPPED__ARRAY__DESC__v1.html#structCUDA__EXTERNAL__MEMORY__MIPMAPPED__ARRAY__DESC__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--external--semaphore--handle--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--semaphore--handle--desc--v1/DOC.md new file mode 100644 index 00000000..715069e0 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--semaphore--handle--desc--v1/DOC.md @@ -0,0 +1,28 @@ +--- +name: driver-struct-cuda--external--semaphore--handle--desc--v1 +description: '**Source:** structCUDA__EXTERNAL__SEMAPHORE__HANDLE__DESC__v1.html#structCUDA__EXTERNAL__SEMAPHORE__HANDLE__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.29. CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 + +**Source:** structCUDA__EXTERNAL__SEMAPHORE__HANDLE__DESC__v1.html#structCUDA__EXTERNAL__SEMAPHORE__HANDLE__DESC__v1 + + +### Public Variables + +int fd + +unsigned int flags + +void * handle + +const void * name + +const void * nvSciSyncObj diff --git a/content/cuda/docs/driver-struct-cuda--external--semaphore--signal--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--semaphore--signal--params--v1/DOC.md new file mode 100644 index 00000000..ec317876 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--semaphore--signal--params--v1/DOC.md @@ -0,0 +1,64 @@ +--- +name: driver-struct-cuda--external--semaphore--signal--params--v1 +description: '**Source:** structCUDA__EXTERNAL__SEMAPHORE__SIGNAL__PARAMS__v1.html#structCUDA__EXTERNAL__SEMAPHORE__SIGNAL__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.30. CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 + +**Source:** structCUDA__EXTERNAL__SEMAPHORE__SIGNAL__PARAMS__v1.html#structCUDA__EXTERNAL__SEMAPHORE__SIGNAL__PARAMS__v1 + + +### Public Variables + +void * fence + +CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::@23::@24 fence + +unsigned int flags + +unsigned long long key + +CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::@23::@26 keyedMutex + +unsigned long long value + + +### Variables + +void * CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::fence + + +Pointer to NvSciSyncFence. Valid if CUexternalSemaphoreHandleType is of type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC. + +CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::@23::@24 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::fence + + +Parameters for fence objects + +unsigned int CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::flags + + +Only when CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS is used to signal a CUexternalSemaphore of type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, the valid flag is CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC which indicates that while signaling the CUexternalSemaphore, no memory synchronization operations should be performed for any external memory object imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. For all other types of CUexternalSemaphore, flags must be zero. + +unsigned long long CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::key + + +Value of key to release the mutex with + +CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::@23::@26 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::keyedMutex + + +Parameters for keyed mutex objects + +unsigned long long CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1::value + + +Value of fence to be signaled + diff --git a/content/cuda/docs/driver-struct-cuda--external--semaphore--wait--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--external--semaphore--wait--params--v1/DOC.md new file mode 100644 index 00000000..7b2c9f1d --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--external--semaphore--wait--params--v1/DOC.md @@ -0,0 +1,71 @@ +--- +name: driver-struct-cuda--external--semaphore--wait--params--v1 +description: '**Source:** structCUDA__EXTERNAL__SEMAPHORE__WAIT__PARAMS__v1.html#structCUDA__EXTERNAL__SEMAPHORE__WAIT__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.31. CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 + +**Source:** structCUDA__EXTERNAL__SEMAPHORE__WAIT__PARAMS__v1.html#structCUDA__EXTERNAL__SEMAPHORE__WAIT__PARAMS__v1 + + +### Public Variables + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@28 fence + +unsigned int flags + +unsigned long long key + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@30 keyedMutex + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@29 nvSciSync + +unsigned int timeoutMs + +unsigned long long value + + +### Variables + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@28 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::fence + + +Parameters for fence objects + +unsigned int CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::flags + + +Only when CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS is used to wait on a CUexternalSemaphore of type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, the valid flag is CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC which indicates that while waiting for the CUexternalSemaphore, no memory synchronization operations should be performed for any external memory object imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. For all other types of CUexternalSemaphore, flags must be zero. + +unsigned long long CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::key + + +Value of key to acquire the mutex with + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@30 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::keyedMutex + + +Parameters for keyed mutex objects + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::@27::@29 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::nvSciSync + + +Pointer to NvSciSyncFence. Valid if CUexternalSemaphoreHandleType is of type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC. + +unsigned int CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::timeoutMs + + +Timeout in milliseconds to wait to acquire the mutex + +unsigned long long CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1::value + + +Value of fence to be waited on + diff --git a/content/cuda/docs/driver-struct-cuda--graph--instantiate--params/DOC.md b/content/cuda/docs/driver-struct-cuda--graph--instantiate--params/DOC.md new file mode 100644 index 00000000..7bd94663 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--graph--instantiate--params/DOC.md @@ -0,0 +1,20 @@ +--- +name: driver-struct-cuda--graph--instantiate--params +description: '**Source:** structCUDA__GRAPH__INSTANTIATE__PARAMS.html#structCUDA__GRAPH__INSTANTIATE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.32. CUDA_GRAPH_INSTANTIATE_PARAMS + +**Source:** structCUDA__GRAPH__INSTANTIATE__PARAMS.html#structCUDA__GRAPH__INSTANTIATE__PARAMS + + +### Public Variables + +cuuint64_t flags diff --git a/content/cuda/docs/driver-struct-cuda--host--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--host--node--params--v1/DOC.md new file mode 100644 index 00000000..4e31d927 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--host--node--params--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--host--node--params--v1 +description: '**Source:** structCUDA__HOST__NODE__PARAMS__v1.html#structCUDA__HOST__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.33. CUDA_HOST_NODE_PARAMS_v1 + +**Source:** structCUDA__HOST__NODE__PARAMS__v1.html#structCUDA__HOST__NODE__PARAMS__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--host--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--host--node--params--v2/DOC.md new file mode 100644 index 00000000..dca3174b --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--host--node--params--v2/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--host--node--params--v2 +description: '**Source:** structCUDA__HOST__NODE__PARAMS__v2.html#structCUDA__HOST__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.34. CUDA_HOST_NODE_PARAMS_v2 + +**Source:** structCUDA__HOST__NODE__PARAMS__v2.html#structCUDA__HOST__NODE__PARAMS__v2 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--kernel--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v1/DOC.md new file mode 100644 index 00000000..a19766d0 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v1/DOC.md @@ -0,0 +1,26 @@ +--- +name: driver-struct-cuda--kernel--node--params--v1 +description: '**Source:** structCUDA__KERNEL__NODE__PARAMS__v1.html#structCUDA__KERNEL__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.35. CUDA_KERNEL_NODE_PARAMS_v1 + +**Source:** structCUDA__KERNEL__NODE__PARAMS__v1.html#structCUDA__KERNEL__NODE__PARAMS__v1 + + +### Public Variables + +unsigned int blockDimX + +unsigned int blockDimY + +unsigned int blockDimZ + +* extra diff --git a/content/cuda/docs/driver-struct-cuda--kernel--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v2/DOC.md new file mode 100644 index 00000000..4903f9d6 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v2/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--kernel--node--params--v2 +description: '**Source:** structCUDA__KERNEL__NODE__PARAMS__v2.html#structCUDA__KERNEL__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.36. CUDA_KERNEL_NODE_PARAMS_v2 + +**Source:** structCUDA__KERNEL__NODE__PARAMS__v2.html#structCUDA__KERNEL__NODE__PARAMS__v2 + + +### Public Variables + +unsigned int blockDimX + +unsigned int blockDimY + +unsigned int blockDimZ diff --git a/content/cuda/docs/driver-struct-cuda--kernel--node--params--v3/DOC.md b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v3/DOC.md new file mode 100644 index 00000000..d47ff5b9 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--kernel--node--params--v3/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--kernel--node--params--v3 +description: '**Source:** structCUDA__KERNEL__NODE__PARAMS__v3.html#structCUDA__KERNEL__NODE__PARAMS__v3' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.37. CUDA_KERNEL_NODE_PARAMS_v3 + +**Source:** structCUDA__KERNEL__NODE__PARAMS__v3.html#structCUDA__KERNEL__NODE__PARAMS__v3 + + +### Public Variables + +unsigned int blockDimX + +unsigned int blockDimY + +unsigned int blockDimZ diff --git a/content/cuda/docs/driver-struct-cuda--launch--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--launch--params--v1/DOC.md new file mode 100644 index 00000000..675739f5 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--launch--params--v1/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--launch--params--v1 +description: '**Source:** structCUDA__LAUNCH__PARAMS__v1.html#structCUDA__LAUNCH__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.38. CUDA_LAUNCH_PARAMS_v1 + +**Source:** structCUDA__LAUNCH__PARAMS__v1.html#structCUDA__LAUNCH__PARAMS__v1 + + +### Public Variables + +unsigned int blockDimX + +unsigned int blockDimY + +unsigned int blockDimZ diff --git a/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v1/DOC.md new file mode 100644 index 00000000..abf6996f --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v1/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--mem--alloc--node--params--v1 +description: '**Source:** structCUDA__MEM__ALLOC__NODE__PARAMS__v1.html#structCUDA__MEM__ALLOC__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.39. CUDA_MEM_ALLOC_NODE_PARAMS_v1 + +**Source:** structCUDA__MEM__ALLOC__NODE__PARAMS__v1.html#structCUDA__MEM__ALLOC__NODE__PARAMS__v1 + + +### Public Variables + +size_t accessDescCount + +const CUmemAccessDesc * accessDescs + +size_t bytesize diff --git a/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v2/DOC.md new file mode 100644 index 00000000..6230e933 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--mem--alloc--node--params--v2/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--mem--alloc--node--params--v2 +description: '**Source:** structCUDA__MEM__ALLOC__NODE__PARAMS__v2.html#structCUDA__MEM__ALLOC__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.40. CUDA_MEM_ALLOC_NODE_PARAMS_v2 + +**Source:** structCUDA__MEM__ALLOC__NODE__PARAMS__v2.html#structCUDA__MEM__ALLOC__NODE__PARAMS__v2 + + +### Public Variables + +size_t accessDescCount + +const CUmemAccessDesc * accessDescs + +size_t bytesize diff --git a/content/cuda/docs/driver-struct-cuda--mem--free--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--mem--free--node--params/DOC.md new file mode 100644 index 00000000..312e322d --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--mem--free--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--mem--free--node--params +description: '**Source:** structCUDA__MEM__FREE__NODE__PARAMS.html#structCUDA__MEM__FREE__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.41. CUDA_MEM_FREE_NODE_PARAMS + +**Source:** structCUDA__MEM__FREE__NODE__PARAMS.html#structCUDA__MEM__FREE__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--memcpy--node--params/DOC.md b/content/cuda/docs/driver-struct-cuda--memcpy--node--params/DOC.md new file mode 100644 index 00000000..f37d89c9 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memcpy--node--params/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--memcpy--node--params +description: '**Source:** structCUDA__MEMCPY__NODE__PARAMS.html#structCUDA__MEMCPY__NODE__PARAMS' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.45. CUDA_MEMCPY_NODE_PARAMS + +**Source:** structCUDA__MEMCPY__NODE__PARAMS.html#structCUDA__MEMCPY__NODE__PARAMS + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--memcpy2d--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--memcpy2d--v2/DOC.md new file mode 100644 index 00000000..a834efe1 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memcpy2d--v2/DOC.md @@ -0,0 +1,22 @@ +--- +name: driver-struct-cuda--memcpy2d--v2 +description: '**Source:** structCUDA__MEMCPY2D__v2.html#structCUDA__MEMCPY2D__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.42. CUDA_MEMCPY2D_v2 + +**Source:** structCUDA__MEMCPY2D__v2.html#structCUDA__MEMCPY2D__v2 + + +### Public Variables + +size_t Height + +size_t WidthInBytes diff --git a/content/cuda/docs/driver-struct-cuda--memcpy3d--peer--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--memcpy3d--peer--v1/DOC.md new file mode 100644 index 00000000..06e0e2c2 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memcpy3d--peer--v1/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--memcpy3d--peer--v1 +description: '**Source:** structCUDA__MEMCPY3D__PEER__v1.html#structCUDA__MEMCPY3D__PEER__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.43. CUDA_MEMCPY3D_PEER_v1 + +**Source:** structCUDA__MEMCPY3D__PEER__v1.html#structCUDA__MEMCPY3D__PEER__v1 + + +### Public Variables + +size_t Depth + +size_t Height + +size_t WidthInBytes diff --git a/content/cuda/docs/driver-struct-cuda--memcpy3d--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--memcpy3d--v2/DOC.md new file mode 100644 index 00000000..82a48375 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memcpy3d--v2/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--memcpy3d--v2 +description: '**Source:** structCUDA__MEMCPY3D__v2.html#structCUDA__MEMCPY3D__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.44. CUDA_MEMCPY3D_v2 + +**Source:** structCUDA__MEMCPY3D__v2.html#structCUDA__MEMCPY3D__v2 + + +### Public Variables + +size_t Depth + +size_t Height + +size_t WidthInBytes diff --git a/content/cuda/docs/driver-struct-cuda--memset--node--params--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--memset--node--params--v1/DOC.md new file mode 100644 index 00000000..3daf4b20 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memset--node--params--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--memset--node--params--v1 +description: '**Source:** structCUDA__MEMSET__NODE__PARAMS__v1.html#structCUDA__MEMSET__NODE__PARAMS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.46. CUDA_MEMSET_NODE_PARAMS_v1 + +**Source:** structCUDA__MEMSET__NODE__PARAMS__v1.html#structCUDA__MEMSET__NODE__PARAMS__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--memset--node--params--v2/DOC.md b/content/cuda/docs/driver-struct-cuda--memset--node--params--v2/DOC.md new file mode 100644 index 00000000..eb7903ad --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--memset--node--params--v2/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--memset--node--params--v2 +description: '**Source:** structCUDA__MEMSET__NODE__PARAMS__v2.html#structCUDA__MEMSET__NODE__PARAMS__v2' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.47. CUDA_MEMSET_NODE_PARAMS_v2 + +**Source:** structCUDA__MEMSET__NODE__PARAMS__v2.html#structCUDA__MEMSET__NODE__PARAMS__v2 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--pointer--attribute--p2p--tokens--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--pointer--attribute--p2p--tokens--v1/DOC.md new file mode 100644 index 00000000..5317ecf9 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--pointer--attribute--p2p--tokens--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuda--pointer--attribute--p2p--tokens--v1 +description: '**Source:** structCUDA__POINTER__ATTRIBUTE__P2P__TOKENS__v1.html#structCUDA__POINTER__ATTRIBUTE__P2P__TOKENS__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.48. CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 + +**Source:** structCUDA__POINTER__ATTRIBUTE__P2P__TOKENS__v1.html#structCUDA__POINTER__ATTRIBUTE__P2P__TOKENS__v1 + + diff --git a/content/cuda/docs/driver-struct-cuda--resource--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--resource--desc--v1/DOC.md new file mode 100644 index 00000000..7e442ef5 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--resource--desc--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--resource--desc--v1 +description: '**Source:** structCUDA__RESOURCE__DESC__v1.html#structCUDA__RESOURCE__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.49. CUDA_RESOURCE_DESC_v1 + +**Source:** structCUDA__RESOURCE__DESC__v1.html#structCUDA__RESOURCE__DESC__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuda--resource--view--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--resource--view--desc--v1/DOC.md new file mode 100644 index 00000000..cb8f5b24 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--resource--view--desc--v1/DOC.md @@ -0,0 +1,24 @@ +--- +name: driver-struct-cuda--resource--view--desc--v1 +description: '**Source:** structCUDA__RESOURCE__VIEW__DESC__v1.html#structCUDA__RESOURCE__VIEW__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.50. CUDA_RESOURCE_VIEW_DESC_v1 + +**Source:** structCUDA__RESOURCE__VIEW__DESC__v1.html#structCUDA__RESOURCE__VIEW__DESC__v1 + + +### Public Variables + +size_t depth + +unsigned int firstLayer + +unsigned int firstMipmapLevel diff --git a/content/cuda/docs/driver-struct-cuda--texture--desc--v1/DOC.md b/content/cuda/docs/driver-struct-cuda--texture--desc--v1/DOC.md new file mode 100644 index 00000000..6e6b0edb --- /dev/null +++ b/content/cuda/docs/driver-struct-cuda--texture--desc--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cuda--texture--desc--v1 +description: '**Source:** structCUDA__TEXTURE__DESC__v1.html#structCUDA__TEXTURE__DESC__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.51. CUDA_TEXTURE_DESC_v1 + +**Source:** structCUDA__TEXTURE__DESC__v1.html#structCUDA__TEXTURE__DESC__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cudevprop--v1/DOC.md b/content/cuda/docs/driver-struct-cudevprop--v1/DOC.md new file mode 100644 index 00000000..4632480f --- /dev/null +++ b/content/cuda/docs/driver-struct-cudevprop--v1/DOC.md @@ -0,0 +1,92 @@ +--- +name: driver-struct-cudevprop--v1 +description: '**Source:** structCUdevprop__v1.html#structCUdevprop__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.52. CUdevprop_v1 + +**Source:** structCUdevprop__v1.html#structCUdevprop__v1 + + +### Public Variables + +int SIMDWidth + +int clockRate + +int maxGridSize[3] + +int maxThreadsDim[3] + +int maxThreadsPerBlock + +int memPitch + +int regsPerBlock + +int sharedMemPerBlock + +int textureAlign + +int totalConstantMemory + + +### Variables + +int CUdevprop_v1::SIMDWidth + + +Warp size in threads + +int CUdevprop_v1::clockRate + + +Clock frequency in kilohertz + +int CUdevprop_v1::maxGridSize[3] + + +Maximum size of each dimension of a grid + +int CUdevprop_v1::maxThreadsDim[3] + + +Maximum size of each dimension of a block + +int CUdevprop_v1::maxThreadsPerBlock + + +Maximum number of threads per block + +int CUdevprop_v1::memPitch + + +Maximum pitch in bytes allowed by memory copies + +int CUdevprop_v1::regsPerBlock + + +32-bit registers available per block + +int CUdevprop_v1::sharedMemPerBlock + + +Shared memory available per block in bytes + +int CUdevprop_v1::textureAlign + + +Alignment requirement for textures + +int CUdevprop_v1::totalConstantMemory + + +Constant memory available on device in bytes + diff --git a/content/cuda/docs/driver-struct-cudevresource/DOC.md b/content/cuda/docs/driver-struct-cudevresource/DOC.md new file mode 100644 index 00000000..e0a35f22 --- /dev/null +++ b/content/cuda/docs/driver-struct-cudevresource/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cudevresource +description: '**Source:** structCUdevResource.html#structCUdevResource' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.53. CUdevResource + +**Source:** structCUdevResource.html#structCUdevResource + + diff --git a/content/cuda/docs/driver-struct-cudevsmresource/DOC.md b/content/cuda/docs/driver-struct-cudevsmresource/DOC.md new file mode 100644 index 00000000..fa2d53c1 --- /dev/null +++ b/content/cuda/docs/driver-struct-cudevsmresource/DOC.md @@ -0,0 +1,50 @@ +--- +name: driver-struct-cudevsmresource +description: '**Source:** structCUdevSmResource.html#structCUdevSmResource' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.54. CUdevSmResource + +**Source:** structCUdevSmResource.html#structCUdevSmResource + + +### Public Variables + +unsigned int flags + +unsigned int minSmPartitionSize + +unsigned int smCoscheduledAlignment + +unsigned int smCount + + +### Variables + +unsigned int CUdevSmResource::flags + + +The flags set on this SM resource. For possible values see CUdevSmResourceGroup_flags. + +unsigned int CUdevSmResource::minSmPartitionSize + + +The minimum number of streaming multiprocessors required to partition this resource. + +unsigned int CUdevSmResource::smCoscheduledAlignment + + +The number of streaming multiprocessors in this resource that are guaranteed to be co-scheduled on the same GPU processing cluster. smCount will be a multiple of this value, unless the backfill flag is set. + +unsigned int CUdevSmResource::smCount + + +The amount of streaming multiprocessors available in this resource. + diff --git a/content/cuda/docs/driver-struct-cudevworkqueueconfigresource/DOC.md b/content/cuda/docs/driver-struct-cudevworkqueueconfigresource/DOC.md new file mode 100644 index 00000000..4cce3096 --- /dev/null +++ b/content/cuda/docs/driver-struct-cudevworkqueueconfigresource/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cudevworkqueueconfigresource +description: '**Source:** structCUdevWorkqueueConfigResource.html#structCUdevWorkqueueConfigResource' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.55. CUdevWorkqueueConfigResource + +**Source:** structCUdevWorkqueueConfigResource.html#structCUdevWorkqueueConfigResource + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cudevworkqueueresource/DOC.md b/content/cuda/docs/driver-struct-cudevworkqueueresource/DOC.md new file mode 100644 index 00000000..ff31c9fe --- /dev/null +++ b/content/cuda/docs/driver-struct-cudevworkqueueresource/DOC.md @@ -0,0 +1,29 @@ +--- +name: driver-struct-cudevworkqueueresource +description: '**Source:** structCUdevWorkqueueResource.html#structCUdevWorkqueueResource' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.56. CUdevWorkqueueResource + +**Source:** structCUdevWorkqueueResource.html#structCUdevWorkqueueResource + + +### Public Variables + +unsigned char reserved[RESOURCE_ABI_BYTES] + + +### Variables + +unsigned char CUdevWorkqueueResource::reserved[RESOURCE_ABI_BYTES] + + +Reserved for future use + diff --git a/content/cuda/docs/driver-struct-cueglframe--v1/DOC.md b/content/cuda/docs/driver-struct-cueglframe--v1/DOC.md new file mode 100644 index 00000000..259d91c7 --- /dev/null +++ b/content/cuda/docs/driver-struct-cueglframe--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cueglframe--v1 +description: '**Source:** structCUeglFrame__v1.html#structCUeglFrame__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.57. CUeglFrame_v1 + +**Source:** structCUeglFrame__v1.html#structCUeglFrame__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuexecaffinityparam--v1/DOC.md b/content/cuda/docs/driver-struct-cuexecaffinityparam--v1/DOC.md new file mode 100644 index 00000000..bdb9c61c --- /dev/null +++ b/content/cuda/docs/driver-struct-cuexecaffinityparam--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuexecaffinityparam--v1 +description: '**Source:** structCUexecAffinityParam__v1.html#structCUexecAffinityParam__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.58. CUexecAffinityParam_v1 + +**Source:** structCUexecAffinityParam__v1.html#structCUexecAffinityParam__v1 + + diff --git a/content/cuda/docs/driver-struct-cuexecaffinitysmcount--v1/DOC.md b/content/cuda/docs/driver-struct-cuexecaffinitysmcount--v1/DOC.md new file mode 100644 index 00000000..968abb84 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuexecaffinitysmcount--v1/DOC.md @@ -0,0 +1,29 @@ +--- +name: driver-struct-cuexecaffinitysmcount--v1 +description: '**Source:** structCUexecAffinitySmCount__v1.html#structCUexecAffinitySmCount__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.59. CUexecAffinitySmCount_v1 + +**Source:** structCUexecAffinitySmCount__v1.html#structCUexecAffinitySmCount__v1 + + +### Public Variables + +unsigned int val + + +### Variables + +unsigned int CUexecAffinitySmCount_v1::val + + +The number of SMs the context is limited to use. + diff --git a/content/cuda/docs/driver-struct-cuextent3d--v1/DOC.md b/content/cuda/docs/driver-struct-cuextent3d--v1/DOC.md new file mode 100644 index 00000000..0b04ef82 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuextent3d--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuextent3d--v1 +description: '**Source:** structCUextent3D__v1.html#structCUextent3D__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.60. CUextent3D_v1 + +**Source:** structCUextent3D__v1.html#structCUextent3D__v1 + + diff --git a/content/cuda/docs/driver-struct-cugraphedgedata/DOC.md b/content/cuda/docs/driver-struct-cugraphedgedata/DOC.md new file mode 100644 index 00000000..683514e3 --- /dev/null +++ b/content/cuda/docs/driver-struct-cugraphedgedata/DOC.md @@ -0,0 +1,50 @@ +--- +name: driver-struct-cugraphedgedata +description: '**Source:** structCUgraphEdgeData.html#structCUgraphEdgeData' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.61. CUgraphEdgeData + +**Source:** structCUgraphEdgeData.html#structCUgraphEdgeData + + +### Public Variables + +unsigned char from_port + +unsigned char reserved[5] + +unsigned char to_port + +unsigned char type + + +### Variables + +unsigned char CUgraphEdgeData::from_port + + +This indicates when the dependency is triggered from the upstream node on the edge. The meaning is specfic to the node type. A value of 0 in all cases means full completion of the upstream node, with memory visibility to the downstream node or portion thereof (indicated by `to_port`). Only kernel nodes define non-zero ports. A kernel node can use the following output port types: CU_GRAPH_KERNEL_NODE_PORT_DEFAULT, CU_GRAPH_KERNEL_NODE_PORT_PROGRAMMATIC, or CU_GRAPH_KERNEL_NODE_PORT_LAUNCH_ORDER. + +unsigned char CUgraphEdgeData::reserved[5] + + +These bytes are unused and must be zeroed. This ensures compatibility if additional fields are added in the future. + +unsigned char CUgraphEdgeData::to_port + + +This indicates what portion of the downstream node is dependent on the upstream node or portion thereof (indicated by `from_port`). The meaning is specific to the node type. A value of 0 in all cases means the entirety of the downstream node is dependent on the upstream work. Currently no node types define non-zero ports. Accordingly, this field must be set to zero. + +unsigned char CUgraphEdgeData::type + + +This should be populated with a value from CUgraphDependencyType. (It is typed as char due to compiler-specific layout of bitfields.) See CUgraphDependencyType. + diff --git a/content/cuda/docs/driver-struct-cugraphexecupdateresultinfo--v1/DOC.md b/content/cuda/docs/driver-struct-cugraphexecupdateresultinfo--v1/DOC.md new file mode 100644 index 00000000..42763280 --- /dev/null +++ b/content/cuda/docs/driver-struct-cugraphexecupdateresultinfo--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cugraphexecupdateresultinfo--v1 +description: '**Source:** structCUgraphExecUpdateResultInfo__v1.html#structCUgraphExecUpdateResultInfo__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.62. CUgraphExecUpdateResultInfo_v1 + +**Source:** structCUgraphExecUpdateResultInfo__v1.html#structCUgraphExecUpdateResultInfo__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cugraphnodeparams/DOC.md b/content/cuda/docs/driver-struct-cugraphnodeparams/DOC.md new file mode 100644 index 00000000..cfe0bcd9 --- /dev/null +++ b/content/cuda/docs/driver-struct-cugraphnodeparams/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cugraphnodeparams +description: '**Source:** structCUgraphNodeParams.html#structCUgraphNodeParams' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.63. CUgraphNodeParams + +**Source:** structCUgraphNodeParams.html#structCUgraphNodeParams + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cuipceventhandle--v1/DOC.md b/content/cuda/docs/driver-struct-cuipceventhandle--v1/DOC.md new file mode 100644 index 00000000..6e399120 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuipceventhandle--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuipceventhandle--v1 +description: '**Source:** structCUipcEventHandle__v1.html#structCUipcEventHandle__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.64. CUipcEventHandle_v1 + +**Source:** structCUipcEventHandle__v1.html#structCUipcEventHandle__v1 + + diff --git a/content/cuda/docs/driver-struct-cuipcmemhandle--v1/DOC.md b/content/cuda/docs/driver-struct-cuipcmemhandle--v1/DOC.md new file mode 100644 index 00000000..bfb19e55 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuipcmemhandle--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuipcmemhandle--v1 +description: '**Source:** structCUipcMemHandle__v1.html#structCUipcMemHandle__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.65. CUipcMemHandle_v1 + +**Source:** structCUipcMemHandle__v1.html#structCUipcMemHandle__v1 + + diff --git a/content/cuda/docs/driver-struct-culaunchattribute/DOC.md b/content/cuda/docs/driver-struct-culaunchattribute/DOC.md new file mode 100644 index 00000000..b62d1c12 --- /dev/null +++ b/content/cuda/docs/driver-struct-culaunchattribute/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-culaunchattribute +description: '**Source:** structCUlaunchAttribute.html#structCUlaunchAttribute' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.66. CUlaunchAttribute + +**Source:** structCUlaunchAttribute.html#structCUlaunchAttribute + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-culaunchconfig/DOC.md b/content/cuda/docs/driver-struct-culaunchconfig/DOC.md new file mode 100644 index 00000000..e59c0540 --- /dev/null +++ b/content/cuda/docs/driver-struct-culaunchconfig/DOC.md @@ -0,0 +1,32 @@ +--- +name: driver-struct-culaunchconfig +description: '**Source:** structCUlaunchConfig.html#structCUlaunchConfig' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.68. CUlaunchConfig + +**Source:** structCUlaunchConfig.html#structCUlaunchConfig + + +### Public Variables + +CUlaunchAttribute * attrs + +unsigned int blockDimX + +unsigned int blockDimY + +unsigned int blockDimZ + +unsigned int gridDimX + +unsigned int gridDimY + +unsigned int gridDimZ diff --git a/content/cuda/docs/driver-struct-culaunchmemsyncdomainmap/DOC.md b/content/cuda/docs/driver-struct-culaunchmemsyncdomainmap/DOC.md new file mode 100644 index 00000000..d4301b59 --- /dev/null +++ b/content/cuda/docs/driver-struct-culaunchmemsyncdomainmap/DOC.md @@ -0,0 +1,36 @@ +--- +name: driver-struct-culaunchmemsyncdomainmap +description: '**Source:** structCUlaunchMemSyncDomainMap.html#structCUlaunchMemSyncDomainMap' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.69. CUlaunchMemSyncDomainMap + +**Source:** structCUlaunchMemSyncDomainMap.html#structCUlaunchMemSyncDomainMap + + +### Public Variables + +unsigned char default_ + +unsigned char remote + + +### Variables + +unsigned char CUlaunchMemSyncDomainMap::default_ + + +The default domain ID to use for designated kernels + +unsigned char CUlaunchMemSyncDomainMap::remote + + +The remote domain ID to use for designated kernels + diff --git a/content/cuda/docs/driver-struct-cumemaccessdesc--v1/DOC.md b/content/cuda/docs/driver-struct-cumemaccessdesc--v1/DOC.md new file mode 100644 index 00000000..035c3a72 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemaccessdesc--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cumemaccessdesc--v1 +description: '**Source:** structCUmemAccessDesc__v1.html#structCUmemAccessDesc__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.70. CUmemAccessDesc_v1 + +**Source:** structCUmemAccessDesc__v1.html#structCUmemAccessDesc__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cumemallocationprop--v1/DOC.md b/content/cuda/docs/driver-struct-cumemallocationprop--v1/DOC.md new file mode 100644 index 00000000..da2a4e60 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemallocationprop--v1/DOC.md @@ -0,0 +1,20 @@ +--- +name: driver-struct-cumemallocationprop--v1 +description: '**Source:** structCUmemAllocationProp__v1.html#structCUmemAllocationProp__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.71. CUmemAllocationProp_v1 + +**Source:** structCUmemAllocationProp__v1.html#structCUmemAllocationProp__v1 + + +### Public Variables + +unsigned char compressionType diff --git a/content/cuda/docs/driver-struct-cumemcpy3doperand--v1/DOC.md b/content/cuda/docs/driver-struct-cumemcpy3doperand--v1/DOC.md new file mode 100644 index 00000000..4a84cab8 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemcpy3doperand--v1/DOC.md @@ -0,0 +1,22 @@ +--- +name: driver-struct-cumemcpy3doperand--v1 +description: '**Source:** structCUmemcpy3DOperand__v1.html#structCUmemcpy3DOperand__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.72. CUmemcpy3DOperand_v1 + +**Source:** structCUmemcpy3DOperand__v1.html#structCUmemcpy3DOperand__v1 + + +### Public Variables + +CUmemcpy3DOperand_v1::@37::@39 array + +size_t layerHeight diff --git a/content/cuda/docs/driver-struct-cumemcpyattributes--v1/DOC.md b/content/cuda/docs/driver-struct-cumemcpyattributes--v1/DOC.md new file mode 100644 index 00000000..2844558e --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemcpyattributes--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cumemcpyattributes--v1 +description: '**Source:** structCUmemcpyAttributes__v1.html#structCUmemcpyAttributes__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.73. CUmemcpyAttributes_v1 + +**Source:** structCUmemcpyAttributes__v1.html#structCUmemcpyAttributes__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cumemdecompressparams/DOC.md b/content/cuda/docs/driver-struct-cumemdecompressparams/DOC.md new file mode 100644 index 00000000..df28e88c --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemdecompressparams/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cumemdecompressparams +description: '**Source:** structCUmemDecompressParams.html#structCUmemDecompressParams' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.74. CUmemDecompressParams + +**Source:** structCUmemDecompressParams.html#structCUmemDecompressParams + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cumemfabrichandle--v1/DOC.md b/content/cuda/docs/driver-struct-cumemfabrichandle--v1/DOC.md new file mode 100644 index 00000000..8afe9c46 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemfabrichandle--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cumemfabrichandle--v1 +description: '**Source:** structCUmemFabricHandle__v1.html#structCUmemFabricHandle__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.75. CUmemFabricHandle_v1 + +**Source:** structCUmemFabricHandle__v1.html#structCUmemFabricHandle__v1 + + diff --git a/content/cuda/docs/driver-struct-cumemlocation--v1/DOC.md b/content/cuda/docs/driver-struct-cumemlocation--v1/DOC.md new file mode 100644 index 00000000..a4a61749 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumemlocation--v1/DOC.md @@ -0,0 +1,20 @@ +--- +name: driver-struct-cumemlocation--v1 +description: '**Source:** structCUmemLocation__v1.html#structCUmemLocation__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.76. CUmemLocation_v1 + +**Source:** structCUmemLocation__v1.html#structCUmemLocation__v1 + + +### Public Variables + +int id diff --git a/content/cuda/docs/driver-struct-cumempoolprops--v1/DOC.md b/content/cuda/docs/driver-struct-cumempoolprops--v1/DOC.md new file mode 100644 index 00000000..322a6c2e --- /dev/null +++ b/content/cuda/docs/driver-struct-cumempoolprops--v1/DOC.md @@ -0,0 +1,18 @@ +--- +name: driver-struct-cumempoolprops--v1 +description: '**Source:** structCUmemPoolProps__v1.html#structCUmemPoolProps__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.77. CUmemPoolProps_v1 + +**Source:** structCUmemPoolProps__v1.html#structCUmemPoolProps__v1 + + +### Public Variables diff --git a/content/cuda/docs/driver-struct-cumempoolptrexportdata--v1/DOC.md b/content/cuda/docs/driver-struct-cumempoolptrexportdata--v1/DOC.md new file mode 100644 index 00000000..3e698e5e --- /dev/null +++ b/content/cuda/docs/driver-struct-cumempoolptrexportdata--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cumempoolptrexportdata--v1 +description: '**Source:** structCUmemPoolPtrExportData__v1.html#structCUmemPoolPtrExportData__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.78. CUmemPoolPtrExportData_v1 + +**Source:** structCUmemPoolPtrExportData__v1.html#structCUmemPoolPtrExportData__v1 + + diff --git a/content/cuda/docs/driver-struct-cumulticastobjectprop--v1/DOC.md b/content/cuda/docs/driver-struct-cumulticastobjectprop--v1/DOC.md new file mode 100644 index 00000000..5d447090 --- /dev/null +++ b/content/cuda/docs/driver-struct-cumulticastobjectprop--v1/DOC.md @@ -0,0 +1,50 @@ +--- +name: driver-struct-cumulticastobjectprop--v1 +description: '**Source:** structCUmulticastObjectProp__v1.html#structCUmulticastObjectProp__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.79. CUmulticastObjectProp_v1 + +**Source:** structCUmulticastObjectProp__v1.html#structCUmulticastObjectProp__v1 + + +### Public Variables + +unsigned long long flags + +unsigned long long handleTypes + +unsigned int numDevices + +size_t size + + +### Variables + +unsigned long long CUmulticastObjectProp_v1::flags + + +Flags for future use, must be zero now + +unsigned long long CUmulticastObjectProp_v1::handleTypes + + +Bitmask of exportable handle types (see CUmemAllocationHandleType) for this object + +unsigned int CUmulticastObjectProp_v1::numDevices + + +The number of devices in the multicast team that will bind memory to this object + +size_t CUmulticastObjectProp_v1::size + + +The maximum amount of memory that can be bound to this multicast object per device + diff --git a/content/cuda/docs/driver-struct-cuoffset3d--v1/DOC.md b/content/cuda/docs/driver-struct-cuoffset3d--v1/DOC.md new file mode 100644 index 00000000..c691c2c7 --- /dev/null +++ b/content/cuda/docs/driver-struct-cuoffset3d--v1/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cuoffset3d--v1 +description: '**Source:** structCUoffset3D__v1.html#structCUoffset3D__v1' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.80. CUoffset3D_v1 + +**Source:** structCUoffset3D__v1.html#structCUoffset3D__v1 + + diff --git a/content/cuda/docs/driver-struct-cutensormap/DOC.md b/content/cuda/docs/driver-struct-cutensormap/DOC.md new file mode 100644 index 00000000..c7882432 --- /dev/null +++ b/content/cuda/docs/driver-struct-cutensormap/DOC.md @@ -0,0 +1,17 @@ +--- +name: driver-struct-cutensormap +description: '**Source:** structCUtensorMap.html#structCUtensorMap' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,struct +--- + +# 7.82. CUtensorMap + +**Source:** structCUtensorMap.html#structCUtensorMap + + diff --git a/content/cuda/docs/driver-surfobject/DOC.md b/content/cuda/docs/driver-surfobject/DOC.md new file mode 100644 index 00000000..d91da3cf --- /dev/null +++ b/content/cuda/docs/driver-surfobject/DOC.md @@ -0,0 +1,78 @@ +--- +name: driver-surfobject +description: '**Source:** group__CUDA__SURFOBJECT.html#group__CUDA__SURFOBJECT' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.29. Surface Object Management + +**Source:** group__CUDA__SURFOBJECT.html#group__CUDA__SURFOBJECT + + +### Functions + +CUresult cuSurfObjectCreate ( CUsurfObject* pSurfObject, const CUDA_RESOURCE_DESC* pResDesc ) + + +Creates a surface object. + +###### Parameters + +`pSurfObject` + \- Surface object to create +`pResDesc` + \- Resource descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a surface object and returns it in `pSurfObject`. `pResDesc` describes the data to perform surface load/stores on. CUDA_RESOURCE_DESC::resType must be CU_RESOURCE_TYPE_ARRAY and CUDA_RESOURCE_DESC::res::array::hArray must be set to a valid CUDA array handle. CUDA_RESOURCE_DESC::flags must be set to zero. + +Surface objects are only supported on devices of compute capability 3.0 or higher. Additionally, a surface object is an opaque value, and, as such, should only be accessed through CUDA API calls. + +CUresult cuSurfObjectDestroy ( CUsurfObject surfObject ) + + +Destroys a surface object. + +###### Parameters + +`surfObject` + \- Surface object to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Destroys the surface object specified by `surfObject`. + +CUresult cuSurfObjectGetResourceDesc ( CUDA_RESOURCE_DESC* pResDesc, CUsurfObject surfObject ) + + +Returns a surface object's resource descriptor. + +###### Parameters + +`pResDesc` + \- Resource descriptor +`surfObject` + \- Surface object + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the resource descriptor for the surface object specified by `surfObject`. diff --git a/content/cuda/docs/driver-surfref--deprecated/DOC.md b/content/cuda/docs/driver-surfref--deprecated/DOC.md new file mode 100644 index 00000000..bcd08309 --- /dev/null +++ b/content/cuda/docs/driver-surfref--deprecated/DOC.md @@ -0,0 +1,64 @@ +--- +name: driver-surfref--deprecated +description: '**Source:** group__CUDA__SURFREF__DEPRECATED.html#group__CUDA__SURFREF__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.27. Surface Reference Management [DEPRECATED] + +**Source:** group__CUDA__SURFREF__DEPRECATED.html#group__CUDA__SURFREF__DEPRECATED + + +### Functions + +CUresult cuSurfRefGetArray ( CUarray* phArray, CUsurfref hSurfRef ) + + +Passes back the CUDA array bound to a surface reference. + +###### Parameters + +`phArray` + \- Surface reference handle +`hSurfRef` + \- Surface reference handle + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*phArray` the CUDA array bound to the surface reference `hSurfRef`, or returns CUDA_ERROR_INVALID_VALUE if the surface reference is not bound to any CUDA array. + +CUresult cuSurfRefSetArray ( CUsurfref hSurfRef, CUarray hArray, unsigned int Flags ) + + +Sets the CUDA array for a surface reference. + +###### Parameters + +`hSurfRef` + \- Surface reference handle +`hArray` + \- CUDA array handle +`Flags` + \- set to 0 + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Sets the CUDA array `hArray` to be read and written by the surface reference `hSurfRef`. Any previous CUDA array state associated with the surface reference is superseded by this function. `Flags` must be set to 0. The CUDA_ARRAY3D_SURFACE_LDST flag must have been set for the CUDA array. Any CUDA array previously bound to `hSurfRef` is unbound. diff --git a/content/cuda/docs/driver-tensor--memory/DOC.md b/content/cuda/docs/driver-tensor--memory/DOC.md new file mode 100644 index 00000000..6b3828b0 --- /dev/null +++ b/content/cuda/docs/driver-tensor--memory/DOC.md @@ -0,0 +1,590 @@ +--- +name: driver-tensor--memory +description: '**Source:** group__CUDA__TENSOR__MEMORY.html#group__CUDA__TENSOR__MEMORY' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.30. Tensor Map Object Managment + +**Source:** group__CUDA__TENSOR__MEMORY.html#group__CUDA__TENSOR__MEMORY + + +### Functions + +CUresult cuTensorMapEncodeIm2col ( CUtensorMap* tensorMap, CUtensorMapDataType tensorDataType, cuuint32_t tensorRank, void* globalAddress, const cuuint64_t* globalDim, const cuuint64_t* globalStrides, const int* pixelBoxLowerCorner, const int* pixelBoxUpperCorner, cuuint32_t channelsPerPixel, cuuint32_t pixelsPerColumn, const cuuint32_t* elementStrides, CUtensorMapInterleave interleave, CUtensorMapSwizzle swizzle, CUtensorMapL2promotion l2Promotion, CUtensorMapFloatOOBfill oobFill ) + + +Create a tensor map descriptor object representing im2col memory region. + +###### Parameters + +`tensorMap` + \- Tensor map object to create +`tensorDataType` + \- Tensor data type +`tensorRank` + \- Dimensionality of tensor; must be at least 3 +`globalAddress` + \- Starting address of memory region described by tensor +`globalDim` + \- Array containing tensor size (number of elements) along each of the `tensorRank` dimensions +`globalStrides` + \- Array containing stride size (in bytes) along each of the `tensorRank` \- 1 dimensions +`pixelBoxLowerCorner` + \- Array containing DHW dimensions of lower box corner +`pixelBoxUpperCorner` + \- Array containing DHW dimensions of upper box corner +`channelsPerPixel` + \- Number of channels per pixel +`pixelsPerColumn` + \- Number of pixels per column +`elementStrides` + \- Array containing traversal stride in each of the `tensorRank` dimensions +`interleave` + \- Type of interleaved layout the tensor addresses +`swizzle` + \- Bank swizzling pattern inside shared memory +`l2Promotion` + \- L2 promotion size +`oobFill` + \- Indicate whether zero or special NaN constant will be used to fill out-of-bound elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a im2col memory layout and returns it in `tensorMap`. + +Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. + +The parameters passed are bound to the following requirements: + + * `tensorMap` address must be aligned to 64 bytes. + + + * `tensorDataType` has to be an enum from CUtensorMapDataType which is defined as: + + ‎ typedef enum CUtensorMapDataType_enum { + CU_TENSOR_MAP_DATA_TYPE_UINT8 = 0, // 1 byte + CU_TENSOR_MAP_DATA_TYPE_UINT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_INT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_INT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B // 6 bits + } CUtensorMapDataType; + +CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B copies '16 x U4' packed values to memory aligned as 8 bytes. There are no gaps between packed values. CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B copies '16 x U4' packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B copies '16 x U6' packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values. + + + * `tensorRank`, which specifies the number of tensor dimensions, must be 3, 4, or 5. + + + * `globalAddress`, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, `globalAddress` must be 32 byte aligned. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, `globalAddress` must be 32 byte aligned. + + + * `globalDim` array, which specifies tensor size of each of the `tensorRank` dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types: + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, globalDim[0] must be a multiple of 128. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, `globalDim`[0] must be a multiple of 2. + + * Dimension for the packed data types must reflect the number of individual U# values. + + + * `globalStrides` array, which specifies tensor stride of each of the lower `tensorRank` \- 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, the strides must be a multiple of 32. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride: + + ‎ globalStrides[0] = globalDim[0] * elementSizeInBytes(tensorDataType) + padding[0]; + for (i = 1; i < tensorRank - 1; i++) + globalStrides[i] = globalStrides[i – 1] * (globalDim[i] + padding[i]); + assert(globalStrides[i] >= globalDim[i]); + + + * `pixelBoxLowerCorner` array specifies the coordinate offsets {D, H, W} of the bounding box from top/left/front corner. The number of offsets and their precision depend on the tensor dimensionality: + * When `tensorRank` is 3, one signed offset within range [-32768, 32767] is supported. + + * When `tensorRank` is 4, two signed offsets each within range [-128, 127] are supported. + + * When `tensorRank` is 5, three offsets each within range [-16, 15] are supported. + + + * `pixelBoxUpperCorner` array specifies the coordinate offsets {D, H, W} of the bounding box from bottom/right/back corner. The number of offsets and their precision depend on the tensor dimensionality: + * When `tensorRank` is 3, one signed offset within range [-32768, 32767] is supported. + + * When `tensorRank` is 4, two signed offsets each within range [-128, 127] are supported. + + * When `tensorRank` is 5, three offsets each within range [-16, 15] are supported. The bounding box specified by `pixelBoxLowerCorner` and `pixelBoxUpperCorner` must have non-zero area. + + + * `channelsPerPixel`, which specifies the number of elements which must be accessed along C dimension, must be less than or equal to 256. Additionally, when `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, `channelsPerPixel` must be 128. + + + * `pixelsPerColumn`, which specifies the number of elements that must be accessed along the {N, D, H, W} dimensions, must be less than or equal to 1024. + + + * `elementStrides` array, which specifies the iteration step along each of the `tensorRank` dimensions, must be non-zero and less than or equal to 8. Note that when `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of the `elementStrides` array are one, `boxDim` specifies the number of elements to load. However, if `elementStrides`[i] is not equal to one for some `i`, then TMA loads ceil( `boxDim`[i] / `elementStrides`[i]) number of elements along i-th dimension. To load N elements along i-th dimension, `boxDim`[i] must be set to N * `elementStrides`[i]. + + + * `interleave` specifies the interleaved layout of type CUtensorMapInterleave, which is defined as: + + ‎ typedef enum CUtensorMapInterleave_enum { + CU_TENSOR_MAP_INTERLEAVE_NONE = 0 + CU_TENSOR_MAP_INTERLEAVE_16B + CU_TENSOR_MAP_INTERLEAVE_32B + } CUtensorMapInterleave; + +TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE and `swizzle` is not CU_TENSOR_MAP_SWIZZLE_NONE, the bounding box inner dimension (computed as `channelsPerPixel` multiplied by element size in bytes derived from `tensorDataType`) must be less than or equal to the swizzle size. + * CU_TENSOR_MAP_SWIZZLE_32B requires the bounding box inner dimension to be <= 32. + + * CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to be <= 64. + + * CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to be <= 128. Additionally, `tensorDataType` of CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B requires `interleave` to be CU_TENSOR_MAP_INTERLEAVE_NONE. + + + * `swizzle`, which specifies the shared memory bank swizzling pattern, has to be of type CUtensorMapSwizzle which is defined as: + + ‎ typedef enum CUtensorMapSwizzle_enum { + CU_TENSOR_MAP_SWIZZLE_NONE = 0 + CU_TENSOR_MAP_SWIZZLE_32B, // Swizzle 16B chunks within 32B span + CU_TENSOR_MAP_SWIZZLE_64B, // Swizzle 16B chunks within 64B span + CU_TENSOR_MAP_SWIZZLE_128B, // Swizzle 16B chunks within 128B span + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B, // Swizzle 32B chunks within 128B span + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B, // Swizzle 32B chunks within 128B span, additionally swap lower 8B with upper 8B within each 16B for every alternate row + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B // Swizzle 64B chunks within 128B span + } CUtensorMapSwizzle; + +Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, `swizzle` must be CU_TENSOR_MAP_SWIZZLE_32B. Other interleave modes can have any swizzling pattern. When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B, only the following swizzle modes are supported: + * CU_TENSOR_MAP_SWIZZLE_NONE (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B (Store only) When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, only the following swizzle modes are supported: + + * CU_TENSOR_MAP_SWIZZLE_NONE (Load only) + + * CU_TENSOR_MAP_SWIZZLE_128B (Load only) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only) + + + * `l2Promotion` specifies L2 fetch size which indicates the byte granularity at which L2 requests are filled from DRAM. It must be of type CUtensorMapL2promotion, which is defined as: + + ‎ typedef enum CUtensorMapL2promotion_enum { + CU_TENSOR_MAP_L2_PROMOTION_NONE = 0 + CU_TENSOR_MAP_L2_PROMOTION_L2_64B + CU_TENSOR_MAP_L2_PROMOTION_L2_128B + CU_TENSOR_MAP_L2_PROMOTION_L2_256B + } CUtensorMapL2promotion; + + + * `oobFill`, which indicates whether zero or a special NaN constant should be used to fill out-of-bound elements, must be of type CUtensorMapFloatOOBfill which is defined as: + + ‎ typedef enum CUtensorMapFloatOOBfill_enum { + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE = 0 + CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA + } CUtensorMapFloatOOBfill; + +Note that CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA can only be used when `tensorDataType` represents a floating-point data type, and when `tensorDataType` is not CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, and CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B. + + +CUresult cuTensorMapEncodeIm2colWide ( CUtensorMap* tensorMap, CUtensorMapDataType tensorDataType, cuuint32_t tensorRank, void* globalAddress, const cuuint64_t* globalDim, const cuuint64_t* globalStrides, int pixelBoxLowerCornerWidth, int pixelBoxUpperCornerWidth, cuuint32_t channelsPerPixel, cuuint32_t pixelsPerColumn, const cuuint32_t* elementStrides, CUtensorMapInterleave interleave, CUtensorMapIm2ColWideMode mode, CUtensorMapSwizzle swizzle, CUtensorMapL2promotion l2Promotion, CUtensorMapFloatOOBfill oobFill ) + + +Create a tensor map descriptor object representing im2col memory region, but where the elements are exclusively loaded along the W dimension. + +###### Parameters + +`tensorMap` + \- Tensor map object to create +`tensorDataType` + \- Tensor data type +`tensorRank` + \- Dimensionality of tensor; must be at least 3 +`globalAddress` + \- Starting address of memory region described by tensor +`globalDim` + \- Array containing tensor size (number of elements) along each of the `tensorRank` dimensions +`globalStrides` + \- Array containing stride size (in bytes) along each of the `tensorRank` \- 1 dimensions +`pixelBoxLowerCornerWidth` + \- Width offset of left box corner +`pixelBoxUpperCornerWidth` + \- Width offset of right box corner +`channelsPerPixel` + \- Number of channels per pixel +`pixelsPerColumn` + \- Number of pixels per column +`elementStrides` + \- Array containing traversal stride in each of the `tensorRank` dimensions +`interleave` + \- Type of interleaved layout the tensor addresses +`mode` + \- W or W128 mode +`swizzle` + \- Bank swizzling pattern inside shared memory +`l2Promotion` + \- L2 promotion size +`oobFill` + \- Indicate whether zero or special NaN constant will be used to fill out-of-bound elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a im2col memory layout and where the row is always loaded along the W dimensuin and returns it in `tensorMap`. This assumes the tensor layout in memory is either NDHWC, NHWC, or NWC. + +This API is only supported on devices of compute capability 10.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. + +The parameters passed are bound to the following requirements: + + * `tensorMap` address must be aligned to 64 bytes. + + + * `tensorDataType` has to be an enum from CUtensorMapDataType which is defined as: + + ‎ typedef enum CUtensorMapDataType_enum { + CU_TENSOR_MAP_DATA_TYPE_UINT8 = 0, // 1 byte + CU_TENSOR_MAP_DATA_TYPE_UINT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_INT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_INT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B // 6 bits + } CUtensorMapDataType; + +CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B copies '16 x U4' packed values to memory aligned as 8 bytes. There are no gaps between packed values. CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B copies '16 x U4' packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B copies '16 x U6' packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values. + + + * `tensorRank`, which specifies the number of tensor dimensions, must be 3, 4, or 5. + + + * `globalAddress`, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, `globalAddress` must be 32 byte aligned. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, `globalAddress` must be 32 byte aligned. + + + * `globalDim` array, which specifies tensor size of each of the `tensorRank` dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types: + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, globalDim[0] must be a multiple of 128. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, `globalDim`[0] must be a multiple of 2. + + * Dimension for the packed data types must reflect the number of individual U# values. + + + * `globalStrides` array, which specifies tensor stride of each of the lower `tensorRank` \- 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, the strides must be a multiple of 32. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride: + + ‎ globalStrides[0] = globalDim[0] * elementSizeInBytes(tensorDataType) + padding[0]; + for (i = 1; i < tensorRank - 1; i++) + globalStrides[i] = globalStrides[i – 1] * (globalDim[i] + padding[i]); + assert(globalStrides[i] >= globalDim[i]); + + + * `pixelBoxLowerCornerWidth` specifies the coordinate offset W of the bounding box from left corner. The offset must be within range [-32768, 32767]. + + + * `pixelBoxUpperCornerWidth` specifies the coordinate offset W of the bounding box from right corner. The offset must be within range [-32768, 32767]. + + +The bounding box specified by `pixelBoxLowerCornerWidth` and `pixelBoxUpperCornerWidth` must have non-zero area. Note that the size of the box along D and H dimensions is always equal to one. + + * `channelsPerPixel`, which specifies the number of elements which must be accessed along C dimension, must be less than or equal to 256. Additionally, when `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, `channelsPerPixel` must be 128. + + + * `pixelsPerColumn`, which specifies the number of elements that must be accessed along the W dimension, must be less than or equal to 1024. This field is ignored when `mode` is CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128. + + + * `elementStrides` array, which specifies the iteration step along each of the `tensorRank` dimensions, must be non-zero and less than or equal to 8. Note that when `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of the `elementStrides` array are one, `boxDim` specifies the number of elements to load. However, if `elementStrides`[i] is not equal to one for some `i`, then TMA loads ceil( `boxDim`[i] / `elementStrides`[i]) number of elements along i-th dimension. To load N elements along i-th dimension, `boxDim`[i] must be set to N * `elementStrides`[i]. + + + * `interleave` specifies the interleaved layout of type CUtensorMapInterleave, which is defined as: + + ‎ typedef enum CUtensorMapInterleave_enum { + CU_TENSOR_MAP_INTERLEAVE_NONE = 0 + CU_TENSOR_MAP_INTERLEAVE_16B + CU_TENSOR_MAP_INTERLEAVE_32B + } CUtensorMapInterleave; + +TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE, the bounding box inner dimension (computed as `channelsPerPixel` multiplied by element size in bytes derived from `tensorDataType`) must be less than or equal to the swizzle size. + * CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to be <= 64. + + * CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to be <= 128. Additionally, `tensorDataType` of CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B requires `interleave` to be CU_TENSOR_MAP_INTERLEAVE_NONE. + + + * `mode`, which describes loading of elements loaded along the W dimension, has to be one of the following CUtensorMapIm2ColWideMode types: + + ‎ CU_TENSOR_MAP_IM2COL_WIDE_MODE_W + CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128 + +CU_TENSOR_MAP_IM2COL_WIDE_MODE_W allows the number of elements loaded along the W dimension to be specified via the `pixelsPerColumn` field. + + + * `swizzle`, which specifies the shared memory bank swizzling pattern, must be one of the following CUtensorMapSwizzle modes (other swizzle modes are not supported): + + ‎ typedef enum CUtensorMapSwizzle_enum { + CU_TENSOR_MAP_SWIZZLE_64B, // Swizzle 16B chunks within 64B span + CU_TENSOR_MAP_SWIZZLE_128B, // Swizzle 16B chunks within 128B span + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B, // Swizzle 32B chunks within 128B span + } CUtensorMapSwizzle; + +Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B, only the following swizzle modes are supported: + * CU_TENSOR_MAP_SWIZZLE_128B (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store) When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, only the following swizzle modes are supported: + + * CU_TENSOR_MAP_SWIZZLE_128B (Load only) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only) + + + * `l2Promotion` specifies L2 fetch size which indicates the byte granularity at which L2 requests are filled from DRAM. It must be of type CUtensorMapL2promotion, which is defined as: + + ‎ typedef enum CUtensorMapL2promotion_enum { + CU_TENSOR_MAP_L2_PROMOTION_NONE = 0 + CU_TENSOR_MAP_L2_PROMOTION_L2_64B + CU_TENSOR_MAP_L2_PROMOTION_L2_128B + CU_TENSOR_MAP_L2_PROMOTION_L2_256B + } CUtensorMapL2promotion; + + + * `oobFill`, which indicates whether zero or a special NaN constant should be used to fill out-of-bound elements, must be of type CUtensorMapFloatOOBfill which is defined as: + + ‎ typedef enum CUtensorMapFloatOOBfill_enum { + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE = 0 + CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA + } CUtensorMapFloatOOBfill; + +Note that CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA can only be used when `tensorDataType` represents a floating-point data type, and when `tensorDataType` is not CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, and CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B. + + +CUresult cuTensorMapEncodeTiled ( CUtensorMap* tensorMap, CUtensorMapDataType tensorDataType, cuuint32_t tensorRank, void* globalAddress, const cuuint64_t* globalDim, const cuuint64_t* globalStrides, const cuuint32_t* boxDim, const cuuint32_t* elementStrides, CUtensorMapInterleave interleave, CUtensorMapSwizzle swizzle, CUtensorMapL2promotion l2Promotion, CUtensorMapFloatOOBfill oobFill ) + + +Create a tensor map descriptor object representing tiled memory region. + +###### Parameters + +`tensorMap` + \- Tensor map object to create +`tensorDataType` + \- Tensor data type +`tensorRank` + \- Dimensionality of tensor +`globalAddress` + \- Starting address of memory region described by tensor +`globalDim` + \- Array containing tensor size (number of elements) along each of the `tensorRank` dimensions +`globalStrides` + \- Array containing stride size (in bytes) along each of the `tensorRank` \- 1 dimensions +`boxDim` + \- Array containing traversal box size (number of elments) along each of the `tensorRank` dimensions. Specifies how many elements to be traversed along each tensor dimension. +`elementStrides` + \- Array containing traversal stride in each of the `tensorRank` dimensions +`interleave` + \- Type of interleaved layout the tensor addresses +`swizzle` + \- Bank swizzling pattern inside shared memory +`l2Promotion` + \- L2 promotion size +`oobFill` + \- Indicate whether zero or special NaN constant must be used to fill out-of-bound elements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a tiled region and returns it in `tensorMap`. + +Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. + +The parameters passed are bound to the following requirements: + + * `tensorMap` address must be aligned to 64 bytes. + + + * `tensorDataType` has to be an enum from CUtensorMapDataType which is defined as: + + ‎ typedef enum CUtensorMapDataType_enum { + CU_TENSOR_MAP_DATA_TYPE_UINT8 = 0, // 1 byte + CU_TENSOR_MAP_DATA_TYPE_UINT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_INT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_UINT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_INT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT64, // 8 bytes + CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, // 2 bytes + CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ, // 4 bytes + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, // 4 bits + CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B // 6 bits + } CUtensorMapDataType; + +CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B copies '16 x U4' packed values to memory aligned as 8 bytes. There are no gaps between packed values. CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B copies '16 x U4' packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B copies '16 x U6' packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values. + + + * `tensorRank` must be non-zero and less than or equal to the maximum supported dimensionality of 5. If `interleave` is not CU_TENSOR_MAP_INTERLEAVE_NONE, then `tensorRank` must additionally be greater than or equal to 3. + + + * `globalAddress`, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, `globalAddress` must be 32 byte aligned. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, `globalAddress` must be 32 byte aligned. + + + * `globalDim` array, which specifies tensor size of each of the `tensorRank` dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types: + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, globalDim[0] must be a multiple of 128. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, `globalDim`[0] must be a multiple of 2. + + * Dimension for the packed data types must reflect the number of individual U# values. + + + * `globalStrides` array, which specifies tensor stride of each of the lower `tensorRank` \- 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, the strides must be a multiple of 32. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride: + + ‎ globalStrides[0] = globalDim[0] * elementSizeInBytes(tensorDataType) + padding[0]; + for (i = 1; i < tensorRank - 1; i++) + globalStrides[i] = globalStrides[i – 1] * (globalDim[i] + padding[i]); + assert(globalStrides[i] >= globalDim[i]); + + + * `boxDim` array, which specifies number of elements to be traversed along each of the `tensorRank` dimensions, must be non-zero and less than or equal to 256. Additionally, the following requirements need to be met: + * When `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE, { `boxDim`[0] * elementSizeInBytes( `tensorDataType` ) } must be a multiple of 16 bytes. + + * When `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B or CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, boxDim[0] must be 128. + + + * `elementStrides` array, which specifies the iteration step along each of the `tensorRank` dimensions, must be non-zero and less than or equal to 8. Note that when `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of `elementStrides` array is one, `boxDim` specifies the number of elements to load. However, if the `elementStrides`[i] is not equal to one, then TMA loads ceil( `boxDim`[i] / `elementStrides`[i]) number of elements along i-th dimension. To load N elements along i-th dimension, `boxDim`[i] must be set to N * `elementStrides`[i]. + + + * `interleave` specifies the interleaved layout of type CUtensorMapInterleave, which is defined as: + + ‎ typedef enum CUtensorMapInterleave_enum { + CU_TENSOR_MAP_INTERLEAVE_NONE = 0 + CU_TENSOR_MAP_INTERLEAVE_16B + CU_TENSOR_MAP_INTERLEAVE_32B + } CUtensorMapInterleave; + +TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When `interleave` is CU_TENSOR_MAP_INTERLEAVE_NONE and `swizzle` is not CU_TENSOR_MAP_SWIZZLE_NONE, the bounding box inner dimension (computed as `boxDim`[0] multiplied by element size derived from `tensorDataType`) must be less than or equal to the swizzle size. + * CU_TENSOR_MAP_SWIZZLE_32B requires the bounding box inner dimension to be <= 32. + + * CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to be <= 64. + + * CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to be <= 128. Additionally, `tensorDataType` of CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B requires `interleave` to be CU_TENSOR_MAP_INTERLEAVE_NONE. + + + * `swizzle`, which specifies the shared memory bank swizzling pattern, has to be of type CUtensorMapSwizzle which is defined as: + + ‎ typedef enum CUtensorMapSwizzle_enum { + CU_TENSOR_MAP_SWIZZLE_NONE = 0 + CU_TENSOR_MAP_SWIZZLE_32B, // Swizzle 16B chunks within 32B span + CU_TENSOR_MAP_SWIZZLE_64B, // Swizzle 16B chunks within 64B span + CU_TENSOR_MAP_SWIZZLE_128B, // Swizzle 16B chunks within 128B span + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B, // Swizzle 32B chunks within 128B span + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B, // Swizzle 32B chunks within 128B span, additionally swap lower 8B with upper 8B within each 16B for every alternate row + CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B // Swizzle 64B chunks within 128B span + } CUtensorMapSwizzle; + +Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When `interleave` is CU_TENSOR_MAP_INTERLEAVE_32B, `swizzle` must be CU_TENSOR_MAP_SWIZZLE_32B. Other interleave modes can have any swizzling pattern. When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B, only the following swizzle modes are supported: + * CU_TENSOR_MAP_SWIZZLE_NONE (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B (Store only) When the `tensorDataType` is CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, only the following swizzle modes are supported: + + * CU_TENSOR_MAP_SWIZZLE_NONE (Load only) + + * CU_TENSOR_MAP_SWIZZLE_128B (Load only) + + * CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only) + + + * `l2Promotion` specifies L2 fetch size which indicates the byte granurality at which L2 requests is filled from DRAM. It must be of type CUtensorMapL2promotion, which is defined as: + + ‎ typedef enum CUtensorMapL2promotion_enum { + CU_TENSOR_MAP_L2_PROMOTION_NONE = 0 + CU_TENSOR_MAP_L2_PROMOTION_L2_64B + CU_TENSOR_MAP_L2_PROMOTION_L2_128B + CU_TENSOR_MAP_L2_PROMOTION_L2_256B + } CUtensorMapL2promotion; + + + * `oobFill`, which indicates whether zero or a special NaN constant should be used to fill out-of-bound elements, must be of type CUtensorMapFloatOOBfill which is defined as: + + ‎ typedef enum CUtensorMapFloatOOBfill_enum { + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE = 0 + CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA + } CUtensorMapFloatOOBfill; + +Note that CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA can only be used when `tensorDataType` represents a floating-point data type, and when `tensorDataType` is not CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B, CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B, and CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B. + + +CUresult cuTensorMapReplaceAddress ( CUtensorMap* tensorMap, void* globalAddress ) + + +Modify an existing tensor map descriptor with an updated global address. + +###### Parameters + +`tensorMap` + \- Tensor map object to modify +`globalAddress` + \- Starting address of memory region described by tensor, must follow previous alignment requirements + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Modifies the descriptor for Tensor Memory Access (TMA) object passed in `tensorMap` with an updated `globalAddress`. + +Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA API calls. diff --git a/content/cuda/docs/driver-texobject/DOC.md b/content/cuda/docs/driver-texobject/DOC.md new file mode 100644 index 00000000..996166d6 --- /dev/null +++ b/content/cuda/docs/driver-texobject/DOC.md @@ -0,0 +1,282 @@ +--- +name: driver-texobject +description: '**Source:** group__CUDA__TEXOBJECT.html#group__CUDA__TEXOBJECT' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.28. Texture Object Management + +**Source:** group__CUDA__TEXOBJECT.html#group__CUDA__TEXOBJECT + + +### Functions + +CUresult cuTexObjectCreate ( CUtexObject* pTexObject, const CUDA_RESOURCE_DESC* pResDesc, const CUDA_TEXTURE_DESC* pTexDesc, const CUDA_RESOURCE_VIEW_DESC* pResViewDesc ) + + +Creates a texture object. + +###### Parameters + +`pTexObject` + \- Texture object to create +`pResDesc` + \- Resource descriptor +`pTexDesc` + \- Texture descriptor +`pResViewDesc` + \- Resource view descriptor + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Creates a texture object and returns it in `pTexObject`. `pResDesc` describes the data to texture from. `pTexDesc` describes how the data should be sampled. `pResViewDesc` is an optional argument that specifies an alternate format for the data described by `pResDesc`, and also describes the subresource region to restrict access to when texturing. `pResViewDesc` can only be specified if the type of resource is a CUDA array or a CUDA mipmapped array not in a block compressed format. + +Texture objects are only supported on devices of compute capability 3.0 or higher. Additionally, a texture object is an opaque value, and, as such, should only be accessed through CUDA API calls. + +The CUDA_RESOURCE_DESC structure is defined as: + + + ‎ typedef struct CUDA_RESOURCE_DESC_st + { + CUresourcetype resType; + + union { + struct { + CUarray hArray; + } array; + struct { + CUmipmappedArray hMipmappedArray; + } mipmap; + struct { + CUdeviceptr devPtr; + CUarray_format format; + unsigned int numChannels; + size_t sizeInBytes; + } linear; + struct { + CUdeviceptr devPtr; + CUarray_format format; + unsigned int numChannels; + size_t width; + size_t height; + size_t pitchInBytes; + } pitch2D; + } res; + + unsigned int flags; + } CUDA_RESOURCE_DESC; + +where: + + * CUDA_RESOURCE_DESC::resType specifies the type of resource to texture from. CUresourceType is defined as: + + ‎ typedef enum CUresourcetype_enum { + CU_RESOURCE_TYPE_ARRAY = 0x00 + CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = 0x01 + CU_RESOURCE_TYPE_LINEAR = 0x02 + CU_RESOURCE_TYPE_PITCH2D = 0x03 + } CUresourcetype; + + +If CUDA_RESOURCE_DESC::resType is set to CU_RESOURCE_TYPE_ARRAY, CUDA_RESOURCE_DESC::res::array::hArray must be set to a valid CUDA array handle. + +If CUDA_RESOURCE_DESC::resType is set to CU_RESOURCE_TYPE_MIPMAPPED_ARRAY, CUDA_RESOURCE_DESC::res::mipmap::hMipmappedArray must be set to a valid CUDA mipmapped array handle. + +If CUDA_RESOURCE_DESC::resType is set to CU_RESOURCE_TYPE_LINEAR, CUDA_RESOURCE_DESC::res::linear::devPtr must be set to a valid device pointer, that is aligned to CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. CUDA_RESOURCE_DESC::res::linear::format and CUDA_RESOURCE_DESC::res::linear::numChannels describe the format of each component and the number of components per array element. CUDA_RESOURCE_DESC::res::linear::sizeInBytes specifies the size of the array in bytes. The total number of elements in the linear address range cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH. The number of elements is computed as (sizeInBytes / (sizeof(format) * numChannels)). + +If CUDA_RESOURCE_DESC::resType is set to CU_RESOURCE_TYPE_PITCH2D, CUDA_RESOURCE_DESC::res::pitch2D::devPtr must be set to a valid device pointer, that is aligned to CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. CUDA_RESOURCE_DESC::res::pitch2D::format and CUDA_RESOURCE_DESC::res::pitch2D::numChannels describe the format of each component and the number of components per array element. CUDA_RESOURCE_DESC::res::pitch2D::width and CUDA_RESOURCE_DESC::res::pitch2D::height specify the width and height of the array in elements, and cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH and CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT respectively. CUDA_RESOURCE_DESC::res::pitch2D::pitchInBytes specifies the pitch between two rows in bytes and has to be aligned to CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT. Pitch cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH. + + * flags must be set to zero. + + +The CUDA_TEXTURE_DESC struct is defined as + + + ‎ typedef struct CUDA_TEXTURE_DESC_st { + CUaddress_mode addressMode[3]; + CUfilter_mode filterMode; + unsigned int flags; + unsigned int maxAnisotropy; + CUfilter_mode mipmapFilterMode; + float mipmapLevelBias; + float minMipmapLevelClamp; + float maxMipmapLevelClamp; + } CUDA_TEXTURE_DESC; + +where + + * CUDA_TEXTURE_DESC::addressMode specifies the addressing mode for each dimension of the texture data. CUaddress_mode is defined as: + + ‎ typedef enum CUaddress_mode_enum { + CU_TR_ADDRESS_MODE_WRAP = 0 + CU_TR_ADDRESS_MODE_CLAMP = 1 + CU_TR_ADDRESS_MODE_MIRROR = 2 + CU_TR_ADDRESS_MODE_BORDER = 3 + } CUaddress_mode; + +This is ignored if CUDA_RESOURCE_DESC::resType is CU_RESOURCE_TYPE_LINEAR. Also, if the flag, CU_TRSF_NORMALIZED_COORDINATES is not set, the only supported address mode is CU_TR_ADDRESS_MODE_CLAMP. + + + * CUDA_TEXTURE_DESC::filterMode specifies the filtering mode to be used when fetching from the texture. CUfilter_mode is defined as: + + ‎ typedef enum CUfilter_mode_enum { + CU_TR_FILTER_MODE_POINT = 0 + CU_TR_FILTER_MODE_LINEAR = 1 + } CUfilter_mode; + +This is ignored if CUDA_RESOURCE_DESC::resType is CU_RESOURCE_TYPE_LINEAR. + + + * CUDA_TEXTURE_DESC::flags can be any combination of the following: + * CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of having the texture promote integer data to floating point data in the range [0, 1]. Note that texture with 32-bit integer format would not be promoted, regardless of whether or not this flag is specified. + + * CU_TRSF_NORMALIZED_COORDINATES, which suppresses the default behavior of having the texture coordinates range from 0, Dim) where Dim is the width or height of the CUDA array. Instead, the texture coordinates [0, 1.0) reference the entire breadth of the array dimension; Note that for CUDA mipmapped arrays, this flag has to be set. + + * [CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear filtering optimizations. Trilinear optimizations improve texture filtering performance by allowing bilinear filtering on textures in scenarios where it can closely approximate the expected results. + + * CU_TRSF_SEAMLESS_CUBEMAP, which enables seamless cube map filtering. This flag can only be specified if the underlying resource is a CUDA array or a CUDA mipmapped array that was created with the flag CUDA_ARRAY3D_CUBEMAP. When seamless cube map filtering is enabled, texture address modes specified by CUDA_TEXTURE_DESC::addressMode are ignored. Instead, if the CUDA_TEXTURE_DESC::filterMode is set to CU_TR_FILTER_MODE_POINT the address mode CU_TR_ADDRESS_MODE_CLAMP will be applied for all dimensions. If the CUDA_TEXTURE_DESC::filterMode is set to CU_TR_FILTER_MODE_LINEAR seamless cube map filtering will be performed when sampling along the cube face borders. + + + * CUDA_TEXTURE_DESC::maxAnisotropy specifies the maximum anisotropy ratio to be used when doing anisotropic filtering. This value will be clamped to the range [1,16]. + + + * CUDA_TEXTURE_DESC::mipmapFilterMode specifies the filter mode when the calculated mipmap level lies between two defined mipmap levels. + + + * CUDA_TEXTURE_DESC::mipmapLevelBias specifies the offset to be applied to the calculated mipmap level. + + + * CUDA_TEXTURE_DESC::minMipmapLevelClamp specifies the lower end of the mipmap level range to clamp access to. + + + * CUDA_TEXTURE_DESC::maxMipmapLevelClamp specifies the upper end of the mipmap level range to clamp access to. + + +The CUDA_RESOURCE_VIEW_DESC struct is defined as + + + ‎ typedef struct CUDA_RESOURCE_VIEW_DESC_st + { + CUresourceViewFormat format; + size_t width; + size_t height; + size_t depth; + unsigned int firstMipmapLevel; + unsigned int lastMipmapLevel; + unsigned int firstLayer; + unsigned int lastLayer; + } CUDA_RESOURCE_VIEW_DESC; + +where: + + * CUDA_RESOURCE_VIEW_DESC::format specifies how the data contained in the CUDA array or CUDA mipmapped array should be interpreted. Note that this can incur a change in size of the texture data. If the resource view format is a block compressed format, then the underlying CUDA array or CUDA mipmapped array has to have a base of format CU_AD_FORMAT_UNSIGNED_INT32. with 2 or 4 channels, depending on the block compressed format. For ex., BC1 and BC4 require the underlying CUDA array to have a format of CU_AD_FORMAT_UNSIGNED_INT32 with 2 channels. The other BC formats require the underlying resource to have the same base format but with 4 channels. + + + * CUDA_RESOURCE_VIEW_DESC::width specifies the new width of the texture data. If the resource view format is a block compressed format, this value has to be 4 times the original width of the resource. For non block compressed formats, this value has to be equal to that of the original resource. + + + * CUDA_RESOURCE_VIEW_DESC::height specifies the new height of the texture data. If the resource view format is a block compressed format, this value has to be 4 times the original height of the resource. For non block compressed formats, this value has to be equal to that of the original resource. + + + * CUDA_RESOURCE_VIEW_DESC::depth specifies the new depth of the texture data. This value has to be equal to that of the original resource. + + + * CUDA_RESOURCE_VIEW_DESC::firstMipmapLevel specifies the most detailed mipmap level. This will be the new mipmap level zero. For non-mipmapped resources, this value has to be zero.CUDA_TEXTURE_DESC::minMipmapLevelClamp and CUDA_TEXTURE_DESC::maxMipmapLevelClamp will be relative to this value. For ex., if the firstMipmapLevel is set to 2, and a minMipmapLevelClamp of 1.2 is specified, then the actual minimum mipmap level clamp will be 3.2. + + + * CUDA_RESOURCE_VIEW_DESC::lastMipmapLevel specifies the least detailed mipmap level. For non-mipmapped resources, this value has to be zero. + + + * CUDA_RESOURCE_VIEW_DESC::firstLayer specifies the first layer index for layered textures. This will be the new layer zero. For non-layered resources, this value has to be zero. + + + * CUDA_RESOURCE_VIEW_DESC::lastLayer specifies the last layer index for layered textures. For non-layered resources, this value has to be zero. + + +CUresult cuTexObjectDestroy ( CUtexObject texObject ) + + +Destroys a texture object. + +###### Parameters + +`texObject` + \- Texture object to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Destroys the texture object specified by `texObject`. + +CUresult cuTexObjectGetResourceDesc ( CUDA_RESOURCE_DESC* pResDesc, CUtexObject texObject ) + + +Returns a texture object's resource descriptor. + +###### Parameters + +`pResDesc` + \- Resource descriptor +`texObject` + \- Texture object + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the resource descriptor for the texture object specified by `texObject`. + +CUresult cuTexObjectGetResourceViewDesc ( CUDA_RESOURCE_VIEW_DESC* pResViewDesc, CUtexObject texObject ) + + +Returns a texture object's resource view descriptor. + +###### Parameters + +`pResViewDesc` + \- Resource view descriptor +`texObject` + \- Texture object + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the resource view descriptor for the texture object specified by `texObject`. If no resource view was set for `texObject`, the CUDA_ERROR_INVALID_VALUE is returned. + +CUresult cuTexObjectGetTextureDesc ( CUDA_TEXTURE_DESC* pTexDesc, CUtexObject texObject ) + + +Returns a texture object's texture descriptor. + +###### Parameters + +`pTexDesc` + \- Texture descriptor +`texObject` + \- Texture object + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns the texture descriptor for the texture object specified by `texObject`. diff --git a/content/cuda/docs/driver-texref--deprecated/DOC.md b/content/cuda/docs/driver-texref--deprecated/DOC.md new file mode 100644 index 00000000..19009994 --- /dev/null +++ b/content/cuda/docs/driver-texref--deprecated/DOC.md @@ -0,0 +1,689 @@ +--- +name: driver-texref--deprecated +description: '**Source:** group__CUDA__TEXREF__DEPRECATED.html#group__CUDA__TEXREF__DEPRECATED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.26. Texture Reference Management [DEPRECATED] + +**Source:** group__CUDA__TEXREF__DEPRECATED.html#group__CUDA__TEXREF__DEPRECATED + + +### Functions + +CUresult cuTexRefCreate ( CUtexref* pTexRef ) + + +Creates a texture reference. + +###### Parameters + +`pTexRef` + \- Returned texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Creates a texture reference and returns its handle in `*pTexRef`. Once created, the application must call cuTexRefSetArray() or cuTexRefSetAddress() to associate the reference with allocated memory. Other texture reference functions are used to specify the format and interpretation (addressing, filtering, etc.) to be used when the memory is read through this texture reference. + +CUresult cuTexRefDestroy ( CUtexref hTexRef ) + + +Destroys a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference to destroy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Destroys the texture reference specified by `hTexRef`. + +CUresult cuTexRefGetAddress ( CUdeviceptr* pdptr, CUtexref hTexRef ) + + +Gets the address associated with a texture reference. + +###### Parameters + +`pdptr` + \- Returned device address +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*pdptr` the base address bound to the texture reference `hTexRef`, or returns CUDA_ERROR_INVALID_VALUE if the texture reference is not bound to any device memory range. + +CUresult cuTexRefGetAddressMode ( CUaddress_mode* pam, CUtexref hTexRef, int dim ) + + +Gets the addressing mode used by a texture reference. + +###### Parameters + +`pam` + \- Returned addressing mode +`hTexRef` + \- Texture reference +`dim` + \- Dimension + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*pam` the addressing mode corresponding to the dimension `dim` of the texture reference `hTexRef`. Currently, the only valid value for `dim` are 0 and 1. + +CUresult cuTexRefGetArray ( CUarray* phArray, CUtexref hTexRef ) + + +Gets the array bound to a texture reference. + +###### Parameters + +`phArray` + \- Returned array +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*phArray` the CUDA array bound to the texture reference `hTexRef`, or returns CUDA_ERROR_INVALID_VALUE if the texture reference is not bound to any CUDA array. + +CUresult cuTexRefGetBorderColor ( float* pBorderColor, CUtexref hTexRef ) + + +Gets the border color used by a texture reference. + +###### Parameters + +`pBorderColor` + \- Returned Type and Value of RGBA color +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `pBorderColor`, values of the RGBA color used by the texture reference `hTexRef`. The color value is of type float and holds color components in the following sequence: pBorderColor[0] holds 'R' component pBorderColor[1] holds 'G' component pBorderColor[2] holds 'B' component pBorderColor[3] holds 'A' component + +CUresult cuTexRefGetFilterMode ( CUfilter_mode* pfm, CUtexref hTexRef ) + + +Gets the filter-mode used by a texture reference. + +###### Parameters + +`pfm` + \- Returned filtering mode +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*pfm` the filtering mode of the texture reference `hTexRef`. + +CUresult cuTexRefGetFlags ( unsigned int* pFlags, CUtexref hTexRef ) + + +Gets the flags used by a texture reference. + +###### Parameters + +`pFlags` + \- Returned flags +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*pFlags` the flags of the texture reference `hTexRef`. + +CUresult cuTexRefGetFormat ( CUarray_format* pFormat, int* pNumChannels, CUtexref hTexRef ) + + +Gets the format used by a texture reference. + +###### Parameters + +`pFormat` + \- Returned format +`pNumChannels` + \- Returned number of components +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*pFormat` and `*pNumChannels` the format and number of components of the CUDA array bound to the texture reference `hTexRef`. If `pFormat` or `pNumChannels` is NULL, it will be ignored. + +CUresult cuTexRefGetMaxAnisotropy ( int* pmaxAniso, CUtexref hTexRef ) + + +Gets the maximum anisotropy for a texture reference. + +###### Parameters + +`pmaxAniso` + \- Returned maximum anisotropy +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns the maximum anisotropy in `pmaxAniso` that's used when reading memory through the texture reference `hTexRef`. + +CUresult cuTexRefGetMipmapFilterMode ( CUfilter_mode* pfm, CUtexref hTexRef ) + + +Gets the mipmap filtering mode for a texture reference. + +###### Parameters + +`pfm` + \- Returned mipmap filtering mode +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns the mipmap filtering mode in `pfm` that's used when reading memory through the texture reference `hTexRef`. + +CUresult cuTexRefGetMipmapLevelBias ( float* pbias, CUtexref hTexRef ) + + +Gets the mipmap level bias for a texture reference. + +###### Parameters + +`pbias` + \- Returned mipmap level bias +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns the mipmap level bias in `pBias` that's added to the specified mipmap level when reading memory through the texture reference `hTexRef`. + +CUresult cuTexRefGetMipmapLevelClamp ( float* pminMipmapLevelClamp, float* pmaxMipmapLevelClamp, CUtexref hTexRef ) + + +Gets the min/max mipmap level clamps for a texture reference. + +###### Parameters + +`pminMipmapLevelClamp` + \- Returned mipmap min level clamp +`pmaxMipmapLevelClamp` + \- Returned mipmap max level clamp +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns the min/max mipmap level clamps in `pminMipmapLevelClamp` and `pmaxMipmapLevelClamp` that's used when reading memory through the texture reference `hTexRef`. + +CUresult cuTexRefGetMipmappedArray ( CUmipmappedArray* phMipmappedArray, CUtexref hTexRef ) + + +Gets the mipmapped array bound to a texture reference. + +###### Parameters + +`phMipmappedArray` + \- Returned mipmapped array +`hTexRef` + \- Texture reference + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Returns in `*phMipmappedArray` the CUDA mipmapped array bound to the texture reference `hTexRef`, or returns CUDA_ERROR_INVALID_VALUE if the texture reference is not bound to any CUDA mipmapped array. + +CUresult cuTexRefSetAddress ( size_t* ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, size_t bytes ) + + +Binds an address as a texture reference. + +###### Parameters + +`ByteOffset` + \- Returned byte offset +`hTexRef` + \- Texture reference to bind +`dptr` + \- Device pointer to bind +`bytes` + \- Size of memory to bind in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Binds a linear address range to the texture reference `hTexRef`. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Any memory previously bound to `hTexRef` is unbound. + +Since the hardware enforces an alignment requirement on texture base addresses, cuTexRefSetAddress() passes back a byte offset in `*ByteOffset` that must be applied to texture fetches in order to read from the desired memory. This offset must be divided by the texel size and passed to kernels that read from the texture so they can be applied to the tex1Dfetch() function. + +If the device memory pointer was returned from cuMemAlloc(), the offset is guaranteed to be 0 and NULL may be passed as the `ByteOffset` parameter. + +The total number of elements (or texels) in the linear address range cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH. The number of elements is computed as (`bytes` / bytesPerElement), where bytesPerElement is determined from the data format and number of components set using cuTexRefSetFormat(). + +CUresult cuTexRefSetAddress2D ( CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR* desc, CUdeviceptr dptr, size_t Pitch ) + + +Binds an address as a 2D texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference to bind +`desc` + \- Descriptor of CUDA array +`dptr` + \- Device pointer to bind +`Pitch` + \- Line pitch in bytes + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Binds a linear address range to the texture reference `hTexRef`. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Any memory previously bound to `hTexRef` is unbound. + +Using a tex2D() function inside a kernel requires a call to either cuTexRefSetArray() to bind the corresponding texture reference to an array, or cuTexRefSetAddress2D() to bind the texture reference to linear memory. + +Function calls to cuTexRefSetFormat() cannot follow calls to cuTexRefSetAddress2D() for the same texture reference. + +It is required that `dptr` be aligned to the appropriate hardware-specific texture alignment. You can query this value using the device attribute CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. If an unaligned `dptr` is supplied, CUDA_ERROR_INVALID_VALUE is returned. + +`Pitch` has to be aligned to the hardware-specific texture pitch alignment. This value can be queried using the device attribute CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT. If an unaligned `Pitch` is supplied, CUDA_ERROR_INVALID_VALUE is returned. + +Width and Height, which are specified in elements (or texels), cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH and CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT respectively. `Pitch`, which is specified in bytes, cannot exceed CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH. + +CUresult cuTexRefSetAddressMode ( CUtexref hTexRef, int dim, CUaddress_mode am ) + + +Sets the addressing mode for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`dim` + \- Dimension +`am` + \- Addressing mode to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the addressing mode `am` for the given dimension `dim` of the texture reference `hTexRef`. If `dim` is zero, the addressing mode is applied to the first parameter of the functions used to fetch from the texture; if `dim` is 1, the second, and so on. CUaddress_mode is defined as: + + + ‎ typedef enum CUaddress_mode_enum { + CU_TR_ADDRESS_MODE_WRAP = 0 + CU_TR_ADDRESS_MODE_CLAMP = 1 + CU_TR_ADDRESS_MODE_MIRROR = 2 + CU_TR_ADDRESS_MODE_BORDER = 3 + } CUaddress_mode; + +Note that this call has no effect if `hTexRef` is bound to linear memory. Also, if the flag, CU_TRSF_NORMALIZED_COORDINATES, is not set, the only supported address mode is CU_TR_ADDRESS_MODE_CLAMP. + +CUresult cuTexRefSetArray ( CUtexref hTexRef, CUarray hArray, unsigned int Flags ) + + +Binds an array as a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference to bind +`hArray` + \- Array to bind +`Flags` + \- Options (must be CU_TRSA_OVERRIDE_FORMAT) + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Binds the CUDA array `hArray` to the texture reference `hTexRef`. Any previous address or CUDA array state associated with the texture reference is superseded by this function. `Flags` must be set to CU_TRSA_OVERRIDE_FORMAT. Any CUDA array previously bound to `hTexRef` is unbound. + +CUresult cuTexRefSetBorderColor ( CUtexref hTexRef, float* pBorderColor ) + + +Sets the border color for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`pBorderColor` + \- RGBA color + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the value of the RGBA color via the `pBorderColor` to the texture reference `hTexRef`. The color value supports only float type and holds color components in the following sequence: pBorderColor[0] holds 'R' component pBorderColor[1] holds 'G' component pBorderColor[2] holds 'B' component pBorderColor[3] holds 'A' component + +Note that the color values can be set only when the Address mode is set to CU_TR_ADDRESS_MODE_BORDER using cuTexRefSetAddressMode. Applications using integer border color values have to "reinterpret_cast" their values to float. + +CUresult cuTexRefSetFilterMode ( CUtexref hTexRef, CUfilter_mode fm ) + + +Sets the filtering mode for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`fm` + \- Filtering mode to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the filtering mode `fm` to be used when reading memory through the texture reference `hTexRef`. CUfilter_mode_enum is defined as: + + + ‎ typedef enum CUfilter_mode_enum { + CU_TR_FILTER_MODE_POINT = 0 + CU_TR_FILTER_MODE_LINEAR = 1 + } CUfilter_mode; + +Note that this call has no effect if `hTexRef` is bound to linear memory. + +CUresult cuTexRefSetFlags ( CUtexref hTexRef, unsigned int Flags ) + + +Sets the flags for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`Flags` + \- Optional flags to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies optional flags via `Flags` to specify the behavior of data returned through the texture reference `hTexRef`. The valid flags are: + + * CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of having the texture promote integer data to floating point data in the range [0, 1]. Note that texture with 32-bit integer format would not be promoted, regardless of whether or not this flag is specified; + + * CU_TRSF_NORMALIZED_COORDINATES, which suppresses the default behavior of having the texture coordinates range from 0, Dim) where Dim is the width or height of the CUDA array. Instead, the texture coordinates [0, 1.0) reference the entire breadth of the array dimension; + + * [CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear filtering optimizations. Trilinear optimizations improve texture filtering performance by allowing bilinear filtering on textures in scenarios where it can closely approximate the expected results. + + +CUresult cuTexRefSetFormat ( CUtexref hTexRef, CUarray_format fmt, int NumPackedComponents ) + + +Sets the format for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`fmt` + \- Format to set +`NumPackedComponents` + \- Number of components per array element + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the format of the data to be read by the texture reference `hTexRef`. `fmt` and `NumPackedComponents` are exactly analogous to the Format and NumChannels members of the CUDA_ARRAY_DESCRIPTOR structure: They specify the format of each component and the number of components per array element. + +CUresult cuTexRefSetMaxAnisotropy ( CUtexref hTexRef, unsigned int maxAniso ) + + +Sets the maximum anisotropy for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`maxAniso` + \- Maximum anisotropy + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the maximum anisotropy `maxAniso` to be used when reading memory through the texture reference `hTexRef`. + +Note that this call has no effect if `hTexRef` is bound to linear memory. + +CUresult cuTexRefSetMipmapFilterMode ( CUtexref hTexRef, CUfilter_mode fm ) + + +Sets the mipmap filtering mode for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`fm` + \- Filtering mode to set + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the mipmap filtering mode `fm` to be used when reading memory through the texture reference `hTexRef`. CUfilter_mode_enum is defined as: + + + ‎ typedef enum CUfilter_mode_enum { + CU_TR_FILTER_MODE_POINT = 0 + CU_TR_FILTER_MODE_LINEAR = 1 + } CUfilter_mode; + +Note that this call has no effect if `hTexRef` is not bound to a mipmapped array. + +CUresult cuTexRefSetMipmapLevelBias ( CUtexref hTexRef, float bias ) + + +Sets the mipmap level bias for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`bias` + \- Mipmap level bias + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the mipmap level bias `bias` to be added to the specified mipmap level when reading memory through the texture reference `hTexRef`. + +Note that this call has no effect if `hTexRef` is not bound to a mipmapped array. + +CUresult cuTexRefSetMipmapLevelClamp ( CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp ) + + +Sets the mipmap min/max mipmap level clamps for a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference +`minMipmapLevelClamp` + \- Mipmap min level clamp +`maxMipmapLevelClamp` + \- Mipmap max level clamp + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Specifies the min/max mipmap level clamps, `minMipmapLevelClamp` and `maxMipmapLevelClamp` respectively, to be used when reading memory through the texture reference `hTexRef`. + +Note that this call has no effect if `hTexRef` is not bound to a mipmapped array. + +CUresult cuTexRefSetMipmappedArray ( CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned int Flags ) + + +Binds a mipmapped array to a texture reference. + +###### Parameters + +`hTexRef` + \- Texture reference to bind +`hMipmappedArray` + \- Mipmapped array to bind +`Flags` + \- Options (must be CU_TRSA_OVERRIDE_FORMAT) + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Deprecated + +###### Description + +Binds the CUDA mipmapped array `hMipmappedArray` to the texture reference `hTexRef`. Any previous address or CUDA array state associated with the texture reference is superseded by this function. `Flags` must be set to CU_TRSA_OVERRIDE_FORMAT. Any CUDA array previously bound to `hTexRef` is unbound. diff --git a/content/cuda/docs/driver-types/DOC.md b/content/cuda/docs/driver-types/DOC.md new file mode 100644 index 00000000..a04d4836 --- /dev/null +++ b/content/cuda/docs/driver-types/DOC.md @@ -0,0 +1,514 @@ +--- +name: driver-types +description: '**Source:** group__CUDA__TYPES.html' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# Next > + +**Source:** group__CUDA__TYPES.html + + +### Classes + +struct + +CUDA_ARRAY3D_DESCRIPTOR_v2 + + +struct + +CUDA_ARRAY_DESCRIPTOR_v2 + + +struct + +CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 + + +struct + +CUDA_ARRAY_SPARSE_PROPERTIES_v1 + + +struct + +CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 + + +struct + +CUDA_BATCH_MEM_OP_NODE_PARAMS_v2 + + +struct + +CUDA_CHILD_GRAPH_NODE_PARAMS + + +struct + +CUDA_CONDITIONAL_NODE_PARAMS + + +struct + +CUDA_EVENT_RECORD_NODE_PARAMS + + +struct + +CUDA_EVENT_WAIT_NODE_PARAMS + + +struct + +CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 + + +struct + +CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 + + +struct + +CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 + + +struct + +CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 + + +struct + +CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 + + +struct + +CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 + + +struct + +CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 + + +struct + +CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 + + +struct + +CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 + + +struct + +CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 + + +struct + +CUDA_GRAPH_INSTANTIATE_PARAMS + + +struct + +CUDA_HOST_NODE_PARAMS_v1 + + +struct + +CUDA_HOST_NODE_PARAMS_v2 + + +struct + +CUDA_KERNEL_NODE_PARAMS_v1 + + +struct + +CUDA_KERNEL_NODE_PARAMS_v2 + + +struct + +CUDA_KERNEL_NODE_PARAMS_v3 + + +struct + +CUDA_LAUNCH_PARAMS_v1 + + +struct + +CUDA_MEMCPY2D_v2 + + +struct + +CUDA_MEMCPY3D_PEER_v1 + + +struct + +CUDA_MEMCPY3D_v2 + + +struct + +CUDA_MEMCPY_NODE_PARAMS + + +struct + +CUDA_MEMSET_NODE_PARAMS_v1 + + +struct + +CUDA_MEMSET_NODE_PARAMS_v2 + + +struct + +CUDA_MEM_ALLOC_NODE_PARAMS_v1 + + +struct + +CUDA_MEM_ALLOC_NODE_PARAMS_v2 + + +struct + +CUDA_MEM_FREE_NODE_PARAMS + + +struct + +CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 + + +struct + +CUDA_RESOURCE_DESC_v1 + + +struct + +CUDA_RESOURCE_VIEW_DESC_v1 + + +struct + +CUDA_TEXTURE_DESC_v1 + + +struct + +CUaccessPolicyWindow_v1 + + +struct + +CUarrayMapInfo_v1 + + +struct + +CUasyncNotificationInfo + + +struct + +CUcheckpointCheckpointArgs + + +struct + +CUcheckpointGpuPair + + +struct + +CUcheckpointLockArgs + + +struct + +CUcheckpointRestoreArgs + + +struct + +CUcheckpointUnlockArgs + + +struct + +CUctxCigParam + + +struct + +CUctxCreateParams + + +struct + +CUdevprop_v1 + + +struct + +CUeglFrame_v1 + + +struct + +CUexecAffinityParam_v1 + + +struct + +CUexecAffinitySmCount_v1 + + +struct + +CUextent3D_v1 + + +struct + +CUgraphEdgeData + + +struct + +CUgraphExecUpdateResultInfo_v1 + + +struct + +CUgraphNodeParams + + +struct + +CUipcEventHandle_v1 + + +struct + +CUipcMemHandle_v1 + + +struct + +CUlaunchAttribute + + +union + +CUlaunchAttributeValue + + +struct + +CUlaunchConfig + + +struct + +CUlaunchMemSyncDomainMap + + +struct + +CUmemAccessDesc_v1 + + +struct + +CUmemAllocationProp_v1 + + +struct + +CUmemFabricHandle_v1 + + +struct + +CUmemLocation_v1 + + +struct + +CUmemPoolProps_v1 + + +struct + +CUmemPoolPtrExportData_v1 + + +struct + +CUmemcpy3DOperand_v1 + + +struct + +CUmemcpyAttributes_v1 + + +struct + +CUmulticastObjectProp_v1 + + +struct + +CUoffset3D_v1 + + +union + +CUstreamBatchMemOpParams_v1 + + +struct + +CUtensorMap + + + +### Defines + +#define CUDA_ARRAY3D_2DARRAY 0x01 + +#define CUDA_ARRAY3D_COLOR_ATTACHMENT 0x20 + +#define CUDA_ARRAY3D_CUBEMAP 0x04 + +#define CUDA_ARRAY3D_DEFERRED_MAPPING 0x80 + +#define CUDA_ARRAY3D_DEPTH_TEXTURE 0x10 + +#define CUDA_ARRAY3D_LAYERED 0x01 + +#define CUDA_ARRAY3D_SPARSE 0x40 + +#define CUDA_ARRAY3D_SURFACE_LDST 0x02 + +#define CUDA_ARRAY3D_TEXTURE_GATHER 0x08 + +#define CUDA_ARRAY3D_VIDEO_ENCODE_DECODE 0x100 + +#define CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC 0x02 + +#define CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC 0x01 + +#define CUDA_EGL_INFINITE_TIMEOUT 0xFFFFFFFF + +#define CUDA_EXTERNAL_MEMORY_DEDICATED 0x1 + +#define CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC 0x01 + +#define CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC 0x02 + +#define CUDA_NVSCISYNC_ATTR_SIGNAL 0x1 + +#define CUDA_NVSCISYNC_ATTR_WAIT 0x2 + +#define CUDA_VERSION 13010 + +#define CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL 0x1 + +#define CU_DEVICE_CPU ((CUdevice)-1) + +#define CU_DEVICE_INVALID ((CUdevice)-2) + +#define CU_GRAPH_COND_ASSIGN_DEFAULT 0x1 + +#define CU_GRAPH_KERNEL_NODE_PORT_DEFAULT 0 + +#define CU_GRAPH_KERNEL_NODE_PORT_LAUNCH_ORDER 2 + +#define CU_GRAPH_KERNEL_NODE_PORT_PROGRAMMATIC 1 + +#define CU_IPC_HANDLE_SIZE 64 + +#define CU_LAUNCH_KERNEL_REQUIRED_BLOCK_DIM 1 + +#define CU_LAUNCH_PARAM_BUFFER_POINTER + +#define CU_LAUNCH_PARAM_BUFFER_POINTER_AS_INT 0x01 + +#define CU_LAUNCH_PARAM_BUFFER_SIZE + +#define CU_LAUNCH_PARAM_BUFFER_SIZE_AS_INT 0x02 + +#define CU_LAUNCH_PARAM_END + +#define CU_LAUNCH_PARAM_END_AS_INT 0x00 + +#define CU_MEMHOSTALLOC_DEVICEMAP 0x02 + +#define CU_MEMHOSTALLOC_PORTABLE 0x01 + +#define CU_MEMHOSTALLOC_WRITECOMBINED 0x04 + +#define CU_MEMHOSTREGISTER_DEVICEMAP 0x02 + +#define CU_MEMHOSTREGISTER_IOMEMORY 0x04 + +#define CU_MEMHOSTREGISTER_PORTABLE 0x01 + +#define CU_MEMHOSTREGISTER_READ_ONLY 0x08 + +#define CU_MEM_CREATE_USAGE_HW_DECOMPRESS 0x2 + +#define CU_MEM_CREATE_USAGE_TILE_POOL 0x1 + +#define CU_MEM_POOL_CREATE_USAGE_HW_DECOMPRESS 0x2 + +#define CU_PARAM_TR_DEFAULT -1 + +#define CU_STREAM_LEGACY ((CUstream)0x1) + +#define CU_STREAM_PER_THREAD ((CUstream)0x2) + +#define CU_TENSOR_MAP_NUM_QWORDS 16 + +#define CU_TRSA_OVERRIDE_FORMAT 0x01 + +#define CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION 0x20 + +#define CU_TRSF_NORMALIZED_COORDINATES 0x02 + +#define CU_TRSF_READ_AS_INTEGER 0x01 + +#define CU_TRSF_SEAMLESS_CUBEMAP 0x40 + +#define CU_TRSF_SRGB 0x10 + +#define MAX_PLANES 3 + + +### Typedefs diff --git a/content/cuda/docs/driver-unified/DOC.md b/content/cuda/docs/driver-unified/DOC.md new file mode 100644 index 00000000..4f932a7e --- /dev/null +++ b/content/cuda/docs/driver-unified/DOC.md @@ -0,0 +1,532 @@ +--- +name: driver-unified +description: '**Source:** group__CUDA__UNIFIED.html#group__CUDA__UNIFIED' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.17. Unified Addressing + +**Source:** group__CUDA__UNIFIED.html#group__CUDA__UNIFIED + + +### Functions + +CUresult cuMemAdvise ( CUdeviceptr devPtr, size_t count, CUmem_advise advice, CUmemLocation location ) + + +Advise about the usage of a given memory range. + +###### Parameters + +`devPtr` + \- Pointer to memory to set the advice for +`count` + \- Size in bytes of the memory range +`advice` + \- Advice to be applied for the specified memory range +`location` + \- location to apply the advice for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Advise the Unified Memory subsystem about the usage pattern for the memory range starting at `devPtr` with a size of `count` bytes. The start address and end address of the memory range will be rounded down and rounded up respectively to be aligned to CPU page size before the advice is applied. The memory range must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables. The memory range could also refer to system-allocated pageable memory provided it represents a valid, host-accessible region of memory and all additional constraints imposed by `advice` as outlined below are also satisfied. Specifying an invalid system-allocated pageable memory range results in an error being returned. + +The `advice` parameter can take the following values: + + * CU_MEM_ADVISE_SET_READ_MOSTLY: This implies that the data is mostly going to be read from and only occasionally written to. Any read accesses from any processor to this region will create a read-only copy of at least the accessed pages in that processor's memory. Additionally, if cuMemPrefetchAsync is called on this region, it will create a read-only copy of the data on the destination processor. If the target location for cuMemPrefetchAsync is a host NUMA node and a read-only copy already exists on another host NUMA node, that copy will be migrated to the targeted host NUMA node. If any processor writes to this region, all copies of the corresponding page will be invalidated except for the one where the write occurred. If the writing processor is the CPU and the preferred location of the page is a host NUMA node, then the page will also be migrated to that host NUMA node. The `location` argument is ignored for this advice. Note that for a page to be read-duplicated, the accessing processor must either be the CPU or a GPU that has a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Also, if a context is created on a device that does not have the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS set, then read-duplication will not occur until all such contexts are destroyed. If the memory region refers to valid system-allocated pageable memory, then the accessing device must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS for a read-only copy to be created on that device. Note however that if the accessing device also has a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, then setting this advice will not create a read-only copy when that device accesses this memory region. + + + * CU_MEM_ADVISE_UNSET_READ_MOSTLY: Undoes the effect of CU_MEM_ADVISE_SET_READ_MOSTLY and also prevents the Unified Memory driver from attempting heuristic read-duplication on the memory range. Any read-duplicated copies of the data will be collapsed into a single copy. The location for the collapsed copy will be the preferred location if the page has a preferred location and one of the read-duplicated copies was resident at that location. Otherwise, the location chosen is arbitrary. Note: The `location` argument is ignored for this advice. + + + * CU_MEM_ADVISE_SET_PREFERRED_LOCATION: This advice sets the preferred location for the data to be the memory belonging to `location`. When CUmemLocation::type is CU_MEM_LOCATION_TYPE_HOST, CUmemLocation::id is ignored and the preferred location is set to be host memory. To set the preferred location to a specific host NUMA node, applications must set CUmemLocation::type to CU_MEM_LOCATION_TYPE_HOST_NUMA and CUmemLocation::id must specify the NUMA ID of the host NUMA node. If CUmemLocation::type is set to CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT, CUmemLocation::id will be ignored and the the host NUMA node closest to the calling thread's CPU will be used as the preferred location. If CUmemLocation::type is a CU_MEM_LOCATION_TYPE_DEVICE, then CUmemLocation::id must be a valid device ordinal and the device must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Setting the preferred location does not cause data to migrate to that location immediately. Instead, it guides the migration policy when a fault occurs on that memory region. If the data is already in its preferred location and the faulting processor can establish a mapping without requiring the data to be migrated, then data migration will be avoided. On the other hand, if the data is not in its preferred location or if a direct mapping cannot be established, then it will be migrated to the processor accessing it. It is important to note that setting the preferred location does not prevent data prefetching done using cuMemPrefetchAsync. Having a preferred location can override the page thrash detection and resolution logic in the Unified Memory driver. Normally, if a page is detected to be constantly thrashing between for example host and device memory, the page may eventually be pinned to host memory by the Unified Memory driver. But if the preferred location is set as device memory, then the page will continue to thrash indefinitely. If CU_MEM_ADVISE_SET_READ_MOSTLY is also set on this memory region or any subset of it, then the policies associated with that advice will override the policies of this advice, unless read accesses from `location` will not result in a read-only copy being created on that procesor as outlined in description for the advice CU_MEM_ADVISE_SET_READ_MOSTLY. If the memory region refers to valid system-allocated pageable memory, and CUmemLocation::type is CU_MEM_LOCATION_TYPE_DEVICE then CUmemLocation::id must be a valid device that has a non-zero alue for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. + + + * CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION: Undoes the effect of CU_MEM_ADVISE_SET_PREFERRED_LOCATION and changes the preferred location to none. The `location` argument is ignored for this advice. + + + * CU_MEM_ADVISE_SET_ACCESSED_BY: This advice implies that the data will be accessed by processor `location`. The CUmemLocation::type must be either CU_MEM_LOCATION_TYPE_DEVICE with CUmemLocation::id representing a valid device ordinal or CU_MEM_LOCATION_TYPE_HOST and CUmemLocation::id will be ignored. All other location types are invalid. If CUmemLocation::id is a GPU, then the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS must be non-zero. This advice does not cause data migration and has no impact on the location of the data per se. Instead, it causes the data to always be mapped in the specified processor's page tables, as long as the location of the data permits a mapping to be established. If the data gets migrated for any reason, the mappings are updated accordingly. This advice is recommended in scenarios where data locality is not important, but avoiding faults is. Consider for example a system containing multiple GPUs with peer-to-peer access enabled, where the data located on one GPU is occasionally accessed by peer GPUs. In such scenarios, migrating data over to the other GPUs is not as important because the accesses are infrequent and the overhead of migration may be too high. But preventing faults can still help improve performance, and so having a mapping set up in advance is useful. Note that on CPU access of this data, the data may be migrated to host memory because the CPU typically cannot access device memory directly. Any GPU that had the CU_MEM_ADVISE_SET_ACCESSED_BY flag set for this data will now have its mapping updated to point to the page in host memory. If CU_MEM_ADVISE_SET_READ_MOSTLY is also set on this memory region or any subset of it, then the policies associated with that advice will override the policies of this advice. Additionally, if the preferred location of this memory region or any subset of it is also `location`, then the policies associated with CU_MEM_ADVISE_SET_PREFERRED_LOCATION will override the policies of this advice. If the memory region refers to valid system-allocated pageable memory, and CUmemLocation::type is CU_MEM_LOCATION_TYPE_DEVICE then device in CUmemLocation::id must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Additionally, if CUmemLocation::id has a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, then this call has no effect. + + + * CU_MEM_ADVISE_UNSET_ACCESSED_BY: Undoes the effect of CU_MEM_ADVISE_SET_ACCESSED_BY. Any mappings to the data from `location` may be removed at any time causing accesses to result in non-fatal page faults. If the memory region refers to valid system-allocated pageable memory, and CUmemLocation::type is CU_MEM_LOCATION_TYPE_DEVICE then device in CUmemLocation::id must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Additionally, if CUmemLocation::id has a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, then this call has no effect. + + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemDiscardAndPrefetchBatchAsync ( CUdeviceptr* dptrs, size_t* sizes, size_t count, CUmemLocation* prefetchLocs, size_t* prefetchLocIdxs, size_t numPrefetchLocs, unsigned long long flags, CUstream hStream ) + + +Performs a batch of memory discards and prefetches asynchronously. + +###### Parameters + +`dptrs` + \- Array of pointers to be discarded +`sizes` + \- Array of sizes for memory discard operations. +`count` + \- Size of `dptrs` and `sizes` arrays. +`prefetchLocs` + \- Array of locations to prefetch to. +`prefetchLocIdxs` + \- Array of indices to specify which operands each entry in the `prefetchLocs` array applies to. The locations specified in prefetchLocs[k] will be applied to operations starting from prefetchLocIdxs[k] through prefetchLocIdxs[k+1] - 1. Also prefetchLocs[numPrefetchLocs - 1] will apply to copies starting from prefetchLocIdxs[numPrefetchLocs \- 1] through count - 1. +`numPrefetchLocs` + \- Size of `prefetchLocs` and `prefetchLocIdxs` arrays. +`flags` + \- Flags reserved for future use. Must be zero. +`hStream` + \- The stream to enqueue the operations in. Must not be legacy NULL stream. + +###### Description + +Performs a batch of memory discards followed by prefetches. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS otherwise the API will return an error. + +Calling cuMemDiscardAndPrefetchBatchAsync is semantically equivalent to calling cuMemDiscardBatchAsync followed by cuMemPrefetchBatchAsync, but is more optimal. For more details on what discarding and prefetching imply, please refer to cuMemDiscardBatchAsync and cuMemPrefetchBatchAsync respectively. Note that any reads, writes or prefetches to any part of the memory range that occur simultaneously with this combined discard+prefetch operation result in undefined behavior. + +Performs memory discard and prefetch on address ranges specified in `dptrs` and `sizes`. Both arrays must be of the same length as specified by `count`. Each memory range specified must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables or it may also refer to system-allocated memory when all devices have a non-zero value for CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Every operation in the batch has to be associated with a valid location to prefetch the address range to and specified in the `prefetchLocs` array. Each entry in this array can apply to more than one operation. This can be done by specifying in the `prefetchLocIdxs` array, the index of the first operation that the corresponding entry in the `prefetchLocs` array applies to. Both `prefetchLocs` and `prefetchLocIdxs` must be of the same length as specified by `numPrefetchLocs`. For example, if a batch has 10 operations listed in dptrs/sizes, the first 6 of which are to be prefetched to one location and the remaining 4 are to be prefetched to another, then `numPrefetchLocs` will be 2, `prefetchLocIdxs` will be {0, 6} and `prefetchLocs` will contain the two set of locations. Note the first entry in `prefetchLocIdxs` must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than `count`. Furthermore, `numPrefetchLocs` must be lesser than or equal to `count`. + +CUresult cuMemDiscardBatchAsync ( CUdeviceptr* dptrs, size_t* sizes, size_t count, unsigned long long flags, CUstream hStream ) + + +Performs a batch of memory discards asynchronously. + +###### Parameters + +`dptrs` + \- Array of pointers to be discarded +`sizes` + \- Array of sizes for memory discard operations. +`count` + \- Size of `dptrs` and `sizes` arrays. +`flags` + \- Flags reserved for future use. Must be zero. +`hStream` + \- The stream to enqueue the operations in. Must not be legacy NULL stream. + +###### Description + +Performs a batch of memory discards. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS otherwise the API will return an error. + +Discarding a memory range informs the driver that the contents of that range are no longer useful. Discarding memory ranges allows the driver to optimize certain data migrations and can also help reduce memory pressure. This operation can be undone on any part of the range by either writing to it or prefetching it via cuMemPrefetchAsync or cuMemPrefetchBatchAsync. Reading from a discarded range, without a subsequent write or prefetch to that part of the range, will return an indeterminate value. Note that any reads, writes or prefetches to any part of the memory range that occur simultaneously with the discard operation result in undefined behavior. + +Performs memory discard on address ranges specified in `dptrs` and `sizes`. Both arrays must be of the same length as specified by `count`. Each memory range specified must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables or it may also refer to system-allocated memory when all devices have a non-zero value for CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. + +CUresult cuMemPrefetchAsync ( CUdeviceptr devPtr, size_t count, CUmemLocation location, unsigned int flags, CUstream hStream ) + + +Prefetches memory to the specified destination location. + +###### Parameters + +`devPtr` + \- Pointer to be prefetched +`count` + \- Size in bytes +`location` + \- Location to prefetch to +`flags` + \- flags for future use, must be zero now. +`hStream` + \- Stream to enqueue prefetch operation + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Prefetches memory to the specified destination location. `devPtr` is the base device pointer of the memory to be prefetched and `location` specifies the destination location. `count` specifies the number of bytes to copy. `hStream` is the stream in which the operation is enqueued. The memory range must refer to managed memory allocated via cuMemAllocManaged, via cuMemAllocFromPool from a managed memory pool or declared via __managed__ variables. + +Specifying CU_MEM_LOCATION_TYPE_DEVICE for CUmemLocation::type will prefetch memory to GPU specified by device ordinal CUmemLocation::id which must have non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Additionally, `hStream` must be associated with a device that has a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Specifying CU_MEM_LOCATION_TYPE_HOST as CUmemLocation::type will prefetch data to host memory. Applications can request prefetching memory to a specific host NUMA node by specifying CU_MEM_LOCATION_TYPE_HOST_NUMA for CUmemLocation::type and a valid host NUMA node id in CUmemLocation::id Users can also request prefetching memory to the host NUMA node closest to the current thread's CPU by specifying CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT for CUmemLocation::type. Note when CUmemLocation::type is etiher CU_MEM_LOCATION_TYPE_HOST OR CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT, CUmemLocation::id will be ignored. + +The start address and end address of the memory range will be rounded down and rounded up respectively to be aligned to CPU page size before the prefetch operation is enqueued in the stream. + +If no physical memory has been allocated for this region, then this memory region will be populated and mapped on the destination device. If there's insufficient memory to prefetch the desired region, the Unified Memory driver may evict pages from other cuMemAllocManaged allocations to host memory in order to make room. Device memory allocated using cuMemAlloc or cuArrayCreate will not be evicted. + +By default, any mappings to the previous location of the migrated pages are removed and mappings for the new location are only setup on the destination location. The exact behavior however also depends on the settings applied to this memory range via cuMemAdvise as described below: + +If CU_MEM_ADVISE_SET_READ_MOSTLY was set on any subset of this memory range, then that subset will create a read-only copy of the pages on destination location. If however the destination location is a host NUMA node, then any pages of that subset that are already in another host NUMA node will be transferred to the destination. + +If CU_MEM_ADVISE_SET_PREFERRED_LOCATION was called on any subset of this memory range, then the pages will be migrated to `location` even if `location` is not the preferred location of any pages in the memory range. + +If CU_MEM_ADVISE_SET_ACCESSED_BY was called on any subset of this memory range, then mappings to those pages from all the appropriate processors are updated to refer to the new location if establishing such a mapping is possible. Otherwise, those mappings are cleared. + +Note that this API is not required for functionality and only serves to improve performance by allowing the application to migrate data to a suitable location before it is accessed. Memory accesses to this range are always coherent and are allowed even when the data is actively being migrated. + +Note that this function is asynchronous with respect to the host and all work on other devices. + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemPrefetchBatchAsync ( CUdeviceptr* dptrs, size_t* sizes, size_t count, CUmemLocation* prefetchLocs, size_t* prefetchLocIdxs, size_t numPrefetchLocs, unsigned long long flags, CUstream hStream ) + + +Performs a batch of memory prefetches asynchronously. + +###### Parameters + +`dptrs` + \- Array of pointers to be prefetched +`sizes` + \- Array of sizes for memory prefetch operations. +`count` + \- Size of `dptrs` and `sizes` arrays. +`prefetchLocs` + \- Array of locations to prefetch to. +`prefetchLocIdxs` + \- Array of indices to specify which operands each entry in the `prefetchLocs` array applies to. The locations specified in prefetchLocs[k] will be applied to copies starting from prefetchLocIdxs[k] through prefetchLocIdxs[k+1] - 1. Also prefetchLocs[numPrefetchLocs - 1] will apply to prefetches starting from prefetchLocIdxs[numPrefetchLocs \- 1] through count - 1. +`numPrefetchLocs` + \- Size of `prefetchLocs` and `prefetchLocIdxs` arrays. +`flags` + \- Flags reserved for future use. Must be zero. +`hStream` + \- The stream to enqueue the operations in. Must not be legacy NULL stream. + +###### Description + +Performs a batch of memory prefetches. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS otherwise the API will return an error. + +The semantics of the individual prefetch operations are as described in cuMemPrefetchAsync. + +Performs memory prefetch on address ranges specified in `dptrs` and `sizes`. Both arrays must be of the same length as specified by `count`. Each memory range specified must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables or it may also refer to system-allocated memory when all devices have a non-zero value for CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. The prefetch location for every operation in the batch is specified in the `prefetchLocs` array. Each entry in this array can apply to more than one operation. This can be done by specifying in the `prefetchLocIdxs` array, the index of the first prefetch operation that the corresponding entry in the `prefetchLocs` array applies to. Both `prefetchLocs` and `prefetchLocIdxs` must be of the same length as specified by `numPrefetchLocs`. For example, if a batch has 10 prefetches listed in dptrs/sizes, the first 4 of which are to be prefetched to one location and the remaining 6 are to be prefetched to another, then `numPrefetchLocs` will be 2, `prefetchLocIdxs` will be {0, 4} and `prefetchLocs` will contain the two locations. Note the first entry in `prefetchLocIdxs` must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than `count`. Furthermore, `numPrefetchLocs` must be lesser than or equal to `count`. + +CUresult cuMemRangeGetAttribute ( void* data, size_t dataSize, CUmem_range_attribute attribute, CUdeviceptr devPtr, size_t count ) + + +Query an attribute of a given memory range. + +###### Parameters + +`data` + \- A pointers to a memory location where the result of each attribute query will be written to. +`dataSize` + \- Array containing the size of data +`attribute` + \- The attribute to query +`devPtr` + \- Start of the range to query +`count` + \- Size of the range to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Query an attribute about the memory range starting at `devPtr` with a size of `count` bytes. The memory range must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables. + +The `attribute` parameter can take the following values: + + * CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY: If this attribute is specified, `data` will be interpreted as a 32-bit integer, and `dataSize` must be 4. The result returned will be 1 if all pages in the given memory range have read-duplication enabled, or 0 otherwise. + + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION: If this attribute is specified, `data` will be interpreted as a 32-bit integer, and `dataSize` must be 4. The result returned will be a GPU device id if all pages in the memory range have that GPU as their preferred location, or it will be CU_DEVICE_CPU if all pages in the memory range have the CPU as their preferred location, or it will be CU_DEVICE_INVALID if either all the pages don't have the same preferred location or some of the pages don't have a preferred location at all. Note that the actual location of the pages in the memory range at the time of the query may be different from the preferred location. + + * CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY: If this attribute is specified, `data` will be interpreted as an array of 32-bit integers, and `dataSize` must be a non-zero multiple of 4. The result returned will be a list of device ids that had CU_MEM_ADVISE_SET_ACCESSED_BY set for that entire memory range. If any device does not have that advice set for the entire memory range, that device will not be included. If `data` is larger than the number of devices that have that advice set for that memory range, CU_DEVICE_INVALID will be returned in all the extra space provided. For ex., if `dataSize` is 12 (i.e. `data` has 3 elements) and only device 0 has the advice set, then the result returned will be { 0, CU_DEVICE_INVALID, CU_DEVICE_INVALID }. If `data` is smaller than the number of devices that have that advice set, then only as many devices will be returned as can fit in the array. There is no guarantee on which specific devices will be returned, however. + + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION: If this attribute is specified, `data` will be interpreted as a 32-bit integer, and `dataSize` must be 4. The result returned will be the last location to which all pages in the memory range were prefetched explicitly via cuMemPrefetchAsync. This will either be a GPU id or CU_DEVICE_CPU depending on whether the last location for prefetch was a GPU or the CPU respectively. If any page in the memory range was never explicitly prefetched or if all pages were not prefetched to the same location, CU_DEVICE_INVALID will be returned. Note that this simply returns the last location that the application requested to prefetch the memory range to. It gives no indication as to whether the prefetch operation to that location has completed or even begun. + + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE: If this attribute is specified, `data` will be interpreted as a CUmemLocationType, and `dataSize` must be sizeof(CUmemLocationType). The CUmemLocationType returned will be CU_MEM_LOCATION_TYPE_DEVICE if all pages in the memory range have the same GPU as their preferred location, or CUmemLocationType will be CU_MEM_LOCATION_TYPE_HOST if all pages in the memory range have the CPU as their preferred location, or it will be CU_MEM_LOCATION_TYPE_HOST_NUMA if all the pages in the memory range have the same host NUMA node ID as their preferred location or it will be CU_MEM_LOCATION_TYPE_INVALID if either all the pages don't have the same preferred location or some of the pages don't have a preferred location at all. Note that the actual location type of the pages in the memory range at the time of the query may be different from the preferred location type. + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID: If this attribute is specified, `data` will be interpreted as a 32-bit integer, and `dataSize` must be 4. If the CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE query for the same address range returns CU_MEM_LOCATION_TYPE_DEVICE, it will be a valid device ordinal or if it returns CU_MEM_LOCATION_TYPE_HOST_NUMA, it will be a valid host NUMA node ID or if it returns any other location type, the id should be ignored. + + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE: If this attribute is specified, `data` will be interpreted as a CUmemLocationType, and `dataSize` must be sizeof(CUmemLocationType). The result returned will be the last location to which all pages in the memory range were prefetched explicitly via cuMemPrefetchAsync. The CUmemLocationType returned will be CU_MEM_LOCATION_TYPE_DEVICE if the last prefetch location was a GPU or CU_MEM_LOCATION_TYPE_HOST if it was the CPU or CU_MEM_LOCATION_TYPE_HOST_NUMA if the last prefetch location was a specific host NUMA node. If any page in the memory range was never explicitly prefetched or if all pages were not prefetched to the same location, CUmemLocationType will be CU_MEM_LOCATION_TYPE_INVALID. Note that this simply returns the last location type that the application requested to prefetch the memory range to. It gives no indication as to whether the prefetch operation to that location has completed or even begun. + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID: If this attribute is specified, `data` will be interpreted as a 32-bit integer, and `dataSize` must be 4. If the CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE query for the same address range returns CU_MEM_LOCATION_TYPE_DEVICE, it will be a valid device ordinal or if it returns CU_MEM_LOCATION_TYPE_HOST_NUMA, it will be a valid host NUMA node ID or if it returns any other location type, the id should be ignored. + + + * + + * This function exhibits asynchronous behavior for most use cases. + + * This function uses standard default stream semantics. + + +CUresult cuMemRangeGetAttributes ( void** data, size_t* dataSizes, CUmem_range_attribute* attributes, size_t numAttributes, CUdeviceptr devPtr, size_t count ) + + +Query attributes of a given memory range. + +###### Parameters + +`data` + \- A two-dimensional array containing pointers to memory locations where the result of each attribute query will be written to. +`dataSizes` + \- Array containing the sizes of each result +`attributes` + \- An array of attributes to query (numAttributes and the number of attributes in this array should match) +`numAttributes` + \- Number of attributes to query +`devPtr` + \- Start of the range to query +`count` + \- Size of the range to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +Query attributes of the memory range starting at `devPtr` with a size of `count` bytes. The memory range must refer to managed memory allocated via cuMemAllocManaged or declared via __managed__ variables. The `attributes` array will be interpreted to have `numAttributes` entries. The `dataSizes` array will also be interpreted to have `numAttributes` entries. The results of the query will be stored in `data`. + +The list of supported attributes are given below. Please refer to cuMemRangeGetAttribute for attribute descriptions and restrictions. + + * CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY + + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION + + * CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY + + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION + + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE + + * CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID + + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE + + * CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID + + +CUresult cuPointerGetAttribute ( void* data, CUpointer_attribute attribute, CUdeviceptr ptr ) + + +Returns information about a pointer. + +###### Parameters + +`data` + \- Returned pointer attribute value +`attribute` + \- Pointer attribute to query +`ptr` + \- Pointer + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +The supported attributes are: + + * CU_POINTER_ATTRIBUTE_CONTEXT: + + +Returns in `*data` the CUcontext in which `ptr` was allocated or registered. The type of `data` must be CUcontext *. + +If `ptr` was not allocated by, mapped by, or registered with a CUcontext which uses unified virtual addressing then CUDA_ERROR_INVALID_VALUE is returned. + + * CU_POINTER_ATTRIBUTE_MEMORY_TYPE: + + +Returns in `*data` the physical memory type of the memory that `ptr` addresses as a CUmemorytype enumerated value. The type of `data` must be unsigned int. + +If `ptr` addresses device memory then `*data` is set to CU_MEMORYTYPE_DEVICE. The particular CUdevice on which the memory resides is the CUdevice of the CUcontext returned by the CU_POINTER_ATTRIBUTE_CONTEXT attribute of `ptr`. + +If `ptr` addresses host memory then `*data` is set to CU_MEMORYTYPE_HOST. + +If `ptr` was not allocated by, mapped by, or registered with a CUcontext which uses unified virtual addressing then CUDA_ERROR_INVALID_VALUE is returned. + +If the current CUcontext does not support unified virtual addressing then CUDA_ERROR_INVALID_CONTEXT is returned. + + * CU_POINTER_ATTRIBUTE_DEVICE_POINTER: + + +Returns in `*data` the device pointer value through which `ptr` may be accessed by kernels running in the current CUcontext. The type of `data` must be CUdeviceptr *. + +If there exists no device pointer value through which kernels running in the current CUcontext may access `ptr` then CUDA_ERROR_INVALID_VALUE is returned. + +If there is no current CUcontext then CUDA_ERROR_INVALID_CONTEXT is returned. + +Except in the exceptional disjoint addressing cases discussed below, the value returned in `*data` will equal the input value `ptr`. + + * CU_POINTER_ATTRIBUTE_HOST_POINTER: + + +Returns in `*data` the host pointer value through which `ptr` may be accessed by by the host program. The type of `data` must be void **. If there exists no host pointer value through which the host program may directly access `ptr` then CUDA_ERROR_INVALID_VALUE is returned. + +Except in the exceptional disjoint addressing cases discussed below, the value returned in `*data` will equal the input value `ptr`. + + * CU_POINTER_ATTRIBUTE_P2P_TOKENS: + + +Returns in `*data` two tokens for use with the nv-p2p.h Linux kernel interface. `data` must be a struct of type CUDA_POINTER_ATTRIBUTE_P2P_TOKENS. + +`ptr` must be a pointer to memory obtained from :cuMemAlloc(). Note that p2pToken and vaSpaceToken are only valid for the lifetime of the source allocation. A subsequent allocation at the same address may return completely different tokens. Querying this attribute has a side effect of setting the attribute CU_POINTER_ATTRIBUTE_SYNC_MEMOPS for the region of memory that `ptr` points to. + + * CU_POINTER_ATTRIBUTE_SYNC_MEMOPS: + + +A boolean attribute which when set, ensures that synchronous memory operations initiated on the region of memory that `ptr` points to will always synchronize. See further documentation in the section titled "API synchronization behavior" to learn more about cases when synchronous memory operations can exhibit asynchronous behavior. + + * CU_POINTER_ATTRIBUTE_BUFFER_ID: + + +Returns in `*data` a buffer ID which is guaranteed to be unique within the process. `data` must point to an unsigned long long. + +`ptr` must be a pointer to memory obtained from a CUDA memory allocation API. Every memory allocation from any of the CUDA memory allocation APIs will have a unique ID over a process lifetime. Subsequent allocations do not reuse IDs from previous freed allocations. IDs are only unique within a single process. + + * CU_POINTER_ATTRIBUTE_IS_MANAGED: + + +Returns in `*data` a boolean that indicates whether the pointer points to managed memory or not. + +If `ptr` is not a valid CUDA pointer then CUDA_ERROR_INVALID_VALUE is returned. + + * CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL: + + +Returns in `*data` an integer representing a device ordinal of a device against which the memory was allocated or registered. + + * CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE: + + +Returns in `*data` a boolean that indicates if this pointer maps to an allocation that is suitable for cudaIpcGetMemHandle. + + * CU_POINTER_ATTRIBUTE_RANGE_START_ADDR: + + +Returns in `*data` the starting address for the allocation referenced by the device pointer `ptr`. Note that this is not necessarily the address of the mapped region, but the address of the mappable address range `ptr` references (e.g. from cuMemAddressReserve). + + * CU_POINTER_ATTRIBUTE_RANGE_SIZE: + + +Returns in `*data` the size for the allocation referenced by the device pointer `ptr`. Note that this is not necessarily the size of the mapped region, but the size of the mappable address range `ptr` references (e.g. from cuMemAddressReserve). To retrieve the size of the mapped region, see cuMemGetAddressRange + + * CU_POINTER_ATTRIBUTE_MAPPED: + + +Returns in `*data` a boolean that indicates if this pointer is in a valid address range that is mapped to a backing allocation. + + * CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES: + + +Returns a bitmask of the allowed handle types for an allocation that may be passed to cuMemExportToShareableHandle. + + * CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE: + + +Returns in `*data` the handle to the mempool that the allocation was obtained from. + + * CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE: + + +Returns in `*data` a boolean that indicates whether the pointer points to memory that is capable to be used for hardware accelerated decompression. + +Note that for most allocations in the unified virtual address space the host and device pointer for accessing the allocation will be the same. The exceptions to this are + + * user memory registered using cuMemHostRegister + + * host memory allocated using cuMemHostAlloc with the CU_MEMHOSTALLOC_WRITECOMBINED flag For these types of allocation there will exist separate, disjoint host and device addresses for accessing the allocation. In particular + + * The host address will correspond to an invalid unmapped device address (which will result in an exception if accessed from the device) + + * The device address will correspond to an invalid unmapped host address (which will result in an exception if accessed from the host). For these types of allocations, querying CU_POINTER_ATTRIBUTE_HOST_POINTER and CU_POINTER_ATTRIBUTE_DEVICE_POINTER may be used to retrieve the host and device addresses from either address. + + +CUresult cuPointerGetAttributes ( unsigned int numAttributes, CUpointer_attribute* attributes, void** data, CUdeviceptr ptr ) + + +Returns information about a pointer. + +###### Parameters + +`numAttributes` + \- Number of attributes to query +`attributes` + \- An array of attributes to query (numAttributes and the number of attributes in this array should match) +`data` + \- A two-dimensional array containing pointers to memory locations where the result of each attribute query will be written to. +`ptr` + \- Pointer to query + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +The supported attributes are (refer to cuPointerGetAttribute for attribute descriptions and restrictions): + + * CU_POINTER_ATTRIBUTE_CONTEXT + + * CU_POINTER_ATTRIBUTE_MEMORY_TYPE + + * CU_POINTER_ATTRIBUTE_DEVICE_POINTER + + * CU_POINTER_ATTRIBUTE_HOST_POINTER + + * CU_POINTER_ATTRIBUTE_SYNC_MEMOPS + + * CU_POINTER_ATTRIBUTE_BUFFER_ID + + * CU_POINTER_ATTRIBUTE_IS_MANAGED + + * CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL + + * CU_POINTER_ATTRIBUTE_RANGE_START_ADDR + + * CU_POINTER_ATTRIBUTE_RANGE_SIZE + + * CU_POINTER_ATTRIBUTE_MAPPED + + * CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE + + * CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES + + * CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE + + * CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE + + +Unlike cuPointerGetAttribute, this function will not return an error when the `ptr` encountered is not a valid CUDA pointer. Instead, the attributes are assigned default NULL values and CUDA_SUCCESS is returned. + +If `ptr` was not allocated by, mapped by, or registered with a CUcontext which uses UVA (Unified Virtual Addressing), CUDA_ERROR_INVALID_CONTEXT is returned. + +CUresult cuPointerSetAttribute ( const void* value, CUpointer_attribute attribute, CUdeviceptr ptr ) + + +Set attributes on a previously allocated memory region. + +###### Parameters + +`value` + \- Pointer to memory containing the value to be set +`attribute` + \- Pointer attribute to set +`ptr` + \- Pointer to a memory region allocated using CUDA memory allocation APIs + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE + +###### Description + +The supported attributes are: + + * CU_POINTER_ATTRIBUTE_SYNC_MEMOPS: + + +A boolean attribute that can either be set (1) or unset (0). When set, the region of memory that `ptr` points to is guaranteed to always synchronize memory operations that are synchronous. If there are some previously initiated synchronous memory operations that are pending when this attribute is set, the function does not return until those memory operations are complete. See further documentation in the section titled "API synchronization behavior" to learn more about cases when synchronous memory operations can exhibit asynchronous behavior. `value` will be considered as a pointer to an unsigned integer to which this attribute is to be set. + + diff --git a/content/cuda/docs/driver-va/DOC.md b/content/cuda/docs/driver-va/DOC.md new file mode 100644 index 00000000..8a3cc03e --- /dev/null +++ b/content/cuda/docs/driver-va/DOC.md @@ -0,0 +1,449 @@ +--- +name: driver-va +description: '**Source:** group__CUDA__VA.html#group__CUDA__VA' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.14. Virtual Memory Management + +**Source:** group__CUDA__VA.html#group__CUDA__VA + + +### Functions + +CUresult cuMemAddressFree ( CUdeviceptr ptr, size_t size ) + + +Free an address range reservation. + +###### Parameters + +`ptr` + \- Starting address of the virtual address range to free +`size` + \- Size of the virtual address region to free + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Frees a virtual address range reserved by cuMemAddressReserve. The size must match what was given to memAddressReserve and the ptr given must match what was returned from memAddressReserve. + +CUresult cuMemAddressReserve ( CUdeviceptr* ptr, size_t size, size_t alignment, CUdeviceptr addr, unsigned long long flags ) + + +Allocate an address range reservation. + +###### Parameters + +`ptr` + \- Resulting pointer to start of virtual address range allocated +`size` + \- Size of the reserved virtual address range requested +`alignment` + \- Alignment of the reserved virtual address range requested +`addr` + \- Hint address for the start of the address range +`flags` + \- Currently unused, must be zero + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Reserves a virtual address range based on the given parameters, giving the starting address of the range in `ptr`. This API requires a system that supports UVA. The size and address parameters must be a multiple of the host page size and the alignment must be a power of two or zero for default alignment. If `addr` is 0, then the driver chooses the address at which to place the start of the reservation whereas when it is non-zero then the driver treats it as a hint about where to place the reservation. + +CUresult cuMemCreate ( CUmemGenericAllocationHandle* handle, size_t size, const CUmemAllocationProp* prop, unsigned long long flags ) + + +Create a CUDA memory handle representing a memory allocation of a given size described by the given properties. + +###### Parameters + +`handle` + \- Value of handle returned. All operations on this allocation are to be performed using this handle. +`size` + \- Size of the allocation requested +`prop` + \- Properties of the allocation to create. +`flags` + \- flags for future use, must be zero now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +This creates a memory allocation on the target device specified through the `prop` structure. The created allocation will not have any device or host mappings. The generic memory `handle` for the allocation can be mapped to the address space of calling process via cuMemMap. This handle cannot be transmitted directly to other processes (see cuMemExportToShareableHandle). On Windows, the caller must also pass an LPSECURITYATTRIBUTE in `prop` to be associated with this handle which limits or allows access to this handle for a recipient process (see CUmemAllocationProp::win32HandleMetaData for more). The `size` of this allocation must be a multiple of the the value given via cuMemGetAllocationGranularity with the CU_MEM_ALLOC_GRANULARITY_MINIMUM flag. To create a CPU allocation that doesn't target any specific NUMA nodes, applications must set CUmemAllocationProp::CUmemLocation::type to CU_MEM_LOCATION_TYPE_HOST. CUmemAllocationProp::CUmemLocation::id is ignored for HOST allocations. HOST allocations are not IPC capable and CUmemAllocationProp::requestedHandleTypes must be 0, any other value will result in CUDA_ERROR_INVALID_VALUE. To create a CPU allocation targeting a specific host NUMA node, applications must set CUmemAllocationProp::CUmemLocation::type to CU_MEM_LOCATION_TYPE_HOST_NUMA and CUmemAllocationProp::CUmemLocation::id must specify the NUMA ID of the CPU. On systems where NUMA is not available CUmemAllocationProp::CUmemLocation::id must be set to 0. Specifying CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT as the CUmemLocation::type will result in CUDA_ERROR_INVALID_VALUE. + +Applications that intend to use CU_MEM_HANDLE_TYPE_FABRIC based memory sharing must ensure: (1) `nvidia-caps-imex-channels` character device is created by the driver and is listed under /proc/devices (2) have at least one IMEX channel file accessible by the user launching the application. + +When exporter and importer CUDA processes have been granted access to the same IMEX channel, they can securely share memory. + +The IMEX channel security model works on a per user basis. Which means all processes under a user can share memory if the user has access to a valid IMEX channel. When multi-user isolation is desired, a separate IMEX channel is required for each user. + +These channel files exist in /dev/nvidia-caps-imex-channels/channel* and can be created using standard OS native calls like mknod on Linux. For example: To create channel0 with the major number from /proc/devices users can execute the following command: `mknod /dev/nvidia-caps-imex-channels/channel0 c =""> 0` + +If CUmemAllocationProp::allocFlags::usage contains CU_MEM_CREATE_USAGE_TILE_POOL flag then the memory allocation is intended only to be used as backing tile pool for sparse CUDA arrays and sparse CUDA mipmapped arrays. (see cuMemMapArrayAsync). + +CUresult cuMemExportToShareableHandle ( void* shareableHandle, CUmemGenericAllocationHandle handle, CUmemAllocationHandleType handleType, unsigned long long flags ) + + +Exports an allocation to a requested shareable handle type. + +###### Parameters + +`shareableHandle` + \- Pointer to the location in which to store the requested handle type +`handle` + \- CUDA handle for the memory allocation +`handleType` + \- Type of shareable handle requested (defines type and size of the `shareableHandle` output parameter) +`flags` + \- Reserved, must be zero + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Given a CUDA memory handle, create a shareable memory allocation handle that can be used to share the memory with other processes. The recipient process can convert the shareable handle back into a CUDA memory handle using cuMemImportFromShareableHandle and map it with cuMemMap. The implementation of what this handle is and how it can be transferred is defined by the requested handle type in `handleType` + +Once all shareable handles are closed and the allocation is released, the allocated memory referenced will be released back to the OS and uses of the CUDA handle afterward will lead to undefined behavior. + +This API can also be used in conjunction with other APIs (e.g. Vulkan, OpenGL) that support importing memory from the shareable type + +CUresult cuMemGetAccess ( unsigned long long* flags, const CUmemLocation* location, CUdeviceptr ptr ) + + +Get the access `flags` set for the given `location` and `ptr`. + +###### Parameters + +`flags` + \- Flags set for this location +`location` + \- Location in which to check the flags for +`ptr` + \- Address in which to check the access flags for + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +CUresult cuMemGetAllocationGranularity ( size_t* granularity, const CUmemAllocationProp* prop, CUmemAllocationGranularity_flags option ) + + +Calculates either the minimal or recommended granularity. + +###### Parameters + +`granularity` + Returned granularity. +`prop` + Property for which to determine the granularity for +`option` + Determines which granularity to return + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Calculates either the minimal or recommended granularity for a given allocation specification and returns it in granularity. This granularity can be used as a multiple for alignment, size, or address mapping. + +CUresult cuMemGetAllocationPropertiesFromHandle ( CUmemAllocationProp* prop, CUmemGenericAllocationHandle handle ) + + +Retrieve the contents of the property structure defining properties for this handle. + +###### Parameters + +`prop` + \- Pointer to a properties structure which will hold the information about this handle +`handle` + \- Handle which to perform the query on + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +CUresult cuMemImportFromShareableHandle ( CUmemGenericAllocationHandle* handle, void* osHandle, CUmemAllocationHandleType shHandleType ) + + +Imports an allocation from a requested shareable handle type. + +###### Parameters + +`handle` + \- CUDA Memory handle for the memory allocation. +`osHandle` + \- Shareable Handle representing the memory allocation that is to be imported. +`shHandleType` + \- handle type of the exported handle CUmemAllocationHandleType. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +If the current process cannot support the memory described by this shareable handle, this API will error as CUDA_ERROR_NOT_SUPPORTED. + +If `shHandleType` is CU_MEM_HANDLE_TYPE_FABRIC and the importer process has not been granted access to the same IMEX channel as the exporter process, this API will error as CUDA_ERROR_NOT_PERMITTED. + +Importing shareable handles exported from some graphics APIs(VUlkan, OpenGL, etc) created on devices under an SLI group may not be supported, and thus this API will return CUDA_ERROR_NOT_SUPPORTED. There is no guarantee that the contents of `handle` will be the same CUDA memory handle for the same given OS shareable handle, or the same underlying allocation. + +CUresult cuMemMap ( CUdeviceptr ptr, size_t size, size_t offset, CUmemGenericAllocationHandle handle, unsigned long long flags ) + + +Maps an allocation handle to a reserved virtual address range. + +###### Parameters + +`ptr` + \- Address where memory will be mapped. +`size` + \- Size of the memory mapping. +`offset` + \- Offset into the memory represented by + + * `handle` from which to start mapping + * Note: currently must be zero. + + +`handle` + \- Handle to a shareable memory +`flags` + \- flags for future use, must be zero now. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_OUT_OF_MEMORY, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED, CUDA_ERROR_ILLEGAL_STATE + +###### Description + +Maps bytes of memory represented by `handle` starting from byte `offset` to `size` to address range [`addr`, `addr` \+ `size`]. This range must be an address reservation previously reserved with cuMemAddressReserve, and `offset` \+ `size` must be less than the size of the memory allocation. Both `ptr`, `size`, and `offset` must be a multiple of the value given via cuMemGetAllocationGranularity with the CU_MEM_ALLOC_GRANULARITY_MINIMUM flag. If `handle` represents a multicast object, `ptr`, `size` and `offset` must be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_MINIMUM_GRANULARITY. For best performance however, it is recommended that `ptr`, `size` and `offset` be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_RECOMMENDED_GRANULARITY. + +When `handle` represents a multicast object, this call may return CUDA_ERROR_ILLEGAL_STATE if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. + +Please note calling cuMemMap does not make the address accessible, the caller needs to update accessibility of a contiguous mapped VA range by calling cuMemSetAccess. + +Once a recipient process obtains a shareable memory handle from cuMemImportFromShareableHandle, the process must use cuMemMap to map the memory into its address ranges before setting accessibility with cuMemSetAccess. + +cuMemMap can only create mappings on VA range reservations that are not currently mapped. + +CUresult cuMemMapArrayAsync ( CUarrayMapInfo* mapInfoList, unsigned int count, CUstream hStream ) + + +Maps or unmaps subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays. + +###### Parameters + +`mapInfoList` + \- List of CUarrayMapInfo +`count` + \- Count of CUarrayMapInfo in `mapInfoList` +`hStream` + \- Stream identifier for the stream to use for map or unmap operations + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE + +###### Description + +Performs map or unmap operations on subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays. Each operation is specified by a CUarrayMapInfo entry in the `mapInfoList` array of size `count`. The structure CUarrayMapInfo is defined as follow: + + + ‎ typedef struct CUarrayMapInfo_st { + CUresourcetype resourceType; + union { + CUmipmappedArray mipmap; + CUarray array; + } resource; + + CUarraySparseSubresourceType subresourceType; + union { + struct { + unsigned int level; + unsigned int layer; + unsigned int offsetX; + unsigned int offsetY; + unsigned int offsetZ; + unsigned int extentWidth; + unsigned int extentHeight; + unsigned int extentDepth; + } sparseLevel; + struct { + unsigned int layer; + unsigned long long offset; + unsigned long long size; + } miptail; + } subresource; + + CUmemOperationType memOperationType; + + CUmemHandleType memHandleType; + union { + CUmemGenericAllocationHandle memHandle; + } memHandle; + + unsigned long long offset; + unsigned int deviceBitMask; + unsigned int flags; + unsigned int reserved[2]; + } CUarrayMapInfo; + +where CUarrayMapInfo::resourceType specifies the type of resource to be operated on. If CUarrayMapInfo::resourceType is set to CUresourcetype::CU_RESOURCE_TYPE_ARRAY then CUarrayMapInfo::resource::array must be set to a valid sparse CUDA array handle. The CUDA array must be either a 2D, 2D layered or 3D CUDA array and must have been allocated using cuArrayCreate or cuArray3DCreate with the flag CUDA_ARRAY3D_SPARSE or CUDA_ARRAY3D_DEFERRED_MAPPING. For CUDA arrays obtained using cuMipmappedArrayGetLevel, CUDA_ERROR_INVALID_VALUE will be returned. If CUarrayMapInfo::resourceType is set to CUresourcetype::CU_RESOURCE_TYPE_MIPMAPPED_ARRAY then CUarrayMapInfo::resource::mipmap must be set to a valid sparse CUDA mipmapped array handle. The CUDA mipmapped array must be either a 2D, 2D layered or 3D CUDA mipmapped array and must have been allocated using cuMipmappedArrayCreate with the flag CUDA_ARRAY3D_SPARSE or CUDA_ARRAY3D_DEFERRED_MAPPING. + +CUarrayMapInfo::subresourceType specifies the type of subresource within the resource. CUarraySparseSubresourceType_enum is defined as: + + + ‎ typedef enum CUarraySparseSubresourceType_enum { + CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL = 0 + CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL = 1 + } CUarraySparseSubresourceType; + +where CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL indicates a sparse-miplevel which spans at least one tile in every dimension. The remaining miplevels which are too small to span at least one tile in any dimension constitute the mip tail region as indicated by CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL subresource type. + +If CUarrayMapInfo::subresourceType is set to CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL then CUarrayMapInfo::subresource::sparseLevel struct must contain valid array subregion offsets and extents. The CUarrayMapInfo::subresource::sparseLevel::offsetX, CUarrayMapInfo::subresource::sparseLevel::offsetY and CUarrayMapInfo::subresource::sparseLevel::offsetZ must specify valid X, Y and Z offsets respectively. The CUarrayMapInfo::subresource::sparseLevel::extentWidth, CUarrayMapInfo::subresource::sparseLevel::extentHeight and CUarrayMapInfo::subresource::sparseLevel::extentDepth must specify valid width, height and depth extents respectively. These offsets and extents must be aligned to the corresponding tile dimension. For CUDA mipmapped arrays CUarrayMapInfo::subresource::sparseLevel::level must specify a valid mip level index. Otherwise, must be zero. For layered CUDA arrays and layered CUDA mipmapped arrays CUarrayMapInfo::subresource::sparseLevel::layer must specify a valid layer index. Otherwise, must be zero. CUarrayMapInfo::subresource::sparseLevel::offsetZ must be zero and CUarrayMapInfo::subresource::sparseLevel::extentDepth must be set to 1 for 2D and 2D layered CUDA arrays and CUDA mipmapped arrays. Tile extents can be obtained by calling cuArrayGetSparseProperties and cuMipmappedArrayGetSparseProperties + +If CUarrayMapInfo::subresourceType is set to CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL then CUarrayMapInfo::subresource::miptail struct must contain valid mip tail offset in CUarrayMapInfo::subresource::miptail::offset and size in CUarrayMapInfo::subresource::miptail::size. Both, mip tail offset and mip tail size must be aligned to the tile size. For layered CUDA mipmapped arrays which don't have the flag CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL set in CUDA_ARRAY_SPARSE_PROPERTIES::flags as returned by cuMipmappedArrayGetSparseProperties, CUarrayMapInfo::subresource::miptail::layer must specify a valid layer index. Otherwise, must be zero. + +If CUarrayMapInfo::resource::array or CUarrayMapInfo::resource::mipmap was created with CUDA_ARRAY3D_DEFERRED_MAPPING flag set the CUarrayMapInfo::subresourceType and the contents of CUarrayMapInfo::subresource will be ignored. + +CUarrayMapInfo::memOperationType specifies the type of operation. CUmemOperationType is defined as: + + + ‎ typedef enum CUmemOperationType_enum { + CU_MEM_OPERATION_TYPE_MAP = 1 + CU_MEM_OPERATION_TYPE_UNMAP = 2 + } CUmemOperationType; + +If CUarrayMapInfo::memOperationType is set to CUmemOperationType::CU_MEM_OPERATION_TYPE_MAP then the subresource will be mapped onto the tile pool memory specified by CUarrayMapInfo::memHandle at offset CUarrayMapInfo::offset. The tile pool allocation has to be created by specifying the CU_MEM_CREATE_USAGE_TILE_POOL flag when calling cuMemCreate. Also, CUarrayMapInfo::memHandleType must be set to CUmemHandleType::CU_MEM_HANDLE_TYPE_GENERIC. + +If CUarrayMapInfo::memOperationType is set to CUmemOperationType::CU_MEM_OPERATION_TYPE_UNMAP then an unmapping operation is performed. CUarrayMapInfo::memHandle must be NULL. + +CUarrayMapInfo::deviceBitMask specifies the list of devices that must map or unmap physical memory. Currently, this mask must have exactly one bit set, and the corresponding device must match the device associated with the stream. If CUarrayMapInfo::memOperationType is set to CUmemOperationType::CU_MEM_OPERATION_TYPE_MAP, the device must also match the device associated with the tile pool memory allocation as specified by CUarrayMapInfo::memHandle. + +CUarrayMapInfo::flags and CUarrayMapInfo::reserved[] are unused and must be set to zero. + +CUresult cuMemRelease ( CUmemGenericAllocationHandle handle ) + + +Release a memory handle representing a memory allocation which was previously allocated through cuMemCreate. + +###### Parameters + +`handle` + Value of handle which was returned previously by cuMemCreate. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Frees the memory that was allocated on a device through cuMemCreate. + +The memory allocation will be freed when all outstanding mappings to the memory are unmapped and when all outstanding references to the handle (including it's shareable counterparts) are also released. The generic memory handle can be freed when there are still outstanding mappings made with this handle. Each time a recipient process imports a shareable handle, it needs to pair it with cuMemRelease for the handle to be freed. If `handle` is not a valid handle the behavior is undefined. + +CUresult cuMemRetainAllocationHandle ( CUmemGenericAllocationHandle* handle, void* addr ) + + +Given an address `addr`, returns the allocation handle of the backing memory allocation. + +###### Parameters + +`handle` + CUDA Memory handle for the backing memory allocation. +`addr` + Memory address to query, that has been mapped previously. + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +The handle is guaranteed to be the same handle value used to map the memory. If the address requested is not mapped, the function will fail. The returned handle must be released with corresponding number of calls to cuMemRelease. + +The address `addr`, can be any address in a range previously mapped by cuMemMap, and not necessarily the start address. + +CUresult cuMemSetAccess ( CUdeviceptr ptr, size_t size, const CUmemAccessDesc* desc, size_t count ) + + +Set the access flags for each location specified in `desc` for the given virtual address range. + +###### Parameters + +`ptr` + \- Starting address for the virtual address range +`size` + \- Length of the virtual address range +`desc` + \- Array of CUmemAccessDesc that describe how to change the + + * mapping for each location specified + + +`count` + \- Number of CUmemAccessDesc in `desc` + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +Given the virtual address range via `ptr` and `size`, and the locations in the array given by `desc` and `count`, set the access flags for the target locations. The range must be a fully mapped address range containing all allocations created by cuMemMap / cuMemCreate. Users cannot specify CU_MEM_LOCATION_TYPE_HOST_NUMA accessibility for allocations created on with other location types. Note: When CUmemAccessDesc::CUmemLocation::type is CU_MEM_LOCATION_TYPE_HOST_NUMA, CUmemAccessDesc::CUmemLocation::id is ignored. When setting the access flags for a virtual address range mapping a multicast object, `ptr` and `size` must be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_MINIMUM_GRANULARITY. For best performance however, it is recommended that `ptr` and `size` be aligned to the value returned by cuMulticastGetGranularity with the flag CU_MULTICAST_RECOMMENDED_GRANULARITY. + + * + + * This function exhibits synchronous behavior for most use cases. + + +CUresult cuMemUnmap ( CUdeviceptr ptr, size_t size ) + + +Unmap the backing memory of a given address range. + +###### Parameters + +`ptr` + \- Starting address for the virtual address range to unmap +`size` + \- Size of the virtual address range to unmap + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_PERMITTED, CUDA_ERROR_NOT_SUPPORTED + +###### Description + +The range must be the entire contiguous address range that was mapped to. In other words, cuMemUnmap cannot unmap a sub-range of an address range mapped by cuMemCreate / cuMemMap. Any backing memory allocations will be freed if there are no existing mappings and there are no unreleased memory handles. + +When cuMemUnmap returns successfully the address range is converted to an address reservation and can be used for a future calls to cuMemMap. Any new mapping to this virtual address will need to have access granted through cuMemSetAccess, as all mappings start with no accessibility setup. + + * + + * This function exhibits synchronous behavior for most use cases. + diff --git a/content/cuda/docs/driver-vdpau/DOC.md b/content/cuda/docs/driver-vdpau/DOC.md new file mode 100644 index 00000000..72f1edb4 --- /dev/null +++ b/content/cuda/docs/driver-vdpau/DOC.md @@ -0,0 +1,130 @@ +--- +name: driver-vdpau +description: '**Source:** group__CUDA__VDPAU.html#group__CUDA__VDPAU' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.44. VDPAU Interoperability + +**Source:** group__CUDA__VDPAU.html#group__CUDA__VDPAU + + +### Functions + +CUresult cuGraphicsVDPAURegisterOutputSurface ( CUgraphicsResource* pCudaResource, VdpOutputSurface vdpSurface, unsigned int flags ) + + +Registers a VDPAU VdpOutputSurface object. + +###### Parameters + +`pCudaResource` + \- Pointer to the returned object handle +`vdpSurface` + \- The VdpOutputSurface to be registered +`flags` + \- Map flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Registers the VdpOutputSurface specified by `vdpSurface` for access by CUDA. A handle to the registered object is returned as `pCudaResource`. The surface's intended usage is specified using `flags`, as follows: + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY: Specifies that CUDA will not write to this resource. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +The VdpOutputSurface is presented as an array of subresources that may be accessed using pointers returned by cuGraphicsSubResourceGetMappedArray. The exact number of valid `arrayIndex` values depends on the VDPAU surface format. The mapping is shown in the table below. `mipLevel` must be 0. + +CUresult cuGraphicsVDPAURegisterVideoSurface ( CUgraphicsResource* pCudaResource, VdpVideoSurface vdpSurface, unsigned int flags ) + + +Registers a VDPAU VdpVideoSurface object. + +###### Parameters + +`pCudaResource` + \- Pointer to the returned object handle +`vdpSurface` + \- The VdpVideoSurface to be registered +`flags` + \- Map flags + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_ALREADY_MAPPED, CUDA_ERROR_INVALID_CONTEXT + +###### Description + +Registers the VdpVideoSurface specified by `vdpSurface` for access by CUDA. A handle to the registered object is returned as `pCudaResource`. The surface's intended usage is specified using `flags`, as follows: + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA. This is the default value. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY: Specifies that CUDA will not write to this resource. + + * CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD: Specifies that CUDA will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved. + + +The VdpVideoSurface is presented as an array of subresources that may be accessed using pointers returned by cuGraphicsSubResourceGetMappedArray. The exact number of valid `arrayIndex` values depends on the VDPAU surface format. The mapping is shown in the table below. `mipLevel` must be 0. + +CUresult cuVDPAUCtxCreate ( CUcontext* pCtx, unsigned int flags, CUdevice device, VdpDevice vdpDevice, VdpGetProcAddress* vdpGetProcAddress ) + + +Create a CUDA context for interoperability with VDPAU. + +###### Parameters + +`pCtx` + \- Returned CUDA context +`flags` + \- Options for CUDA context creation +`device` + \- Device on which to create the context +`vdpDevice` + \- The VdpDevice to interop with +`vdpGetProcAddress` + \- VDPAU's VdpGetProcAddress function pointer + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY + +###### Description + +Creates a new CUDA context, initializes VDPAU interoperability, and associates the CUDA context with the calling thread. It must be called before performing any other VDPAU interoperability operations. It may fail if the needed VDPAU driver facilities are not available. For usage of the `flags` parameter, see cuCtxCreate(). + +CUresult cuVDPAUGetDevice ( CUdevice* pDevice, VdpDevice vdpDevice, VdpGetProcAddress* vdpGetProcAddress ) + + +Gets the CUDA device associated with a VDPAU device. + +###### Parameters + +`pDevice` + \- Device associated with vdpDevice +`vdpDevice` + \- A VdpDevice handle +`vdpGetProcAddress` + \- VDPAU's VdpGetProcAddress function pointer + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*pDevice` the CUDA device associated with a `vdpDevice`, if applicable. + + diff --git a/content/cuda/docs/driver-version/DOC.md b/content/cuda/docs/driver-version/DOC.md new file mode 100644 index 00000000..5bd8212b --- /dev/null +++ b/content/cuda/docs/driver-version/DOC.md @@ -0,0 +1,40 @@ +--- +name: driver-version +description: '**Source:** group__CUDA__VERSION.html#group__CUDA__VERSION' +metadata: + languages: cuda + versions: '13.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,driver-api,api +--- + +# 6.4. Version Management + +**Source:** group__CUDA__VERSION.html#group__CUDA__VERSION + + +### Functions + +CUresult cuDriverGetVersion ( int* driverVersion ) + + +Returns the latest CUDA version supported by driver. + +###### Parameters + +`driverVersion` + \- Returns the CUDA driver version + +###### Returns + +CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE + +###### Description + +Returns in `*driverVersion` the version of CUDA supported by the driver. The version is returned as (1000 * major + 10 * minor). For example, CUDA 9.2 would be represented by 9020. + +This function automatically returns CUDA_ERROR_INVALID_VALUE if `driverVersion` is NULL. + + diff --git a/content/cuda/docs/driver/DOC.md b/content/cuda/docs/driver/DOC.md new file mode 100644 index 00000000..ee388665 --- /dev/null +++ b/content/cuda/docs/driver/DOC.md @@ -0,0 +1,73 @@ +--- +name: driver +description: "CUDA Driver API essentials: explicit context management, module loading, and kernel launch." +metadata: + languages: "cpp" + versions: "12.4" + revision: 1 + updated-on: "2026-03-18" + source: community + tags: "cuda,gpu,kernel,driver,api,ptx" +--- + +# CUDA Driver API (C++) + +Use the Driver API when you need explicit control over contexts, modules, and dynamic kernel loading. It is lower-level than the Runtime API. + +## Basic Flow + +1. Initialize the driver and pick a device +2. Create a context +3. Load a module (PTX or cubin) +4. Get the kernel function +5. Allocate memory and launch +6. Cleanup + +```cpp +#include +#include + +int main() { + CUdevice dev; + CUcontext ctx; + cuInit(0); + cuDeviceGet(&dev, 0); + cuCtxCreate(&ctx, 0, dev); + + CUmodule module; + CUfunction func; + cuModuleLoad(&module, "kernel.ptx"); + cuModuleGetFunction(&func, module, "my_kernel"); + + CUdeviceptr d_out; + cuMemAlloc(&d_out, 1024); + + void* args[] = { &d_out }; + cuLaunchKernel(func, + 1, 1, 1, + 256, 1, 1, + 0, 0, args, 0); + + cuMemFree(d_out); + cuModuleUnload(module); + cuCtxDestroy(ctx); + return 0; +} +``` + +## Core Driver APIs + +- Context: `cuInit`, `cuDeviceGet`, `cuCtxCreate`, `cuCtxDestroy` +- Module: `cuModuleLoad`, `cuModuleLoadData`, `cuModuleGetFunction` +- Memory: `cuMemAlloc`, `cuMemFree`, `cuMemcpyHtoD`, `cuMemcpyDtoH` +- Launch: `cuLaunchKernel` + +## Common Pitfalls + +- Forgetting to create a context before module operations +- Using mismatched kernel names between PTX and host code +- Not checking return codes (Driver API returns `CUresult`) + +## Related Topics + +- Module loading details: `references/module-loading.md` diff --git a/content/cuda/docs/driver/references/module-loading.md b/content/cuda/docs/driver/references/module-loading.md new file mode 100644 index 00000000..c7634b1a --- /dev/null +++ b/content/cuda/docs/driver/references/module-loading.md @@ -0,0 +1,19 @@ +# CUDA Driver Module Loading + +You can load modules from: + +- PTX text (JIT compiled): `cuModuleLoadData` or `cuModuleLoadDataEx` +- Cubin file (precompiled): `cuModuleLoad` + +Common patterns: + +```cpp +CUmodule module = nullptr; +CUresult r = cuModuleLoad(&module, "kernel.cubin"); +// or +r = cuModuleLoadData(&module, ptx_string); +``` + +Notes: +- `cuModuleLoadDataEx` lets you pass JIT options for diagnostics or optimization. +- Always unload modules with `cuModuleUnload` when done. diff --git a/content/cuda/docs/dynamic-parallelism/DOC.md b/content/cuda/docs/dynamic-parallelism/DOC.md new file mode 100644 index 00000000..068410f6 --- /dev/null +++ b/content/cuda/docs/dynamic-parallelism/DOC.md @@ -0,0 +1,65 @@ +--- +name: dynamic-parallelism +description: "CUDA Dynamic Parallelism essentials: device-side kernel launch semantics, synchronization behavior, and memory-space constraints." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,dynamic-parallelism,cdp,device-side-launch,child-kernel,cudaDeviceSynchronize,memory-coherence" +--- + +# CUDA Dynamic Parallelism (C++) + +Use this page when kernels launch other kernels on the device. + +## What It Is + +Dynamic Parallelism (CDP) lets device code launch child grids. + +- parent and child execute on the device +- launch configuration is provided from device code +- useful for irregular recursion-like or adaptive decomposition patterns + +## Core Semantics + +- child launch is asynchronous with respect to the launching thread by default +- synchronization choices in parent code determine when child results are consumed +- launch overhead is non-trivial; avoid using CDP for tiny kernels in hot loops + +## Memory-Space Coherence + +Key memory-space rule from CUDA docs: + +- parent and child share global/constant memory +- local and shared memory are private to their respective thread/block contexts + +Do not assume parent shared memory is visible to child kernels. + +## Typical Use Cases + +- adaptive refinement +- irregular tree/graph traversal +- work generation discovered during device execution + +For regular dense workloads, host-side launch or CUDA Graphs is usually better. + +## Common Pitfalls + +- launching too many tiny child kernels +- misunderstanding parent/child visibility boundaries +- relying on implicit ordering that is not guaranteed + +## Related Topics + +- CUDA Graphs: `../cuda-graphs/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` +- Memory fences and ordering: `../memory-fences-and-ordering/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, Dynamic Parallelism: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, memory coherence in CDP: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/error-handling-and-debug-build/DOC.md b/content/cuda/docs/error-handling-and-debug-build/DOC.md new file mode 100644 index 00000000..e3453b5a --- /dev/null +++ b/content/cuda/docs/error-handling-and-debug-build/DOC.md @@ -0,0 +1,75 @@ +--- +name: error-handling-and-debug-build +description: "CUDA error-handling and debug-build essentials: launch checks, sync checks, debug flags, and diagnosis workflow." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,error-handling,cudaGetLastError,cudaPeekAtLastError,cudaDeviceSynchronize,debug-build,nvcc,-G,lineinfo" +--- + +# CUDA Error Handling And Debug Build (C++) + +Use this page for practical correctness diagnostics in CUDA applications. + +## Two-Step Error Check Pattern + +Always separate: + +1. launch configuration/API errors +2. runtime execution errors + +Typical pattern: + +```cpp +kernel<<>>(...); +cudaError_t e1 = cudaGetLastError(); // launch/config error +cudaError_t e2 = cudaDeviceSynchronize(); // execution error +``` + +Use stream-specific synchronization when possible instead of global device sync. + +## Why This Matters + +- some errors are detected at launch +- others appear only when kernel execution actually runs + +Checking only one side can hide failures. + +## Debug Build Basics + +For debugging kernels, common compile choices include: + +- device debug info (`-G`) for heavy debug sessions +- line info (`-lineinfo`) for profiling-friendly symbol mapping + +Debug builds can change optimization and performance; do not compare debug and release timings directly. + +## Runtime Diagnostics + +- use descriptive error strings with `cudaGetErrorString` +- include kernel name / input shape in logs +- fail fast in development paths to avoid cascading corruption + +## Practical Workflow + +1. reproduce with smallest failing input. +2. enable strict launch+sync checks. +3. switch to debug-oriented build flags if needed. +4. profile or inspect only after correctness is stable. + +## Related Topics + +- Runtime overview: `../runtime/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` +- NVTX workflow: `../nvtx-and-profiling-workflow/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Runtime API, error handling APIs: https://docs.nvidia.com/cuda/cuda-runtime-api/index.html +- CUDA C++ Best Practices Guide, correctness and debugging guidance: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- NVCC documentation (debug flags): https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/execution-model/DOC.md b/content/cuda/docs/execution-model/DOC.md new file mode 100644 index 00000000..bbe48a0c --- /dev/null +++ b/content/cuda/docs/execution-model/DOC.md @@ -0,0 +1,93 @@ +--- +name: execution-model +description: "CUDA execution model essentials: warps, SM scheduling, divergence, and how ordinary arithmetic paths differ from Tensor Core paths." +metadata: + languages: "cpp" + versions: "13.1" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,execution-model,simt,warp,sm,scheduler,divergence,cuda-core,tensor-core" +--- + +# CUDA Execution Model (C++) + +Use this page to understand how CUDA threads are grouped and scheduled, and how ordinary arithmetic execution differs from Tensor Core execution. + +## SIMT Basics + +CUDA executes threads in groups of 32 called warps. + +- a warp is the main scheduling unit inside an SM +- threads in a warp conceptually execute the same kernel code in SIMT style +- divergence inside a warp reduces efficiency because different branch paths are executed separately + +This is why block sizes are usually chosen as multiples of 32. + +## SM-Level Scheduling + +An SM manages many resident warps and switches among them to hide latency. + +- when one warp stalls on memory or dependencies, the SM can issue instructions from another ready warp +- latency hiding depends on both occupancy and instruction-level parallelism +- exact scheduler and execution-unit details vary by architecture + +## What Developers Mean By "CUDA Core" + +NVIDIA documentation usually talks about instruction throughput, FP32/INT32/FP64 units, and SM execution resources rather than a CUDA C++ API called "CUDA Core". + +In practice, developers use "CUDA Core path" to mean: + +- ordinary arithmetic instructions such as FP32 / INT32 math +- standard SIMT execution on the SM's general arithmetic pipelines +- kernels that do not explicitly target Tensor Core matrix instructions + +This is an interpretation of the hardware execution model, not a separate CUDA C++ programming interface. + +## Tensor Core Path + +Tensor Cores are specialized matrix-multiply-accumulate units. + +- they are exposed in CUDA C++ through warp-level matrix APIs such as `nvcuda::wmma` +- they are exposed in PTX through matrix instructions such as `wgmma` +- they are most relevant when the computation naturally maps to small matrix tiles and supported types/layouts + +If a kernel is written using ordinary scalar or vector arithmetic, it is usually on the ordinary SM arithmetic path rather than the Tensor Core path. + +## Divergence And Utilization + +Ordinary arithmetic kernels often lose efficiency because of: + +- warp divergence +- uncoalesced memory access +- bank conflicts +- low occupancy or long dependency chains + +Tensor Core kernels add extra constraints: + +- warp-wide participation +- shape / layout / alignment restrictions +- staging and synchronization overhead around fragments or async pipelines + +## Rule Of Thumb + +- generic elementwise, reduction, indexing-heavy, and control-heavy kernels usually live on the ordinary arithmetic path +- dense matrix-multiply-like kernels are the main candidates for Tensor Core acceleration + +## Related Topics + +- CUDA Core path: `../cuda-core/DOC.md` +- Compute throughput model: `../compute-throughput/DOC.md` +- Occupancy tuning: `../occupancy/DOC.md` +- Warp-level primitives: `../warp-primitives/DOC.md` +- Tensor Core API usage: `../tensor-cores/DOC.md` +- WMMA kernel patterns: `../wmma-kernel-patterns/DOC.md` +- CUDA Core vs Tensor Core path selection: `../cuda-core-vs-tensor-core-path-selection/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Programming Guide, programming model and warps: https://docs.nvidia.com/cuda/archive/13.1.1/cuda-programming-guide/01-introduction/programming-model.html +- CUDA Programming Guide, SIMT execution model: https://docs.nvidia.com/cuda/cuda-programming-guide/03-advanced/advanced-kernel-programming.html +- Turing Tuning Guide, SM scheduling and execution resources: https://docs.nvidia.com/cuda/archive/12.4.0/turing-tuning-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/fallback-strategies-and-capability-detection/DOC.md b/content/cuda/docs/fallback-strategies-and-capability-detection/DOC.md new file mode 100644 index 00000000..fa0fe900 --- /dev/null +++ b/content/cuda/docs/fallback-strategies-and-capability-detection/DOC.md @@ -0,0 +1,63 @@ +--- +name: fallback-strategies-and-capability-detection +description: "CUDA capability detection and fallback essentials: feature probes, architecture guards, and safe runtime degradation paths." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,capability-detection,fallback,feature-probe,sm-version,graceful-degradation,runtime-guards" +--- + +# Fallback Strategies And Capability Detection (C++) + +Use this page when kernels depend on architecture-specific features (Tensor Cores, clusters, async paths, etc.). + +## Capability Detection + +Query device properties at runtime and gate features explicitly. + +Typical inputs: + +- compute capability (SM version) +- shared-memory limits +- cooperative/cluster support +- peer access/topology capabilities + +Do not infer support from GPU name strings. + +## Fallback Hierarchy + +Define ordered execution paths: + +1. preferred fast path (feature-rich) +2. compatible optimized fallback +3. conservative correctness fallback + +All paths should be tested; fallback code is production code. + +## Guardrail Principles + +- fail fast for unsupported required features +- degrade gracefully for optional accelerations +- log selected path for observability and debugging + +## Common Mistakes + +- fallback exists but is untested +- path selection logic diverges from documented requirements +- silent fallback causes unnoticed performance regressions + +## Related Topics + +- Build and ABI compatibility: `../build-and-abi-compatibility/DOC.md` +- Multi-GPU and peer access: `../multi-gpu-and-peer-access/DOC.md` +- Production readiness checklist: `../production-readiness-checklist/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Runtime API, device property query interfaces: https://docs.nvidia.com/cuda/cuda-runtime-api/index.html +- CUDA C++ Programming Guide, architecture/capability-dependent feature context: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/flash-attention-implementation-patterns/DOC.md b/content/cuda/docs/flash-attention-implementation-patterns/DOC.md new file mode 100644 index 00000000..9c07e22d --- /dev/null +++ b/content/cuda/docs/flash-attention-implementation-patterns/DOC.md @@ -0,0 +1,73 @@ +--- +name: flash-attention-implementation-patterns +description: "FlashAttention design patterns: online softmax scaling, SRAM-aware tiling, causality masking, and recomputation techniques." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,flash-attention,attention,online-softmax,tiling,shared-memory,recomputation,gemm" +--- + +# Flash Attention Implementation Patterns (C++) + +Use this page as a structural guide to implementing exact, memory-efficient attention operations (FlashAttention-style) in CUDA. + +## The Memory Bottleneck in Attention + +Standard attention materializes the $N \times N$ attention matrix $S = QK^T$ in global memory. For large sequence lengths $N$, the global-memory traffic of writing and reading $S$ outweighs the arithmetic cost. + +FlashAttention keeps the intermediate $S$ and $P = \text{softmax}(S)$ entirely within shared memory (SRAM), drastically cutting memory bandwidth requirements. + +## Online Softmax Formulation + +To compute the softmax without scanning the entire row of $S$ at once (which exceeds shared memory capacity), you must use the online safe softmax trick: + +- Track the running block maximum: $m_{\text{new}} = \max(m_{\text{old}}, \max(S_{\text{block}}))$ +- Track the running denominator: $l_{\text{new}} = l_{\text{old}} \cdot e^{m_{\text{old}} - m_{\text{new}}} + \sum e^{S_{\text{block}} - m_{\text{new}}}$ +- Rescale the running output accumulator $O$ when the maximum changes. + +## Double GEMM Pipeline + +A standard FlashAttention block does: + +1. **GEMM 1:** Load a tile of $Q$ and a tile of $K$. Compute tile of $S = QK^T$. +2. **Masking & Scaling:** Apply causal masks and scale by $1/\sqrt{d}$. +3. **Softmax:** Update running online softmax metrics ($m, l$). Compute tile of $P = e^{S - m_{new}}$. +4. **GEMM 2:** Load a tile of $V$. Compute $O = O \cdot \text{scale} + P V$. + +Both GEMM operations involve the accumulator in registers/shared memory. + +## SRAM Layout and Occupancy + +The primary constraint is shared memory size: +- You must fit tiles of $Q$, $K$, and $V$ in shared memory. +- $Q$ usually stays resident in the outer loop, while $K$ and $V$ stream through the inner loop. +- To maintain sufficient warp occupancy, optimize tile sizes (e.g., $128 \times 64$ or $64 \times 128$) to leave room for at least 2 thread blocks per SM. + +## Recomputation on the Backward Pass + +Instead of saving the massive $S$ or $P$ matrices for the backward pass, FlashAttention recalculates them during the backward kernel. +- State saved to global memory: only the softmax normalization constants (Log-Sum-Exp, $L$) and output $O$. +- During backward evaluation, knowing $L$ allows exact re-derivation of $P$ using only the query/key memory bandwidth. + +## Thread-block and Warp Assignment + +- Assign the sequence dimension of $Q$ across thread blocks. +- Within a block, parallelize the computation of $QK^T$ rows across warps. +- Use the `mma.sync` or `wgmma` PTX paths for the heavy matrix multiplications. + +## Related Topics + +- Shared memory layout: `../shared-memory/DOC.md` +- Tensor Core pipeline patterns: `../tensor-core-pipeline-patterns/DOC.md` +- PTX WGMMA: `../ptx/instructions/wgmma/DOC.md` +- Paged attention: `../paged-attention-and-vllm-integration/DOC.md` + +## Official Source Links (Fact Check) + +- FlashAttention Original Paper / Algorithm: https://arxiv.org/abs/2205.14135 +- FlashAttention-2 Algorithm: https://arxiv.org/abs/2307.08691 + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/fp8-training-and-inference-playbook/DOC.md b/content/cuda/docs/fp8-training-and-inference-playbook/DOC.md new file mode 100644 index 00000000..b157fcc5 --- /dev/null +++ b/content/cuda/docs/fp8-training-and-inference-playbook/DOC.md @@ -0,0 +1,67 @@ +--- +name: fp8-training-and-inference-playbook +description: "FP8 full stack usage playbook: E4M3 vs E5M2 formats, precision scaling factors, and accumulation hazards." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,fp8,e4m3,e5m2,training,inference,tensor-cores,llm,precision" +--- + +# FP8 Training and Inference Playbook + +Use this page to navigate the complexities of using 8-bit floating point formats (FP8) effectively on Hopper (SM90) and Blackwell (SM100/120) architectures. + +## The Two Sub-Formats + +FP8 isn't a single format; it consists of two distinct encodings defined by IEEE / OCP: + +- **E4M3:** (4 exponent bits, 3 mantissa bits). Smaller dynamic range, higher precision. Exclusively used for forward-pass activations and weights during inference. +- **E5M2:** (5 exponent bits, 2 mantissa bits). Larger dynamic range, lower precision. Mirrors the exponent structure of FP16. Used primarily for gradients in the backward pass during training. + +## Tensor Cores and Formats + +Tensor Core instructions (`mma` / `wgmma`) on architectures supporting FP8 support distinct rules: +- Inputs can be typed as either E4M3 or E5M2. +- The output (accumulator) is always a higher precision format (FP32 or FP16). +- FP8 Tensor Cores provide exactly 2x the throughput of FP16/BF16 Tensor Cores on Hopper/Blackwell. + +## Dynamic Scaling Mechanics + +FP8 requires an external scaling factor per tensor to avoid underflow or overflow. +When executing an FP8 GEMM ($D = \alpha \cdot A \cdot B + \beta \cdot C$): +1. **Host/Pre-pass Tracking:** Compute the absolute maximum of the upstream tensor. +2. **Quantization:** Scale the values so the maximum fits just under the maximum representable value of the FP8 format (e.g., 448 for E4M3). +3. **GEMM:** Perform the multiplied accumulating in FP32. +4. **Rescaling:** De-quantize the FP32 accumulator using the scale factors before writing back, or fuse with the next quantization step. + +CUDA APIs (like `cublasLt`) often accept the scaling factors as independent parameters. If writing custom kernels, you must multiply the factors explicitly before output. + +## Storage Types in C++ + +CUDA C++ provides intrinsic types for FP8. +- Include `` +- Types: `__nv_fp8_e4m3` and `__nv_fp8_e5m2` + +*Warning:* Arithmetic operations (like `+`, `*`) are not defined natively on these types by the compiler. They are strictly storage types. You must cast to `half` or `float` to do math outside of Tensor Core instructions. + +## The Delayed Scaling Strategy + +Calculating the max value of a tensor blocks the pipeline. A common strategy in FP8 training is "Delayed Scaling": +- Use the scale factor derived from the maximum of step $t-1$ to quantize step $t$. +- The history proves sufficient for stabilization in most LLM training regimens, avoiding synchronous reduction bottlenecks in the critical path. + +## Related Topics + +- Blackwell MX numeric formats: `../blackwell-mx-numerical-formats/DOC.md` +- Numerics and precision: `../numerics-and-precision/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- Transformer Engine Documentation (NVIDIA): https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/index.html +- CUDA Math API - FP8: https://docs.nvidia.com/cuda/cuda-math-api/cuda_math_api/group__CUDA__MATH__FP8.html + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/fused-kernel-design-patterns/DOC.md b/content/cuda/docs/fused-kernel-design-patterns/DOC.md new file mode 100644 index 00000000..ec01fb56 --- /dev/null +++ b/content/cuda/docs/fused-kernel-design-patterns/DOC.md @@ -0,0 +1,75 @@ +--- +name: fused-kernel-design-patterns +description: "CUDA fused-kernel design essentials: when fusion helps, when it hurts, and practical patterns for memory-traffic reduction." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,fusion,fused-kernel,memory-traffic,register-pressure,launch-overhead,epilogue-fusion" +--- + +# CUDA Fused-Kernel Design Patterns (C++) + +Use this page when deciding whether to combine multiple operations into one kernel. + +## Why Fusion Helps + +Fusion can improve performance by: + +- reducing global-memory round trips +- reducing kernel-launch overhead +- keeping intermediate values in registers/shared memory + +## Why Fusion Can Hurt + +Over-fusion can degrade performance due to: + +- register pressure and spills +- lower occupancy +- larger instruction footprint +- harder scheduling and poorer maintainability + +Fusion is beneficial only when memory/launch savings outweigh these costs. + +## Common Fusion Patterns + +- elementwise chain fusion (A->B->C) +- reduction + lightweight post-processing +- GEMM epilogue fusion (bias/add/activation) +- load-transform-store pipelines with shared-memory staging + +## Practical Decision Rule + +Fuse when: + +- intermediate tensors are large +- extra kernel boundaries dominate runtime +- the fused kernel remains resource-balanced + +Do not fuse when: + +- each op is already compute-heavy and well-optimized +- fusion introduces high register pressure or complex control divergence + +## Validation Workflow + +1. benchmark unfused baseline. +2. fuse one boundary at a time. +3. profile register usage, spills, occupancy, and bandwidth. +4. keep fusion only where end-to-end latency improves. + +## Related Topics + +- Coalescing: `../coalescing/DOC.md` +- Occupancy: `../occupancy/DOC.md` +- Launch bounds and registers: `../launch-bounds-and-registers/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, memory and launch optimization context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA C++ Programming Guide, execution and memory behavior background: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/incident-response-and-rollback-playbook/DOC.md b/content/cuda/docs/incident-response-and-rollback-playbook/DOC.md new file mode 100644 index 00000000..adcfc788 --- /dev/null +++ b/content/cuda/docs/incident-response-and-rollback-playbook/DOC.md @@ -0,0 +1,68 @@ +--- +name: incident-response-and-rollback-playbook +description: "CUDA incident-response essentials: triage, rollback criteria, mitigation levers, and post-incident hardening steps." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,incident,response,rollback,mitigation,triage,oncall,postmortem" +--- + +# Incident Response And Rollback Playbook (C++) + +Use this page when a CUDA optimization regresses latency, correctness, or stability in production. + +## Fast Triage Checklist + +1. identify blast radius (which models/tasks/hardware). +2. classify failure mode (correctness, latency, crash, OOM, timeout). +3. isolate recent kernel/config/toolchain changes. +4. determine safe rollback target. + +## Rollback Criteria + +Rollback immediately when: + +- correctness deviations exceed policy +- crash rate or timeout rate breaches SLO +- latency regression is severe and sustained + +Do not wait for perfect root-cause certainty before restoring service. + +## Mitigation Levers + +- disable risky fast paths via feature flags +- switch to known-safe kernel variant +- reduce batch size or concurrency temporarily +- force conservative precision/mode where necessary + +## Evidence Collection + +- capture failing inputs and minimal repro shapes +- record selected kernel path/capability info +- collect timeline + kernel profiles for before/after comparison + +## Post-Incident Hardening + +- add regression tests for the triggering pattern +- add rollout guardrails (canary, staged enablement) +- improve observability for path-selection and error counters +- document lessons and owner actions + +## Related Topics + +- Production readiness checklist: `../production-readiness-checklist/DOC.md` +- Regression testing and CI: `../regression-testing-and-ci/DOC.md` +- NVTX profiling workflow: `../nvtx-and-profiling-workflow/DOC.md` +- Fallback strategies: `../fallback-strategies-and-capability-detection/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide (verification + optimization workflow context): https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- Nsight Systems / Nsight Compute docs for triage instrumentation: + - https://docs.nvidia.com/nsight-systems/UserGuide/index.html + - https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/input-shape-specialization-and-autotuning/DOC.md b/content/cuda/docs/input-shape-specialization-and-autotuning/DOC.md new file mode 100644 index 00000000..575e5ce2 --- /dev/null +++ b/content/cuda/docs/input-shape-specialization-and-autotuning/DOC.md @@ -0,0 +1,60 @@ +--- +name: input-shape-specialization-and-autotuning +description: "CUDA shape specialization and autotuning essentials: variant spaces, compile/runtime dispatch, and robust tuning workflows." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,autotuning,shape-specialization,dispatch,variant-selection,tile-size,benchmarking" +--- + +# Input Shape Specialization And Autotuning (C++) + +Use this page when one kernel configuration cannot serve all input shapes efficiently. + +## Why Specialization Is Needed + +Kernel performance often depends on: + +- shape geometry +- stride/layout +- precision mode +- architecture/resource limits + +A single static launch/config choice is usually suboptimal across broad workloads. + +## Specialization Strategies + +- compile-time variants for known shape classes +- runtime dispatch by shape buckets +- autotuned parameter sets (tile sizes, block sizes, staging depth) + +Keep variant count bounded to control maintenance overhead. + +## Autotuning Workflow + +1. define search space (block/tile/stage variants). +2. benchmark representative shape corpus. +3. store winning config per shape bucket and hardware class. +4. validate correctness and stability of selected variants. + +## Robustness Rules + +- never tune on one micro-benchmark only +- include tail shapes and borderline sizes +- preserve safe fallback when no tuned profile matches + +## Related Topics + +- Benchmarking methodology: `../benchmarking-methodology/DOC.md` +- Fused kernel patterns: `../fused-kernel-design-patterns/DOC.md` +- Build and ABI compatibility: `../build-and-abi-compatibility/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, empirical optimization guidance: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA C++ Programming Guide, launch/resource model background: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/kernel-api-design-guidelines/DOC.md b/content/cuda/docs/kernel-api-design-guidelines/DOC.md new file mode 100644 index 00000000..02e795d1 --- /dev/null +++ b/content/cuda/docs/kernel-api-design-guidelines/DOC.md @@ -0,0 +1,67 @@ +--- +name: kernel-api-design-guidelines +description: "CUDA kernel API design essentials: parameter contracts, shape/stride conventions, launch invariants, and forward-compatible interface choices." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,api-design,shape,stride,contracts,launch-invariants,interface,maintainability" +--- + +# CUDA Kernel API Design Guidelines (C++) + +Use this page when defining or refactoring kernel-facing interfaces for long-term maintainability. + +## Interface Contracts First + +Document and enforce: + +- tensor shape expectations +- stride/layout assumptions +- alignment requirements +- supported dtype/precision combinations + +Unstated assumptions become production bugs. + +## Parameter Design + +Prefer explicit parameters over hidden globals: + +- dimensions (`n`, `h`, `w`, etc.) +- leading dimensions/strides +- flags that affect algorithmic paths + +Keep argument ordering stable and predictable across related kernels. + +## Launch Invariants + +Define launch invariants close to API: + +- valid block size range +- shared-memory requirements +- grid coverage model + +Validate invariants early in host code where possible. + +## Versioning Mindset + +If a kernel API is reused across modules: + +- avoid breaking parameter semantics silently +- add new fields/options in backward-compatible ways +- keep deprecation path explicit + +## Related Topics + +- Data layout and alignment: `../data-layout-and-alignment/DOC.md` +- Build and ABI compatibility: `../build-and-abi-compatibility/DOC.md` +- Regression testing and CI: `../regression-testing-and-ci/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, kernel launch and execution model background: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, software design and optimization workflow context: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/kernel-bottleneck-diagnosis-workflow/DOC.md b/content/cuda/docs/kernel-bottleneck-diagnosis-workflow/DOC.md new file mode 100644 index 00000000..9417333f --- /dev/null +++ b/content/cuda/docs/kernel-bottleneck-diagnosis-workflow/DOC.md @@ -0,0 +1,83 @@ +--- +name: kernel-bottleneck-diagnosis-workflow +description: "Kernel bottleneck diagnosis workflow: classify memory-bound vs compute-bound vs launch-bound, then choose targeted optimization paths." +metadata: + languages: "cpp" + versions: "2024.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,bottleneck,diagnosis,workflow,memory-bound,compute-bound,launch-bound,profiling,nsight" +--- + +# Kernel Bottleneck Diagnosis Workflow (C++) + +Use this page when you need a repeatable way to decide which optimization direction is actually relevant. + +## Classification First + +Classify each hot kernel into one of three primary classes: + +- memory-bound +- compute-bound +- launch/orchestration-bound + +Do this with profiling evidence, not intuition. + +## Evidence Signals + +Memory-bound indicators: + +- high memory-pipeline utilization with low arithmetic utilization +- strong sensitivity to coalescing/layout changes + +Compute-bound indicators: + +- arithmetic pipeline pressure dominates +- throughput improves mainly with instruction-mix or scheduling improvements + +Launch-bound indicators: + +- many short kernels +- significant CPU/launch overhead and weak overlap + +## Optimization Routing + +If memory-bound: + +- prioritize coalescing, reuse, layout, and staging fixes. + +If compute-bound: + +- optimize instruction mix, occupancy/ILP balance, and path selection (CUDA Core vs Tensor Core). + +If launch-bound: + +- reduce launch count, fuse kernels where valid, and evaluate CUDA Graphs. + +## Guardrails + +- Reclassify after each major optimization; bottleneck class can change. +- Keep correctness and numerical checks active during performance iteration. +- Record profiler snapshots per step to avoid regression ambiguity. + +## Related Topics + +- Performance debugging: `../performance-debugging/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Memory-bound optimization playbook: `../memory-bound-kernel-optimization-playbook/DOC.md` +- Compute-bound optimization playbook: `../compute-bound-kernel-optimization-playbook/DOC.md` +- Launch-bound optimization playbook: `../launch-bound-optimization-playbook/DOC.md` +- Nsight metrics interpretation cheatsheet: `../nsight-metrics-interpretation-cheatsheet/DOC.md` +- CUDA Core optimization checklist: `../cuda-core-optimization-checklist/DOC.md` +- CUDA Core vs Tensor Core path selection: `../cuda-core-vs-tensor-core-path-selection/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` +- Fused kernel design patterns: `../fused-kernel-design-patterns/DOC.md` + +## Official Source Links (Fact Check) + +- Nsight Systems User Guide: https://docs.nvidia.com/nsight-systems/UserGuide/index.html +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html +- CUDA C++ Best Practices Guide: https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/launch-bound-optimization-playbook/DOC.md b/content/cuda/docs/launch-bound-optimization-playbook/DOC.md new file mode 100644 index 00000000..fbc3a7ee --- /dev/null +++ b/content/cuda/docs/launch-bound-optimization-playbook/DOC.md @@ -0,0 +1,64 @@ +--- +name: launch-bound-optimization-playbook +description: "Launch-bound optimization playbook: reducing launch overhead, improving overlap, and deciding when to use fusion or CUDA Graphs." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,launch-bound,optimization,launch-overhead,cuda-graphs,fusion,stream-overlap,orchestration" +--- + +# Launch-Bound Optimization Playbook (C++) + +Use this page when many short kernels or orchestration overhead dominate runtime. + +## Primary Objectives + +- Reduce launch overhead. +- Increase useful overlap between copy and compute. +- Simplify scheduling structure for repeated execution patterns. + +## High-Impact Levers + +- Reduce kernel launch count where semantically safe. +- Apply kernel fusion when it improves end-to-end cost. +- Evaluate CUDA Graphs for repetitive execution DAGs. +- Improve stream/event structure to avoid accidental serialization. + +## Triage Sequence + +1. Confirm launch/orchestration bottleneck in timeline profiling. +2. Identify high-frequency short kernels and synchronization hotspots. +3. Test fusion and graph capture candidates. +4. Reprofile overlap and CPU-side launch cost. + +## Common Failure Modes + +- Fusion increases register pressure and hurts throughput. +- Graph capture applied to highly dynamic control flow without clear gain. +- Stream dependencies unintentionally serialize work. + +## Verification Checklist + +- CPU launch overhead decreases. +- Timeline overlap improves. +- Overall runtime drops on production traces, not just micro-tests. + +## Related Topics + +- CUDA Graphs: `../cuda-graphs/DOC.md` +- Fused kernel design patterns: `../fused-kernel-design-patterns/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` +- NVTX and profiling workflow: `../nvtx-and-profiling-workflow/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA Graphs programming guidance: https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- Nsight Systems User Guide: https://docs.nvidia.com/nsight-systems/UserGuide/index.html +- CUDA C++ Best Practices Guide: https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/launch-bounds-and-registers/DOC.md b/content/cuda/docs/launch-bounds-and-registers/DOC.md new file mode 100644 index 00000000..cfa16467 --- /dev/null +++ b/content/cuda/docs/launch-bounds-and-registers/DOC.md @@ -0,0 +1,69 @@ +--- +name: launch-bounds-and-registers +description: "CUDA launch bounds and register-pressure essentials: __launch_bounds__, occupancy tradeoffs, and spill-aware tuning." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,launch-bounds,__launch_bounds__,register-pressure,spills,occupancy,maxrregcount" +--- + +# CUDA Launch Bounds And Registers (C++) + +Use this page when kernel performance depends on register pressure and block residency. + +## What `__launch_bounds__` Does + +`__launch_bounds__(maxThreadsPerBlock, minBlocksPerMultiprocessor)` gives the compiler launch-time assumptions. + +- `maxThreadsPerBlock` constrains the intended block size +- optional `minBlocksPerMultiprocessor` asks the compiler to keep enough resources for a target block residency + +This can change register allocation decisions and instruction scheduling. + +## Why It Matters + +Register pressure directly affects occupancy. + +- too many registers per thread can reduce active blocks/warps +- too few registers can cause spills to local memory + +So tuning is a balance: occupancy gain versus spill cost. + +## Practical Tuning Pattern + +1. Start from correctness and baseline performance. +2. Inspect occupancy and local-memory traffic in Nsight Compute. +3. Try `__launch_bounds__` with realistic block sizes. +4. Re-measure runtime, spills, and achieved occupancy. +5. Keep the setting only if end-to-end time improves. + +## `-maxrregcount` Caution + +Compiler flag `-maxrregcount` can cap registers globally, but it is blunt. + +- it may improve occupancy +- it can also increase spills and hurt performance + +Prefer targeted kernel-level tuning (`__launch_bounds__`) before applying global caps. + +## Common Mistakes + +- optimizing for occupancy percentage alone +- forcing low register count without checking spill metrics +- setting launch bounds that do not match actual launch configuration + +## Related Topics + +- Occupancy tuning: `../occupancy/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, launch bounds: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, occupancy and execution model discussion: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/llm-decoding-gemv-optimization/DOC.md b/content/cuda/docs/llm-decoding-gemv-optimization/DOC.md new file mode 100644 index 00000000..450834b2 --- /dev/null +++ b/content/cuda/docs/llm-decoding-gemv-optimization/DOC.md @@ -0,0 +1,61 @@ +--- +name: llm-decoding-gemv-optimization +description: "LLM Autoregressive decoding optimizations: Split-K GEMV, persistent thread blocks, and memory-bandwidth saturation techniques." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,gemv,llm,decoding,split-k,autoregressive,persistent-kernel,memory-bound" +--- + +# LLM Decoding Phase Optimization (GEMV) + +Use this page when optimizing the auto-regressive decoding phase of Large Language Models, which is fundamentally constrained by memory bandwidth rather than compute. + +## GEMV vs. GEMM Mechanics + +During the prefill phase (prompt processing), the operation is a GEMM (Matrix-Matrix), which is compute-bound. +During the decoding phase (batch_size = 1), generating the next token is a GEMV (Matrix-Vector) operation. + +- **GEMM Math:** $O = Q \cdot K^T$. Tensor Cores are fully utilized. +- **GEMV Math:** $O = q \cdot K^T$. Tensor Cores may be severely underutilized. The SM spends most of its time waiting for $K$ and $V$ weights to arrive from global memory. + +## The Under-Occupancy Problem + +In a standard batch-size=1 GEMV, the computation might only launch enough thread blocks to cover the attention heads. On a GPU like the H100 with 132 SMs, launching only 32 thread blocks (for 32 heads) leaves 100 SMs completely idle. + +## Split-K Optimization Strategy + +To saturate the GPU, you must parallelize across the reduction dimension ($K$, representing the sequence length of the KV Cache). + +**How it works:** +1. Split the KV cache sequence for a single head across multiple thread blocks (e.g., 4 blocks per head). +2. Each block computes a partial sum (vector dot product) for its slice of the sequence. +3. The partial sums are written to shared global workspace. +4. A final reduction step (using atomic adds or a subsequent lightweight kernel) aggregates the partial sums. + +*Result:* $32 \text{ heads} \times 4 \text{ splits/head} = 128 \text{ blocks}$, successfully saturating the massive GPU footprint. + +## Persistent Thread Blocks (Persistent Kernels) + +Launching a new kernel for every single token being decoded introduces severe CPU launch overhead (often 2-5 microseconds per launch), which accumulates heavily across thousands of tokens. + +**The Solution:** +Instead of returning control to the CPU after one token, the kernel uses a `while` loop that spins on a global memory flag. +- The GPU continuously polls a memory location to check if the next query vector is ready. +- Communication between layers happens entirely via NVLink / Global Memory, bypassing the CPU scheduler completely (often referred to as CUDA Graphs or Device Graphs). + +## Related Topics + +- Cooperative groups (useful for Split-K reductions): `../cooperative-groups/DOC.md` +- Fused kernel design patterns (epilogue fusion): `../fused-kernel-design-patterns/DOC.md` +- Paged attention and vLLM: `../paged-attention-and-vllm-integration/DOC.md` + +## Official Source Links (Fact Check) + +- NVIDIA TensorRT-LLM Documentation: https://nvidia.github.io/TensorRT-LLM/ +- Persistent Kernels context: https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/memory-bound-kernel-optimization-playbook/DOC.md b/content/cuda/docs/memory-bound-kernel-optimization-playbook/DOC.md new file mode 100644 index 00000000..944dd57e --- /dev/null +++ b/content/cuda/docs/memory-bound-kernel-optimization-playbook/DOC.md @@ -0,0 +1,64 @@ +--- +name: memory-bound-kernel-optimization-playbook +description: "Memory-bound kernel optimization playbook: coalescing, cache locality, shared-memory staging, and bandwidth-focused validation." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,memory-bound,optimization,coalescing,cache,shared-memory,bandwidth,staging,latency" +--- + +# Memory-Bound Kernel Optimization Playbook (C++) + +Use this page after profiling confirms the kernel is limited by memory movement instead of arithmetic throughput. + +## Primary Objectives + +- Increase effective bandwidth. +- Reduce wasted traffic. +- Improve locality and access regularity. + +## High-Impact Levers + +- Coalesced global-memory access. +- Reuse through registers/shared memory. +- Shared-memory layouts that avoid severe bank conflicts. +- Data-layout changes that reduce strided/scattered loads. + +## Triage Sequence + +1. Validate coalescing quality for major tensors. +2. Check L1/L2 reuse opportunity and cache-policy behavior. +3. Add or improve shared-memory staging for high-reuse tiles. +4. Recheck occupancy/register pressure after staging changes. + +## Common Failure Modes + +- Correct staging logic but poor layout (bank conflicts dominate). +- More shared memory with no reuse gain (occupancy drops, throughput worsens). +- Overly complex index math adds latency and defeats memory gains. + +## Verification Checklist + +- Achieved bandwidth increases in profiler metrics. +- Memory-related warp stalls decrease in hot sections. +- Total runtime improves on representative production shapes. + +## Related Topics + +- Coalescing: `../coalescing/DOC.md` +- Shared memory: `../shared-memory/DOC.md` +- Cache behavior: `../cache-behavior-and-access-policy/DOC.md` +- Data layout and alignment: `../data-layout-and-alignment/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, memory optimizations: https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/ +- CUDA C++ Programming Guide, memory hierarchy and access behavior: https://docs.nvidia.com/cuda/cuda-c-programming-guide/ +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/memory-fences-and-ordering/DOC.md b/content/cuda/docs/memory-fences-and-ordering/DOC.md new file mode 100644 index 00000000..7897149d --- /dev/null +++ b/content/cuda/docs/memory-fences-and-ordering/DOC.md @@ -0,0 +1,86 @@ +--- +name: memory-fences-and-ordering +description: "CUDA memory-ordering essentials: weak ordering, __threadfence* scopes, visibility vs ordering, and fence-based handoff patterns." +metadata: + languages: "cpp" + versions: "12.6" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,memory-ordering,memory-fence,__threadfence,__threadfence_block,__threadfence_system,visibility,volatile" +--- + +# CUDA Memory Fences And Ordering (C++) + +Use this page when kernels communicate through memory and correctness depends on ordering rather than just synchronization. + +## Weak Ordering + +CUDA uses a weakly ordered memory model. + +- two unsynchronized threads reading and writing the same location create a data race +- memory fences enforce ordering of a thread's memory operations +- fences do not automatically provide block-wide participation like `__syncthreads()` + +## Fence Scope Variants + +CUDA provides three common fence scopes: + +- `__threadfence_block()` +- `__threadfence()` +- `__threadfence_system()` + +Roughly: + +- block scope: ordering relevant to the calling block +- device scope: ordering relevant across the device +- system scope: ordering visible to host threads and peer devices as well + +## Ordering vs Visibility + +This distinction matters: + +- fences order memory operations by the calling thread +- barriers coordinate participating threads +- visibility to observers may still require the right memory access path and synchronization pattern + +In other words, a fence is not a replacement for `__syncthreads()`. + +## Typical Pattern + +Producer-consumer handoff across blocks often looks like: + +1. producer writes data +2. producer executes `__threadfence()` +3. producer updates a flag or counter atomically +4. consumer observes the flag and then reads the data + +Without the fence, the flag can become visible before the data it is meant to publish. + +## Choosing The Scope + +- same block only: usually `__threadfence_block()` or a block barrier pattern +- different blocks on the same device: typically `__threadfence()` +- host or peer-device observers: `__threadfence_system()` + +Choose the narrowest scope that matches the communication pattern. + +## Common Mistakes + +- assuming atomics alone solve all ordering problems +- using `__threadfence()` when a block-local barrier is the real need +- forgetting that fences do not synchronize other threads +- using device-wide or system-wide fences more broadly than necessary + +## Related Topics + +- Synchronization rules: `../synchronization/DOC.md` +- Atomics and reductions: `../atomics-and-reductions/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, memory fence functions: https://docs.nvidia.com/cuda/archive/12.6.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, historical fence examples and ordering discussion: https://docs.nvidia.com/cuda/archive/11.5.0/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/memory-hierarchy/DOC.md b/content/cuda/docs/memory-hierarchy/DOC.md new file mode 100644 index 00000000..d10803be --- /dev/null +++ b/content/cuda/docs/memory-hierarchy/DOC.md @@ -0,0 +1,115 @@ +--- +name: memory-hierarchy +description: "CUDA memory hierarchy essentials: registers, local, shared, global, constant, and texture/read-only paths." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,memory-hierarchy,registers,local-memory,shared-memory,global-memory,constant-memory,texture-memory" +--- + +# CUDA Memory Hierarchy (C++) + +Use this page to decide which CUDA memory space fits a kernel access pattern. + +## The Main Spaces + +- registers: fastest per-thread storage, but limited +- local memory: per-thread memory in device memory, commonly used for spills or large automatic objects +- shared memory: on-chip storage shared by threads in a block +- global memory: large device memory visible across kernels and blocks +- constant memory: cached read-only storage, especially effective when many threads read the same location +- texture/read-only path: cached read-only access path that can help some spatial access patterns + +## Registers + +Registers are the first-choice storage for hot per-thread values. + +- lowest-latency storage for thread-private temporaries +- high register pressure can reduce occupancy +- if the compiler runs out of registers, values may spill to local memory + +## Local Memory + +Despite the name, local memory is not on-chip shared scratchpad memory. + +- it is private to one thread +- it resides in device memory +- it often appears when large automatic arrays are used or when register pressure causes spills + +If a kernel unexpectedly slows down, local-memory traffic is often a sign that register use is too high. + +## Shared Memory + +Shared memory is the standard block-level scratchpad. + +- shared by threads in one block +- useful for data reuse, tiling, transpose, and reduction +- requires explicit synchronization when threads communicate through it +- performance depends on avoiding bank conflicts + +See `../shared-memory/DOC.md` for the detailed usage rules. + +## Global Memory + +Global memory is the default large device memory space. + +- visible to all threads and across kernel launches +- highest capacity among device spaces +- much slower than on-chip storage +- performance depends heavily on coalesced access patterns + +See `../coalescing/DOC.md` for access-pattern guidance. + +## Constant Memory + +Constant memory is read-only from device code and is cached. + +- best when many threads read the same address +- not a substitute for shared memory +- useful for broadcast-like parameters or small read-only tables + +## Texture / Read-Only Path + +Texture and read-only cached access paths can help when: + +- access is read-only +- locality is irregular or spatial +- the pattern is not ideal for standard coalesced global loads + +Do not default to texture memory for ordinary linear arrays; it is a pattern-specific tool. + +## Selection Heuristics + +- value reused only by one thread: registers first +- value reused by many threads in one block: shared memory +- large tensor or array visible across blocks: global memory +- small read-only broadcast table: constant memory +- read-only data with irregular spatial locality: texture/read-only path + +## Practical Warnings + +- local memory is usually a warning sign, not a target optimization space +- shared memory helps only when reuse or reordering outweighs its setup and sync cost +- high occupancy alone does not guarantee fast memory behavior +- coalescing and bank conflicts often matter more than raw memory-space choice + +## Related Topics + +- Shared memory details: `../shared-memory/DOC.md` +- Synchronization rules: `../synchronization/DOC.md` +- Coalesced access patterns: `../coalescing/DOC.md` +- Unified Memory: `../unified-memory/DOC.md` +- Pinned memory and transfers: `../pinned-memory-and-transfers/DOC.md` +- PTX state spaces: `../ptx/references/state-spaces-and-types.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, programming model and memory overview: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, device memory space specifiers: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html#device-memory-space-specifiers +- CUDA C++ Programming Guide, local memory discussion: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, shared memory: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html#shared + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/moe-routing-and-expert-execution/DOC.md b/content/cuda/docs/moe-routing-and-expert-execution/DOC.md new file mode 100644 index 00000000..dba3f189 --- /dev/null +++ b/content/cuda/docs/moe-routing-and-expert-execution/DOC.md @@ -0,0 +1,57 @@ +--- +name: moe-routing-and-expert-execution +description: "Mixture of Experts (MoE) kernel patterns: token routing, prefix sums, contiguous memory repacking, and batched expert GEMMs." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,moe,mixture-of-experts,routing,radix-sort,prefix-sum,grouped-gemm,scatter-gather" +--- + +# Mixture of Experts (MoE) Routing and Execution + +Use this page when designing kernels for Mixture of Experts (MoE) architectures, which are characterized by dynamic control flow and extreme memory irregularity (e.g., Mixtral, DeepSeek). + +## The MoE Irregularity Problem + +In a dense MLP layer, all tokens in a batch hit the same linear weight matrices. +In an MoE MLP layer, a router (gate) assigns each token to 1 or 2 (or more) "Experts" out of $E$ possible experts. + +If executed naively, each expert does a tiny GEMM on non-contiguous tokens scattered across the batch. This shatters memory coalescing and leaves SMs starved. + +## Phase 1: The Routing / Sorting Kernel + +Before doing the math, tokens must be physically regrouped: +1. **Gate Evaluation:** Compute `softmax(X * W_gate)` to get expert probabilities. +2. **Top-K Selection:** Select the top $K$ experts and their routing weights. +3. **Prefix Sum (Scan):** Use a fast parallel prefix sum (e.g., via CUB) to count how many tokens go to each expert and compute their target offsets. +4. **Scatter/Repack:** Move the token activation vectors from their original batch position into a new contiguous buffer where all tokens for Expert 0 are laid out together, followed by Expert 1, etc. + +## Phase 2: Grouped GEMM / Batched Execution + +Once tokens are contiguous per expert, the math becomes a **Grouped GEMM**. +Instead of launching $E$ separate small GEMM kernels (which causes severe launch overhead), you launch a single Grouped GEMM kernel (or use `cublasLtGroupedGemm`). + +- **Block Assignment:** The kernel reads an array of "problem sizes" (how many tokens each expert received). Thread blocks are assigned dynamically to expert chunks. +- **Tail Effects:** If Expert 2 receives 3 tokens and the Block Tile size is 64, compute utilization is terrible. Highly optimized MoE kernels (like Megatron-LM or vLLM's custom kernels) implement "Continuous Batching" or "Marlin-style" techniques to pack uneven segments across thread blocks tightly. + +## Dealing with Dropped Tokens & Padding + +In training or strict capacity routing, an expert has a maximum capacity $C$. +- If an expert is oversubscribed, tokens are "dropped" (zeroed out or routed to the next best layer). +- The routing kernel must safely truncate writes using atomic operations or masked prefix sums to avoid out-of-bounds memory corruption. + +## Related Topics + +- Sparse and irregular kernels: `../sparse-and-irregular-kernels/DOC.md` +- Fused kernel design patterns: `../fused-kernel-design-patterns/DOC.md` +- Paged attention (for dynamic memory): `../paged-attention-and-vllm-integration/DOC.md` + +## Official Source Links (Fact Check) + +- NVIDIA Megatron-LM MoE Implementation Concepts: https://github.com/NVIDIA/Megatron-LM +- CUTLASS Grouped GEMM: https://github.com/NVIDIA/cutlass/tree/main/examples/24_gemm_grouped + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/multi-gpu-and-peer-access/DOC.md b/content/cuda/docs/multi-gpu-and-peer-access/DOC.md new file mode 100644 index 00000000..3cd3a878 --- /dev/null +++ b/content/cuda/docs/multi-gpu-and-peer-access/DOC.md @@ -0,0 +1,74 @@ +--- +name: multi-gpu-and-peer-access +description: "CUDA multi-GPU essentials: device selection, peer access (P2P), topology constraints, and cross-device synchronization basics." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,multi-gpu,peer-access,p2p,cudaDeviceEnablePeerAccess,cudaMemcpyPeerAsync,topology,nvlink" +--- + +# CUDA Multi-GPU And Peer Access (C++) + +Use this page for process-level multi-GPU programming and direct device-to-device data movement. + +## Device Selection Basics + +Multi-GPU programs typically: + +1. query device count and capabilities +2. assign work partitions per device +3. set active device with `cudaSetDevice` +4. create per-device streams/resources + +Avoid frequent device switching in tight host loops unless necessary. + +## Peer Access (P2P) + +Peer access allows one GPU to access memory on another GPU directly when topology and capability permit it. + +Core APIs: + +- `cudaDeviceCanAccessPeer` +- `cudaDeviceEnablePeerAccess` +- `cudaMemcpyPeerAsync` + +Always check capability before enabling peer access. + +## Why P2P Matters + +When supported, P2P can reduce host staging overhead for inter-GPU exchange. + +Performance depends on topology: + +- NVLink-connected peers often outperform PCIe-only paths +- some GPU pairs may not support peer access at all + +## Synchronization Notes + +Cross-device workflows still need explicit ordering and synchronization. + +- use stream/event patterns per device +- avoid global sync unless required +- ensure destination-side readiness before kernel consumption + +## Common Mistakes + +- assuming all GPU pairs support P2P +- forgetting to set the correct active device before API calls +- building one global stream strategy across devices without per-device ownership + +## Related Topics + +- Streams and events: `../streams-and-events/DOC.md` +- Pinned memory and transfers: `../pinned-memory-and-transfers/DOC.md` +- Unified Memory: `../unified-memory/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, multi-device and peer access: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA Runtime API, peer-device memory access APIs: https://docs.nvidia.com/cuda/cuda-runtime-api/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/nsight-metrics-interpretation-cheatsheet/DOC.md b/content/cuda/docs/nsight-metrics-interpretation-cheatsheet/DOC.md new file mode 100644 index 00000000..a562ba37 --- /dev/null +++ b/content/cuda/docs/nsight-metrics-interpretation-cheatsheet/DOC.md @@ -0,0 +1,53 @@ +--- +name: nsight-metrics-interpretation-cheatsheet +description: "Nsight metrics interpretation cheatsheet: practical mapping from common metric patterns to likely bottleneck classes and next actions." +metadata: + languages: "cpp" + versions: "2024.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,nsight,metrics,profiling,interpretation,warp-stalls,occupancy,bandwidth,bottleneck" +--- + +# Nsight Metrics Interpretation Cheatsheet (C++) + +Use this page for fast mapping from profiler symptoms to likely root causes and next steps. + +## Symptom To Action Map + +- High memory pressure + low arithmetic utilization: + likely memory-bound, prioritize coalescing/layout/reuse. +- Low issue efficiency + dependency-heavy stalls: + likely compute-bound scheduling/dependency bottleneck. +- Many short kernels + high CPU orchestration share: + likely launch-bound, evaluate fusion/graphs/overlap changes. + +## Warp Stall Reading Rules + +- Treat stall reasons as supporting evidence, not standalone truth. +- Interpret stall categories together with achieved throughput and occupancy. +- Re-check after each optimization stage because dominant stalls can shift. + +## Minimal Workflow + +1. Timeline classify (Nsight Systems). +2. Kernel-level metrics drilldown (Nsight Compute). +3. Route to memory/compute/launch playbook. +4. Reprofile and confirm bottleneck shift. + +## Related Topics + +- Performance debugging: `../performance-debugging/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` +- Memory-bound playbook: `../memory-bound-kernel-optimization-playbook/DOC.md` +- Compute-bound playbook: `../compute-bound-kernel-optimization-playbook/DOC.md` +- Launch-bound playbook: `../launch-bound-optimization-playbook/DOC.md` + +## Official Source Links (Fact Check) + +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html +- Nsight Systems User Guide: https://docs.nvidia.com/nsight-systems/UserGuide/index.html + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/numerics-and-precision/DOC.md b/content/cuda/docs/numerics-and-precision/DOC.md new file mode 100644 index 00000000..671db38f --- /dev/null +++ b/content/cuda/docs/numerics-and-precision/DOC.md @@ -0,0 +1,74 @@ +--- +name: numerics-and-precision +description: "CUDA numerics and precision essentials: FP16/BF16/TF32 behavior, accumulation choices, and stability-aware kernel design." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,numerics,precision,fp16,bf16,tf32,accumulation,rounding,tensor-cores" +--- + +# CUDA Numerics And Precision (C++) + +Use this page when correctness and performance depend on precision mode choices. + +## Precision Choices Matter + +CUDA kernels often trade off: + +- throughput +- memory footprint +- numeric stability + +Common formats include FP32, FP16, BF16, and TF32 (Tensor Core-oriented math mode). + +## Storage Type vs Accumulation Type + +A robust pattern is mixed precision: + +- store inputs in lower precision (for bandwidth / throughput) +- accumulate in higher precision (for stability) + +Example direction: + +- FP16/BF16 inputs with FP32 accumulation for reductions and GEMM-like operations. + +## Tensor Core Precision Modes + +Tensor Core paths can use type-specific behavior (for example TF32/FP16/BF16 combinations depending on architecture and library mode). + +When enabling Tensor Core math modes: + +- verify expected numeric tolerance +- compare against a high-precision baseline +- record configuration to keep benchmark results reproducible + +## Common Instability Patterns + +- long reductions in low precision +- subtractive cancellation with similar-magnitude values +- iterative algorithms without periodic re-normalization + +## Practical Guardrails + +1. define accuracy targets first (absolute/relative tolerance). +2. choose accumulation precision before micro-optimizing. +3. test on representative dynamic ranges, not only random unit-scale inputs. +4. keep a reference path (often FP32 accumulation) for regression checks. + +## Related Topics + +- Tensor Core usage: `../tensor-cores/DOC.md` +- Tensor Core numerical validation: `../tensor-core-numerical-validation/DOC.md` +- WMMA debugging checklist: `../wmma-debugging-checklist/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Performance debugging: `../performance-debugging/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, floating-point and mixed precision behavior: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Programming Guide, WMMA/Tensor Core precision context: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/nvtx-and-profiling-workflow/DOC.md b/content/cuda/docs/nvtx-and-profiling-workflow/DOC.md new file mode 100644 index 00000000..ab838296 --- /dev/null +++ b/content/cuda/docs/nvtx-and-profiling-workflow/DOC.md @@ -0,0 +1,58 @@ +--- +name: nvtx-and-profiling-workflow +description: "CUDA NVTX and profiling workflow essentials: annotation strategy, Nsight Systems correlation, and handoff to Nsight Compute." +metadata: + languages: "cpp" + versions: "2024.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,nvtx,profiling,nsight-systems,nsight-compute,annotation,timeline" +--- + +# NVTX And Profiling Workflow (C++) + +Use this page for a repeatable profiling workflow across host code and CUDA kernels. + +## Why NVTX First + +NVTX markers make timeline analysis actionable. + +- they label logical phases in host code +- Nsight Systems can correlate those ranges with stream activity and kernel launches +- this reduces guesswork before deep kernel-level profiling + +## Recommended Workflow + +1. add NVTX ranges around pipeline phases. +2. run Nsight Systems to identify timeline bottlenecks. +3. select top kernels from the timeline. +4. run Nsight Compute for per-kernel microanalysis. + +This avoids premature micro-optimization of non-critical kernels. + +## Annotation Guidelines + +- annotate coarse phases first (data load, preprocess, compute, postprocess) +- add finer ranges only where needed +- keep naming stable across runs for easy diffing + +## Common Mistakes + +- profiling kernels without timeline context +- over-annotating every tiny function +- changing workload shape between profiling runs + +## Related Topics + +- Performance debugging: `../performance-debugging/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` + +## Official Source Links (Fact Check) + +- NVTX documentation: https://nvidia.github.io/NVTX/ +- Nsight Systems User Guide: https://docs.nvidia.com/nsight-systems/UserGuide/index.html +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/occupancy/DOC.md b/content/cuda/docs/occupancy/DOC.md new file mode 100644 index 00000000..c5f1b841 --- /dev/null +++ b/content/cuda/docs/occupancy/DOC.md @@ -0,0 +1,103 @@ +--- +name: occupancy +description: "CUDA occupancy essentials: active warps, launch configuration APIs, and the tradeoff with registers and shared memory." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,occupancy,launch-configuration,block-size,register-pressure,shared-memory,cudaOccupancyMaxPotentialBlockSize" +--- + +# CUDA Occupancy (C++) + +Use this page when tuning block size, shared memory size, or register usage and you need to reason about how many warps and blocks can stay active on an SM. + +## What Occupancy Means + +Occupancy is the ratio of active warps on an SM to the maximum supported warps on that SM. + +In practice, occupancy is constrained by: + +- threads per block +- registers used per thread +- shared memory used per block +- architectural limits on blocks and warps per SM + +## Important Caveat + +Higher occupancy is not automatically better. + +- low occupancy can hurt latency hiding +- very high occupancy can be unnecessary if the kernel is already bandwidth-limited or instruction-efficient +- reducing registers just to raise occupancy can backfire if it causes spills to local memory + +Treat occupancy as a constraint and diagnostic, not a standalone optimization target. + +## Runtime APIs + +CUDA provides helper APIs for launch configuration: + +- `cudaOccupancyMaxActiveBlocksPerMultiprocessor` +- `cudaOccupancyMaxPotentialBlockSize` +- `cudaOccupancyMaxPotentialBlockSizeVariableSMem` + +Use them to estimate a reasonable starting block size based on register and shared-memory usage. + +Minimal pattern: + +```cpp +int minGridSize = 0; +int blockSize = 0; +cudaOccupancyMaxPotentialBlockSize( + &minGridSize, + &blockSize, + my_kernel, + 0, + 0); +``` + +This gives a good starting point, not a final answer. + +## What Usually Lowers Occupancy + +- large dynamic shared memory allocations +- high register pressure +- overly large block sizes +- cluster or architecture-specific launch constraints on newer GPUs + +## Practical Tuning Rules + +- start in the 128 to 256 threads-per-block range unless you have a strong reason otherwise +- prefer a multiple of warp size +- if a kernel frequently calls `__syncthreads()`, several smaller blocks can outperform one very large block +- if reducing block size barely changes runtime, the kernel may not be occupancy-limited + +## Common Misread + +If performance is poor, ask these in order: + +1. Is memory access coalesced? +2. Are there bank conflicts? +3. Is there divergence? +4. Is occupancy actually the limiting factor? + +Very often, memory behavior matters more than squeezing out a few more active warps. + +## Related Topics + +- Execution model: `../execution-model/DOC.md` +- Compute throughput model: `../compute-throughput/DOC.md` +- Shared memory constraints: `../shared-memory/DOC.md` +- Memory hierarchy overview: `../memory-hierarchy/DOC.md` +- Synchronization behavior: `../synchronization/DOC.md` +- Coalesced global memory access: `../coalescing/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, occupancy calculator APIs: https://docs.nvidia.com/cuda/archive/11.8.0/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, thread/block sizing guidance: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA Driver API occupancy reference: https://docs.nvidia.com/cuda/archive/11.4.4/cuda-driver-api/group__CUDA__OCCUPANCY.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/paged-attention-and-vllm-integration/DOC.md b/content/cuda/docs/paged-attention-and-vllm-integration/DOC.md new file mode 100644 index 00000000..3f31dbfe --- /dev/null +++ b/content/cuda/docs/paged-attention-and-vllm-integration/DOC.md @@ -0,0 +1,63 @@ +--- +name: paged-attention-and-vllm-integration +description: "Paged attention kernel patterns: irregular memory management, KV cache block tables, and integration with dynamic batching systems." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-22" + source: official + tags: "cuda,gpu,kernel,paged-attention,vllm,kv-cache,block-tables,llm,dynamic-batching,sparse-memory" +--- + +# Paged Attention and vLLM Integration (C++) + +Use this page when writing attention kernels that deal with non-contiguous Key-Value (KV) cache memory. + +## The Memory Fragmentation Problem + +In generative LLM inference, keeping the KV cache in contiguous global memory leads to severe fragmentation and waste due to variable sequence lengths and unknown generation lengths. + +Paged Attention solves this by partitioning the KV cache into fixed-size "blocks" (pages) distributed irregularly in memory, mimicking OS virtual memory. + +## Core Architectural Differences + +Instead of addressing $K[b, h, seq, d]$, paged attention kernels require an indirection layer: +- **Block Table:** An array of pointers or physical block indices. `block_table[b, logical_block_idx] -> physical_block_idx`. +- **Physical KV Cache:** A pre-allocated memory pool of shape `[num_physical_blocks, block_size, num_heads, head_size]`. + +## Pointers vs Indices + +During the inner loop of the FlashAttention-style GEMM, the kernel must fetch $K$ and $V$ tiles. +- **Contiguous:** `k_ptr = k_base + stride * idx` +- **Paged:** + 1. Determine `logical_block = seq_idx / block_size` + 2. Map to `physical_block = block_table[logical_block]` + 3. Load from `physical_kv_pool + physical_block_stride + local_offset` + +*Warning:* Performing this modular math or indirection randomly inside a tight inner loop causes severe instruction pipeline stalls. The index calculation must be done warp-uniformly and scheduled outside the core MMA pipeline if possible. + +## TMA Compatibility Challenges + +Hardware Tensor Memory Accelerator (TMA) typically assumes contiguous, standard-stride tensors. TMA fetching across block boundaries in a paged KV cache is non-trivial. +- If $K$ tile spans a page boundary, two TMA descriptors/requests might be necessary. +- **Mitigation:** Ensure the block size is an integer multiple of the MMA tile size along the sequence dimension (e.g., $N=64$). This guarantees a fetched tile is physically contiguous. + +## Prefix Sharing and Radix Attention + +Paged attention naturally enables memory sharing (e.g., prompt sharing across multiple parallel generations). +- The `block_table` for different sequences can simply point to the same `physical_block`. +- Since KV cache memory is read-only during the generation phase for existing tokens, no special hardware locks are needed. + +## Related Topics + +- Flash Attention patterns: `../flash-attention-implementation-patterns/DOC.md` +- Sparse and irregular kernels: `../sparse-and-irregular-kernels/DOC.md` +- Asynchronous copies: `../async-copy/DOC.md` + +## Official Source Links (Fact Check) + +- vLLM Project Documentation: https://vllm.readthedocs.io/ +- PagedAttention Paper (vLLM): https://arxiv.org/abs/2309.06180 + +Last cross-check date: 2026-03-22 diff --git a/content/cuda/docs/performance-debugging/DOC.md b/content/cuda/docs/performance-debugging/DOC.md new file mode 100644 index 00000000..7c1d1624 --- /dev/null +++ b/content/cuda/docs/performance-debugging/DOC.md @@ -0,0 +1,100 @@ +--- +name: performance-debugging +description: "CUDA performance debugging essentials: when to use Nsight Systems vs Nsight Compute, key metrics, and how to read warp stalls." +metadata: + languages: "cpp" + versions: "2024.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,performance-debugging,nsight-compute,nsight-systems,warp-stalls,occupancy,bandwidth,profiling" +--- + +# CUDA Performance Debugging (C++) + +Use this page when a kernel is correct but slow and you need to decide what to profile first. + +## First Tool Choice + +Use the tools for different questions: + +- Nsight Systems: timeline, host/device orchestration, overlap, streams, events, graph behavior +- Nsight Compute: per-kernel metrics, throughput, occupancy, warp stalls, memory behavior + +If you do not yet know whether the problem is on the host side or inside the kernel, start with Nsight Systems. + +## Nsight Systems + +Use Nsight Systems when you need to answer: + +- are streams actually overlapping? +- are copies blocking kernels? +- is the CPU launch path the bottleneck? +- are events or graphs introducing serialization? + +NVTX ranges are useful here for relating CPU regions to CUDA activity. + +## Nsight Compute + +Use Nsight Compute when you need to answer: + +- is the kernel memory-bound or compute-bound? +- is occupancy too low? +- are schedulers issuing efficiently? +- what are the top warp stall reasons? + +Useful report sections include: + +- SpeedOfLight +- Occupancy +- SchedulerStats +- WarpStateStats + +## Reading Stall Reasons Carefully + +NVIDIA's profiling guide explicitly warns not to over-focus on stalls unless schedulers are failing to issue well. + +Examples: + +- high short-scoreboard stalls often point to shared-memory operations or similar MIO dependencies +- high barrier-related stalls often mean uneven work before synchronization +- high not-selected can simply indicate there are enough eligible warps + +So stall interpretation should follow, not replace, a top-level throughput diagnosis. + +## Practical Triage Order + +1. check total runtime structure with Nsight Systems +2. identify the expensive kernel(s) +3. inspect throughput, occupancy, and warp states in Nsight Compute +4. map the dominant issue back to code: + coalescing, bank conflicts, divergence, occupancy, or launch overhead + +## Related Topics + +- Occupancy tuning: `../occupancy/DOC.md` +- Compute throughput: `../compute-throughput/DOC.md` +- Kernel bottleneck diagnosis workflow: `../kernel-bottleneck-diagnosis-workflow/DOC.md` +- Nsight metrics interpretation cheatsheet: `../nsight-metrics-interpretation-cheatsheet/DOC.md` +- Memory-bound optimization playbook: `../memory-bound-kernel-optimization-playbook/DOC.md` +- Compute-bound optimization playbook: `../compute-bound-kernel-optimization-playbook/DOC.md` +- Launch-bound optimization playbook: `../launch-bound-optimization-playbook/DOC.md` +- CUDA Core optimization checklist: `../cuda-core-optimization-checklist/DOC.md` +- WMMA debugging checklist: `../wmma-debugging-checklist/DOC.md` +- Tensor Core numerical validation: `../tensor-core-numerical-validation/DOC.md` +- Streams and events: `../streams-and-events/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` +- NVTX workflow: `../nvtx-and-profiling-workflow/DOC.md` +- Error handling and debug build: `../error-handling-and-debug-build/DOC.md` +- Benchmarking methodology: `../benchmarking-methodology/DOC.md` +- Regression testing and CI: `../regression-testing-and-ci/DOC.md` +- Data layout and alignment: `../data-layout-and-alignment/DOC.md` +- Cache behavior and access policy: `../cache-behavior-and-access-policy/DOC.md` + +## Official Source Links (Fact Check) + +- Nsight Systems User Guide: https://docs.nvidia.com/nsight-systems/UserGuide/index.html +- Nsight Compute Profiling Guide: https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html +- Older Nsight Compute profiling guide with stall explanations: https://docs.nvidia.com/nsight-compute/2022.4/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/persistent-kernels-and-work-queues/DOC.md b/content/cuda/docs/persistent-kernels-and-work-queues/DOC.md new file mode 100644 index 00000000..1fbd90db --- /dev/null +++ b/content/cuda/docs/persistent-kernels-and-work-queues/DOC.md @@ -0,0 +1,62 @@ +--- +name: persistent-kernels-and-work-queues +description: "CUDA persistent-kernel essentials: resident worker model, device work queues, load balancing, and synchronization hazards." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,persistent-kernel,work-queue,load-balancing,atomics,producer-consumer,latency" +--- + +# CUDA Persistent Kernels And Work Queues (C++) + +Use this page for latency-sensitive or irregular workloads where one long-lived kernel processes dynamic work. + +## Persistent Kernel Model + +A persistent kernel keeps a fixed set of resident blocks/warps alive and repeatedly pulls tasks from a queue. + +This can reduce launch overhead and improve responsiveness for fine-grained dynamic work. + +## Typical Components + +- global/device work queue +- atomic enqueue/dequeue indices +- worker loop with termination protocol +- backoff or batching strategy for queue contention + +## Where It Helps + +- irregular task sizes +- real-time/low-latency pipelines +- workloads where kernel launch overhead is a large fraction of runtime + +## Where It Hurts + +- queue contention hotspots +- heavy atomic traffic +- poor fairness or starvation in naive dequeue policies +- over-occupying resources and blocking other kernels + +## Design Guardrails + +1. define clear producer/consumer ordering rules. +2. minimize global atomics per task (batch when possible). +3. bound queue contention with per-block or per-warp staging. +4. profile fairness and tail latency, not only average throughput. + +## Related Topics + +- Sparse and irregular kernels: `../sparse-and-irregular-kernels/DOC.md` +- Atomics and reductions: `../atomics-and-reductions/DOC.md` +- Memory fences and ordering: `../memory-fences-and-ordering/DOC.md` +- Streams/events and graphs: `../streams-and-events/DOC.md`, `../cuda-graphs/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Programming Guide, synchronization/order primitives used by queue-based designs: https://docs.nvidia.com/cuda/archive/12.9.1/cuda-c-programming-guide/index.html +- CUDA C++ Best Practices Guide, launch overhead and memory/atomic considerations: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/pinned-memory-and-transfers/DOC.md b/content/cuda/docs/pinned-memory-and-transfers/DOC.md new file mode 100644 index 00000000..b08a1793 --- /dev/null +++ b/content/cuda/docs/pinned-memory-and-transfers/DOC.md @@ -0,0 +1,66 @@ +--- +name: pinned-memory-and-transfers +description: "CUDA pinned-memory and transfer essentials: page-locked host memory, async memcpy overlap, and transfer-path tuning." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,pinned-memory,page-locked,cudaHostAlloc,cudaMemcpyAsync,transfer-overlap,pcie" +--- + +# CUDA Pinned Memory And Transfers (C++) + +Use this page when host-device transfer performance or overlap is a bottleneck. + +## What Pinned Memory Is + +Pinned (page-locked) host memory is allocated with APIs such as: + +- `cudaHostAlloc` +- `cudaMallocHost` + +Because it is page-locked, the runtime can perform faster and more predictable DMA transfers. + +## Why It Matters + +`cudaMemcpyAsync` overlap with kernel execution generally requires: + +- non-default stream usage +- pinned host buffers for transfer endpoints + +Without pinned memory, many async-copy scenarios degrade to serialized behavior. + +## Basic Pattern + +1. allocate pinned host buffers +2. launch `cudaMemcpyAsync(..., stream)` +3. launch kernels in suitable streams +4. synchronize with stream/event primitives, not global device sync + +## Tradeoffs + +- pinned memory improves transfer behavior +- but excessive pinning can hurt overall system memory behavior on the host + +Pin only hot buffers and reuse them. + +## Common Mistakes + +- assuming `cudaMemcpyAsync` always overlaps without checking buffer type +- mixing default-stream semantics and expecting full concurrency +- over-allocating pinned memory globally + +## Related Topics + +- Streams and events: `../streams-and-events/DOC.md` +- Unified Memory: `../unified-memory/DOC.md` +- CUDA Graphs: `../cuda-graphs/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide, host-device transfer optimization: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA Runtime API, host-memory management and async memcpy: https://docs.nvidia.com/cuda/cuda-runtime-api/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/production-readiness-checklist/DOC.md b/content/cuda/docs/production-readiness-checklist/DOC.md new file mode 100644 index 00000000..f155304f --- /dev/null +++ b/content/cuda/docs/production-readiness-checklist/DOC.md @@ -0,0 +1,72 @@ +--- +name: production-readiness-checklist +description: "CUDA production-readiness checklist: correctness gates, performance stability, observability, compatibility, and rollout safeguards." +metadata: + languages: "cpp" + versions: "12.9" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,gpu,kernel,production,readiness,checklist,observability,compatibility,rollback,release-gates" +--- + +# CUDA Production Readiness Checklist (C++) + +Use this page before shipping optimized CUDA kernels to production environments. + +## 1) Correctness Gates + +- reference-baseline comparison on representative datasets +- tolerance policy per precision mode +- stress tests for boundary sizes and adversarial shapes +- deterministic/reproducibility expectations documented + +## 2) Performance Gates + +- benchmark methodology fixed and repeatable +- p50/p95 latency and throughput baselines recorded +- regression thresholds defined and enforced in CI/perf jobs +- cold-start versus steady-state behavior measured + +## 3) Observability + +- NVTX ranges present for major pipeline phases +- key metrics exported (latency, error rates, fallback rate) +- profiler workflows documented for oncall debugging + +## 4) Compatibility + +- target `-gencode` matrix matches deployment fleet +- driver/toolkit compatibility validated +- fallback path behavior tested when preferred kernels are unavailable + +## 5) Operational Safety + +- feature flag or staged rollout strategy +- fast rollback path +- runtime guardrails for unexpected shapes/resource exhaustion + +## 6) Documentation Hygiene + +- kernel assumptions and constraints documented +- precision and determinism modes documented +- known limitations and troubleshooting notes linked + +## Related Topics + +- Regression testing and CI: `../regression-testing-and-ci/DOC.md` +- Benchmarking methodology: `../benchmarking-methodology/DOC.md` +- Build and ABI compatibility: `../build-and-abi-compatibility/DOC.md` +- NVTX profiling workflow: `../nvtx-and-profiling-workflow/DOC.md` +- Fallback strategies and capability detection: `../fallback-strategies-and-capability-detection/DOC.md` +- Incident response and rollback playbook: `../incident-response-and-rollback-playbook/DOC.md` + +## Official Source Links (Fact Check) + +- CUDA C++ Best Practices Guide: https://docs.nvidia.com/cuda/archive/13.0.0/cuda-c-best-practices-guide/index.html +- CUDA Compatibility documentation: https://docs.nvidia.com/deploy/cuda-compatibility/index.html +- Nsight Systems / Compute docs for observability workflows: + - https://docs.nvidia.com/nsight-systems/UserGuide/index.html + - https://docs.nvidia.com/nsight-compute/2024.2/ProfilingGuide/index.html + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/ptx-a-highly-multithreaded-coprocessor/DOC.md b/content/cuda/docs/ptx-a-highly-multithreaded-coprocessor/DOC.md new file mode 100644 index 00000000..b7f8a3af --- /dev/null +++ b/content/cuda/docs/ptx-a-highly-multithreaded-coprocessor/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-a-highly-multithreaded-coprocessor +description: 'The GPU is a compute device capable of executing a very large number + of threads in parallel. It operates as a coprocessor to the main CPU, or host: In + other words, data-parallel, compute-intensive por...' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 2.1. A Highly Multithreaded Coprocessor + +--- +title: "2.1. A Highly Multithreaded Coprocessor" +section: 2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 2.1. A Highly Multithreaded Coprocessor + + +The GPU is a compute device capable of executing a very large number of threads in parallel. It operates as a coprocessor to the main CPU, or host: In other words, data-parallel, compute-intensive portions of applications running on the host are off-loaded onto the device. + +More precisely, a portion of an application that is executed many times, but independently on different data, can be isolated into a kernel function that is executed on the GPU as many different threads. To that effect, such a function is compiled to the PTX instruction set and the resulting kernel is translated at install time to the target GPU instruction set. \ No newline at end of file diff --git a/content/cuda/docs/ptx-a-set-of-simt-multiprocessors/DOC.md b/content/cuda/docs/ptx-a-set-of-simt-multiprocessors/DOC.md new file mode 100644 index 00000000..8159b1aa --- /dev/null +++ b/content/cuda/docs/ptx-a-set-of-simt-multiprocessors/DOC.md @@ -0,0 +1,44 @@ +--- +name: ptx-a-set-of-simt-multiprocessors +description: The NVIDIA GPU architecture is built around a scalable array of multithreaded + _Streaming Multiprocessors (SMs)_. When a host program invokes a kernel grid, the + blocks of the grid are enumerated and di... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 3.1. A Set of SIMT Multiprocessors + +--- +title: "3.1. A Set of SIMT Multiprocessors" +section: 3.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 3.1. A Set of SIMT Multiprocessors + + +The NVIDIA GPU architecture is built around a scalable array of multithreaded _Streaming Multiprocessors (SMs)_. When a host program invokes a kernel grid, the blocks of the grid are enumerated and distributed to multiprocessors with available execution capacity. The threads of a thread block execute concurrently on one multiprocessor. As thread blocks terminate, new blocks are launched on the vacated multiprocessors. + +A multiprocessor consists of multiple _Scalar Processor (SP)_ cores, a multithreaded instruction unit, and on-chip shared memory. The multiprocessor creates, manages, and executes concurrent threads in hardware with zero scheduling overhead. It implements a single-instruction barrier synchronization. Fast barrier synchronization together with lightweight thread creation and zero-overhead thread scheduling efficiently support very fine-grained parallelism, allowing, for example, a low granularity decomposition of problems by assigning one thread to each data element (such as a pixel in an image, a voxel in a volume, a cell in a grid-based computation). + +To manage hundreds of threads running several different programs, the multiprocessor employs an architecture we call _SIMT (single-instruction, multiple-thread)_. The multiprocessor maps each thread to one scalar processor core, and each scalar thread executes independently with its own instruction address and register state. The multiprocessor SIMT unit creates, manages, schedules, and executes threads in groups of parallel threads called _warps_. (This term originates from weaving, the first parallel thread technology.) Individual threads composing a SIMT warp start together at the same program address but are otherwise free to branch and execute independently. + +When a multiprocessor is given one or more thread blocks to execute, it splits them into warps that get scheduled by the SIMT unit. The way a block is split into warps is always the same; each warp contains threads of consecutive, increasing thread IDs with the first warp containing thread 0. + +At every instruction issue time, the SIMT unit selects a warp that is ready to execute and issues the next instruction to the active threads of the warp. A warp executes one common instruction at a time, so full efficiency is realized when all threads of a warp agree on their execution path. If threads of a warp diverge via a data-dependent conditional branch, the warp serially executes each branch path taken, disabling threads that are not on that path, and when all paths complete, the threads converge back to the same execution path. Branch divergence occurs only within a warp; different warps execute independently regardless of whether they are executing common or disjointed code paths. + +SIMT architecture is akin to SIMD (Single Instruction, Multiple Data) vector organizations in that a single instruction controls multiple processing elements. A key difference is that SIMD vector organizations expose the SIMD width to the software, whereas SIMT instructions specify the execution and branching behavior of a single thread. In contrast with SIMD vector machines, SIMT enables programmers to write thread-level parallel code for independent, scalar threads, as well as data-parallel code for coordinated threads. For the purposes of correctness, the programmer can essentially ignore the SIMT behavior; however, substantial performance improvements can be realized by taking care that the code seldom requires threads in a warp to diverge. In practice, this is analogous to the role of cache lines in traditional code: Cache line size can be safely ignored when designing for correctness but must be considered in the code structure when designing for peak performance. Vector architectures, on the other hand, require the software to coalesce loads into vectors and manage divergence manually. + +How many blocks a multiprocessor can process at once depends on how many registers per thread and how much shared memory per block are required for a given kernel since the multiprocessor’s registers and shared memory are split among all the threads of the batch of blocks. If there are not enough registers or shared memory available per multiprocessor to process at least one block, the kernel will fail to launch. + +![_images/hardware-model.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/hardware-model.png) + +Figure 4 Hardware Model + +A set of SIMT multiprocessors with on-chip shared memory. \ No newline at end of file diff --git a/content/cuda/docs/ptx-abs/DOC.md b/content/cuda/docs/ptx-abs/DOC.md new file mode 100644 index 00000000..ee27cbe2 --- /dev/null +++ b/content/cuda/docs/ptx-abs/DOC.md @@ -0,0 +1,80 @@ +--- +name: ptx-abs +description: Absolute value +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.4.6. Half Precision Floating Point Instructions:abs + +--- +title: "9.7.4.6. Half Precision Floating Point Instructions:abs" +section: 9.7.4.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.4.6. Half Precision Floating Point Instructions:abs + + +`abs` + +Absolute value + +Syntax + +abs{.ftz}.f16 d, a; + abs{.ftz}.f16x2 d, a; + abs.bf16 d, a; + abs.bf16x2 d, a; + +Description + +Take absolute value of `a` and store the result in `d`. + +For `.f16x2` and `.bf16x2` instruction type, forms input vector by extracting half word values from the source operand. Absolute values of half-word operands are then computed in parallel to produce `.f16x2` or `.bf16x2` result in destination. + +For `.f16` instruction type, operands `d` and `a` have `.f16` or `.b16` type. For `.f16x2` instruction type, operands `d` and `a` have `.f16x2` or `.b32` type. For `.bf16` instruction type, operands `d` and `a` have `.b16` type. For `.bf16x2` instruction type, operands `d` and `a` have `.b32` type. + +Semantics + +if (type == f16 || type == bf16) { + d = |a|; + } else if (type == f16x2 || type == bf16x2) { + fA[0] = a[0:15]; + fA[1] = a[16:31]; + for (i = 0; i < 2; i++) { + d[i] = |fA[i]|; + } + } + +Notes + +Subnormal numbers: + + +By default, subnormal numbers are supported. `abs.ftz.{f16, f16x2}` flushes subnormal inputs and results to sign-preserving zero. + +`NaN` inputs yield an unspecified `NaN`. Future implementations may comply with the IEEE 754 standard by preserving payload and modifying only the sign bit. + +PTX ISA Notes + +Introduced in PTX ISA version 6.5. + +`abs.bf16` and `abs.bf16x2` introduced in PTX ISA 7.0. + +Target ISA Notes + +Requires `sm_53` or higher. + +`abs.bf16` and `abs.bf16x2` requires architecture `sm_80` or higher. + +Examples + +abs.ftz.f16 x,f0; + abs.bf16 x,b0; + abs.bf16x2 x1,b1; \ No newline at end of file diff --git a/content/cuda/docs/ptx-activemask/DOC.md b/content/cuda/docs/ptx-activemask/DOC.md new file mode 100644 index 00000000..2fd4b2c9 --- /dev/null +++ b/content/cuda/docs/ptx-activemask/DOC.md @@ -0,0 +1,50 @@ +--- +name: ptx-activemask +description: Queries the active threads within a warp. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.11. Parallel Synchronization and Communication Instructions:activemask + +--- +title: "9.7.13.11. Parallel Synchronization and Communication Instructions:activemask" +section: 9.7.13.11 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.11. Parallel Synchronization and Communication Instructions:activemask + + +`activemask` + +Queries the active threads within a warp. + +Syntax + +activemask.b32 d; + +Description + +`activemask` queries predicated-on active threads from the executing warp and sets the destination `d` with 32-bit integer mask where bit position in the mask corresponds to the thread’s `laneid`. + +Destination `d` is a 32-bit destination register. + +An active thread will contribute 1 for its entry in the result and exited or inactive or predicated-off thread will contribute 0 for its entry in the result. + +PTX ISA Notes + +Introduced in PTX ISA version 6.2. + +Target ISA Notes + +Requires `sm_30` or higher. + +Examples + +activemask.b32 %r1; \ No newline at end of file diff --git a/content/cuda/docs/ptx-add/DOC.md b/content/cuda/docs/ptx-add/DOC.md new file mode 100644 index 00000000..d383707d --- /dev/null +++ b/content/cuda/docs/ptx-add/DOC.md @@ -0,0 +1,91 @@ +--- +name: ptx-add +description: Add 2 values. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.5.1. Mixed Precision Floating Point Instructions:add + +--- +title: "9.7.5.1. Mixed Precision Floating Point Instructions:add" +section: 9.7.5.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.5.1. Mixed Precision Floating Point Instructions:add + + +`add` + +Add 2 values. + +Syntax + +add{.rnd}{.sat}.f32.atype d, a, c; + + .atype = { .f16, .bf16}; + .rnd = { .rn, .rz, .rm, .rp }; + +Description + +Converts input operand `a` from `.atype` into `.f32` type. The converted value is then used for the addition. The resulting value is stored in the destination operand `d`. + +Semantics + +d = convert(a) + c; + +Notes + +Rounding modifiers: + +`.rn` + + +mantissa LSB rounds to nearest even + +`.rz` + + +mantissa LSB rounds towards zero + +`.rm` + + +mantissa LSB rounds towards negative infinity + +`.rp` + + +mantissa LSB rounds towards positive infinity + +The default value of rounding modifier is `.rn`. Note that an `add` instruction with an explicit rounding modifier is treated conservatively by the code optimizer. An `add` instruction with no rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code optimizer. In particular, `mul`/`add` sequences with no rounding modifiers may be optimized to use fused-multiply-add instructions on the target device. + +Subnormal numbers: + + +By default, subnormal numbers are supported. + +Saturation modifier: + + +`add.sat` clamps the result to [0.0, 1.0]. `NaN` results are flushed to `+0.0f`. + +PTX ISA Notes + +`add.f32.{f16/bf16}` introduced in PTX ISA version 8.6. + +Target ISA Notes + +`add.f32.{f16/bf16}` requires `sm_100` or higher. + +Examples + +.reg .f32 fc, fd; + .reg .b16 ba; + add.rz.f32.bf16.sat fd, fa, fc; \ No newline at end of file diff --git a/content/cuda/docs/ptx-addc/DOC.md b/content/cuda/docs/ptx-addc/DOC.md new file mode 100644 index 00000000..eaeda86a --- /dev/null +++ b/content/cuda/docs/ptx-addc/DOC.md @@ -0,0 +1,69 @@ +--- +name: ptx-addc +description: Add two values with carry-in and optional carry-out. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.2.2. Extended-Precision Arithmetic Instructions:addc + +--- +title: "9.7.2.2. Extended-Precision Arithmetic Instructions:addc" +section: 9.7.2.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.2.2. Extended-Precision Arithmetic Instructions:addc + + +`addc` + +Add two values with carry-in and optional carry-out. + +Syntax + +addc{.cc}.type d, a, b; + + .type = { .u32, .s32, .u64, .s64 }; + +Description + +Performs integer addition with carry-in and optionally writes the carry-out value into the condition code register. + +Semantics + +d = a + b + CC.CF; + +if `.cc` specified, carry-out written to `CC.CF` + +Notes + +No integer rounding modifiers. + +No saturation. + +Behavior is the same for unsigned and signed integers. + +PTX ISA Notes + +32-bit `addc` introduced in PTX ISA version 1.2. + +64-bit `addc` introduced in PTX ISA version 4.3. + +Target ISA Notes + +32-bit `addc` is supported on all target architectures. + +64-bit `addc` requires `sm_20` or higher. + +Examples + +@p add.cc.u32 x1,y1,z1; // extended-precision addition of + @p addc.cc.u32 x2,y2,z2; // two 128-bit values + @p addc.cc.u32 x3,y3,z3; + @p addc.u32 x4,y4,z4; \ No newline at end of file diff --git a/content/cuda/docs/ptx-addcc/DOC.md b/content/cuda/docs/ptx-addcc/DOC.md new file mode 100644 index 00000000..2759cf76 --- /dev/null +++ b/content/cuda/docs/ptx-addcc/DOC.md @@ -0,0 +1,69 @@ +--- +name: ptx-addcc +description: Add two values with carry-out. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.2.1. Extended-Precision Arithmetic Instructions:add.cc + +--- +title: "9.7.2.1. Extended-Precision Arithmetic Instructions:add.cc" +section: 9.7.2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.2.1. Extended-Precision Arithmetic Instructions:add.cc + + +`add.cc` + +Add two values with carry-out. + +Syntax + +add.cc.type d, a, b; + + .type = { .u32, .s32, .u64, .s64 }; + +Description + +Performs integer addition and writes the carry-out value into the condition code register. + +Semantics + +d = a + b; + +carry-out written to `CC.CF` + +Notes + +No integer rounding modifiers. + +No saturation. + +Behavior is the same for unsigned and signed integers. + +PTX ISA Notes + +32-bit `add.cc` introduced in PTX ISA version 1.2. + +64-bit `add.cc` introduced in PTX ISA version 4.3. + +Target ISA Notes + +32-bit `add.cc` is supported on all target architectures. + +64-bit `add.cc` requires `sm_20` or higher. + +Examples + +@p add.cc.u32 x1,y1,z1; // extended-precision addition of + @p addc.cc.u32 x2,y2,z2; // two 128-bit values + @p addc.cc.u32 x3,y3,z3; + @p addc.u32 x4,y4,z4; \ No newline at end of file diff --git a/content/cuda/docs/ptx-aliases/DOC.md b/content/cuda/docs/ptx-aliases/DOC.md new file mode 100644 index 00000000..5252135a --- /dev/null +++ b/content/cuda/docs/ptx-aliases/DOC.md @@ -0,0 +1,25 @@ +--- +name: ptx-aliases +description: Two distinct virtual addresses are said to be aliases if they map to + the same memory location. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.2. Aliases + +--- +title: "8.2.2. Aliases" +section: 8.2.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.2. Aliases + + +Two distinct virtual addresses are said to be aliases if they map to the same memory location. \ No newline at end of file diff --git a/content/cuda/docs/ptx-alignment/DOC.md b/content/cuda/docs/ptx-alignment/DOC.md new file mode 100644 index 00000000..aaf7a6b8 --- /dev/null +++ b/content/cuda/docs/ptx-alignment/DOC.md @@ -0,0 +1,35 @@ +--- +name: ptx-alignment +description: Byte alignment of storage for all addressable variables can be specified + in the variable declaration. Alignment is specified using an optional `.align` _byte-count_ + specifier immediately following the... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.4.5. Alignment + +--- +title: "5.4.5. Alignment" +section: 5.4.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.4.5. Alignment + + +Byte alignment of storage for all addressable variables can be specified in the variable declaration. Alignment is specified using an optional `.align` _byte-count_ specifier immediately following the state-space specifier. The variable will be aligned to an address which is an integer multiple of byte-count. The alignment value byte-count must be a power of two. For arrays, alignment specifies the address alignment for the starting address of the entire array, not for individual elements. + +The default alignment for scalar and array variables is to a multiple of the base-type size. The default alignment for vector variables is to a multiple of the overall vector size. + +Examples + +// allocate array at 4-byte aligned address. Elements are bytes. + .const .align 4 .b8 bar[8] = {0,0,0,0,2,0,0,0}; + +Note that all PTX instructions that access memory require that the address be aligned to a multiple of the access size. The access size of a memory instruction is the total number of bytes accessed in memory. For example, the access size of `ld.v4.b32` is 16 bytes, while the access size of `atom.f16x2` is 4 bytes. \ No newline at end of file diff --git a/content/cuda/docs/ptx-alloca/DOC.md b/content/cuda/docs/ptx-alloca/DOC.md new file mode 100644 index 00000000..a4b90003 --- /dev/null +++ b/content/cuda/docs/ptx-alloca/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-alloca +description: PTX provides `alloca` instruction for allocating storage at runtime on + the per-thread local memory stack. The allocated stack memory can be accessed with + `ld.local` and `st.local` instructions using t... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 7.3. Alloca + +--- +title: "7.3. Alloca" +section: 7.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 7.3. Alloca + + +PTX provides `alloca` instruction for allocating storage at runtime on the per-thread local memory stack. The allocated stack memory can be accessed with `ld.local` and `st.local` instructions using the pointer returned by `alloca`. + +In order to facilitate deallocation of memory allocated with `alloca`, PTX provides two additional instructions: `stacksave` which allows reading the value of stack pointer in a local variable, and `stackrestore` which can restore the stack pointer with the saved value. + +`alloca`, `stacksave`, and `stackrestore` instructions are described in [Stack Manipulation Instructions](<#stack-manipulation-instructions>). \ No newline at end of file diff --git a/content/cuda/docs/ptx-alternate-floating-point-data-formats/DOC.md b/content/cuda/docs/ptx-alternate-floating-point-data-formats/DOC.md new file mode 100644 index 00000000..17e9bc6e --- /dev/null +++ b/content/cuda/docs/ptx-alternate-floating-point-data-formats/DOC.md @@ -0,0 +1,73 @@ +--- +name: ptx-alternate-floating-point-data-formats +description: The fundamental floating-point types supported in PTX have implicit bit + representations that indicate the number of bits used to store exponent and mantissa. + For example, the `.f16` type indicates 5 b... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.3. Alternate Floating-Point Data Formats + +--- +title: "5.2.3. Alternate Floating-Point Data Formats" +section: 5.2.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.2.3. Alternate Floating-Point Data Formats + + +The fundamental floating-point types supported in PTX have implicit bit representations that indicate the number of bits used to store exponent and mantissa. For example, the `.f16` type indicates 5 bits reserved for exponent and 10 bits reserved for mantissa. In addition to the floating-point representations assumed by the fundamental types, PTX allows the following alternate floating-point data formats: + +`bf16` data format: + + +This data format is a 16-bit floating point format with 8 bits for exponent and 7 bits for mantissa. A register variable containing `bf16` data must be declared with `.b16` type. + +`e4m3` data format: + + +This data format is an 8-bit floating point format with 4 bits for exponent and 3 bits for mantissa. The `e4m3` encoding does not support infinity and `NaN` values are limited to `0x7f` and `0xff`. A register variable containing `e4m3` value must be declared using bit-size type. + +`e5m2` data format: + + +This data format is an 8-bit floating point format with 5 bits for exponent and 2 bits for mantissa. A register variable containing `e5m2` value must be declared using bit-size type. + +`tf32` data format: + + +This data format is a special 32-bit floating point format supported by the matrix multiply-and-accumulate instructions, with the same range as `.f32` and reduced precision (>=10 bits). The internal layout of `tf32` format is implementation defined. PTX facilitates conversion from single precision `.f32` type to `tf32` format. A register variable containing `tf32` data must be declared with `.b32` type. + +`e2m1` data format: + + +This data format is a 4-bit floating point format with 2 bits for exponent and 1 bit for mantissa. The `e2m1` encoding does not support infinity and `NaN`. `e2m1` values must be used in a packed format specified as `e2m1x2`. A register variable containing two `e2m1` values must be declared with `.b8` type. + +`e2m3` data format: + + +This data format is a 6-bit floating point format with 2 bits for exponent and 3 bits for mantissa. The `e2m3` encoding does not support infinity and `NaN`. `e2m3` values must be used in a packed format specified as `e2m3x2`. A register variable containing two `e2m3` values must be declared with `.b16` type where each `.b8` element has 6-bit floating point value and 2 MSB bits padded with zeros. + +`e3m2` data format: + + +This data format is a 6-bit floating point format with 3 bits for exponent and 2 bits for mantissa. The `e3m2` encoding does not support infinity and `NaN`. `e3m2` values must be used in a packed format specified as `e3m2x2`. A register variable containing two `e3m2` values must be declared with `.b16` type where each `.b8` element has 6-bit floating point value and 2 MSB bits padded with zeros. + +`ue8m0` data format: + + +This data format is an 8-bit unsigned floating-point format with 8 bits for exponent and 0 bits for mantissa. The `ue8m0` encoding does not support infinity. `NaN` value is limited to `0xff`. `ue8m0` values must be used in a packed format specified as `ue8m0x2`. A register variable containing two `ue8m0` values must be declared with `.b16` type. + +`ue4m3` data format: + + +This data format is a 7-bit unsigned floating-point format with 4 bits for exponent and 3 bits for mantissa. The `ue4m3` encoding does not support infinity. `NaN` value is limited to `0x7f`. A register variable containing single `ue4m3` value must be declared with `.b8` type having MSB bit padded with zero. + +Alternate data formats cannot be used as fundamental types. They are supported as source or destination formats by certain instructions. \ No newline at end of file diff --git a/content/cuda/docs/ptx-and/DOC.md b/content/cuda/docs/ptx-and/DOC.md new file mode 100644 index 00000000..1a9026c6 --- /dev/null +++ b/content/cuda/docs/ptx-and/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-and +description: Bitwise AND. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.8.1. Logic and Shift Instructions:and + +--- +title: "9.7.8.1. Logic and Shift Instructions:and" +section: 9.7.8.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.8.1. Logic and Shift Instructions:and + + +`and` + +Bitwise AND. + +Syntax + +and.type d, a, b; + + .type = { .pred, .b16, .b32, .b64 }; + +Description + +Compute the bit-wise and operation for the bits in `a` and `b`. + +Semantics + +d = a & b; + +Notes + +The size of the operands must match, but not necessarily the type. + +Allowed types include predicate registers. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +and.b32 x,q,r; + and.b32 sign,fpvalue,0x80000000; \ No newline at end of file diff --git a/content/cuda/docs/ptx-applypriority/DOC.md b/content/cuda/docs/ptx-applypriority/DOC.md new file mode 100644 index 00000000..c8460b22 --- /dev/null +++ b/content/cuda/docs/ptx-applypriority/DOC.md @@ -0,0 +1,55 @@ +--- +name: ptx-applypriority +description: Apply the cache eviction priority to the specified address in the specified + cache level. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.16. Data Movement and Conversion Instructions:applypriority + +--- +title: "9.7.9.16. Data Movement and Conversion Instructions:applypriority" +section: 9.7.9.16 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.16. Data Movement and Conversion Instructions:applypriority + + +`applypriority` + +Apply the cache eviction priority to the specified address in the specified cache level. + +Syntax + +applypriority{.global}.level::eviction_priority [a], size; + + .level::eviction_priority = { .L2::evict_normal }; + +Description + +The `applypriority` instruction applies the cache eviction priority specified by the `.level::eviction_priority` qualifier to the address range `[a..a+size)` in the specified cache level. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the specified address does not fall within the address window of `.global` state space then the behavior is undefined. + +The operand `size` is an integer constant that specifies the amount of data, in bytes, in the specified cache level on which the priority is to be applied. The only supported value for the `size` operand is 128. + +Supported addressing modes for operand `a` are described in [Addresses as Operands](<#addresses-as-operands>). `a` must be aligned to 128 bytes. + +PTX ISA Notes + +Introduced in PTX ISA version 7.4. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + +applypriority.global.L2::evict_normal [ptr], 128; \ No newline at end of file diff --git a/content/cuda/docs/ptx-array-declarations/DOC.md b/content/cuda/docs/ptx-array-declarations/DOC.md new file mode 100644 index 00000000..de025bc0 --- /dev/null +++ b/content/cuda/docs/ptx-array-declarations/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-array-declarations +description: Array declarations are provided to allow the programmer to reserve space. + To declare an array, the variable name is followed with dimensional declarations + similar to fixed-size array declarations in C... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.4.3. Array Declarations + +--- +title: "5.4.3. Array Declarations" +section: 5.4.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.4.3. Array Declarations + + +Array declarations are provided to allow the programmer to reserve space. To declare an array, the variable name is followed with dimensional declarations similar to fixed-size array declarations in C. The size of each dimension is a constant expression. + +Examples + +.local .u16 kernel[19][19]; + .shared .u8 mailbox[128]; + +The size of the array specifies how many elements should be reserved. For the declaration of array _kernel_ above, 19*19 = 361 halfwords are reserved, for a total of 722 bytes. + +When declared with an initializer, the first dimension of the array may be omitted. The size of the first array dimension is determined by the number of elements in the array initializer. + +Examples + +.global .u32 index[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; + .global .s32 offset[][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; + +Array _index_ has eight elements, and array _offset_ is a 4x2 array. \ No newline at end of file diff --git a/content/cuda/docs/ptx-arrays-as-operands/DOC.md b/content/cuda/docs/ptx-arrays-as-operands/DOC.md new file mode 100644 index 00000000..96c3c007 --- /dev/null +++ b/content/cuda/docs/ptx-arrays-as-operands/DOC.md @@ -0,0 +1,32 @@ +--- +name: ptx-arrays-as-operands +description: Arrays of all types can be declared, and the identifier becomes an address + constant in the space where the array is declared. The size of the array is a constant + in the program. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.4.2. Arrays as Operands + +--- +title: "6.4.2. Arrays as Operands" +section: 6.4.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 6.4.2. Arrays as Operands + + +Arrays of all types can be declared, and the identifier becomes an address constant in the space where the array is declared. The size of the array is a constant in the program. + +Array elements can be accessed using an explicitly calculated byte address, or by indexing into the array using square-bracket notation. The expression within square brackets is either a constant integer, a register variable, or a simple _register with constant offset_ expression, where the offset is a constant expression that is either added or subtracted from a register variable. If more complicated indexing is desired, it must be written as an address calculation prior to use. Examples are: + +ld.global.u32 s, a[0]; + ld.global.u32 s, a[N-1]; + mov.u32 s, a[1]; // move address of a[1] into s \ No newline at end of file diff --git a/content/cuda/docs/ptx-async-proxy/DOC.md b/content/cuda/docs/ptx-async-proxy/DOC.md new file mode 100644 index 00000000..85716c20 --- /dev/null +++ b/content/cuda/docs/ptx-async-proxy/DOC.md @@ -0,0 +1,29 @@ +--- +name: ptx-async-proxy +description: The `wgmma.mma_async` operations are performed in the asynchronous proxy + (or async proxy). +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.15.4. Async Proxy + +--- +title: "9.7.15.4. Async Proxy" +section: 9.7.15.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.15.4. Async Proxy + + +The `wgmma.mma_async` operations are performed in the asynchronous proxy (or async proxy). + +Accessing the same memory location across multiple proxies needs a cross-proxy fence. For the async proxy, `fence.proxy.async` should be used to synchronize memory between generic proxy and the async proxy. + +The completion of a `wgmma.mma_async` operation is followed by an implicit generic-async proxy fence. So the result of the asynchronous operation is made visible to the generic proxy as soon as its completion is observed. `wgmma.commit_group` and `wgmma.wait_group` operations must be used to wait for the completion of the `wgmma.mma_async` instructions. \ No newline at end of file diff --git a/content/cuda/docs/ptx-asynchronous-copy/DOC.md b/content/cuda/docs/ptx-asynchronous-copy/DOC.md new file mode 100644 index 00000000..8a6dcb16 --- /dev/null +++ b/content/cuda/docs/ptx-asynchronous-copy/DOC.md @@ -0,0 +1,585 @@ +--- +name: ptx-asynchronous-copy +description: An asynchronous copy operation performs the underlying operation asynchronously + in the background, thus allowing the issuing threads to perform subsequent tasks. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.25. Data Movement and Conversion Instructions: Asynchronous copy + +--- +title: "9.7.9.25. Data Movement and Conversion Instructions: Asynchronous copy" +section: 9.7.9.25 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.25. Data Movement and Conversion Instructions: Asynchronous copy + + +An asynchronous copy operation performs the underlying operation asynchronously in the background, thus allowing the issuing threads to perform subsequent tasks. + +An asynchronous copy operation can be a _bulk_ operation that operates on a large amount of data, or a _non-bulk_ operation that operates on smaller sized data. The amount of data handled by a bulk asynchronous operation must be a multiple of 16 bytes. + +An asynchronous copy operation typically includes the following sequence: + +* Optionally, reading from the tensormap. + + * Reading data from the source location(s). + + * Writing data to the destination location(s). + + * Writes being made visible to the executing thread or other threads. + +##### 9.7.9.25.1. [Completion Mechanisms for Asynchronous Copy Operations](<#data-movement-and-conversion-instructions-asynchronous-copy-completion-mechanisms>) + +A thread must explicitly wait for the completion of an asynchronous copy operation in order to access the result of the operation. Once an asynchronous copy operation is initiated, modifying the source memory location or tensor descriptor or reading from the destination memory location before the asynchronous operation completes, exhibits undefined behavior. + +This section describes two asynchronous copy operation completion mechanisms supported in PTX: Async-group mechanism and mbarrier-based mechanism. + +Asynchronous operations may be tracked by either of the completion mechanisms or both mechanisms. The tracking mechanism is instruction/instruction-variant specific. + +###### 9.7.9.25.1.1. [Async-group mechanism](<#data-movement-and-conversion-instructions-asynchronous-copy-completion-mechanisms-async-group>) + +When using the async-group completion mechanism, the issuing thread specifies a group of asynchronous operations, called _async-group_ , using a _commit_ operation and tracks the completion of this group using a _wait_ operation. The thread issuing the asynchronous operation must create separate _async-groups_ for bulk and non-bulk asynchronous operations. + +A _commit_ operation creates a per-thread _async-group_ containing all prior asynchronous operations tracked by _async-group_ completion and initiated by the executing thread but none of the asynchronous operations following the commit operation. A committed asynchronous operation belongs to a single _async-group_. + +When an _async-group_ completes, all the asynchronous operations belonging to that group are complete and the executing thread that initiated the asynchronous operations can read the result of the asynchronous operations. All _async-groups_ committed by an executing thread always complete in the order in which they were committed. There is no ordering between asynchronous operations within an _async-group_. + +A typical pattern of using _async-group_ as the completion mechanism is as follows: + + * Initiate the asynchronous operations. + + * Group the asynchronous operations into an _async-group_ using a _commit_ operation. + + * Wait for the completion of the async-group using the wait operation. + + * Once the _async-group_ completes, access the results of all asynchronous operations in that _async-group_. + + +###### 9.7.9.25.1.2. [Mbarrier-based mechanism](<#data-movement-and-conversion-instructions-asynchronous-copy-completion-mechanisms-mbarrier>) + +A thread can track the completion of one or more asynchronous operations using the current phase of an _mbarrier object_. When the current phase of the _mbarrier object_ is complete, it implies that all asynchronous operations tracked by this phase are complete, and all threads participating in that _mbarrier object_ can access the result of the asynchronous operations. + +The _mbarrier object_ to be used for tracking the completion of an asynchronous operation can be either specified along with the asynchronous operation as part of its syntax, or as a separate operation. For a bulk asynchronous operation, the _mbarrier object_ must be specified in the asynchronous operation, whereas for non-bulk operations, it can be specified after the asynchronous operation. + +A typical pattern of using mbarrier-based completion mechanism is as follows: + + * Initiate the asynchronous operations. + + * Set up an _mbarrier object_ to track the asynchronous operations in its current phase, either as part of the asynchronous operation or as a separate operation. + + * Wait for the _mbarrier object_ to complete its current phase using `mbarrier.test_wait` or `mbarrier.try_wait`. + + * Once the `mbarrier.test_wait` or `mbarrier.try_wait` operation returns `True`, access the results of the asynchronous operations tracked by the _mbarrier object_. + +##### 9.7.9.25.2. [Async Proxy](<#async-proxy>) + +The `cp{.reduce}.async.bulk` operations are performed in the _asynchronous proxy_ (or _async proxy_). + +Accessing the same memory location across multiple proxies needs a cross-proxy fence. For the _async proxy_ , `fence.proxy.async` should be used to synchronize memory between _generic proxy_ and the _async proxy_. + +The completion of a `cp{.reduce}.async.bulk` operation is followed by an implicit _generic-async_ proxy fence. So the result of the asynchronous operation is made visible to the generic proxy as soon as its completion is observed. _Async-group_ OR _mbarrier-based_ completion mechanism must be used to wait for the completion of the `cp{.reduce}.async.bulk` instructions. + +##### 9.7.9.25.3. [Data Movement and Conversion Instructions: Non-bulk copy](<#data-movement-and-conversion-instructions-non-bulk-copy>) + +###### 9.7.9.25.3.1. [Data Movement and Conversion Instructions: `cp.async`](<#data-movement-and-conversion-instructions-cp-async>) + +`cp.async` + +Initiates an asynchronous copy operation from one state space to another. + +Syntax + + + cp.async.ca.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size} + [dst], [src], cp-size{, src-size}{, cache-policy} ; + cp.async.cg.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size} + [dst], [src], 16{, src-size}{, cache-policy} ; + cp.async.ca.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size} + [dst], [src], cp-size{, ignore-src}{, cache-policy} ; + cp.async.cg.shared{::cta}.global{.level::cache_hint}{.level::prefetch_size} + [dst], [src], 16{, ignore-src}{, cache-policy} ; + + .level::cache_hint = { .L2::cache_hint } + .level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B } + cp-size = { 4, 8, 16 } + + +Description + +`cp.async` is a non-blocking instruction which initiates an asynchronous copy operation of data from the location specified by source address operand `src` to the location specified by destination address operand `dst`. Operand `src` specifies a location in the global state space and `dst` specifies a location in the shared state space. + +Operand `cp-size` is an integer constant which specifies the size of data in bytes to be copied to the destination `dst`. `cp-size` can only be 4, 8 and 16. + +Instruction `cp.async` allows optionally specifying a 32-bit integer operand `src-size`. Operand `src-size` represents the size of the data in bytes to be copied from `src` to `dst` and must be less than `cp-size`. In such case, remaining bytes in destination `dst` are filled with zeros. Specifying `src-size` larger than `cp-size` results in undefined behavior. + +The optional and non-immediate predicate argument `ignore-src` specifies whether the data from the source location `src` should be ignored completely. If the source data is ignored then zeros will be copied to destination `dst`. If the argument `ignore-src` is not specified then it defaults to `False`. + +Supported alignment requirements and addressing modes for operand `src` and `dst` are described in [Addresses as Operands](<#addresses-as-operands>). + +The mandatory `.async` qualifier indicates that the `cp` instruction will initiate the memory copy operation asynchronously and control will return to the executing thread before the copy operation is complete. The executing thread can then use [async-group based completion mechanism](<#data-movement-and-conversion-instructions-asynchronous-copy-completion-mechanisms-async-group>) or the [mbarrier based completion mechanism](<#data-movement-and-conversion-instructions-asynchronous-copy-completion-mechanisms-mbarrier>) to wait for completion of the asynchronous copy operation. No other synchronization mechanism guarantees the completion of the asynchronous copy operations. + +There is no ordering guarantee between two `cp.async` operations if they are not explicitly synchronized using `cp.async.wait_all` or `cp.async.wait_group` or [mbarrier instructions](<#parallel-synchronization-and-communication-instructions-mbarrier>). + +As described in [Cache Operators](<#cache-operators>), the `.cg` qualifier indicates caching of data only at global level cache L2 and not at L1 whereas `.ca` qualifier indicates caching of data at all levels including L1 cache. Cache operator are treated as performance hints only. + +`cp.async` is treated as a weak memory operation in the [Memory Consistency Model](<#memory-consistency-model>). + +The `.level::prefetch_size` qualifier is a hint to fetch additional data of the specified size into the respective cache level.The sub-qualifier `prefetch_size` can be set to either of `64B`, `128B`, `256B` thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes respectively. + +The qualifier `.level::prefetch_size` may only be used with `.global` state space and with generic addressing where the address points to `.global` state space. If the generic address does not fall within the address window of the global memory, then the prefetching behavior is undefined. + +The `.level::prefetch_size` qualifier is treated as a performance hint only. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +The qualifier `.level::cache_hint` is only supported for `.global` state space and for generic addressing where the address points to the `.global` state space. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for `.level::cache_hint` and `.level::prefetch_size` qualifiers introduced in PTX ISA version 7.4. + +Support for `ignore-src` operand introduced in PTX ISA version 7.5. + +Support for sub-qualifier `::cta` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_80` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Examples + + + cp.async.ca.shared.global [shrd], [gbl + 4], 4; + cp.async.ca.shared::cta.global [%r0 + 8], [%r1], 8; + cp.async.cg.shared.global [%r2], [%r3], 16; + + cp.async.cg.shared.global.L2::64B [%r2], [%r3], 16; + cp.async.cg.shared.global.L2::128B [%r0 + 16], [%r1], 16; + cp.async.cg.shared.global.L2::256B [%r2 + 32], [%r3], 16; + + createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 cache-policy, 0.25; + cp.async.ca.shared.global.L2::cache_hint [%r2], [%r1], 4, cache-policy; + + cp.async.ca.shared.global [shrd], [gbl], 4, p; + cp.async.cg.shared.global.L2::cache_hint [%r0], [%r2], 16, q, cache-policy; + + +###### 9.7.9.25.3.2. [Data Movement and Conversion Instructions: `cp.async.commit_group`](<#data-movement-and-conversion-instructions-cp-async-commit-group>) + +`cp.async.commit_group` + +Commits all prior initiated but uncommitted `cp.async` instructions into a _cp.async-group_. + +Syntax + + + cp.async.commit_group ; + + +Description + +`cp.async.commit_group` instruction creates a new _cp.async-group_ per thread and batches all prior `cp.async` instructions initiated by the executing thread but not committed to any _cp.async-group_ into the new _cp.async-group_. If there are no uncommitted `cp.async` instructions then `cp.async.commit_group` results in an empty _cp.async-group._ + +An executing thread can wait for the completion of all `cp.async` operations in a _cp.async-group_ using `cp.async.wait_group`. + +There is no memory ordering guarantee provided between any two `cp.async` operations within the same _cp.async-group_. So two or more `cp.async` operations within a _cp.async-group_ copying data to the same location results in undefined behavior. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + // Example 1: + cp.async.ca.shared.global [shrd], [gbl], 4; + cp.async.commit_group ; // Marks the end of a cp.async group + + // Example 2: + cp.async.ca.shared.global [shrd1], [gbl1], 8; + cp.async.ca.shared.global [shrd1+8], [gbl1+8], 8; + cp.async.commit_group ; // Marks the end of cp.async group 1 + + cp.async.ca.shared.global [shrd2], [gbl2], 16; + cp.async.cg.shared.global [shrd2+16], [gbl2+16], 16; + cp.async.commit_group ; // Marks the end of cp.async group 2 + + +###### 9.7.9.25.3.3. [Data Movement and Conversion Instructions: `cp.async.wait_group` / `cp.async.wait_all`](<#data-movement-and-conversion-instructions-cp-async-wait-group>) + +`cp.async.wait_group`, `cp.async.wait_all` + +Wait for completion of prior asynchronous copy operations. + +Syntax + + + cp.async.wait_group N; + cp.async.wait_all ; + + +Description + +`cp.async.wait_group` instruction will cause executing thread to wait till only `N` or fewer of the most recent _cp.async-group_ s are pending and all the prior _cp.async-group_ s committed by the executing threads are complete. For example, when `N` is 0, the executing thread waits on all the prior _cp.async-group_ s to complete. Operand `N` is an integer constant. + +`cp.async.wait_all` is equivalent to : + + + cp.async.commit_group; + cp.async.wait_group 0; + + +An empty _cp.async-group_ is considered to be trivially complete. + +Writes performed by `cp.async` operations are made visible to the executing thread only after: + + 1. The completion of `cp.async.wait_all` or + + 2. The completion of `cp.async.wait_group` on the _cp.async-group_ in which the `cp.async` belongs to or + + 3. [mbarrier.test_wait](<#parallel-synchronization-and-communication-instructions-mbarrier-test-wait-try-wait>) returns `True` on an _mbarrier object_ which is tracking the completion of the `cp.async` operation. + + +There is no ordering between two `cp.async` operations that are not synchronized with `cp.async.wait_all` or `cp.async.wait_group` or [mbarrier objects](<#parallel-synchronization-and-communication-instructions-mbarrier>). + +`cp.async.wait_group` and `cp.async.wait_all` does not provide any ordering and visibility guarantees for any other memory operation apart from `cp.async`. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + // Example of .wait_all: + cp.async.ca.shared.global [shrd1], [gbl1], 4; + cp.async.cg.shared.global [shrd2], [gbl2], 16; + cp.async.wait_all; // waits for all prior cp.async to complete + + // Example of .wait_group : + cp.async.ca.shared.global [shrd3], [gbl3], 8; + cp.async.commit_group; // End of group 1 + + cp.async.cg.shared.global [shrd4], [gbl4], 16; + cp.async.commit_group; // End of group 2 + + cp.async.cg.shared.global [shrd5], [gbl5], 16; + cp.async.commit_group; // End of group 3 + + cp.async.wait_group 1; // waits for group 1 and group 2 to complete + +##### 9.7.9.25.4. [Data Movement and Conversion Instructions: Bulk copy](<#data-movement-and-conversion-instructions-bulk-copy>) + +###### 9.7.9.25.4.1. [Data Movement and Conversion Instructions: `cp.async.bulk`](<#data-movement-and-conversion-instructions-cp-async-bulk>) + +`cp.async.bulk` + +Initiates an asynchronous copy operation from one state space to another. + +Syntax + + + // global -> shared::cta + cp.async.bulk.dst.src.completion_mechanism{.level::cache_hint} + [dstMem], [srcMem], size, [mbar] {, cache-policy} + + .dst = { .shared::cta } + .src = { .global } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + .level::cache_hint = { .L2::cache_hint } + + + // global -> shared::cluster + cp.async.bulk.dst.src.completion_mechanism{.multicast}{.level::cache_hint} + [dstMem], [srcMem], size, [mbar] {, ctaMask} {, cache-policy} + + .dst = { .shared::cluster } + .src = { .global } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + .level::cache_hint = { .L2::cache_hint } + .multicast = { .multicast::cluster } + + + // shared::cta -> shared::cluster + cp.async.bulk.dst.src.completion_mechanism [dstMem], [srcMem], size, [mbar] + + .dst = { .shared::cluster } + .src = { .shared::cta } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + + + // shared::cta -> global + cp.async.bulk.dst.src.completion_mechanism{.level::cache_hint}{.cp_mask} + [dstMem], [srcMem], size {, cache-policy} {, byteMask} + + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + .level::cache_hint = { .L2::cache_hint } + + +Description + +`cp.async.bulk` is a non-blocking instruction which initiates an asynchronous bulk-copy operation from the location specified by source address operand `srcMem` to the location specified by destination address operand `dstMem`. + +The direction of bulk-copy is from the state space specified by the `.src` modifier to the state space specified by the `.dst` modifiers. + +The 32-bit operand `size` specifies the amount of memory to be copied, in terms of number of bytes. `size` must be a multiple of 16. If the value is not a multiple of 16, then the behavior is undefined. The memory range `[dstMem, dstMem + size - 1]` must not overflow the destination memory space and the memory range `[srcMem, srcMem + size - 1]` must not overflow the source memory space. Otherwise, the behavior is undefined. The addresses `dstMem` and `srcMem` must be aligned to 16 bytes. + +When the destination of the copy is `.shared::cta` the destination address has to be in the shared memory of the executing CTA within the cluster, otherwise the behavior is undefined. + +When the source of the copy is `.shared::cta` and the destination is `.shared::cluster`, the destination has to be in the shared memory of a different CTA within the cluster. + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported on the instruction variant. The completion mechanisms that are supported for different variants are summarized in the following table: + +.completion-mechanism | `.dst` | `.src` | Completion mechanism +---|---|---|--- +`.mbarrier::...` | `.shared::cta` | `.global` | mbarrier based +`.shared::cluster` | `.global` +`.shared::cluster` | `.shared::cta` +`.bulk_group` | `.global` | `.shared::cta` | _Bulk async-group_ based + +The modifier `.mbarrier::complete_tx::bytes` specifies that the `cp.async.bulk` variant uses mbarrier based completion mechanism. The [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation, with `completeCount` argument equal to amount of data copied in bytes, will be performed on the mbarrier object specified by the operand `mbar`. This instruction accesses its `mbarrier` operand using generic-proxy. + +The modifier `.bulk_group` specifies that the `cp.async.bulk` variant uses _bulk async-group_ based completion mechanism. + +The optional modifier `.multicast::cluster` allows copying of data from global memory to shared memory of multiple CTAs in the cluster. Operand `ctaMask` specifies the destination CTAs in the cluster such that each bit position in the 16-bit `ctaMask` operand corresponds to the `%ctaid` of the destination CTA. The source data is multicast to the same CTA-relative offset as `dstMem` in the shared memory of each destination CTA. The mbarrier signal is also multicast to the same CTA-relative offset as `mbar` in the shared memory of the destination CTA. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. The qualifier `.level::cache_hint` is only supported when at least one of the `.src` or `.dst` statespaces is `.global` state space. + +When the optional qualifier `.cp_mask` is specified, the argument `byteMask` is required. The i-th bit in the 16-bit wide `byteMask` operand specifies whether the i-th byte of each 16-byte wide chunk of source data is copied to the destination. If the bit is set, the byte is copied. + +The copy operation in `cp.async.bulk` is treated as a weak memory operation and the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the mbarrier has `.release` semantics at the `.cluster` scope as described in the [Memory Consistency Model](<#memory-consistency-model>). + +Notes + +`.multicast::cluster` qualifier is optimized for target architecture `sm_90a`/`sm_100f`/`sm_100a`/ `sm_103f`/`sm_103a`/`sm_110f`/`sm_110a` and may have substantially reduced performance on other targets and hence `.multicast::cluster` is advised to be used with `.target` `sm_90a`/`sm_100f`/ `sm_100a`/`sm_103f`/`sm_103a`/`sm_110f`/`sm_110a`. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Support for `.shared::cta` as destination state space is introduced in PTX ISA version 8.6. + +Support for `.cp_mask` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_90` or higher. + +`.multicast::cluster` qualifier advised to be used with `.target` `sm_90a` or `sm_100f` or `sm_100a` or `sm_103f` or `sm_103a` or `sm_110f` or `sm_110a`. + +Support for `.cp_mask` qualifier requires `sm_100` or higher. + +Examples + + + // .global -> .shared::cta (strictly non-remote): + cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes [dstMem], [srcMem], size, [mbar]; + + cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint + [dstMem], [srcMem], size, [mbar], cache-policy; + + // .global -> .shared::cluster: + cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [dstMem], [srcMem], size, [mbar]; + + cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster + [dstMem], [srcMem], size, [mbar], ctaMask; + + cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint + [dstMem], [srcMem], size, [mbar], cache-policy; + + + // .shared::cta -> .shared::cluster (strictly remote): + cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [dstMem], [srcMem], size, [mbar]; + + // .shared::cta -> .global: + cp.async.bulk.global.shared::cta.bulk_group [dstMem], [srcMem], size; + + cp.async.bulk.global.shared::cta.bulk_group.L2::cache_hint} [dstMem], [srcMem], size, cache-policy; + + // .shared::cta -> .global with .cp_mask: + cp.async.bulk.global.shared::cta.bulk_group.L2::cache_hint.cp_mask [dstMem], [srcMem], size, cache-policy, byteMask; + + +###### 9.7.9.25.4.2. [Data Movement and Conversion Instructions: `cp.reduce.async.bulk`](<#data-movement-and-conversion-instructions-cp-reduce-async-bulk>) + +`cp.reduce.async.bulk` + +Initiates an asynchronous reduction operation. + +Syntax + + + cp.reduce.async.bulk.dst.src.completion_mechanism.redOp.type + [dstMem], [srcMem], size, [mbar] + + .dst = { .shared::cluster } + .src = { .shared::cta } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + .redOp= { .and, .or, .xor, + .add, .inc, .dec, + .min, .max } + .type = { .b32, .u32, .s32, .b64, .u64 } + + + cp.reduce.async.bulk.dst.src.completion_mechanism{.level::cache_hint}.redOp.type + [dstMem], [srcMem], size{, cache-policy} + + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + .level::cache_hint = { .L2::cache_hint } + .redOp= { .and, .or, .xor, + .add, .inc, .dec, + .min, .max } + .type = { .f16, .bf16, .b32, .u32, .s32, .b64, .u64, .s64, .f32, .f64 } + + + cp.reduce.async.bulk.dst.src.completion_mechanism{.level::cache_hint}.add.noftz.type + [dstMem], [srcMem], size{, cache-policy} + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + .type = { .f16, .bf16 } + + +Description + +`cp.reduce.async.bulk` is a non-blocking instruction which initiates an asynchronous reduction operation on an array of memory locations specified by the destination address operand `dstMem` with the source array whose location is specified by the source address operand `srcMem`. The size of the source and the destination array must be the same and is specified by the operand `size`. + +Each data element in the destination array is reduced inline with the corresponding data element in the source array with the reduction operation specified by the modifier `.redOp`. The type of each data element in the source and the destination array is specified by the modifier `.type`. + +The source address operand `srcMem` is located in the state space specified by `.src` and the destination address operand `dstMem` is located in the state specified by the `.dst`. + +The 32-bit operand `size` specifies the amount of memory to be copied from the source location and used in the reduction operation, in terms of number of bytes. `size` must be a multiple of 16. If the value is not a multiple of 16, then the behavior is undefined. The memory range `[dstMem, dstMem + size - 1]` must not overflow the destination memory space and the memory range `[srcMem, srcMem + size - 1]` must not overflow the source memory space. Otherwise, the behavior is undefined. The addresses `dstMem` and `srcMem` must be aligned to 16 bytes. + +The operations supported by `.redOp` are classified as follows: + + * The bit-size operations are `.and`, `.or`, and `.xor`. + + * The integer operations are `.add`, `.inc`, `.dec`, `.min`, and `.max`. The `.inc` and `.dec` operations return a result in the range `[0..x]` where `x` is the value at the source state space. + + * The floating point operation `.add` rounds to the nearest even. The current implementation of `cp.reduce.async.bulk.add.f32` flushes subnormal inputs and results to sign-preserving zero. The `cp.reduce.async.bulk.add.f16` and `cp.reduce.async.bulk.add.bf16` operations require `.noftz` qualifier. It preserves input and result subnormals, and does not flush them to zero. + + +The following table describes the valid combinations of `.redOp` and element type: + +`.dst` | `.redOp` | Element type +---|---|--- +`.shared::cluster` | `.add` | `.u32`, `.s32`, `.u64` +`.min`, `.max` | `.u32`, `.s32` +`.inc`, `.dec` | `.u32` +`.and`, `.or`, `.xor` | `.b32` +`.global` | `.add` | `.u32`, `.s32`, `.u64`, `.f32`, `.f64`, `.f16`, `.bf16` +`.min`, `.max` | `.u32`, `.s32`, `.u64`, `.s64`, `.f16`, `.bf16` +`.inc`, `.dec` | `.u32` +`.and`, `.or`, `.xor` | `.b32`, `.b64` + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported on the instruction variant. The completion mechanisms that are supported for different variants are summarized in the following table: + +.completion-mechanism | `.dst` | `.src` | Completion mechanism +---|---|---|--- +`.mbarrier::...` | `.shared::cluster` | `.global` | mbarrier based +`.shared::cluster` | `.shared::cta` +`.bulk_group` | `.global` | `.shared::cta` | _Bulk async-group_ based + +The modifier `.mbarrier::complete_tx::bytes` specifies that the `cp.reduce.async.bulk` variant uses mbarrier based completion mechanism. The [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation, with `completeCount` argument equal to amount of data copied in bytes, will be performed on the mbarrier object specified by the operand `mbar`. This instruction accesses its `mbarrier` operand using generic-proxy. + +The modifier `.bulk_group` specifies that the `cp.reduce.async.bulk` variant uses _bulk async-group_ based completion mechanism. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. The qualifier `.level::cache_hint` is only supported when at least one of the `.src` or `.dst` statespaces is `.global` state space. + +Each reduction operation performed by the `cp.reduce.async.bulk` has individually `.relaxed.gpu` memory ordering semantics. The load operations in `cp.reduce.async.bulk` are treated as weak memory operation and the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the mbarrier has `.release` semantics at the `.cluster` scope as described in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + cp.reduce.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes.add.u64 + [dstMem], [srcMem], size, [mbar]; + + cp.reduce.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes.min.s32 + [dstMem], [srcMem], size, [mbar]; + + cp.reduce.async.bulk.global.shared::cta.bulk_group.min.f16 [dstMem], [srcMem], size; + + cp.reduce.async.bulk.global.shared::cta.bulk_group.L2::cache_hint.xor.s32 [dstMem], [srcMem], size, policy; + + cp.reduce.async.bulk.global.shared::cta.bulk_group.add.noftz.f16 [dstMem], [srcMem], size; + + +###### 9.7.9.25.4.3. [Data Movement and Conversion Instructions: `cp.async.bulk.prefetch`](<#data-movement-and-conversion-instructions-cp-async-bulk-prefetch>) + +`cp.async.bulk.prefetch` + +Provides a hint to the system to initiate the asynchronous prefetch of data to the cache. + +Syntax + + + cp.async.bulk.prefetch.L2.src{.level::cache_hint} [srcMem], size {, cache-policy} + + .src = { .global } + .level::cache_hint = { .L2::cache_hint } + + +Description + +`cp.async.bulk.prefetch` is a non-blocking instruction which may initiate an asynchronous prefetch of data from the location specified by source address operand `srcMem`, in `.src` statespace, to the L2 cache. + +The 32-bit operand `size` specifies the amount of memory to be prefetched in terms of number of bytes. `size` must be a multiple of 16. If the value is not a multiple of 16, then the behavior is undefined. The address `srcMem` must be aligned to 16 bytes. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +`cp.async.bulk.prefetch` is treated as a weak memory operation in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + cp.async.bulk.prefetch.L2.global [srcMem], size; + + cp.async.bulk.prefetch.L2.global.L2::cache_hint [srcMem], size, policy; \ No newline at end of file diff --git a/content/cuda/docs/ptx-asynchronous-operations/DOC.md b/content/cuda/docs/ptx-asynchronous-operations/DOC.md new file mode 100644 index 00000000..4a3edafb --- /dev/null +++ b/content/cuda/docs/ptx-asynchronous-operations/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-asynchronous-operations +description: Some PTX instructions (all variants of `cp.async`, `cp.async.bulk`, `cp.reduce.async.bulk`, + `wgmma.mma_async`) perform operations that are asynchronous to the thread that executed + the instruction. The... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.1.1. Asynchronous Operations + +--- +title: "8.9.1.1. Asynchronous Operations" +section: 8.9.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 8.9.1.1. Asynchronous Operations + + +Some PTX instructions (all variants of `cp.async`, `cp.async.bulk`, `cp.reduce.async.bulk`, `wgmma.mma_async`) perform operations that are asynchronous to the thread that executed the instruction. These asynchronous operations are ordered after prior instructions in the same thread (except in the case of `wgmma.mma_async`), but they are not part of the program order for that thread. Instead, they provide weaker ordering guarantees as documented in the instruction description. + +For example, the loads and stores performed as part of a `cp.async` are ordered with respect to each other, but not to those of any other `cp.async` instructions initiated by the same thread, nor any other instruction subsequently issued by the thread with the exception of `cp.async.commit_group` or `cp.async.mbarrier.arrive`. The asynchronous mbarrier [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation performed by a `cp.async.mbarrier.arrive` instruction is ordered with respect to the memory operations performed by all prior `cp.async` operations initiated by the same thread, but not to those of any other instruction issued by the thread. The implicit mbarrier [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation that is part of all variants of `cp.async.bulk` and `cp.reduce.async.bulk` instructions is ordered only with respect to the memory operations performed by the same asynchronous instruction, and in particular it does not transitively establish ordering with respect to prior instructions from the issuing thread. \ No newline at end of file diff --git a/content/cuda/docs/ptx-asynchronous-warpgroup-level-matrix-multiply-accumulate-operation-usingwgmmamma-asyncinstruction/DOC.md b/content/cuda/docs/ptx-asynchronous-warpgroup-level-matrix-multiply-accumulate-operation-usingwgmmamma-asyncinstruction/DOC.md new file mode 100644 index 00000000..6c17e3ac --- /dev/null +++ b/content/cuda/docs/ptx-asynchronous-warpgroup-level-matrix-multiply-accumulate-operation-usingwgmmamma-asyncinstruction/DOC.md @@ -0,0 +1,741 @@ +--- +name: ptx-asynchronous-warpgroup-level-matrix-multiply-accumulate-operation-usingwgmmamma-asyncinstruction +description: This section describes warpgroup level `wgmma.mma_async` instruction + and the organization of various matrices involved in this instruction. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.15.5. Asynchronous Warpgroup Level Matrix Multiply-Accumulate Operation usingwgmma.mma_asyncinstruction + +--- +title: "9.7.15.5. Asynchronous Warpgroup Level Matrix Multiply-Accumulate Operation usingwgmma.mma_asyncinstruction" +section: 9.7.15.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.15.5. Asynchronous Warpgroup Level Matrix Multiply-Accumulate Operation usingwgmma.mma_asyncinstruction + + +This section describes warpgroup level `wgmma.mma_async` instruction and the organization of various matrices involved in this instruction. + +##### 9.7.15.5.1. [Register Fragments and Shared Memory Matrix Layouts](<#asynchronous-warpgroup-level-matrix-fragment>) + +The input matrix A of the warpgroup wide MMA operations can be either in registers or in the shared memory. The input matrix B of the warpgroup wide MMA operations must be in the shared memory. This section describes the layouts of register fragments and shared memory expected by the warpgroup MMA instructions. + +When the matrices are in shared memory, their starting addresses must be aligned to 16 bytes. + +###### 9.7.15.5.1.1. [Register Fragments](<#asynchronous-warpgroup-level-matrix-register-fragment>) + +This section describes the organization of various matrices located in register operands of the `wgmma.mma_async` instruction. + +####### 9.7.15.5.1.1.1. [Matrix Fragments for `wgmma.mma_async.m64nNk16`](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n16>) + +A warpgroup executing `wgmma.mma_async.m64nNk16` will compute an MMA operation of shape `.m64nNk16` where N is a valid `n` dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A in registers: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.f16`/`.bf16` | A vector expression containing four `.f16x2` registers, with each register containing two `.f16`/ `.bf16` elements from matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 + +The layout of the fragments held by different threads is shown in [Figure 148](<#wgmma-64n16-a>). + +![_images/wgmma-64N16-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N16-A.png) + +Figure 148 WGMMA .m64nNk16 register fragment layout for matrix A. + + * Accumulator D: + +.dtype | Fragment | Elements (low to high) +---|---|--- +`.f16` | A vector expression containing N/4 number of `.f16x2` registers, with each register containing two `.f16` elements from matrix D. | d0, d1, d2, d3, …, dX, dY, dZ, dW where `X = N/2 - 4` `Y = N/2 - 3` `Z = N/2 - 2` `W = N/2 - 1` `N = 8*i where i = {1, 2, ... , 32}` +`.f32` | A vector expression containing N/2 number of `.f32` registers. + +The layout of the fragments held by different threads is shown in [Figure 149](<#wgmma-64n16-d>). + +![_images/wgmma-64N16-D.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N16-D.png) + +Figure 149 WGMMA .m64nNk16 register fragment layout for accumulator matrix D. + + +####### 9.7.15.5.1.1.2. [Matrix Fragments for `wgmma.mma_async.m64nNk8`](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n8>) + +A warpgroup executing `wgmma.mma_async.m64nNk8` will compute an MMA operation of shape `.m64nNk8` where N is a valid `n` dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A in registers: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.tf32` | A vector expression containing four `.b32` registers containing four `.tf32` elements from matrix A. | a0, a1, a2, a3 + +The layout of the fragments held by different threads is shown in [Figure 150](<#wgmma-64n8-a>). + +![_images/wgmma-64N8-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N8-A.png) + +Figure 150 WGMMA .m64nNk8 register fragment layout for matrix A. + + * Accumulator D: + +.dtype | Fragment | Elements (low to high) +---|---|--- +`.f32` | A vector expression containing N/2 number of `.f32` registers. | d0, d1, d2, d3, …, dX, dY, dZ, dW where `X = N/2 - 4` `Y = N/2 - 3` `Z = N/2 - 2` `W = N/2 - 1` `N = 8*i where i = {1, 2, ... , 32}` + +The layout of the fragments held by different threads is shown in [Figure 151](<#wgmma-64n8-d>). + +![_images/wgmma-64N8-D.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N8-D.png) + +Figure 151 WGMMA .m64nNk8 register fragment layout for accumulator matrix D. + + +####### 9.7.15.5.1.1.3. [Matrix Fragments for `wgmma.mma_async.m64nNk32`](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n32>) + +A warpgroup executing `wgmma.mma_async.m64nNk32` will compute an MMA operation of shape `.m64nNk32` where N is a valid `n` dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A in registers: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.s8`/`.u8` | A vector expression containing four `.b32` registers, with each register containing four `.u8`/ `.s8` elements from matrix A. | a0, a1, a2, a3, … , a14, a15 +`.e4m3`/ `.e5m2` | A vector expression containing four `.b32` registers, with each register containing four `.e4m3`/ `.e5m2` elements from matrix A. + +The layout of the fragments held by different threads is shown in [Figure 152](<#wgmma-64n32-a>). + +![_images/wgmma-64N32-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N32-A.png) + +Figure 152 WGMMA .m64nNk32 register fragment layout for matrix A. + + * Accumulator D: + +.dtype | Fragment | Elements (low to high) | Miscellaneous Information +---|---|---|--- +`.s32` | A vector expression containing N/2 number of `.s32` registers. | d0, d1, d2, d3, …, dX, dY, dZ, dW where `X = N/2 - 4` `Y = N/2 - 3` `Z = N/2 - 2` `W = N/2 - 1` `N` depends on .dtype, as described in the next column. | `N = 8*i where i = {1, 2, 3, 4}` + +> `= 16*i where i = {3, 4, ..., 15, 16}` + +`.f32` | A vector expression containing N/2 number of `.f32` registers. | `N = 8*i where i = {1, 2, ... , 32}` +`.f16` | A vector expression containing N/4 number of `.f16x2` registers, with each register containing two `.f16` elements from matrix D. + +The layout of the fragments held by different threads is shown in [Figure 153](<#wgmma-64n32-d>). + +![_images/wgmma-64N32-D.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N32-D.png) + +Figure 153 WGMMA .m64nNk32 register fragment layout for accumulator matrix D. + + +####### 9.7.15.5.1.1.4. [Matrix Fragments for `wgmma.mma_async.m64nNk256`](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n256>) + +A warpgroup executing `wgmma.mma_async.m64nNk256` will compute an MMA operation of shape `.m64nNk256` where N is a valid `n` dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A in registers: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing four `.b32` registers, with each register containing thirty two `.b1` element from matrix A. | a0, a1, a2, …, a127 + +The layout of the fragments held by different threads is shown in [Figure 154](<#wgmma-64n256-a>). + +![_images/wgmma-64N256-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N256-A.png) + +Figure 154 WGMMA .m64nNk256 register fragment layout for matrix A. + + * Accumulator D: + +.dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing N/2 number of `.s32` registers. | d0, d1, d2, d3, …, dX, dY, dZ, dW where `X = N/2 - 4` `Y = N/2 - 3` `Z = N/2 - 2` `W = N/2 - 1` `N = 8*i where i = {1, 2, 3, 4}` `= 16*i where i = {3, 4, ..., 15, 16}` + +The layout of the fragments held by different threads is shown in [Figure 155](<#wgmma-64n256-d>). + +![_images/wgmma-64N256-D.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/wgmma-64N256-D.png) + +Figure 155 WGMMA .m64nNk256 register fragment layout for accumulator matrix D. + + +###### 9.7.15.5.1.2. [Shared Memory Matrix Layout](<#asynchronous-warpgroup-level-matrix-shared-memory-layout>) + +If the argument `imm-trans-a` / `imm-trans-b` of the instruction `wgmma.mma_async{.sp}` is 0, then _K-major_ is used for matrix `A` / `B` respectively. If the value of argument `imm-trans-a` is 1 then _M-major_ is used for matrix `A`. If the value of the argument `imm-trans-b` is 1, then _N-major_ is used for matrix `B`. + +In a column-major default BLAS library such as cuBLAS, the matrices `A` and `B` with and without transpose can be classified as either _K-Major_ or _M-or-N-Major_ as shown in the following table: + +| Non-Transposed | Transposed +---|---|--- +A | K-major | M-major +B | K-major | N-major + +To avoid confusion with `A`, `B`, `row-major`, `col-major`, `transpose`, and `non-transpose`, we will use _MN-Major_ and _K-Major_ throughout this section. + +The matrices in the shared memory are made up of one or more “swizzle layout atom”. The exact layout of these swizzle atoms depends on the swizzling mode, swizzle-atomicity, and the leading dimension. The layout of the swizzle are shown in [Table 38](<#asynchronous-warpgroup-level-swizzle-lead-dim>). + +Table 38 Various combinations of swizzling mode, leading dimension and swizzle-atom layout Swizzling mode | Leading Dimension / Major-ness | Swizzle atom layout (128b element) +---|---|--- +128B Swizzling Mode | M/N | 8x8 +K | 8x8 +64B Swizzling Mode | M/N | 4x8 +K | 8x4 +32B Swizzling Mode | M/N | 2x8 +K | 8x2 +None | M/N | 1x8 +K | 8x1 + +The above shapes are for elements of size 128 bits. For smaller elements sizes, the same shapes would get multiplied along the leading dimension by a factor of `128/sizeof_bits(Element)`. For example, 128B MN major swizzle atom would have a shape of `(8*(128/32))x8 = 32x8` for `tf32` tensor core inputs. + +Examples + +The following are some example layouts of _MxK_ or _KxN_ matrices with various swizzling modes, and are in units of 128b elements as shown by each colored cell as shown in [Figure 156](<#async-warpgroup-smem-layout-128b-mn>), [Figure 157](<#async-warpgroup-smem-layout-128b-k>), [Figure 158](<#async-warpgroup-smem-layout-64b-mn>), [Figure 159](<#async-warpgroup-smem-layout-64b-k>), [Figure 160](<#async-warpgroup-smem-layout-32b-mn>), [Figure 161](<#async-warpgroup-smem-layout-32b-k>), [Figure 162](<#async-warpgroup-smem-layout-mn-interleaved>), [Figure 163](<#async-warpgroup-smem-layout-k-interleaved>). + +![_images/async-warpgroup-smem-layout-128B-mn.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-128B-mn.png) + +Figure 156 MN major 128B swizzling + +![_images/async-warpgroup-smem-layout-128B-k.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-128B-k.png) + +Figure 157 K major 128B swizzling + +![_images/async-warpgroup-smem-layout-64B-mn.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-64B-mn.png) + +Figure 158 MN major 64B swizzling + +![_images/async-warpgroup-smem-layout-64B-k.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-64B-k.png) + +Figure 159 K major 64B swizzling + +![_images/async-warpgroup-smem-layout-32B-mn.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-32B-mn.png) + +Figure 160 MN major 32B swizzling + +![_images/async-warpgroup-smem-layout-32B-k.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-32B-k.png) + +Figure 161 K major 32B swizzling + +![_images/async-warpgroup-smem-layout-mn-interleaved.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-mn-interleaved.png) + +Figure 162 MN major interleaved + +![_images/async-warpgroup-smem-layout-k-interleaved.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-k-interleaved.png) + +Figure 163 K major interleaved + +Following are some of the examples of the 128B swizzling layout for `tf32` element type. + + * K-Major: [Figure 164](<#async-warpgroup-smem-layout-128b-k-tf32>) + +> ![_images/async-warpgroup-smem-layout-128B-k-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-128B-k-tf32.png) +> +> Figure 164 K major + + * MN-Major: [Figure 165](<#async-warpgroup-smem-layout-128b-mn-tf32>) + +> ![_images/async-warpgroup-smem-layout-128B-mn-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-smem-layout-128B-mn-tf32.png) +> +> Figure 165 MN major + + +####### 9.7.15.5.1.2.1. [Major-ness supported by Strides](<#asynchronous-warpgroup-level-majorness-supported-by-strides>) + +There are two strides involved while accessing a matrix from shared memory: + + 1. Leading dimension byte offset + + 2. Stride dimension byte offset + + +######## 9.7.15.5.1.2.1.1. [Leading Dimension Byte Offset](<#asynchronous-warpgroup-level-leading-dimension-byte-offset>) + +The leading dimension byte offset is defined differently for transposed and non-transposed matrices. The leading byte offset is defined as follows for matrices whose element types are normalized to 128-bits: + +Major-ness | Definition +---|--- +K-Major | + + * No-Swizzling: the offset from the first column to the second columns of the 8x2 tile in the 128-bit element type normalized matrix. + * Swizzled layouts: not used, assumed to be 1. + + +MN-Major | + + * Interleave: offset from the first 8 columns to the next 8 columns. + * Swizzled layouts: offset from the first (swizzle-byte-size/16) rows to the next (swizzle-byte-size/16) rows. + + + +######## 9.7.15.5.1.2.1.2. [Stride Dimension Byte Offset](<#asynchronous-warpgroup-level-stride-dimension-byte-offset>) + +The stride dimension byte offset is defined differently for transposed and non-transposed matrices. The stride dimension byte offset is defined as follows for matrices whose element types are normalized to 128-bits: + +Major-ness | Definition +---|--- +K-Major | The offset from the first 8 rows to the next 8 rows. +MN-Major | + + * Interleave: offset from the first row to the next row. + * Swizzled layout: offset from the first 8 columns to the next 8 columns + + + +######## 9.7.15.5.1.2.1.3. [Canonical Layouts](<#asynchronous-warpgroup-level-canonical-layouts>) + +In terms of [CuTe layouts]() the canonical layout can be expressed as follows: + +Major- ness | Swizzling mode | Canonical Layout without swizzling | [Swizzling]() on the previous column +---|---|---|--- +MN- major | No-swizzling or Interleaved | ((T,1,m),(8,k)):((1,T,SBO),(1T,LBO)) | Swizzle<0, 4, 3> +32B Swizzling | ((T,2,m),(8,k)):((1,T,LBO),(2T,SBO)) | Swizzle<1, 4, 3> +64B Swizzling | ((T,4,m),(8,k)):((1,T,LBO),(4T,SBO)) | Swizzle<2, 4, 3> +128B Swizzling | ((T,8,m),(8,k)):((1,T,LBO),(8T,SBO)) | Swizzle<3, 4, 3> +K- major | No-swizzling or Interleaved | ((8,m),(T,2k)):((1T,SBO),(1,LBO)) | Swizzle<0, 4, 3> +32B Swizzling | ((8,m),(T,2k)):((2T,SBO),(1,T)) | Swizzle<1, 4, 3> +64B Swizzling | ((8,m),(T,2k)):((4T,SBO),(1,T)) | Swizzle<2, 4, 3> +128B Swizzling | ((8,m),(T,2k)):((8T,SBO),(1,T)) | Swizzle<3, 4, 3> + +where + + * T = 128 / sizeof-elements-in-bits T represents scale factor which normalizes matrix element types to 128-bits. + + * m represents the number of repeating patterns across rows. + + * k represents the number of repeating patterns across columns. + + +Examples + + * K-Major, no-swizzling and tf32 type: [Figure 166](<#async-warpgroup-k-no-swizzle-tf32>) + +![_images/async-warpgroup-k-no-swizzle-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-k-no-swizzle-tf32.png) + +Figure 166 K major, no-swizzling and tf32 type + +the strides and related details are as follows: + +Exact layout : Swizzle<0,4,3> o ((8,2),(4,4)):((4,32),(1,64)) + +Canonical Layout :Swizzle<0,4,3> o ((8,m),(T,2k)):((1T,SBO),(1,LBO)) + +Parameters | Value +---|--- +T | 4 +m | 2 +k | 2 +LBO | 64*sizeof(tf32) +SBO | 32*sizeof(tf32) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 8 + * K-Major, 32B swizzling and tf32 type: [Figure 167](<#async-warpgroup-k-32b-swizzle-tf32>) + +![_images/async-warpgroup-k-32B-swizzle-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-k-32B-swizzle-tf32.png) + +Figure 167 K major, 32B swizzling and tf32 type + +the strides and related details are as follows: + +Exact layout : Swizzle<1,4,3> o ((8,2),(4,4)):((8,64),(1,4)) + +Canonical Layout :Swizzle<1,4,3> o ((8,m),(T,2k)):((2T,SBO),(1,T)) + +Parameters | Value +---|--- +T | 4 +m | 2 +k | 2 +LBO | NA +SBO | 64*sizeof(tf32) +Encoding of LBO in descriptor | 1 (assumed) +Encoding of SBO in descriptor | (SBO) >> 4 = 16 + * MN-Major, no-swizzling and bf16 type: [Figure 168](<#async-warpgroup-mn-no-swizzle-bf16>) + +![_images/async-warpgroup-mn-no-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-no-swizzle-bf16.png) + +Figure 168 MN major, no-swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<0,4,3> o ((8,1,2),(8,2)):((1,8,64),(8,128)) + +Canonical Layout :Swizzle<0,4,3> o ((T,1,m),(8,k)):((1,T,SBO),(1T,LBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO | 128*sizeof(bf16) +SBO | 64*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 8 + * MN-Major, 32B swizzling and bf16 type: [Figure 169](<#async-warpgroup-mn-32b-swizzle-bf16>) + +![_images/async-warpgroup-mn-32B-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-32B-swizzle-bf16.png) + +Figure 169 MN major, 32B swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<1,4,3> o ((8,2,2),(8,2)):((1,8,128),(16,256)) + +Canonical Layout :Swizzle<1,4,3> o ((T,2,m),(8,k)):((1,T,LBO),(2T,SBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO | 128*sizeof(bf16) +SBO | 256*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 32 + * MN-Major, 64B swizzling and bf16 type: [Figure 170](<#async-warpgroup-mn-64b-swizzle-bf16>) + +![_images/async-warpgroup-mn-64B-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-64B-swizzle-bf16.png) + +Figure 170 MN major, 64B swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<2,4,3> o ((8,4,2),(8,2)):((1,8,256),(32,512)) + +Canonical Layout :Swizzle<2,4,3> o ((T,4,m),(8,k)):((1,T,LBO),(4T,SBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO | 256*sizeof(bf16) +SBO | 512*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 32 +Encoding of SBO in descriptor | (SBO) >> 4 = 64 + + +####### 9.7.15.5.1.2.2. [Matrix Descriptor Format](<#asynchronous-warpgroup-level-matrix-shared-memory-layout-matrix-descriptor>) + +Matrix descriptor specifies the properties of the matrix in shared memory that is a multiplicand in the matrix multiply and accumulate operation. It is a 64-bit value contained in a register with the following layout: + +Bit-field | Size in bits | Description +---|---|--- +13–0 | 14 | matrix-descriptor-encode(Matrix start address) +29–16 | 14 | matrix-descriptor-encode ([Leading dimension byte offset](<#asynchronous-warpgroup-level-leading-dimension-byte-offset>)) +45–32 | 14 | matrix-descriptor-encode ([Stride dimension byte offset](<#asynchronous-warpgroup-level-stride-dimension-byte-offset>)) +51–49 | 3 | Matrix base offset. This is valid for all swizzling modes except the no-swizzle mode. +63–62 | 2 | Specifies the swizzling mode to be used: + + * 0: No swizzle + * 1: 128-Byte swizzle + * 2: 64-Byte swizzle + * 3: 32-Byte swizzle + + + +where + + + matrix-descriptor-encode(x) = (x & 0x3FFFF) >> 4 + + +The value of base offset is 0 when the repeating pattern of the specified swizzling mode starts as per the below table: + +> Swizzling mode | Starting address of the repeating pattern +> ---|--- +> 128-Byte swizzle | 1024-Byte boundary +> 64-Byte swizzle | 512-Byte boundary +> 32-Byte swizzle | 256-Byte boundary + +Otherwise, the base offset must be a non-zero value, computed using the following formula: + + + base offset = (pattern start addr >> 0x7) & 0x7 + +##### 9.7.15.5.2. [Asynchronous Multiply-and-Accumulate Instruction: `wgmma.mma_async`](<#asynchronous-warpgroup-level-matrix-instructions-wgmma-mma>) + +`wgmma.mma_async` + +Perform matrix multiply-and-accumulate operation across warpgroup + +Syntax + +Half precision floating point type: + + + wgmma.mma_async.sync.aligned.shape.dtype.f16.f16 d, a-desc, b-desc, scale-d, imm-scale-a, imm-scale-b, imm-trans-a, imm-trans-b; + + wgmma.mma_async.sync.aligned.shape.dtype.f16.f16 d, a, b-desc, scale-d, imm-scale-a, imm-scale-b, imm-trans-b; + + .shape = {.m64n8k16, .m64n16k16, .m64n24k16, .m64n32k16, + .m64n40k16, .m64n48k16, .m64n56k16, .m64n64k16, + .m64n72k16, .m64n80k16, .m64n88k16, .m64n96k16, + .m64n104k16, .m64n112k16, .m64n120k16, .m64n128k16, + .m64n136k16, .m64n144k16, .m64n152k16, .m64n160k16, + .m64n168k16, .m64n176k16, .m64n184k16, .m64n192k16, + .m64n200k16, .m64n208k16, .m64n216k16, .m64n224k16, + .m64n232k16, .m64n240k16, .m64n248k16, .m64n256k16}; + .dtype = {.f16, .f32}; + + +Alternate floating point type : + + + .bf16 floating point type: + + wgmma.mma_async.sync.aligned.shape.dtype.bf16.bf16 d, a-desc, b-desc, scale-d, imm-scale-a, imm-scale-b, imm-trans-a, imm-trans-b; + + wgmma.mma_async.sync.aligned.shape.dtype.bf16.bf16 d, a, b-desc, scale-d, imm-scale-a, imm-scale-b, imm-trans-b; + + .shape = {.m64n8k16, .m64n16k16, .m64n24k16, .m64n32k16, + .m64n40k16, .m64n48k16, .m64n56k16, .m64n64k16, + .m64n72k16, .m64n80k16, .m64n88k16, .m64n96k16, + .m64n104k16, .m64n112k16, .m64n120k16, .m64n128k16, + .m64n136k16, .m64n144k16, .m64n152k16, .m64n160k16, + .m64n168k16, .m64n176k16, .m64n184k16, .m64n192k16, + .m64n200k16, .m64n208k16, .m64n216k16, .m64n224k16, + .m64n232k16, .m64n240k16, .m64n248k16, .m64n256k16}; + .dtype = {.f32}; + + .tf32 floating point type: + + wgmma.mma_async.sync.aligned.shape.dtype.tf32.tf32 d, a-desc, b-desc, scale-d, imm-scale-a, imm-scale-b; + + wgmma.mma_async.sync.aligned.shape.dtype.tf32.tf32 d, a, b-desc, scale-d, imm-scale-a, imm-scale-b; + + .shape = {.m64n8k8, .m64n16k8, .m64n24k8, .m64n32k8, + .m64n40k8, .m64n48k8, .m64n56k8, .m64n64k8, + .m64n72k8, .m64n80k8, .m64n88k8, .m64n96k8, + .m64n104k8, .m64n112k8, .m64n120k8, .m64n128k8, + .m64n136k8, .m64n144k8, .m64n152k8, .m64n160k8, + .m64n168k8, .m64n176k8, .m64n184k8, .m64n192k8, + .m64n200k8, .m64n208k8, .m64n216k8, .m64n224k8, + .m64n232k8, .m64n240k8, .m64n248k8, .m64n256k8}; + .dtype = {.f32}; + + FP8 floating point type + + wgmma.mma_async.sync.aligned.shape.dtype.atype.btype d, a-desc, b-desc, scale-d, imm-scale-a, imm-scale-b; + + wgmma.mma_async.sync.aligned.shape.dtype.atype.btype d, a, b-desc, scale-d, imm-scale-a, imm-scale-b; + + .shape = {.m64n8k32, .m64n16k32, .m64n24k32, .m64n32k32, + .m64n40k32, .m64n48k32, .m64n56k32, .m64n64k32, + .m64n72k32, .m64n80k32, .m64n88k32, .m64n96k32, + .m64n104k32, .m64n112k32, .m64n120k32, .m64n128k32, + .m64n136k32, .m64n144k32, .m64n152k32, .m64n160k32, + .m64n168k32, .m64n176k32, .m64n184k32, .m64n192k32, + .m64n200k32, .m64n208k32, .m64n216k32, .m64n224k32, + .m64n232k32, .m64n240k32, .m64n248k32, .m64n256k32}; + .atype = {.e4m3, .e5m2}; + .btype = {.e4m3, .e5m2}; + .dtype = {.f16, .f32}; + + +Integer type: + + + wgmma.mma_async.sync.aligned.shape{.satfinite}.s32.atype.btype d, a-desc, b-desc, scale-d; + + wgmma.mma_async.sync.aligned.shape{.satfinite}.s32.atype.btype d, a, b-desc, scale-d; + + .shape = {.m64n8k32, .m64n16k32, .m64n24k32, .m64n32k32, + .m64n48k32, .m64n64k32, .m64n80k32, .m64n96k32, + .m64n112k32, .m64n128k32, .m64n144k32, .m64n160k32, + .m64n176k32, .m64n192k32, .m64n208k32, .m64n224k32}; + .atype = {.s8, .u8}; + .btype = {.s8, .u8}; + + +Single bit: + + + wgmma.mma_async.sync.aligned.shape.s32.b1.b1.op.popc d, a-desc, b-desc, scale-d; + + wgmma.mma_async.sync.aligned.shape.s32.b1.b1.op.popc d, a, b-desc, scale-d; + + .shape = {.m64n8k256, .m64n16k256, .m64n24k256, .m64n32k256, + .m64n48k256, .m64n64k256, .m64n80k256, .m64n96k256, + .m64n112k256, .m64n128k256, .m64n144k256, .m64n160k256, + .m64n176k256, .m64n192k256, .m64n208k256, .m64n224k256, + .m64n240k256, .m64n256k256}; + .op = {.and}; + + +Description + +Instruction `wgmma.mma_async` issues a `MxNxK` matrix multiply and accumulate operation, `D = A*B+D`, where the A matrix is `MxK`, the B matrix is `KxN`, and the D matrix is `MxN`. + +The operation of the form `D = A*B` is issued when the input predicate argument `scale-d` is false. + +`wgmma.fence` instruction must be used to fence the register accesses of `wgmma.mma_async` instruction from their prior accesses. Otherwise, the behavior is undefined. + +`wgmma.commit_group` and `wgmma.wait_group` operations must be used to wait for the completion of the asynchronous matrix multiply and accumulate operations before the results are accessed. + +Register operand `d` represents the accumulator matrix as well as the destination matrix, distributed across the participating threads. Register operand `a` represents the multiplicand matrix A in register distributed across the participating threads. The 64-bit register operands `a-desc` and `b-desc` are the matrix descriptors which represent the multiplicand matrices A and B in shared memory respectively. The contents of a matrix descriptor must be same across all the warps in the warpgroup. The format of the matrix descriptor is described in [Matrix Descriptor Format](<#asynchronous-warpgroup-level-matrix-shared-memory-layout-matrix-descriptor>). + +Matrices A and B are stored in row-major and column-major format respectively. For certain floating point variants, the input matrices A and B can be transposed by specifying the value 1 for the immediate integer arguments `imm-trans-a` and `imm-trans-b` respectively. A value of 0 can be used to avoid the transpose operation. The valid values of `imm-trans-a` and `imm-trans-b` are 0 and 1. The transpose operation is only supported for the `wgmma.mma_async` variants with `.f16`/ `.bf16` types on matrices accessed from shared memory using matrix descriptors. + +For the floating point variants of the `wgmma.mma_async` operation, each element of the input matrices A and B can be negated by specifying the value -1 for operands `imm-scale-a` and `imm-scale-b` respectively. A value of 1 can be used to avoid the negate operation. The valid values of `imm-scale-a` and `imm-scale-b` are -1 and 1. + +The qualifiers `.dtype`, `.atype` and `.btype` indicate the data type of the elements in matrices D, A and B respectively. `.atype` and `.btype` must be the same for all floating point `wgmma.mma_async` variants except for the FP8 floating point variants. The sizes of individual data elements of matrices A and B in alternate floating point variants of the `wgmma.mma_async` operation are as follows: + + * Matrices A and B have 8-bit data elements when `.atype`/ `.btype` is `.e4m3`/`.e5m2`. + + * Matrices A and B have 16-bit data elements when `.atype`/ `.btype` is `.bf16`. + + * Matrices A and B have 32-bit data elements when `.atype`/ `.btype` is `.tf32`. + + +Precision and rounding: + + * Floating point operations: + +Element-wise multiplication of matrix A and B is performed with at least single precision. When `.dtype` is `.f32`, accumulation of the intermediate values is performed with at least single precision. When `.dtype` is `.f16`, the accumulation is performed with at least half precision. + +The accumulation order, rounding and handling of subnormal inputs are unspecified. + + * `.bf16` and `.tf32` floating point operations: + +Element-wise multiplication of matrix A and B is performed with specified precision. `wgmma.mma_async` operation involving type `.tf32` will truncate lower 13 bits of the 32-bit input data before multiplication is issued. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * Integer operations: + +The integer `wgmma.mma_async` operation is performed with `.s32` accumulators. The `.satfinite` qualifier indicates that on overflow, the accumulated value is limited to the range _MIN_INT32_.. _MAX_INT32_ (where the bounds are defined as the minimum negative signed 32-bit integer and the maximum positive signed 32-bit integer respectively). + +If `.satfinite` is not specified, the accumulated value is wrapped instead. + + +The mandatory `.sync` qualifier indicates that `wgmma.mma_async` instruction causes the executing thread to wait until all threads in the warp execute the same `wgmma.mma_async` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warpgroup must execute the same `wgmma.mma_async` instruction. In conditionally executed code, a `wgmma.mma_async` instruction should only be used if it is known that all threads in the warpgroup evaluate the condition identically, otherwise behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Support for `.u8.s8` and `.s8.u8` as .atype.btype introduced in PTX ISA version 8.4. + +Target ISA Notes + +Requires `sm_90a`. + +Examples of half precision floating point type + + + .reg .f16x2 f16a<40>, f16d<40>; + .reg .f32 f32d<40>; + .reg .b64 descA, descB; + .reg .pred scaleD; + wgmma.mma_async.sync.aligned.m64n8k16.f32.f16.f16 + {f32d0, f32d1, f32d2, f32d3}, + {f16a0, f16a1, f16a2, f16a3}, + descB, + 1, -1, -1, 1; + + wgmma.mma_async.sync.aligned.m64n72k16.f16.f16.f16 + {f16d0, f16d1, f16d2, f16d3, f16d4, f16d5, f16d6, f16d7, f16d8, + f16d9, f16d10, f16d11, f16d12, f16d13, f16d14, f16d15, f16d16, f16d17}, + descA, + descB, + scaleD, -1, 1, 1, 0; + + +Examples of alternate floating point type + + + .reg .f32 f32d<40>; + .reg .b32 bf16a<40> + .reg .b64 descA, descB; + + wgmma.mma_async.sync.aligned.m64n120k16.f32.bf16.bf16 + {f32d0, f32d1, f32d2, f32d3, f32d4, f32d5, f32d6, f32d7, f32d8, f32d9, + f32d10, f32d11, f32d12, f32d13, f32d14, f32d15, f32d16, f32d17, f32d18, f32d19, + f32d20, f32d21, f32d22, f32d23, f32d24, f32d25, f32d26, f32d27, f32d28, f32d29, + f32d30, f32d31, f32d32, f32d33, f32d34, f32d35, f32d36, f32d37, f32d38, f32d39, + f32d40, f32d41, f32d42, f32d43, f32d44, f32d45, f32d46, f32d47, f32d48, f32d49, + f32d50, f32d51, f32d52, f32d53, f32d54, f32d55, f32d56, f32d57, f32d58, f32d59}, + {bf16a0, bf16a1, bf16a2, bf16a3}, + descB, + scaleD, -1, -1, 0; + + .reg .f32 f32d<40>; + .reg .b64 descA, descB; + + wgmma.mma_async.sync.aligned.m64n16k8.f32.tf32.tf32 + {f32d0, f32d1, f32d2, f32d3, f32d4, f32d5, f32d6, f32d7}, + descA, + descB, + 0, -1, -1; + + .reg .b32 f16d<8>, f16a<8>; + .reg .f32 f32d<8>; + .reg .b64 descA, descB; + + wgmma.mma_async.sync.aligned.m64n8k32.f16.e4m3.e5m2 + {f16d0, f16d1}, + descA, + descB, + scaleD, -1, 1; + + wgmma.mma_async.sync.aligned.m64n8k32.f32.e5m2.e4m3 + {f32d0, f32d1, f32d2, f32d3}, + {f16a0, f16a1, f16a2, f16a3}, + descB, + 1, -1, -1; + + +Examples of integer type + + + .reg .s32 s32d<8>, s32a<8>; + .reg .u32 u32a<8>; + .reg .pred scaleD; + .reg .b64 descA, descB; + + wgmma.mma_async.sync.aligned.m64n8k32.s32.s8.s8.satfinite + {s32d0, s32d1, s32d2, s32d3}, + {s32a0, s32a1, s32a2, s32a3}, + descB, + 1; + + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.u8 + {s32d0, s32d1, s32d2, s32d3}, + descA, + descB, + scaleD; + + wgmma.mma_async.sync.aligned.m64n8k32.s32.s8.u8.satfinite + {s32d0, s32d1, s32d2, s32d3}, + {s32a0, s32a1, s32a2, s32a3}, + descB, + scaleD; + + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.s8 + {s32d0, s32d1, s32d2, s32d3}, + descA, + descB, + scaleD; + + +Examples of single bit type + + + .reg .s32 s32d<4>; + .reg .b32 b32a<4>; + .reg .pred scaleD; + .reg .b64 descA, descB; + + + wgmma.mma_async.sync.aligned.m64n8k256.s32.b1.b1.and.popc + {s32d0, s32d1, s32d2, s32d3}, + {b32a0, b32a1, b32a2, b32a3}, + descB, + scaleD; \ No newline at end of file diff --git a/content/cuda/docs/ptx-asynchronous-warpgroup-level-multiply-and-accumulate-operation-usingwgmmamma-asyncspinstruction/DOC.md b/content/cuda/docs/ptx-asynchronous-warpgroup-level-multiply-and-accumulate-operation-usingwgmmamma-asyncspinstruction/DOC.md new file mode 100644 index 00000000..dd75a5a8 --- /dev/null +++ b/content/cuda/docs/ptx-asynchronous-warpgroup-level-multiply-and-accumulate-operation-usingwgmmamma-asyncspinstruction/DOC.md @@ -0,0 +1,393 @@ +--- +name: ptx-asynchronous-warpgroup-level-multiply-and-accumulate-operation-usingwgmmamma-asyncspinstruction +description: This section describes warp-level `wgmma.mma_async.sp` instruction with + sparse matrix A. This variant of the `wgmma.mma_async` operation can be used when + A is a structured sparse matrix with 50% zeros... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.15.6. Asynchronous Warpgroup Level Multiply-and-Accumulate Operation usingwgmma.mma_async.spinstruction + +--- +title: "9.7.15.6. Asynchronous Warpgroup Level Multiply-and-Accumulate Operation usingwgmma.mma_async.spinstruction" +section: 9.7.15.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.15.6. Asynchronous Warpgroup Level Multiply-and-Accumulate Operation usingwgmma.mma_async.spinstruction + + +This section describes warp-level `wgmma.mma_async.sp` instruction with sparse matrix A. This variant of the `wgmma.mma_async` operation can be used when A is a structured sparse matrix with 50% zeros in each row distributed in a shape-specific granularity. For an `MxNxK` sparse `wgmma.mma_async.sp` operation, the `MxK` matrix A is packed into `MxK/2` elements. For each K-wide row of matrix A, 50% elements are zeros and the remaining `K/2` non-zero elements are packed in the operand representing matrix A. The mapping of these `K/2` elements to the corresponding K-wide row is provided explicitly as metadata. + +##### 9.7.15.6.1. [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>) + +Granularity of sparse matrix A is defined as the ratio of the number of non-zero elements in a sub-chunk of the matrix row to the total number of elements in that sub-chunk where the size of the sub-chunk is shape-specific. For example, in a `64x32` matrix A used in floating point `wgmma.mma_async` operations, sparsity is expected to be at 2:4 granularity, i.e. each 4-element vector (i.e. a sub-chunk of 4 consecutive elements) of a matrix row contains 2 zeros. Index of each non-zero element in a sub-chunk is stored in the metadata operand. Values `0b0000`, `0b0101`, `0b1010`, `0b1111` are invalid values for metadata and will result in undefined behavior. In a group of four consecutive threads, one or more threads store the metadata for the whole group depending upon the matrix shape. These threads are specified using an additional sparsity selector operand. + +Matrix A and its corresponding input operand to the sparse wgmma is similar to the diagram shown in [Figure 111](<#sparse-mma-storage-example>), with an appropriate matrix size. + +Granularities for different matrix shapes and data types are described below. + +Sparse `wgmma.mma_async.sp` with half-precision and `.bf16` type + +For `.f16` and `.bf16` types, for all supported `64xNx32` shapes, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A have two zeroes and two non-zero elements. Only the two non-zero elements are stored in matrix A and their positions in the four-wide chunk in Matrix A are indicated by two 2-bits indices in the metadata operand. + +![_images/f16-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/f16-metadata-example.png) + +Figure 171 Sparse WGMMA metadata example for `.f16`/`.bf16` type. + +The sparsity selector indicates a thread-pair within a group of four consecutive threads which contributes the sparsity metadata. Hence, the sparsity selector must be either 0 (threads T0, T1) or 1 (threads T2, T3); any other value results in an undefined behavior. + +Sparse `wgmma.mma_async.sp` with `.tf32` type + +For `.tf32` type, for all supported `64xNx16` shapes, matrix A is structured sparse at a granularity of 1:2. In other words, each chunk of two adjacent elements in a row of matrix A have one zero and one non-zero element. Only the non-zero element is stored in operand for matrix A and the 4-bit index in the metadata indicates the position of the non-zero element in the two-wide chunk. 0b1110 and 0b0100 are the only meaningful values of the index, the remaining values result in an undefined behavior. + +![_images/tf32-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tf32-metadata-example.png) + +Figure 172 Sparse WGMMA metadata example for `.tf32` type. + +The sparsity selector indicates a thread-pair within a group of four consecutive threads which contributes the sparsity metadata. Hence, the sparsity selector must be either 0 (threads T0, T1) or 1 (threads T2, T3); any other value results in an undefined behavior. + +Sparse `wgmma.mma_async.sp` with `.e4m3` and `.e5m2` floating point type + +For `.e4m3` and `.e5m2` types, for all supported `64xNx64` shapes, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A have two zeroes and two non-zero elements. Only the two non-zero elements are stored in matrix A and their positions in the four-wide chunk in Matrix A are indicated by two 2-bits indices in the metadata operand. + +![_images/u8s8-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/u8s8-metadata-example.png) + +Figure 173 Sparse WGMMA metadata example for `.e4m3`/`.e5m2` type. + +All threads contribute the sparsity metadata and the sparsity selector must be 0; any other value results in an undefined behavior. + +Sparse `wgmma.mma_async.sp` with integer type + +For the integer type, for all supported `64xNx64` shapes, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A have two zeroes and two non-zero elements. Only the two non-zero elements are stored in matrix A and two 2-bit indices in the metadata indicate the position of these two non-zero elements in the four-wide chunk. + +![_images/u8s8-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/u8s8-metadata-example.png) + +Figure 174 Sparse WGMMA metadata example for `.u8`/`.s8` type. + +All threads contribute the sparsity metadata and the sparsity selector must be 0; any other value results in an undefined behavior. + +##### 9.7.15.6.2. [Matrix fragments for warpgroup-level multiply-accumulate operation with sparse matrix A](<#asynchronous-warpgroup-level-matrix-fragments-for-sparse-wgmma>) + +In this section we describe how the contents of thread registers are associated with fragments of A matrix and the sparsity metadata. + +Each warp in the warpgroup provides sparsity information for 16 rows of matrix A. The following table shows the assignment of warps to rows of matrix A: + +Warp | Sparsity information for rows of matrix A +---|--- +`%warpid` % 4 = 3 | 48-63 +`%warpid` % 4 = 2 | 32-47 +`%warpid` % 4 = 1 | 16-31 +`%warpid` % 4 = 0 | 0-15 + +The following conventions are used throughout this section: + + * For matrix A, only the layout of a fragment is described in terms of register vector sizes and their association with the matrix data. + + * For matrix D, since the matrix dimension - data type combination is the same for all supported shapes, and is already covered in [Asynchronous Warpgroup Level Matrix Multiply-Accumulate Operation using wgmma.mma_async instruction](<#asynchronous-warpgroup-level-matrix-operation-wgmma-mma-async>), the pictorial representations of matrix fragments are not included in this section. + + * For the metadata operand, pictorial representations of the association between indices of the elements of matrix A and the contents of the metadata operand are included. `Tk: [m..n]` present in cell `[x][y..z]` indicates that bits `m` through `n` (with `m` being higher) in the metadata operand of thread with `%laneid=k` contains the indices of the non-zero elements from the chunk `[x][y]..[x][z]` of matrix A. + + +###### 9.7.15.6.2.1. [Matrix Fragments for sparse `wgmma.mma_async.m64nNk32`](<#asynchronous-warpgroup-level-matrix-fragment-sparse-wgmma-64n32>) + +A warpgroup executing sparse `wgmma.mma_async.m64nNk32` will compute an MMA operation of shape `.m64nNk32` where N is a valid n dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A, from shared memory is documented in [Shared Memory Matrix Layout](<#asynchronous-warpgroup-level-matrix-shared-memory-layout>). + + * Multiplicand A, from registers: + +> .atype | Fragments | Elements +> ---|---|--- +> `.f16` / `.bf16` | A vector expression containing four `.b32` registers, with each register containing two non-zero `.f16` /`.bf16` elements out of 4 consecutive elements from matrix A. | Non-zero elements: a0, a1, a2, a3, a4, a5, a6, a7 Mapping of the non-zero elements is as described in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>) +> +> The layout of the fragments held by different threads is shown in [Figure 175](<#sparse-wgmma-64n32-f16-bf16-a>). +> +> ![_images/sparse-wgmma-64N32-f16-bf16-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-wgmma-64N32-f16-bf16-A.png) +> +> Figure 175 Sparse WGMMA .m64nNk32 fragment layout for matrix A with `.f16`/`.bf16` type. + + * Accumulator D: + +Matrix fragments for accumulator D are the same as in case of [Matrix Fragments for wgmma.mma_async.m64nNk32](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n32>) for the same `.dtype` format. + + * Multiplicand B: + +Shared memory layout for Matrix B is documented in [Shared Memory Matrix Layout](<#asynchronous-warpgroup-level-matrix-shared-memory-layout>). + + * Metadata operand is a `.b32` register containing 16 2-bit vectors each storing the index of a non-zero element of a 4-wide chunk of matrix A. + +[Figure 176](<#sparse-wgmma-metadata-64n32-f16bf16>) shows the mapping of the metadata bits to the elements of matrix A for a warp. In this figure, variable `i` represents the value of the sparsity selector operand. + +> ![_images/sparse-mma-metadata-16832-f16bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16832-f16bf16.png) +> +> Figure 176 Sparse WGMMA .m64nNk32 metadata layout for `.f16`/`.bf16` type. + + +###### 9.7.15.6.2.2. [Matrix Fragments for sparse `wgmma.mma_async.m64nNk16`](<#asynchronous-warpgroup-level-matrix-fragment-sparse-wgmma-64n16>) + +A warpgroup executing sparse `wgmma.mma_async.m64nNk16` will compute an MMA operation of shape `.m64nNk16` where N is a valid n dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A, from shared memory is documented in [Shared Memory Matrix Layout](<#asynchronous-warpgroup-level-matrix-shared-memory-layout>). + + * Multiplicand A, from registers: + +> .atype | Fragments | Elements +> ---|---|--- +> `.tf32` | A vector expression containing four `.b32` registers, containing four non-zero `.tf32` elements out of eight consecutive elements from matrix A. | Non-zero elements: a0, a1, a2, a3 +> Mapping of the non-zero elements is as described in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>) +> +> The layout of the fragments held by different threads is shown in [Figure 177](<#sparse-wgmma-64n16-tf32-a>). +> +> ![_images/sparse-wgmma-64N16-tf32-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-wgmma-64N16-tf32-A.png) +> +> Figure 177 Sparse WGMMA .m64nNk16 fragment layout for matrix A with `.tf32` type. + + * Accumulator D: + +Matrix fragments for accumulator D are the same as in case of [Matrix Fragments for wgmma.mma_async.m64nNk8](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n8>) for the same `.dtype` format. + + * Multiplicand B: + +Shared memory layout for Matrix B is documented in [Shared Memory Matrix Layout](<#asynchronous-warpgroup-level-matrix-shared-memory-layout>). + + * Metadata operand is a `.b32` register containing eight 4-bit vectors each storing the index of a non-zero element of a 2-wide chunk of matrix A. + +[Figure 178](<#sparse-wgmma-metadata-64n16-tf32>) shows the mapping of the metadata bits to the elements of matrix A for a warp. In this figure, variable `i` represents the value of the sparsity selector operand. + +> ![_images/sparse-mma-metadata-16816-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16816-tf32.png) +> +> Figure 178 Sparse WGMMA .m64nNk16 metadata layout for `.tf32` type. + + +###### 9.7.15.6.2.3. [Matrix Fragments for sparse `wgmma.mma_async.m64nNk64`](<#asynchronous-warpgroup-level-matrix-fragment-sparse-wgmma-64n64>) + +A warpgroup executing sparse `wgmma.mma_async.m64nNk64` will compute an MMA operation of shape `.m64nNk64` where N is a valid n dimension as listed in [Matrix Shape](<#asynchronous-warpgroup-level-matrix-shape>). + +Elements of the matrix are distributed across the threads in a warpgroup so each thread of the warpgroup holds a fragment of the matrix. + + * Multiplicand A, from shared memory is documented in [Matrix Fragments for sparse wgmma.mma_async.m64nNk64](<#asynchronous-warpgroup-level-matrix-fragment-sparse-wgmma-64n64>). + + * Multiplicand A, from registers: + +> .atype | Fragments | Elements +> ---|---|--- +> `.e4m3` / `.e5m2` | A vector expression containing four `.b32` registers, with each register containing four non-zero `.e4m3` /`.e5m2` elements out of eight consecutive elements from matrix A. | +> Non-zero elements: a0, a1, a2, … , a15 +> Mapping of the non-zero elements is as described in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>) +> `.s8` / `.u8` | A vector expression containing four `.b32` registers, with each register containing four non-zero `.s8` /`.u8` elements out of eight consecutive elements from matrix A. +> +> The layout of the fragments held by different threads is shown in [Figure 179](<#sparse-wgmma-64n64-e4m3-e5m2-s8-u8-a>). +> +> ![_images/sparse-wgmma-64N64-e4m3-e5m2-s8-u8-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-wgmma-64N64-e4m3-e5m2-s8-u8-A.png) +> +> Figure 179 Sparse WGMMA .m64nNk64 fragment layout for matrix A with `.e4m3`/ `.e5m2`/ `.s8`/ `.u8` type. + + * Accumulator D: + +Matrix fragments for accumulator D are the same as in case of [Matrix Fragments for wgmma.mma_async.m64nNk32](<#asynchronous-warpgroup-level-matrix-register-fragment-wgmma-64n32>) for the same `.dtype` format. + + * Multiplicand B: + +Shared memory layout for Matrix B is documented in [Matrix Fragments for sparse wgmma.mma_async.m64nNk64](<#asynchronous-warpgroup-level-matrix-fragment-sparse-wgmma-64n64>). + + * Metadata operand is a `.b32` register containing 16 4-bit vectors each storing the indices of two non-zero elements of a 4-wide chunk of matrix A. + +[Figure 180](<#sparse-wgmma-metadata-64n64-e4m3-e5m2-s8-u8-first32col>) shows the mapping of the metadata bits to the elements of columns 0–31 of matrix A. + +> ![_images/sparse-mma-metadata-16864-u8s8-first32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16864-u8s8-first32col.png) +> +> Figure 180 Sparse WGMMA .m64nNk64 metadata layout for `.e4m3`/ `.e5m2`/ `.s8`/ `.u8` type for columns 0–31 + +[Figure 181](<#sparse-wgmma-metadata-64n64-e4m3-e5m2-s8-u8-last32col>) shows the mapping of the metadata bits to the elements of columns 32–63 of matrix A. + +> ![_images/sparse-mma-metadata-16864-u8s8-last32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16864-u8s8-last32col.png) +> +> Figure 181 Sparse WGMMA .m64nNk64 metadata layout for `.e4m3`/ `.e5m2`/ `.s8`/ `.u8` type for columns 32–63 + +##### 9.7.15.6.3. [Asynchronous Multiply-and-Accumulate Instruction: `wgmma.mma_async.sp`](<#asynchronous-warpgroup-level-matrix-instructions-wgmma-mma-sp>) + +`wgmma.mma_async.sp` + +Perform matrix multiply-and-accumulate operation with sparse matrix A across warpgroup + +Syntax + +Half precision floating point type: + + + wgmma.mma_async.sp.sync.aligned.shape.dtype.f16.f16 d, a-desc, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b, imm-trans-a, imm-trans-b; + + wgmma.mma_async.sp.sync.aligned.shape.dtype.f16.f16 d, a, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b, imm-trans-b; + + .shape = {.m64n8k32, .m64n16k32, .m64n24k32, .m64n32k32, + .m64n40k32, .m64n48k32, .m64n56k32, .m64n64k32, + .m64n72k32, .m64n80k32, .m64n88k32, .m64n96k32, + .m64n104k32, .m64n112k32, .m64n120k32, .m64n128k32, + .m64n136k32, .m64n144k32, .m64n152k32, .m64n160k32, + .m64n168k32, .m64n176k32, .m64n184k32, .m64n192k32, + .m64n200k32, .m64n208k32, .m64n216k32, .m64n224k32, + .m64n232k32, .m64n240k32, .m64n248k32, .m64n256k32}; + .dtype = {.f16, .f32}; + + +Alternate floating point type : + + + .bf16 floating point type: + + wgmma.mma_async.sp.sync.aligned.shape.dtype.bf16.bf16 d, a-desc, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b, imm-trans-a, imm-trans-b; + + wgmma.mma_async.sp.sync.aligned.shape.dtype.bf16.bf16 d, a, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b, imm-trans-b; + + .shape = {.m64n8k32, .m64n16k32, .m64n24k32, .m64n32k32, + .m64n40k32, .m64n48k32, .m64n56k32, .m64n64k32, + .m64n72k32, .m64n80k32, .m64n88k32, .m64n96k32, + .m64n104k32, .m64n112k32, .m64n120k32, .m64n128k32, + .m64n136k32, .m64n144k32, .m64n152k32, .m64n160k32, + .m64n168k32, .m64n176k32, .m64n184k32, .m64n192k32, + .m64n200k32, .m64n208k32, .m64n216k32, .m64n224k32, + .m64n232k32, .m64n240k32, .m64n248k32, .m64n256k32}; + .dtype = {.f32}; + + .tf32 floating point type: + + wgmma.mma_async.sp.sync.aligned.shape.dtype.tf32.tf32 d, a-desc, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b; + + wgmma.mma_async.sp.sync.aligned.shape.dtype.tf32.tf32 d, a, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b; + + .shape = {.m64n8k16, .m64n16k16, .m64n24k16, .m64n32k16, + .m64n40k16, .m64n48k16, .m64n56k16, .m64n64k16, + .m64n72k16, .m64n80k16, .m64n88k16, .m64n96k16, + .m64n104k16, .m64n112k16, .m64n120k16, .m64n128k16, + .m64n136k16, .m64n144k16, .m64n152k16, .m64n160k16, + .m64n168k16, .m64n176k16, .m64n184k16, .m64n192k16, + .m64n200k16, .m64n208k16, .m64n216k16, .m64n224k16, + .m64n232k16, .m64n240k16, .m64n248k16, .m64n256k16}; + .dtype = {.f32}; + + FP8 floating point type + + wgmma.mma_async.sp.sync.aligned.shape.dtype.atype.btype d, a-desc, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b; + + wgmma.mma_async.sp.sync.aligned.shape.dtype.atype.btype d, a, b-desc, sp-meta, sp-sel, scale-d, imm-scale-a, imm-scale-b; + + .shape = {.m64n8k64, .m64n16k64, .m64n24k64, .m64n32k64, + .m64n40k64, .m64n48k64, .m64n56k64, .m64n64k64, + .m64n72k64, .m64n80k64, .m64n88k64, .m64n96k64, + .m64n104k64, .m64n112k64, .m64n120k64, .m64n128k64, + .m64n136k64, .m64n144k64, .m64n152k64, .m64n160k64, + .m64n168k64, .m64n176k64, .m64n184k64, .m64n192k64, + .m64n200k64, .m64n208k64, .m64n216k64, .m64n224k64, + .m64n232k64, .m64n240k64, .m64n248k64, .m64n256k64}; + .atype = {.e4m3, .e5m2}; + .btype = {.e4m3, .e5m2}; + .dtype = {.f16, .f32}; + + +Integer type: + + + wgmma.mma_async.sp.sync.aligned.shape{.satfinite}.s32.atype.btype d, a-desc, b-desc, sp-meta, sp-sel, scale-d; + + wgmma.mma_async.sp.sync.aligned.shape{.satfinite}.s32.atype.btype d, a, b-desc, sp-meta, sp-sel, scale-d; + + .shape = {.m64n8k64, .m64n16k64, .m64n24k64, .m64n32k64, + .m64n48k64, .m64n64k64, .m64n80k64, .m64n96k64, + .m64n112k64, .m64n128k64, .m64n144k64, .m64n160k64, + .m64n176k64, .m64n192k64, .m64n208k64, .m64n224k64, + .m64n240k64, .m64n256k64}; + .atype = {.s8, .u8}; + .btype = {.s8, .u8}; + + +Description + +Instruction `wgmma.mma_async` issues a `MxNxK` matrix multiply and accumulate operation, `D = A*B+D`, where the A matrix is `MxK`, the B matrix is `KxN`, and the D matrix is `MxN`. + +The matrix A is stored in the packed format Mx(K/2) as described in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>). + +The operation of the form `D = A*B` is issued when the input predicate argument `scale-d` is false. + +`wgmma.fence` instruction must be used to fence the register accesses of `wgmma.mma_async` instruction from their prior accesses. Otherwise, the behavior is undefined. + +`wgmma.commit_group` and `wgmma.wait_group` operations must be used to wait for the completion of the asynchronous matrix multiply and accumulate operations before the results are accessed. + +Register operand `d` represents the accumulator matrix as well as the destination matrix, distributed across the participating threads. Register operand `a` represents the multiplicand matrix A in register distributed across the participating threads. The 64-bit register operands `a-desc` and `b-desc` are the matrix descriptors which represent the multiplicand matrices A and B in shared memory respectively. The contents of a matrix descriptor must be same across all the warps in the warpgroup. The format of the matrix descriptor is described in [Matrix Descriptor Format](<#asynchronous-warpgroup-level-matrix-shared-memory-layout-matrix-descriptor>). Matrix A is structured sparse as described in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>). Operands `sp-meta` and `sp-sel` represent sparsity metadata and sparsity selector respectively. Operand `sp-meta` is a 32-bit integer and operand `sp-sel` is a 32-bit integer constant with values in the range 0..3. + +The valid values of `sp-meta` and `sp-sel` for each shape is specified in [Sparse matrix storage](<#asynchronous-warpgroup-level-sparse-matrix-storage>) and are summarized here : + +Matrix shape | `.atype` | Valid values of `sp-meta` | Valid values of `sp-sel` +---|---|---|--- +`.m64nNk16` | `.tf32` | 0b1110 , 0b0100 | 0 (threads T0, T1) or 1 (threads T2, T3) +`.m64nNk32` | `.f16`/ `.bf16` | 0b00, 0b01, 0b10, 0b11 | 0 (threads T0, T1) or 1 (threads T2, T3) +`.m64nNk64` | `.e4m3` / `.e5m2` / `.s8` / `.u8` | 0b00, 0b01, 0b10, 0b11 | 0 (all threads contribute) + +Matrices A and B are stored in row-major and column-major format respectively. For certain floating point variants, the input matrices A and B can be transposed by specifying the value 1 for the immediate integer arguments `imm-trans-a` and `imm-trans-b` respectively. A value of 0 can be used to avoid the transpose operation. The valid values of `imm-trans-a` and `imm-trans-b` are 0 and 1. The transpose operation is only supported for the `wgmma.mma_async` variants with `.f16`/ `.bf16` types on matrices accessed from shared memory using matrix descriptors. + +For the floating point variants of the `wgmma.mma_async` operation, each element of the input matrices A and B can be negated by specifying the value -1 for operands `imm-scale-a` and `imm-scale-b` respectively. A value of 1 can be used to avoid the negate operation. The valid values of `imm-scale-a` and `imm-scale-b` are -1 and 1. + +The qualifiers `.dtype`, `.atype` and `.btype` indicate the data type of the elements in matrices D, A and B respectively. `.atype` and `.btype` must be the same for all floating point `wgmma.mma_async` variants except for the FP8 floating point variants. The sizes of individual data elements of matrices A and B in alternate floating point variants of the `wgmma.mma_async` operation are as follows: + + * Matrices A and B have 8-bit data elements when `.atype`/ `.btype` is `.e4m3`/`.e5m2`. + + * Matrices A and B have 16-bit data elements when `.atype`/ `.btype` is `.bf16`. + + * Matrices A and B have 32-bit data elements when `.atype`/ `.btype` is `.tf32`. + + +Precision and rounding: + + * Floating point operations: + +Element-wise multiplication of matrix A and B is performed with at least single precision. When `.dtype` is `.f32`, accumulation of the intermediate values is performed with at least single precision. When `.dtype` is `.f16`, the accumulation is performed with at least half precision. + +The accumulation order, rounding and handling of subnormal inputs are unspecified. + + * `.bf16` and `.tf32` floating point operations: + +Element-wise multiplication of matrix A and B is performed with specified precision. `wgmma.mma_async` operation involving type `.tf32` will truncate lower 13 bits of the 32-bit input data before multiplication is issued. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * Integer operations: + +The integer `wgmma.mma_async` operation is performed with `.s32` accumulators. The `.satfinite` qualifier indicates that on overflow, the accumulated value is limited to the range _MIN_INT32_.. _MAX_INT32_ (where the bounds are defined as the minimum negative signed 32-bit integer and the maximum positive signed 32-bit integer respectively). + +If `.satfinite` is not specified, the accumulated value is wrapped instead. + + +The mandatory `.sync` qualifier indicates that `wgmma.mma_async` instruction causes the executing thread to wait until all threads in the warp execute the same `wgmma.mma_async` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warpgroup must execute the same `wgmma.mma_async` instruction. In conditionally executed code, a `wgmma.mma_async` instruction should only be used if it is known that all threads in the warpgroup evaluate the condition identically, otherwise behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.2. + +Support for `.u8.s8` and `.s8.u8` as .atype.btype introduced in PTX ISA version 8.4. + +Target ISA Notes + +Requires `sm_90a`. + +Examples of integer type + + + wgmma.fence.sync.aligned; + wgmma.mma_async.sp.sync.aligned.m64n8k64.s32.u8.u8 {s32d0, s32d1, s32d2, s32d3}, + descA, descB, spMeta, 0, scaleD; + wgmma.mma_async.sp.sync.aligned.m64n8k64.s32.s8.u8 {s32d0, s32d1, s32d2, s32d3}, + descA, descB, spMeta, 0, scaleD; + wgmma.commit_group.sync.aligned; + wgmma.wait_group.sync.aligned 0; \ No newline at end of file diff --git a/content/cuda/docs/ptx-asynchronouswgmmaproxy-operations/DOC.md b/content/cuda/docs/ptx-asynchronouswgmmaproxy-operations/DOC.md new file mode 100644 index 00000000..f50bbc16 --- /dev/null +++ b/content/cuda/docs/ptx-asynchronouswgmmaproxy-operations/DOC.md @@ -0,0 +1,168 @@ +--- +name: ptx-asynchronouswgmmaproxy-operations +description: This section describes warpgroup level `wgmma.fence`, `wgmma.commit_group` + and `wgmma.wait_group` instructions. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.15.7. AsynchronouswgmmaProxy Operations + +--- +title: "9.7.15.7. AsynchronouswgmmaProxy Operations" +section: 9.7.15.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.15.7. AsynchronouswgmmaProxy Operations + + +This section describes warpgroup level `wgmma.fence`, `wgmma.commit_group` and `wgmma.wait_group` instructions. + +##### 9.7.15.7.1. [Asynchronous Multiply-and-Accumulate Instruction: `wgmma.fence`](<#asynchronous-warpgroup-level-matrix-instructions-wgmma-fence>) + +`wgmma.fence` + +Enforce an ordering of register accesses between `wgmma.mma_async` and other operations. + +Syntax + + + wgmma.fence.sync.aligned; + + +Description + +`wgmma.fence` instruction establishes an ordering between prior accesses to any warpgroup registers and subsequent accesses to the same registers by a `wgmma.mma_async` instruction. Only the accumulator register and the input registers containing the fragments of matrix A require this ordering. + +The `wgmma.fence` instruction must be issued by all warps of the warpgroup at the following locations: + + * Before the first `wgmma.mma_async` operation in a warpgroup. + + * Between a register access by a thread in the warpgroup and any `wgmma.mma_async` instruction that accesses the same registers, either as accumulator or input register containing fragments of matrix A, except when these are accumulator register accesses across multiple `wgmma.mma_async` instructions of the same shape. In the latter case, an ordering guarantee is provided by default. + + +Otherwise, the behavior is undefined. + +An async proxy fence must be used to establish an ordering between prior writes to shared memory matrices and subsequent reads of the same matrices in a `wgmma.mma_async` instruction. + +The mandatory `.sync` qualifier indicates that `wgmma.fence` instruction causes the executing thread to wait until all threads in the warp execute the same `wgmma.fence` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warpgroup must execute the same `wgmma.fence` instruction. In conditionally executed code, an `wgmma.fence` instruction should only be used if it is known that all threads in the warpgroup evaluate the condition identically, otherwise the behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90a`. + +Examples + + + // Example 1, first use example: + wgmma.fence.sync.aligned; // Establishes an ordering w.r.t. prior accesses to the registers s32d<0-3> + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.u8 {s32d0, s32d1, s32d2, s32d3}, + descA, descB, scaleD; + wgmma.commit_group.sync.aligned; + wgmma.wait_group.sync.aligned 0; + + // Example 2, use-case with the input value updated in between: + wgmma.fence.sync.aligned; + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.u8 {s32d0, s32d1, s32d2, s32d3}, + descA, descB, scaleD; + ... + mov.b32 s32d0, new_val; + wgmma.fence.sync.aligned; + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.u8 {s32d4, s32d5, s32d6, s32d7}, + {s32d0, s32d1, s32d2, s32d3}, + descB, scaleD; + wgmma.commit_group.sync.aligned; + wgmma.wait_group.sync.aligned 0; + +##### 9.7.15.7.2. [Asynchronous Multiply-and-Accumulate Instruction: `wgmma.commit_group`](<#asynchronous-warpgroup-level-matrix-instructions-wgmma-commit-group>) + +`wgmma.commit_group` + +Commits all prior uncommitted `wgmma.mma_async` operations into a _wgmma-group_. + +Syntax + + + wgmma.commit_group.sync.aligned; + + +Description + +`wgmma.commit_group` instruction creates a new wgmma-group per warpgroup and batches all prior `wgmma.mma_async` instructions initiated by the executing warp but not committed to any wgmma-group into the new wgmma-group. If there are no uncommitted `wgmma.mma_async` instructions then `wgmma.commit_group` results in an empty wgmma-group. + +An executing thread can wait for the completion of all `wgmma.mma_async` operations in a wgmma-group by using `wgmma.wait_group`. + +The mandatory `.sync` qualifier indicates that `wgmma.commit_group` instruction causes the executing thread to wait until all threads in the warp execute the same `wgmma.commit_group` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warpgroup must execute the same `wgmma.commit_group` instruction. In conditionally executed code, an `wgmma.commit_group` instruction should only be used if it is known that all threads in the warpgroup evaluate the condition identically, otherwise the behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90a`. + +Examples + + + wgmma.commit_group.sync.aligned; + +##### 9.7.15.7.3. [Asynchronous Multiply-and-Accumulate Instruction: `wgmma.wait_group`](<#asynchronous-warpgroup-level-matrix-instructions-wgmma-wait-group>) + +`wgmma.wait_group` + +Signal the completion of a preceding warpgroup operation. + +Syntax + + + wgmma.wait_group.sync.aligned N; + + +Description + +`wgmma.wait_group` instruction will cause the executing thread to wait until only N or fewer of the most recent wgmma-groups are pending and all the prior wgmma-groups committed by the executing threads are complete. For example, when N is 0, the executing thread waits on all the prior wgmma-groups to complete. Operand N is an integer constant. + +Accessing the accumulator register or the input register containing the fragments of matrix A of a `wgmma.mma_async` instruction without first performing a `wgmma.wait_group` instruction that waits on a _wgmma-group_ including that `wgmma.mma_async` instruction is undefined behavior. + +The mandatory `.sync` qualifier indicates that `wgmma.wait_group` instruction causes the executing thread to wait until all threads in the warp execute the same `wgmma.wait_group` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warpgroup must execute the same `wgmma.wait_group` instruction. In conditionally executed code, an `wgmma.wait_group` instruction should only be used if it is known that all threads in the warpgroup evaluate the condition identically, otherwise the behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90a`. + +Examples + + + wgmma.fence.sync.aligned; + + wgmma.mma_async.sync.aligned.m64n8k32.s32.u8.u8 {s32d0, s32d1, s32d2, s32d3}, + descA, descB, scaleD; + wgmma.commit_group.sync.aligned; + + wgmma.mma_async.sync.aligned.m64n8k16.f32.f16.f16 {f32d0, f32d1, f32d2, f32d3}, + {f16a0, f16a1, f16a2, f16a3}, + descB, 1, -1, -1, 1; + wgmma.commit_group.sync.aligned; + + wgmma.wait_group.sync.aligned 0; \ No newline at end of file diff --git a/content/cuda/docs/ptx-atom/DOC.md b/content/cuda/docs/ptx-atom/DOC.md new file mode 100644 index 00000000..b8349277 --- /dev/null +++ b/content/cuda/docs/ptx-atom/DOC.md @@ -0,0 +1,239 @@ +--- +name: ptx-atom +description: Atomic reduction operations for thread-to-thread communication. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.5. Parallel Synchronization and Communication Instructions:atom + +--- +title: "9.7.13.5. Parallel Synchronization and Communication Instructions:atom" +section: 9.7.13.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.5. Parallel Synchronization and Communication Instructions:atom + + +`atom` + +Atomic reduction operations for thread-to-thread communication. + +Syntax + +Atomic operation with scalar type: + +atom{.sem}{.scope}{.space}.op{.level::cache_hint}.type d, [a], b{, cache-policy}; + atom{.sem}{.scope}{.space}.op.type d, [a], b, c; + + atom{.sem}{.scope}{.space}.cas.b16 d, [a], b, c; + + atom{.sem}{.scope}{.space}.cas.b128 d, [a], b, c; + atom{.sem}{.scope}{.space}.exch{.level::cache_hint}.b128 d, [a], b {, cache-policy}; + + atom{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.f16 d, [a], b{, cache-policy}; + atom{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.f16x2 d, [a], b{, cache-policy}; + + atom{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.bf16 d, [a], b{, cache-policy}; + atom{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.bf16x2 d, [a], b{, cache-policy}; + + .space = { .global, .shared{::cta, ::cluster} }; + .sem = { .relaxed, .acquire, .release, .acq_rel }; + .scope = { .cta, .cluster, .gpu, .sys }; + + .op = { .and, .or, .xor, + .cas, .exch, + .add, .inc, .dec, + .min, .max }; + .level::cache_hint = { .L2::cache_hint }; + .type = { .b32, .b64, .u32, .u64, .s32, .s64, .f32, .f64 }; + +Atomic operation with vector type: + +atom{.sem}{.scope}{.global}.add{.level::cache_hint}.vec_32_bit.f32 d, [a], b{, cache-policy}; + atom{.sem}{.scope}{.global}.op.noftz{.level::cache_hint}.vec_16_bit.half_word_type d, [a], b{, cache-policy}; + atom{.sem}{.scope}{.global}.op.noftz{.level::cache_hint}.vec_32_bit.packed_type d, [a], b{, cache-policy}; + + .sem = { .relaxed, .acquire, .release, .acq_rel }; + .scope = { .cta, .cluster, .gpu, .sys }; + .op = { .add, .min, .max }; + .half_word_type = { .f16, .bf16 }; + .packed_type = { .f16x2, .bf16x2 }; + .vec_16_bit = { .v2, .v4, .v8 } + .vec_32_bit = { .v2, .v4 }; + .level::cache_hint = { .L2::cache_hint } + +Description + +Atomically loads the original value at location `a` into destination register `d`, performs a reduction operation with operand `b` and the value in location `a`, and stores the result of the specified operation at location `a`, overwriting the original value. Operand `a` specifies a location in the specified state space. If no state space is given, perform the memory accesses using [Generic Addressing](<#generic-addressing>). `atom` with scalar type may be used only with `.global` and `.shared` spaces and with generic addressing, where the address points to `.global` or `.shared` space. `atom` with vector type may be used only with `.global` space and with generic addressing where the address points to `.global` space. + +For `atom` with vector type, operands `d` and `b` are brace-enclosed vector expressions, size of which is equal to the size of vector qualifier. + +If no sub-qualifier is specified with `.shared` state space, then `::cta` is assumed by default. + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.sem` qualifier is absent, `.relaxed` is assumed by default. + +The optional `.scope` qualifier specifies the set of threads that can directly observe the memory synchronizing effect of this operation, as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.scope` qualifier is absent, `.gpu` scope is assumed by default. + +For `atom` with vector type, the supported combinations of vector qualifier and types, and atomic operations supported on these combinations are depicted in the following table: + +Vector qualifier | Types +---|--- +`.f16`/ `bf16` | `.f16x2`/ `bf16x2` | `.f32` +`.v2` | `.add`, `.min`, `.max` | `.add`, `.min`, `.max` | `.add` +`.v4` | `.add`, `.min`, `.max` | `.add`, `.min`, `.max` | `.add` +`.v8` | `.add`, `.min`, `.max` | Not supported | Not Supported + +Two atomic operations (`atom` or `red`) are performed atomically with respect to each other only if each operation specifies a scope that includes the other. When this condition is not met, each operation observes the other operation being performed as if it were split into a read followed by a dependent write. + +`atom` instruction on packed type or vector type, accesses adjacent scalar elements in memory. In such cases, the atomicity is guaranteed separately for each of the individual scalar elements; the entire `atom` is not guaranteed to be atomic as a single access. + +For `sm_6x` and earlier architectures, `atom` operations on `.shared` state space do not guarantee atomicity with respect to normal store instructions to the same address. It is the programmer’s responsibility to guarantee correctness of programs that use shared memory atomic instructions, e.g., by inserting barriers between normal stores and atomic operations to a common address, or by using atom.exch to store to locations accessed by other atomic operations. + +Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>) + +The bit-size operations are `.and`, `.or`, `.xor`, `.cas` (compare-and-swap), and `.exch` (exchange). + +The integer operations are `.add`, `.inc`, `.dec`, `.min`, `.max`. The `.inc` and `.dec` operations return a result in the range `[0..b]`. + +The floating-point operation `.add` operation rounds to nearest even. Current implementation of `atom.add.f32` on global memory flushes subnormal inputs and results to sign-preserving zero; whereas `atom.add.f32` on shared memory supports subnormal inputs and results and doesn’t flush them to zero. + +`atom.add.f16`, `atom.add.f16x2`, `atom.add.bf16` and `atom.add.bf16x2` operation requires the `.noftz` qualifier; it preserves subnormal inputs and results, and does not flush them to zero. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +The qualifier `.level::cache_hint` is only supported for `.global` state space and for generic addressing where the address points to the `.global` state space. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +Semantics + +atomic { + d = *a; + *a = (operation == cas) ? operation(*a, b, c) + : operation(*a, b); + } + where + inc(r, s) = (r >= s) ? 0 : r+1; + dec(r, s) = (r==0 || r > s) ? s : r-1; + exch(r, s) = s; + cas(r,s,t) = (r == s) ? t : r; + +Notes + +Simple reductions may be specified by using the _bit bucket_ destination operand `_`. + +PTX ISA Notes + +32-bit atom.global introduced in PTX ISA version 1.1. + +`atom.shared` and 64-bit `atom.global.{add,cas,exch}` introduced in PTX ISA 1.2. + +`atom.add.f32` and 64-bit `atom.shared.{add,cas,exch}` introduced in PTX ISA 2.0. + +64-bit `atom.{and,or,xor,min,max}` introduced in PTX ISA 3.1. + +`atom.add.f64` introduced in PTX ISA 5.0. + +`.scope` qualifier introduced in PTX ISA 5.0. + +`.sem` qualifier introduced in PTX ISA version 6.0. + +`atom.add.noftz.f16x2` introduced in PTX ISA 6.2. + +`atom.add.noftz.f16` and `atom.cas.b16` introduced in PTX ISA 6.3. + +Per-element atomicity of `atom.f16x2` clarified in PTX ISA version 6.3, with retrospective effect from PTX ISA version 6.2. + +Support for `.level::cache_hint` qualifier introduced in PTX ISA version 7.4. + +`atom.add.noftz.bf16` and `atom.add.noftz.bf16x2` introduced in PTX ISA 7.8. + +Support for `.cluster` scope qualifier introduced in PTX ISA version 7.8. + +Support for `::cta` and `::cluster` sub-qualifiers introduced in PTX ISA version 7.8. + +Support for vector types introduced in PTX ISA version 8.1. + +Support for `.b128` type introduced in PTX ISA version 8.3. + +Support for `.sys` scope with `.b128` type introduced in PTX ISA version 8.4. + +Target ISA Notes + +`atom.global` requires `sm_11` or higher. + +`atom.shared` requires `sm_12` or higher. + +64-bit `atom.global.{add,cas,exch}` require `sm_12` or higher. + +64-bit `atom.shared.{add,cas,exch}` require `sm_20` or higher. + +64-bit `atom.{and,or,xor,min,max}` require `sm_32` or higher. + +`atom.add.f32` requires `sm_20` or higher. + +`atom.add.f64` requires `sm_60` or higher. + +`.scope` qualifier requires `sm_60` or higher. + +`.sem` qualifier requires `sm_70` or higher. + +Use of generic addressing requires `sm_20` or higher. + +`atom.add.noftz.f16x2` requires `sm_60` or higher. + +`atom.add.noftz.f16` and `atom.cas.b16` requires `sm_70` or higher. + +Support for `.level::cache_hint` qualifier requires `sm_80` or higher. + +`atom.add.noftz.bf16` and `atom.add.noftz.bf16x2` require `sm_90` or higher. + +Support for `.cluster` scope qualifier requires `sm_90` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Support for vector types requires `sm_90` or higher. + +Support for `.b128` type requires `sm_90` or higher. + +Examples + +atom.global.add.s32 d,[a],1; + atom.shared::cta.max.u32 d,[x+4],0; + @p atom.global.cas.b32 d,[p],my_val,my_new_val; + atom.global.sys.add.u32 d, [a], 1; + atom.global.acquire.sys.inc.u32 ans, [gbl], %r0; + atom.add.noftz.f16x2 d, [a], b; + atom.add.noftz.f16 hd, [ha], hb; + atom.global.cas.b16 hd, [ha], hb, hc; + atom.add.noftz.bf16 hd, [a], hb; + atom.add.noftz.bf16x2 bd, [b], bb; + atom.add.shared::cluster.noftz.f16 hd, [ha], hb; + atom.shared.b128.cas d, a, b, c; // 128-bit atom + atom.global.b128.exch d, a, b; // 128-bit atom + + atom.global.cluster.relaxed.add.u32 d, [a], 1; + + createpolicy.fractional.L2::evict_last.b64 cache-policy, 0.25; + atom.global.add.L2::cache_hint.s32 d, [a], 1, cache-policy; + + atom.global.v8.f16.max.noftz {%hd0, %hd1, %hd2, %hd3, %hd4, %hd5, %hd6, %hd7}, [gbl], + {%h0, %h1, %h2, %h3, %h4, %h5, %h6, %h7}; + atom.global.v8.bf16.add.noftz {%hd0, %hd1, %hd2, %hd3, %hd4, %hd5, %hd6, %hd7}, [gbl], + {%h0, %h1, %h2, %h3, %h4, %h5, %h6, %h7}; + atom.global.v2.f16.add.noftz {%hd0, %hd1}, [gbl], {%h0, %h1}; + atom.global.v2.bf16.add.noftz {%hd0, %hd1}, [gbl], {%h0, %h1}; + atom.global.v4.b16x2.min.noftz {%hd0, %hd1, %hd2, %hd3}, [gbl], {%h0, %h1, %h2, %h3}; + atom.global.v4.f32.add {%f0, %f1, %f2, %f3}, [gbl], {%f0, %f1, %f2, %f3}; + atom.global.v2.f16x2.min.noftz {%bd0, %bd1}, [g], {%b0, %b1}; + atom.global.v2.bf16x2.max.noftz {%bd0, %bd1}, [g], {%b0, %b1}; + atom.global.v2.f32.add {%f0, %f1}, [g], {%f0, %f1}; \ No newline at end of file diff --git a/content/cuda/docs/ptx-atomic-and-reduction-patterns/DOC.md b/content/cuda/docs/ptx-atomic-and-reduction-patterns/DOC.md new file mode 100644 index 00000000..9bbcd56f --- /dev/null +++ b/content/cuda/docs/ptx-atomic-and-reduction-patterns/DOC.md @@ -0,0 +1,68 @@ +--- +name: ptx-atomic-and-reduction-patterns +description: "PTX atomic and reduction patterns: atom/cas/red/redux usage, scope/semantic choices, and lock-free update templates." +metadata: + languages: "cpp" + versions: "9.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,ptx,atomics,reduction,atom,atom.cas,compare-and-swap,cas,cas-loop,red,redux,scope,acquire,release,lock-free,lockfree" +--- + +# PTX Atomic and Reduction Patterns + +Use this page when designing concurrent PTX update paths with explicit scope and memory semantics. + +## Instruction Families + +- Atomic RMW: `atom.*` +- Compare-and-swap: `atom.cas` +- Reduction-update: `red.*` +- Warp/group reduction helper: `redux.sync` + +## Scope and Semantics First + +Correctness depends on selecting: + +- target state space (shared/global/cluster forms as supported) +- scope (`cta`, `cluster`, `gpu`, `sys` as applicable) +- semantics (relaxed/acquire/release/acq_rel where available) + +A wrong scope can appear correct in tests but fail under real concurrency. + +## Canonical Patterns + +- Lock-free queue/head update: + CAS loop with explicit acquire/release semantics. +- Aggregation path: + `red.*` for one-way accumulation where return value is not required. +- Predicate-guided lane aggregation: + warp-level reduction then fewer global atomics. + +## Failure Modes + +- Missing acquire/release pairing between producer and consumer. +- Overly wide scope adds contention and latency. +- Excessive global atomics with no local aggregation stage. + +## Verification Checklist + +- Stress under high contention and varied scheduling. +- Validate determinism policy (if required) separately from correctness. +- Profile contention hotspots and retry-loop pressure. + +## Related Topics + +- PTX synchronization instructions: `../ptx/instructions/sync-comm/DOC.md` +- PTX memory consistency model: `../ptx/references/memory-consistency-model.md` +- PTX warp synchronization patterns: `../ptx-warp-synchronization-patterns/DOC.md` + +## Official Source Links (Fact Check) + +- PTX atom instruction family: https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-atom +- PTX red instruction family: https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-red +- PTX redux.sync: https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-redux-sync +- PTX Memory Consistency Model: https://docs.nvidia.com/cuda/parallel-thread-execution/#memory-consistency-model + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/ptx-atomicity/DOC.md b/content/cuda/docs/ptx-atomicity/DOC.md new file mode 100644 index 00000000..a9cd1c0b --- /dev/null +++ b/content/cuda/docs/ptx-atomicity/DOC.md @@ -0,0 +1,84 @@ +--- +name: ptx-atomicity +description: Single-Copy Atomicity +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.10.3. Atomicity + +--- +title: "8.10.3. Atomicity" +section: 8.10.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.10.3. Atomicity + + +Single-Copy Atomicity + +Conflicting _morally strong_ operations are performed with _single-copy atomicity_. When a read R and a write W are _morally strong_ , then the following two communications cannot both exist in the same execution, for the set of bytes accessed by both R and W: + +1. R reads any byte from W. + + 2. R reads any byte from any write W’ which precedes W in _coherence order_. + +Atomicity of read-modify-write (RMW) operations + +When an _atomic_ operation A and a write W _overlap_ and are _morally strong_ , then the following two communications cannot both exist in the same execution, for the set of bytes accessed by both A and W: + +1. A reads any byte from a write W’ that precedes W in _coherence order_. + + 2. A follows W in _coherence order_. + +Litmus Test 1 + +.global .u32 x = 0; + + +--- +T1 | T2 + + + A1: atom.sys.inc.u32 %r0, [x]; + + +| + + + A2: atom.sys.inc.u32 %r0, [x]; + + + + FINAL STATE: x == 2 + +Atomicity is guaranteed when the operations are _morally strong_. + +Litmus Test 2 + +.global .u32 x = 0; + + +--- +T1 | T2 (In a different CTA) + + + A1: atom.cta.inc.u32 %r0, [x]; + + +| + + + A2: atom.gpu.inc.u32 %r0, [x]; + + + + FINAL STATE: x == 1 OR x == 2 + +Atomicity is not guaranteed if the operations are not _morally strong_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-banked-constant-state-space-deprecated/DOC.md b/content/cuda/docs/ptx-banked-constant-state-space-deprecated/DOC.md new file mode 100644 index 00000000..8aa79c9d --- /dev/null +++ b/content/cuda/docs/ptx-banked-constant-state-space-deprecated/DOC.md @@ -0,0 +1,41 @@ +--- +name: ptx-banked-constant-state-space-deprecated +description: Previous versions of PTX exposed constant memory as a set of eleven 64 + KB banks, with explicit bank numbers required for variable declaration and during + access. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.3.1. Banked Constant State Space (deprecated) + +--- +title: "5.1.3.1. Banked Constant State Space (deprecated)" +section: 5.1.3.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.1.3.1. Banked Constant State Space (deprecated) + + +Previous versions of PTX exposed constant memory as a set of eleven 64 KB banks, with explicit bank numbers required for variable declaration and during access. + +Prior to PTX ISA version 2.2, the constant memory was organized into fixed size banks. There were eleven 64 KB banks, and banks were specified using the `.const[bank]` modifier, where _bank_ ranged from 0 to 10. If no bank number was given, bank zero was assumed. + +By convention, bank zero was used for all statically-sized constant variables. The remaining banks were used to declare _incomplete_ constant arrays (as in C, for example), where the size is not known at compile time. For example, the declaration + +.extern .const[2] .b32 const_buffer[]; + +resulted in `const_buffer` pointing to the start of constant bank two. This pointer could then be used to access the entire 64 KB constant bank. Multiple incomplete array variables declared in the same bank were aliased, with each pointing to the start address of the specified constant bank. + +To access data in contant banks 1 through 10, the bank number was required in the state space of the load instruction. For example, an incomplete array in bank 2 was accessed as follows: + +.extern .const[2] .b32 const_buffer[]; + ld.const[2].b32 %r1, [const_buffer+4]; // load second word + +In PTX ISA version 2.2, we eliminated explicit banks and replaced the incomplete array representation of driver-allocated constant buffers with kernel parameter attributes that allow pointers to constant buffers to be passed as kernel parameters. \ No newline at end of file diff --git a/content/cuda/docs/ptx-barbarrier/DOC.md b/content/cuda/docs/ptx-barbarrier/DOC.md new file mode 100644 index 00000000..a1a1b262 --- /dev/null +++ b/content/cuda/docs/ptx-barbarrier/DOC.md @@ -0,0 +1,150 @@ +--- +name: ptx-barbarrier +description: '`bar`, `bar.cta`, `barrier`, `barrier.cta`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.1. Parallel Synchronization and Communication Instructions:bar,barrier + +--- +title: "9.7.13.1. Parallel Synchronization and Communication Instructions:bar,barrier" +section: 9.7.13.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.1. Parallel Synchronization and Communication Instructions:bar,barrier + + +`bar`, `bar.cta`, `barrier`, `barrier.cta` + +Barrier synchronization. + +Syntax + +barrier{.cta}.sync{.aligned} a{, b}; + barrier{.cta}.arrive{.aligned} a, b; + + barrier{.cta}.red.popc{.aligned}.u32 d, a{, b}, {!}c; + barrier{.cta}.red.op{.aligned}.pred p, a{, b}, {!}c; + + bar{.cta}.sync a{, b}; + bar{.cta}.arrive a, b; + + bar{.cta}.red.popc.u32 d, a{, b}, {!}c; + bar{.cta}.red.op.pred p, a{, b}, {!}c; + + .op = { .and, .or }; + +Description + +Performs barrier synchronization and communication within a CTA. Each CTA instance has sixteen barriers numbered `0..15`. + +`barrier{.cta}` instructions can be used by the threads within the CTA for synchronization and communication. + +Operands `a`, `b`, and `d` have type `.u32`; operands `p` and `c` are predicates. Source operand `a` specifies a logical barrier resource as an immediate constant or register with value `0` through `15`. Operand `b` specifies the number of threads participating in the barrier. If no thread count is specified, all threads in the CTA participate in the barrier. When specifying a thread count, the value must be a multiple of the warp size. Note that a non-zero thread count is required for `barrier{.cta}.arrive`. + +Depending on operand `b`, either specified number of threads (in multiple of warp size) or all threads in the CTA participate in `barrier{.cta}` instruction. The `barrier{.cta}` instructions signal the arrival of the executing threads at the named barrier. + +`barrier{.cta}` instruction causes executing thread to wait for all non-exited threads from its warp and marks warps’ arrival at barrier. In addition to signaling its arrival at the barrier, the `barrier{.cta}.red` and `barrier{.cta}.sync` instructions causes executing thread to wait for non-exited threads of all other warps participating in the barrier to arrive. `barrier{.cta}.arrive` does not cause executing thread to wait for threads of other participating warps. + +When a barrier completes, the waiting threads are restarted without delay, and the barrier is reinitialized so that it can be immediately reused. + +The `barrier{.cta}.sync` or `barrier{.cta}.red` or `barrier{.cta}.arrive` instruction guarantees that when the barrier completes, prior memory accesses requested by this thread are performed relative to all threads participating in the barrier. The `barrier{.cta}.sync` and `barrier{.cta}.red` instruction further guarantees that no new memory access is requested by this thread before the barrier completes. + +A memory read (e.g., by `ld` or `atom`) has been performed when the value read has been transmitted from memory and cannot be modified by another thread participating in the barrier. A memory write (e.g., by `st`, `red` or `atom`) has been performed when the value written has become visible to other threads participating in the barrier, that is, when the previous value can no longer be read. + +`barrier{.cta}.red` performs a reduction operation across threads. The `c` predicate (or its complement) from all threads in the CTA are combined using the specified reduction operator. Once the barrier count is reached, the final value is written to the destination register in all threads waiting at the barrier. + +The reduction operations for `barrier{.cta}.red` are population-count (`.popc`), all-threads-True (`.and`), and any-thread-True (`.or`). The result of `.popc` is the number of threads with a `True` predicate, while `.and` and `.or` indicate if all the threads had a `True` predicate or if any of the threads had a `True` predicate. + +Instruction `barrier{.cta}` has optional `.aligned` modifier. When specified, it indicates that all threads in CTA will execute the same `barrier{.cta}` instruction. In conditionally executed code, an aligned `barrier{.cta}` instruction should only be used if it is known that all threads in CTA evaluate the condition identically, otherwise behavior is undefined. + +Different warps may execute different forms of the `barrier{.cta}` instruction using the same barrier name and thread count. One example mixes `barrier{.cta}.sync` and `barrier{.cta}.arrive` to implement producer/consumer models. The producer threads execute `barrier{.cta}.arrive` to announce their arrival at the barrier and continue execution without delay to produce the next value, while the consumer threads execute the `barrier{.cta}.sync` to wait for a resource to be produced. The roles are then reversed, using a different barrier, where the producer threads execute a `barrier{.cta}.sync` to wait for a resource to consumed, while the consumer threads announce that the resource has been consumed with `barrier{.cta}.arrive`. Care must be taken to keep a warp from executing more `barrier{.cta}` instructions than intended (`barrier{.cta}.arrive` followed by any other `barrier{.cta}` instruction to the same barrier) prior to the reset of the barrier. `barrier{.cta}.red` should not be intermixed with `barrier{.cta}.sync` or `barrier{.cta}.arrive` using the same active barrier. Execution in this case is unpredictable. + +The optional `.cta` qualifier simply indicates CTA-level applicability of the barrier and it doesn’t change the semantics of the instruction. + +`bar{.cta}.sync` is equivalent to `barrier{.cta}.sync.aligned`. `bar{.cta}.arrive` is equivalent to `barrier{.cta}.arrive.aligned`. `bar{.cta}.red` is equivalent to `barrier{.cta}.red.aligned`. + +Note + +For .target `sm_6x` or below, + + 1. `barrier{.cta}` instruction without `.aligned` modifier is equivalent to `.aligned` variant and has the same restrictions as of `.aligned` variant. + + 2. All threads in warp (except for those have exited) must execute `barrier{.cta}` instruction in convergence. + +PTX ISA Notes + +`bar.sync` without a thread count introduced in PTX ISA version 1.0. + +Register operands, thread count, and `bar.{arrive,red}` introduced in PTX ISA version 2.0. + +`barrier` instruction introduced in PTX ISA version 6.0. + +`.cta` qualifier introduced in PTX ISA version 7.8. + +Target ISA Notes + +Register operands, thread count, and `bar{.cta}.{arrive,red}` require `sm_20` or higher. + +Only `bar{.cta}.sync` with an immediate barrier number is supported for `sm_1x` targets. + +`barrier{.cta}` instruction requires `sm_30` or higher. + +Examples + +// Use bar.sync to arrive at a pre-computed barrier number and + // wait for all threads in CTA to also arrive: + st.shared [r0],r1; // write my result to shared memory + bar.cta.sync 1; // arrive, wait for others to arrive + ld.shared r2,[r3]; // use shared results from other threads + + // Use bar.sync to arrive at a pre-computed barrier number and + // wait for fixed number of cooperating threads to arrive: + #define CNT1 (8*12) // Number of cooperating threads + + st.shared [r0],r1; // write my result to shared memory + bar.cta.sync 1, CNT1; // arrive, wait for others to arrive + ld.shared r2,[r3]; // use shared results from other threads + + // Use bar.red.and to compare results across the entire CTA: + setp.eq.u32 p,r1,r2; // p is True if r1==r2 + bar.cta.red.and.pred r3,1,p; // r3=AND(p) forall threads in CTA + + // Use bar.red.popc to compute the size of a group of threads + // that have a specific condition True: + setp.eq.u32 p,r1,r2; // p is True if r1==r2 + bar.cta.red.popc.u32 r3,1,p; // r3=SUM(p) forall threads in CTA + + // Examples of barrier.cta.sync + st.shared [r0],r1; + barrier.cta.sync 0; + ld.shared r1, [r0]; + + /* Producer/consumer model. The producer deposits a value in + * shared memory, signals that it is complete but does not wait + * using bar.arrive, and begins fetching more data from memory. + * Once the data returns from memory, the producer must wait + * until the consumer signals that it has read the value from + * the shared memory location. In the meantime, a consumer + * thread waits until the data is stored by the producer, reads + * it, and then signals that it is done (without waiting). + */ + // Producer code places produced value in shared memory. + st.shared [r0],r1; + bar.arrive 0,64; + ld.global r1,[r2]; + bar.sync 1,64; + ... + + // Consumer code, reads value from shared memory + bar.sync 0,64; + ld.shared r1,[r0]; + bar.arrive 1,64; + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-barriercluster/DOC.md b/content/cuda/docs/ptx-barriercluster/DOC.md new file mode 100644 index 00000000..ef6e0d1b --- /dev/null +++ b/content/cuda/docs/ptx-barriercluster/DOC.md @@ -0,0 +1,84 @@ +--- +name: ptx-barriercluster +description: Barrier synchronization within a cluster. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.3. Parallel Synchronization and Communication Instructions:barrier.cluster + +--- +title: "9.7.13.3. Parallel Synchronization and Communication Instructions:barrier.cluster" +section: 9.7.13.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.3. Parallel Synchronization and Communication Instructions:barrier.cluster + + +`barrier.cluster` + +Barrier synchronization within a cluster. + +Syntax + +barrier.cluster.arrive{.sem}{.aligned}; + barrier.cluster.wait{.acquire}{.aligned}; + + .sem = {.release, .relaxed} + +Description + +Performs barrier synchronization and communication within a cluster. + +`barrier.cluster` instructions can be used by the threads within the cluster for synchronization and communication. + +`barrier.cluster.arrive` instruction marks warps’ arrival at barrier without causing executing thread to wait for threads of other participating warps. + +`barrier.cluster.wait` instruction causes the executing thread to wait for all non-exited threads of the cluster to perform `barrier.cluster.arrive`. + +In addition, `barrier.cluster` instructions cause the executing thread to wait for all non-exited threads from its warp. + +When all non-exited threads in the cluster have executed `barrier.cluster.arrive`, the barrier completes and is automatically reinitialized. After using `barrier.cluster.wait` to detect completion of the barrier, a thread may immediately arrive at the barrier once again. Each thread must arrive at the barrier only once before the barrier completes. + +The `barrier.cluster.wait` instruction guarantees that when it completes the execution, memory accesses (except asynchronous operations) requested, in program order, prior to the preceding `barrier.cluster.arrive` by all threads in the cluster are complete and visible to the executing thread. + +There is no memory ordering and visibility guarantee for memory accesses requested by the executing thread, in program order, after `barrier.cluster.arrive` and prior to `barrier.cluster.wait`. + +The optional `.relaxed` qualifier on `barrier.cluster.arrive` specifies that there are no memory ordering and visibility guarantees provided for the memory accesses performed prior to `barrier.cluster.arrive`. + +The optional `.sem` and `.acquire` qualifiers on instructions `barrier.cluster.arrive` and `barrier.cluster.wait` specify the memory synchronization as described in the [Memory Consistency Model](<#memory-consistency-model>). If the optional `.sem` qualifier is absent for `barrier.cluster.arrive`, `.release` is assumed by default. If the optional `.acquire` qualifier is absent for `barrier.cluster.wait`, `.acquire` is assumed by default. + +The optional `.aligned` qualifier indicates that all threads in the warp must execute the same `barrier.cluster` instruction. In conditionally executed code, an aligned `barrier.cluster` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Support for `.acquire`, `.relaxed`, `.release` qualifiers introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +// use of arrive followed by wait + ld.shared::cluster.u32 r0, [addr]; + barrier.cluster.arrive.aligned; + ... + barrier.cluster.wait.aligned; + st.shared::cluster.u32 [addr], r1; + + // use memory fence prior to arrive for relaxed barrier + @cta0 ld.shared::cluster.u32 r0, [addr]; + fence.cluster.acq_rel; + barrier.cluster.arrive.relaxed.aligned; + ... + barrier.cluster.wait.aligned; + @cta1 st.shared::cluster.u32 [addr], r1; \ No newline at end of file diff --git a/content/cuda/docs/ptx-barwarpsync/DOC.md b/content/cuda/docs/ptx-barwarpsync/DOC.md new file mode 100644 index 00000000..04bb2b88 --- /dev/null +++ b/content/cuda/docs/ptx-barwarpsync/DOC.md @@ -0,0 +1,58 @@ +--- +name: ptx-barwarpsync +description: Barrier synchronization for threads in a warp. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.2. Parallel Synchronization and Communication Instructions:bar.warp.sync + +--- +title: "9.7.13.2. Parallel Synchronization and Communication Instructions:bar.warp.sync" +section: 9.7.13.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.2. Parallel Synchronization and Communication Instructions:bar.warp.sync + + +`bar.warp.sync` + +Barrier synchronization for threads in a warp. + +Syntax + +bar.warp.sync membermask; + +Description + +`bar.warp.sync` will cause executing thread to wait until all threads corresponding to `membermask` have executed a `bar.warp.sync` with the same `membermask` value before resuming execution. + +Operand `membermask` specifies a 32-bit integer which is a mask indicating threads participating in barrier where the bit position corresponds to thread’s `laneid`. + +The behavior of `bar.warp.sync` is undefined if the executing thread is not in the `membermask`. + +`bar.warp.sync` also guarantee memory ordering among threads participating in barrier. Thus, threads within warp that wish to communicate via memory can store to memory, execute `bar.warp.sync`, and then safely read values stored by other threads in warp. + +Note + +For .target `sm_6x` or below, all threads in `membermask` must execute the same `bar.warp.sync` instruction in convergence, and only threads belonging to some `membermask` can be active when the `bar.warp.sync` instruction is executed. Otherwise, the behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 6.0. + +Target ISA Notes + +Requires `sm_30` or higher. + +Examples + +st.shared.u32 [r0],r1; // write my result to shared memory + bar.warp.sync 0xffffffff; // arrive, wait for others to arrive + ld.shared.u32 r2,[r3]; // read results written by other threads \ No newline at end of file diff --git a/content/cuda/docs/ptx-bfe/DOC.md b/content/cuda/docs/ptx-bfe/DOC.md new file mode 100644 index 00000000..3a51537a --- /dev/null +++ b/content/cuda/docs/ptx-bfe/DOC.md @@ -0,0 +1,83 @@ +--- +name: ptx-bfe +description: Bit Field Extract. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.19. Integer Arithmetic Instructions:bfe + +--- +title: "9.7.1.19. Integer Arithmetic Instructions:bfe" +section: 9.7.1.19 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.19. Integer Arithmetic Instructions:bfe + + +`bfe` + +Bit Field Extract. + +Syntax + +bfe.type d, a, b, c; + + .type = { .u32, .u64, + .s32, .s64 }; + +Description + +Extract bit field from `a` and place the zero or sign-extended result in `d`. Source `b` gives the bit field starting bit position, and source `c` gives the bit field length in bits. + +Operands `a` and `d` have the same type as the instruction type. Operands `b` and `c` are type `.u32`, but are restricted to the 8-bit value range `0..255`. + +The sign bit of the extracted field is defined as: + +`.u32`, `.u64`: + + +zero + +`.s32`, `.s64`: + + +`msb` of input a if the extracted field extends beyond the `msb` of a `msb` of extracted field, otherwise + +If the bit field length is zero, the result is zero. + +The destination `d` is padded with the sign bit of the extracted field. If the start position is beyond the `msb` of the input, the destination `d` is filled with the replicated sign bit of the extracted field. + +Semantics + +msb = (.type==.u32 || .type==.s32) ? 31 : 63; + pos = b & 0xff; // pos restricted to 0..255 range + len = c & 0xff; // len restricted to 0..255 range + + if (.type==.u32 || .type==.u64 || len==0) + sbit = 0; + else + sbit = a[min(pos+len-1,msb)]; + + d = 0; + for (i=0; i<=msb; i++) { + d[i] = (i=0; i--) { + if (a & (1<) shows an example of `mma` with block scaling of `scale_vec::2X`. + +![_images/mma-block-scaling.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-block-scaling.png) + +Figure 42 `mma` with block scaling of `.scale_vec::2X` + +The shapes for `scale_A` and `scale_B` matrices depend upon the qualifier `.scale_vec_size` as shown in [Table 35](<#mma-scale-vec-matrix-shape>). + +Table 35 Shapes for scale matrices depending upon `.scale_vec_size` qualifier .scale_vec_size | Shape of scale_A | Shape of scale_B +---|---|--- +`.scale_vec::1X` | M x 1 | 1 x N +`.scale_vec::2X` | M x 2 | 2 x N +`.scale_vec::4X` | M x 4 | 4 x N + +The valid combination of the exact element types and the `.scale_vec_size` are listed in [Table 36](<#mma-scaling-kind-type-valid-combination>). + +Table 36 Valid combinations of `.scale_vec_size` and `.kind` qualifier .kind::* | Element Data Type .atype and .btype | Scale Data Type .stype | .scale_vec_size +---|---|---|--- +`.kind::mxf8f6f4` | `.e4m3`, `.e5m2` `.e3m2`, `.e2m3` `.e2m1` | `.ue8m0` | `.scale_vec::1X` +`.kind::mxf4` | `.e2m1` | `.ue8m0` | `.scale_vec::2X` +`.kind::mxf4nvf4` | `.e2m1` | `.ue8m0` | `.scale_vec::2X`, `.scale_vec::4X` +`.e2m1` | `.ue4m3` | `.scale_vec::4X` + +The `scale-a-data` and `scale-b-data` argument provides metadata for `scale_A` and `scale_B` matrices respectively. The tuple `{byte-id-a, thread-id-a}` and `{byte-id-b, thread-id-b}` provides the selector information to choose elements _SF_A_ and _SF_B_ from corresponding metadata arguments `scale-a-data` and `scale-b-data`. The tuple `{byte-id-a, thread-id-a}` allows to select the scale matrix element _SF_A_ from `scale-a-data`. Similarly, the tuple `{byte-id-b, thread-id-b}` allows to select the scale matrix element _SF_B_ from `scale-b-data`. + +The components `thread-id-a`, `thread-id-b` decides which threads among the quad contribute the _SF_A_ and _SF_B_ values. The following listing describes the impact of thread selector component `thread-id-a`, `thread-id-b`: + +* One thread-pair within the quad determined by `thread-id-a`, contributes the _SF_A_ values. The value of 0 selects lower two threads whereas value of 1 selects upper two threads from the quad. In other words, when `thread-id-a` set to 0, thread-pair satisfying: `%laneid` % 4 == 0 or 1 provides the _SF_A_. In contrast when `thread-id-a` set to 1, thread-pair satisfying: `%laneid` % 4 == 2 or 3 provides the _SF_A_. Refer [Figure 43](<#mma-scaling-thread-id-a-selection>) for more details. + +![_images/mma-scaling-thread-id-a-selection.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-scaling-thread-id-a-selection.png) + +Figure 43 Selection of set of values for _SF_A_ based on `thread-id-a` + + * One thread within the quad, determined by `thread-id-b`, contributes the _SF_B_ value. In other words, each thread satisfying: `%laneid` % 4 == `thread-id-b` provides the _SF_B_. Refer [Figure 44](<#mma-scaling-thread-id-b-selection>) for more details. + +![_images/mma-scaling-thread-id-b-selection.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-scaling-thread-id-b-selection.png) + +Figure 44 Selection of set of values for _SF_B_ based on `thread-id-b` + +The arguments `byte-id-a`, `byte-id-b` selects which bytes from the `scale-a-data`, `scale-b-data` contribute the _SF_A_ and _SF_B_ values. The following listing describes implications of `.scale_vec_size` qualifier on byte selector component `byte-id-a`, `byte-id-b`: + +* When `.scale_vec_size` is `.scale_vec::1X` + + * One byte each within `scale-a-data` and `scale-b-data` determined by `byte-id-a`, `byte-id-b` respectively contributes the _SF_A_ and _SF_B_ values. + + * When `.scale_vec_size` is `.scale_vec::2X` + + * One byte-pair (two bytes) within `scale-a-data` and `scale-b-data` determined by `byte-id-a` and `byte-id-b` contributes the _SF_A_ and _SF_B_ values. The value of 0 selects lower two bytes whereas value of 2 selects upper two bytes from the corresponding metadata value. + + * When `.scale_vec_size` is `.scale_vec::4X` + + * All four bytes within `scale-a-data` and `scale-b-data` contribute the values. Hence, `byte-id-a`, `byte-id-b` must be zero. + +Refer [Figure 45](<#mma-scaling-byte-id-selection>) for more details. + +![_images/mma-scaling-byte-id-selection.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-scaling-byte-id-selection.png) + +Figure 45 Selection of set of values for _SF_A_ or _SF_B_ based on `byte-id-a` or `byte-id-b` + +[Table 37](<#mma-scaling-valid-values-of-selector-components>) enumerates the valid values for various selector components. Any other value results in an undefined behavior. + +Table 37 Valid values for various selector components .scale_vec_size | Selector Components +---|--- +byte-id-a | thread-id-a | byte-id-b | thread-id-b +`scale_vec::1X` | [0, 1, 2, 3] | [0, 1] | [0, 1, 2, 3] | [0, 1, 2, 3] +`scale_vec::2X` | [0, 2] | [0, 2] +`scale_vec::4X` | 0 | 0 \ No newline at end of file diff --git a/content/cuda/docs/ptx-bmsk/DOC.md b/content/cuda/docs/ptx-bmsk/DOC.md new file mode 100644 index 00000000..0f9babf1 --- /dev/null +++ b/content/cuda/docs/ptx-bmsk/DOC.md @@ -0,0 +1,88 @@ +--- +name: ptx-bmsk +description: Bit Field Mask. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.22. Integer Arithmetic Instructions:bmsk + +--- +title: "9.7.1.22. Integer Arithmetic Instructions:bmsk" +section: 9.7.1.22 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.22. Integer Arithmetic Instructions:bmsk + + +`bmsk` + +Bit Field Mask. + +Syntax + +bmsk.mode.b32 d, a, b; + + .mode = { .clamp, .wrap }; + +Description + +Generates a 32-bit mask starting from the bit position specified in operand `a`, and of the width specified in operand `b`. The generated bitmask is stored in the destination operand `d`. + +The resulting bitmask is 0 in the following cases: + +* When the value of `a` is 32 or higher and `.mode` is `.clamp`. + + * When either the specified value of `b` or the wrapped value of `b` (when `.mode` is specified as `.wrap`) is 0. + +Semantics + +a1 = a & 0x1f; + mask0 = (~0) << a1; + b1 = b & 0x1f; + sum = a1 + b1; + mask1 = (~0) << sum; + + sum-overflow = sum >= 32 ? true : false; + bit-position-overflow = false; + bit-width-overflow = false; + + if (.mode == .clamp) { + if (a >= 32) { + bit-position-overflow = true; + mask0 = 0; + } + if (b >= 32) { + bit-width-overflow = true; + } + } + + if (sum-overflow || bit-position-overflow || bit-width-overflow) { + mask1 = 0; + } else if (b1 == 0) { + mask1 = ~0; + } + d = mask0 & ~mask1; + +Notes + +The bitmask width specified by operand `b` is limited to range `0..32` in `.clamp` mode and to range `0..31` in `.wrap` mode. + +PTX ISA Notes + +Introduced in PTX ISA version 7.6. + +Target ISA Notes + +`bmsk` requires `sm_70` or higher. + +Examples + +bmsk.clamp.b32 rd, ra, rb; + bmsk.wrap.b32 rd, 1, 2; // Creates a bitmask of 0x00000006. \ No newline at end of file diff --git a/content/cuda/docs/ptx-bounding-box/DOC.md b/content/cuda/docs/ptx-bounding-box/DOC.md new file mode 100644 index 00000000..3de9cf5d --- /dev/null +++ b/content/cuda/docs/ptx-bounding-box/DOC.md @@ -0,0 +1,45 @@ +--- +name: ptx-bounding-box +description: In these modes, the size of the bounding box in `D` and `H` dimensions + are 1. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.5.5.1. Bounding Box + +--- +title: "5.5.5.1. Bounding Box" +section: 5.5.5.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.5.5.1. Bounding Box + + +In these modes, the size of the bounding box in `D` and `H` dimensions are 1. + +The `D` and `H` dimensions in the tensor coordinates argument in the PTX instruction specify the position of the bounding box in the tensor space. + +The Bounding-Box `Lower-Corner-W` and Bounding-Box `Upper-Corner-W` specify the two opposite corners of the Bounding Box in the `W` dimension. + +The `W` dimension in the tensor coordinates argument in the PTX instruction specify the location of the first element that is to be accessed in the bounding box. + +Number of pixels loaded in `im2col::w` mode is as specified by Pixels-per-Column in the TensorMap. Number of pixels loaded in `im2col::w::128` mode is always 128. So, Pixels-per-Column is ignored in `im2col::w::128` mode. + +[Figure 16](<#tensor-im2col-w-w128-modes-example>) shows an example of the `im2col::w` and `im2col::w:128` modes. + +![_images/tensor-im2col-w-w128-modes-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tensor-im2col-w-w128-modes-example.png) + +Figure 16 im2col::w and im2col::w::128 modes example + +The first element can lie outside of the Bounding Box in the W-dimension only and only on the left side of the Bounding Box. [Figure 17](<#tensor-im2col-w-w128-modes-example2>) shows of an example of this. + +![_images/tensor-im2col-w-w128-modes-example2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tensor-im2col-w-w128-modes-example2.png) + +Figure 17 im2col::w and im2col::w::128 modes first element outside Bounding Box example \ No newline at end of file diff --git a/content/cuda/docs/ptx-bra/DOC.md b/content/cuda/docs/ptx-bra/DOC.md new file mode 100644 index 00000000..d75b1ee3 --- /dev/null +++ b/content/cuda/docs/ptx-bra/DOC.md @@ -0,0 +1,58 @@ +--- +name: ptx-bra +description: Branch to a target and continue execution there. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.12.3. Control Flow Instructions:bra + +--- +title: "9.7.12.3. Control Flow Instructions:bra" +section: 9.7.12.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.12.3. Control Flow Instructions:bra + + +`bra` + +Branch to a target and continue execution there. + +Syntax + +@p bra{.uni} tgt; // tgt is a label + bra{.uni} tgt; // unconditional branch + +Description + +Continue execution at the target. Conditional branches are specified by using a guard predicate. The branch target must be a label. + +`bra.uni` is guaranteed to be non-divergent, i.e. all active threads in a warp that are currently executing this instruction have identical values for the guard predicate and branch target. + +Semantics + +if (p) { + pc = tgt; + } + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Unimplemented indirect branch introduced in PTX ISA version 2.1 has been removed from the spec. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +bra.uni L_exit; // uniform unconditional jump + @q bra L23; // conditional branch \ No newline at end of file diff --git a/content/cuda/docs/ptx-brev/DOC.md b/content/cuda/docs/ptx-brev/DOC.md new file mode 100644 index 00000000..eb1ec544 --- /dev/null +++ b/content/cuda/docs/ptx-brev/DOC.md @@ -0,0 +1,56 @@ +--- +name: ptx-brev +description: Bit reverse. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.18. Integer Arithmetic Instructions:brev + +--- +title: "9.7.1.18. Integer Arithmetic Instructions:brev" +section: 9.7.1.18 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.18. Integer Arithmetic Instructions:brev + + +`brev` + +Bit reverse. + +Syntax + +brev.type d, a; + + .type = { .b32, .b64 }; + +Description + +Perform bitwise reversal of input. + +Semantics + +msb = (.type==.b32) ? 31 : 63; + + for (i=0; i<=msb; i++) { + d[i] = a[msb-i]; + } + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +`brev` requires `sm_20` or higher. + +Examples + +brev.b32 d, a; \ No newline at end of file diff --git a/content/cuda/docs/ptx-brkpt/DOC.md b/content/cuda/docs/ptx-brkpt/DOC.md new file mode 100644 index 00000000..4aed2921 --- /dev/null +++ b/content/cuda/docs/ptx-brkpt/DOC.md @@ -0,0 +1,47 @@ +--- +name: ptx-brkpt +description: Breakpoint. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.19.1. Miscellaneous Instructions:brkpt + +--- +title: "9.7.19.1. Miscellaneous Instructions:brkpt" +section: 9.7.19.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.19.1. Miscellaneous Instructions:brkpt + + +`brkpt` + +Breakpoint. + +Syntax + +brkpt; + +Description + +Suspends execution. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +`brkpt` requires `sm_11` or higher. + +Examples + +brkpt; + @p brkpt; \ No newline at end of file diff --git a/content/cuda/docs/ptx-brxidx/DOC.md b/content/cuda/docs/ptx-brxidx/DOC.md new file mode 100644 index 00000000..bb66be6f --- /dev/null +++ b/content/cuda/docs/ptx-brxidx/DOC.md @@ -0,0 +1,75 @@ +--- +name: ptx-brxidx +description: Branch to a label indexed from a list of potential branch targets. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.12.4. Control Flow Instructions:brx.idx + +--- +title: "9.7.12.4. Control Flow Instructions:brx.idx" +section: 9.7.12.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.12.4. Control Flow Instructions:brx.idx + + +`brx.idx` + +Branch to a label indexed from a list of potential branch targets. + +Syntax + +@p brx.idx{.uni} index, tlist; + brx.idx{.uni} index, tlist; + +Description + +Index into a list of possible destination labels, and continue execution from the chosen label. Conditional branches are specified by using a guard predicate. + +`brx.idx.uni` guarantees that the branch is non-divergent, i.e. all active threads in a warp that are currently executing this instruction have identical values for the guard predicate and the `index` argument. + +The `index` operand is a `.u32` register. The `tlist` operand must be the label of a `.branchtargets` directive. It is accessed as a zero-based sequence using `index`. Behaviour is undefined if the value of `index` is greater than or equal to the length of `tlist`. + +The `.branchtargets` directive must be defined in the local function scope before it is used. It must refer to labels within the current function. + +Semantics + +if (p) { + if (index < length(tlist)) { + pc = tlist[index]; + } else { + pc = undefined; + } + } + +PTX ISA Notes + +Introduced in PTX ISA version 6.0. + +Target ISA Notes + +Requires `sm_30` or higher. + +Examples + +.function foo () { + .reg .u32 %r0; + ... + L1: + ... + L2: + ... + L3: + ... + ts: .branchtargets L1, L2, L3; + @p brx.idx %r0, ts; + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-cache-eviction-priority-hints/DOC.md b/content/cuda/docs/ptx-cache-eviction-priority-hints/DOC.md new file mode 100644 index 00000000..bd169df6 --- /dev/null +++ b/content/cuda/docs/ptx-cache-eviction-priority-hints/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-cache-eviction-priority-hints +description: PTX ISA version 7.4 adds optional cache eviction priority hints on load + and store instructions. Cache eviction priority requires target architecture `sm_70` + or higher. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.2. Cache Eviction Priority Hints + +--- +title: "9.7.9.2. Cache Eviction Priority Hints" +section: 9.7.9.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.2. Cache Eviction Priority Hints + + +PTX ISA version 7.4 adds optional cache eviction priority hints on load and store instructions. Cache eviction priority requires target architecture `sm_70` or higher. + +Cache eviction priority on load or store instructions is treated as a performance hint. It is supported for `.global` state space and generic addresses where the address points to `.global` state space. + +Table 32 Cache Eviction Priority Hints for Memory Load and Store Instructions Cache Eviction Priority | Meaning +---|--- +`evict_normal` | Cache data with normal eviction priority. This is the default eviction priority. +`evict_first` | Data cached with this priority will be first in the eviction priority order and will likely be evicted when cache eviction is required. This priority is suitable for streaming data. +`evict_last` | Data cached with this priority will be last in the eviction priority order and will likely be evicted only after other data with `evict_normal` or `evict_first` eviction priotity is already evicted. This priority is suitable for data that should remain persistent in cache. +`evict_unchanged` | Do not change eviction priority order as part of this operation. +`no_allocate` | Do not allocate data to cache. This priority is suitable for streaming data. \ No newline at end of file diff --git a/content/cuda/docs/ptx-cache-operators/DOC.md b/content/cuda/docs/ptx-cache-operators/DOC.md new file mode 100644 index 00000000..965c9680 --- /dev/null +++ b/content/cuda/docs/ptx-cache-operators/DOC.md @@ -0,0 +1,44 @@ +--- +name: ptx-cache-operators +description: PTX ISA version 2.0 introduced optional cache operators on load and store + instructions. The cache operators require a target architecture of `sm_20` or higher. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.1. Cache Operators + +--- +title: "9.7.9.1. Cache Operators" +section: 9.7.9.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.1. Cache Operators + + +PTX ISA version 2.0 introduced optional cache operators on load and store instructions. The cache operators require a target architecture of `sm_20` or higher. + +Cache operators on load or store instructions are treated as performance hints only. The use of a cache operator on an `ld` or `st` instruction does not change the memory consistency behavior of the program. + +For `sm_20` and higher, the cache operators have the following definitions and behavior. + +Table 30 Cache Operators for Memory Load Instructions Operator | Meaning +---|--- +`.ca` | Cache at all levels, likely to be accessed again. The default load instruction cache operation is ld.ca, which allocates cache lines in all levels (L1 and L2) with normal eviction policy. Global data is coherent at the L2 level, but multiple L1 caches are not coherent for global data. If one thread stores to global memory via one L1 cache, and a second thread loads that address via a second L1 cache with `ld.ca`, the second thread may get stale L1 cache data, rather than the data stored by the first thread. The driver must invalidate global L1 cache lines between dependent grids of parallel threads. Stores by the first grid program are then correctly fetched by the second grid program issuing default `ld.ca` loads cached in L1. +`.cg` | Cache at global level (cache in L2 and below, not L1). Use `ld.cg` to cache loads only globally, bypassing the L1 cache, and cache only in the L2 cache. +`.cs` | Cache streaming, likely to be accessed once. The `ld.cs` load cached streaming operation allocates global lines with evict-first policy in L1 and L2 to limit cache pollution by temporary streaming data that may be accessed once or twice. When `ld.cs` is applied to a Local window address, it performs the `ld.lu` operation. +`.lu` | Last use. The compiler/programmer may use `ld.lu` when restoring spilled registers and popping function stack frames to avoid needless write-backs of lines that will not be used again. The `ld.lu` instruction performs a load cached streaming operation (`ld.cs`) on global addresses. +`.cv` | Don’t cache and fetch again (consider cached system memory lines stale, fetch again). The ld.cv load operation applied to a global System Memory address invalidates (discards) a matching L2 line and re-fetches the line on each new load. + +Table 31 Cache Operators for Memory Store Instructions Operator | Meaning +---|--- +`.wb` | Cache write-back all coherent levels. The default store instruction cache operation is `st.wb`, which writes back cache lines of coherent cache levels with normal eviction policy. If one thread stores to global memory, bypassing its L1 cache, and a second thread in a different SM later loads from that address via a different L1 cache with `ld.ca`, the second thread may get a hit on stale L1 cache data, rather than get the data from L2 or memory stored by the first thread. The driver must invalidate global L1 cache lines between dependent grids of thread arrays. Stores by the first grid program are then correctly missed in L1 and fetched by the second grid program issuing default `ld.ca` loads. +`.cg` | Cache at global level (cache in L2 and below, not L1). Use `st.cg` to cache global store data only globally, bypassing the L1 cache, and cache only in the L2 cache. +`.cs` | Cache streaming, likely to be accessed once. The `st.cs` store cached-streaming operation allocates cache lines with evict-first policy to limit cache pollution by streaming output data. +`.wt` | Cache write-through (to system memory). The `st.wt` store write-through operation applied to a global System Memory address writes through the L2 cache. \ No newline at end of file diff --git a/content/cuda/docs/ptx-call/DOC.md b/content/cuda/docs/ptx-call/DOC.md new file mode 100644 index 00000000..dbada4a0 --- /dev/null +++ b/content/cuda/docs/ptx-call/DOC.md @@ -0,0 +1,101 @@ +--- +name: ptx-call +description: Call a function, recording the return location. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.12.5. Control Flow Instructions:call + +--- +title: "9.7.12.5. Control Flow Instructions:call" +section: 9.7.12.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.12.5. Control Flow Instructions:call + + +`call` + +Call a function, recording the return location. + +Syntax + +// direct call to named function, func is a symbol + call{.uni} (ret-param), func, (param-list); + call{.uni} func, (param-list); + call{.uni} func; + + // indirect call via pointer, with full list of call targets + call{.uni} (ret-param), fptr, (param-list), flist; + call{.uni} fptr, (param-list), flist; + call{.uni} fptr, flist; + + // indirect call via pointer, with no knowledge of call targets + call{.uni} (ret-param), fptr, (param-list), fproto; + call{.uni} fptr, (param-list), fproto; + call{.uni} fptr, fproto; + +Description + +The `call` instruction stores the address of the next instruction, so execution can resume at that point after executing a `ret` instruction. A `call` is assumed to be divergent unless the `.uni` suffix is present. The `.uni` suffix indicates that the `call` is guaranteed to be non-divergent, i.e. all active threads in a warp that are currently executing this instruction have identical values for the guard predicate and `call` target. + +For direct calls, the called location `func` must be a symbolic function name; for indirect calls, the called location `fptr` must be an address of a function held in a register. Input arguments and return values are optional. Arguments may be registers, immediate constants, or variables in `.param` space. Arguments are pass-by-value. + +Indirect calls require an additional operand, `flist` or `fproto`, to communicate the list of potential `call` targets or the common function prototype of all `call` targets, respectively. In the first case, `flist` gives a complete list of potential `call` targets and the optimizing backend is free to optimize the calling convention. In the second case, where the complete list of potential `call` targets may not be known, the common function prototype is given and the `call` must obey the ABI’s calling convention. + +The `flist` operand is either the name of an array (call table) initialized to a list of function names; or a label associated with a `.calltargets` directive, which declares a list of potential `call` targets. In both cases the fptr register holds the address of a function listed in the call table or `.calltargets` list, and the `call` operands are type-checked against the type signature of the functions indicated by `flist`. + +The fproto operand is the name of a label associated with a `.callprototype` directive. This operand is used when a complete list of potential targets is not known. The `call` operands are type-checked against the prototype, and code generation will follow the ABI calling convention. If a function that doesn’t match the prototype is called, the behavior is undefined. + +Call tables may be declared at module scope or local scope, in either the constant or global state space. The `.calltargets` and `.callprototype` directives must be declared within a function body. All functions must be declared prior to being referenced in a `call` table initializer or `.calltargets` directive. + +PTX ISA Notes + +Direct `call` introduced in PTX ISA version 1.0. Indirect `call` introduced in PTX ISA version 2.1. + +Target ISA Notes + +Direct `call` supported on all target architectures. Indirect `call` requires `sm_20` or higher. + +Examples + +// examples of direct call + call init; // call function 'init' + call.uni g, (a); // call function 'g' with parameter 'a' + @p call (d), h, (a, b); // return value into register d + + // call-via-pointer using jump table + .func (.reg .u32 rv) foo (.reg .u32 a, .reg .u32 b) ... + .func (.reg .u32 rv) bar (.reg .u32 a, .reg .u32 b) ... + .func (.reg .u32 rv) baz (.reg .u32 a, .reg .u32 b) ... + + .global .u32 jmptbl[5] = { foo, bar, baz }; + ... + @p ld.global.u32 %r0, [jmptbl+4]; + @p ld.global.u32 %r0, [jmptbl+8]; + call (retval), %r0, (x, y), jmptbl; + + // call-via-pointer using .calltargets directive + .func (.reg .u32 rv) foo (.reg .u32 a, .reg .u32 b) ... + .func (.reg .u32 rv) bar (.reg .u32 a, .reg .u32 b) ... + .func (.reg .u32 rv) baz (.reg .u32 a, .reg .u32 b) ... + ... + @p mov.u32 %r0, foo; + @q mov.u32 %r0, baz; + Ftgt: .calltargets foo, bar, baz; + call (retval), %r0, (x, y), Ftgt; + + // call-via-pointer using .callprototype directive + .func dispatch (.reg .u32 fptr, .reg .u32 idx) + { + ... + Fproto: .callprototype _ (.param .u32 _, .param .u32 _); + call %fptr, (x, y), Fproto; + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-causality-order/DOC.md b/content/cuda/docs/ptx-causality-order/DOC.md new file mode 100644 index 00000000..b3e20be3 --- /dev/null +++ b/content/cuda/docs/ptx-causality-order/DOC.md @@ -0,0 +1,66 @@ +--- +name: ptx-causality-order +description: "_Causality order_ captures how memory operations become visible across\ + \ threads through synchronizing operations. The axiom \u201CCausality\u201D uses\ + \ this order to constrain the set of write operations from whi..." +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.5. Causality Order + +--- +title: "8.9.5. Causality Order" +section: 8.9.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.5. Causality Order + + +_Causality order_ captures how memory operations become visible across threads through synchronizing operations. The axiom “Causality” uses this order to constrain the set of write operations from which a read operation may read a value. + +Relations in the _causality order_ primarily consist of relations in _Base causality order_ 1 , which is a transitive order, determined at runtime. + +Base causality order + +An operation X precedes an operation Y in _base causality order_ if: + +1. X precedes Y in _program order_ , or + + 2. X _synchronizes_ with Y, or + + 3. For some operation Z, + + 1. X precedes Z in _program order_ and Z precedes Y in _base causality order_ , or + + 2. X precedes Z in _base causality order_ and Z precedes Y in _program order_ , or + + 3. X precedes Z in _base causality order_ and Z precedes Y in _base causality order_. + +Proxy-preserved base causality order + +A memory operation X precedes a memory operation Y in _proxy-preserved base causality order_ if X precedes Y in _base causality order_ , and: + +1. X and Y are performed to the same address, using the _generic proxy_ , or + + 2. X and Y are performed to the same address, using the same _proxy_ , and by the same thread block, or + + 3. X and Y are aliases and there is an alias _proxy fence_ along the base causality path from X to Y. + +Causality order + +_Causality order_ combines _base causality order_ with some non-transitive relations as follows: + +An operation X precedes an operation Y in _causality order_ if: + +1. X precedes Y in _proxy-preserved base causality order_ , or + + 2. For some operation Z, X precedes Z in observation order, and Z precedes Y in _proxy-preserved base causality order_. + +1 The transitivity of _base causality order_ accounts for the “cumulativity” of synchronizing operations. \ No newline at end of file diff --git a/content/cuda/docs/ptx-causality/DOC.md b/content/cuda/docs/ptx-causality/DOC.md new file mode 100644 index 00000000..2682ed72 --- /dev/null +++ b/content/cuda/docs/ptx-causality/DOC.md @@ -0,0 +1,113 @@ +--- +name: ptx-causality +description: 'Relations in _communication order_ cannot contradict _causality order_. + This constrains the set of candidate write operations that a read operation may + read from:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.10.6. Causality + +--- +title: "8.10.6. Causality" +section: 8.10.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.10.6. Causality + + +Relations in _communication order_ cannot contradict _causality order_. This constrains the set of candidate write operations that a read operation may read from: + +1. If a read R precedes an _overlapping_ write W in _causality order_ , then R cannot read from W. + + 2. If a write W precedes an _overlapping_ read R in _causality order_ , then for any byte accessed by both R and W, R cannot read from any write W’ that precedes W in _coherence order_. + +Litmus Test: Message Passing + +.global .u32 data = 0; + .global .u32 flag = 0; + + +--- +T1 | T2 + + + W1: st.global.u32 [data], 1; + F1: fence.sys; + W2: st.global.relaxed.sys.u32 [flag], 1; + + +| + + + R1: ld.global.relaxed.sys.u32 %r0, [flag]; + F2: fence.sys; + R2: ld.global.u32 %r1, [data]; + + + + IF %r0 == 1 THEN %r1 == 1 + +The litmus test known as “MP” (Message Passing) represents the essence of typical synchronization algorithms. A vast majority of useful programs can be reduced to sequenced applications of this pattern. + +Thread T1 first writes to a data variable and then to a flag variable while a second thread T2 first reads from the flag variable and then from the data variable. The operations on the flag are _morally strong_ and the memory operations in each thread are separated by a _fence_ , and these _fences_ are _morally strong_. + +If R1 observes W2, then the release pattern “F1; W2” _synchronizes_ with the _acquire pattern_ “R1; F2”. This establishes the _causality order_ W1 -> F1 -> W2 -> R1 -> F2 -> R2. Then axiom _causality_ guarantees that R2 cannot read from any write that precedes W1 in _coherence order_. In the absence of any other writes in this example, R2 must read from W1. + +Litmus Test: CoWR + +// These addresses are aliases + .global .u32 data_alias_1; + .global .u32 data_alias_2; + + +--- +T1 + + + W1: st.global.u32 [data_alias_1], 1; + F1: fence.proxy.alias; + R1: ld.global.u32 %r1, [data_alias_2]; + + + + %r1 == 1 + +Virtual aliases require an alias _proxy fence_ along the synchronization path. + +Litmus Test: Store Buffering + +The litmus test known as “SB” (Store Buffering) demonstrates the _sequential consistency_ enforced by the `fence.sc`. A thread T1 writes to a first variable, and then reads the value of a second variable, while a second thread T2 writes to the second variable and then reads the value of the first variable. The memory operations in each thread are separated by `fence.`sc instructions, and these _fences_ are _morally strong_. + +.global .u32 x = 0; + .global .u32 y = 0; + + +--- +T1 | T2 + + + W1: st.global.u32 [x], 1; + F1: fence.sc.sys; + R1: ld.global.u32 %r0, [y]; + + +| + + + W2: st.global.u32 [y], 1; + F2: fence.sc.sys; + R2: ld.global.u32 %r1, [x]; + + + + %r0 == 1 OR %r1 == 1 + +In any execution, either F1 precedes F2 in _Fence-SC_ order, or vice versa. If F1 precedes F2 in _Fence-SC_ order, then F1 _synchronizes_ with F2. This establishes the _causality order_ in W1 -> F1 -> F2 -> R2. Axiom _causality_ ensures that R2 cannot read from any write that precedes W1 in _coherence order_. In the absence of any other write to that variable, R2 must read from W1. Similarly, in the case where F2 precedes F1 in _Fence-SC_ order, R1 must read from W2. If each `fence.sc` in this example were replaced by a `fence.acq_rel` instruction, then this outcome is not guaranteed. There may be an execution where the write from each thread remains unobserved from the other thread, i.e., an execution is possible, where both R1 and R2 return the initial value “0” for variables y and x respectively. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-from-ptx-isa-version-1x/DOC.md b/content/cuda/docs/ptx-changes-from-ptx-isa-version-1x/DOC.md new file mode 100644 index 00000000..d5fd1d0c --- /dev/null +++ b/content/cuda/docs/ptx-changes-from-ptx-isa-version-1x/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-changes-from-ptx-isa-version-1x +description: In PTX ISA version 1.x, formal parameters were restricted to .reg state + space, and there was no support for array parameters. Objects such as C structures + were flattened and passed or returned using m... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 7.1.1. Changes from PTX ISA Version 1.x + +--- +title: "7.1.1. Changes from PTX ISA Version 1.x" +section: 7.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 7.1.1. Changes from PTX ISA Version 1.x + + +In PTX ISA version 1.x, formal parameters were restricted to .reg state space, and there was no support for array parameters. Objects such as C structures were flattened and passed or returned using multiple registers. PTX ISA version 1.x supports multiple return values for this purpose. + +Beginning with PTX ISA version 2.0, formal parameters may be in either `.reg` or `.param` state space, and `.param` space parameters support arrays. For targets `sm_20` or higher, PTX restricts functions to a single return value, and a `.param` byte array should be used to return objects that do not fit into a register. PTX continues to support multiple return registers for `sm_1x` targets. + +Note + +PTX implements a stack-based ABI only for targets `sm_20` or higher. + +PTX ISA versions prior to 3.0 permitted variables in `.reg` and `.local` state spaces to be defined at module scope. When compiling to use the ABI, PTX ISA version 3.0 and later disallows module-scoped `.reg` and `.local` variables and restricts their use to within function scope. When compiling without use of the ABI, module-scoped `.reg` and `.local` variables are supported as before. When compiling legacy PTX code (ISA versions prior to 3.0) containing module-scoped `.reg` or `.local` variables, the compiler silently disables use of the ABI. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-20/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-20/DOC.md new file mode 100644 index 00000000..3cc3abfe --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-20/DOC.md @@ -0,0 +1,104 @@ +--- +name: ptx-changes-in-ptx-isa-version-20 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.38. Changes in PTX ISA Version 2.0 + +--- +title: "13.38. Changes in PTX ISA Version 2.0" +section: 13.38 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.38. Changes in PTX ISA Version 2.0 + + +New Features + +Floating Point Extensions + +This section describes the floating-point changes in PTX ISA version 2.0 for `sm_20` targets. The goal is to achieve IEEE 754 compliance wherever possible, while maximizing backward compatibility with legacy PTX ISA version 1.x code and `sm_1x` targets. + +The changes from PTX ISA version 1.x are as follows: + +* Single-precision instructions support subnormal numbers by default for `sm_20` targets. The `.ftz` modifier may be used to enforce backward compatibility with `sm_1x`. + + * Single-precision `add`, `sub`, and `mul` now support `.rm` and `.rp` rounding modifiers for `sm_20` targets. + + * A single-precision fused multiply-add (fma) instruction has been added, with support for IEEE 754 compliant rounding modifiers and support for subnormal numbers. The `fma.f32` instruction also supports `.ftz` and `.sat` modifiers. `fma.f32` requires `sm_20`. The `mad.f32` instruction has been extended with rounding modifiers so that it’s synonymous with `fma.f32` for `sm_20` targets. Both `fma.f32` and `mad.f32` require a rounding modifier for `sm_20` targets. + + * The `mad.f32` instruction _without rounding_ is retained so that compilers can generate code for `sm_1x` targets. When code compiled for `sm_1x` is executed on `sm_20` devices, `mad.f32` maps to `fma.rn.f32`. + + * Single- and double-precision `div`, `rcp`, and `sqrt` with IEEE 754 compliant rounding have been added. These are indicated by the use of a rounding modifier and require `sm_20`. + + * Instructions `testp` and `copysign` have been added. + +New Instructions + +A _load uniform_ instruction, `ldu`, has been added. + +Surface instructions support additional `.clamp` modifiers, `.clamp` and `.zero`. + +Instruction `sust` now supports formatted surface stores. + +A _count leading zeros_ instruction, `clz`, has been added. + +A _find leading non-sign bit instruction_ , `bfind`, has been added. + +A _bit reversal_ instruction, `brev`, has been added. + +Bit field extract and insert instructions, `bfe` and `bfi`, have been added. + +A _population count_ instruction, `popc`, has been added. + +A _vote ballot_ instruction, `vote.ballot.b32`, has been added. + +Instructions `{atom,red}.add.f32` have been implemented. + +Instructions `{atom,red}`.shared have been extended to handle 64-bit data types for `sm_20` targets. + +A system-level membar instruction, `membar.sys`, has been added. + +The `bar` instruction has been extended as follows: + +* A `bar.arrive` instruction has been added. + + * Instructions `bar.red.popc.u32` and `bar.red.{and,or}.pred` have been added. + + * `bar` now supports optional thread count and register operands. + +Scalar video instructions (includes `prmt`) have been added. + +Instruction `isspacep` for querying whether a generic address falls within a specified state space window has been added. + +Instruction `cvta` for converting global, local, and shared addresses to generic address and vice-versa has been added. + +Other New Features + +Instructions `ld`, `ldu`, `st`, `prefetch`, `prefetchu`, `isspacep`, `cvta`, `atom`, and `red` now support generic addressing. + +New special registers `%nwarpid`, `%nsmid`, `%clock64`, `%lanemask_{eq,le,lt,ge,gt}` have been added. + +Cache operations have been added to instructions `ld`, `st`, `suld`, and `sust`, e.g., for `prefetching` to specified level of memory hierarchy. Instructions `prefetch` and `prefetchu` have also been added. + +The `.maxnctapersm` directive was deprecated and replaced with `.minnctapersm` to better match its behavior and usage. + +A new directive, `.section`, has been added to replace the `@@DWARF` syntax for passing DWARF-format debugging information through PTX. + +A new directive, `.pragma nounroll`, has been added to allow users to disable loop unrolling. + +Semantic Changes and Clarifications + +The errata in `cvt.ftz` for PTX ISA versions 1.4 and earlier, where single-precision subnormal inputs and results were not flushed to zero if either source or destination type size was 64-bits, has been fixed. In PTX ISA version 1.5 and later, `cvt.ftz` (and `cvt` for `.target sm_1x`, where `.ftz` is implied) instructions flush single-precision subnormal inputs and results to sign-preserving zero for all combinations of floating-point instruction types. To maintain compatibility with legacy PTX code, if .version is 1.4 or earlier, single-precision subnormal inputs and results are flushed to sign-preserving zero only when neither source nor destination type size is 64-bits. + +Components of special registers `%tid`, `%ntid`, `%ctaid`, and `%nctaid` have been extended from 16-bits to 32-bits. These registers now have type `.v4.u32`. + +The number of samplers available in independent texturing mode was incorrectly listed as thirty-two in PTX ISA version 1.5; the correct number is sixteen. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-21/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-21/DOC.md new file mode 100644 index 00000000..5502e702 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-21/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-changes-in-ptx-isa-version-21 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.37. Changes in PTX ISA Version 2.1 + +--- +title: "13.37. Changes in PTX ISA Version 2.1" +section: 13.37 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.37. Changes in PTX ISA Version 2.1 + + +New Features + +The underlying, stack-based ABI is supported in PTX ISA version 2.1 for `sm_2x` targets. + +Support for indirect calls has been implemented for `sm_2x` targets. + +New directives, `.branchtargets` and `.calltargets`, have been added for specifying potential targets for indirect branches and indirect function calls. A `.callprototype` directive has been added for declaring the type signatures for indirect function calls. + +The names of `.global` and `.const` variables can now be specified in variable initializers to represent their addresses. + +A set of thirty-two driver-specific execution environment special registers has been added. These are named `%envreg0..%envreg31`. + +Textures and surfaces have new fields for channel data type and channel order, and the `txq` and `suq` instructions support queries for these fields. + +Directive `.minnctapersm` has replaced the `.maxnctapersm` directive. + +Directive `.reqntid` has been added to allow specification of exact CTA dimensions. + +A new instruction, `rcp.approx.ftz.f64`, has been added to compute a fast, gross approximate reciprocal. + +Semantic Changes and Clarifications + +A warning is emitted if `.minnctapersm` is specified without also specifying `.maxntid`. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-22/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-22/DOC.md new file mode 100644 index 00000000..67d7d478 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-22/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-changes-in-ptx-isa-version-22 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.36. Changes in PTX ISA Version 2.2 + +--- +title: "13.36. Changes in PTX ISA Version 2.2" +section: 13.36 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.36. Changes in PTX ISA Version 2.2 + + +New Features + +PTX 2.2 adds a new directive for specifying kernel parameter attributes; specifically, there is a new directives for specifying that a kernel parameter is a pointer, for specifying to which state space the parameter points, and for optionally specifying the alignment of the memory to which the parameter points. + +PTX 2.2 adds a new field named `force_unnormalized_coords` to the `.samplerref` opaque type. This field is used in the independent texturing mode to override the `normalized_coords` field in the texture header. This field is needed to support languages such as OpenCL, which represent the property of normalized/unnormalized coordinates in the sampler header rather than in the texture header. + +PTX 2.2 deprecates explicit constant banks and supports a large, flat address space for the `.const` state space. Legacy PTX that uses explicit constant banks is still supported. + +PTX 2.2 adds a new `tld4` instruction for loading a component (`r`, `g`, `b`, or `a`) from the four texels compising the bilinear interpolation footprint of a given texture location. This instruction may be used to compute higher-precision bilerp results in software, or for performing higher-bandwidth texture loads. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-23/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-23/DOC.md new file mode 100644 index 00000000..ba9b90ef --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-23/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-changes-in-ptx-isa-version-23 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.35. Changes in PTX ISA Version 2.3 + +--- +title: "13.35. Changes in PTX ISA Version 2.3" +section: 13.35 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.35. Changes in PTX ISA Version 2.3 + + +New Features + +PTX 2.3 adds support for texture arrays. The texture array feature supports access to an array of 1D or 2D textures, where an integer indexes into the array of textures, and then one or two single-precision floating point coordinates are used to address within the selected 1D or 2D texture. + +PTX 2.3 adds a new directive, `.address_size`, for specifying the size of addresses. + +Variables in `.const` and `.global` state spaces are initialized to zero by default. + +Semantic Changes and Clarifications + +The semantics of the `.maxntid` directive have been updated to match the current implementation. Specifically, `.maxntid` only guarantees that the total number of threads in a thread block does not exceed the maximum. Previously, the semantics indicated that the maximum was enforced separately in each dimension, which is not the case. + +Bit field extract and insert instructions BFE and BFI now indicate that the `len` and `pos` operands are restricted to the value range `0..255`. + +Unimplemented instructions `{atom,red}.{min,max}.f32` have been removed. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-30/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-30/DOC.md new file mode 100644 index 00000000..2bce9dc4 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-30/DOC.md @@ -0,0 +1,56 @@ +--- +name: ptx-changes-in-ptx-isa-version-30 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.34. Changes in PTX ISA Version 3.0 + +--- +title: "13.34. Changes in PTX ISA Version 3.0" +section: 13.34 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.34. Changes in PTX ISA Version 3.0 + + +New Features + +PTX ISA version 3.0 introduces the following new features: + +* Support for `sm_30` target architectures. + + * SIMD video instructions. + + * A new warp shuffle instruction. + + * Instructions `mad.cc` and `madc` for efficient, extended-precision integer multiplication. + + * Surface instructions with 3D and array geometries. + + * The texture instruction supports reads from cubemap and cubemap array textures. + + * Platform option `.target` debug to declare that a PTX module contains `DWARF` debug information. + + * `pmevent.mask`, for triggering multiple performance monitor events. + + * Performance monitor counter special registers `%pm4..%pm7`. + +Semantic Changes and Clarifications + +Special register `%gridid` has been extended from 32-bits to 64-bits. + +PTX ISA version 3.0 deprecates module-scoped `.reg` and `.local` variables when compiling to the Application Binary Interface (ABI). When compiling without use of the ABI, module-scoped `.reg` and `.local` variables are supported as before. When compiling legacy PTX code (ISA versions prior to 3.0) containing module-scoped `.reg` or `.local` variables, the compiler silently disables use of the ABI. + +The `shfl` instruction semantics were updated to clearly indicate that value of source operand `a` is unpredictable for inactive and predicated-off threads within the warp. + +PTX modules no longer allow duplicate `.version` directives. This feature was unimplemented, so there is no semantic change. + +Unimplemented instructions `suld.p` and `sust.p.{u32,s32,f32}` have been removed. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-31/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-31/DOC.md new file mode 100644 index 00000000..ab79967d --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-31/DOC.md @@ -0,0 +1,50 @@ +--- +name: ptx-changes-in-ptx-isa-version-31 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.33. Changes in PTX ISA Version 3.1 + +--- +title: "13.33. Changes in PTX ISA Version 3.1" +section: 13.33 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.33. Changes in PTX ISA Version 3.1 + + +New Features + +PTX ISA version 3.1 introduces the following new features: + +* Support for `sm_35` target architecture. + + * Support for CUDA Dynamic Parallelism, which enables a kernel to create and synchronize new work. + + * `ld.global.nc` for loading read-only global data though the non-coherent texture cache. + + * A new funnel shift instruction, `shf`. + + * Extends atomic and reduction instructions to perform 64-bit `{and, or, xor}` operations, and 64-bit integer `{min, max}` operations. + + * Adds support for `mipmaps`. + + * Adds support for indirect access to textures and surfaces. + + * Extends support for generic addressing to include the `.const` state space, and adds a new operator, `generic()`, to form a generic address for `.global` or `.const` variables used in initializers. + + * A new `.weak` directive to permit linking multiple object files containing declarations of the same symbol. + +Semantic Changes and Clarifications + +PTX 3.1 redefines the default addressing for global variables in initializers, from generic addresses to offsets in the global state space. Legacy PTX code is treated as having an implicit `generic()` operator for each global variable used in an initializer. PTX 3.1 code should either include explicit `generic()` operators in initializers, use `cvta.global` to form generic addresses at runtime, or load from the non-generic address using `ld.global`. + +Instruction `mad.f32` requires a rounding modifier for `sm_20` and higher targets. However for PTX ISA version 3.0 and earlier, ptxas does not enforce this requirement and `mad.f32` silently defaults to `mad.rn.f32`. For PTX ISA version 3.1, ptxas generates a warning and defaults to `mad.rn.f32`, and in subsequent releases ptxas will enforce the requirement for PTX ISA version 3.2 and later. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-32/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-32/DOC.md new file mode 100644 index 00000000..e8891fce --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-32/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-changes-in-ptx-isa-version-32 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.32. Changes in PTX ISA Version 3.2 + +--- +title: "13.32. Changes in PTX ISA Version 3.2" +section: 13.32 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.32. Changes in PTX ISA Version 3.2 + + +New Features + +PTX ISA version 3.2 introduces the following new features: + +* The texture instruction supports reads from multi-sample and multisample array textures. + + * Extends `.section` debugging directive to include label + immediate expressions. + + * Extends `.file` directive to include timestamp and file size information. + +Semantic Changes and Clarifications + +The `vavrg2` and `vavrg4` instruction semantics were updated to indicate that instruction adds 1 only if Va[i] + Vb[i] is non-negative, and that the addition result is shifted by 1 (rather than being divided by 2). \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-40/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-40/DOC.md new file mode 100644 index 00000000..e2613eb7 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-40/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-40 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.31. Changes in PTX ISA Version 4.0 + +--- +title: "13.31. Changes in PTX ISA Version 4.0" +section: 13.31 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.31. Changes in PTX ISA Version 4.0 + + +New Features + +PTX ISA version 4.0 introduces the following new features: + +* Support for `sm_32` and `sm_50` target architectures. + + * Support for 64bit performance counter special registers `%pm0_64,..,%pm7_64`. + + * A new `istypep` instruction. + + * A new instruction, `rsqrt.approx.ftz.f64` has been added to compute a fast approximation of the square root reciprocal of a value. + + * Support for a new directive `.attribute` for specifying special attributes of a variable. + + * Support for `.managed` variable attribute. + +Semantic Changes and Clarifications + +The `vote` instruction semantics were updated to clearly indicate that an inactive thread in a warp contributes a 0 for its entry when participating in `vote.ballot.b32`. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-41/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-41/DOC.md new file mode 100644 index 00000000..785752fa --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-41/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-changes-in-ptx-isa-version-41 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.30. Changes in PTX ISA Version 4.1 + +--- +title: "13.30. Changes in PTX ISA Version 4.1" +section: 13.30 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.30. Changes in PTX ISA Version 4.1 + + +New Features + +PTX ISA version 4.1 introduces the following new features: + +* Support for `sm_37` and `sm_52` target architectures. + + * Support for new fields `array_size`, `num_mipmap_levels` and `num_samples` for Textures, and the `txq` instruction support for querying these fields. + + * Support for new field `array_size` for Surfaces, and the `suq` instruction support for querying this field. + + * Support for special registers `%total_smem_size` and `%dynamic_smem_size`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-42/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-42/DOC.md new file mode 100644 index 00000000..596203ad --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-42/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-changes-in-ptx-isa-version-42 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.29. Changes in PTX ISA Version 4.2 + +--- +title: "13.29. Changes in PTX ISA Version 4.2" +section: 13.29 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.29. Changes in PTX ISA Version 4.2 + + +New Features + +PTX ISA version 4.2 introduces the following new features: + +* Support for `sm_53` target architecture. + + * Support for arithmetic, comparsion and texture instructions for `.f16` and `.f16x2` types. + + * Support for `memory_layout` field for surfaces and `suq` instruction support for querying this field. + +Semantic Changes and Clarifications + +Semantics for parameter passing under ABI were updated to indicate `ld.param` and `st.param` instructions used for argument passing cannot be predicated. + +Semantics of `{atom/red}.add.f32` were updated to indicate subnormal inputs and results are flushed to sign-preserving zero for atomic operations on global memory; whereas atomic operations on shared memory preserve subnormal inputs and results and don’t flush them to zero. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-43/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-43/DOC.md new file mode 100644 index 00000000..1303ce10 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-43/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-43 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.28. Changes in PTX ISA Version 4.3 + +--- +title: "13.28. Changes in PTX ISA Version 4.3" +section: 13.28 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.28. Changes in PTX ISA Version 4.3 + + +New Features + +PTX ISA version 4.3 introduces the following new features: + +* A new `lop3` instruction which allows arbitrary logical operation on 3 inputs. + + * Adds support for 64-bit computations in extended precision arithmetic instructions. + + * Extends `tex.grad` instruction to support `cube` and `acube` geometries. + + * Extends `tld4` instruction to support `a2d`, `cube` and `acube` geometries. + + * Extends `tex` and `tld4` instructions to support optional operands for offset vector and depth compare. + + * Extends `txq` instruction to support querying texture fields from specific LOD. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-50/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-50/DOC.md new file mode 100644 index 00000000..dff75fd7 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-50/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-changes-in-ptx-isa-version-50 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.27. Changes in PTX ISA Version 5.0 + +--- +title: "13.27. Changes in PTX ISA Version 5.0" +section: 13.27 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.27. Changes in PTX ISA Version 5.0 + + +New Features + +PTX ISA version 5.0 introduces the following new features: + +* Support for `sm_60`, `sm_61`, `sm_62` target architecture. + + * Extends atomic and reduction instructions to perform double-precision add operation. + + * Extends atomic and reduction instructions to specify `scope` modifier. + + * A new `.common` directive to permit linking multiple object files containing declarations of the same symbol with different size. + + * A new `dp4a` instruction which allows 4-way dot product with accumulate operation. + + * A new `dp2a` instruction which allows 2-way dot product with accumulate operation. + + * Support for special register `%clock_hi`. + +Semantic Changes and Clarifications + +Semantics of cache modifiers on `ld` and `st` instructions were clarified to reflect cache operations are treated as performance hint only and do not change memory consistency behavior of the program. + +Semantics of `volatile` operations on `ld` and `st` instructions were clarified to reflect how `volatile` operations are handled by optimizing compiler. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-60/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-60/DOC.md new file mode 100644 index 00000000..956e323f --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-60/DOC.md @@ -0,0 +1,64 @@ +--- +name: ptx-changes-in-ptx-isa-version-60 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.26. Changes in PTX ISA Version 6.0 + +--- +title: "13.26. Changes in PTX ISA Version 6.0" +section: 13.26 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.26. Changes in PTX ISA Version 6.0 + + +New Features + +PTX ISA version 6.0 introduces the following new features: + +* Support for `sm_70` target architecture. + + * Specifies the memory consistency model for programs running on `sm_70` and later architectures. + + * Various extensions to memory instructions to specify memory synchronization semantics and scopes at which such synchronization can be observed. + + * New instruction `wmma` for matrix operations which allows loading matrices from memory, performing multiply-and-accumulate on them and storing result in memory. + + * Support for new `barrier` instruction. + + * Extends `neg` instruction to support `.f16` and `.f16x2` types. + + * A new instruction `fns` which allows finding n-th set bit in integer. + + * A new instruction `bar.warp.sync` which allows synchronizing threads in warp. + + * Extends `vote` and `shfl` instructions with `.sync` modifier which waits for specified threads before executing the `vote` and `shfl` operation respectively. + + * A new instruction `match.sync` which allows broadcasting and comparing a value across threads in warp. + + * A new instruction `brx.idx` which allows branching to a label indexed from list of potential targets. + + * Support for unsized array parameter for `.func` which can be used to implement variadic functions. + + * Support for `.b16` integer type in dwarf-lines. + + * Support for taking address of device function return parameters using `mov` instruction. + +Semantic Changes and Clarifications + +* Semantics of `bar` instruction were updated to indicate that executing thread waits for other non-exited threads from it’s warp. + + * Support for indirect branch introduced in PTX 2.1 which was unimplemented has been removed from the spec. + + * Support for taking address of labels, using labels in initializers which was unimplemented has been removed from the spec. + + * Support for variadic functions which was unimplemented has been removed from the spec. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-61/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-61/DOC.md new file mode 100644 index 00000000..5b87bd6f --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-61/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-changes-in-ptx-isa-version-61 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.25. Changes in PTX ISA Version 6.1 + +--- +title: "13.25. Changes in PTX ISA Version 6.1" +section: 13.25 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.25. Changes in PTX ISA Version 6.1 + + +New Features + +PTX ISA version 6.1 introduces the following new features: + +* Support for `sm_72` target architecture. + + * Support for new matrix shapes `32x8x16` and `8x32x16` in `wmma` instruction. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-62/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-62/DOC.md new file mode 100644 index 00000000..db3ef078 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-62/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-62 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.24. Changes in PTX ISA Version 6.2 + +--- +title: "13.24. Changes in PTX ISA Version 6.2" +section: 13.24 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.24. Changes in PTX ISA Version 6.2 + + +New Features + +PTX ISA version 6.2 introduces the following new features: + +* A new instruction `activemask` for querying active threads in a warp. + + * Extends atomic and reduction instructions to perform `.f16x2` addition operation with mandatory `.noftz` qualifier. + +Deprecated Features + +PTX ISA version 6.2 deprecates the following features: + +* The use of `shfl` and `vote` instructions without the `.sync` is deprecated retrospectively from PTX ISA version 6.0, which introduced the `sm_70` architecture that implements [Independent Thread Scheduling](<#independent-thread-scheduling>). + +Semantic Changes and Clarifications + +* Clarified that `wmma` instructions can be used in conditionally executed code only if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + + * In the memory consistency model, the definition of _morally strong operations_ was updated to exclude fences from the requirement of _complete overlap_ since fences do not access memory. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-63/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-63/DOC.md new file mode 100644 index 00000000..b447922a --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-63/DOC.md @@ -0,0 +1,48 @@ +--- +name: ptx-changes-in-ptx-isa-version-63 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.23. Changes in PTX ISA Version 6.3 + +--- +title: "13.23. Changes in PTX ISA Version 6.3" +section: 13.23 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.23. Changes in PTX ISA Version 6.3 + + +New Features + +PTX ISA version 6.3 introduces the following new features: + +* Support for `sm_75` target architecture. + + * Adds support for a new instruction `nanosleep` that suspends a thread for a specified duration. + + * Adds support for `.alias` directive which allows definining alias to function symbol. + + * Extends `atom` instruction to perform `.f16` addition operation and `.cas.b16` operation. + + * Extends `red` instruction to perform `.f16` addition operation. + + * The `wmma` instructions are extended to support multiplicand matrices of type `.s8`, `.u8`, `.s4`, `.u4`, `.b1` and accumulator matrices of type `.s32`. + +Semantic Changes and Clarifications + +* Introduced the mandatory `.aligned` qualifier for all `wmma` instructions. + + * Specified the alignment required for the base address and stride parameters passed to `wmma.load` and `wmma.store`. + + * Clarified that layout of fragment returned by `wmma` operation is architecture dependent and passing `wmma` fragments around functions compiled for different link compatible SM architectures may not work as expected. + + * Clarified that atomicity for `{atom/red}.f16x2}` operations is guranteed separately for each of the two `.f16` elements but not guranteed to be atomic as single 32-bit access. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-64/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-64/DOC.md new file mode 100644 index 00000000..26001797 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-64/DOC.md @@ -0,0 +1,48 @@ +--- +name: ptx-changes-in-ptx-isa-version-64 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.22. Changes in PTX ISA Version 6.4 + +--- +title: "13.22. Changes in PTX ISA Version 6.4" +section: 13.22 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.22. Changes in PTX ISA Version 6.4 + + +New Features + +PTX ISA version 6.4 introduces the following new features: + +* Adds support for `.noreturn` directive which can be used to indicate a function does not return to it’s caller function. + + * Adds support for `mma` instruction which allows performing matrix multiply-and-accumulate operation. + +Deprecated Features + +PTX ISA version 6.4 deprecates the following features: + +* Support for `.satfinite` qualifier on floating point `wmma.mma` instruction. + +Removed Features + +PTX ISA version 6.4 removes the following features: + +* Support for `shfl` and `vote` instructions without the `.sync` qualifier has been removed for `.target``sm_70` and higher. This support was deprecated since PTX ISA version 6.0 as documented in PTX ISA version 6.2. + +Semantic Changes and Clarifications + +* Clarified that resolving references of a `.weak` symbol considers only `.weak` or `.visible` symbols with the same name and does not consider local symbols with the same name. + + * Clarified that in `cvt` instruction, modifier `.ftz` can only be specified when either `.atype` or `.dtype` is `.f32`. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-65/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-65/DOC.md new file mode 100644 index 00000000..67f579a8 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-65/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-changes-in-ptx-isa-version-65 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.21. Changes in PTX ISA Version 6.5 + +--- +title: "13.21. Changes in PTX ISA Version 6.5" +section: 13.21 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.21. Changes in PTX ISA Version 6.5 + + +New Features + +PTX ISA version 6.5 introduces the following new features: + +* Adds support for integer destination types for half precision comparison instruction `set`. + + * Extends `abs` instruction to support `.f16` and `.f16x2` types. + + * Adds support for `cvt.pack` instruction which allows converting two integer values and packing the results together. + + * Adds new shapes `.m16n8k8`, `.m8n8k16` and `.m8n8k32` on the `mma` instruction. + + * Adds support for `ldmatrix` instruction which loads one or more matrices from shared memory for `mma` instruction. + +Removed Features + +PTX ISA version 6.5 removes the following features: + +* Support for `.satfinite` qualifier on floating point `wmma.mma` instruction has been removed. This support was deprecated since PTX ISA version 6.4. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-70/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-70/DOC.md new file mode 100644 index 00000000..02d977ec --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-70/DOC.md @@ -0,0 +1,64 @@ +--- +name: ptx-changes-in-ptx-isa-version-70 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.20. Changes in PTX ISA Version 7.0 + +--- +title: "13.20. Changes in PTX ISA Version 7.0" +section: 13.20 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.20. Changes in PTX ISA Version 7.0 + + +New Features + +PTX ISA version 7.0 introduces the following new features: + +* Support for `sm_80` target architecture. + + * Adds support for asynchronous copy instructions that allow copying of data asynchronously from one state space to another. + + * Adds support for `mbarrier` instructions that allow creation of _mbarrier objects_ in memory and use of these objects to synchronize threads and asynchronous copy operations initiated by threads. + + * Adds support for `redux.sync` instruction which allows reduction operation across threads in a warp. + + * Adds support for new alternate floating-point data formats `.bf16` and `.tf32`. + + * Extends `wmma` instruction to support `.f64` type with shape `.m8n8k4`. + + * Extends `wmma` instruction to support `.bf16` data format. + + * Extends `wmma` instruction to support `.tf32` data format with shape `.m16n16k8`. + + * Extends `mma` instruction to support `.f64` type with shape `.m8n8k4`. + + * Extends `mma` instruction to support `.bf16` and `.tf32` data formats with shape `.m16n8k8`. + + * Extends `mma` instruction to support new shapes `.m8n8k128`, `.m16n8k4`, `.m16n8k16`, `.m16n8k32`, `.m16n8k64`, `.m16n8k128` and `.m16n8k256`. + + * Extends `abs` and `neg` instructions to support `.bf16` and `.bf16x2` data formats. + + * Extends `min` and `max` instructions to support `.NaN` modifier and `.f16`, `.f16x2`, `.bf16` and `.bf16x2` data formats. + + * Extends `fma` instruction to support `.relu` saturation mode and `.bf16` and `.bf16x2` data formats. + + * Extends `cvt` instruction to support `.relu` saturation mode and `.f16`, `.f16x2`, `.bf16`, `.bf16x2` and `.tf32` destination formats. + + * Adds support for `tanh` instruction that computes hyperbolic-tangent. + + * Extends `ex2` instruction to support `.f16` and `.f16x2` types. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-71/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-71/DOC.md new file mode 100644 index 00000000..6f0889a3 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-71/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-71 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.19. Changes in PTX ISA Version 7.1 + +--- +title: "13.19. Changes in PTX ISA Version 7.1" +section: 13.19 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.19. Changes in PTX ISA Version 7.1 + + +New Features + +PTX ISA version 7.1 introduces the following new features: + +* Support for `sm_86` target architecture. + + * Adds a new operator, `mask()`, to extract a specific byte from variable’s address used in initializers. + + * Extends `tex` and `tld4` instructions to return an optional predicate that indicates if data at specified coordinates is resident in memory. + + * Extends single-bit `wmma` and `mma` instructions to support `.and` operation. + + * Extends `mma` instruction to support `.sp` modifier that allows matrix multiply-accumulate operation when input matrix A is sparse. + + * Extends `mbarrier.test_wait` instruction to test the completion of specific phase parity. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-72/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-72/DOC.md new file mode 100644 index 00000000..2de2c107 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-72/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-changes-in-ptx-isa-version-72 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.18. Changes in PTX ISA Version 7.2 + +--- +title: "13.18. Changes in PTX ISA Version 7.2" +section: 13.18 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.18. Changes in PTX ISA Version 7.2 + + +New Features + +PTX ISA version 7.2 introduces the following new features: + +* Enhances `.loc` directive to represent inline function information. + + * Adds support to define labels inside the debug sections. + + * Extends `min` and `max` instructions to support `.xorsign` and `.abs` modifiers. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-73/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-73/DOC.md new file mode 100644 index 00000000..9aa84dcb --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-73/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-changes-in-ptx-isa-version-73 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.17. Changes in PTX ISA Version 7.3 + +--- +title: "13.17. Changes in PTX ISA Version 7.3" +section: 13.17 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.17. Changes in PTX ISA Version 7.3 + + +New Features + +PTX ISA version 7.3 introduces the following new features: + +* Extends `mask()` operator used in initializers to also support integer constant expression. + + * Adds support for stack manpulation instructions that allow manipulating stack using `stacksave` and `stackrestore` instructions and allocation of per-thread stack using `alloca` instruction. + +Semantic Changes and Clarifications + +The unimplemented version of `alloca` from the older PTX ISA specification has been replaced with new stack manipulation instructions in PTX ISA version 7.3. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-74/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-74/DOC.md new file mode 100644 index 00000000..a442cf5e --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-74/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-74 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.16. Changes in PTX ISA Version 7.4 + +--- +title: "13.16. Changes in PTX ISA Version 7.4" +section: 13.16 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.16. Changes in PTX ISA Version 7.4 + + +New Features + +PTX ISA version 7.4 introduces the following new features: + +* Support for `sm_87` target architecture. + + * Support for `.level::eviction_priority` qualifier which allows specifying cache eviction priority hints on `ld`, `ld.global.nc`, `st`, and `prefetch` instructions. + + * Support for `.level::prefetch_size` qualifier which allows specifying data prefetch hints on `ld` and `cp.async` instructions. + + * Support for `createpolicy` instruction which allows construction of different types of cache eviction policies. + + * Support for `.level::cache_hint` qualifier which allows the use of cache eviction policies with `ld`, `ld.global.nc`, `st`, `atom`, `red` and `cp.async` instructions. + + * Support for `applypriority` and `discard` operations on cached data. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-75/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-75/DOC.md new file mode 100644 index 00000000..32de7def --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-75/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-changes-in-ptx-isa-version-75 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.15. Changes in PTX ISA Version 7.5 + +--- +title: "13.15. Changes in PTX ISA Version 7.5" +section: 13.15 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.15. Changes in PTX ISA Version 7.5 + + +New Features + +PTX ISA version 7.5 introduces the following new features: + +* Debug information enhancements to support label difference and negative values in the `.section` debugging directive. + + * Support for `ignore-src` operand on `cp.async` instruction. + + * Extensions to the memory consistency model to introduce the following new concepts: + +> * A _memory proxy_ as an abstract label for different methods of memory access. +> +> * Virtual aliases as distinct memory addresses accessing the same physical memory location. + + * Support for new `fence.proxy` and `membar.proxy` instructions to allow synchronization of memory accesses performed via virtual aliases. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-76/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-76/DOC.md new file mode 100644 index 00000000..be8b49b2 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-76/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-changes-in-ptx-isa-version-76 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.14. Changes in PTX ISA Version 7.6 + +--- +title: "13.14. Changes in PTX ISA Version 7.6" +section: 13.14 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.14. Changes in PTX ISA Version 7.6 + + +New Features + +PTX ISA version 7.6 introduces the following new features: + +* Support for `szext` instruction which performs sign-extension or zero-extension on a specified value. + + * Support for `bmsk` instruction which creates a bitmask of the specified width starting at the specified bit position. + + * Support for special registers `%reserved_smem_offset_begin`, `%reserved_smem_offset_end`, `%reserved_smem_offset_cap`, `%reserved_smem_offset<2>`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-77/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-77/DOC.md new file mode 100644 index 00000000..86a10e81 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-77/DOC.md @@ -0,0 +1,32 @@ +--- +name: ptx-changes-in-ptx-isa-version-77 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.13. Changes in PTX ISA Version 7.7 + +--- +title: "13.13. Changes in PTX ISA Version 7.7" +section: 13.13 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.13. Changes in PTX ISA Version 7.7 + + +New Features + +PTX ISA version 7.7 introduces the following new features: + +* Extends `isspacep` and `cvta` instructions to include the `.param` state space for kernel function parameters. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-78/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-78/DOC.md new file mode 100644 index 00000000..91f00369 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-78/DOC.md @@ -0,0 +1,76 @@ +--- +name: ptx-changes-in-ptx-isa-version-78 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.12. Changes in PTX ISA Version 7.8 + +--- +title: "13.12. Changes in PTX ISA Version 7.8" +section: 13.12 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.12. Changes in PTX ISA Version 7.8 + + +New Features + +PTX ISA version 7.8 introduces the following new features: + +* Adds support for `sm_89` target architecture. + + * Adds support for `sm_90` target architecture. + + * Extends `bar` and `barrier` instructions to accept optional scope qualifier `.cta`. + + * Extends `.shared` state space qualifier with optional sub-qualifier `::cta`. + + * Adds support for `movmatrix` instruction which transposes a matrix in registers across a warp. + + * Adds support for `stmatrix` instruction which stores one or more matrices to shared memory. + + * Extends the `.f64` floating point type `mma` operation with shapes `.m16n8k4`, `.m16n8k8`, and `.m16n8k16`. + + * Extends `add`, `sub`, `mul`, `set`, `setp`, `cvt`, `tanh`, `ex2`, `atom` and `red` instructions with `bf16` alternate floating point data format. + + * Adds support for new alternate floating-point data formats `.e4m3` and `.e5m2`. + + * Extends `cvt` instruction to convert `.e4m3` and `.e5m2` alternate floating point data formats. + + * Adds support for `griddepcontrol` instruction as a communication mechanism to control the execution of dependent grids. + + * Extends `mbarrier` instruction to allow a new phase completion check operation _try_wait_. + + * Adds support for new thread scope `.cluster` which is a set of Cooperative Thread Arrays (CTAs). + + * Extends `fence`/`membar`, `ld`, `st`, `atom`, and `red` instructions to accept `.cluster` scope. + + * Adds support for extended visibility of shared state space to all threads within a cluster. + + * Extends `.shared` state space qualifier with `::cluster` sub-qualifier for cluster-level visibility of shared memory. + + * Extends `isspacep`, `cvta`, `ld`, `st`, `atom`, and `red` instructions to accept `::cluster` sub-qualifier with `.shared` state space qualifier. + + * Adds support for `mapa` instruction to map a shared memory address to the corresponding address in a different CTA within the cluster. + + * Adds support for `getctarank` instruction to query the rank of the CTA that contains a given address. + + * Adds support for new barrier synchronization instruction `barrier.cluster`. + + * Extends the memory consistency model to include the new cluster scope. + + * Adds support for special registers related to cluster information: `%is_explicit_cluster`, `%clusterid`, `%nclusterid`, `%cluster_ctaid`, `%cluster_nctaid`, `%cluster_ctarank`, `%cluster_nctarank`. + + * Adds support for cluster dimension directives `.reqnctapercluster`, `.explicitcluster`, and `.maxclusterrank`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-80/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-80/DOC.md new file mode 100644 index 00000000..8ad274dd --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-80/DOC.md @@ -0,0 +1,58 @@ +--- +name: ptx-changes-in-ptx-isa-version-80 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.11. Changes in PTX ISA Version 8.0 + +--- +title: "13.11. Changes in PTX ISA Version 8.0" +section: 13.11 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.11. Changes in PTX ISA Version 8.0 + + +New Features + +PTX ISA version 8.0 introduces the following new features: + +* Adds support for target `sm_90a` that supports architecture-specific features. + + * Adds support for asynchronous warpgroup-level matrix multiply-and-accumulate operation `wgmma`. + + * Extends the asynchronous copy operations with bulk operations that operate on large data, including tensor data. + + * Introduces packed integer types `.u16x2` and `.s16x2`. + + * Extends integer arithmetic instruction `add` to allow packed integer types `.u16x2` and `.s16x2`. + + * Extends integer arithmetic instructions `min` and `max` to allow packed integer types `.u16x2` and `.s16x2`, as well as saturation modifier `.relu` on `.s16x2` and `.s32` types. + + * Adds support for special register `%current_graph_exec` that identifies the currently executing CUDA device graph. + + * Adds support for `elect.sync` instruction. + + * Adds support for `.unified` attribute on functions and variables. + + * Adds support for `setmaxnreg` instruction. + + * Adds support for `.sem` qualifier on `barrier.cluster` instruction. + + * Extends the `fence` instruction to allow opcode-specific synchronizaion using `op_restrict` qualifier. + + * Adds support for `.cluster` scope on `mbarrier.arrive`, `mbarrier.arrive_drop`, `mbarrier.test_wait` and `mbarrier.try_wait` operations. + + * Adds support for transaction count operations on `mbarrier` objects, specified with `.expect_tx` and `.complete_tx` qualifiers. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-81/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-81/DOC.md new file mode 100644 index 00000000..f9b8ea57 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-81/DOC.md @@ -0,0 +1,50 @@ +--- +name: ptx-changes-in-ptx-isa-version-81 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.10. Changes in PTX ISA Version 8.1 + +--- +title: "13.10. Changes in PTX ISA Version 8.1" +section: 13.10 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.10. Changes in PTX ISA Version 8.1 + + +New Features + +PTX ISA version 8.1 introduces the following new features: + +* Adds support for `st.async` and `red.async` instructions for asynchronous store and asynchronous reduction operations respectively on shared memory. + + * Adds support for `.oob` modifier on half-precision `fma` instruction. + + * Adds support for `.satfinite` saturation modifer on `cvt` instruction for `.f16`, `.bf16` and `.tf32` formats. + + * Extends support for `cvt` with `.e4m3`/`.e5m2` to `sm_89`. + + * Extends `atom` and `red` instructions to support vector types. + + * Adds support for special register `%aggr_smem_size`. + + * Extends `sured` instruction with 64-bit `min`/`max` operations. + + * Adds support for increased kernel parameter size of 32764 bytes. + + * Adds support for multimem addresses in memory consistency model. + + * Adds support for `multimem.ld_reduce`, `multimem.st` and `multimem.red` instructions to perform memory operations on multimem addresses. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-82/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-82/DOC.md new file mode 100644 index 00000000..5cc45020 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-82/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-changes-in-ptx-isa-version-82 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.9. Changes in PTX ISA Version 8.2 + +--- +title: "13.9. Changes in PTX ISA Version 8.2" +section: 13.9 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.9. Changes in PTX ISA Version 8.2 + + +New Features + +PTX ISA version 8.2 introduces the following new features: + +* Adds support for `.mmio` qualifier on `ld` and `st` instructions. + + * Extends `lop3` instruction to allow predicate destination. + + * Extends `multimem.ld_reduce` instruction to support `.acc::f32` qualifer to allow `.f32` precision of the intermediate accumulation. + + * Extends the asynchronous warpgroup-level matrix multiply-and-accumulate operation `wgmma.mma_async` to support `.sp` modifier that allows matrix multiply-accumulate operation when input matrix A is sparse. + +Semantic Changes and Clarifications + +The `.multicast::cluster` qualifier on `cp.async.bulk` and `cp.async.bulk.tensor` instructions is optimized for target architecture `sm_90a` and may have substantially reduced performance on other targets and hence `.multicast::cluster` is advised to be used with `sm_90a`. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-83/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-83/DOC.md new file mode 100644 index 00000000..d231ba52 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-83/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-changes-in-ptx-isa-version-83 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.8. Changes in PTX ISA Version 8.3 + +--- +title: "13.8. Changes in PTX ISA Version 8.3" +section: 13.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.8. Changes in PTX ISA Version 8.3 + + +New Features + +PTX ISA version 8.3 introduces the following new features: + +* Adds support for pragma `used_bytes_mask` that is used to specify mask for used bytes for a load operation. + + * Extends `isspacep`, `cvta.to`, `ld` and `st` instructions to accept `::entry` and `::func` sub-qualifiers with `.param` state space qualifier. + + * Adds support for `.b128` type on instructions `ld`, `ld.global.nc`, `ldu`, `st`, `mov` and `atom`. + + * Add support for instructions `tensormap.replace`, `tensormap.cp_fenceproxy` and support for qualifier `.to_proxykind::from_proxykind` on instruction `fence.proxy` to support modifying `tensor-map`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-84/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-84/DOC.md new file mode 100644 index 00000000..43e1e5c3 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-84/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-changes-in-ptx-isa-version-84 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.7. Changes in PTX ISA Version 8.4 + +--- +title: "13.7. Changes in PTX ISA Version 8.4" +section: 13.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.7. Changes in PTX ISA Version 8.4 + + +New Features + +PTX ISA version 8.4 introduces the following new features: + +* Extends `ld`, `st` and `atom` instructions with `.b128` type to support `.sys` scope. + + * Extends integer `wgmma.mma_async` instruction to support `.u8.s8` and `.s8.u8` as `.atype` and `.btype` respectively. + + * Extends `mma`, `mma.sp` instructions to support FP8 types `.e4m3` and `.e5m2`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-85/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-85/DOC.md new file mode 100644 index 00000000..abfa5c3a --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-85/DOC.md @@ -0,0 +1,32 @@ +--- +name: ptx-changes-in-ptx-isa-version-85 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.6. Changes in PTX ISA Version 8.5 + +--- +title: "13.6. Changes in PTX ISA Version 8.5" +section: 13.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.6. Changes in PTX ISA Version 8.5 + + +New Features + +PTX ISA version 8.5 introduces the following new features: + +* Adds support for `mma.sp::ordered_metadata` instruction. + +Semantic Changes and Clarifications + +* Values `0b0000`, `0b0101`, `0b1010`, `0b1111` for sparsity metadata (operand `e`) of instruction `mma.sp` are invalid and their usage results in undefined behavior. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-86/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-86/DOC.md new file mode 100644 index 00000000..b02d12a4 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-86/DOC.md @@ -0,0 +1,80 @@ +--- +name: ptx-changes-in-ptx-isa-version-86 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.5. Changes in PTX ISA Version 8.6 + +--- +title: "13.5. Changes in PTX ISA Version 8.6" +section: 13.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.5. Changes in PTX ISA Version 8.6 + + +New Features + +PTX ISA version 8.6 introduces the following new features: + +* Adds support for `sm_100` target architecture. + + * Adds support for target `sm_100a` that supports architecture-specific features. + + * Adds support for `sm_101` target architecture. + + * Adds support for target `sm_101a` that supports architecture-specific features. + + * Extends `cp.async.bulk` and `cp.async.bulk.tensor` instructions to add `.shared::cta` as destination state space. + + * Extends `fence` instruction to add support for `.acquire` and `.release` qualifiers. + + * Extends `fence` and `fence.proxy` instructions to add support for `.sync_restrict` qualifier. + + * Extends `ldmatrix` instruction to support `.m16n16`, `.m8n16` shapes and `.b8` type. + + * Extends `ldmatrix` instruction to support `.src_fmt`, `.dst_fmt` qualifiers. + + * Extends `stmatrix` instruction to support `.m16n8` shape and `.b8` type. + + * Adds support for `clusterlaunchcontrol` instruction. + + * Extends `add`, `sub` and `fma` instructions to support mixed precision floating point operations with `.f32` as destaination operand type and `.f16`/`.bf16` as source operand types. + + * Extends `add`, `sub`, `mul` and `fma` instructions to support `.f32x2` type. + + * Extends `cvt` instruction with `.tf32` type to support `.satfinite` qualifier for `.rn`/`.rz` rounding modes. + + * Extends `cp.async.bulk` instruction to support `.cp_mask` qualifier and `byteMask` operand. + + * Extends `multimem.ld_reduce` and `multimem.st` instructions to support `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2` and `.e4m3x4` types. + + * Extends `cvt` instruction to support conversions to/from `.e2m1x2`, `.e3m2x2`, `.e2m3x2` and `.ue8m0x2` types. + + * Extends `cp.async.bulk.tensor` and `cp.async.bulk.prefetch.tensor` instructions to support new load_mode qualifiers `.tile::scatter4` and `.tile::gather4`. + + * Extends `tensormap.replace` instruction to add support for new qualifier `.swizzle_atomicity` for supporting new swizzle modes. + + * Extends `mbarrier.arrive`, `mbarrier.arrive_drop`, `.mbarrier.test_wait` and `.mbarrier.try_wait` instructions to support `.relaxed` qualifier. + + * Extends `cp.async.bulk.tensor` and `cp.async.bulk.prefetch.tensor` instructions to support new load_mode qualifiers `.im2col::w` and `.im2col::w::128`. + + * Extends `cp.async.bulk.tensor` instruction to support new qualifier `.cta_group`. + + * Add support for `st.bulk` instruction. + + * Adds support for tcgen05 features and related instructions: `tcgen05.alloc`, `tcgen05.dealloc`, `tcgen05.relinquish_alloc_permit`, `tcgen05.ld`, `tcgen05.st`, `tcgen05.wait`, `tcgen05.cp`, `tcgen05.shift`, `tcgen05.mma`, `tcgen05.mma.sp`, `tcgen05.mma.ws`, `tcgen05.mma.ws.sp`, `tcgen05.fence` and `tcgen05.commit`. + + * Extends `redux.sync` instruction to add support for `.f32` type with qualifiers `.abs` and `.NaN`. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-87/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-87/DOC.md new file mode 100644 index 00000000..0de6a025 --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-87/DOC.md @@ -0,0 +1,48 @@ +--- +name: ptx-changes-in-ptx-isa-version-87 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.4. Changes in PTX ISA Version 8.7 + +--- +title: "13.4. Changes in PTX ISA Version 8.7" +section: 13.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.4. Changes in PTX ISA Version 8.7 + + +New Features + +PTX ISA version 8.7 introduces the following new features: + +* Adds support for `sm_120` target architecture. + + * Adds support for target `sm_120a` that supports architecture-specific features. + + * Extends `tcgen05.mma` instruction to add support for `.kind::mxf4nvf4` and `.scale_vec::4X` qualifiers. + + * Extends `mma` instructions to support `.f16` type accumulator and shape `.m16n8k16` with FP8 types `.e4m3` and `.e5m2`. + + * Extends `cvt` instruction to add support for `.rs` rounding mode and destination types `.e2m1x4`, `.e4m3x4`, `.e5m2x4`, `.e3m2x4`, `.e2m3x4`. + + * Extends support for `st.async` and `red.async` instructions to add support for `.mmio`, `.release`, `.global` and `.scope` qualifiers. + + * Extends `tensormap.replace` instruction to add support for values `13` to `15` for `.elemtype` qualifier. + + * Extends `mma` and `mma.sp::ordered_metadata` instructions to add support for types `.e3m2`/`.e2m3`/ `.e2m1` and qualifiers `.kind`, `.block_scale`, `.scale_vec_size`. + +Semantic Changes and Clarifications + +* Clarified that in `.tile::gather4`, `.tile::scatter4` modes, tensor coordinates need to be specified as {col_idx, row_idx0, row_idx1, row_idx2, row_idx3} i.e. {x, y0, y1, y2, y3} instead of {x0, x1, x2, x3, y}. + + * Updated [Instruction descriptor](<#tcgen05-instruction-descriptor>) of `tcgen05.mma` instruction to clarify the bits that are reserved for future use. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-88/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-88/DOC.md new file mode 100644 index 00000000..94a6aafa --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-88/DOC.md @@ -0,0 +1,77 @@ +--- +name: ptx-changes-in-ptx-isa-version-88 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.3. Changes in PTX ISA Version 8.8 + +--- +title: "13.3. Changes in PTX ISA Version 8.8" +section: 13.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.3. Changes in PTX ISA Version 8.8 + + +New Features + +PTX ISA version 8.8 introduces the following new features: + +* Adds support for `sm_103` target architecture. + + * Adds support for target `sm_103a` that supports architecture-specific features. + + * Adds support for `sm_121` target architecture. + + * Adds support for target `sm_121a` that supports architecture-specific features. + + * Introduces family-specific target architectures that are represented with “f” suffix. PTX for family-specific targets is compatible with all subsequent targets in same family. Adds support for `sm_100f`, `sm_101f`, `sm_103f`, `sm_120f`, `sm_121f`. + + * Extends `min` and `max` instructions to support three input arguments. + + * Extends `tcgen05.mma` instruction to add support for new `scale_vectorsize` qualifiers `.block16` and `.block32` and K dimension 96. + + * Extends `.field3` of `tensormap.replace` instruction to support 96B swizzle mode. + + * Adds support for `tcgen05.ld.red` instruction. + + * Extends `ld`, `ld.global.nc` and `st` instructions to support 256b load/store operations. + + * [Table 61](<#changes-in-ptx-isa-8-8-family-specific-features>) shows the list of features that are supported on family-specific targets: + +Table 61 List of features promoted to family-specific architecture Feature | Supported targets +---|--- +`.m16n8`, `.m16n16`, `.m8n16` shapes and `.b8` type for `ldmatrix`/`stmatrix` | `sm_100f`, `sm_101f`, `sm_120f` +Shapes for `tcgen05` `.16x64b` `.16x128b`, `.16x256b`, `.16x32bx2`, `.32x32b`, `.4x256b`, `.32x128b`, `.64x128b`, `.128x256b`, `.128x128b`, `.31x256b` | `sm_100f`, `sm_101f` +`setmaxnreg` | `sm_100f`, `sm_101f`, `sm_120f` +`.cta_group` modifier | `sm_100f`, `sm_101f` +`cvt` with `.e2m1x2`, `.e3m2x2`, `.e2m3x2`, `.ue8m0x2` | `sm_100f`, `sm_101f`, `sm_120f` +`multimem` with `.acc::f16` and `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` types | `sm_100f`, `sm_101f` +`tensormap.replace` | `sm_100f`, `sm_101f`, `sm_120f` +`tcgen05.ld.red` | `sm_101f`, `sm_103f` +`tcgen05.ld`/`st`/`fence`/ `wait`/`commit`/`cp`/ `alloc`/`dealloc`/ `relinquish_alloc_permit` | `sm_100f`, `sm_101f` +`tcgen05.mma{.ws}{.sp}` (except `kind::mxf4`/ `kind::mxf4nvf4` for `.sp`) | `sm_100f`, `sm_101f` +`tcgen05` `.kind::mxf4nvf4`, `.kind::mxf4`, `.kind::mxf8f6f4`, `.kind::f16`, `.kind::tf32`, `.kind::f8f6f4` | `sm_100f`, `sm_101f` +`.ashift`, `.collector_usage` modifiers for `tcgen05` | `sm_100f`, `sm_101f` +Modifiers `.b8x16`, `.b6x16_p32`, `.b4x16_p64` | `sm_100f`, `sm_101f`, `sm_120f` +`.block_scale` modifier | `sm_100f`, `sm_101f`, `sm_120f` +`mma{.sp}` with `.e3m2`, `.e2m3`, `.e2m1` types and `.kind`, `.block_scale`, `.scale_vec_size` modifiers (except `.sp` with `mxf4`/ `mxf4nvf4`) | `sm_120f` +`.scale_vec::1X`/`2X`/`4X` modifiers | `sm_120f` +`.block16`/`.block32` modifiers (alias to `scale_vec`) | `sm_100f`, `sm_101f` +`.warpx2::02_13`, `.warpx2::01_23`, `.warpx4`, `.pack::16b`, `.unpack::16b` modifiers for `tcgen05` | `sm_100f`, `sm_101f` +`clusterlaunchcontrol.try_cancel` `multicast::cluster::all` | `sm_100f`, `sm_101f`, `sm_120f` +`.tile::scatter4`, `.tile::gather4`, `.im2col::w`, `.im2col::w::128` | `sm_100f`, `sm_101f` +`redux.f32` | `sm_100f` +`scale-input-d` for `tcgen05` | `sm_100f` + +Semantic Changes and Clarifications + +* Clarified the behavior of float-to-integer conversions for `NaN` input. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-90/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-90/DOC.md new file mode 100644 index 00000000..881b3f8c --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-90/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-changes-in-ptx-isa-version-90 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.2. Changes in PTX ISA Version 9.0 + +--- +title: "13.2. Changes in PTX ISA Version 9.0" +section: 13.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.2. Changes in PTX ISA Version 9.0 + + +New Features + +PTX ISA version 9.0 introduces the following new features: + +* Adds support for `sm_88` target architecture. + + * Adds support for `sm_110` target architecture. + + * Adds support for target `sm_110f` that supports family-specific features. + + * Adds support for target `sm_110a` that supports architecture-specific features. + + * Adds support for pragma `enable_smem_spilling` that is used to enable shared memory spilling for a function. + + * Adds support for pragma `frequency` that is used to specify the execution frequency of a basic block. + + * Adds support for directive `.blocksareclusters` that is used to specify that CUDA thread blocks are mapped to clusters. + + * Extends `size` operand of `st.bulk` instruction to support 32-bit length. + + * Adds support for performance-tuning directives `.abi_preserve` and `.abi_preserve_control` that are used to specify the number of data and control registers that should be preserved by the callers of a function. + +Notes + +* Targets `sm_{101,101f,101a}` are renamed to targets `sm_{110,110f,110a}` from PTX ISA version 9.0. + +Semantic Changes and Clarifications + +* All `tcgen05` instructions(`tcgen05.alloc`, `tcgen05.dealloc`, `tcgen05.relinquish_alloc_permit`, `tcgen05.cp`, `tcgen05.shift`, `tcgen05.mma`, `tcgen05.mma.sp`, `tcgen05.mma.ws, tcgen05.mma.ws.sp`, `tcgen05.commit`) within a kernel must specify the same value for the `.cta_group` qualifier. \ No newline at end of file diff --git a/content/cuda/docs/ptx-changes-in-ptx-isa-version-91/DOC.md b/content/cuda/docs/ptx-changes-in-ptx-isa-version-91/DOC.md new file mode 100644 index 00000000..eebf966b --- /dev/null +++ b/content/cuda/docs/ptx-changes-in-ptx-isa-version-91/DOC.md @@ -0,0 +1,40 @@ +--- +name: ptx-changes-in-ptx-isa-version-91 +description: New Features +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 13.1. Changes in PTX ISA Version 9.1 + +--- +title: "13.1. Changes in PTX ISA Version 9.1" +section: 13.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 13.1. Changes in PTX ISA Version 9.1 + + +New Features + +PTX ISA version 9.1 introduces the following new features: + +* Adds support for `.volatile` qualifier with `.local` state space for `ld` and `st` instructions. + + * Adds support for `.f16x2` and `.bf16x2` source types for `cvt` instruction with destination types `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e4m3x2`, `.e5m2x2`. + + * Adds support for `.scale_vec::4X` with `.ue8m0` as `.stype` with `.kind::mxf4nvf4` for `mma`/`mma.sp` instructions. + + * Adds support for `.s2f6x2` instruction type for `cvt` instruction. + + * Adds support for `multimem.cp.async.bulk` and `multimem.cp.reduce.async.bulk` instructions. + +Semantic Changes and Clarifications + +None. \ No newline at end of file diff --git a/content/cuda/docs/ptx-channel-data-type-and-channel-order-fields/DOC.md b/content/cuda/docs/ptx-channel-data-type-and-channel-order-fields/DOC.md new file mode 100644 index 00000000..c9de42a0 --- /dev/null +++ b/content/cuda/docs/ptx-channel-data-type-and-channel-order-fields/DOC.md @@ -0,0 +1,55 @@ +--- +name: ptx-channel-data-type-and-channel-order-fields +description: The `channel_data_type` and `channel_order` fields have enumeration types + corresponding to the source language API. Currently, OpenCL is the only source language + that defines these fields. [Table 13](... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.3.3. Channel Data Type and Channel Order Fields + +--- +title: "5.3.3. Channel Data Type and Channel Order Fields" +section: 5.3.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.3.3. Channel Data Type and Channel Order Fields + + +The `channel_data_type` and `channel_order` fields have enumeration types corresponding to the source language API. Currently, OpenCL is the only source language that defines these fields. [Table 13](<#channel-data-type-and-channel-order-fields-opencl-channel-order-definition>) and [Table 12](<#channel-data-type-and-channel-order-fields-opencl-channel-data-type-definition>) show the enumeration values defined in OpenCL version 1.0 for channel data type and channel order. + +Table 12 OpenCL 1.0 Channel Data Type Definition `CL_SNORM_INT8` | `0x10D0` +---|--- +`CL_SNORM_INT16` | `0x10D1` +`CL_UNORM_INT8` | `0x10D2` +`CL_UNORM_INT16` | `0x10D3` +`CL_UNORM_SHORT_565` | `0x10D4` +`CL_UNORM_SHORT_555` | `0x10D5` +`CL_UNORM_INT_101010` | `0x10D6` +`CL_SIGNED_INT8` | `0x10D7` +`CL_SIGNED_INT16` | `0x10D8` +`CL_SIGNED_INT32` | `0x10D9` +`CL_UNSIGNED_INT8` | `0x10DA` +`CL_UNSIGNED_INT16` | `0x10DB` +`CL_UNSIGNED_INT32` | `0x10DC` +`CL_HALF_FLOAT` | `0x10DD` +`CL_FLOAT` | `0x10DE` + +Table 13 OpenCL 1.0 Channel Order Definition `CL_R` | `0x10B0` +---|--- +`CL_A` | `0x10B1` +`CL_RG` | `0x10B2` +`CL_RA` | `0x10B3` +`CL_RGB` | `0x10B4` +`CL_RGBA` | `0x10B5` +`CL_BGRA` | `0x10B6` +`CL_ARGB` | `0x10B7` +`CL_INTENSITY` | `0x10B8` +`CL_LUMINANCE` | `0x10B9` \ No newline at end of file diff --git a/content/cuda/docs/ptx-cluster-dimension-directivesexplicitcluster/DOC.md b/content/cuda/docs/ptx-cluster-dimension-directivesexplicitcluster/DOC.md new file mode 100644 index 00000000..351f6276 --- /dev/null +++ b/content/cuda/docs/ptx-cluster-dimension-directivesexplicitcluster/DOC.md @@ -0,0 +1,51 @@ +--- +name: ptx-cluster-dimension-directivesexplicitcluster +description: Declare that Kernel must be launched with cluster dimensions explicitly + specified. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.7.2. Cluster Dimension Directives:.explicitcluster + +--- +title: "11.7.2. Cluster Dimension Directives:.explicitcluster" +section: 11.7.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.7.2. Cluster Dimension Directives:.explicitcluster + + +`.explicitcluster` + +Declare that Kernel must be launched with cluster dimensions explicitly specified. + +Syntax + +.explicitcluster + +Description + +Declares that this Kernel should be launched with cluster dimension explicitly specified. + +Semantics + +Kernels with `.explicitcluster` directive must be launched with cluster dimension explicitly specified (either at launch time or via `.reqnctapercluster`), otherwise program will fail with runtime error or kernel launch failure. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +.entry foo .explicitcluster { . . . } \ No newline at end of file diff --git a/content/cuda/docs/ptx-cluster-dimension-directivesmaxclusterrank/DOC.md b/content/cuda/docs/ptx-cluster-dimension-directivesmaxclusterrank/DOC.md new file mode 100644 index 00000000..f9d11528 --- /dev/null +++ b/content/cuda/docs/ptx-cluster-dimension-directivesmaxclusterrank/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-cluster-dimension-directivesmaxclusterrank +description: Declare the maximum number of CTAs that can be part of the cluster. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.7.3. Cluster Dimension Directives:.maxclusterrank + +--- +title: "11.7.3. Cluster Dimension Directives:.maxclusterrank" +section: 11.7.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.7.3. Cluster Dimension Directives:.maxclusterrank + + +`.maxclusterrank` + +Declare the maximum number of CTAs that can be part of the cluster. + +Syntax + +.maxclusterrank n + +Description + +Declare the maximum number of thread blocks (CTAs) allowed to be part of the cluster. + +Semantics + +Product of the number of CTAs in each cluster dimension specified in any invocation of the kernel is required to be less or equal to that specified in this directive. Otherwise invocation will result in a runtime error or kernel launch failure. + +The `.maxclusterrank` directive cannot be used in conjunction with the `.reqnctapercluster` directive. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +.entry foo ..maxclusterrank 8 { . . . } \ No newline at end of file diff --git a/content/cuda/docs/ptx-cluster-dimension-directivesreqnctapercluster/DOC.md b/content/cuda/docs/ptx-cluster-dimension-directivesreqnctapercluster/DOC.md new file mode 100644 index 00000000..f892759d --- /dev/null +++ b/content/cuda/docs/ptx-cluster-dimension-directivesreqnctapercluster/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-cluster-dimension-directivesreqnctapercluster +description: '`.reqnctapercluster`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.7.1. Cluster Dimension Directives:.reqnctapercluster + +--- +title: "11.7.1. Cluster Dimension Directives:.reqnctapercluster" +section: 11.7.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.7.1. Cluster Dimension Directives:.reqnctapercluster + + +`.reqnctapercluster` + +Declare the number of CTAs in the cluster. + +Syntax + +.reqnctapercluster nx + .reqnctapercluster nx, ny + .reqnctapercluster nx, ny, nz + +Description + +Set the number of thread blocks (CTAs) in the cluster by specifying the extent of each dimension of the 1D, 2D, or 3D cluster. The total number of CTAs is the product of the number of CTAs in each dimension. For kernels with `.reqnctapercluster` directive specified, runtime will use the specified values for configuring the launch if the same are not specified at launch time. + +Semantics + +If cluster dimension is explicitly specified at launch time, it should be equal to the values specified in this directive. Specifying a different cluster dimension at launch will result in a runtime error or kernel launch failure. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +.entry foo .reqnctapercluster 2 { . . . } + .entry bar .reqnctapercluster 2, 2, 1 { . . . } + .entry ker .reqnctapercluster 3, 2 { . . . } \ No newline at end of file diff --git a/content/cuda/docs/ptx-cluster-of-cooperative-thread-arrays/DOC.md b/content/cuda/docs/ptx-cluster-of-cooperative-thread-arrays/DOC.md new file mode 100644 index 00000000..bc6373f2 --- /dev/null +++ b/content/cuda/docs/ptx-cluster-of-cooperative-thread-arrays/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-cluster-of-cooperative-thread-arrays +description: Cluster is a group of CTAs that run concurrently or in parallel and can + synchronize and communicate with each other via shared memory. The executing CTA + has to make sure that the shared memory of the ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 2.2.2. Cluster of Cooperative Thread Arrays + +--- +title: "2.2.2. Cluster of Cooperative Thread Arrays" +section: 2.2.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 2.2.2. Cluster of Cooperative Thread Arrays + + +Cluster is a group of CTAs that run concurrently or in parallel and can synchronize and communicate with each other via shared memory. The executing CTA has to make sure that the shared memory of the peer CTA exists before communicating with it via shared memory and the peer CTA hasn’t exited before completing the shared memory operation. + +Threads within the different CTAs in a cluster can synchronize and communicate with each other via shared memory. Cluster-wide barriers can be used to synchronize all the threads within the cluster. Each CTA in a cluster has a unique CTA identifier within its cluster (_cluster_ctaid_). Each cluster of CTAs has 1D, 2D or 3D shape specified by the parameter _cluster_nctaid_. Each CTA in the cluster also has a unique CTA identifier (_cluster_ctarank_) across all dimensions. The total number of CTAs across all the dimensions in the cluster is specified by _cluster_nctarank_. Threads may read and use these values through predefined, read-only special registers `%cluster_ctaid`, `%cluster_nctaid`, `%cluster_ctarank`, `%cluster_nctarank`. + +Cluster level is applicable only on target architecture `sm_90` or higher. Specifying cluster level during launch time is optional. If the user specifies the cluster dimensions at launch time then it will be treated as explicit cluster launch, otherwise it will be treated as implicit cluster launch with default dimension 1x1x1. PTX provides read-only special register `%is_explicit_cluster` to differentiate between explicit and implicit cluster launch. \ No newline at end of file diff --git a/content/cuda/docs/ptx-clusterlaunchcontrolquery-cancel/DOC.md b/content/cuda/docs/ptx-clusterlaunchcontrolquery-cancel/DOC.md new file mode 100644 index 00000000..e2f0bf2f --- /dev/null +++ b/content/cuda/docs/ptx-clusterlaunchcontrolquery-cancel/DOC.md @@ -0,0 +1,68 @@ +--- +name: ptx-clusterlaunchcontrolquery-cancel +description: '`clusterlaunchcontrol.query_cancel`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.18. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.query_cancel + +--- +title: "9.7.13.18. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.query_cancel" +section: 9.7.13.18 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.18. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.query_cancel + + +`clusterlaunchcontrol.query_cancel` + +Queries response of `clusterlaunchcontrol.try_cancel` operation. + +Syntax + +clusterlaunchcontrol.query_cancel.is_canceled.pred.b128 pred, try_cancel_response; + + clusterlaunchcontrol.query_cancel.get_first_ctaid.v4.b32.b128 {xdim, ydim, zdim, _}, try_cancel_response; + + clusterlaunchcontrol.query_cancel.get_first_ctaid{::dimension}.b32.b128 reg, try_cancel_response; + + ::dimension = { ::x, ::y, ::z }; + +Description + +Instruction `clusterlaunchcontrol.query_cancel` can be used to decode opaque response written by instruction `clusterlaunchcontrol.try_cancel`. + +After loading response from `clusterlaunchcontrol.try_cancel` instruction into 16-byte register it can be further queried using `clusterlaunchcontrol.query_cancel` instruction as follows: + +`clusterlaunchcontrol.query_cancel.is_canceled.pred.b128`: If the cluster is canceled successfully, predicate `p` is set to `true`; otherwise, it is set to `false`. + +If the request succeeded, the instruction `clusterlaunchcontrol.query_cancel.get_first_ctaid` extracts the CTA id of the first CTA in the canceled cluster. By default, the instruction returns a `.v4` vector whose first three elements are the `x`, `y` and `z` coordinate of first CTA in canceled cluster. The contents of the 4th element are unspecified. The explicit `.get_first_ctaid::x`, `.get_first_ctaid::y`, or `.get_first_ctaid::z` qualifiers can be used to extract individual `x`, `y` or `z` coordinates into a 32-bit register. + +If the request fails the behavior of `clusterlaunchcontrol.query_cancel.get_first_ctaid` is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_100` or higher. + +Examples + +clusterlaunchcontrol.query_cancel.is_canceled pred.b128 p, handle; + + @p clusterlaunchcontrol.query_cancel.get_first_ctaid.v4.b32.b128 {xdim, ydim, zdim, ignr} handle; + + clusterlaunchcontrol.query_cancel.get_first_ctaid::x.b32.b128 reg0, handle; + + clusterlaunchcontrol.query_cancel.get_first_ctaid::y.b32.b128 reg1, handle; + + clusterlaunchcontrol.query_cancel.get_first_ctaid::z.b32.b128 reg2, handle; \ No newline at end of file diff --git a/content/cuda/docs/ptx-clusterlaunchcontroltry-cancel/DOC.md b/content/cuda/docs/ptx-clusterlaunchcontroltry-cancel/DOC.md new file mode 100644 index 00000000..e096b146 --- /dev/null +++ b/content/cuda/docs/ptx-clusterlaunchcontroltry-cancel/DOC.md @@ -0,0 +1,150 @@ +--- +name: ptx-clusterlaunchcontroltry-cancel +description: '`clusterlaunchcontrol.try_cancel`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.17. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.try_cancel + +--- +title: "9.7.13.17. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.try_cancel" +section: 9.7.13.17 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.17. Parallel Synchronization and Communication Instructions:clusterlaunchcontrol.try_cancel + + +`clusterlaunchcontrol.try_cancel` + +Requests cancellation of cluster which is not launched yet. + +Syntax + +clusterlaunchcontrol.try_cancel.async{.space}.completion_mechanism{.multicast::cluster::all}.b128 [addr], [mbar]; + + .completion_mechanism = { .mbarrier::complete_tx::bytes }; + .space = { .shared::cta }; + +Description + +The `clusterlaunchcontrol.try_cancel` instruction requests atomically cancelling the launch of a cluster that has not started running yet. It asynchronously writes an opaque response to shared memory indicating whether the operation succeeded or failed. The completion of the asynchronous operation is tracked using the mbarrier completion mechanism at `.cluster` scope. This instruction accesses its `mbarrier` operand using generic-proxy. + +On success, the opaque response contains the `ctaid` of the first CTA of the canceled cluster; no other successful response from other `clusterlaunchcontrol.try_cancel` operations from the same grid will contain that id. + +The mandatory `.async` qualifier indicates that the instruction will initiate the cancellation operation asynchronously and control will return to the executing thread before the requested operation is complete. + +The `.space` qualifier is specified, both operands `addr` and `mbar` must be in the `.shared::cta` state space. Otherwise, generic addressing will be assumed for both. The result is undefined if any of address operands do not fall within the address window of `.shared::cta`. + +The qualifier `.completion_mechanism` specifies that upon completion of the asynchronous operation, [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation, with `completeCount` argument equal to amount of data stored in bytes, will be performed on the mbarrier object specified by the operand `mbar`. + +The executing thread can then use [mbarrier instructions](<#parallel-synchronization-and-communication-instructions-mbarrier>) to wait for completion of the asynchronous operation. No other synchronization mechanisms described in [Memory Consistency Model](<#memory-consistency-model>) can be used to guarantee the completion of the asynchronous copy operations. + +The `.multicast::cluster::all` qualifier indicates that the response is asynchronously written using weak async-proxy writes to the corresponding local shared memory `addr` of each CTA in the requesting cluster. The completion of the writes to `addr` of a particular CTA is signaled via a complete-tx operation to the mbarrier object on the shared memory of that CTA. + +The behavior of instruction with `.multicast::cluster::all` qualifier is undefined if any CTA in the cluster is exited. + +Operand `addr` specifies the naturally aligned address of the 16-byte wide shared memory location where the request’s response is written. + +The response of `clusterlaunchcontrol.try_cancel` instruction will be 16-byte opaque value and will be it available at location specified by operand `addr`. After loading this response into 16-byte register, instruction `clusterlaunchcontrol.query_cancel` can be used to check if request was successful and to retrieve `ctaid` of the first CTA of the canceled cluster. + +If the executing CTA has already observed the completion of a `clusterlaunchcontrol.try_cancel` instruction as failed, then the behavior of issuing a subsequent `clusterlaunchcontrol.try_cancel` instruction is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_100` or higher. + +Qualifier `.multicast::cluster::all` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +Examples + +// Assumption: 1D cluster (cluster_ctaid.y/.z == 1) with 1 thread per CTA. + + // Current Cluster to be processed: initially the launched cluster: + mov.b32 xctaid, %ctaid.x; + + // Establish full synchronization across all CTAs of the cluster for the first iteration. + // Weaker synchronization may suffice depending on initialization sequence. + barrier.cluster.arrive; + barrier.cluster.wait; + + // Iteration loop over all cluster CTAs + processCluster: + mov.u32 %r0, %tid.x; + setp.u32.eq p0, %r0, 0x0; + // Elect a leader thread (thread idx 0) for each CTA to arrive and expect_tx at + // each CTA local shared memory barrier: + mov.u32 %r0, %tid.x; + setp.u32.eq p0, %r0, 0x0; + // All other threads skip to processing the work of the current cluster: + @!p0 bra processCurrentCluster; + + // All CTAs in the cluster arrive at their local SMEM barrier and set 16B handle tx count: + mbarrier.arrive.expect_tx.cluster.relaxed.shared::cta.b64 state, [mbar], 16; + + // First CTA in Cluster attempts to cancel a not-yet-started cluster: + mov.u32 %r0, %cluster_ctaid.x; + setp.u32.eq p0, %r0, 0x0; + @p0 clusterlaunchcontrol.try_cancel.async.mbarrier::complete_tx::bytes.multicast::cluster::all.b128 [addr], [mbar]; + + processCurrentCluster: + // ...process current cluster ("xctaid") while cancellation request for next cluster runs asynchronously... + + // After processing current cluster, wait on cancellation request response for next cluster via specified mbarrier: + waitLoop: + // .acquire prevents weak handle read ("ld.shared handle, [addr]") from overtaking this mbarrier.try_wait: + mbarrier.try_wait.cluster.acquire.shared::cta.b64 complete, [mbar], state; + @!complete bra waitLoop; + // Cancellation request has completed. + + // Generic-proxy weak read of cancellation request into 16-byte wide register: + ld.shared.b128 handle, [addr]; + + // Check whether cancellation succeeded: + clusterlaunchcontrol.query_cancel.is_canceled.pred.b128 p, handle; + // If cancellation request failed, we couldn't cancel any other cluster, so all current cluster CTAs exit. + @!p ret; + + // Otherwise, cancellation request succeeded. + // Extract "ctaid" of first cancelled-cluster CTA which we'll process in next "processCluster" loop iteration: + @p clusterlaunchcontrol.query_cancel.get_first_ctaid.v4.b32.b128 {xctaid, _, _, _}, handle; + + // Release current iteration generic-proxy weak read of handle ("ld.shared handle, [addr]") + // before next iteration async-proxy write to handle ("clusterlaunchcontrol.try_cancel [addr]") + fence.proxy.async::generic.release.sync_restrict::shared::cta.cluster; + + // Arrive and wait at the next iteration cluster barrier with relaxed semantics. + barrier.cluster.arrive.relaxed; + barrier.cluster.wait; + + // Acquire prior iteration generic-proxy weak read of handle ("ld.shared handle, [addr]") + // before current iteration async-proxy write to handle ("clusterlaunchcontrol.try_cancel [addr]") + fence.proxy.async::generic.acquire.sync_restrict::shared::cluster.cluster; + + bra processCluster; \ No newline at end of file diff --git a/content/cuda/docs/ptx-clz/DOC.md b/content/cuda/docs/ptx-clz/DOC.md new file mode 100644 index 00000000..7bf8a8c3 --- /dev/null +++ b/content/cuda/docs/ptx-clz/DOC.md @@ -0,0 +1,60 @@ +--- +name: ptx-clz +description: Count leading zeros. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.15. Integer Arithmetic Instructions:clz + +--- +title: "9.7.1.15. Integer Arithmetic Instructions:clz" +section: 9.7.1.15 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.15. Integer Arithmetic Instructions:clz + + +`clz` + +Count leading zeros. + +Syntax + +clz.type d, a; + + .type = { .b32, .b64 }; + +Description + +Count the number of leading zeros in `a` starting with the most-significant bit and place the result in 32-bit destination register `d`. Operand `a` has the instruction type, and destination `d` has type `.u32`. For `.b32` type, the number of leading zeros is between 0 and 32, inclusively. For `.b64` type, the number of leading zeros is between 0 and 64, inclusively. + +Semantics + +.u32 d = 0; + if (.type == .b32) { max = 32; mask = 0x80000000; } + else { max = 64; mask = 0x8000000000000000; } + + while (d < max && (a&mask == 0) ) { + d++; + a = a << 1; + } + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +`clz` requires `sm_20` or higher. + +Examples + +clz.b32 d, a; + clz.b64 cnt, X; // cnt is .u32 \ No newline at end of file diff --git a/content/cuda/docs/ptx-cnot/DOC.md b/content/cuda/docs/ptx-cnot/DOC.md new file mode 100644 index 00000000..e29bf11c --- /dev/null +++ b/content/cuda/docs/ptx-cnot/DOC.md @@ -0,0 +1,56 @@ +--- +name: ptx-cnot +description: C/C++ style logical negation. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.8.5. Logic and Shift Instructions:cnot + +--- +title: "9.7.8.5. Logic and Shift Instructions:cnot" +section: 9.7.8.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.8.5. Logic and Shift Instructions:cnot + + +`cnot` + +C/C++ style logical negation. + +Syntax + +cnot.type d, a; + + .type = { .b16, .b32, .b64 }; + +Description + +Compute the logical negation using C/C++ semantics. + +Semantics + +d = (a==0) ? 1 : 0; + +Notes + +The size of the operands must match, but not necessarily the type. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +cnot.b32 d,a; \ No newline at end of file diff --git a/content/cuda/docs/ptx-coherence-order/DOC.md b/content/cuda/docs/ptx-coherence-order/DOC.md new file mode 100644 index 00000000..9e87bdf1 --- /dev/null +++ b/content/cuda/docs/ptx-coherence-order/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-coherence-order +description: There exists a partial transitive order that relates _overlapping_ write + operations, determined at runtime, called the _coherence order_ 1. Two _overlapping_ + write operations are related in _coherence... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.6. Coherence Order + +--- +title: "8.9.6. Coherence Order" +section: 8.9.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.6. Coherence Order + + +There exists a partial transitive order that relates _overlapping_ write operations, determined at runtime, called the _coherence order_ 1. Two _overlapping_ write operations are related in _coherence order_ if they are _morally strong_ or if they are related in _causality order_. Two _overlapping_ writes are unrelated in _coherence order_ if they are in a _data-race_ , which gives rise to the partial nature of _coherence order_. + +1 _Coherence order_ cannot be observed directly since it consists entirely of write operations. It may be observed indirectly by its use in constraining the set of candidate writes that a read operation may read from. \ No newline at end of file diff --git a/content/cuda/docs/ptx-coherence/DOC.md b/content/cuda/docs/ptx-coherence/DOC.md new file mode 100644 index 00000000..be302d62 --- /dev/null +++ b/content/cuda/docs/ptx-coherence/DOC.md @@ -0,0 +1,25 @@ +--- +name: ptx-coherence +description: "If a write W precedes an _overlapping_ write W\u2019 in _causality order_\ + \ , then W must precede W\u2019 in _coherence order_." +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.10.1. Coherence + +--- +title: "8.10.1. Coherence" +section: 8.10.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.10.1. Coherence + + +If a write W precedes an _overlapping_ write W’ in _causality order_ , then W must precede W’ in _coherence order_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-comments/DOC.md b/content/cuda/docs/ptx-comments/DOC.md new file mode 100644 index 00000000..60335006 --- /dev/null +++ b/content/cuda/docs/ptx-comments/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-comments +description: Comments in PTX follow C/C++ syntax, using non-nested `/*` and `*/` for + comments that may span multiple lines, and using `//` to begin a comment that extends + up to the next newline character, which te... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.2. Comments + +--- +title: "4.2. Comments" +section: 4.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 4.2. Comments + + +Comments in PTX follow C/C++ syntax, using non-nested `/*` and `*/` for comments that may span multiple lines, and using `//` to begin a comment that extends up to the next newline character, which terminates the current line. Comments cannot occur within character constants, string literals, or within other comments. + +Comments in PTX are treated as whitespace. \ No newline at end of file diff --git a/content/cuda/docs/ptx-communication-order/DOC.md b/content/cuda/docs/ptx-communication-order/DOC.md new file mode 100644 index 00000000..b0720093 --- /dev/null +++ b/content/cuda/docs/ptx-communication-order/DOC.md @@ -0,0 +1,33 @@ +--- +name: ptx-communication-order +description: The _communication order_ is a non-transitive order, determined at runtime, + that relates write operations to other _overlapping_ memory operations. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.7. Communication Order + +--- +title: "8.9.7. Communication Order" +section: 8.9.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.7. Communication Order + + +The _communication order_ is a non-transitive order, determined at runtime, that relates write operations to other _overlapping_ memory operations. + +1. A write W precedes an _overlapping_ read R in _communication order_ if R returns the value of any byte that was written by W. + + 2. A write W precedes a write W’ in _communication order_ if W precedes W’ in _coherence order_. + + 3. A read R precedes an _overlapping_ write W in _communication order_ if, for any byte accessed by both R and W, R returns the value written by a write W’ that precedes W in _coherence order_. + +_Communication order_ captures the visibility of memory operations — when a memory operation X1 precedes a memory operation X2 in _communication order_ , X1 is said to be visible to X2. \ No newline at end of file diff --git a/content/cuda/docs/ptx-conflict-and-data-races/DOC.md b/content/cuda/docs/ptx-conflict-and-data-races/DOC.md new file mode 100644 index 00000000..0eb1825b --- /dev/null +++ b/content/cuda/docs/ptx-conflict-and-data-races/DOC.md @@ -0,0 +1,27 @@ +--- +name: ptx-conflict-and-data-races +description: Two _overlapping_ memory operations are said to _conflict_ when at least + one of them is a _write_. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.7.1. Conflict and Data-races + +--- +title: "8.7.1. Conflict and Data-races" +section: 8.7.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.7.1. Conflict and Data-races + + +Two _overlapping_ memory operations are said to _conflict_ when at least one of them is a _write_. + +Two _conflicting_ memory operations are said to be in a _data-race_ if they are not related in _causality order_ and they are not _morally strong_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-constant-expressions/DOC.md b/content/cuda/docs/ptx-constant-expressions/DOC.md new file mode 100644 index 00000000..71427228 --- /dev/null +++ b/content/cuda/docs/ptx-constant-expressions/DOC.md @@ -0,0 +1,49 @@ +--- +name: ptx-constant-expressions +description: In PTX, constant expressions are formed using operators as in C and are + evaluated using rules similar to those in C, but simplified by restricting types + and sizes, removing most casts, and defining fu... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.5.4. Constant Expressions + +--- +title: "4.5.4. Constant Expressions" +section: 4.5.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.5.4. Constant Expressions + + +In PTX, constant expressions are formed using operators as in C and are evaluated using rules similar to those in C, but simplified by restricting types and sizes, removing most casts, and defining full semantics to eliminate cases where expression evaluation in C is implementation dependent. + +Constant expressions are formed from constant literals, unary plus and minus, basic arithmetic operators (addition, subtraction, multiplication, division), comparison operators, the conditional ternary operator ( `?:` ), and parentheses. Integer constant expressions also allow unary logical negation (`!`), bitwise complement (`~`), remainder (`%`), shift operators (`<<` and `>>`), bit-type operators (`&`, `|`, and `^`), and logical operators (`&&`, `||`). + +Constant expressions in PTX do not support casts between integer and floating-point. + +Constant expressions are evaluated using the same operator precedence as in C. [Table 4](<#constant-expressions-operator-precedence>) gives operator precedence and associativity. Operator precedence is highest for unary operators and decreases with each line in the chart. Operators on the same line have the same precedence and are evaluated right-to-left for unary operators and left-to-right for binary operators. + +Table 4 Operator Precedence Kind | Operator Symbols | Operator Names | Associates +---|---|---|--- +Primary | `()` | parenthesis | n/a +Unary | `+- ! ~` | plus, minus, negation, complement | right +`(.s64)``(.u64)` | casts | right +Binary | `*/ %` | multiplication, division, remainder | left +`+-` | addition, subtraction +`>> <<` | shifts +`< > <= >=` | ordered comparisons +`== !=` | equal, not equal +`&` | bitwise AND +`^` | bitwise XOR +`|` | bitwise OR +`&&` | logical AND +`||` | logical OR +Ternary | `?:` | conditional | right \ No newline at end of file diff --git a/content/cuda/docs/ptx-control-flow-directivesbranchtargets/DOC.md b/content/cuda/docs/ptx-control-flow-directivesbranchtargets/DOC.md new file mode 100644 index 00000000..a67ae164 --- /dev/null +++ b/content/cuda/docs/ptx-control-flow-directivesbranchtargets/DOC.md @@ -0,0 +1,78 @@ +--- +name: ptx-control-flow-directivesbranchtargets +description: Declare a list of potential branch targets. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.3.1. Control Flow Directives:.branchtargets + +--- +title: "11.3.1. Control Flow Directives:.branchtargets" +section: 11.3.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.3.1. Control Flow Directives:.branchtargets + + +`.branchtargets` + +Declare a list of potential branch targets. + +Syntax + +Label: .branchtargets list-of-labels ; + +Description + +Declares a list of potential branch targets for a subsequent `brx.idx`, and associates the list with the label at the start of the line. + +All control flow labels in the list must occur within the same function as the declaration. + +The list of labels may use the compact, shorthand syntax for enumerating a range of labels having a common prefix, similar to the syntax described in [Parameterized Variable Names](<#parameterized-variable-names>). + +PTX ISA Notes + +Introduced in PTX ISA version 2.1. + +Target ISA Notes + +Requires `sm_20` or higher. + +Examples + +.function foo () { + .reg .u32 %r0; + ... + L1: + ... + L2: + ... + L3: + ... + ts: .branchtargets L1, L2, L3; + @p brx.idx %r0, ts; + ... + + .function bar() { + .reg .u32 %r0; + ... + N0: + ... + N1: + ... + N2: + ... + N3: + ... + N4: + ... + ts: .branchtargets N<5>; + @p brx.idx %r0, ts; + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-control-flow-directivescallprototype/DOC.md b/content/cuda/docs/ptx-control-flow-directivescallprototype/DOC.md new file mode 100644 index 00000000..6af3d14c --- /dev/null +++ b/content/cuda/docs/ptx-control-flow-directivescallprototype/DOC.md @@ -0,0 +1,87 @@ +--- +name: ptx-control-flow-directivescallprototype +description: Declare a prototype for use in an indirect call. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.3.3. Control Flow Directives:.callprototype + +--- +title: "11.3.3. Control Flow Directives:.callprototype" +section: 11.3.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.3.3. Control Flow Directives:.callprototype + + +`.callprototype` + +Declare a prototype for use in an indirect call. + +Syntax + +// no input or return parameters + label: .callprototype _ .noreturn {.abi_preserve N} {.abi_preserve_control N}; + // input params, no return params + label: .callprototype _ (param-list) .noreturn {.abi_preserve N} {.abi_preserve_control N}; + // no input params, // return params + label: .callprototype (ret-param) _ {.abi_preserve N} {.abi_preserve_control N}; + // input, return parameters + label: .callprototype (ret-param) _ (param-list) {.abi_preserve N} {.abi_preserve_control N}; + +Description + +Defines a prototype with no specific function name, and associates the prototype with a label. The prototype may then be used in indirect call instructions where there is incomplete knowledge of the possible call targets. + +Parameters may have either base types in the register or parameter state spaces, or array types in parameter state space. The sink symbol `'_'` may be used to avoid dummy parameter names. + +An optional `.noreturn` directive indicates that the function does not return to the caller function. `.noreturn` directive cannot be specified on functions which have return parameters. See the description of .noreturn directive in [Performance-Tuning Directives: .noreturn](<#performance-tuning-directives-noreturn>). + +Optional `.abi_preserve` and `.abi_preserve_control` directives are used to specify the number of general purpose registers and control registers. See description of [Performance-Tuning Directives: .abi_preserve](<#performance-tuning-directives-abi-preserve>) and [Performance-Tuning Directives: .abi_preserve_control](<#performance-tuning-directives-abi-preserve-control>) for more details. + +PTX ISA Notes + +Introduced in PTX ISA version 2.1. + +Support for `.noreturn` directive introduced in PTX ISA version 6.4. + +Support for `.abi_preserve` and `.abi_preserve_control` directives introduced in PTX ISA version 9.0. + +Target ISA Notes + +Requires `sm_20` or higher. + +`.noreturn` directive requires `sm_30` or higher. + +`.abi_preserve` and `.abi_preserve_control` directives require `sm_80` or higher. + +Examples + +Fproto1: .callprototype _ ; + Fproto2: .callprototype _ (.param .f32 _); + Fproto3: .callprototype (.param .u32 _) _ ; + Fproto4: .callprototype (.param .u32 _) _ (.param .f32 _); + ... + @p call (%val), %r0, (%f1), Fproto4; + ... + + // example of array parameter + Fproto5: .callprototype _ (.param .b8 _[12]); + + Fproto6: .callprototype _ (.param .f32 _) .noreturn; + ... + @p call %r0, (%f1), Fproto6; + ... + + // example of .abi_preserve + Fproto7: .callprototype _ (.param .b32 _) .abi_preserve 10; + ... + @p call %r0, (%r1), Fproto7; + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-control-flow-directivescalltargets/DOC.md b/content/cuda/docs/ptx-control-flow-directivescalltargets/DOC.md new file mode 100644 index 00000000..c33f6f02 --- /dev/null +++ b/content/cuda/docs/ptx-control-flow-directivescalltargets/DOC.md @@ -0,0 +1,51 @@ +--- +name: ptx-control-flow-directivescalltargets +description: Declare a list of potential call targets. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.3.2. Control Flow Directives:.calltargets + +--- +title: "11.3.2. Control Flow Directives:.calltargets" +section: 11.3.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.3.2. Control Flow Directives:.calltargets + + +`.calltargets` + +Declare a list of potential call targets. + +Syntax + +Label: .calltargets list-of-functions ; + +Description + +Declares a list of potential call targets for a subsequent indirect call, and associates the list with the label at the start of the line. + +All functions named in the list must be declared prior to the `.calltargets` directive, and all functions must have the same type signature. + +PTX ISA Notes + +Introduced in PTX ISA version 2.1. + +Target ISA Notes + +Requires `sm_20` or higher. + +Examples + +calltgt: .calltargets fastsin, fastcos; + ... + @p call (%f1), %r0, (%x), calltgt; + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-cooperative-thread-arrays/DOC.md b/content/cuda/docs/ptx-cooperative-thread-arrays/DOC.md new file mode 100644 index 00000000..59c8e966 --- /dev/null +++ b/content/cuda/docs/ptx-cooperative-thread-arrays/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-cooperative-thread-arrays +description: 'The _Parallel Thread Execution (PTX)_ programming model is explicitly + parallel: a PTX program specifies the execution of a given thread of a parallel + thread array. A _cooperative thread array_ , or CT...' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 2.2.1. Cooperative Thread Arrays + +--- +title: "2.2.1. Cooperative Thread Arrays" +section: 2.2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 2.2.1. Cooperative Thread Arrays + + +The _Parallel Thread Execution (PTX)_ programming model is explicitly parallel: a PTX program specifies the execution of a given thread of a parallel thread array. A _cooperative thread array_ , or CTA, is an array of threads that execute a kernel concurrently or in parallel. + +Threads within a CTA can communicate with each other. To coordinate the communication of the threads within the CTA, one can specify synchronization points where threads wait until all threads in the CTA have arrived. + +Each thread has a unique thread identifier within the CTA. Programs use a data parallel decomposition to partition inputs, work, and results across the threads of the CTA. Each CTA thread uses its thread identifier to determine its assigned role, assign specific input and output positions, compute addresses, and select work to perform. The thread identifier is a three-element vector `tid`, (with elements `tid.x`, `tid.y`, and `tid.z`) that specifies the thread’s position within a 1D, 2D, or 3D CTA. Each thread identifier component ranges from zero up to the number of thread ids in that CTA dimension. + +Each CTA has a 1D, 2D, or 3D shape specified by a three-element vector `ntid` (with elements `ntid.x`, `ntid.y`, and `ntid.z`). The vector `ntid` specifies the number of threads in each CTA dimension. + +Threads within a CTA execute in SIMT (single-instruction, multiple-thread) fashion in groups called _warps_. A _warp_ is a maximal subset of threads from a single CTA, such that the threads execute the same instructions at the same time. Threads within a warp are sequentially numbered. The warp size is a machine-dependent constant. Typically, a warp has 32 threads. Some applications may be able to maximize performance with knowledge of the warp size, so PTX includes a run-time immediate constant, `WARP_SZ`, which may be used in any instruction where an immediate operand is allowed. \ No newline at end of file diff --git a/content/cuda/docs/ptx-copysign/DOC.md b/content/cuda/docs/ptx-copysign/DOC.md new file mode 100644 index 00000000..a5b42422 --- /dev/null +++ b/content/cuda/docs/ptx-copysign/DOC.md @@ -0,0 +1,49 @@ +--- +name: ptx-copysign +description: Copy sign of one input to another. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.2. Floating Point Instructions:copysign + +--- +title: "9.7.3.2. Floating Point Instructions:copysign" +section: 9.7.3.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.2. Floating Point Instructions:copysign + + +`copysign` + +Copy sign of one input to another. + +Syntax + +copysign.type d, a, b; + + .type = { .f32, .f64 }; + +Description + +Copy sign bit of `a` into value of `b`, and return the result as `d`. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +Requires `sm_20` or higher. + +Examples + +copysign.f32 x, y, z; + copysign.f64 A, B, C; \ No newline at end of file diff --git a/content/cuda/docs/ptx-cos/DOC.md b/content/cuda/docs/ptx-cos/DOC.md new file mode 100644 index 00000000..fdfb8ca0 --- /dev/null +++ b/content/cuda/docs/ptx-cos/DOC.md @@ -0,0 +1,88 @@ +--- +name: ptx-cos +description: Find the cosine of a value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.19. Floating Point Instructions:cos + +--- +title: "9.7.3.19. Floating Point Instructions:cos" +section: 9.7.3.19 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.19. Floating Point Instructions:cos + + +`cos` + +Find the cosine of a value. + +Syntax + +cos.approx{.ftz}.f32 d, a; + +Description + +Find the cosine of the angle `a` (in radians). + +Semantics + +d = cos(a); + +Notes + +`cos.approx.f32` implements a fast approximation to cosine. + +Input | Result +---|--- +-Inf | NaN +-0.0 | +1.0 ++0.0 | +1.0 ++Inf | NaN +NaN | NaN + +The maximum absolute error over input range is as follows: + +Range | [-2pi .. 2pi] | [-100pi .. +100pi] +---|---|--- +Error | 2-20.5 | 2-14.7 + +Outside of the range [-100pi .. +100pi], only best effort is provided. There are no defined error guarantees. + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`cos.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +Subnormal inputs and results to sign-preserving zero. + +PTX ISA Notes + +`cos.f32` introduced in PTX ISA version 1.0. Explicit modifiers `.approx` and `.ftz` introduced in PTX ISA version 1.4. + +For PTX ISA version 1.4 and later, the `.approx` modifier is required. + +For PTX ISA versions 1.0 through 1.3, `cos.f32` defaults to `cos.approx.ftz.f32`. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +cos.approx.ftz.f32 ca, a; \ No newline at end of file diff --git a/content/cuda/docs/ptx-createpolicy/DOC.md b/content/cuda/docs/ptx-createpolicy/DOC.md new file mode 100644 index 00000000..f6a6672b --- /dev/null +++ b/content/cuda/docs/ptx-createpolicy/DOC.md @@ -0,0 +1,102 @@ +--- +name: ptx-createpolicy +description: Create a cache eviction policy for the specified cache level. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.18. Data Movement and Conversion Instructions:createpolicy + +--- +title: "9.7.9.18. Data Movement and Conversion Instructions:createpolicy" +section: 9.7.9.18 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.18. Data Movement and Conversion Instructions:createpolicy + + +`createpolicy` + +Create a cache eviction policy for the specified cache level. + +Syntax + +// Range-based policy + createpolicy.range{.global}.level::primary_priority{.level::secondary_priority}.b64 + cache-policy, [a], primary-size, total-size; + + // Fraction-based policy + createpolicy.fractional.level::primary_priority{.level::secondary_priority}.b64 + cache-policy{, fraction}; + + // Converting the access property from CUDA APIs + createpolicy.cvt.L2.b64 cache-policy, access-property; + + .level::primary_priority = { .L2::evict_last, .L2::evict_normal, + .L2::evict_first, .L2::evict_unchanged }; + .level::secondary_priority = { .L2::evict_first, .L2::evict_unchanged }; + +Description + +The `createpolicy` instruction creates a cache eviction policy for the specified cache level in an opaque 64-bit register specified by the destination operand `cache-policy`. The cache eviction policy specifies how cache eviction priorities are applied to global memory addresses used in memory operations with `.level::cache_hint` qualifier. + +There are two types of cache eviction policies: + +* Range-based policy + +The cache eviction policy created using `createpolicy.range` specifies the cache eviction behaviors for the following three address ranges: + + * `[a .. a + (primary-size - 1)]` referred to as primary range. + + * `[a + primary-size .. a + (total-size - 1)]` referred to as trailing secondary range. + + * `[a - (total-size - primary-size) .. (a - 1)]` referred to as preceding secondary range. + +When a range-based cache eviction policy is used in a memory operation with `.level::cache_hint` qualifier, the eviction priorities are applied as follows: + + * If the memory address falls in the primary range, the eviction priority specified by `.L2::primary_priority` is applied. + + * If the memory address falls in any of the secondary ranges, the eviction priority specified by `.L2::secondary_priority` is applied. + + * If the memory address does not fall in either of the above ranges, then the applied eviction priority is unspecified. + +The 32-bit operand `primary-size` specifies the size, in bytes, of the primary range. The 32-bit operand `total-size` specifies the combined size, in bytes, of the address range including primary and secondary ranges. The value of `primary-size` must be less than or equal to the value of `total-size`. Maximum allowed value of `total-size` is 4GB. + +If `.L2::secondary_priority` is not specified, then it defaults to `.L2::evict_unchanged`. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the specified address does not fall within the address window of `.global` state space then the behavior is undefined. + + * Fraction-based policy + +A memory operation with `.level::cache_hint` qualifier can use the fraction-based cache eviction policy to request the cache eviction priority specified by `.L2:primary_priority` to be applied to a fraction of cache accesses specified by the 32-bit floating point operand `fraction`. The remainder of the cache accesses get the eviction priority specified by `.L2::secondary_priority`. This implies that in a memory operation that uses a fraction-based cache policy, the memory access has a probability specified by the operand `fraction` of getting the cache eviction priority specified by `.L2::primary_priority`. + +The valid range of values for the operand `fraction` is `(0.0,.., 1.0]`. If the operand `fraction` is not specified, it defaults to 1.0. + +If `.L2::secondary_priority` is not specified, then it defaults to `.L2::evict_unchanged`. + +The access property created using the CUDA APIs can be converted into cache eviction policy by the instruction `createpolicy.cvt`. The source operand `access-property` is a 64-bit opaque register. Refer to _CUDA programming guide_ for more details. + +PTX ISA Notes + +Introduced in PTX ISA version 7.4. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + +createpolicy.fractional.L2::evict_last.b64 policy, 1.0; + createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 policy, 0.5; + + createpolicy.range.L2::evict_last.L2::evict_first.b64 + policy, [ptr], 0x100000, 0x200000; + + // access-prop is created by CUDA APIs. + createpolicy.cvt.L2.b64 policy, access-prop; \ No newline at end of file diff --git a/content/cuda/docs/ptx-cvt/DOC.md b/content/cuda/docs/ptx-cvt/DOC.md new file mode 100644 index 00000000..cd284601 --- /dev/null +++ b/content/cuda/docs/ptx-cvt/DOC.md @@ -0,0 +1,599 @@ +--- +name: ptx-cvt +description: Convert a value from one type to another. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.21. Data Movement and Conversion Instructions:cvt + +--- +title: "9.7.9.21. Data Movement and Conversion Instructions:cvt" +section: 9.7.9.21 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.21. Data Movement and Conversion Instructions:cvt + + +`cvt` + +Convert a value from one type to another. + +Syntax + +cvt{.irnd}{.ftz}{.sat}.dtype.atype d, a; // integer rounding + cvt{.frnd}{.ftz}{.sat}.dtype.atype d, a; // fp rounding + + cvt.frnd2{.relu}{.satfinite}.f16.f32 d, a; + cvt.frnd2{.relu}{.satfinite}.f16x2.f32 d, a, b; + cvt.rs{.relu}{.satfinite}.f16x2.f32 d, a, b, rbits; + + cvt.frnd2{.relu}{.satfinite}.bf16.f32 d, a; + cvt.frnd2{.relu}{.satfinite}.bf16x2.f32 d, a, b; + cvt.rs{.relu}{.satfinite}.bf16x2.f32 d, a, b, rbits; + + cvt.rna{.satfinite}.tf32.f32 d, a; + cvt.frnd2{.satfinite}{.relu}.tf32.f32 d, a; + + cvt.rn.satfinite{.relu}.f8x2type.f32 d, a, b; + cvt.rn.satfinite{.relu}.f8x2type.fp16x2 d, a; + cvt.rn.{.relu}.f16x2.f8x2type d, a; + cvt.rs{.relu}.satfinite.f8x4type.f32 d, {a, b, e, f}, rbits; + + cvt.rn.satfinite{.relu}.f4x2type.f32 d, a, b; + cvt.rn.satfinite{.relu}.f4x2type.fp16x2type d, a; + cvt.rn{.relu}.f16x2.f4x2type d, a; + cvt.rs{.relu}.satfinite.f4x4type.f32 d, {a, b, e, f}, rbits; + + cvt.rn.satfinite{.relu}.f6x2type.f32 d, a, b; + cvt.rn.satfinite{.relu}.f6x2type.fp16x2type d, a; + cvt.rn{.relu}.f16x2.f6x2type d, a; + cvt.rs{.relu}.satfinite.f6x4type.f32 d, {a, b, e, f}, rbits; + + cvt.frnd3{.satfinite}.ue8m0x2.f32 d, a, b; + cvt.frnd3{.satfinite}.ue8m0x2.bf16x2 d, a; + cvt.rn.bf16x2.ue8m0x2 d, a; + + cvt.rn.satfinite{.relu}{.scaled::n2::ue8m0}.s2f6x2.f32 d, a, b{, scale-factor}; + cvt.rn.satfinite{.relu}{.scaled::n2::ue8m0}.s2f6x2.bf16x2 d, a{, scale-factor}; + cvt.rn{.satfinite}{.relu}{.scaled::n2::ue8m0}.bf16x2.s2f6x2 d, a{, scale-factor}; + + .irnd = { .rni, .rzi, .rmi, .rpi }; + .frnd = { .rn, .rz, .rm, .rp }; + .frnd2 = { .rn, .rz }; + .frnd3 = { .rz, .rp }; + .dtype = .atype = { .u8, .u16, .u32, .u64, + .s8, .s16, .s32, .s64, + .bf16, .f16, .f32, .f64 }; + .f8x2type = { .e4m3x2, .e5m2x2 }; + .f4x2type = { .e2m1x2 }; + .f6x2type = { .e2m3x2, .e3m2x2 }; + .f4x4type = { .e2m1x4 }; + .f8x4type = { .e4m3x4, .e5m2x4 }; + .f6x4type = { .e2m3x4, .e3m2x4 }; + .fp16x2type = { .f16x2, .bf16x2 }; + +Description + +Convert between different types and sizes. + +For `.f16x2` and `.bf16x2` instruction type, two inputs `a` and `b` of `.f32` type are converted into `.f16` or `.bf16` type and the converted values are packed in the destination register `d`, such that the value converted from input `a` is stored in the upper half of `d` and the value converted from input `b` is stored in the lower half of `d` + +For `.f16x2` instruction type, destination operand `d` has `.f16x2` or `.b32` type. For `.bf16` instruction type, operand `d` has `.b16` type. For `.bf16x2` instruction type, operand `d` has `.b32` type. For `.tf32` instruction type, operand `d` has `.b32` type. + +When converting to `.e4m3x2`/`.e5m2x2` data formats, the destination operand `d` has `.b16` type. When converting two `.f32` inputs to `.e4m3x2`/`.e5m2x2`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from input `a` is stored in the upper 8 bits of `d` and the value converted from input `b` is stored in the lower 8 bits of `d`. When converting an `.f16x2`/`.bf16x2` input to `.e4m3x2`/ `.e5m2x2`, each `.f16`/`.bf16` input from operand `a` is converted to the specified format. The converted values are packed in the destination operand `d` such that the value converted from the upper 16 bits of input `a` is stored in the upper 8 bits of `d` and the value converted from the lower 16 bits of input `a` is stored in the lower 8 bits of `d`. + +When converting from `.e4m3x2`/`.e5m2x2` to `.f16x2`, source operand `a` has `.b16` type. Each 8-bit input value in operand `a` is converted to `.f16` type. The converted values are packed in the destination operand `d` such that the value converted from the upper 8 bits of `a` is stored in the upper 16 bits of `d` and the value converted from the lower 8 bits of `a` is stored in the lower 16 bits of `d`. + +When converting to `.e2m1x2` data formats, the destination operand `d` has `.b8` type. When converting two `.f32` inputs to `.e2m1x2`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from input `a` is stored in the upper 4 bits of `d` and the value converted from input `b` is stored in the lower 4 bits of `d`. When converting an `.f16x2`/`.bf16x2` input to `.e2m1x2`, each `.f16`/`.bf16` input from operand `a` is converted to the specified format. The converted values are packed in `d` so that the value from the upper 16 bits of `a` is stored in the upper 4 bits of `d`, and the value from the lower 16 bits of `a` is stored in the lower 4 bits of `d`. + +When converting from `.e2m1x2` to `.f16x2`, source operand `a` has `.b8` type. Each 4-bit input value in operand `a` is converted to `.f16` type. The converted values are packed in the destination operand `d` such that the value converted from the upper 4 bits of `a` is stored in the upper 16 bits of `d` and the value converted from the lower 4 bits of `a` is stored in the lower 16 bits of `d`. + +When converting to `.e2m1x4` data format, the destination operand `d` has `.b16` type. When converting four `.f32` inputs to `.e2m1x4`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from inputs `a`, `b`, `e`, `f` are stored in each 4 bits starting from upper bits of `d`. + +When converting to `.e2m3x2`/`.e3m2x2` data formats, the destination operand `d` has `.b16` type. When converting two `.f32` inputs to `.e2m3x2`/`.e3m2x2`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from input `a` is stored in the upper 8 bits of `d` with 2 MSB bits padded with zeros and the value converted from input `b` is stored in the lower 8 bits of `d` with 2 MSB bits padded with zeros. When converting an `.f16x2`/`.bf16x2` input to `.e2m3x2`/`.e3m2x2`, each `.f16`/`.bf16` input from operand `a` is converted to the specified format. The converted values are packed in the destination operand `d` so that the value from the upper 16 bits of input `a` is stored in the upper 8 bits of `d` with 2 MSB bits padded with zeros, and the value from the lower 16 bits of input `a` is stored in the lower 8 bits of `d` with 2 MSB bits padded with zeros. + +When converting from `.e2m3x2`/`.e3m2x2` to `.f16x2`, source operand `a` has `.b16` type. Each 8-bit input value with 2 MSB bits 0 in operand `a` is converted to `.f16` type. The converted values are packed in the destination operand `d` such that the value converted from the upper 8 bits of `a` is stored in the upper 16 bits of `d` and the value converted from the lower 8 bits of `a` is stored in the lower 16 bits of `d`. + +When converting to `.e5m2x4`/`.e4m3x4`/`.e3m2x4`/`.e2m3x4` data format, the destination operand `d` has `.b32` type. When converting four `.f32` inputs to `.e5m2x4`/`.e4m3x4`/`.e3m2x4`/`.e2m3x4`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from inputs `a`, `b`, `e`, `f` are stored in each 8 bits starting from upper bits of `d`. For `.e3m2x4`/`.e2m3x4`, each 8-bit output will have 2 MSB bits padded with zeros. + +When converting to `.ue8m0x2` data formats, the destination operand `d` has `.b16` type. When converting two `.f32` or two packed `.bf16` inputs to `.ue8m0x2`, each input is converted to the specified format, and the converted values are packed in the destination operand `d` such that the value converted from input `a` is stored in the upper 8 bits of `d` and the value converted from input `b` is stored in the lower 8 bits of `d`. + +When converting from `.ue8m0x2` to `.bf16x2`, source operand `a` has `.b16` type. Each 8-bit input value in operand `a` is converted to `.bf16` type. The converted values are packed in the destination operand `d` such that the value converted from the upper 8 bits of `a` is stored in the upper 16 bits of `d` and the value converted from the lower 8 bits of `a` is stored in the lower 16 bits of `d`. + +When converting to `.s2f6x2` data formats, the destination operand `d` has `.b16` type. When converting two `.f32` inputs to `.s2f6x2`, each input is converted to the `.s2f6` value, and the converted values are packed in the destination operand `d` such that the value converted from input `a` is stored in the upper 8 bits of `d` and the value converted from input `b` is stored in the lower 8 bits of `d`. When converting from `.bf16x2`, each input packed in operand `a` is converted to `.s2f6` value and converted values are packed in the destination operand `d` such that value converted from upper 8 bits of input `a` is stored in upper 8 bits of operand `d` and the value converted from lower 8 bits of input `a` is stored in lower 8 bits of operand `d`. Optional operand `scale-factor` has type `.b16` and stores two packed scaling factors of type `.ue8m0`. For down conversion, inputs are divided by `scale-factor` and then conversion is performed. The scaling factor of input `a`/`.bf16` input from upper 16 bits of `a` is stored in the upper 8 bits of operand `scale-factor` and the scaling factor of input `b`/`.bf16` input from lower 16 bits of `a` is stored in the lower 8 bits of operand `scale-factor`. If not specified explicitly, value of `scale-factor` will be assumed to be `0x7f7f`, that is, assumed as value `1` for both input scale factors. + +When converting from `.s2f6x2` to `.bf16x2`, source operand `a` has `.b16` type. Each 8-bit input value in operand `a` is converted to `.bf16` type. The converted values are packed in the destination operand `d` such that the value converted from the upper 8 bits of `a` is stored in the upper 16 bits of `d` and the value converted from the lower 8 bits of `a` is stored in the lower 16 bits of `d`. Optional operand `scale-factor` has type `.b16` and stores two packed scaling factors of type `.ue8m0`. For up-conversion, inputs are converted to destination type and then multiplied by `scale-factor`. The scaling factor of `.s2f6` input from upper 8 bits of `a` is stored in the upper 8 bits of operand `scale-factor` and the scaling factor of `.s2f6` input from lower 8 bits of `a` is stored in the lower 8 bits of operand `scale-factor`. If not specified explicitly, value of `scale-factor` will be assumed to be `0x7f7f`, that is, assumed as value `1` for both input scale factors. + +Optional qualifier `.scaled::n2::ue8m0` specifies that the instruction uses packed scale-factor with 2 scale values of `ue8m0` type. Operand `scale-factor` and qualifier `.scaled::n2::ue8m0` must be used together. + +`rbits` is a `.b32` type register operand used for providing random bits for `.rs` rounding mode. + +When converting to `.f16x2`, two 16-bit values are provided from `rbits` where 13 LSBs from upper 16-bits are used as random bits for operand `a` with 3 MSBs are 0 and 13 LSBs from lower 16-bits are used as random bits for operand `b` with 3 MSBs are 0. + +When converting to `.bf16x2`, two 16-bit values are provided from `rbits` where upper 16-bits are used as random bits for operand `a` and lower 16-bits are used as random bits for operand `b`. + +When converting to `.e4m3x4`/`.e5m2x4`/`.e2m3x4`/`.e3m2x4`, two 16-bit values are provided from `rbits` where lower 16-bits are used for operands `e`, `f` and upper 16 bits are used for operands `a`, `b`. + +When converting to `.e2m1x4`, two 16-bit values are provided from `rbits` where lower 8-bits from both 16-bits half of `rbits` are used for operands `e`, `f` and upper 8-bits from both 16-bits half of `rbits` are used for operands `a`, `b`. + +Rounding modifier is mandatory in all of the following cases: + +* float-to-float conversions, when destination type is smaller than source type + + * All float-to-int conversions + + * All int-to-float conversions + + * All conversions involving `.f16x2`, `.e4m3x2, .e5m2x2,`, `.bf16x2`, `.tf32`, `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e4m3x4`, `.e5m2x4`, `.e2m1x4`, `.e2m3x4`, `.e3m2x4`, `.s2f6x2` and `.ue8m0x2` instruction types. + +`.satfinite` modifier is only supported for conversions involving the following types: + +* `.e4m3x2`, `.e5m2x2`, `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e4m3x4`, `.e5m2x4`, `.e2m1x4`, `.e2m3x4`, `.e3m2x4`, `.s2f6x2` destination types. `.satfinite` modifier is mandatory for such conversions. + + * `.f16`, `.bf16`, `.f16x2`, `.bf16x2`, `.tf32`, `.ue8m0x2` as destination types. + +Semantics + +if (/* inst type is .f16x2 or .bf16x2 */) { + d[31:16] = convert(a); + d[15:0] = convert(b); + } else if (/* inst destination type is .e5m2x2 or .e4m3x2 or .ue8m0x2 */) { + if (/* inst source type is .f32 */) { + d[15:8] = convert(a); + d[7:0] = convert(b); + } else { + d[15:8] = convert(a[31:16]); + d[7:0] = convert(a[15:0]); + } + } else if (/* inst destination type is .s2f6x2 */) { + if (/* inst source type is .f32 */) { + d[15:8] = convert(a / scale-factor[15:8]); + d[7:0] = convert(b / scale-factor[7:0]); + } else { + d[15:8] = convert(a[15:8] / scale-factor[15:8]); + d[7:0] = convert(a[7:0] / scale-factor[7:0]); + } + } else if (/* inst source type is .s2f6x2 */) { + d[31:16] = convert(a[15:8]) * scale-factor[15:8]; + d[15:0] = convert(a[7:0]) * scale-factor[7:0]; + } else if (/* inst destination type is .e2m1x2 */) { + if (/* inst source type is .f32 */) { + d[7:4] = convert(a); + d[3:0] = convert(b); + } else { + d[7:4] = convert(a[31:16]); + d[3:0] = convert(a[15:0]); + } + } else if (/* inst destination type is .e2m3x2 or .e3m2x2 */) { + if (/* inst source type is .f32 */) { + d[15:14] = 0; + d[13:8] = convert(a); + d[7:6] = 0; + d[5:0] = convert(b); + } else { + d[15:14] = 0; + d[13:8] = convert(a[31:16]); + d[7:6] = 0; + d[5:0] = convert(a[15:0]); + } + } else if (/* inst destination type is .e2m1x4 */) { + d[15:12] = convert(a); + d[11:8] = convert(b); + d[7:4] = convert(e); + d[3:0] = convert(f); + } else if (/* inst destination type is .e4m3x4 or .e5m2x4 */) { + d[31:24] = convert(a); + d[23:16] = convert(b); + d[15:8] = convert(e); + d[7:0] = convert(f); + } else if (/* inst destination type is .e2m3x4 or .e3m2x4 */) { + d[31:30] = 0; + d[29:24] = convert(a); + d[23:22] = 0; + d[21:16] = convert(b); + d[15:14] = 0; + d[13:8] = convert(e); + d[7:6] = 0; + d[5:0] = convert(f); + } else { + d = convert(a); + } + +// Random bits `rbits` semantics for `.rs` rounding: + +1. Destination type `.f16`: Refer [Figure 38](<#cvt-rs-rbits-layout-f16>) for random bits layout details. + +![_images/cvt-rs-rbits-layout-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/cvt-rs-rbits-layout-f16.png) + +Figure 38 Random bits layout for `.rs` rounding with `.f16` destination type + + 2. Destination type `.bf16`: Refer [Figure 39](<#cvt-rs-rbits-layout-bf16>) for random bits layout details. + +![_images/cvt-rs-rbits-layout-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/cvt-rs-rbits-layout-bf16.png) + +Figure 39 Random bits layout for `.rs` rounding with `.bf16` destination type + + 3. Destination type `.e2m1x4`: Refer [Figure 40](<#cvt-rs-rbits-layout-f4>) for random bits layout details. + +![_images/cvt-rs-rbits-layout-f4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/cvt-rs-rbits-layout-f4.png) + +Figure 40 Random bits layout for `.rs` rounding with `.e2m1x4` destination type + + 4. Destination type `.e5m2x4`, `.e4m3x4`, `.e3m2x4`, `.e2m3x4`: Refer [Figure 41](<#cvt-rs-rbits-layout-f8-f6>) for random bits layout details. + +![_images/cvt-rs-rbits-layout-f8-f6.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/cvt-rs-rbits-layout-f8-f6.png) + +Figure 41 Random bits layout for `.rs` rounding with `.e5m2x4`/`.e4m3x4`/`.e3m2x4`/`.e2m3x4` destination type + +Integer Notes + +Integer rounding is required for float-to-integer conversions, and for same-size float-to-float conversions where the value is rounded to an integer. Integer rounding is illegal in all other instances. + +Integer rounding modifiers: + +`.rni` + + +round to nearest integer, choosing even integer if source is equidistant between two integers + +`.rzi` + + +round to nearest integer in the direction of zero + +`.rmi` + + +round to nearest integer in direction of negative infinity + +`.rpi` + + +round to nearest integer in direction of positive infinity + +In float-to-integer conversions, depending upon conversion types, `NaN` input results in following value: + +1. Zero if source is not `.f64` and destination is not `.s64`, `.u64`. + + 2. Otherwise 1 << (BitWidth(dst) - 1) corresponding to the value of (`MAXINT` >> 1) + 1 for unsigned type or `MININT` for signed type. + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +For `cvt.ftz.dtype.f32` float-to-integer conversions and `cvt.ftz.f32.f32` float-to-float conversions with integer rounding, subnormal inputs are flushed to sign-preserving zero. Modifier `.ftz` can only be specified when either `.dtype` or `.atype` is `.f32` and applies only to single precision (`.f32`) inputs and results. + +`sm_1x` + + +For `cvt.ftz.dtype.f32` float-to-integer conversions and `cvt.ftz.f32.f32` float-to-float conversions with integer rounding, subnormal inputs are flushed to sign-preserving zero. The optional `.ftz` modifier may be specified in these cases for clarity. + +**Note:** In PTX ISA versions 1.4 and earlier, the `cvt` instruction did not flush single-precision subnormal inputs or results to zero if the destination type size was 64-bits. The compiler will preserve this behavior for legacy PTX code. + +Saturation modifier: + +`.sat` + + +For integer destination types, `.sat` limits the result to `MININT..MAXINT` for the size of the operation. Note that saturation applies to both signed and unsigned integer types. + +The saturation modifier is allowed only in cases where the destination type’s value range is not a superset of the source type’s value range; i.e., the `.sat` modifier is illegal in cases where saturation is not possible based on the source and destination types. + +For float-to-integer conversions, the result is clamped to the destination range by default; i.e, `.sat` is redundant. + +Floating Point Notes + +Floating-point rounding is required for float-to-float conversions that result in loss of precision, and for integer-to-float conversions. Floating-point rounding is illegal in all other instances. + +Floating-point rounding modifiers: + +`.rn` + + +rounding to nearest, with ties to even + +`.rna` + + +rounding to nearest, with ties away from zero + +`.rz` + + +rounding toward zero + +`.rm` + + +rounding toward negative infinity + +`.rp` + + +rounding toward positive infinity + +`.rs` + + +Stochastic rounding is achieved through the use of the supplied random bits. Operation’s result is rounded in the direction toward zero or away from zero based on the carry out of the integer addition of the supplied random bits (`rbits`) to the truncated off (discarded) bits of mantissa from the input. + +A floating-point value may be rounded to an integral value using the integer rounding modifiers (see Integer Notes). The operands must be of the same size. The result is an integral value, stored in floating-point format. + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. Modifier `.ftz` may be specified to flush single-precision subnormal inputs and results to sign-preserving zero. Modifier `.ftz` can only be specified when either `.dtype` or `.atype` is `.f32` and applies only to single precision (`.f32`) inputs and results. + +`sm_1x` + + +Single-precision subnormal inputs and results are flushed to sign-preserving zero. The optional `.ftz` modifier may be specified in these cases for clarity. + +**Note:** In PTX ISA versions 1.4 and earlier, the `cvt` instruction did not flush single-precision subnormal inputs or results to zero if either source or destination type was `.f64`. The compiler will preserve this behavior for legacy PTX code. Specifically, if the PTX ISA version is 1.4 or earlier, single-precision subnormal inputs and results are flushed to sign-preserving zero only for `cvt.f32.f16`, `cvt.f16.f32`, and `cvt.f32.f32` instructions. + +Saturation modifier: + +`.sat`: + + +For floating-point destination types, `.sat` limits the result to the range [0.0, 1.0]. `NaN` results are flushed to positive zero. Applies to `.f16`, `.f32`, and `.f64` types. + +`.relu`: + + +For `.f16`, `.f16x2`, `.bf16`, `.bf16x2`, `.e4m3x2`, `.e5m2x2`, `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e4m3x4`, `.e5m2x4`, `.e2m1x4`, `.e2m3x4`, `.e3m2x4`, `.s2f6x2` and `.tf32` destination types, `.relu` clamps the result to 0 if negative. `NaN` results are converted to canonical `NaN`. + +`.satfinite`: + + +For `.f16`, `.f16x2`, `.bf16`, `.bf16x2`, `.e4m3x2`, `.e5m2x2`, `.ue8m0x2`, `.e4m3x4`, `.e5m2x4` and `.tf32` destination formats, if the input value is `NaN`, then the result is `NaN` in the specified destination format. For `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e2m1x4`, `.e2m3x4`, `.e3m2x4`, `.s2f6x2` destination formats `NaN` results are converted to positive _MAX_NORM_. If the absolute value of input (ignoring sign) is greater than _MAX_NORM_ of the specified destination format, then the result is sign-preserved _MAX_NORM_ of the destination format and a positive _MAX_NORM_ in `.ue8m0x2` for which the destination sign is not supported. + +Notes + +A source register wider than the specified type may be used, except when the source operand has `.bf16` or `.bf16x2` format. The lower `n` bits corresponding to the instruction-type width are used in the conversion. See [Operand Size Exceeding Instruction-Type Size](<#operand-size-exceeding-instruction-type-size>) for a description of these relaxed type-checking rules. + +A destination register wider than the specified type may be used, except when the destination operand has `.bf16`, `.bf16x2` or `.tf32` format. The result of conversion is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned, bit-size, and floating-point types. See [Operand Size Exceeding Instruction-Type Size](<#operand-size-exceeding-instruction-type-size>) for a description of these relaxed type-checking rules. + +For `cvt.f32.bf16`, `NaN` input yields unspecified `NaN`. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +`.relu` modifier and {`.f16x2`, `.bf16`, `.bf16x2`, `.tf32`} destination formats introduced in PTX ISA version 7.0. + +`cvt.f32.bf16` introduced in PTX ISA version 7.1. + +`cvt.bf16.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64/bf16}`, `cvt.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64}.bf16`, and `cvt.tf32.f32.{relu}.{rn/rz}` introduced in PTX ISA version 7.8. + +`.ftz` qualifier for `cvt.f32.bf16` introduced in PTX ISA version 7.8. + +`cvt` with `.e4m3x2`/`.e5m2x2` for `sm_90` or higher introduced in PTX ISA version 7.8. + +`cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}` for `sm_90` or higher introduced in PTX ISA version 7.8. + +`cvt` with `.e4m3x2`/`.e5m2x2` for `sm_89` introduced in PTX ISA version 8.1. + +`cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}` for `sm_89` introduced in PTX ISA version 8.1. + +`cvt.satfinite.{f16, bf16, f16x2, bf16x2, tf32}.f32` introduced in PTX ISA version 8.1. + +`cvt.{rn/rz}.satfinite.tf32.f32` introduced in PTX ISA version 8.6. + +`cvt.rn.satfinite{.relu}.{e2m1x2/e2m3x2/e3m2x2/ue8m0x2}.f32` introduced in PTX ISA version 8.6. + +`cvt.rn{.relu}.f16x2.{e2m1x2/e2m3x2/e3m2x2}` introduced in PTX ISA version 8.6. + +`cvt.{rp/rz}{.satfinite}{.relu}.ue8m0x2.bf16x2` introduced in PTX ISA version 8.6. + +`cvt.{rz/rp}.satfinite.ue8m0x2.f32` introduced in PTX ISA version 8.6. + +`cvt.rn.bf16x2.ue8m0x2` introduced in PTX ISA version 8.6. + +`.rs` rounding mode introduced in PTX ISA version 8.7. + +`cvt.rs{.e2m1x4/.e4m3x4/.e5m2x4/.e3m2x4/.e2m3x4}.f32` introduced in PTX ISA version 8.7. + +`cvt.rn.satfinite{.relu}{.e5m2x2/.e4m3x2}{.bf16x2}` introduced in PTX ISA version 9.1. + +`cvt.rn.satfinite{.relu}{.e2m3x2/.e3m2x2/.e2m1x2}{.f16x2/.bf16x2}` introduced in PTX ISA version 9.1. + +`cvt` with `.s2f6x2` instruction type introduced in PTX ISA version 9.1. + +Target ISA Notes + +`cvt` to or from `.f64` requires `sm_13` or higher. + +`.relu` modifier and {`.f16x2`, `.bf16`, `.bf16x2`, `.tf32`} destination formats require `sm_80` or higher. + +`cvt.f32.bf16` requires `sm_80` or higher. + +`cvt.bf16.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64/bf16}`, `cvt.{u8/s8/u16/s16/u32/s32/u64/s64/f16/f64}.bf16`, and `cvt.tf32.f32.{relu}.{rn/rz}` require `sm_90` or higher. + +`.ftz` qualifier for `cvt.f32.bf16` requires `sm_90` or higher. + +`cvt` with `.e4m3x2`/`.e5m2x2` requires `sm89` or higher. + +`cvt.satfinite.{e4m3x2, e5m2x2}.{f32, f16x2}` requires `sm_89` or higher. + +`cvt.{rn/rz}.satfinite.tf32.f32` requires `sm_100` or higher. + +`cvt.rn.satfinite{.relu}.{e2m1x2/e2m3x2/e3m2x2/ue8m0x2}.f32` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +`cvt.rn{.relu}.f16x2.{e2m1x2/e2m3x2/e3m2x2}` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +`cvt.{rz/rp}{.satfinite}{.relu}.ue8m0x2.bf16x2` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +`cvt.{rz/rp}.satfinite.ue8m0x2.f32` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +`cvt.rn.bf16x2.ue8m0x2` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + +`.rs` rounding mode is supported on following architectures: + +* `sm_100a` + + * `sm_103a` + +`cvt.rs{.e2m1x4/.e4m3x4/.e5m2x4/.e3m2x4/.e2m3x4}.f32` is supported on following architectures: + +* `sm_100a` + + * `sm_103a` + +`cvt.rn.satfinite{.relu}{.e5m2x2/.e4m3x2}{.bf16x2}` is supported on following family-specific architectures: + +* `sm_100f` or higher in the same family + + * `sm_110f` or higher in the same family + + * `sm_120f` or higher in the same family + +`cvt.rn.satfinite{.relu}{.e2m3x2/.e3m2x2/.e2m1x2}{.f16x2/.bf16x2}` is supported on following family-specific architectures: + +* `sm_100f` or higher in the same family + + * `sm_110f` or higher in the same family + + * `sm_120f` or higher in the same family + +`cvt` with `.s2f6x2` instruction type is supported on following architectures: + +* `sm_100a` + + * `sm_103a` + + * `sm_110a` + + * `sm_120a` + + * `sm_121a` + +Examples + +cvt.f32.s32 f,i; + cvt.s32.f64 j,r; // float-to-int saturates by default + cvt.rni.f32.f32 x,y; // round to nearest int, result is fp + cvt.f32.f32 x,y; // note .ftz behavior for sm_1x targets + cvt.rn.relu.f16.f32 b, f; // result is saturated with .relu saturation mode + cvt.rz.f16x2.f32 b1, f, f1; // convert two fp32 values to packed fp16 outputs + cvt.rn.relu.satfinite.f16x2.f32 b1, f, f1; // convert two fp32 values to packed fp16 outputs with .relu saturation on each output + cvt.rn.bf16.f32 b, f; // convert fp32 to bf16 + cvt.rz.relu.satfinite.bf16.f3 2 b, f; // convert fp32 to bf16 with .relu and .satfinite saturation + cvt.rz.satfinite.bf16x2.f32 b1, f, f1; // convert two fp32 values to packed bf16 outputs + cvt.rn.relu.bf16x2.f32 b1, f, f1; // convert two fp32 values to packed bf16 outputs with .relu saturation on each output + cvt.rna.satfinite.tf32.f32 b1, f; // convert fp32 to tf32 format + cvt.rn.relu.tf32.f32 d, a; // convert fp32 to tf32 format + cvt.f64.bf16.rp f, b; // convert bf16 to f64 format + cvt.bf16.f16.rz b, f // convert f16 to bf16 format + cvt.bf16.u64.rz b, u // convert u64 to bf16 format + cvt.s8.bf16.rpi s, b // convert bf16 to s8 format + cvt.bf16.bf16.rpi b1, b2 // convert bf16 to corresponding int represented in bf16 format + cvt.rn.satfinite.e4m3x2.f32 d, a, b; // convert a, b to .e4m3 and pack as .e4m3x2 output + cvt.rn.relu.satfinite.e5m2x2.f16x2 d, a; // unpack a and convert the values to .e5m2 outputs with .relu + // saturation on each output and pack as .e5m2x2 + cvt.rn.f16x2.e4m3x2 d, a; // unpack a, convert two .e4m3 values to packed f16x2 output + cvt.rn.satfinite.tf32.f32 d, a; // convert fp32 to tf32 format + cvt.rn.relu.f16x2.e2m1x2 d, a; // unpack a, convert two .e2m1 values to packed f16x2 output + cvt.rn.satfinite.e2m3x2.f32 d, a, b; // convert a, b to .e2m3 and pack as .e2m3x2 output + cvt.rn.relu.f16x2.e3m2x2 d, a; // unpack a, convert two .e3m2 values to packed f16x2 output + + cvt.rs.f16x2.f32 d, a, b, rbits; // convert 2 fp32 values to packed fp16 with applying .rs rounding + cvt.rs.satfinite.e2m1x4.f32 d, {a, b, e, f}, rbits; // convert 4 fp32 values to packed 4 e2m1 values with applying .rs rounding + + cvt.rn.satfinite.relu.e2m1x2type.f16x2 d, a; // unpack a and covert to two .e2m1 values + cvt.rn.satfinite.e2m3x2type.bf16x2 d, a; // unpack a and covert to two .e2m3 values + + // Convert 2 f32 values to s2f6 after applying scale factor for dividing the value + cvt.rn.satfinite.scaled::n2::ue8m0.s2f6x2.f32 d, a, b, scale-factor; \ No newline at end of file diff --git a/content/cuda/docs/ptx-cvta/DOC.md b/content/cuda/docs/ptx-cvta/DOC.md new file mode 100644 index 00000000..16dcaa33 --- /dev/null +++ b/content/cuda/docs/ptx-cvta/DOC.md @@ -0,0 +1,87 @@ +--- +name: ptx-cvta +description: Convert address from `.const`, [Kernel Function Parameters](<#kernel-function-parameters>) + (`.param`), `.global`, `.local`, or `.shared` state space to generic, or vice-versa. + Take the generic address... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.20. Data Movement and Conversion Instructions:cvta + +--- +title: "9.7.9.20. Data Movement and Conversion Instructions:cvta" +section: 9.7.9.20 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.20. Data Movement and Conversion Instructions:cvta + + +`cvta` + +Convert address from `.const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `.global`, `.local`, or `.shared` state space to generic, or vice-versa. Take the generic address of a variable declared in `.const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `.global`, `.local`, or `.shared` state space. + +Syntax + +// convert const, global, local, or shared address to generic address + cvta.space.size p, a; // source address in register a + cvta.space.size p, var; // get generic address of var + cvta.space.size p, var+imm; // generic address of var+offset + + // convert generic address to const, global, local, or shared address + cvta.to.space.size p, a; + + .space = { .const, .global, .local, .shared{::cta, ::cluster}, .param{::entry} }; + .size = { .u32, .u64 }; + +Description + +Convert a `const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `global`, `local`, or `shared` address to a generic address, or vice-versa. The source and destination addresses must be the same size. Use `cvt.u32.u64` or `cvt.u64.u32` to truncate or zero-extend addresses. + +For variables declared in `.const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `.global`, `.local`, or `.shared` state space, the generic address of the variable may be taken using `cvta`. The source is either a register or a variable defined in `const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `global`, `local`, or `shared` memory with an optional offset. + +When converting a generic address into a `const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `global`, `local`, or `shared` address, the resulting address is undefined in cases where the generic address does not fall within the address window of the specified state space. A program may use `isspacep` to guard against such incorrect behavior. + +For `cvta` with `.shared` state space, the address must belong to the space specified by `::cta` or `::cluster` sub-qualifier, otherwise the behavior is undefined. If no sub-qualifier is specified with `.shared` state space, then `::cta` is assumed by default. + +If `.param` is specified without any sub-qualifiers then it defaults to `.param::entry`. For `.param{::entry}` state space, operand `a` must be a kernel parameter address, otherwise behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +`cvta.const` and `cvta.to.const` introduced in PTX ISA version 3.1. + +`cvta.param` and `cvta.to.param` introduced in PTX ISA version 7.7. + +**Note:** The current implementation does not allow generic pointers to `const` space variables in programs that contain pointers to constant buffers passed as kernel parameters. + +Support for `::cta` and `::cluster` sub-qualifiers introduced in PTX ISA version 7.8. + +Support for sub-qualifier `::entry` on `.param` space introduced in PTX ISA version 8.3. + +Target ISA Notes + +`cvta` requires `sm_20` or higher. + +`cvta.param{::entry}` and `cvta.to.param{::entry}` requires `sm_70` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Examples + +cvta.const.u32 ptr,cvar; + cvta.local.u32 ptr,lptr; + cvta.shared::cta.u32 p,As+4; + cvta.shared::cluster.u32 ptr, As; + cvta.to.global.u32 p,gptr; + cvta.param.u64 ptr,pvar; + cvta.to.param::entry.u64 epptr, ptr; \ No newline at end of file diff --git a/content/cuda/docs/ptx-cvtpack/DOC.md b/content/cuda/docs/ptx-cvtpack/DOC.md new file mode 100644 index 00000000..9b79487f --- /dev/null +++ b/content/cuda/docs/ptx-cvtpack/DOC.md @@ -0,0 +1,92 @@ +--- +name: ptx-cvtpack +description: Convert two integer values from one integer type to another and pack + the results. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.22. Data Movement and Conversion Instructions:cvt.pack + +--- +title: "9.7.9.22. Data Movement and Conversion Instructions:cvt.pack" +section: 9.7.9.22 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.22. Data Movement and Conversion Instructions:cvt.pack + + +`cvt.pack` + +Convert two integer values from one integer type to another and pack the results. + +Syntax + +cvt.pack.sat.convertType.abType d, a, b; + .convertType = { .u16, .s16 } + .abType = { .s32 } + + cvt.pack.sat.convertType.abType.cType d, a, b, c; + .convertType = { .u2, .s2, .u4, .s4, .u8, .s8 } + .abType = { .s32 } + .cType = { .b32 } + +Description + +Convert two 32-bit integers `a` and `b` into specified type and pack the results into `d`. + +Destination `d` is an unsigned 32-bit integer. Source operands `a` and `b` are integers of type `.abType` and the source operand `c` is an integer of type `.cType`. + +The inputs `a` and `b` are converted to values of type specified by `.convertType` with saturation and the results after conversion are packed into lower bits of `d`. + +If operand `c` is specified then remaining bits of `d` are copied from lower bits of `c`. + +Semantics + +ta = a < MIN(convertType) ? MIN(convertType) : a; + ta = a > MAX(convertType) ? MAX(convertType) : a; + tb = b < MIN(convertType) ? MIN(convertType) : b; + tb = b > MAX(convertType) ? MAX(convertType) : b; + + size = sizeInBits(convertType); + td = tb ; + for (i = size; i <= 2 * size - 1; i++) { + td[i] = ta[i - size]; + } + + if (isU16(convertType) || isS16(convertType)) { + d = td; + } else { + for (i = 0; i < 2 * size; i++) { + d[i] = td[i]; + } + for (i = 2 * size; i <= 31; i++) { + d[i] = c[i - 2 * size]; + } + } + +`.sat` modifier limits the converted values to `MIN(convertType)`.. `MAX(convertedType)` (no overflow) if the corresponding inputs are not in the range of datatype specified as `.convertType`. + +PTX ISA Notes + +Introduced in PTX ISA version 6.5. + +Target ISA Notes + +Requires `sm_72` or higher. + +Sub byte types (`.u4`/`.s4` and `.u2`/`.s2`) requires `sm_75` or higher. + +Examples + +cvt.pack.sat.s16.s32 %r1, %r2, %r3; // 32-bit to 16-bit conversion + cvt.pack.sat.u8.s32.b32 %r4, %r5, %r6, 0; // 32-bit to 8-bit conversion + cvt.pack.sat.u8.s32.b32 %r7, %r8, %r9, %r4; // %r7 = { %r5, %r6, %r8, %r9 } + cvt.pack.sat.u4.s32.b32 %r10, %r12, %r13, %r14; // 32-bit to 4-bit conversion + cvt.pack.sat.s2.s32.b32 %r15, %r16, %r17, %r18; // 32-bits to 2-bit conversion \ No newline at end of file diff --git a/content/cuda/docs/ptx-debugging-directivesdwarf/DOC.md b/content/cuda/docs/ptx-debugging-directivesdwarf/DOC.md new file mode 100644 index 00000000..746b091b --- /dev/null +++ b/content/cuda/docs/ptx-debugging-directivesdwarf/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-debugging-directivesdwarf +description: DWARF-format information. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.5.1. Debugging Directives:@@dwarf + +--- +title: "11.5.1. Debugging Directives:@@dwarf" +section: 11.5.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.5.1. Debugging Directives:@@dwarf + + +`@@dwarf` + +DWARF-format information. + +Syntax + +@@DWARF dwarf-string + + dwarf-string may have one of the + .byte byte-list // comma-separated hexadecimal byte values + .4byte int32-list // comma-separated hexadecimal integers in range [0..2^32-1] + .quad int64-list // comma-separated hexadecimal integers in range [0..2^64-1] + .4byte label + .quad label + +PTX ISA Notes + +Introduced in PTX ISA version 1.2. Deprecated as of PTX ISA version 2.0, replaced by `.section` directive. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +@@DWARF .section .debug_pubnames, "", @progbits + @@DWARF .byte 0x2b, 0x00, 0x00, 0x00, 0x02, 0x00 + @@DWARF .4byte .debug_info + @@DWARF .4byte 0x000006b5, 0x00000364, 0x61395a5f, 0x5f736f63 + @@DWARF .4byte 0x6e69616d, 0x63613031, 0x6150736f, 0x736d6172 + @@DWARF .byte 0x00, 0x00, 0x00, 0x00, 0x00 \ No newline at end of file diff --git a/content/cuda/docs/ptx-debugging-directivesfile/DOC.md b/content/cuda/docs/ptx-debugging-directivesfile/DOC.md new file mode 100644 index 00000000..c82925ab --- /dev/null +++ b/content/cuda/docs/ptx-debugging-directivesfile/DOC.md @@ -0,0 +1,62 @@ +--- +name: ptx-debugging-directivesfile +description: Source file name. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.5.3. Debugging Directives:.file + +--- +title: "11.5.3. Debugging Directives:.file" +section: 11.5.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.5.3. Debugging Directives:.file + + +`.file` + +Source file name. + +Syntax + +.file file_index "filename" {, timestamp, file_size} + +Description + +Associates a source filename with an integer index. `.loc` directives reference source files by index. + +`.file` directive allows optionally specifying an unsigned number representing time of last modification and an unsigned integer representing size in bytes of source file. `timestamp` and `file_size` value can be 0 to indicate this information is not available. + +`timestamp` value is in format of C and C++ data type `time_t`. + +`file_size` is an unsigned 64-bit integer. + +The `.file` directive is allowed only in the outermost scope, i.e., at the same level as kernel and device function declarations. + +Semantics + +If timestamp and file size are not specified, they default to 0. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Timestamp and file size introduced in PTX ISA version 3.2. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.file 1 "example.cu" + .file 2 "kernel.cu" + .file 1 "kernel.cu", 1339013327, 64118 \ No newline at end of file diff --git a/content/cuda/docs/ptx-debugging-directivesloc/DOC.md b/content/cuda/docs/ptx-debugging-directivesloc/DOC.md new file mode 100644 index 00000000..c202c7e3 --- /dev/null +++ b/content/cuda/docs/ptx-debugging-directivesloc/DOC.md @@ -0,0 +1,103 @@ +--- +name: ptx-debugging-directivesloc +description: Source file location. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.5.4. Debugging Directives:.loc + +--- +title: "11.5.4. Debugging Directives:.loc" +section: 11.5.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.5.4. Debugging Directives:.loc + + +`.loc` + +Source file location. + +Syntax + +.loc file_index line_number column_position + .loc file_index line_number column_position,function_name label {+ immediate }, inlined_at file_index2 line_number2 column_position2 + +Description + +Declares the source file location (source file, line number, and column position) to be associated with lexically subsequent PTX instructions. `.loc` refers to `file_index` which is defined by a `.file` directive. + +To indicate PTX instructions that are generated from a function that got inlined, additional attribute `.inlined_at` can be specified as part of the `.loc` directive. `.inlined_at` attribute specifies source location at which the specified function is inlined. `file_index2`, `line_number2`, and `column_position2` specify the location at which function is inlined. Source location specified as part of `.inlined_at` directive must lexically precede as source location in `.loc` directive. + +The `function_name` attribute specifies an offset in the DWARF section named `.debug_str`. Offset is specified as `label` expression or `label + immediate` expression where `label` is defined in `.debug_str` section. DWARF section `.debug_str` contains ASCII null-terminated strings that specify the name of the function that is inlined. + +Note that a PTX instruction may have a single associated source location, determined by the nearest lexically preceding .loc directive, or no associated source location if there is no preceding .loc directive. Labels in PTX inherit the location of the closest lexically following instruction. A label with no following PTX instruction has no associated source location. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +`function_name` and `inlined_at` attributes are introduced in PTX ISA version 7.2. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.loc 2 4237 0 + L1: // line 4237, col 0 of file #2, + // inherited from mov + mov.u32 %r1,%r2; // line 4237, col 0 of file #2 + add.u32 %r2,%r1,%r3; // line 4237, col 0 of file #2 + ... + L2: // line 4239, col 5 of file #2, + // inherited from sub + .loc 2 4239 5 + sub.u32 %r2,%r1,%r3; // line 4239, col 5 of file #2 + .loc 1 21 3 + .loc 1 9 3, function_name info_string0, inlined_at 1 21 3 + ld.global.u32 %r1, [gg]; // Function at line 9 + setp.lt.s32 %p1, %r1, 8; // inlined at line 21 + .loc 1 27 3 + .loc 1 10 5, function_name info_string1, inlined_at 1 27 3 + .loc 1 15 3, function_name .debug_str+16, inlined_at 1 10 5 + setp.ne.s32 %p2, %r1, 18; + @%p2 bra BB2_3; + + .section .debug_str { + info_string0: + .b8 95 // _ + .b8 90 // z + .b8 51 // 3 + .b8 102 // f + .b8 111 // o + .b8 111 // o + .b8 118 // v + .b8 0 + + info_string1: + .b8 95 // _ + .b8 90 // z + .b8 51 // 3 + .b8 98 // b + .b8 97 // a + .b8 114 // r + .b8 118 // v + .b8 0 + .b8 95 // _ + .b8 90 // z + .b8 51 // 3 + .b8 99 // c + .b8 97 // a + .b8 114 // r + .b8 118 // v + .b8 0 + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-debugging-directivessection/DOC.md b/content/cuda/docs/ptx-debugging-directivessection/DOC.md new file mode 100644 index 00000000..c705b322 --- /dev/null +++ b/content/cuda/docs/ptx-debugging-directivessection/DOC.md @@ -0,0 +1,100 @@ +--- +name: ptx-debugging-directivessection +description: PTX section definition. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.5.2. Debugging Directives:.section + +--- +title: "11.5.2. Debugging Directives:.section" +section: 11.5.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.5.2. Debugging Directives:.section + + +`.section` + +PTX section definition. + +Syntax + +.section section_name { dwarf-lines } + + dwarf-lines have the following formats: + .b8 byte-list // comma-separated list of integers + // in range [-128..255] + .b16 int16-list // comma-separated list of integers + // in range [-2^15..2^16-1] + .b32 int32-list // comma-separated list of integers + // in range [-2^31..2^32-1] + label: // Define label inside the debug section + .b64 int64-list // comma-separated list of integers + // in range [-2^63..2^64-1] + .b32 label + .b64 label + .b32 label+imm // a sum of label address plus a constant integer byte + // offset(signed, 32bit) + .b64 label+imm // a sum of label address plus a constant integer byte + // offset(signed, 64bit) + .b32 label1-label2 // a difference in label addresses between labels in + // the same dwarf section (32bit) + .b64 label3-label4 // a difference in label addresses between labels in + // the same dwarf section (64bit) + +PTX ISA Notes + +Introduced in PTX ISA version 2.0, replaces `@@DWARF` syntax. + +label+imm expression introduced in PTX ISA version 3.2. + +Support for `.b16` integers in dwarf-lines introduced in PTX ISA version 6.0. + +Support for defining `label` inside the DWARF section is introduced in PTX ISA version 7.2. + +`label1-label2` expression introduced in PTX ISA version 7.5. + +Negative numbers in dwarf lines introduced in PTX ISA version 7.5. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.section .debug_pubnames + { + .b32 LpubNames_end0-LpubNames_begin0 + LpubNames_begin0: + .b8 0x2b, 0x00, 0x00, 0x00, 0x02, 0x00 + .b32 .debug_info + info_label1: + .b32 0x000006b5, 0x00000364, 0x61395a5f, 0x5f736f63 + .b32 0x6e69616d, 0x63613031, 0x6150736f, 0x736d6172 + .b8 0x00, 0x00, 0x00, 0x00, 0x00 + LpubNames_end0: + } + + .section .debug_info + { + .b32 11430 + .b8 2, 0 + .b32 .debug_abbrev + .b8 8, 1, 108, 103, 101, 110, 102, 101, 58, 32, 69, 68, 71, 32, 52, 46, 49 + .b8 0 + .b32 3, 37, 176, -99 + .b32 info_label1 + .b32 .debug_loc+0x4 + .b8 -11, 11, 112, 97 + .b32 info_label1+12 + .b64 -1 + .b16 -5, -65535 + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-destination-operands/DOC.md b/content/cuda/docs/ptx-destination-operands/DOC.md new file mode 100644 index 00000000..b90bd7a6 --- /dev/null +++ b/content/cuda/docs/ptx-destination-operands/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-destination-operands +description: PTX instructions that produce a single result store the result in the + field denoted by `d` (for destination) in the instruction descriptions. The result + operand is a scalar or vector variable in the r... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.3. Destination Operands + +--- +title: "6.3. Destination Operands" +section: 6.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 6.3. Destination Operands + + +PTX instructions that produce a single result store the result in the field denoted by `d` (for destination) in the instruction descriptions. The result operand is a scalar or vector variable in the register state space. \ No newline at end of file diff --git a/content/cuda/docs/ptx-device-function-parameters/DOC.md b/content/cuda/docs/ptx-device-function-parameters/DOC.md new file mode 100644 index 00000000..5c06cd0e --- /dev/null +++ b/content/cuda/docs/ptx-device-function-parameters/DOC.md @@ -0,0 +1,80 @@ +--- +name: ptx-device-function-parameters +description: PTX ISA version 2.0 extended the use of parameter space to device function + parameters. The most common use is for passing objects by value that do not fit + within a PTX register, such as C structures l... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.6.4. Device Function Parameters + +--- +title: "5.1.6.4. Device Function Parameters" +section: 5.1.6.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.1.6.4. Device Function Parameters + + +PTX ISA version 2.0 extended the use of parameter space to device function parameters. The most common use is for passing objects by value that do not fit within a PTX register, such as C structures larger than 8 bytes. In this case, a byte array in parameter space is used. Typically, the caller will declare a locally-scoped `.param` byte array variable that represents a flattened C structure or union. This will be passed by value to a callee, which declares a `.param` formal parameter having the same size and alignment as the passed argument. + +Example + +// pass object of type struct { double d; int y; }; + .func foo ( .reg .b32 N, .param .align 8 .b8 buffer[12] ) + { + .reg .f64 %d; + .reg .s32 %y; + + ld.param.f64 %d, [buffer]; + ld.param.s32 %y, [buffer+8]; + ... + } + + // code snippet from the caller + // struct { double d; int y; } mystruct; is flattened, passed to foo + ... + .reg .f64 dbl; + .reg .s32 x; + .param .align 8 .b8 mystruct; + ... + st.param.f64 [mystruct+0], dbl; + st.param.s32 [mystruct+8], x; + call foo, (4, mystruct); + ... + +See the section on function call syntax for more details. + +Function input parameters may be read via `ld.param` and function return parameters may be written using `st.param`; it is illegal to write to an input parameter or read from a return parameter. + +Aside from passing structures by value, `.param` space is also required whenever a formal parameter has its address taken within the called function. In PTX, the address of a function input parameter may be moved into a register using the `mov` instruction. Note that the parameter will be copied to the stack if necessary, and so the address will be in the `.local` state space and is accessed via `ld.local` and `st.local` instructions. It is not possible to use `mov` to get the address of or a locally-scoped `.param` space variable. Starting PTX ISA version 6.0, it is possible to use `mov` instruction to get address of return parameter of device function. + +Example + +// pass array of up to eight floating-point values in buffer + .func foo ( .param .b32 N, .param .b32 buffer[32] ) + { + .reg .u32 %n, %r; + .reg .f32 %f; + .reg .pred %p; + + ld.param.u32 %n, [N]; + mov.u32 %r, buffer; // forces buffer to .local state space + Loop: + setp.eq.u32 %p, %n, 0; + @%p bra Done; + ld.local.f32 %f, [%r]; + ... + add.u32 %r, %r, 4; + sub.u32 %n, %n, 1; + bra Loop; + Done: + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-directive-statements/DOC.md b/content/cuda/docs/ptx-directive-statements/DOC.md new file mode 100644 index 00000000..c577d079 --- /dev/null +++ b/content/cuda/docs/ptx-directive-statements/DOC.md @@ -0,0 +1,37 @@ +--- +name: ptx-directive-statements +description: Directive keywords begin with a dot, so no conflict is possible with + user-defined identifiers. The directives in PTX are listed in [Table 1](<#directive-statements-ptx-directives>) + and described in [S... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.3.1. Directive Statements + +--- +title: "4.3.1. Directive Statements" +section: 4.3.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.3.1. Directive Statements + + +Directive keywords begin with a dot, so no conflict is possible with user-defined identifiers. The directives in PTX are listed in [Table 1](<#directive-statements-ptx-directives>) and described in [State Spaces, Types, and Variables](<#state-spaces-types-and-variables>) and [Directives](<#directives>). + +Table 1 PTX Directives `.address_size` | `.explicitcluster` | `.maxnreg` | `.section` +---|---|---|--- +`.alias` | `.extern` | `.maxntid` | `.shared` +`.align` | `.file` | `.minnctapersm` | `.sreg` +`.branchtargets` | `.func` | `.noreturn` | `.target` +`.callprototype` | `.global` | `.param` | `.tex` +`.calltargets` | `.loc` | `.pragma` | `.version` +`.common` | `.local` | `.reg` | `.visible` +`.const` | `.maxclusterrank` | `.reqnctapercluster` | `.weak` +`.entry` | `.maxnctapersm` | `.reqntid` | \ No newline at end of file diff --git a/content/cuda/docs/ptx-discard/DOC.md b/content/cuda/docs/ptx-discard/DOC.md new file mode 100644 index 00000000..fac2ebc1 --- /dev/null +++ b/content/cuda/docs/ptx-discard/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-discard +description: Discard the data at the specified address range and cache level. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.17. Data Movement and Conversion Instructions:discard + +--- +title: "9.7.9.17. Data Movement and Conversion Instructions:discard" +section: 9.7.9.17 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.17. Data Movement and Conversion Instructions:discard + + +`discard` + +Discard the data at the specified address range and cache level. + +Syntax + +discard{.global}.level [a], size; + + .level = { .L2 }; + +Description + +Semantically, this behaves like a weak write of an _unstable indeterminate value_ : reads of memory locations with _unstable indeterminate values_ may return different bit patterns each time until the memory is overwritten. This operation _hints_ to the implementation that data in the specified cache `.level` can be destructively discarded without writing it back to memory. + +The operand `size` is an integer constant that specifies the length in bytes of the address range `[a, a + size)` to write _unstable indeterminate values_ into. The only supported value for the `size` operand is `128`. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the specified address does not fall within the address window of `.global` state space then the behavior is undefined. + +Supported addressing modes for address operand `a` are described in [Addresses as Operands](<#addresses-as-operands>). `a` must be aligned to 128 bytes. + +PTX ISA Notes + +Introduced in PTX ISA version 7.4. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + +discard.global.L2 [ptr], 128; + ld.weak.u32 r0, [ptr]; + ld.weak.u32 r1, [ptr]; + // The values in r0 and r1 may differ! \ No newline at end of file diff --git a/content/cuda/docs/ptx-div/DOC.md b/content/cuda/docs/ptx-div/DOC.md new file mode 100644 index 00000000..1c12bc38 --- /dev/null +++ b/content/cuda/docs/ptx-div/DOC.md @@ -0,0 +1,117 @@ +--- +name: ptx-div +description: Divide one value by another. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.8. Floating Point Instructions:div + +--- +title: "9.7.3.8. Floating Point Instructions:div" +section: 9.7.3.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.8. Floating Point Instructions:div + + +`div` + +Divide one value by another. + +Syntax + +div.approx{.ftz}.f32 d, a, b; // fast, approximate divide + div.full{.ftz}.f32 d, a, b; // full-range approximate divide + div.rnd{.ftz}.f32 d, a, b; // IEEE 754 compliant rounding + div.rnd.f64 d, a, b; // IEEE 754 compliant rounding + + .rnd = { .rn, .rz, .rm, .rp }; + +Description + +Divides `a` by `b`, stores result in `d`. + +Semantics + +d = a / b; + +Notes + +Fast, approximate single-precision divides: + +* `div.approx.f32` implements a fast approximation to divide, computed as `d = a * (1/b)`. For `|b|` in [2-126, 2126], the maximum `ulp` error is 2. For 2126 < `|b|` < 2128, if `a` is infinity, `div.approx.f32` returns `NaN`, otherwise it returns a sign-preserving zero. + + * `div.full.f32` implements a relatively fast, full-range approximation that scales operands to achieve better accuracy, but is not fully IEEE 754 compliant and does not support rounding modifiers. The maximum `ulp` error is 2 across the full range of inputs. + +Divide with IEEE 754 compliant rounding: + +Rounding modifiers (no default): + +`.rn` + + +mantissa LSB rounds to nearest even + +`.rz` + + +mantissa LSB rounds towards zero + +`.rm` + + +mantissa LSB rounds towards negative infinity + +`.rp` + + +mantissa LSB rounds towards positive infinity + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`div.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`div.f64` supports subnormal numbers. + +`div.f32` flushes subnormal inputs and results to sign-preserving zero. + +PTX ISA Notes + +`div.f32` and `div.f64` introduced in PTX ISA version 1.0. + +Explicit modifiers `.approx`, `.full`, `.ftz`, and rounding introduced in PTX ISA version 1.4. + +For PTX ISA version 1.4 and later, one of `.approx`, `.full`, or `.rnd` is required. + +For PTX ISA versions 1.0 through 1.3, `div.f32` defaults to `div.approx.ftz.f32`, and `div.f64` defaults to `div.rn.f64`. + +Target ISA Notes + +`div.approx.f32` and `div.full.f32` supported on all target architectures. + +`div.rnd.f32` requires `sm_20` or higher. + +`div.rn.f64` requires `sm_13` or higher, or `.target map_f64_to_f32`. + +`div.{rz,rm,rp}.f64` requires `sm_20` or higher. + +Examples + +div.approx.ftz.f32 diam,circum,3.14159; + div.full.ftz.f32 x, y, z; + div.rn.f64 xd, yd, zd; \ No newline at end of file diff --git a/content/cuda/docs/ptx-divergence-of-threads-in-control-constructs/DOC.md b/content/cuda/docs/ptx-divergence-of-threads-in-control-constructs/DOC.md new file mode 100644 index 00000000..11ec931f --- /dev/null +++ b/content/cuda/docs/ptx-divergence-of-threads-in-control-constructs/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-divergence-of-threads-in-control-constructs +description: Threads in a CTA execute together, at least in appearance, until they + come to a conditional control construct such as a conditional branch, conditional + function call, or conditional return. If threads... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.5. Divergence of Threads in Control Constructs + +--- +title: "9.5. Divergence of Threads in Control Constructs" +section: 9.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 9.5. Divergence of Threads in Control Constructs + + +Threads in a CTA execute together, at least in appearance, until they come to a conditional control construct such as a conditional branch, conditional function call, or conditional return. If threads execute down different control flow paths, the threads are called _divergent_. If all of the threads act in unison and follow a single control flow path, the threads are called _uniform_. Both situations occur often in programs. + +A CTA with divergent threads may have lower performance than a CTA with uniformly executing threads, so it is important to have divergent threads re-converge as soon as possible. All control constructs are assumed to be divergent points unless the control-flow instruction is marked as uniform, using the `.uni` suffix. For divergent control flow, the optimizing code generator automatically determines points of re-convergence. Therefore, a compiler or code author targeting PTX can ignore the issue of divergent threads, but has the opportunity to improve performance by marking branch points as uniform when the compiler or author can guarantee that the branch point is non-divergent. \ No newline at end of file diff --git a/content/cuda/docs/ptx-document-structure/DOC.md b/content/cuda/docs/ptx-document-structure/DOC.md new file mode 100644 index 00000000..0695b0be --- /dev/null +++ b/content/cuda/docs/ptx-document-structure/DOC.md @@ -0,0 +1,70 @@ +--- +name: ptx-document-structure +description: 'The information in this document is organized into the following Chapters:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 1.4. Document Structure + +--- +title: "1.4. Document Structure" +section: 1.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 1.4. Document Structure + + +The information in this document is organized into the following Chapters: + +* [Programming Model](<#programming-model>) outlines the programming model. + + * [PTX Machine Model](<#ptx-machine-model>) gives an overview of the PTX virtual machine model. + + * [Syntax](<#syntax>) describes the basic syntax of the PTX language. + + * [State Spaces, Types, and Variables](<#state-spaces-types-and-variables>) describes state spaces, types, and variable declarations. + + * [Instruction Operands](<#instruction-operands>) describes instruction operands. + + * [Abstracting the ABI](<#abstracting-abi>) describes the function and call syntax, calling convention, and PTX support for abstracting the _Application Binary Interface (ABI)_. + + * [Instruction Set](<#instruction-set>) describes the instruction set. + + * [Special Registers](<#special-registers>) lists special registers. + + * [Directives](<#directives>) lists the assembly directives supported in PTX. + + * [Release Notes](<#release-notes>) provides release notes for PTX ISA versions 2.x and beyond. + +References + +* 754-2008 IEEE Standard for Floating-Point Arithmetic. ISBN 978-0-7381-5752-8, 2008. + +[http://ieeexplore.ieee.org/servlet/opac?punumber=4610933]() + + * The OpenCL Specification, Version: 1.1, Document Revision: 44, June 1, 2011. + +[http://www.khronos.org/registry/cl/specs/opencl-1.1.pdf]() + + * CUDA Programming Guide. + +[https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html]() + + * CUDA Dynamic Parallelism Programming Guide. + +[https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#cuda-dynamic-parallelism]() + + * CUDA Atomicity Requirements. + +[https://nvidia.github.io/cccl/libcudacxx/extended_api/memory_model.html#atomicity]() + + * PTX Writers Guide to Interoperability. + +[https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/index.html]() \ No newline at end of file diff --git a/content/cuda/docs/ptx-dp2a/DOC.md b/content/cuda/docs/ptx-dp2a/DOC.md new file mode 100644 index 00000000..ba39f5f4 --- /dev/null +++ b/content/cuda/docs/ptx-dp2a/DOC.md @@ -0,0 +1,73 @@ +--- +name: ptx-dp2a +description: Two-way dot product-accumulate. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.24. Integer Arithmetic Instructions:dp2a + +--- +title: "9.7.1.24. Integer Arithmetic Instructions:dp2a" +section: 9.7.1.24 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.24. Integer Arithmetic Instructions:dp2a + + +`dp2a` + +Two-way dot product-accumulate. + +Syntax + +dp2a.mode.atype.btype d, a, b, c; + + .atype = .btype = { .u32, .s32 }; + .mode = { .lo, .hi }; + +Description + +Two-way 16-bit to 8-bit dot product which is accumulated in 32-bit result. + +Operand `a` and `b` are 32-bit inputs. Operand `a` holds two 16-bits inputs in packed form and operand `b` holds 4 byte inputs in packed form for dot product. + +Depending on the `.mode` specified, either lower half or upper half of operand `b` will be used for dot product. + +Operand `c` has type `.u32` if both `.atype` and `.btype` are `.u32` else operand `c` has type `.s32`. + +Semantics + +d = c; + // Extract two 16-bit values from a 32-bit input and sign or zero extend + // based on input type. + Va = extractAndSignOrZeroExt_2(a, .atype); + + // Extract four 8-bit values from a 32-bit input and sign or zer extend + // based on input type. + Vb = extractAndSignOrZeroExt_4(b, .btype); + + b_select = (.mode == .lo) ? 0 : 2; + + for (i = 0; i < 2; ++i) { + d += Va[i] * Vb[b_select + i]; + } + +PTX ISA Notes + +Introduced in PTX ISA version 5.0. + +Target ISA Notes + +Requires `sm_61` or higher. + +Examples + +dp2a.lo.u32.u32 d0, a0, b0, c0; + dp2a.hi.u32.s32 d1, a1, b1, c1; \ No newline at end of file diff --git a/content/cuda/docs/ptx-dp4a/DOC.md b/content/cuda/docs/ptx-dp4a/DOC.md new file mode 100644 index 00000000..ce69d696 --- /dev/null +++ b/content/cuda/docs/ptx-dp4a/DOC.md @@ -0,0 +1,66 @@ +--- +name: ptx-dp4a +description: Four-way byte dot product-accumulate. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.23. Integer Arithmetic Instructions:dp4a + +--- +title: "9.7.1.23. Integer Arithmetic Instructions:dp4a" +section: 9.7.1.23 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.23. Integer Arithmetic Instructions:dp4a + + +`dp4a` + +Four-way byte dot product-accumulate. + +Syntax + +dp4a.atype.btype d, a, b, c; + + .atype = .btype = { .u32, .s32 }; + +Description + +Four-way byte dot product which is accumulated in 32-bit result. + +Operand `a` and `b` are 32-bit inputs which hold 4 byte inputs in packed form for dot product. + +Operand `c` has type `.u32` if both `.atype` and `.btype` are `.u32` else operand `c` has type `.s32`. + +Semantics + +d = c; + + // Extract 4 bytes from a 32bit input and sign or zero extend + // based on input type. + Va = extractAndSignOrZeroExt_4(a, .atype); + Vb = extractAndSignOrZeroExt_4(b, .btype); + + for (i = 0; i < 4; ++i) { + d += Va[i] * Vb[i]; + } + +PTX ISA Notes + +Introduced in PTX ISA version 5.0. + +Target ISA Notes + +Requires `sm_61` or higher. + +Examples + +dp4a.u32.u32 d0, a0, b0, c0; + dp4a.u32.s32 d1, a1, b1, c1; \ No newline at end of file diff --git a/content/cuda/docs/ptx-electsync/DOC.md b/content/cuda/docs/ptx-electsync/DOC.md new file mode 100644 index 00000000..d1eea3e2 --- /dev/null +++ b/content/cuda/docs/ptx-electsync/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-electsync +description: Elect a leader thread from a set of threads. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.14. Parallel Synchronization and Communication Instructions:elect.sync + +--- +title: "9.7.13.14. Parallel Synchronization and Communication Instructions:elect.sync" +section: 9.7.13.14 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.14. Parallel Synchronization and Communication Instructions:elect.sync + + +`elect.sync` + +Elect a leader thread from a set of threads. + +Syntax + +elect.sync d|p, membermask; + +Description + +`elect.sync` elects one predicated active leader thread from among a set of threads specified by `membermask`. `laneid` of the elected thread is returned in the 32-bit destination operand `d`. The sink symbol ‘_’ can be used for destination operand `d`. The predicate destination `p` is set to `True` for the leader thread, and `False` for all other threads. + +Operand `membermask` specifies a 32-bit integer indicating the set of threads from which a leader is to be elected. The behavior is undefined if the executing thread is not in `membermask`. + +Election of a leader thread happens deterministically, i.e. the same leader thread is elected for the same `membermask` every time. + +The mandatory `.sync` qualifier indicates that `elect` causes the executing thread to wait until all threads in the `membermask` execute the `elect` instruction before resuming execution. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +elect.sync %r0|%p0, 0xffffffff; \ No newline at end of file diff --git a/content/cuda/docs/ptx-ex2/DOC.md b/content/cuda/docs/ptx-ex2/DOC.md new file mode 100644 index 00000000..5829b7c7 --- /dev/null +++ b/content/cuda/docs/ptx-ex2/DOC.md @@ -0,0 +1,102 @@ +--- +name: ptx-ex2 +description: Find the base-2 exponent of input. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.4.10. Half Precision Floating Point Instructions:ex2 + +--- +title: "9.7.4.10. Half Precision Floating Point Instructions:ex2" +section: 9.7.4.10 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.4.10. Half Precision Floating Point Instructions:ex2 + + +`ex2` + +Find the base-2 exponent of input. + +Syntax + +ex2.approx.atype d, a; + ex2.approx.ftz.btype d, a; + + .atype = { .f16, .f16x2} + .btype = { .bf16, .bf16x2} + +Description + +Raise 2 to the power `a`. + +The type of operands `d` and `a` are as specified by `.type`. + +For `.f16x2` or `.bf16x2` instruction type, each of the half-word operands are operated in parallel and the results are packed appropriately into a `.f16x2` or `.bf16x2`. + +Semantics + +if (.type == .f16 || .type == .bf16) { + d = 2 ^ a + } else if (.type == .f16x2 || .type == .bf16x2) { + fA[0] = a[0:15]; + fA[1] = a[16:31]; + d[0] = 2 ^ fA[0] + d[1] = 2 ^ fA[1] + } + +Notes + +`ex2.approx.{f16, f16x2, bf16, bf16x2}` implement a fast approximation to 2a. + +For the `.f16` type, subnormal inputs are supported. `ex2.approx.ftz.bf16` flushes subnormal inputs and results to sign-preserving zero. + +Results of `ex2.approx.ftz.bf16` for various corner-case inputs are as follows: + +Input | Result +---|--- +-Inf | +0.0 +-subnormal | +1.0 +-0.0 | +1.0 ++0.0 | +1.0 ++subnormal | +1.0 ++Inf | +Inf +NaN | NaN + +Results of `ex2.approx.f16` for various corner-case inputs are as follows: + +Input | Result +---|--- +-Inf | +0.0 +-0.0 | +1.0 ++0.0 | +1.0 ++Inf | +Inf +NaN | NaN + +The maximum relative error for `.f16` type is 2-9.9. The maximum relative error for `.bf16` type is 2-7. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +`ex2.approx.ftz.{bf16/bf16x2}` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_75` or higher. + +`ex2.approx.ftz.{bf16/bf16x2}` requires `sm_90` or higher. + +Examples + +ex2.approx.f16 h1, h0; + ex2.approx.f16x2 hd1, hd0; + ex2.approx.ftz.bf16 b1, b2; + ex2.approx.ftz.bf16x2 hb1, hb2; \ No newline at end of file diff --git a/content/cuda/docs/ptx-exit/DOC.md b/content/cuda/docs/ptx-exit/DOC.md new file mode 100644 index 00000000..a6b2e287 --- /dev/null +++ b/content/cuda/docs/ptx-exit/DOC.md @@ -0,0 +1,49 @@ +--- +name: ptx-exit +description: Terminate a thread. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.12.7. Control Flow Instructions:exit + +--- +title: "9.7.12.7. Control Flow Instructions:exit" +section: 9.7.12.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.12.7. Control Flow Instructions:exit + + +`exit` + +Terminate a thread. + +Syntax + +exit; + +Description + +Ends execution of a thread. + +Barriers exclusively waiting on arrivals from exited threads are always released. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +exit; + @p exit; \ No newline at end of file diff --git a/content/cuda/docs/ptx-fence-sc-order/DOC.md b/content/cuda/docs/ptx-fence-sc-order/DOC.md new file mode 100644 index 00000000..909d37ec --- /dev/null +++ b/content/cuda/docs/ptx-fence-sc-order/DOC.md @@ -0,0 +1,25 @@ +--- +name: ptx-fence-sc-order +description: The _Fence-SC_ order is an acyclic partial order, determined at runtime, + that relates every pair of _morally strong fence.sc_ operations. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.3. Fence-SC Order + +--- +title: "8.9.3. Fence-SC Order" +section: 8.9.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.3. Fence-SC Order + + +The _Fence-SC_ order is an acyclic partial order, determined at runtime, that relates every pair of _morally strong fence.sc_ operations. \ No newline at end of file diff --git a/content/cuda/docs/ptx-fence-sc/DOC.md b/content/cuda/docs/ptx-fence-sc/DOC.md new file mode 100644 index 00000000..cdf47fb3 --- /dev/null +++ b/content/cuda/docs/ptx-fence-sc/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-fence-sc +description: _Fence-SC_ order cannot contradict _causality order_. For a pair of _morally + strong_ _fence.sc_ operations F1 and F2, if F1 precedes F2 in _causality order_ + , then F1 must precede F2 in _Fence-SC_ ord... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.10.2. Fence-SC + +--- +title: "8.10.2. Fence-SC" +section: 8.10.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.10.2. Fence-SC + + +_Fence-SC_ order cannot contradict _causality order_. For a pair of _morally strong_ _fence.sc_ operations F1 and F2, if F1 precedes F2 in _causality order_ , then F1 must precede F2 in _Fence-SC_ order. \ No newline at end of file diff --git a/content/cuda/docs/ptx-fixed-point-data-format/DOC.md b/content/cuda/docs/ptx-fixed-point-data-format/DOC.md new file mode 100644 index 00000000..c36b3a04 --- /dev/null +++ b/content/cuda/docs/ptx-fixed-point-data-format/DOC.md @@ -0,0 +1,31 @@ +--- +name: ptx-fixed-point-data-format +description: 'PTX supports following fixed-point data formats:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.4. Fixed-point Data format + +--- +title: "5.2.4. Fixed-point Data format" +section: 5.2.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.2.4. Fixed-point Data format + + +PTX supports following fixed-point data formats: + +`s2f6` data format: + + +This data format is 8-bit signed 2’s complement integer with 2 sign-integer bits and 6 fractional bits with form **xx.xxxxxx**. The `s2f6` encoding does not support infinity and `NaN`. + +`s2f6` value = s8 value * 2^(-6) Positive max representation = 01.111111 = 127 * 2^(-6) = 1.984375 Negative max representation = 10.000000 = -128 * 2^(-6) = -2.0 \ No newline at end of file diff --git a/content/cuda/docs/ptx-floating-point-comparisons/DOC.md b/content/cuda/docs/ptx-floating-point-comparisons/DOC.md new file mode 100644 index 00000000..0ca38fe6 --- /dev/null +++ b/content/cuda/docs/ptx-floating-point-comparisons/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-floating-point-comparisons +description: The ordered floating-point comparisons are `eq`, `ne`, `lt`, `le`, `gt`, + and `ge`. If either operand is `NaN`, the result is `False`. [Table 23](<#floating-point-comparisons-floating-point-operators>)... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.3.1.2. Floating Point Comparisons + +--- +title: "9.3.1.2. Floating Point Comparisons" +section: 9.3.1.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.3.1.2. Floating Point Comparisons + + +The ordered floating-point comparisons are `eq`, `ne`, `lt`, `le`, `gt`, and `ge`. If either operand is `NaN`, the result is `False`. [Table 23](<#floating-point-comparisons-floating-point-operators>) lists the floating-point comparison operators. + +Table 23 Floating-Point Comparison Operators Meaning | Floating-Point Operator +---|--- +`a == b && !isNaN(a) && !isNaN(b)` | `eq` +`a != b && !isNaN(a) && !isNaN(b)` | `ne` +`a < b && !isNaN(a) && !isNaN(b)` | `lt` +`a <= b && !isNaN(a) && !isNaN(b)` | `le` +`a > b && !isNaN(a) && !isNaN(b)` | `gt` +`a >= b && !isNaN(a) && !isNaN(b)` | `ge` + +To aid comparison operations in the presence of `NaN` values, unordered floating-point comparisons are provided: `equ`, `neu`, `ltu`, `leu`, `gtu`, and `geu`. If both operands are numeric values (not `NaN`), then the comparison has the same result as its ordered counterpart. If either operand is `NaN`, then the result of the comparison is `True`. + +[Table 24](<#floating-point-comparisons-floating-point-operators-nan>) lists the floating-point comparison operators accepting `NaN` values. + +Table 24 Floating-Point Comparison Operators Accepting NaN Meaning | Floating-Point Operator +---|--- +`a == b || isNaN(a) || isNaN(b)` | `equ` +`a != b || isNaN(a) || isNaN(b)` | `neu` +`a < b || isNaN(a) || isNaN(b)` | `ltu` +`a <= b || isNaN(a) || isNaN(b)` | `leu` +`a > b || isNaN(a) || isNaN(b)` | `gtu` +`a >= b || isNaN(a) || isNaN(b)` | `geu` + +To test for `NaN` values, two operators `num` (`numeric`) and `nan` (`isNaN`) are provided. `num` returns `True` if both operands are numeric values (not `NaN`), and `nan` returns `True` if either operand is `NaN`. [Table 25](<#floating-point-comparisons-floating-point-operators-testing-nan>) lists the floating-point comparison operators testing for `NaN` values. + +Table 25 Floating-Point Comparison Operators Testing for NaN Meaning | Floating-Point Operator +---|--- +`!isNaN(a) && !isNaN(b)` | `num` +`isNaN(a) || isNaN(b)` | `nan` \ No newline at end of file diff --git a/content/cuda/docs/ptx-floating-point-constants/DOC.md b/content/cuda/docs/ptx-floating-point-constants/DOC.md new file mode 100644 index 00000000..c143e5b6 --- /dev/null +++ b/content/cuda/docs/ptx-floating-point-constants/DOC.md @@ -0,0 +1,37 @@ +--- +name: ptx-floating-point-constants +description: Floating-point constants are represented as 64-bit double-precision values, + and all floating-point constant expressions are evaluated using 64-bit double precision + arithmetic. The only exception is th... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.5.2. Floating-Point Constants + +--- +title: "4.5.2. Floating-Point Constants" +section: 4.5.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.5.2. Floating-Point Constants + + +Floating-point constants are represented as 64-bit double-precision values, and all floating-point constant expressions are evaluated using 64-bit double precision arithmetic. The only exception is the 32-bit hex notation for expressing an exact single-precision floating-point value; such values retain their exact 32-bit single-precision value and may not be used in constant expressions. Each 64-bit floating-point constant is converted to the appropriate floating-point size based on the data or instruction type at its use. + +Floating-point literals may be written with an optional decimal point and an optional signed exponent. Unlike C and C++, there is no suffix letter to specify size; literals are always represented in 64-bit double-precision format. + +PTX includes a second representation of floating-point constants for specifying the exact machine representation using a hexadecimal constant. To specify IEEE 754 double-precision floating point values, the constant begins with `0d` or `0D` followed by 16 hex digits. To specify IEEE 754 single-precision floating point values, the constant begins with `0f` or `0F` followed by 8 hex digits. + +0[fF]{hexdigit}{8} // single-precision floating point + 0[dD]{hexdigit}{16} // double-precision floating point + +Example + +mov.f32 $f3, 0F3f800000; // 1.0 \ No newline at end of file diff --git a/content/cuda/docs/ptx-fma/DOC.md b/content/cuda/docs/ptx-fma/DOC.md new file mode 100644 index 00000000..67c53ed1 --- /dev/null +++ b/content/cuda/docs/ptx-fma/DOC.md @@ -0,0 +1,130 @@ +--- +name: ptx-fma +description: Fused multiply-add. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.6. Floating Point Instructions:fma + +--- +title: "9.7.3.6. Floating Point Instructions:fma" +section: 9.7.3.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.6. Floating Point Instructions:fma + + +`fma` + +Fused multiply-add. + +Syntax + +fma.rnd{.ftz}{.sat}.f32 d, a, b, c; + fma.rnd{.ftz}.f32x2 d, a, b, c; + fma.rnd.f64 d, a, b, c; + + .rnd = { .rn, .rz, .rm, .rp }; + +Description + +Performs a fused multiply-add with no loss of precision in the intermediate product and addition. + +For `.f32x2` instruction type, forms input vectors of single precision (`.f32`) values from source operands. Single precision (`.f32`) operands are then operated in parallel to produce `.f32x2` result in destination. + +For `.f32x2` instruction type, operands `d`, `a`, `b` and `c` have `.b64` type. + +Semantics + +if (type == f32 || type == f64) { + d = a * b + c; + } else if (type == f32x2) { + fA[0] = a[0:31]; + fA[1] = a[32:63]; + fB[0] = b[0:31]; + fB[1] = b[32:63]; + fC[0] = c[0:31]; + fC[1] = c[32:63]; + for (i = 0; i < 2; i++) { + d[i] = fA[i] * fB[i] + fC[i]; + } + } + +Notes + +`fma.f32` computes the product of `a` and `b` to infinite precision and then adds `c` to this product, again in infinite precision. The resulting value is then rounded to single precision using the rounding mode specified by `.rnd`. + +`fma.f64` computes the product of `a` and `b` to infinite precision and then adds `c` to this product, again in infinite precision. The resulting value is then rounded to double precision using the rounding mode specified by `.rnd`. + +`fma.f64` is the same as `mad.f64`. + +Rounding modifiers (no default): + +`.rn` + + +mantissa LSB rounds to nearest even + +`.rz` + + +mantissa LSB rounds towards zero + +`.rm` + + +mantissa LSB rounds towards negative infinity + +`.rp` + + +mantissa LSB rounds towards positive infinity + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`fma.ftz.f32`, `fma.ftz.f32x2` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`fma.f64` supports subnormal numbers. + +`fma.f32` is unimplemented for `sm_1x` targets. + +Saturation: + +`fma.sat.f32` clamps the result to [0.0, 1.0]. `NaN` results are flushed to `+0.0f`. + +PTX ISA Notes + +`fma.f64` introduced in PTX ISA version 1.4. + +`fma.f32` introduced in PTX ISA version 2.0. + +`fma.f32x2` introduced in PTX ISA version 8.6. + +Target ISA Notes + +`fma.f32` requires `sm_20` or higher. + +`fma.f64` requires `sm_13` or higher. + +`fma.f32x2` requires `sm_100` or higher. + +Examples + +fma.rn.ftz.f32 w,x,y,z; + @p fma.rn.f64 d,a,b,c; + fma.rp.ftz.f32x2 p,q,r,s; \ No newline at end of file diff --git a/content/cuda/docs/ptx-fns/DOC.md b/content/cuda/docs/ptx-fns/DOC.md new file mode 100644 index 00000000..20fddace --- /dev/null +++ b/content/cuda/docs/ptx-fns/DOC.md @@ -0,0 +1,78 @@ +--- +name: ptx-fns +description: Find the n-th set bit +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.17. Integer Arithmetic Instructions:fns + +--- +title: "9.7.1.17. Integer Arithmetic Instructions:fns" +section: 9.7.1.17 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.17. Integer Arithmetic Instructions:fns + + +`fns` + +Find the n-th set bit + +Syntax + +fns.b32 d, mask, base, offset; + +Description + +Given a 32-bit value `mask` and an integer value `base` (between 0 and 31), find the n-th (given by offset) set bit in `mask` from the `base` bit, and store the bit position in `d`. If not found, store 0xffffffff in `d`. + +Operand `mask` has a 32-bit type. Operand `base` has `.b32`, `.u32` or `.s32` type. Operand offset has `.s32` type. Destination `d` has type `.b32.` + +Operand `base` must be <= 31, otherwise behavior is undefined. + +Semantics + +d = 0xffffffff; + if (offset == 0) { + if (mask[base] == 1) { + d = base; + } + } else { + pos = base; + count = |offset| - 1; + inc = (offset > 0) ? 1 : -1; + + while ((pos >= 0) && (pos < 32)) { + if (mask[pos] == 1) { + if (count == 0) { + d = pos; + break; + } else { + count = count - 1; + } + } + pos = pos + inc; + } + } + +PTX ISA Notes + +Introduced in PTX ISA version 6.0. + +Target ISA Notes + +`fns` requires `sm_30` or higher. + +Examples + +fns.b32 d, 0xaaaaaaaa, 3, 1; // d = 3 + fns.b32 d, 0xaaaaaaaa, 3, -1; // d = 3 + fns.b32 d, 0xaaaaaaaa, 2, 1; // d = 3 + fns.b32 d, 0xaaaaaaaa, 2, -1; // d = 1 \ No newline at end of file diff --git a/content/cuda/docs/ptx-format-and-semantics-of-instruction-descriptions/DOC.md b/content/cuda/docs/ptx-format-and-semantics-of-instruction-descriptions/DOC.md new file mode 100644 index 00000000..84598ce9 --- /dev/null +++ b/content/cuda/docs/ptx-format-and-semantics-of-instruction-descriptions/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-format-and-semantics-of-instruction-descriptions +description: This section describes each PTX instruction. In addition to the name + and the format of the instruction, the semantics are described, followed by some + examples that attempt to show several possible ins... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.1. Format and Semantics of Instruction Descriptions + +--- +title: "9.1. Format and Semantics of Instruction Descriptions" +section: 9.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 9.1. Format and Semantics of Instruction Descriptions + + +This section describes each PTX instruction. In addition to the name and the format of the instruction, the semantics are described, followed by some examples that attempt to show several possible instantiations of the instruction. \ No newline at end of file diff --git a/content/cuda/docs/ptx-fundamental-types/DOC.md b/content/cuda/docs/ptx-fundamental-types/DOC.md new file mode 100644 index 00000000..9ce070cc --- /dev/null +++ b/content/cuda/docs/ptx-fundamental-types/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-fundamental-types +description: In PTX, the fundamental types reflect the native data types supported + by the target architectures. A fundamental type specifies both a basic type and + a size. Register variables are always of a fundame... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.1. Fundamental Types + +--- +title: "5.2.1. Fundamental Types" +section: 5.2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.2.1. Fundamental Types + + +In PTX, the fundamental types reflect the native data types supported by the target architectures. A fundamental type specifies both a basic type and a size. Register variables are always of a fundamental type, and instructions operate on these types. The same type-size specifiers are used for both variable definitions and for typing instructions, so their names are intentionally short. + +[Table 8](<#fundamental-types-fundamental-type-specifiers>) lists the fundamental type specifiers for each basic type: + +Table 8 Fundamental Type Specifiers Basic Type | Fundamental Type Specifiers +---|--- +Signed integer | `.s8`, `.s16`, `.s32`, `.s64` +Unsigned integer | `.u8`, `.u16`, `.u32`, `.u64` +Floating-point | `.f16`, `.f16x2`, `.f32`, `.f64` +Bits (untyped) | `.b8`, `.b16`, `.b32`, `.b64`, `.b128` +Predicate | `.pred` + +Most instructions have one or more type specifiers, needed to fully specify instruction behavior. Operand types and sizes are checked against instruction types for compatibility. + +Two fundamental types are compatible if they have the same basic type and are the same size. Signed and unsigned integer types are compatible if they have the same size. The bit-size type is compatible with any fundamental type having the same size. + +In principle, all variables (aside from predicates) could be declared using only bit-size types, but typed variables enhance program readability and allow for better operand type checking. \ No newline at end of file diff --git a/content/cuda/docs/ptx-generic-addressing/DOC.md b/content/cuda/docs/ptx-generic-addressing/DOC.md new file mode 100644 index 00000000..7c07146a --- /dev/null +++ b/content/cuda/docs/ptx-generic-addressing/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-generic-addressing +description: If a memory instruction does not specify a state space, the operation + is performed using generic addressing. The state spaces `.const`, [Kernel Function + Parameters](<#kernel-function-parameters>) (`.p... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.4.1.1. Generic Addressing + +--- +title: "6.4.1.1. Generic Addressing" +section: 6.4.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 6.4.1.1. Generic Addressing + + +If a memory instruction does not specify a state space, the operation is performed using generic addressing. The state spaces `.const`, [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`), `.local` and `.shared` are modeled as windows within the generic address space. Each window is defined by a window base and a window size that is equal to the size of the corresponding state space. A generic address maps to `global` memory unless it falls within the window for `const`, `local`, or `shared` memory. The [Kernel Function Parameters](<#kernel-function-parameters>) (`.param`) window is contained within the `.global` window. Within each window, a generic address maps to an address in the underlying state space by subtracting the window base from the generic address. \ No newline at end of file diff --git a/content/cuda/docs/ptx-getctarank/DOC.md b/content/cuda/docs/ptx-getctarank/DOC.md new file mode 100644 index 00000000..21c33aae --- /dev/null +++ b/content/cuda/docs/ptx-getctarank/DOC.md @@ -0,0 +1,67 @@ +--- +name: ptx-getctarank +description: Generate the CTA rank of the address. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.24. Data Movement and Conversion Instructions:getctarank + +--- +title: "9.7.9.24. Data Movement and Conversion Instructions:getctarank" +section: 9.7.9.24 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.24. Data Movement and Conversion Instructions:getctarank + + +`getctarank` + +Generate the CTA rank of the address. + +Syntax + +getctarank{.space}.type d, a; + + // Get cta rank from source shared memory address in register a. + getctarank.shared::cluster.type d, a; + + // Get cta rank from shared memory variable. + getctarank.shared::cluster.type d, var; + + // Get cta rank from shared memory variable+offset. + getctarank.shared::cluster.type d, var + imm; + + // Get cta rank from generic address of shared memory variable in register a. + getctarank.type d, a; + + .space = { .shared::cluster } + .type = { .u32, .u64 } + +Description + +Write the destination register `d` with the rank of the CTA which contains the address specified in operand `a`. + +Instruction type `.type` indicates the type of source operand `a`. + +When space is `.shared::cluster`, source `a` is either a shared memory variable or a register containing a valid shared memory address. When the optional qualifier `.space` is not specified, `a` is a register containing a generic addresses pointing to shared memory. Destination `d` is always a 32-bit register which holds the rank of the CTA. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +getctarank.shared::cluster.u32 d1, addr; + getctarank.shared::cluster.u64 d2, sh + 4; + getctarank.u64 d3, src; \ No newline at end of file diff --git a/content/cuda/docs/ptx-global-state-space/DOC.md b/content/cuda/docs/ptx-global-state-space/DOC.md new file mode 100644 index 00000000..def87f1f --- /dev/null +++ b/content/cuda/docs/ptx-global-state-space/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-global-state-space +description: The global (`.global`) state space is memory that is accessible by all + threads in a context. It is the mechanism by which threads in different CTAs, clusters, + and grids can communicate. Use `ld.global... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.4. Global State Space + +--- +title: "5.1.4. Global State Space" +section: 5.1.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.1.4. Global State Space + + +The global (`.global`) state space is memory that is accessible by all threads in a context. It is the mechanism by which threads in different CTAs, clusters, and grids can communicate. Use `ld.global`, `st.global`, and `atom.global` to access global variables. + +Global variables have an optional variable initializer; global variables with no explicit initializer are initialized to zero by default. \ No newline at end of file diff --git a/content/cuda/docs/ptx-goals-of-ptx/DOC.md b/content/cuda/docs/ptx-goals-of-ptx/DOC.md new file mode 100644 index 00000000..5db00712 --- /dev/null +++ b/content/cuda/docs/ptx-goals-of-ptx/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-goals-of-ptx +description: _PTX_ provides a stable programming model and instruction set for general + purpose parallel programming. It is designed to be efficient on NVIDIA GPUs supporting + the computation features defined by the... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 1.2. Goals of PTX + +--- +title: "1.2. Goals of PTX" +section: 1.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 1.2. Goals of PTX + + +_PTX_ provides a stable programming model and instruction set for general purpose parallel programming. It is designed to be efficient on NVIDIA GPUs supporting the computation features defined by the NVIDIA Tesla architecture. High level language compilers for languages such as CUDA and C/C++ generate PTX instructions, which are optimized for and translated to native target-architecture instructions. + +The goals for PTX include the following: + +* Provide a stable ISA that spans multiple GPU generations. + + * Achieve performance in compiled applications comparable to native GPU performance. + + * Provide a machine-independent ISA for C/C++ and other compilers to target. + + * Provide a code distribution ISA for application and middleware developers. + + * Provide a common source-level ISA for optimizing code generators and translators, which map PTX to specific target machines. + + * Facilitate hand-coding of libraries, performance kernels, and architecture tests. + + * Provide a scalable programming model that spans GPU sizes from a single unit to many parallel units. \ No newline at end of file diff --git a/content/cuda/docs/ptx-grid-of-clusters/DOC.md b/content/cuda/docs/ptx-grid-of-clusters/DOC.md new file mode 100644 index 00000000..3d6152b1 --- /dev/null +++ b/content/cuda/docs/ptx-grid-of-clusters/DOC.md @@ -0,0 +1,44 @@ +--- +name: ptx-grid-of-clusters +description: There is a maximum number of threads that a CTA can contain and a maximum + number of CTAs that a cluster can contain. However, clusters with CTAs that execute + the same kernel can be batched together in... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 2.2.3. Grid of Clusters + +--- +title: "2.2.3. Grid of Clusters" +section: 2.2.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 2.2.3. Grid of Clusters + + +There is a maximum number of threads that a CTA can contain and a maximum number of CTAs that a cluster can contain. However, clusters with CTAs that execute the same kernel can be batched together into a grid of clusters, so that the total number of threads that can be launched in a single kernel invocation is very large. This comes at the expense of reduced thread communication and synchronization, because threads in different clusters cannot communicate and synchronize with each other. + +Each cluster has a unique cluster identifier (_clusterid_) within a grid of clusters. Each grid of clusters has a 1D, 2D , or 3D shape specified by the parameter _nclusterid_. Each grid also has a unique temporal grid identifier (_gridid_). Threads may read and use these values through predefined, read-only special registers `%tid`, `%ntid`, `%clusterid`, `%nclusterid`, and `%gridid`. + +Each CTA has a unique identifier (_ctaid_) within a grid. Each grid of CTAs has 1D, 2D, or 3D shape specified by the parameter _nctaid_. Thread may use and read these values through predefined, read-only special registers `%ctaid` and `%nctaid`. + +Each kernel is executed as a batch of threads organized as a grid of clusters consisting of CTAs where cluster is optional level and is applicable only for target architectures `sm_90` and higher. [Figure 1](<#grid-of-clusters-grid-with-ctas>) shows a grid consisting of CTAs and [Figure 2](<#grid-of-clusters-grid-with-clusters>) shows a grid consisting of clusters. + +Grids may be launched with dependencies between one another - a grid may be a dependent grid and/or a prerequisite grid. To understand how grid dependencies may be defined, refer to the section on _CUDA Graphs_ in the _Cuda Programming Guide_. + +![Grid with CTAs](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/grid-with-CTAs.png) + +Figure 1 Grid with CTAs + +![Grid with clusters](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/grid-with-clusters.png) + +Figure 2 Grid with clusters + +A cluster is a set of cooperative thread arrays (CTAs) where a CTA is a set of concurrent threads that execute the same kernel program. A grid is a set of clusters consisting of CTAs that execute independently. \ No newline at end of file diff --git a/content/cuda/docs/ptx-griddepcontrol/DOC.md b/content/cuda/docs/ptx-griddepcontrol/DOC.md new file mode 100644 index 00000000..81c56c6f --- /dev/null +++ b/content/cuda/docs/ptx-griddepcontrol/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-griddepcontrol +description: Control execution of dependent grids. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.13. Parallel Synchronization and Communication Instructions:griddepcontrol + +--- +title: "9.7.13.13. Parallel Synchronization and Communication Instructions:griddepcontrol" +section: 9.7.13.13 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.13. Parallel Synchronization and Communication Instructions:griddepcontrol + + +`griddepcontrol` + +Control execution of dependent grids. + +Syntax + +griddepcontrol.action; + + .action = { .launch_dependents, .wait } + +Description + +The `griddepcontrol` instruction allows the dependent grids and prerequisite grids as defined by the runtime, to control execution in the following way: + +`.launch_dependents` modifier signals that specific dependents the runtime system designated to react to this instruction can be scheduled as soon as all other CTAs in the grid issue the same instruction or have completed. The dependent may launch before the completion of the current grid. There is no guarantee that the dependent will launch before the completion of the current grid. Repeated invocations of this instruction by threads in the current CTA will have no additional side effects past that of the first invocation. + +`.wait` modifier causes the executing thread to wait until all prerequisite grids in flight have completed and all the memory operations from the prerequisite grids are performed and made visible to the current grid. + +Note + +If the prerequisite grid is using `griddepcontrol.launch_dependents`, then the dependent grid must use `griddepcontrol.wait` to ensure correct functional execution. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +griddepcontrol.launch_dependents; + griddepcontrol.wait; \ No newline at end of file diff --git a/content/cuda/docs/ptx-identifiers/DOC.md b/content/cuda/docs/ptx-identifiers/DOC.md new file mode 100644 index 00000000..96bd0152 --- /dev/null +++ b/content/cuda/docs/ptx-identifiers/DOC.md @@ -0,0 +1,47 @@ +--- +name: ptx-identifiers +description: 'User-defined identifiers follow extended C++ rules: they either start + with a letter followed by zero or more letters, digits, underscore, or dollar characters; + or they start with an underscore, dollar...' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.4. Identifiers + +--- +title: "4.4. Identifiers" +section: 4.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 4.4. Identifiers + + +User-defined identifiers follow extended C++ rules: they either start with a letter followed by zero or more letters, digits, underscore, or dollar characters; or they start with an underscore, dollar, or percentage character followed by one or more letters, digits, underscore, or dollar characters: + +followsym: [a-zA-Z0-9_$] + identifier: [a-zA-Z]{followsym}* | {[_$%]{followsym}+ + +PTX does not specify a maximum length for identifiers and suggests that all implementations support a minimum length of at least 1024 characters. + +Many high-level languages such as C and C++ follow similar rules for identifier names, except that the percentage sign is not allowed. PTX allows the percentage sign as the first character of an identifier. The percentage sign can be used to avoid name conflicts, e.g., between user-defined variable names and compiler-generated names. + +PTX predefines one constant and a small number of special registers that begin with the percentage sign, listed in [Table 3](<#identifiers-predefined-identifiers>). + +Table 3 Predefined Identifiers `%aggr_smem_size` | `%dynamic_smem_size` | `%lanemask_gt` | `%reserved_smem_offset_begin` +---|---|---|--- +`%clock` | `%envreg<32>` | `%lanemask_le` | `%reserved_smem_offset_cap` +`%clock64` | `%globaltimer` | `%lanemask_lt` | `%reserved_smem_offset_end` +`%cluster_ctaid` | `%globaltimer_hi` | `%nclusterid` | `%smid` +`%cluster_ctarank` | `%globaltimer_lo` | `%nctaid` | `%tid` +`%cluster_nctaid` | `%gridid` | `%nsmid` | `%total_smem_size` +`%cluster_nctarank` | `%is_explicit_cluster` | `%ntid` | `%warpid` +`%clusterid` | `%laneid` | `%nwarpid` | `WARP_SZ` +`%ctaid` | `%lanemask_eq` | `%pm0, ..., %pm7` | +`%current_graph_exec` | `%lanemask_ge` | `%reserved_smem_offset_<2>` | \ No newline at end of file diff --git a/content/cuda/docs/ptx-independent-thread-scheduling/DOC.md b/content/cuda/docs/ptx-independent-thread-scheduling/DOC.md new file mode 100644 index 00000000..1bca5e8e --- /dev/null +++ b/content/cuda/docs/ptx-independent-thread-scheduling/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-independent-thread-scheduling +description: On architectures prior to Volta, warps used a single program counter + shared amongst all 32 threads in the warp together with an active mask specifying + the active threads of the warp. As a result, thre... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 3.2. Independent Thread Scheduling + +--- +title: "3.2. Independent Thread Scheduling" +section: 3.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 3.2. Independent Thread Scheduling + + +On architectures prior to Volta, warps used a single program counter shared amongst all 32 threads in the warp together with an active mask specifying the active threads of the warp. As a result, threads from the same warp in divergent regions or different states of execution cannot signal each other or exchange data, and algorithms requiring fine-grained sharing of data guarded by locks or mutexes can easily lead to deadlock, depending on which warp the contending threads come from. + +Starting with the Volta architecture, _Independent Thread Scheduling_ allows full concurrency between threads, regardless of warp. With _Independent Thread Scheduling_ , the GPU maintains execution state per thread, including a program counter and call stack, and can yield execution at a per-thread granularity, either to make better use of execution resources or to allow one thread to wait for data to be produced by another. A schedule optimizer determines how to group active threads from the same warp together into SIMT units. This retains the high throughput of SIMT execution as in prior NVIDIA GPUs, but with much more flexibility: threads can now diverge and reconverge at sub-warp granularity. + +_Independent Thread Scheduling_ can lead to a rather different set of threads participating in the executed code than intended if the developer made assumptions about warp-synchronicity of previous hardware architectures. In particular, any warp-synchronous code (such as synchronization-free, intra-warp reductions) should be revisited to ensure compatibility with Volta and beyond. See the section on Compute Capability 7.x in the _Cuda Programming Guide_ for further details. \ No newline at end of file diff --git a/content/cuda/docs/ptx-index/DOC.md b/content/cuda/docs/ptx-index/DOC.md new file mode 100644 index 00000000..a0468774 --- /dev/null +++ b/content/cuda/docs/ptx-index/DOC.md @@ -0,0 +1,323 @@ +--- +name: ptx-index +description: The threads of the CTA can perform the loads and stores to the [Tensor + Memory](<#tensor-memory>) of the CTA and move data between registers and Tensor + Memory. The loads and stores of data can be perfo... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.8. Tensor Memory and Register Load/Store Instructions + +--- +title: "9.7.16.8. Tensor Memory and Register Load/Store Instructions" +section: 9.7.16.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.8. Tensor Memory and Register Load/Store Instructions + + +The threads of the CTA can perform the loads and stores to the [Tensor Memory](<#tensor-memory>) of the CTA and move data between registers and Tensor Memory. The loads and stores of data can be performed in certain shapes as specified in the [Matrix and Data Movement Shape](<#tcgen05-matrix-data-movement-shape>) section. + +##### 9.7.16.8.1. [Access restrictions](<#tcgen05-tensor-memory-ld-st-access-restrictions>) + +Not all threads of the CTA can access the entire Tensor Memory via the `tcgen05.ld` and `tcgen05.st` operations. + +The Tensor Memory of a CTA is divided into 4 equal chunks such that each warp of a warpgroup in the CTA can access a chunk of the Tensor Memory. All the columns of the Tensor Memory can be accessed by all the four warps of a warpgroup. A lane of the Tensor Memory can be accessed by a single warp in the warpgroup. The following table describes the access restriction. + +ID of the warp within the warpgroup | Accessible Lanes +---|--- +0 | 0-31 +1 | 32-63 +2 | 64-95 +3 | 96-127 + +##### 9.7.16.8.2. [Packing and Unpacking](<#tcgen05-tensor-memory-ld-st-packing-unpacking>) + +Optionally, the following pack and unpack operations can be performed during the load and store: + + 1. Packing: two 16-bit chunks can be packed into a single 32-bit chunk in the register in `tcgen05.ld` + + 2. Unpacking: a single 32-bit chunk in the register can be unpacked into two 16-bit chunks in `tcgen05.st` + + +as shown in the [Figure 193](<#tcgen05-ld-st-pack-unpack>). + +![_images/tcgen05-ld-st-pack-unpack.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-ld-st-pack-unpack.png) + +Figure 193 Pack/Unpack operations for tcgen05 ld/st + +##### 9.7.16.8.3. [Tensorcore 5th Generation Instructions: `tcgen05.ld`](<#tcgen05-instructions-tcgen05-ld>) + +`tcgen05.ld` + +Asynchronous collective load from tensor memory into registers. + +Syntax + + + // Base load instruction: + + tcgen05.ld.sync.aligned.shape1.num{.pack}.b32 r, [taddr]; + + tcgen05.ld.sync.aligned.shape2.num{.pack}.b32 r, [taddr], immHalfSplitoff; + + .shape1 = { .16x64b, .16x128b, .16x256b, .32x32b } + .shape2 = { .16x32bx2 } + .num = { .x1, .x2, .x4, .x8, .x16, .x32, .x64, .x128 } + .pack = { .pack::16b } + + // Floating point type load along with reduction : + + tcgen05.ld.red.sync.aligned.shape3.num.redOp{.abs}{.NaN}.f32 r, redval, [taddr]; + + tcgen05.ld.red.sync.aligned.shape4.num.redOp{.abs}{.NaN}.f32 r, redval, [taddr], immHalfSplitoff; + + // Integer type load along with reduction : + + tcgen05.ld.red.sync.aligned.shape3.num.redOp.type r, redval, [taddr]; + + tcgen05.ld.red.sync.aligned.shape4.num.redOp.type r, redval, [taddr], immHalfSplitoff; + + .shape3 = { .32x32b } + .shape4 = { .16x32bx2 } + .redOp = { .min, .max } + .type = { .u32, .s32 } + + +Description + +Instruction `tcgen05.ld` asynchronously loads data from the [Tensor Memory](<#tensor-memory>) at the location specified by the 32-bit address operand `taddr` into the destination register `r`, collectively across all threads of the warps. + +All the threads in the warp must specify the same value of `taddr`, which must be the base address of the collective load operation. Otherwise, the behavior is undefined. + +The `.shape` qualifier and the `.num` qualifier together determines the total dimension of the data which is loaded from the [Tensor Memory](<#tensor-memory>). The `.shape` qualifier indicates the base dimension of data to be accessed as described in the [Data Movement Shape](<#tcgen05-data-movement-shape>). The `.num` qualifier indicates the repeat factor on the base dimension resulting in the total dimension of the data that is accessed. + +The shape `.16x32bx2` performs two accesses into Tensor Memory of the shape `.16x32b`. The base address of the first access is specified by taddr and the base address of the second access is specified by `taddr+immHalfSplitoff`, where `immHalfSplitoff` is an immediate argument. + +The destination operand `r` is a brace-enclosed vector expression consisting of one or more 32-bit registers as per the value of `.shape` and `.num`. The size of the vector for various combinations of `.num` and `.shape` is shown in [Table 49](<#tcgen05-num-shapes-ld>). + +Table 49 Various-combinations of .num and .shape .num | .shape +---|--- +.16x32bx2 / .16x64b / .32x32b | .16x128b | .16x256b +`.x1` | 1 | 2 | 4 +`.x2` | 2 | 4 | 8 +`.x4` | 4 | 8 | 16 +`.x8` | 8 | 16 | 32 +`.x16` | 16 | 32 | 64 +`.x32` | 32 | 64 | 128 +`.x64` | 64 | 128 | NA +`.x128` | 128 | NA | NA + +The qualifier `.red` specifies that the reduction operation specified by `.redOp` is performed on the data that is loaded across columns in each lane. The result of the reduction operation is written into the corresponding thread’s 32-bit destination register operand `redVal`. When `.red` qualifier is specified, `.num` modifier must be at least `.x2`. + +The optional qualifier `.pack::16b` can be used to pack two 16-bit elements from adjacent columns into a single 32-bit element during the load as shown in the section [Packing and Unpacking](<#tcgen05-tensor-memory-ld-st-packing-unpacking>). + +The mandatory `.sync` qualifier indicates that `tcgen05.ld` causes the executing thread to wait until all threads in the warp execute the same `tcgen05.ld` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `tcgen05.ld` instruction. In conditionally executed code, a `tcgen05.ld` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + +The behavior of `tcgen05.ld` is undefined if all threads do not use the same values of `taddr`, or if any thread in the warp has exited. + +The instruction `tcgen05.ld` is performed asynchronously and more details are specified in the section [Memory Consistency Model for 5th generation of TensorCore operations](<#tcgen05-memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.6. + +`tcgen05.ld.red` is introduced in PTX ISA version 8.8. + +Target ISA Notes + +Supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +`tcgen05.ld.red` is supported on following architectures: + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_103f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Examples + + + tcgen05.ld.sync.aligned.32x32b.x2.b32 {r0, r1}, [taddr1]; + + tcgen05.ld.sync.aligned.16x128b.x4.b32 {r0, r1, r2, r3, r4, r5, r6, r7}, [taddr2]; + + tcgen05.ld.red.sync.aligned.16x32bx2.x8.u32.max {r0, r1, r2, r3, r4, r5, r6, r7}, + redVal, [taddr3], 16; + +##### 9.7.16.8.4. [Tensorcore 5th Generation Instructions: `tcgen05.st`](<#tcgen05-instructions-tcgen05-st>) + +`tcgen05.st` + +Asynchronous collective store to tensor memory from registers. + +Syntax + + + tcgen05.st.sync.aligned.shape1.num{.unpack}.b32 [taddr], r; + + tcgen05.st.sync.aligned.shape2.num{.unpack}.b32 [taddr], immHalfSplitoff, r; + + .shape1 = { .16x64b, .16x128b, .16x256b, .32x32b } + .shape2 = { .16x32bx2 } + .num = { .x1, .x2, .x4, .x8, .x16, .x32, .x64, .x128 } + .unpack = { .unpack::16b } + + +Description + +Instruction `tcgen05.st` asynchronously stores data from the source register `r` into the [Tensor Memory](<#tensor-memory>) at the location specified by the 32-bit address operand `taddr`, collectively across all threads of the warps. + +All the threads in the warp must specify the same value of `taddr`, which must be the base address of the collective store operation. Otherwise, the behavior is undefined. + +The `.shape` qualifier and the `.num` qualifier together determines the total dimension of the data which is stored to the Tensor Memory. The `.shape` qualifier indicates the base dimension of data to be accessed as described in the [Data Movement Shape](<#tcgen05-data-movement-shape>). The `.num` qualifier indicates the repeat factor on the base dimension resulting in the total dimension of the data that is accessed. + +The shape `.16x32bx2` performs two accesses into Tensor Memory of the shape `.16x32b`. The base address of the first access is specified by `taddr` and the base address of the second access is specified by `taddr+immHalfSplitoff`, where `immHalfSplitoff` is an immediate argument. + +The source operand `r` is a brace-enclosed vector expression consisting of one or more 32-bit registers as per the value of `.shape` and `.num`. The size of the vector for various combinations of `.num` and `.shape` is shown in [Table 50](<#tcgen05-num-shapes-st>). + +Table 50 Various-combinations of .num and .shape .num | .shape +---|--- +.16x32bx2 / .16x64b / .32x32b | .16x128b | .16x256b +`.x1` | 1 | 2 | 4 +`.x2` | 2 | 4 | 8 +`.x4` | 4 | 8 | 16 +`.x8` | 8 | 16 | 32 +`.x16` | 16 | 32 | 64 +`.x32` | 32 | 64 | 128 +`.x64` | 64 | 128 | NA +`.x128` | 128 | NA | NA + +The optional qualifier `.unpack::16b` can be used to unpack a 32-bit element in the register into two 16-bit elements and store them in adjacent columns as shown in the section [Packing and Unpacking](<#tcgen05-tensor-memory-ld-st-packing-unpacking>). + +The mandatory `.sync` qualifier indicates that `tcgen05.st` causes the executing thread to wait until all threads in the warp execute the same `tcgen05.st` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `tcgen05.st` instruction. In conditionally executed code, a `tcgen05.st` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + +The behavior of `tcgen05.st` is undefined if all threads do not use the same values of `taddr`, or if any thread in the warp has exited. + +The instruction `tcgen05.st` is performed asynchronously and more details are specified in the section [Memory Consistency Model for 5th generation of TensorCore operations](<#tcgen05-memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.6. + +Target ISA Notes + +Supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Examples + + + tcgen05.st.sync.aligned.16x64b.x4.b32 [taddr0], {r0, r1, r2, r3}; + + tcgen05.st.sync.aligned.16x128b.x1.unpack::16b.b32 [taddr1], {r0, r1}; + +##### 9.7.16.8.5. [Tensorcore 5th Generation Instructions: `tcgen05.wait`](<#tcgen05-instructions-tcgen05-wait>) + +`tcgen05.wait` + +Waits for the completion of all prior asynchronous `tcgen05.ld` / `tcgen05.st` instructions. + +Syntax + + + tcgen05.wait_operation.sync.aligned; + + .wait_operation = { .wait::ld, .wait::st } + + +Description + +Instruction `tcgen05.wait::st` causes the executing thread to block until all prior `tcgen05.st` operations issued by the executing thread have completed. + +Instruction `tcgen05.wait::ld` causes the executing thread to block until all prior `tcgen05.ld` operations issued by the executing thread have completed. + +The mandatory `.sync` qualifier indicates that `tcgen05.wait_operation` causes the executing thread to wait until all threads in the warp execute the same `tcgen05.wait_operation` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `tcgen05.wait_operation` instruction. + +PTX ISA Notes + +Introduced in PTX ISA version 8.6. + +Target ISA Notes + +Supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Examples + + + Example 1: + + tcgen05.ld.sync.aligned.32x32b.x2.b32 {r0, r1}, [taddr0]; + + // Prevents subsequent tcgen05.mma from racing ahead of the tcgen05.ld + + tcgen05.wait::ld.sync.aligned; + + tcgen05.mma.cta_group::1.kind::f16 [taddr0], a-desc, b-desc, idesc, p; + + Example 2: + + tcgen05.st.sync.aligned.32x32b.x2.b32 [taddr0], {r0, r1}; + + // Prevents the write to taddr0 in tcgen05.mma from racing ahead of the tcgen05.st + + tcgen05.wait::st.sync.aligned; + + tcgen05.mma.cta_group::1.kind::f16 [taddr0], a-desc, b-desc, idesc, p; \ No newline at end of file diff --git a/content/cuda/docs/ptx-initialization/DOC.md b/content/cuda/docs/ptx-initialization/DOC.md new file mode 100644 index 00000000..96bae019 --- /dev/null +++ b/content/cuda/docs/ptx-initialization/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-initialization +description: Each byte in memory is initialized by a hypothetical write _W0_ executed + before starting any thread in the program. If the byte is included in a program + variable, and that variable has an initial valu... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.6. Initialization + +--- +title: "8.2.6. Initialization" +section: 8.2.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.6. Initialization + + +Each byte in memory is initialized by a hypothetical write _W0_ executed before starting any thread in the program. If the byte is included in a program variable, and that variable has an initial value, then _W0_ writes the corresponding initial value for that byte; else _W0_ is assumed to have written an unknown but constant value to the byte. \ No newline at end of file diff --git a/content/cuda/docs/ptx-initializers/DOC.md b/content/cuda/docs/ptx-initializers/DOC.md new file mode 100644 index 00000000..5220c6f5 --- /dev/null +++ b/content/cuda/docs/ptx-initializers/DOC.md @@ -0,0 +1,93 @@ +--- +name: ptx-initializers +description: Declared variables may specify an initial value using a syntax similar + to C/C++, where the variable name is followed by an equals sign and the initial + value or values for the variable. A scalar takes ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.4.4. Initializers + +--- +title: "5.4.4. Initializers" +section: 5.4.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.4.4. Initializers + + +Declared variables may specify an initial value using a syntax similar to C/C++, where the variable name is followed by an equals sign and the initial value or values for the variable. A scalar takes a single value, while vectors and arrays take nested lists of values inside of curly braces (the nesting matches the dimensionality of the declaration). + +As in C, array initializers may be incomplete, i.e., the number of initializer elements may be less than the extent of the corresponding array dimension, with remaining array locations initialized to the default value for the specified array type. + +Examples + +.const .f32 vals[8] = { 0.33, 0.25, 0.125 }; + .global .s32 x[3][2] = { {1,2}, {3} }; + +is equivalent to + +.const .f32 vals[8] = { 0.33, 0.25, 0.125, 0.0, 0.0, 0.0, 0.0, 0.0 }; + .global .s32 x[3][2] = { {1,2}, {3,0}, {0,0} }; + +Currently, variable initialization is supported only for constant and global state spaces. Variables in constant and global state spaces with no explicit initializer are initialized to zero by default. Initializers are not allowed in external variable declarations. + +Variable names appearing in initializers represent the address of the variable; this can be used to statically initialize a pointer to a variable. Initializers may also contain _var+offset_ expressions, where _offset_ is a byte offset added to the address of _var_. Only variables in `.global` or `.const` state spaces may be used in initializers. By default, the resulting address is the offset in the variable’s state space (as is the case when taking the address of a variable with a `mov` instruction). An operator, `generic()`, is provided to create a generic address for variables used in initializers. + +Starting PTX ISA version 7.1, an operator `mask()` is provided, where `mask` is an integer immediate. The only allowed expressions in the `mask()` operator are integer constant expression and symbol expression representing address of variable. The `mask()` operator extracts `n` consecutive bits from the expression used in initializers and inserts these bits at the lowest position of the initialized variable. The number `n` and the starting position of the bits to be extracted is specified by the integer immediate `mask`. PTX ISA version 7.1 only supports extracting a single byte starting at byte boundary from the address of the variable. PTX ISA version 7.3 supports Integer constant expression as an operand in the `mask()` operator. + +Supported values for `mask` are: 0xFF, 0xFF00, 0XFF0000, 0xFF000000, 0xFF00000000, 0xFF0000000000, 0xFF000000000000, 0xFF00000000000000. + +Examples + +.const .u32 foo = 42; + .global .u32 bar[] = { 2, 3, 5 }; + .global .u32 p1 = foo; // offset of foo in .const space + .global .u32 p2 = generic(foo); // generic address of foo + + // array of generic-address pointers to elements of bar + .global .u32 parr[] = { generic(bar), generic(bar)+4, + generic(bar)+8 }; + + // examples using mask() operator are pruned for brevity + .global .u8 addr[] = {0xff(foo), 0xff00(foo), 0xff0000(foo), ...}; + + .global .u8 addr2[] = {0xff(foo+4), 0xff00(foo+4), 0xff0000(foo+4),...} + + .global .u8 addr3[] = {0xff(generic(foo)), 0xff00(generic(foo)),...} + + .global .u8 addr4[] = {0xff(generic(foo)+4), 0xff00(generic(foo)+4),...} + + // mask() operator with integer const expression + .global .u8 addr5[] = { 0xFF(1000 + 546), 0xFF00(131187), ...}; + +Note + +PTX 3.1 redefines the default addressing for global variables in initializers, from generic addresses to offsets in the global state space. Legacy PTX code is treated as having an implicit `generic()` operator for each global variable used in an initializer. PTX 3.1 code should either include explicit `generic()` operators in initializers, use `cvta.global` to form generic addresses at runtime, or load from the non-generic address using `ld.global`. + +Device function names appearing in initializers represent the address of the first instruction in the function; this can be used to initialize a table of function pointers to be used with indirect calls. Beginning in PTX ISA version 3.1, kernel function names can be used as initializers e.g. to initialize a table of kernel function pointers, to be used with CUDA Dynamic Parallelism to launch kernels from GPU. See the _CUDA Dynamic Parallelism Programming Guide_ for details. + +Labels cannot be used in initializers. + +Variables that hold addresses of variables or functions should be of type `.u8` or `.u32` or `.u64`. + +Type `.u8` is allowed only if the `mask()` operator is used. + +Initializers are allowed for all types except `.f16`, `.f16x2` and `.pred`. + +Examples + +.global .s32 n = 10; + .global .f32 blur_kernel[][3] + = {{.05,.1,.05},{.1,.4,.1},{.05,.1,.05}}; + + .global .u32 foo[] = { 2, 3, 5, 7, 9, 11 }; + .global .u64 ptr = generic(foo); // generic address of foo[0] + .global .u64 ptr = generic(foo)+8; // generic address of foo[2] \ No newline at end of file diff --git a/content/cuda/docs/ptx-instruction-statements/DOC.md b/content/cuda/docs/ptx-instruction-statements/DOC.md new file mode 100644 index 00000000..66772a4c --- /dev/null +++ b/content/cuda/docs/ptx-instruction-statements/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-instruction-statements +description: Instructions are formed from an instruction opcode followed by a comma-separated + list of zero or more operands, and terminated with a semicolon. Operands may be + register variables, constant expression... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.3.2. Instruction Statements + +--- +title: "4.3.2. Instruction Statements" +section: 4.3.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.3.2. Instruction Statements + + +Instructions are formed from an instruction opcode followed by a comma-separated list of zero or more operands, and terminated with a semicolon. Operands may be register variables, constant expressions, address expressions, or label names. Instructions have an optional guard predicate which controls conditional execution. The guard predicate follows the optional label and precedes the opcode, and is written as `@p`, where `p` is a predicate register. The guard predicate may be optionally negated, written as `@!p`. + +The destination operand is first, followed by source operands. + +Instruction keywords are listed in [Table 2](<#instruction-statements-reserved-instruction-keywords-new>). All instruction keywords are reserved tokens in PTX. + +Table 2 Reserved Instruction Keywords `abs` | `cvta` | `membar` | `setp` | `vabsdiff` +---|---|---|---|--- +`activemask` | `discard` | `min` | `shf` | `vabsdiff2` +`add` | `div` | `mma` | `shfl` | `vabsdiff4` +`addc` | `dp2a` | `mov` | `shl` | `vadd` +`alloca` | `dp4a` | `movmatrix` | `shr` | `vadd2` +`and` | `elect` | `mul` | `sin` | `vadd4` +`applypriority` | `ex2` | `mul24` | `slct` | `vavrg2` +`atom` | `exit` | `multimem` | `sqrt` | `vavrg4` +`bar` | `fence` | `nanosleep` | `st` | `vmad` +`barrier` | `fma` | `neg` | `stackrestore` | `vmax` +`bfe` | `fns` | `not` | `stacksave` | `vmax2` +`bfi` | `getctarank` | `or` | `stmatrix` | `vmax4` +`bfind` | `griddepcontrol` | `pmevent` | `sub` | `vmin` +`bmsk` | `isspacep` | `popc` | `subc` | `vmin2` +`bra` | `istypep` | `prefetch` | `suld` | `vmin4` +`brev` | `ld` | `prefetchu` | `suq` | `vote` +`brkpt` | `ldmatrix` | `prmt` | `sured` | `vset` +`brx` | `ldu` | `rcp` | `sust` | `vset2` +`call` | `lg2` | `red` | `szext` | `vset4` +`clz` | `lop3` | `redux` | `tanh` | `vshl` +`cnot` | `mad` | `rem` | `tcgen05` | `vshr` +`copysign` | `mad24` | `ret` | `tensormap` | `vsub` +`cos` | `madc` | `rsqrt` | `testp` | `vsub2` +`clusterlaunchcontrol` | `mapa` | `sad` | `tex` | `vsub4` +`cp` | `match` | `selp` | `tld4` | `wgmma` +`createpolicy` | `max` | `set` | `trap` | `wmma` +`cvt` | `mbarrier` | `setmaxnreg` | `txq` | `xor` \ No newline at end of file diff --git a/content/cuda/docs/ptx-integer-and-bit-size-comparisons/DOC.md b/content/cuda/docs/ptx-integer-and-bit-size-comparisons/DOC.md new file mode 100644 index 00000000..37c35d72 --- /dev/null +++ b/content/cuda/docs/ptx-integer-and-bit-size-comparisons/DOC.md @@ -0,0 +1,37 @@ +--- +name: ptx-integer-and-bit-size-comparisons +description: The signed integer comparisons are the traditional `eq` (equal), `ne` + (not-equal), `lt` (less-than), `le` (less-than-or-equal), `gt` (greater-than), and + `ge` (greater-than-or-equal). The unsigned comp... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.3.1.1. Integer and Bit-Size Comparisons + +--- +title: "9.3.1.1. Integer and Bit-Size Comparisons" +section: 9.3.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.3.1.1. Integer and Bit-Size Comparisons + + +The signed integer comparisons are the traditional `eq` (equal), `ne` (not-equal), `lt` (less-than), `le` (less-than-or-equal), `gt` (greater-than), and `ge` (greater-than-or-equal). The unsigned comparisons are `eq`, `ne`, `lo` (lower), `ls` (lower-or-same), `hi` (higher), and `hs` (higher-or-same). The bit-size comparisons are `eq` and `ne`; ordering comparisons are not defined for bit-size types. + +[Table 22](<#integer-and-bit-size-comparisons-operators-for-signed-integer-unsigned-integer-and-bit-size-types>) shows the operators for signed integer, unsigned integer, and bit-size types. + +Table 22 Operators for Signed Integer, Unsigned Integer, and Bit-Size Types Meaning | Signed Operator | Unsigned Operator | Bit-Size Operator +---|---|---|--- +`a == b` | `eq` | `eq` | `eq` +`a != b` | `ne` | `ne` | `ne` +`a < b` | `lt` | `lo` | n/a +`a <= b` | `le` | `ls` | n/a +`a > b` | `gt` | `hi` | n/a +`a >= b` | `ge` | `hs` | n/a \ No newline at end of file diff --git a/content/cuda/docs/ptx-integer-bit-manipulation-patterns/DOC.md b/content/cuda/docs/ptx-integer-bit-manipulation-patterns/DOC.md new file mode 100644 index 00000000..29a0d417 --- /dev/null +++ b/content/cuda/docs/ptx-integer-bit-manipulation-patterns/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-integer-bit-manipulation-patterns +description: "PTX integer and bit-manipulation patterns: logic/shift/select primitives, packing/unpacking strategies, and common correctness traps." +metadata: + languages: "cpp" + versions: "9.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,ptx,integer,bit-manipulation,logic,shift,selp,lop3,bfe,bfi,popc,brev,prmt" +--- + +# PTX Integer and Bit-Manipulation Patterns + +Use this page for practical composition of PTX integer/logic instructions in performance-sensitive kernels. + +## Core Primitive Groups + +- Logic: `and`, `or`, `xor`, `not`, `lop3` +- Shift and funnel-shift: `shl`, `shr`, `shf` +- Bitfield extraction/insert: `bfe`, `bfi` +- Bit counting/permutation: `clz`, `popc`, `brev`, `prmt` +- Predicate-style selection: `selp`, `setp` + +## Common Composition Patterns + +- Use `setp + selp` for branchless integer clamps and conditional assignment. +- Use `bfe/bfi` for packed-field decode/encode instead of long mask chains. +- Use `lop3` to fuse multi-step boolean logic into fewer instructions. +- Use `popc` and `clz` for bitset analytics and index derivation. + +## Correctness Traps + +- Signed vs unsigned shift semantics (`shr.s*` vs `shr.u*`) change high-bit fill behavior. +- Type width mismatches silently change mask and overflow behavior. +- Packing/unpacking code must define bit positions and endianness assumptions explicitly. + +## Performance Heuristics + +- Prefer fewer dependent bit-ops in hot loops to reduce scoreboard pressure. +- Validate whether `lop3` or `prmt` reduces instruction count on target architecture. +- Recheck register pressure after replacing arithmetic with heavy bit-manipulation sequences. + +## Related Topics + +- PTX integer instruction index: `../ptx/instructions/integer/DOC.md` +- PTX control flow: `../ptx/instructions/control-flow/DOC.md` +- PTX synchronization and communication: `../ptx/instructions/sync-comm/DOC.md` + +## Official Source Links (Fact Check) + +- PTX Integer Arithmetic Instructions: https://docs.nvidia.com/cuda/parallel-thread-execution/#integer-arithmetic-instructions +- PTX Logic and Shift Instructions: https://docs.nvidia.com/cuda/parallel-thread-execution/#logic-and-shift-instructions +- PTX Comparison and Selection Instructions: https://docs.nvidia.com/cuda/parallel-thread-execution/#comparison-and-selection-instructions + +Last cross-check date: 2026-03-20 + diff --git a/content/cuda/docs/ptx-integer-constant-expression-evaluation/DOC.md b/content/cuda/docs/ptx-integer-constant-expression-evaluation/DOC.md new file mode 100644 index 00000000..fc9b56e8 --- /dev/null +++ b/content/cuda/docs/ptx-integer-constant-expression-evaluation/DOC.md @@ -0,0 +1,60 @@ +--- +name: ptx-integer-constant-expression-evaluation +description: Integer constant expressions are evaluated at compile time according + to a set of rules that determine the type (signed `.s64` versus unsigned `.u64`) + of each sub-expression. These rules are based on t... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.5.5. Integer Constant Expression Evaluation + +--- +title: "4.5.5. Integer Constant Expression Evaluation" +section: 4.5.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.5.5. Integer Constant Expression Evaluation + + +Integer constant expressions are evaluated at compile time according to a set of rules that determine the type (signed `.s64` versus unsigned `.u64`) of each sub-expression. These rules are based on the rules in C, but they’ve been simplified to apply only to 64-bit integers, and behavior is fully defined in all cases (specifically, for remainder and shift operators). + +* Literals are signed unless unsigned is needed to prevent overflow, or unless the literal uses a `U` suffix. For example: + + * `42`, `0x1234`, `0123` are signed. + + * `0xfabc123400000000`, `42U`, `0x1234U` are unsigned. + + * Unary plus and minus preserve the type of the input operand. For example: + + * `+123`, `-1`, `-(-42)` are signed. + + * `-1U`, `-0xfabc123400000000` are unsigned. + + * Unary logical negation (`!`) produces a signed result with value `0` or `1`. + + * Unary bitwise complement (`~`) interprets the source operand as unsigned and produces an unsigned result. + + * Some binary operators require normalization of source operands. This normalization is known as _the usual arithmetic conversions_ and simply converts both operands to unsigned type if either operand is unsigned. + + * Addition, subtraction, multiplication, and division perform the usual arithmetic conversions and produce a result with the same type as the converted operands. That is, the operands and result are unsigned if either source operand is unsigned, and is otherwise signed. + + * Remainder (`%`) interprets the operands as unsigned. Note that this differs from C, which allows a negative divisor but defines the behavior to be implementation dependent. + + * Left and right shift interpret the second operand as unsigned and produce a result with the same type as the first operand. Note that the behavior of right-shift is determined by the type of the first operand: right shift of a signed value is arithmetic and preserves the sign, and right shift of an unsigned value is logical and shifts in a zero bit. + + * AND (`&`), OR (`|`), and XOR (`^`) perform the usual arithmetic conversions and produce a result with the same type as the converted operands. + + * AND_OP (`&&`), OR_OP (`||`), Equal (`==`), and Not_Equal (`!=`) produce a signed result. The result value is 0 or 1. + + * Ordered comparisons (`<`, `<=`, `>`, `>=`) perform the usual arithmetic conversions on source operands and produce a signed result. The result value is `0` or `1`. + + * Casting of expressions to signed or unsigned is supported using (`.s64`) and (`.u64`) casts. + + * For the conditional operator ( `? :` ) , the first operand must be an integer, and the second and third operands are either both integers or both floating-point. The usual arithmetic conversions are performed on the second and third operands, and the result type is the same as the converted type. \ No newline at end of file diff --git a/content/cuda/docs/ptx-integer-constants/DOC.md b/content/cuda/docs/ptx-integer-constants/DOC.md new file mode 100644 index 00000000..15b4cdce --- /dev/null +++ b/content/cuda/docs/ptx-integer-constants/DOC.md @@ -0,0 +1,37 @@ +--- +name: ptx-integer-constants +description: Integer constants are 64-bits in size and are either signed or unsigned, + i.e., every integer constant has type `.s64` or `.u64`. The signed/unsigned nature + of an integer constant is needed to correctl... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.5.1. Integer Constants + +--- +title: "4.5.1. Integer Constants" +section: 4.5.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.5.1. Integer Constants + + +Integer constants are 64-bits in size and are either signed or unsigned, i.e., every integer constant has type `.s64` or `.u64`. The signed/unsigned nature of an integer constant is needed to correctly evaluate constant expressions containing operations such as division and ordered comparisons, where the behavior of the operation depends on the operand types. When used in an instruction or data initialization, each integer constant is converted to the appropriate size based on the data or instruction type at its use. + +Integer literals may be written in decimal, hexadecimal, octal, or binary notation. The syntax follows that of C. Integer literals may be followed immediately by the letter `U` to indicate that the literal is unsigned. + +hexadecimal literal: 0[xX]{hexdigit}+U? + octal literal: 0{octal digit}+U? + binary literal: 0[bB]{bit}+U? + decimal literal {nonzero-digit}{digit}*U? + +Integer literals are non-negative and have a type determined by their magnitude and optional type suffix as follows: literals are signed (`.s64`) unless the value cannot be fully represented in `.s64` or the unsigned suffix is specified, in which case the literal is unsigned (`.u64`). + +The predefined integer constant `WARP_SZ` specifies the number of threads per warp for the target platform; to date, all target architectures have a `WARP_SZ` value of 32. \ No newline at end of file diff --git a/content/cuda/docs/ptx-interleave-layout/DOC.md b/content/cuda/docs/ptx-interleave-layout/DOC.md new file mode 100644 index 00000000..39a0a86e --- /dev/null +++ b/content/cuda/docs/ptx-interleave-layout/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-interleave-layout +description: 'Tensor can be interleaved and the following interleave layouts are supported:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.5.6. Interleave layout + +--- +title: "5.5.6. Interleave layout" +section: 5.5.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.5.6. Interleave layout + + +Tensor can be interleaved and the following interleave layouts are supported: + +* No interleave (NDHWC) + + * 8 byte interleave (NC/8DHWC8) : C8 utilizes 16 bytes in memory assuming 2B per channel. + + * 16 byte interleave (NC/16HWC16) : C16 utilizes 32 bytes in memory assuming 4B per channel. + +The _C_ information is organized in slices where sequential C elements are grouped in 16 byte or 32 byte quantities. + +If the total number of channels is not a multiple of the number of channels per slice, then the last slice must be padded with zeros to make it complete 16B or 32B slice. + +Interleaved layouts are supported only for the dimensionalities : 3D, 4D and 5D. + +The interleave layout is not supported for `.im2col::w` and `.im2col::w::128` modes. \ No newline at end of file diff --git a/content/cuda/docs/ptx-isspacep/DOC.md b/content/cuda/docs/ptx-isspacep/DOC.md new file mode 100644 index 00000000..97ef7b93 --- /dev/null +++ b/content/cuda/docs/ptx-isspacep/DOC.md @@ -0,0 +1,79 @@ +--- +name: ptx-isspacep +description: Query whether a generic address falls within a specified state space + window. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.19. Data Movement and Conversion Instructions:isspacep + +--- +title: "9.7.9.19. Data Movement and Conversion Instructions:isspacep" +section: 9.7.9.19 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.19. Data Movement and Conversion Instructions:isspacep + + +`isspacep` + +Query whether a generic address falls within a specified state space window. + +Syntax + +isspacep.space p, a; // result is .pred + + .space = { const, .global, .local, .shared{::cta, ::cluster}, .param{::entry} }; + +Description + +Write predicate register `p` with `1` if generic address a falls within the specified state space window and with `0` otherwise. Destination `p` has type `.pred`; the source address operand must be of type `.u32` or `.u64`. + +`isspacep.param{::entry}` returns `1` if the generic address falls within the window of [Kernel Function Parameters](<#kernel-function-parameters>), otherwise returns `0`. If `.param` is specified without any sub-qualifiers then it defaults to `.param::entry`. + +`isspacep.global` returns `1` for [Kernel Function Parameters](<#kernel-function-parameters>) as `.param` window is contained within the `.global` window. + +If no sub-qualifier is specified with `.shared` state space, then `::cta` is assumed by default. + +Note + +`ispacep.shared::cluster` will return 1 for every shared memory address that is accessible to the threads in the cluster, whereas `ispacep.shared::cta` will return 1 only if the address is of a variable declared in the executing CTA. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +`isspacep.const` introduced in PTX ISA version 3.1. + +`isspacep.param` introduced in PTX ISA version 7.7. + +Support for `::cta` and `::cluster` sub-qualifiers introduced in PTX ISA version 7.8. + +Support for sub-qualifier `::entry` on `.param` space introduced in PTX ISA version 8.3. + +Target ISA Notes + +`isspacep` requires `sm_20` or higher. + +`isspacep.param{::entry}` requires `sm_70` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Examples + +isspacep.const iscnst, cptr; + isspacep.global isglbl, gptr; + isspacep.local islcl, lptr; + isspacep.shared isshrd, sptr; + isspacep.param::entry isparam, pptr; + isspacep.shared::cta isshrdcta, sptr; + isspacep.shared::cluster ishrdany sptr; \ No newline at end of file diff --git a/content/cuda/docs/ptx-issue-granularity/DOC.md b/content/cuda/docs/ptx-issue-granularity/DOC.md new file mode 100644 index 00000000..dfefa854 --- /dev/null +++ b/content/cuda/docs/ptx-issue-granularity/DOC.md @@ -0,0 +1,98 @@ +--- +name: ptx-issue-granularity +description: Each of the `tcgen05` operation has different requirements for the number + of threads/warps that needs to issue them. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.5. Issue Granularity + +--- +title: "9.7.16.5. Issue Granularity" +section: 9.7.16.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.5. Issue Granularity + + +Each of the `tcgen05` operation has different requirements for the number of threads/warps that needs to issue them. + +The following table lists the execution granularity requirements of each of the `tcgen05` operation: + +Table 46 Execution granularity requirements for tcgen05 operations tcgen05 operation | .cta_group | Issue Granularity +---|---|--- + + + .mma, + .cp, + .shift, + .commit + + +| ::1 | An issue from a single thread in the current CTA would initiate the base operation. +::2 | Issue from a single thread from the [CTA-Pair](<#tcgen05-cta-pair>) would initiate the base operation. When the current CTA issues the operation, the peer CTA should be active and should not have exited. + + + .alloc, + .dealloc, + .relinquish_alloc_permit + + +| ::1 | Issue from a single warp in the current CTA would initiate the allocation management instruction. +::2 | Issue from two warps, one in each of the current CTA and its [Peer CTA](<#tcgen05-peer-cta>), in order to collectively perform the operation, i.e., the first warp to perform the operation could block until the the second warp in the [Peer CTA](<#tcgen05-peer-cta>) also performs the operation (see examples below). + + + .ld, + .st, + .wait::{ld, st} + + +| N/A | Issue from a warp in the current CTA can access only 1/4 of the Tensor Memory of the current CTA. So, a warpgroup is needed to access the entire Tensor Memory of the current CTA. + + + .fence::* + + +| N/A | A thread needs to fence all its accesses to the tensor memory that it wants to order with other accesses to the tensor memory from other threads. + +The following example shows that: + +* Before attempting to deallocate Tensor Memory, it suffices to ensure that there are no concurrent Tensor Memory accesses from the [Peer CTA](<#tcgen05-peer-cta>). + + * Warps can immediately exit after deallocating Tensor Memory; no extra synchronization required. + +Table 47 Example of deallocating Tensor Memory before CTA exit. CTA0 Warp | CTA1 Warp +---|--- +barrier.cluster.arrive; barrier.cluster.wait; tcgen05.dealloc.2cta.sync.aligned; exit; | barrier.cluster.arrive; barrier.cluster.wait; tcgen05.dealloc.2cta.sync.aligned; exit; + +This example uses a cluster barrier for illustration purposes but in practice other synchronization mechanisms are often used. + +The following example illustrates a scenario in which the program exhibits non-deterministic behavior due to incorrect synchronizaton because `.dealloc` may or may not block: + +Table 48 Example of non-determinstic hang due to incorrect synchronization CTA0 Warp | CTA1 Warp +---|--- +barrier.cluster.arrive; barrier.cluster.wait; tcgen05.dealloc.2cta.sync.aligned; exit; | tcgen05.dealloc.2cta.sync.aligned; barrier.cluster.arrive; barrier.cluster.wait; exit; + +##### 9.7.16.5.1. [CTA Pair](<#tcgen05-cta-pair>) + +Any 2 CTAs within the cluster whose `%cluster_ctarank` differs by the last bit only is said to form a CTA pair. + +Within a CTA pair, the CTA whose last bit in the `%cluster_ctarank` is: + + * 0 is termed the even numbered CTA within the CTA pair. + + * 1 is termed as the odd numbered CTA within the CTA pair. + + +Most of the `tcgen05` operations can either execute at a single CTA level granularity OR at a CTA pair level granularity. When a `tcgen05` operation is performed at CTA pair granularity, the Tensor Memory of both the CTAs within the CTA pair are accessed. The set of threads that need to issue the `tcgen05` operation is listed in the [Issue Granularity](<#tcgen05-issue-granularity>). + +##### 9.7.16.5.2. [Peer CTA](<#tcgen05-peer-cta>) + +The peer CTA of the odd CTA within the CTA pair is the even CTA in the same pair. Similarly, the peer CTA of the even CTA within the CTA pair is the odd CTA in the same pair. \ No newline at end of file diff --git a/content/cuda/docs/ptx-istypep/DOC.md b/content/cuda/docs/ptx-istypep/DOC.md new file mode 100644 index 00000000..ed8ec61f --- /dev/null +++ b/content/cuda/docs/ptx-istypep/DOC.md @@ -0,0 +1,51 @@ +--- +name: ptx-istypep +description: Query whether a register points to an opaque variable of a specified + type. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.10.6. Texture Instructions:istypep + +--- +title: "9.7.10.6. Texture Instructions:istypep" +section: 9.7.10.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.10.6. Texture Instructions:istypep + + +`istypep` + +Query whether a register points to an opaque variable of a specified type. + +Syntax + +istypep.type p, a; // result is .pred + + .type = { .texref, .samplerref, .surfref }; + +Description + +Write predicate register `p` with 1 if register `a` points to an opaque variable of the specified type, and with 0 otherwise. Destination `p` has type `.pred`; the source address operand must be of type `.u64`. + +PTX ISA Notes + +Introduced in PTX ISA version 4.0. + +Target ISA Notes + +istypep requires `sm_30` or higher. + +Examples + +istypep.texref istex, tptr; + istypep.samplerref issampler, sptr; + istypep.surfref issurface, surfptr; \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-and-function-directivesalias/DOC.md b/content/cuda/docs/ptx-kernel-and-function-directivesalias/DOC.md new file mode 100644 index 00000000..286c8316 --- /dev/null +++ b/content/cuda/docs/ptx-kernel-and-function-directivesalias/DOC.md @@ -0,0 +1,77 @@ +--- +name: ptx-kernel-and-function-directivesalias +description: Define an alias to existing function symbol. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.2.3. Kernel and Function Directives:.alias + +--- +title: "11.2.3. Kernel and Function Directives:.alias" +section: 11.2.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.2.3. Kernel and Function Directives:.alias + + +`.alias` + +Define an alias to existing function symbol. + +Syntax + +.alias fAlias, fAliasee; + +Description + +`.alias` is a module scope directive that defines identifier `fAlias` to be an alias to function specified by `fAliasee`. + +Both `fAlias` and `fAliasee` are non-entry function symbols. + +Identifier `fAlias` is a function declaration without body. + +Identifier `fAliasee` is a function symbol which must be defined in the same module as `.alias` declaration. Function `fAliasee` cannot have `.weak` linkage. + +Prototype of `fAlias` and `fAliasee` must match. + +Program can use either `fAlias` or `fAlisee` identifiers to reference function defined with `fAliasee`. + +PTX ISA Notes + +`.alias` directive introduced in PTX ISA 6.3. + +Target ISA Notes + +`.alias` directive requires `sm_30` or higher. + +Examples + +.visible .func foo(.param .u32 p) { + ... + } + .visible .func bar(.param .u32 p); + .alias bar, foo; + .entry test() + { + .param .u32 p; + ... + call foo, (p); // call foo directly + ... + .param .u32 p; + call bar, (p); // call foo through alias + } + .entry filter ( .param .b32 x, .param .b32 y, .param .b32 z ) + { + .reg .b32 %r1, %r2, %r3; + ld.param.b32 %r1, [x]; + ld.param.b32 %r2, [y]; + ld.param.b32 %r3, [z]; + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-and-function-directivesentry/DOC.md b/content/cuda/docs/ptx-kernel-and-function-directivesentry/DOC.md new file mode 100644 index 00000000..bb0cb893 --- /dev/null +++ b/content/cuda/docs/ptx-kernel-and-function-directivesentry/DOC.md @@ -0,0 +1,89 @@ +--- +name: ptx-kernel-and-function-directivesentry +description: Kernel entry point and body, with optional parameters. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.2.1. Kernel and Function Directives:.entry + +--- +title: "11.2.1. Kernel and Function Directives:.entry" +section: 11.2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.2.1. Kernel and Function Directives:.entry + + +`.entry` + +Kernel entry point and body, with optional parameters. + +Syntax + +.entry kernel-name ( param-list ) kernel-body + .entry kernel-name kernel-body + +Description + +Defines a kernel entry point name, parameters, and body for the kernel function. + +Parameters are passed via `.param` space memory and are listed within an optional parenthesized parameter list. Parameters may be referenced by name within the kernel body and loaded into registers using `ld.param{::entry}` instructions. + +In addition to normal parameters, opaque `.texref`, `.samplerref`, and `.surfref` variables may be passed as parameters. These parameters can only be referenced by name within texture and surface load, store, and query instructions and cannot be accessed via `ld.param` instructions. + +The shape and size of the CTA executing the kernel are available in special registers. + +Semantics + +Specify the entry point for a kernel program. + +At kernel launch, the kernel dimensions and properties are established and made available via special registers, e.g., `%ntid`, `%nctaid`, etc. + +PTX ISA Notes + +For PTX ISA version 1.4 and later, parameter variables are declared in the kernel parameter list. For PTX ISA versions 1.0 through 1.3, parameter variables are declared in the kernel body. + +The maximum memory size supported by PTX for normal (non-opaque type) parameters is 32764 bytes. Depending upon the PTX ISA version, the parameter size limit varies. The following table shows the allowed parameter size for a PTX ISA version: + +PTX ISA Version | Maximum parameter size (In bytes) +---|--- +PTX ISA version 8.1 and above | 32764 +PTX ISA version 1.5 and above | 4352 +PTX ISA version 1.4 and above | 256 + +The CUDA and OpenCL drivers support the following limits for parameter memory: + +Driver | Parameter memory size +---|--- +CUDA | 256 bytes for `sm_1x`, 4096 bytes for `sm_2x and higher`, 32764 bytes fo `sm_70` and higher +OpenCL | 32764 bytes for `sm_70` and higher, 4352 bytes on `sm_6x` and lower + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry cta_fft + .entry filter ( .param .b32 x, .param .b32 y, .param .b32 z ) + { + .reg .b32 %r<99>; + ld.param.b32 %r1, [x]; + ld.param.b32 %r2, [y]; + ld.param.b32 %r3, [z]; + ... + } + + .entry prefix_sum ( .param .align 4 .s32 pitch[8000] ) + { + .reg .s32 %t; + ld.param::entry.s32 %t, [pitch]; + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-and-function-directivesfunc/DOC.md b/content/cuda/docs/ptx-kernel-and-function-directivesfunc/DOC.md new file mode 100644 index 00000000..59f9f04d --- /dev/null +++ b/content/cuda/docs/ptx-kernel-and-function-directivesfunc/DOC.md @@ -0,0 +1,138 @@ +--- +name: ptx-kernel-and-function-directivesfunc +description: Function definition. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.2.2. Kernel and Function Directives:.func + +--- +title: "11.2.2. Kernel and Function Directives:.func" +section: 11.2.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.2.2. Kernel and Function Directives:.func + + +`.func` + +Function definition. + +Syntax + +.func {.attribute(attr-list)} fname {.noreturn} {.abi_preserve N} {.abi_preserve_control N} function-body + .func {.attribute(attr-list)} fname (param-list) {.noreturn} {.abi_preserve N} {.abi_preserve_control N} function-body + .func {.attribute(attr-list)} (ret-param) fname (param-list) {.abi_preserve N} {.abi_preserve_control N} function-body + +Description + +Defines a function, including input and return parameters and optional function body. + +An optional `.noreturn` directive indicates that the function does not return to the caller function. `.noreturn` directive cannot be specified on functions which have return parameters. See the description of `.noreturn` directive in [Performance-Tuning Directives: .noreturn](<#performance-tuning-directives-noreturn>). + +An optional `.attribute` directive specifies additional information associated with the function. See the description of [Variable and Function Attribute Directive: .attribute](<#variable-and-function-attribute-directive-attribute>) for allowed attributes. + +Optional `.abi_preserve` and `.abi_preserve_control` directives are used to specify the number of general purpose registers and control registers. See description of [Performance-Tuning Directives: .abi_preserve](<#performance-tuning-directives-abi-preserve>) and [Performance-Tuning Directives: .abi_preserve_control](<#performance-tuning-directives-abi-preserve-control>) for more details. + +Directives, if any specified, for a function, e.g. `.noreturn`, must be specified consistently between function declaration and definition. + +A `.func` definition with no body provides a function prototype. + +The parameter lists define locally-scoped variables in the function body. Parameters must be base types in either the register or parameter state space. Parameters in register state space may be referenced directly within instructions in the function body. Parameters in `.param` space are accessed using `ld.param{::func}` and `st.param{::func}` instructions in the body. Parameter passing is call-by-value. + +The last parameter in the parameter list may be a `.param` array of type `.b8` with no size specified. It is used to pass an arbitrary number of parameters to the function packed into a single array object. + +When calling a function with such an unsized last argument, the last argument may be omitted from the `call` instruction if no parameter is passed through it. Accesses to this array parameter must be within the bounds of the array. The result of an access is undefined if no array was passed, or if the access was outside the bounds of the actual array being passed. + +Semantics + +The PTX syntax hides all details of the underlying calling convention and ABI. + +The implementation of parameter passing is left to the optimizing translator, which may use a combination of registers and stack locations to pass parameters. + +Release Notes + +For PTX ISA version 1.x code, parameters must be in the register state space, there is no stack, and recursion is illegal. + +PTX ISA versions 2.0 and later with target `sm_20` or higher allow parameters in the `.param` state space, implements an ABI with stack, and supports recursion. + +PTX ISA versions 2.0 and later with target `sm_20` or higher support at most one return value. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Support for unsized array parameter introduced in PTX ISA version 6.0. + +Support for `.noreturn` directive introduced in PTX ISA version 6.4. + +Support for `.attribute` directive introduced in PTX ISA version 8.0. + +Support for `.abi_preserve` and `.abi_preserve_control` directives introduced in PTX ISA version 9.0. + +Target ISA Notes + +Functions without unsized array parameter supported on all target architectures. + +Unsized array parameter requires `sm_30` or higher. + +`.noreturn` directive requires `sm_30` or higher. + +`.attribute` directive requires `sm_90` or higher. + +`.abi_preserve` and `.abi_preserve_control` directives require `sm_80` or higher. + +Examples + +.func (.reg .b32 rval) foo (.reg .b32 N, .reg .f64 dbl) + { + .reg .b32 localVar; + + ... use N, dbl; + other code; + + mov.b32 rval,result; + ret; + } + + ... + call (fooval), foo, (val0, val1); // return value in fooval + ... + + .func foo (.reg .b32 N, .reg .f64 dbl) .noreturn + { + .reg .b32 localVar; + ... use N, dbl; + other code; + mov.b32 rval, result; + ret; + } + ... + call foo, (val0, val1); + ... + + .func (.param .u32 rval) bar(.param .u32 N, .param .align 4 .b8 numbers[]) + { + .reg .b32 input0, input1; + ld.param.b32 input0, [numbers + 0]; + ld.param.b32 input1, [numbers + 4]; + ... + other code; + ret; + } + ... + + .param .u32 N; + .param .align 4 .b8 numbers[8]; + st.param.u32 [N], 2; + st.param.b32 [numbers + 0], 5; + st.param.b32 [numbers + 4], 10; + call (rval), bar, (N, numbers); + ... \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-function-parameter-attributes/DOC.md b/content/cuda/docs/ptx-kernel-function-parameter-attributes/DOC.md new file mode 100644 index 00000000..bf2dc6d7 --- /dev/null +++ b/content/cuda/docs/ptx-kernel-function-parameter-attributes/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-kernel-function-parameter-attributes +description: Kernel function parameters may be declared with an optional .ptr attribute + to indicate that a parameter is a pointer to memory, and also indicate the state + space and alignment of the memory being poin... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.6.2. Kernel Function Parameter Attributes + +--- +title: "5.1.6.2. Kernel Function Parameter Attributes" +section: 5.1.6.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.1.6.2. Kernel Function Parameter Attributes + + +Kernel function parameters may be declared with an optional .ptr attribute to indicate that a parameter is a pointer to memory, and also indicate the state space and alignment of the memory being pointed to. [Kernel Parameter Attribute: .ptr](<#kernel-parameter-attribute-ptr>) describes the `.ptr` kernel parameter attribute. \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-function-parameters/DOC.md b/content/cuda/docs/ptx-kernel-function-parameters/DOC.md new file mode 100644 index 00000000..3ea212a3 --- /dev/null +++ b/content/cuda/docs/ptx-kernel-function-parameters/DOC.md @@ -0,0 +1,55 @@ +--- +name: ptx-kernel-function-parameters +description: Each kernel function definition includes an optional list of parameters. + These parameters are addressable, read-only variables declared in the `.param` state + space. Values passed from the host to the ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.6.1. Kernel Function Parameters + +--- +title: "5.1.6.1. Kernel Function Parameters" +section: 5.1.6.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.1.6.1. Kernel Function Parameters + + +Each kernel function definition includes an optional list of parameters. These parameters are addressable, read-only variables declared in the `.param` state space. Values passed from the host to the kernel are accessed through these parameter variables using `ld.param` instructions. The kernel parameter variables are shared across all CTAs from all clusters within a grid. + +The address of a kernel parameter may be moved into a register using the `mov` instruction. The resulting address is in the `.param` state space and is accessed using `ld.param` instructions. + +Example + +.entry foo ( .param .b32 N, .param .align 8 .b8 buffer[64] ) + { + .reg .u32 %n; + .reg .f64 %d; + + ld.param.u32 %n, [N]; + ld.param.f64 %d, [buffer]; + ... + +Example + +.entry bar ( .param .b32 len ) + { + .reg .u32 %ptr, %n; + + mov.u32 %ptr, len; + ld.param.u32 %n, [%ptr]; + ... + +Kernel function parameters may represent normal data values, or they may hold addresses to objects in constant, global, local, or shared state spaces. In the case of pointers, the compiler and runtime system need information about which parameters are pointers, and to which state space they point. Kernel parameter attribute directives are used to provide this information at the PTX level. See [Kernel Function Parameter Attributes](<#kernel-function-parameter-attributes>) for a description of kernel parameter attribute directives. + +Note + +The current implementation does not allow creation of generic pointers to constant variables (`cvta.const`) in programs that have pointers to constant buffers passed as kernel parameters. \ No newline at end of file diff --git a/content/cuda/docs/ptx-kernel-parameter-attributeptr/DOC.md b/content/cuda/docs/ptx-kernel-parameter-attributeptr/DOC.md new file mode 100644 index 00000000..034f7cea --- /dev/null +++ b/content/cuda/docs/ptx-kernel-parameter-attributeptr/DOC.md @@ -0,0 +1,58 @@ +--- +name: ptx-kernel-parameter-attributeptr +description: Kernel parameter alignment attribute. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.6.3. Kernel Parameter Attribute:.ptr + +--- +title: "5.1.6.3. Kernel Parameter Attribute:.ptr" +section: 5.1.6.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.1.6.3. Kernel Parameter Attribute:.ptr + + +`.ptr` + +Kernel parameter alignment attribute. + +Syntax + +.param .type .ptr .space .align N varname + .param .type .ptr .align N varname + + .space = { .const, .global, .local, .shared }; + +Description + +Used to specify the state space and, optionally, the alignment of memory pointed to by a pointer type kernel parameter. The alignment value _N_ , if present, must be a power of two. If no state space is specified, the pointer is assumed to be a generic address pointing to one of const, global, local, or shared memory. If no alignment is specified, the memory pointed to is assumed to be aligned to a 4 byte boundary. + +Spaces between `.ptr`, `.space`, and `.align` may be eliminated to improve readability. + +PTX ISA Notes + +* Introduced in PTX ISA version 2.2. + + * Support for generic addressing of .const space added in PTX ISA version 3.1. + +Target ISA Notes + +* Supported on all target architectures. + +Examples + +.entry foo ( .param .u32 param1, + .param .u32 .ptr.global.align 16 param2, + .param .u32 .ptr.const.align 8 param3, + .param .u32 .ptr.align 16 param4 // generic address + // pointer + ) { .. } \ No newline at end of file diff --git a/content/cuda/docs/ptx-labels-and-function-names-as-operands/DOC.md b/content/cuda/docs/ptx-labels-and-function-names-as-operands/DOC.md new file mode 100644 index 00000000..1f00edbb --- /dev/null +++ b/content/cuda/docs/ptx-labels-and-function-names-as-operands/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-labels-and-function-names-as-operands +description: Labels and function names can be used only in `bra`/`brx.idx` and `call` + instructions respectively. Function names can be used in `mov` instruction to get + the address of the function into a register, ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.4.4. Labels and Function Names as Operands + +--- +title: "6.4.4. Labels and Function Names as Operands" +section: 6.4.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 6.4.4. Labels and Function Names as Operands + + +Labels and function names can be used only in `bra`/`brx.idx` and `call` instructions respectively. Function names can be used in `mov` instruction to get the address of the function into a register, for use in an indirect call. + +Beginning in PTX ISA version 3.1, the `mov` instruction may be used to take the address of kernel functions, to be passed to a system call that initiates a kernel launch from the GPU. This feature is part of the support for CUDA Dynamic Parallelism. See the _CUDA Dynamic Parallelism Programming Guide_ for details. \ No newline at end of file diff --git a/content/cuda/docs/ptx-ld/DOC.md b/content/cuda/docs/ptx-ld/DOC.md new file mode 100644 index 00000000..ff4fb73a --- /dev/null +++ b/content/cuda/docs/ptx-ld/DOC.md @@ -0,0 +1,261 @@ +--- +name: ptx-ld +description: Load a register variable from an addressable state space variable. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.8. Data Movement and Conversion Instructions:ld + +--- +title: "9.7.9.8. Data Movement and Conversion Instructions:ld" +section: 9.7.9.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.8. Data Movement and Conversion Instructions:ld + + +`ld` + +Load a register variable from an addressable state space variable. + +Syntax + +ld{.weak}{.ss}{.cop}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{.unified}{, cache-policy}; + + ld{.weak}{.ss}{.level1::eviction_priority}{.level2::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{.unified}{, cache-policy}; + + ld.volatile{.ss}{.level::prefetch_size}{.vec}.type d, [a]; + + ld.relaxed.scope{.ss}{.level1::eviction_priority}{.level2::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{, cache-policy}; + + ld.acquire.scope{.ss}{.level1::eviction_priority}{.level2::eviction_priority}{.level::cache_hint}{.level::prefetch_size}{.vec}.type d, [a]{, cache-policy}; + + ld.mmio.relaxed.sys{.global}.type d, [a]; + + .ss = { .const, .global, .local, .param{::entry, ::func}, .shared{::cta, ::cluster} }; + .cop = { .ca, .cg, .cs, .lu, .cv }; + .level1::eviction_priority = { .L1::evict_normal, .L1::evict_unchanged, + .L1::evict_first, .L1::evict_last, .L1::no_allocate }; + .level2::eviction_priority = {.L2::evict_normal, .L2::evict_first, .L2::evict_last}; + .level::cache_hint = { .L2::cache_hint }; + .level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B } + .scope = { .cta, .cluster, .gpu, .sys }; + .vec = { .v2, .v4, .v8 }; + .type = { .b8, .b16, .b32, .b64, .b128, + .u8, .u16, .u32, .u64, + .s8, .s16, .s32, .s64, + .f32, .f64 }; + +Description + +Load register variable `d` from the location specified by the source address operand `a` in specified state space. If no state space is given, perform the load using [Generic Addressing](<#generic-addressing>). + +If no sub-qualifier is specified with `.shared` state space, then `::cta` is assumed by default. + +Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>) + +If no sub-qualifier is specified with `.param` state space, then: + +* `::func` is assumed when access is inside a device function. + + * `::entry` is assumed when accessing kernel function parameters from entry function. Otherwise, when accessing device function parameters or any other `.param` variables from entry function `::func` is assumed by default. + +For `ld.param::entry` instruction, operand a must be a kernel parameter address, otherwise behavior is undefined. For `ld.param::func` instruction, operand a must be a device function parameter address, otherwise behavior is undefined. + +Instruction `ld.param{::func}` used for reading value returned from device function call cannot be predicated. See [Parameter State Space](<#parameter-state-space>) and [Function Declarations and Definitions](<#function-declarations-and-definitions>) for descriptions of the proper use of `ld.param`. + +The `.relaxed` and `.acquire` qualifiers indicate memory synchronization as described in the [Memory Consistency Model](<#memory-consistency-model>). The `.scope` qualifier indicates the set of threads with which an `ld.relaxed` or `ld.acquire` instruction can directly synchronize1. The `.weak` qualifier indicates a memory instruction with no synchronization. The effects of this instruction become visible to other threads only when synchronization is established by other means. + +The semantic details of `.mmio` qualifier are described in the [Memory Consistency Model](<#memory-consistency-model>). Only `.sys` thread scope is valid for `ld.mmio` operation. The qualifiers `.mmio` and `.relaxed` must be specified together. + +The semantic details of `.volatile` qualifier are described in the [Memory Consistency Model](<#memory-consistency-model>). + +The `.weak`, `.volatile`, `.relaxed` and `.acquire` qualifiers are mutually exclusive. When none of these is specified, the `.weak` qualifier is assumed by default. + +`.relaxed` and `.acquire`: + +* May be used with `.global`, `.shared` spaces, or with generic addressing where the address points to `.global` or `.shared` space. + + * Cache operations are not allowed. + +`.volatile`: + +* May be used with `.global`, `.shared`, `.local` spaces, or with generic addressing where the address points to `.global`, `.shared`, or `.local` space. + + * Cache operations are not allowed. + +`.mmio`: + +* May be used only with `.global` space or with generic addressing where the address points to `.global` space. + +The optional qualifier `.unified` must be specified on operand `a` if `a` is the address of a variable declared with `.unified` attribute as described in [Variable and Function Attribute Directive: .attribute](<#variable-and-function-attribute-directive-attribute>). + +The `.v8` (`.vec`) qualifier is supported if: + +* `.type` is `.b32` or `.s32` or `.u32` or `.f32` AND + + * State space is `.global` or with generic addressing where address points to `.global` state space + +The `.v4` (`.vec`) qualifier with type `.b64` or `.s64` or `.u64` or `.f64` is supported if: + +* State space is `.global` or with generic addressing where address points to `.global` state space + +Qualifiers `.level1::eviction_priority` and `.level2::eviction_priority` specify the eviction policy for L1 and L2 cache respectively which may be applied during memory access. + +Qualifier `.level2::eviction_priority` is supported if: + +* `.vec` is `.v8` and `.type` is `.b32` or `.s32` or `.u32` or `.f32` + + * AND Operand `d` is vector of 8 registers with type specified with `.type` + + * OR `.vec` is `.v4` and `.type` is `.b64` or `.s64` or `.u64` or `.f64` + + * AND Operand `d` is vector of 4 registers with type specified with `.type` + +Optionally, sink symbol ‘_’ can be used in vector expression `d` when: + +* `.vec` is `.v8` and `.type` is `.b32` or `.s32` or `.u32` or `.f32` OR + + * `.vec` is `.v4` and `.type` is `.b64` or `.s64` or `.u64` or `.f64` + +which indicates that data from corresponding memory location is not read. + +The `.level::prefetch_size` qualifier is a hint to fetch additional data of the specified size into the respective cache level.The sub-qualifier `prefetch_size` can be set to either of `64B`, `128B`, `256B` thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes respectively. + +The qualifier `.level::prefetch_size` may only be used with `.global` state space and with generic addressing where the address points to `.global` state space. If the generic address does not fall within the address window of the global memory, then the prefetching behavior is undefined. + +The `.level::prefetch_size` qualifier is treated as a performance hint only. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +The qualifiers `.unified` and `.level::cache_hint` are only supported for `.global` state space and for generic addressing where the address points to the `.global` state space. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +1 This synchronization is further extended to other threads through the transitive nature of _causality order_ , as described in the memory consistency model. + +Semantics + +d = a; // named variable a + d = *(&a+immOff) // variable-plus-offset + d = *a; // register + d = *(a+immOff); // register-plus-offset + d = *(immAddr); // immediate address + +Notes + +Destination `d` must be in the `.reg` state space. + +A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types. See [Table 28](<#operand-size-exceeding-instruction-type-size-relaxed-type-checking-rules-destination-operands>) for a description of these relaxed type-checking rules. + +`.f16` data may be loaded using `ld.b16`, and then converted to `.f32` or `.f64` using `cvt` or can be used in half precision floating point instructions. + +`.f16x2` data may be loaded using `ld.b32` and then used in half precision floating point instructions. + +PTX ISA Notes + +ld introduced in PTX ISA version 1.0. `ld.volatile` introduced in PTX ISA version 1.1. + +Generic addressing and cache operations introduced in PTX ISA version 2.0. + +Support for scope qualifier, `.relaxed`, `.acquire`, `.weak` qualifiers introduced in PTX ISA version 6.0. + +Support for generic addressing of .const space added in PTX ISA version 3.1. + +Support for `.level1::eviction_priority`, `.level::prefetch_size` and `.level::cache_hint` qualifiers introduced in PTX ISA version 7.4. + +Support for `.cluster` scope qualifier introduced in PTX ISA version 7.8. + +Support for `::cta` and `::cluster` sub-qualifiers introduced in PTX ISA version 7.8. + +Support for `.unified` qualifier introduced in PTX ISA version 8.0. + +Support for `.mmio` qualifier introduced in PTX ISA version 8.2. + +Support for `::entry` and `::func` sub-qualifiers on `.param` space introduced in PTX ISA version 8.3. + +Support for `.b128` type introduced in PTX ISA version 8.3. + +Support for `.sys` scope with `.b128` type introduced in PTX ISA version 8.4. + +Support for `.level2::eviction_priority` qualifier and `.v8.b32`/`.v4.b64` introduced in PTX ISA version 8.8. + +Support for `.volatile` qualifier with `.local` state space introduced in PTX ISA version 9.1. + +Target ISA Notes + +`ld.f64` requires `sm_13` or higher. + +Support for scope qualifier, `.relaxed`, `.acquire`, `.weak` qualifiers require `sm_70` or higher. + +Generic addressing requires `sm_20` or higher. + +Cache operations require `sm_20` or higher. + +Support for `.level::eviction_priority` qualifier requires `sm_70` or higher. + +Support for `.level::prefetch_size` qualifier requires `sm_75` or higher. + +Support for `.L2::256B` and `.L2::cache_hint` qualifiers requires `sm_80` or higher. + +Support for `.cluster` scope qualifier requires `sm_90` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Support for `.unified` qualifier requires `sm_90` or higher. + +Support for `.mmio` qualifier requires `sm_70` or higher. + +Support for `.b128` type requires `sm_70` or higher. + +Support for `.level2::eviction_priority` qualifier and `.v8.b32`/`.v4.b64` require `sm_100` or higher. + +Examples + +ld.global.f32 d,[a]; + ld.shared.v4.b32 Q,[p]; + ld.const.s32 d,[p+4]; + ld.local.b32 x,[p+-8]; // negative offset + ld.local.b64 x,[240]; // immediate address + + ld.global.b16 %r,[fs]; // load .f16 data into 32-bit reg + cvt.f32.f16 %r,%r; // up-convert f16 data to f32 + + ld.global.b32 %r0, [fs]; // load .f16x2 data in 32-bit reg + ld.global.b32 %r1, [fs + 4]; // load .f16x2 data in 32-bit reg + add.rn.f16x2 %d0, %r0, %r1; // addition of f16x2 data + ld.global.relaxed.gpu.u32 %r0, [gbl]; + ld.shared.acquire.gpu.u32 %r1, [sh]; + ld.global.relaxed.cluster.u32 %r2, [gbl]; + ld.shared::cta.acquire.gpu.u32 %r2, [sh + 4]; + ld.shared::cluster.u32 %r3, [sh + 8]; + ld.global.mmio.relaxed.sys.u32 %r3, [gbl]; + ld.local.volatile.u32 %r4, [lcl]; + + ld.global.f32 d,[ugbl].unified; + ld.b32 %r0, [%r1].unified; + + ld.global.L1::evict_last.u32 d, [p]; + + ld.global.L2::64B.b32 %r0, [gbl]; // Prefetch 64B to L2 + ld.L2::128B.f64 %r1, [gbl]; // Prefetch 128B to L2 + ld.global.L2::256B.f64 %r2, [gbl]; // Prefetch 256B to L2 + + createpolicy.fractional.L2::evict_last.L2::evict_unchanged.b64 cache-policy, 1; + ld.global.L2::cache_hint.b64 x, [p], cache-policy; + ld.param::entry.b32 %rp1, [kparam1]; + + ld.global.b128 %r0, [gbl]; // 128-bit load + + // 256-bit load + ld.global.L2::evict_last.v8.f32 { %reg0, _, %reg2, %reg3, %reg4, %reg5, %reg6, %reg7}, [addr]; + ld.global.L2::evict_last.L1::evict_last.v4.u64 { %reg0, %reg1, %reg2, %reg3}, [addr]; \ No newline at end of file diff --git a/content/cuda/docs/ptx-ldglobalnc/DOC.md b/content/cuda/docs/ptx-ldglobalnc/DOC.md new file mode 100644 index 00000000..9ad68c12 --- /dev/null +++ b/content/cuda/docs/ptx-ldglobalnc/DOC.md @@ -0,0 +1,149 @@ +--- +name: ptx-ldglobalnc +description: Load a register variable from global state space via non-coherent cache. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.9. Data Movement and Conversion Instructions:ld.global.nc + +--- +title: "9.7.9.9. Data Movement and Conversion Instructions:ld.global.nc" +section: 9.7.9.9 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.9. Data Movement and Conversion Instructions:ld.global.nc + + +`ld.global.nc` + +Load a register variable from global state space via non-coherent cache. + +Syntax + +ld.global{.cop}.nc{.level::cache_hint}{.level::prefetch_size}.type d, [a]{, cache-policy}; + ld.global{.cop}.nc{.level::cache_hint}{.level::prefetch_size}.vec.type d, [a]{, cache-policy}; + + ld.global.nc{.level1::eviction_priority}{.level2::eviction_priority}{.level::cache_hint}{.level::prefetch_size}.type d, [a]{, cache-policy}; + ld.global.nc{.level1::eviction_priority}{.level2::eviction_priority}{.level::cache_hint}{.level::prefetch_size}.vec.type d, [a]{, cache-policy}; + + .cop = { .ca, .cg, .cs }; // cache operation + .level1::eviction_priority = { .L1::evict_normal, .L1::evict_unchanged, + .L1::evict_first, .L1::evict_last, .L1::no_allocate}; + .level2::eviction_priority = {.L2::evict_normal, .L2::evict_first, .L2::evict_last}; + .level::cache_hint = { .L2::cache_hint }; + .level::prefetch_size = { .L2::64B, .L2::128B, .L2::256B } + .vec = { .v2, .v4, .v8 }; + .type = { .b8, .b16, .b32, .b64, .b128, + .u8, .u16, .u32, .u64, + .s8, .s16, .s32, .s64, + .f32, .f64 }; + +Description + +Load register variable `d` from the location specified by the source address operand `a` in the global state space, and optionally cache in non-coherent read-only cache. + +Note + +On some architectures, the texture cache is larger, has higher bandwidth, and longer latency than the global memory cache. For applications with sufficient parallelism to cover the longer latency, `ld.global.nc` should offer better performance than `ld.global` on such architectures. + +The address operand `a` shall contain a global address. Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>). + +The `.v8` (`.vec`) qualifier is supported if: + +* `.type` is `.b32`, `.s32`, `.u32`, or `.f32` AND + + * State space is `.global` or with generic addressing where address points to `.global` state space + +The `.v4` (`.vec`) qualifier with type `.b64` or `.s64` or `.u64` or `.f64` is supported if: + +* State space is `.global` or with generic addressing where address points to `.global` state space + +Qualifiers `.level1::eviction_priority` and `.level2::eviction_priority` specify the eviction policy for L1 and L2 cache respectively which may be applied during memory access. + +Qualifier `.level2::eviction_priority` is supported if: + +* `.vec` is `.v8` and `.type` is `.b32` or `.s32` or `.u32` or `.f32` + + * AND Operand `d` is vector of 8 registers with type specified with `.type` + + * OR `.vec` is `.v4` and `.type` is `.b64` or `.s64` or `.u64` or `.f64` + + * AND Operand `d` is vector of 4 registers with type specified with `.type` + +Optionally, sink symbol ‘_’ can be used in vector expression `d` when: + +* `.vec` is `.v8` and `.type` is `.b32` or `.s32` or `.u32` or `.f32` OR + + * `.vec` is `.v4` and `.type` is `.b64` or `.s64` or `.u64` or `.f64` + +which indicates that data from corresponding memory location is not read. + +The `.level::prefetch_size` qualifier is a hint to fetch additional data of the specified size into the respective cache level.The sub-qualifier `prefetch_size` can be set to either of `64B`, `128B`, `256B` thereby allowing the prefetch size to be 64 Bytes, 128 Bytes or 256 Bytes respectively. + +The `.level::prefetch_size` qualifier is treated as a performance hint only. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +Semantics + +d = a; // named variable a + d = *(&a+immOff) // variable-plus-offset + d = *a; // register + d = *(a+immOff); // register-plus-offset + d = *(immAddr); // immediate address + +Notes + +Destination `d` must be in the `.reg` state space. + +A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types. + +`.f16` data may be loaded using `ld.b16`, and then converted to `.f32` or `.f64` using `cvt`. + +PTX ISA Notes + +Introduced in PTX ISA version 3.1. + +Support for `.level::eviction_priority`, `.level::prefetch_size` and `.level::cache_hint` qualifiers introduced in PTX ISA version 7.4. + +Support for `.b128` type introduced in PTX ISA version 8.3. + +Support for `.level2::eviction_priority` qualifier and `.v8.b32`/`.v4.b64` introduced in PTX ISA version 8.8. + +Target ISA Notes + +Requires `sm_32` or higher. + +Support for `.level1::eviction_priority` qualifier requires `sm_70` or higher. + +Support for `.level::prefetch_size` qualifier requires `sm_75` or higher. + +Support for `.level::cache_hint` qualifier requires `sm_80` or higher. + +Support for `.b128` type requires `sm_70` or higher. + +Support for `.level2::eviction_priority` qualifier and `.v8.b32`/`.v4.b64` require `sm_100` or higher. + +Examples + +ld.global.nc.f32 d, [a]; + ld.gloal.nc.L1::evict_last.u32 d, [a]; + + createpolicy.fractional.L2::evict_last.b64 cache-policy, 0.5; + ld.global.nc.L2::cache_hint.f32 d, [a], cache-policy; + + ld.global.nc.L2::64B.b32 d, [a]; // Prefetch 64B to L2 + ld.global.nc.L2::256B.f64 d, [a]; // Prefetch 256B to L2 + + ld.global.nc.b128 d, [a]; + + ld.global.nc.L2::evict_first.v4.f64 {%reg0, %reg1. %reg2, %reg3}. [a]; // 256-bit load \ No newline at end of file diff --git a/content/cuda/docs/ptx-ldu/DOC.md b/content/cuda/docs/ptx-ldu/DOC.md new file mode 100644 index 00000000..80a18632 --- /dev/null +++ b/content/cuda/docs/ptx-ldu/DOC.md @@ -0,0 +1,82 @@ +--- +name: ptx-ldu +description: Load read-only data from an address that is common across threads in + the warp. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.10. Data Movement and Conversion Instructions:ldu + +--- +title: "9.7.9.10. Data Movement and Conversion Instructions:ldu" +section: 9.7.9.10 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.10. Data Movement and Conversion Instructions:ldu + + +`ldu` + +Load read-only data from an address that is common across threads in the warp. + +Syntax + +ldu{.ss}.type d, [a]; // load from address + ldu{.ss}.vec.type d, [a]; // vec load from address + + .ss = { .global }; // state space + .vec = { .v2, .v4 }; + .type = { .b8, .b16, .b32, .b64, .b128, + .u8, .u16, .u32, .u64, + .s8, .s16, .s32, .s64, + .f32, .f64 }; + +Description + +Load _read-only_ data into register variable `d` from the location specified by the source address operand `a` in the global state space, where the address is guaranteed to be the same across all threads in the warp. If no state space is given, perform the load using [Generic Addressing](<#generic-addressing>). + +Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>). + +Semantics + +d = a; // named variable a + d = *(&a+immOff) // variable-plus-offset + d = *a; // register + d = *(a+immOff); // register-plus-offset + d = *(immAddr); // immediate address + +Notes + +Destination `d` must be in the `.reg` state space. + +A destination register wider than the specified type may be used. The value loaded is sign-extended to the destination register width for signed integers, and is zero-extended to the destination register width for unsigned and bit-size types. See [Table 28](<#operand-size-exceeding-instruction-type-size-relaxed-type-checking-rules-destination-operands>) for a description of these relaxed type-checking rules. + +`.f16` data may be loaded using `ldu.b16`, and then converted to `.f32` or `.f64` using `cvt` or can be used in half precision floating point instructions. + +`.f16x2` data may be loaded using `ldu.b32` and then used in half precision floating point instructions. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Support for `.b128` type introduced in PTX ISA version 8.3. + +Target ISA Notes + +`ldu.f64` requires `sm_13` or higher. + +Support for `.b128` type requires `sm_70` or higher. + +Examples + +ldu.global.f32 d,[a]; + ldu.global.b32 d,[p+4]; + ldu.global.v4.f32 Q,[p]; + ldu.global.b128 d,[a]; \ No newline at end of file diff --git a/content/cuda/docs/ptx-lg2/DOC.md b/content/cuda/docs/ptx-lg2/DOC.md new file mode 100644 index 00000000..98b9fa2a --- /dev/null +++ b/content/cuda/docs/ptx-lg2/DOC.md @@ -0,0 +1,83 @@ +--- +name: ptx-lg2 +description: Find the base-2 logarithm of a value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.20. Floating Point Instructions:lg2 + +--- +title: "9.7.3.20. Floating Point Instructions:lg2" +section: 9.7.3.20 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.20. Floating Point Instructions:lg2 + + +`lg2` + +Find the base-2 logarithm of a value. + +Syntax + +lg2.approx{.ftz}.f32 d, a; + +Description + +Determine the log2 of `a`. + +Semantics + +d = log(a) / log(2); + +Notes + +`lg2.approx.f32` implements a fast approximation to log2(a). + +Input | Result +---|--- +-Inf | NaN +-normal | NaN +-0.0 | -Inf ++0.0 | -Inf ++Inf | +Inf +NaN | NaN + +The maximum absolute error is 2-22 when the input operand is in the range (0.5, 2). For positive finite inputs outside of this interval, maximum relative error is 2-22. + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`lg2.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +Subnormal inputs and results to sign-preserving zero. + +PTX ISA Notes + +`lg2.f32` introduced in PTX ISA version 1.0. Explicit modifiers `.approx` and `.ftz` introduced in PTX ISA version 1.4. + +For PTX ISA version 1.4 and later, the `.approx` modifier is required. + +For PTX ISA versions 1.0 through 1.3, `lg2.f32` defaults to `lg2.approx.ftz.f32`. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +lg2.approx.ftz.f32 la, a; \ No newline at end of file diff --git a/content/cuda/docs/ptx-limitations-on-atomicity-at-system-scope/DOC.md b/content/cuda/docs/ptx-limitations-on-atomicity-at-system-scope/DOC.md new file mode 100644 index 00000000..e8e191e6 --- /dev/null +++ b/content/cuda/docs/ptx-limitations-on-atomicity-at-system-scope/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-limitations-on-atomicity-at-system-scope +description: When communicating with the host CPU, certain strong operations with + system scope may not be performed atomically on some systems. For more details on + atomicity guarantees to host memory, see the _CUD... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.1.1. Limitations on atomicity at system scope + +--- +title: "8.1.1. Limitations on atomicity at system scope" +section: 8.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.1.1. Limitations on atomicity at system scope + + +When communicating with the host CPU, certain strong operations with system scope may not be performed atomically on some systems. For more details on atomicity guarantees to host memory, see the _CUDA Atomicity Requirements_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-limitations-on-mixed-size-data-races/DOC.md b/content/cuda/docs/ptx-limitations-on-mixed-size-data-races/DOC.md new file mode 100644 index 00000000..c3c772dd --- /dev/null +++ b/content/cuda/docs/ptx-limitations-on-mixed-size-data-races/DOC.md @@ -0,0 +1,32 @@ +--- +name: ptx-limitations-on-mixed-size-data-races +description: A _data-race_ between operations that _overlap_ completely is called + a _uniform-size data-race_ , while a _data-race_ between operations that _overlap_ + partially is called a _mixed-size data-race_. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.7.2. Limitations on Mixed-size Data-races + +--- +title: "8.7.2. Limitations on Mixed-size Data-races" +section: 8.7.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.7.2. Limitations on Mixed-size Data-races + + +A _data-race_ between operations that _overlap_ completely is called a _uniform-size data-race_ , while a _data-race_ between operations that _overlap_ partially is called a _mixed-size data-race_. + +The axioms in the memory consistency model do not apply if a PTX program contains one or more _mixed-size data-races_. But these axioms are sufficient to describe the behavior of a PTX program with only _uniform-size data-races_. + +Atomicity of mixed-size RMW operations + +In any program with or without _mixed-size data-races_ , the following property holds for every pair of _overlapping atomic_ operations A1 and A2 such that each specifies a _scope_ that includes the other: Either the _read-modify-write_ operation specified by A1 is performed completely before A2 is initiated, or vice versa. This property holds irrespective of whether the two operations A1 and A2 overlap partially or completely. \ No newline at end of file diff --git a/content/cuda/docs/ptx-linking-directivescommon/DOC.md b/content/cuda/docs/ptx-linking-directivescommon/DOC.md new file mode 100644 index 00000000..cebf8501 --- /dev/null +++ b/content/cuda/docs/ptx-linking-directivescommon/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-linking-directivescommon +description: Visible (externally) symbol declaration. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.6.4. Linking Directives:.common + +--- +title: "11.6.4. Linking Directives:.common" +section: 11.6.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.6.4. Linking Directives:.common + + +`.common` + +Visible (externally) symbol declaration. + +Syntax + +.common identifier + +Description + +Declares identifier to be globally visible but “common”. + +Common symbols are similar to globally visible symbols. However multiple object files may declare the same common symbol and they may have different types and sizes and references to a symbol get resolved against a common symbol with the largest size. + +Only one object file can initialize a common symbol and that must have the largest size among all other definitions of that common symbol from different object files. + +`.common` linking directive can be used only on variables with `.global` storage. It cannot be used on function symbols or on symbols with opaque type. + +PTX ISA Notes + +Introduced in PTX ISA version 5.0. + +Target ISA Notes + +`.common` directive requires `sm_20` or higher. + +Examples + +.common .global .u32 gbl; \ No newline at end of file diff --git a/content/cuda/docs/ptx-linking-directivesextern/DOC.md b/content/cuda/docs/ptx-linking-directivesextern/DOC.md new file mode 100644 index 00000000..6d49bc7e --- /dev/null +++ b/content/cuda/docs/ptx-linking-directivesextern/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-linking-directivesextern +description: External symbol declaration. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.6.1. Linking Directives:.extern + +--- +title: "11.6.1. Linking Directives:.extern" +section: 11.6.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.6.1. Linking Directives:.extern + + +`.extern` + +External symbol declaration. + +Syntax + +.extern identifier + +Description + +Declares identifier to be defined external to the current module. The module defining such identifier must define it as `.weak` or `.visible` only once in a single object file. Extern declaration of symbol may appear multiple times and references to that get resolved against the single definition of that symbol. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.extern .global .b32 foo; // foo is defined in another module \ No newline at end of file diff --git a/content/cuda/docs/ptx-linking-directivesvisible/DOC.md b/content/cuda/docs/ptx-linking-directivesvisible/DOC.md new file mode 100644 index 00000000..bbe98a4c --- /dev/null +++ b/content/cuda/docs/ptx-linking-directivesvisible/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-linking-directivesvisible +description: Visible (externally) symbol declaration. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.6.2. Linking Directives:.visible + +--- +title: "11.6.2. Linking Directives:.visible" +section: 11.6.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.6.2. Linking Directives:.visible + + +`.visible` + +Visible (externally) symbol declaration. + +Syntax + +.visible identifier + +Description + +Declares identifier to be globally visible. Unlike C, where identifiers are globally visible unless declared static, PTX identifiers are visible only within the current module unless declared `.visible` outside the current. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.visible .global .b32 foo; // foo will be externally visible \ No newline at end of file diff --git a/content/cuda/docs/ptx-linking-directivesweak/DOC.md b/content/cuda/docs/ptx-linking-directivesweak/DOC.md new file mode 100644 index 00000000..9633a04c --- /dev/null +++ b/content/cuda/docs/ptx-linking-directivesweak/DOC.md @@ -0,0 +1,46 @@ +--- +name: ptx-linking-directivesweak +description: Visible (externally) symbol declaration. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.6.3. Linking Directives:.weak + +--- +title: "11.6.3. Linking Directives:.weak" +section: 11.6.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.6.3. Linking Directives:.weak + + +`.weak` + +Visible (externally) symbol declaration. + +Syntax + +.weak identifier + +Description + +Declares identifier to be globally visible but _weak_. Weak symbols are similar to globally visible symbols, except during linking, weak symbols are only chosen after globally visible symbols during symbol resolution. Unlike globally visible symbols, multiple object files may declare the same weak symbol, and references to a symbol get resolved against a weak symbol only if no global symbols have the same name. + +PTX ISA Notes + +Introduced in PTX ISA version 3.1. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.weak .func (.reg .b32 val) foo; // foo will be externally visible \ No newline at end of file diff --git a/content/cuda/docs/ptx-local-state-space/DOC.md b/content/cuda/docs/ptx-local-state-space/DOC.md new file mode 100644 index 00000000..b1ce64a0 --- /dev/null +++ b/content/cuda/docs/ptx-local-state-space/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-local-state-space +description: The local state space (`.local`) is private memory for each thread to + keep its own data. It is typically standard memory with cache. The size is limited, + as it must be allocated on a per-thread basis.... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.5. Local State Space + +--- +title: "5.1.5. Local State Space" +section: 5.1.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.1.5. Local State Space + + +The local state space (`.local`) is private memory for each thread to keep its own data. It is typically standard memory with cache. The size is limited, as it must be allocated on a per-thread basis. Use `ld.local` and `st.local` to access local variables. + +When compiling to use the _Application Binary Interface (ABI)_ , `.local` state-space variables must be declared within function scope and are allocated on the stack. In implementations that do not support a stack, all local memory variables are stored at fixed addresses, recursive function calls are not supported, and `.local` variables may be declared at module scope. When compiling legacy PTX code (ISA versions prior to 3.0) containing module-scoped `.local` variables, the compiler silently disables use of the ABI. \ No newline at end of file diff --git a/content/cuda/docs/ptx-lop3/DOC.md b/content/cuda/docs/ptx-lop3/DOC.md new file mode 100644 index 00000000..3867f56e --- /dev/null +++ b/content/cuda/docs/ptx-lop3/DOC.md @@ -0,0 +1,107 @@ +--- +name: ptx-lop3 +description: Arbitrary logical operation on 3 inputs. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.8.6. Logic and Shift Instructions:lop3 + +--- +title: "9.7.8.6. Logic and Shift Instructions:lop3" +section: 9.7.8.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.8.6. Logic and Shift Instructions:lop3 + + +`lop3` + +Arbitrary logical operation on 3 inputs. + +Syntax + +lop3.b32 d, a, b, c, immLut; + lop3.BoolOp.b32 d|p, a, b, c, immLut, q; + + .BoolOp = { .or , .and }; + +Description + +Compute bitwise logical operation on inputs `a`, `b`, `c` and store the result in destination `d`. + +Optionally, `.BoolOp` can be specified to compute the predicate result `p` by performing a Boolean operation on the destination operand `d` with the predicate `q` in the following manner: + +p = (d != 0) BoolOp q; + +The sink symbol ‘_’ may be used in place of the destination operand `d` when `.BoolOp` qualifier is specified. + +The logical operation is defined by a look-up table which, for 3 inputs, can be represented as an 8-bit value specified by operand `immLut` as described below. `immLut` is an integer constant that can take values from 0 to 255, thereby allowing up to 256 distinct logical operations on inputs `a`, `b`, `c`. + +For a logical operation `F(a, b, c)` the value of `immLut` can be computed by applying the same operation to three predefined constant values as follows: + +ta = 0xF0; + tb = 0xCC; + tc = 0xAA; + + immLut = F(ta, tb, tc); + +Examples: + +If F = (a & b & c); + immLut = 0xF0 & 0xCC & 0xAA = 0x80 + + If F = (a | b | c); + immLut = 0xF0 | 0xCC | 0xAA = 0xFE + + If F = (a & b & ~c); + immLut = 0xF0 & 0xCC & (~0xAA) = 0x40 + + If F = ((a & b | c) ^ a); + immLut = (0xF0 & 0xCC | 0xAA) ^ 0xF0 = 0x1A + +The following table illustrates computation of `immLut` for various logical operations: + +ta | tb | tc | Oper 0 (False) | Oper 1 (ta & tb & tc) | Oper 2 (ta & tb & ~tc) | … | Oper 254 (ta | tb | tc) | Oper 255 (True) +---|---|---|---|---|---|---|---|--- +0 | 0 | 0 | 0 | 0 | 0 | … | 0 | 1 +0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 +0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 +0 | 1 | 1 | 0 | 0 | 0 | 1 | 1 +1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 +1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 +1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 +1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 +**immLut** | **0x0** | **0x80** | **0x40** | **…** | **0xFE** | **0xFF** + +Semantics + +F = GetFunctionFromTable(immLut); // returns the function corresponding to immLut value + d = F(a, b, c); + if (BoolOp specified) { + p = (d != 0) BoolOp q; + } + +PTX ISA Notes + +Introduced in PTX ISA version 4.3. + +Support for `.BoolOp` qualifier introduced in PTX ISA version 8.2. + +Target ISA Notes + +Requires `sm_50` or higher. + +Qualifier `.BoolOp` requires `sm_70` or higher. + +Examples + +lop3.b32 d, a, b, c, 0x40; + lop3.or.b32 d|p, a, b, c, 0x3f, q; + lop3.and.b32 _|p, a, b, c, 0x3f, q; \ No newline at end of file diff --git a/content/cuda/docs/ptx-machine-specific-semantics-of-16-bit-code/DOC.md b/content/cuda/docs/ptx-machine-specific-semantics-of-16-bit-code/DOC.md new file mode 100644 index 00000000..1fcbdc47 --- /dev/null +++ b/content/cuda/docs/ptx-machine-specific-semantics-of-16-bit-code/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-machine-specific-semantics-of-16-bit-code +description: A PTX program may execute on a GPU with either a 16-bit or a 32-bit data + path. When executing on a 32-bit data path, 16-bit registers in PTX are mapped to + 32-bit physical registers, and 16-bit computa... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.6.1. Machine-Specific Semantics of 16-bit Code + +--- +title: "9.6.1. Machine-Specific Semantics of 16-bit Code" +section: 9.6.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 9.6.1. Machine-Specific Semantics of 16-bit Code + + +A PTX program may execute on a GPU with either a 16-bit or a 32-bit data path. When executing on a 32-bit data path, 16-bit registers in PTX are mapped to 32-bit physical registers, and 16-bit computations are _promoted_ to 32-bit computations. This can lead to computational differences between code run on a 16-bit machine versus the same code run on a 32-bit machine, since the promoted computation may have bits in the high-order half-word of registers that are not present in 16-bit physical registers. These extra precision bits can become visible at the application level, for example, by a right-shift instruction. + +At the PTX language level, one solution would be to define semantics for 16-bit code that is consistent with execution on a 16-bit data path. This approach introduces a performance penalty for 16-bit code executing on a 32-bit data path, since the translated code would require many additional masking instructions to suppress extra precision bits in the high-order half-word of 32-bit registers. + +Rather than introduce a performance penalty for 16-bit code running on 32-bit GPUs, the semantics of 16-bit instructions in PTX is machine-specific. A compiler or programmer may chose to enforce portable, machine-independent 16-bit semantics by adding explicit conversions to 16-bit values at appropriate points in the program to guarantee portability of the code. However, for many performance-critical applications, this is not desirable, and for many applications the difference in execution is preferable to limiting performance. \ No newline at end of file diff --git a/content/cuda/docs/ptx-mad/DOC.md b/content/cuda/docs/ptx-mad/DOC.md new file mode 100644 index 00000000..e5a0aaea --- /dev/null +++ b/content/cuda/docs/ptx-mad/DOC.md @@ -0,0 +1,76 @@ +--- +name: ptx-mad +description: Multiply two values, optionally extract the high or low half of the intermediate + result, and add a third value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.4. Integer Arithmetic Instructions:mad + +--- +title: "9.7.1.4. Integer Arithmetic Instructions:mad" +section: 9.7.1.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.4. Integer Arithmetic Instructions:mad + + +`mad` + +Multiply two values, optionally extract the high or low half of the intermediate result, and add a third value. + +Syntax + +mad.mode.type d, a, b, c; + mad.hi.sat.s32 d, a, b, c; + + .mode = { .hi, .lo, .wide }; + .type = { .u16, .u32, .u64, + .s16, .s32, .s64 }; + +Description + +Multiplies two values, optionally extracts the high or low half of the intermediate result, and adds a third value. Writes the result into a destination register. + +Semantics + +t = a * b; + n = bitwidth of type; + d = t + c; // for .wide + d = t<2n-1..n> + c; // for .hi variant + d = t + c; // for .lo variant + +Notes + +The type of the operation represents the types of the `a` and `b` operands. If .hi or .lo is specified, then `d` and `c` are the same size as `a` and `b`, and either the upper or lower half of the result is written to the destination register. If `.wide` is specified, then `d` and `c` are twice as wide as `a` and `b` to receive the result of the multiplication. + +The `.wide` suffix is supported only for 16-bit and 32-bit integer types. + +Saturation modifier: + +`.sat` + + +limits result to `MININT..MAXINT` (no overflow) for the size of the operation. + +Applies only to `.s32` type in `.hi` mode. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +@p mad.lo.s32 d,a,b,c; + mad.lo.s32 r,p,q,r; \ No newline at end of file diff --git a/content/cuda/docs/ptx-mad24/DOC.md b/content/cuda/docs/ptx-mad24/DOC.md new file mode 100644 index 00000000..2e38b169 --- /dev/null +++ b/content/cuda/docs/ptx-mad24/DOC.md @@ -0,0 +1,75 @@ +--- +name: ptx-mad24 +description: Multiply two 24-bit integer values and add a third value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.6. Integer Arithmetic Instructions:mad24 + +--- +title: "9.7.1.6. Integer Arithmetic Instructions:mad24" +section: 9.7.1.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.6. Integer Arithmetic Instructions:mad24 + + +`mad24` + +Multiply two 24-bit integer values and add a third value. + +Syntax + +mad24.mode.type d, a, b, c; + mad24.hi.sat.s32 d, a, b, c; + + .mode = { .hi, .lo }; + .type = { .u32, .s32 }; + +Description + +Compute the product of two 24-bit integer values held in 32-bit source registers, and add a third, 32-bit value to either the high or low 32-bits of the 48-bit result. Return either the high or low 32-bits of the 48-bit result. + +Semantics + +t = a * b; + d = t<47..16> + c; // for .hi variant + d = t<31..0> + c; // for .lo variant + +Notes + +Integer multiplication yields a result that is twice the size of the input operands, i.e., 48-bits. + +`mad24.hi` performs a 24x24-bit multiply and adds the high 32 bits of the 48-bit result to a third value. + +`mad24.lo` performs a 24x24-bit multiply and adds the low 32 bits of the 48-bit result to a third value. + +All operands are of the same type and size. + +Saturation modifier: + +`.sat` + + +limits result of 32-bit signed addition to `MININT..MAXINT` (no overflow). Applies only to `.s32` type in .hi mode. + +`mad24.hi` may be less efficient on machines without hardware support for 24-bit multiply. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +mad24.lo.s32 d,a,b,c; // low 32-bits of 24x24-bit signed multiply. \ No newline at end of file diff --git a/content/cuda/docs/ptx-madc/DOC.md b/content/cuda/docs/ptx-madc/DOC.md new file mode 100644 index 00000000..f4e5a2b7 --- /dev/null +++ b/content/cuda/docs/ptx-madc/DOC.md @@ -0,0 +1,74 @@ +--- +name: ptx-madc +description: Multiply two values, extract high or low half of result, and add a third + value with carry-in and optional carry-out. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.2.6. Extended-Precision Arithmetic Instructions:madc + +--- +title: "9.7.2.6. Extended-Precision Arithmetic Instructions:madc" +section: 9.7.2.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.2.6. Extended-Precision Arithmetic Instructions:madc + + +`madc` + +Multiply two values, extract high or low half of result, and add a third value with carry-in and optional carry-out. + +Syntax + +madc{.hi,.lo}{.cc}.type d, a, b, c; + + .type = { .u32, .s32, .u64, .s64 }; + +Description + +Multiplies two values, extracts either the high or low part of the result, and adds a third value along with carry-in. Writes the result to the destination register and optionally writes the carry-out from the addition into the condition code register. + +Semantics + +t = a * b; + d = t<63..32> + c + CC.CF; // for .hi variant + d = t<31..0> + c + CC.CF; // for .lo variant + +if `.cc` specified, carry-out from addition is written to `CC.CF` + +Notes + +Generally used in combination with `mad.cc` and `addc` to implement extended-precision multi-word multiplication. See example below. + +PTX ISA Notes + +32-bit `madc` introduced in PTX ISA version 3.0. + +64-bit `madc` introduced in PTX ISA version 4.3. + +Target ISA Notes + +Requires target `sm_20` or higher. + +Examples + +// extended-precision multiply: [r3,r2,r1,r0] = [r5,r4] * [r7,r6] + mul.lo.u32 r0,r4,r6; // r0=(r4*r6).[31:0], no carry-out + mul.hi.u32 r1,r4,r6; // r1=(r4*r6).[63:32], no carry-out + mad.lo.cc.u32 r1,r5,r6,r1; // r1+=(r5*r6).[31:0], may carry-out + madc.hi.u32 r2,r5,r6,0; // r2 =(r5*r6).[63:32]+carry-in, + // no carry-out + mad.lo.cc.u32 r1,r4,r7,r1; // r1+=(r4*r7).[31:0], may carry-out + madc.hi.cc.u32 r2,r4,r7,r2; // r2+=(r4*r7).[63:32]+carry-in, + // may carry-out + addc.u32 r3,0,0; // r3 = carry-in, no carry-out + mad.lo.cc.u32 r2,r5,r7,r2; // r2+=(r5*r7).[31:0], may carry-out + madc.hi.u32 r3,r5,r7,r3; // r3+=(r5*r7).[63:32]+carry-in \ No newline at end of file diff --git a/content/cuda/docs/ptx-madcc/DOC.md b/content/cuda/docs/ptx-madcc/DOC.md new file mode 100644 index 00000000..6bec667c --- /dev/null +++ b/content/cuda/docs/ptx-madcc/DOC.md @@ -0,0 +1,64 @@ +--- +name: ptx-madcc +description: Multiply two values, extract high or low half of result, and add a third + value with carry-out. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.2.5. Extended-Precision Arithmetic Instructions:mad.cc + +--- +title: "9.7.2.5. Extended-Precision Arithmetic Instructions:mad.cc" +section: 9.7.2.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.2.5. Extended-Precision Arithmetic Instructions:mad.cc + + +`mad.cc` + +Multiply two values, extract high or low half of result, and add a third value with carry-out. + +Syntax + +mad{.hi,.lo}.cc.type d, a, b, c; + + .type = { .u32, .s32, .u64, .s64 }; + +Description + +Multiplies two values, extracts either the high or low part of the result, and adds a third value. Writes the result to the destination register and the carry-out from the addition into the condition code register. + +Semantics + +t = a * b; + d = t<63..32> + c; // for .hi variant + d = t<31..0> + c; // for .lo variant + +carry-out from addition is written to `CC.CF` + +Notes + +Generally used in combination with `madc` and `addc` to implement extended-precision multi-word multiplication. See `madc` for an example. + +PTX ISA Notes + +32-bit `mad.cc` introduced in PTX ISA version 3.0. + +64-bit `mad.cc` introduced in PTX ISA version 4.3. + +Target ISA Notes + +Requires target `sm_20` or higher. + +Examples + +@p mad.lo.cc.u32 d,a,b,c; + mad.lo.cc.u32 r,p,q,r; \ No newline at end of file diff --git a/content/cuda/docs/ptx-major-ness-supported-by-strides/DOC.md b/content/cuda/docs/ptx-major-ness-supported-by-strides/DOC.md new file mode 100644 index 00000000..6b3195b9 --- /dev/null +++ b/content/cuda/docs/ptx-major-ness-supported-by-strides/DOC.md @@ -0,0 +1,212 @@ +--- +name: ptx-major-ness-supported-by-strides +description: 'There are two strides involved while accessing a matrix from shared + memory:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.3. Major-ness supported by Strides + +--- +title: "9.7.16.3. Major-ness supported by Strides" +section: 9.7.16.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.3. Major-ness supported by Strides + + +There are two strides involved while accessing a matrix from shared memory: + +1. Leading dimension stride (byte offset or absolute address) + + 2. Stride dimension byte offset + +##### 9.7.16.3.1. [Leading Dimension Stride: relative offset or absolute address](<#tcgen05-leading-dimension-byte-offset>) + +There are two modes of Leading Dimension Strides as described below. Bit #52 in the [Shared memory descriptor](<#tcgen05-shared-memory-descriptor>) is used to distinguish between two modes. + +###### 9.7.16.3.1.1. [Relative offset mode](<#tcgen05-leading-dimension-byte-offset-relative-offset>) + +In this mode, the leading dimension stride is specified as a relative byte offset between the columns as explained in the below table. The leading dimension stride can either be specified as a relative offset between the columns or as an absolute byte address of next buffer. The leading dimension stride is defined differently for transposed and non-transposed matrices. The leading dimension stride is defined as follows for matrices whose element types are normalized to 128-bits: + +Major-ness | Definition +---|--- +K-Major | + + * No-Swizzling: the stride from the first column to the second column of the 8x2 tile in the 128-bit element type normalized matrix. + * Swizzled layouts: not used, assumed to be 1. + + +MN-Major | + + * Interleave: stride from the first 8 columns to the next 8 columns. + * Swizzled layouts: stride from the first (swizzle-byte-size/16) rows to the next (swizzle-byte-size/16) rows. + + + +###### 9.7.16.3.1.2. [Absolute address mode for K dimension being 48B](<#tcgen05-leading-dimension-byte-offset-absolute-address>) + +The `tcgen05.mma` instruction with _K-dimension_ of 48B would overflow the 128B shared memory boundary if the data is packed contiguously. + +In this case, the absolute address mode can be used to break up the data in the shared memory into two chunks such that both these chunks are laid out within the aligned 128-byte address boundary. The leading dimension absolute address can point to the second data chunk in the shared memory. + +####### 9.7.16.3.1.2.1. [Restrictions on the Leading Dimension Absolute Address Stride](<#tcgen05-leading-dimension-byte-offset-absolute-address-restriction>) + +Following are the restrictions on the absolute address stride mode: + + 1. Only 128B swizzle (with 16B atomicity) is supported. + + 2. Only K-Major mode is supported. That is, the transpose bits(bits #15 and #16) in [Instruction descriptor](<#tcgen05-instruction-descriptor>) must be 0. + + 3. The matrix base offset must be 0. + +##### 9.7.16.3.2. [Stride Dimension Byte Offset](<#tcgen05-stride-dimension-byte-offset>) + +The stride dimension byte offset is defined differently for transposed and non-transposed matrices. The stride dimension byte offset is defined as follows for matrices whose element types are normalized to 128-bits: + +Major-ness | Definition +---|--- +K-Major | The offset from the first 8 rows to the next 8 rows. +MN-Major | + + * Interleave: offset from the first row to the next row. + * Swizzled layout: offset from the first 8 columns to the next 8 columns + +##### 9.7.16.3.3. [Canonical Layouts](<#tcgen05-canonical-layouts>) + +In terms of [CuTe layouts]() the canonical layout can be expressed as follows: + +Major- ness | Swizzling mode | Canonical Layout without swizzling | [Swizzling]() on the previous column +---|---|---|--- +MN- major | No-swizzling or Interleaved | ((T,1,m),(8,k)):((1,T,SBO),(1T,LBO)) | Swizzle<0, 4, 3> +32B Swizzling | ((T,2,m),(8,k)):((1,T,LBO),(2T,SBO)) | Swizzle<1, 4, 3> +64B Swizzling | ((T,4,m),(8,k)):((1,T,LBO),(4T,SBO)) | Swizzle<2, 4, 3> +128B Swizzling | ((T,8,m),(8,k)):((1,T,LBO),(8T,SBO)) | Swizzle<3, 4, 3> +K- major | No-swizzling or Interleaved | ((8,m),(T,2k)):((1T,SBO),(1,LBO)) | Swizzle<0, 4, 3> +32B Swizzling | ((8,m),(T,2k)):((2T,SBO),(1,T)) | Swizzle<1, 4, 3> +64B Swizzling | ((8,m),(T,2k)):((4T,SBO),(1,T)) | Swizzle<2, 4, 3> +128B Swizzling | ((8,m),(T,2k)):((8T,SBO),(1,T)) | Swizzle<3, 4, 3> + +where + + * T = 128 / sizeof-elements-in-bits T represents scale factor which normalizes matrix element types to 128-bits. + + * m represents the number of repeating patterns across rows. + + * k represents the number of repeating patterns across columns. + + +Examples + + * K-Major, no-swizzling and tf32 type: [Figure 188](<#tcgen05-k-no-swizzle-tf32>) + +![_images/async-warpgroup-k-no-swizzle-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-k-no-swizzle-tf32.png) + +Figure 188 K major, no-swizzling and tf32 type + +the strides and related details are as follows: + +Exact layout : Swizzle<0,4,3> o ((8,2),(4,4)):((4,32),(1,64)) + +Canonical Layout :Swizzle<0,4,3> o ((8,m),(T,2k)):((1T,SBO),(1,LBO)) + +Parameters | Value +---|--- +T | 4 +m | 2 +k | 2 +LBO (relative offset) | 64*sizeof(tf32) +SBO | 32*sizeof(tf32) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 8 + * K-Major, 32B swizzling and tf32 type: [Figure 189](<#tcgen05-k-32b-swizzle-tf32>) + +![_images/async-warpgroup-k-32B-swizzle-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-k-32B-swizzle-tf32.png) + +Figure 189 K major, 32B swizzling and tf32 type + +the strides and related details are as follows: + +Exact layout : Swizzle<1,4,3> o ((8,2),(4,4)):((8,64),(1,4)) + +Canonical Layout :Swizzle<1,4,3> o ((8,m),(T,2k)):((2T,SBO),(1,T)) + +Parameters | Value +---|--- +T | 4 +m | 2 +k | 2 +LBO (relative offset) | NA +SBO | 64*sizeof(tf32) +Encoding of LBO in descriptor | 1 (assumed) +Encoding of SBO in descriptor | (SBO) >> 4 = 16 + * MN-Major, no-swizzling and bf16 type: [Figure 190](<#tcgen05-mn-no-swizzle-bf16>) + +![_images/async-warpgroup-mn-no-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-no-swizzle-bf16.png) + +Figure 190 MN major, no-swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<0,4,3> o ((8,1,2),(8,2)):((1,8,64),(8,128)) + +Canonical Layout :Swizzle<0,4,3> o ((T,1,m),(8,k)):((1,T,SBO),(1T,LBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO (relative offset) | 128*sizeof(bf16) +SBO | 64*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 8 + * MN-Major, 32B swizzling and bf16 type: [Figure 191](<#tcgen05-mn-32b-swizzle-bf16>) + +![_images/async-warpgroup-mn-32B-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-32B-swizzle-bf16.png) + +Figure 191 MN major, 32B swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<1,4,3> o ((8,2,2),(8,2)):((1,8,128),(16,256)) + +Canonical Layout :Swizzle<1,4,3> o ((T,2,m),(8,k)):((1,T,LBO),(2T,SBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO (relative offset) | 128*sizeof(bf16) +SBO | 256*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 16 +Encoding of SBO in descriptor | (SBO) >> 4 = 32 + * MN-Major, 64B swizzling and bf16 type: [Figure 192](<#tcgen05-mn-64b-swizzle-bf16>) + +![_images/async-warpgroup-mn-64B-swizzle-bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/async-warpgroup-mn-64B-swizzle-bf16.png) + +Figure 192 MN major, 64B swizzling and bf16 type + +the strides and related details are as follows: + +Exact layout : Swizzle<2,4,3> o ((8,4,2),(8,2)):((1,8,256),(32,512)) + +Canonical Layout :Swizzle<2,4,3> o ((T,4,m),(8,k)):((1,T,LBO),(4T,SBO)) + +Parameters | Value +---|--- +T | 8 +m | 2 +k | 2 +LBO (relative offset) | 256*sizeof(bf16) +SBO | 512*sizeof(bf16) +Encoding of LBO in descriptor | (LBO) >> 4 = 32 +Encoding of SBO in descriptor | (SBO) >> 4 = 64 \ No newline at end of file diff --git a/content/cuda/docs/ptx-manipulating-predicates/DOC.md b/content/cuda/docs/ptx-manipulating-predicates/DOC.md new file mode 100644 index 00000000..81544905 --- /dev/null +++ b/content/cuda/docs/ptx-manipulating-predicates/DOC.md @@ -0,0 +1,29 @@ +--- +name: ptx-manipulating-predicates +description: 'Predicate values may be computed and manipulated using the following + instructions: `and`, `or`, `xor`, `not`, and `mov`.' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.3.2. Manipulating Predicates + +--- +title: "9.3.2. Manipulating Predicates" +section: 9.3.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 9.3.2. Manipulating Predicates + + +Predicate values may be computed and manipulated using the following instructions: `and`, `or`, `xor`, `not`, and `mov`. + +There is no direct conversion between predicates and integer values, and no direct way to load or store predicate register values. However, `setp` can be used to generate a predicate from an integer, and the predicate-based select (`selp`) instruction can be used to generate an integer value based on the value of a predicate; for example: + +selp.u32 %r1,1,0,%p; // convert predicate to 32-bit value \ No newline at end of file diff --git a/content/cuda/docs/ptx-mapa/DOC.md b/content/cuda/docs/ptx-mapa/DOC.md new file mode 100644 index 00000000..74414a72 --- /dev/null +++ b/content/cuda/docs/ptx-mapa/DOC.md @@ -0,0 +1,71 @@ +--- +name: ptx-mapa +description: Map the address of the shared variable in the target CTA. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.23. Data Movement and Conversion Instructions:mapa + +--- +title: "9.7.9.23. Data Movement and Conversion Instructions:mapa" +section: 9.7.9.23 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.23. Data Movement and Conversion Instructions:mapa + + +`mapa` + +Map the address of the shared variable in the target CTA. + +Syntax + +mapa{.space}.type d, a, b; + + // Maps shared memory address in register a into CTA b. + mapa.shared::cluster.type d, a, b; + + // Maps shared memory variable into CTA b. + mapa.shared::cluster.type d, sh, b; + + // Maps shared memory variable into CTA b. + mapa.shared::cluster.type d, sh + imm, b; + + // Maps generic address in register a into CTA b. + mapa.type d, a, b; + + .space = { .shared::cluster } + .type = { .u32, .u64 } + +Description + +Get address in the CTA specified by operand `b` which corresponds to the address specified by operand `a`. + +Instruction type `.type` indicates the type of the destination operand `d` and the source operand `a`. + +When space is `.shared::cluster`, source `a` is either a shared memory variable or a register containing a valid shared memory address and register `d` contains a shared memory address. When the optional qualifier `.space` is not specified, both `a` and `d` are registers containing generic addresses pointing to shared memory. + +`b` is a 32-bit integer operand representing the rank of the target CTA. + +Destination register `d` will hold an address in CTA `b` corresponding to operand `a`. + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +mapa.shared::cluster.u64 d1, %reg1, cta; + mapa.shared::cluster.u32 d2, sh, 3; + mapa.u64 d3, %reg2, cta; \ No newline at end of file diff --git a/content/cuda/docs/ptx-matchsync/DOC.md b/content/cuda/docs/ptx-matchsync/DOC.md new file mode 100644 index 00000000..9bfc3742 --- /dev/null +++ b/content/cuda/docs/ptx-matchsync/DOC.md @@ -0,0 +1,76 @@ +--- +name: ptx-matchsync +description: Broadcast and compare a value across threads in warp. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.10. Parallel Synchronization and Communication Instructions:match.sync + +--- +title: "9.7.13.10. Parallel Synchronization and Communication Instructions:match.sync" +section: 9.7.13.10 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.10. Parallel Synchronization and Communication Instructions:match.sync + + +`match.sync` + +Broadcast and compare a value across threads in warp. + +Syntax + +match.any.sync.type d, a, membermask; + match.all.sync.type d[|p], a, membermask; + + .type = { .b32, .b64 }; + +Description + +`match.sync` will cause executing thread to wait until all non-exited threads from `membermask` have executed `match.sync` with the same qualifiers and same `membermask` value before resuming execution. + +Operand `membermask` specifies a 32-bit integer which is a mask indicating threads participating in this instruction where the bit position corresponds to thread’s laneid. + +`match.sync` performs broadcast and compare of operand `a` across all non-exited threads in `membermask` and sets destination `d` and optional predicate `p` based on mode. + +Operand `a` has instruction type and `d` has `.b32` type. + +Destination `d` is a 32-bit mask where bit position in mask corresponds to thread’s laneid. + +The matching operation modes are: + +`.all` + + +`d` is set to mask corresponding to non-exited threads in `membermask` if all non-exited threads in `membermask` have same value of operand `a`; otherwise `d` is set to 0. Optionally predicate `p` is set to true if all non-exited threads in `membermask` have same value of operand `a`; otherwise `p` is set to false. The sink symbol ‘_’ may be used in place of any one of the destination operands. + +`.any` + + +`d` is set to mask of non-exited threads in `membermask` that have same value of operand `a`. + +The behavior of `match.sync` is undefined if the executing thread is not in the `membermask`. + +PTX ISA Notes + +Introduced in PTX ISA version 6.0. + +Target ISA Notes + +Requires `sm_70` or higher. + +Release Notes + +Note that `match.sync` applies to threads in a single warp, not across an entire CTA. + +Examples + +match.any.sync.b32 d, a, 0xffffffff; + match.all.sync.b64 d|p, a, mask; \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-and-data-movement-shape/DOC.md b/content/cuda/docs/ptx-matrix-and-data-movement-shape/DOC.md new file mode 100644 index 00000000..4a60b59d --- /dev/null +++ b/content/cuda/docs/ptx-matrix-and-data-movement-shape/DOC.md @@ -0,0 +1,195 @@ +--- +name: ptx-matrix-and-data-movement-shape +description: There are two kinds of shapes involved. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.2. Matrix and Data Movement Shape + +--- +title: "9.7.16.2. Matrix and Data Movement Shape" +section: 9.7.16.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.2. Matrix and Data Movement Shape + + +There are two kinds of shapes involved. + +1. Shapes in the data movement operations + + 2. Shapes in the MMA operations + +##### 9.7.16.2.1. [Matrix Shape](<#tcgen05-matrix-shape>) + +The matrix multiply and accumulate operations support a limited set of shapes for the operand matrices `A`, `B` and `D`. The shapes of all three matrix operands are collectively described by the tuple _MxNxK_ where `A` is _MxK_ matrix, `B` is a _KxN_ matrix, and `D` is a _MxN_ matrix. + +[Table 39](<#tcgen05-kind-shapes>) shows matrix shapes that are supported for the specified types for the `tcgen05.mma` operation. + +Table 39 Various combinations of .kind and shapes Various Combinations | Shapes Supported +---|--- +.kind::* | Has .ws | CTA Group | Sparsity | dtype | atype/btype +`kind::f16` | No `.ws` | 1 | Dense | `.f16` | `.f16` | 64xNxK 128xNxK | N = {8, 16, 24, … 256} steps of 8 | K = 16 +`.f32` | `.f16`, `.bf16` +Sparse | `.f16` | `.f16` | K = 32 +`.f32` | `.f16`, `.bf16` +2 | Dense | `.f16` | `.f16` | 128xNxK 256xNxK | N = {16, 32, … 256} steps of 16 | K = 16 +`.f32` | `.f16`, `.bf16` +Sparse | `.f16` | `.f16` | K = 32 +`.f32` | `.f16`, `.bf16` +`.ws` | 1 | Dense | `.f16` | `.f16` | 32xNxK 64xNxK 128xNxK | N = {64, 128, 256} | K = 16 +`.f32` | `.f16`, `.bf16` +Sparse | `.f16` | `.f16` | N = {64, 128} | K = 32 +`.f32` | `.f16`, `.bf16` +2 | Either | `.f16` | `.f16` | Invalid +`.f32` | `.f16`, `.bf16` +`.kind::tf32` | No `.ws` | 1 | Dense | `.f32` | `.tf32` | 64xNxK 128xNxK | N = {8, 16, 24, … 256} steps of 8 | K = 8 +Sparse | K = 16 +2 | Dense | 128xNxK 256xNxK | N = {16, 32, … 256} steps of 16 | K = 8 +Sparse | K = 16 +`.ws` | 1 | Dense | 32xNxK 64xNxK 128xNxK | N = {64, 128, 256} | K = 8 +Sparse | N = {64, 128} | K = 16 +2 | Dense | Invalid +Sparse +`.kind::f8f6f4` | No `.ws` | 1 | Dense | `.f32` `.f16` | `.e4m3`, `.e5m2`, `.e2m3`, `.e3m2`, `.e2m1` | 64xNxK 128xNxK | N = {8, 16, … 256} steps of 8 | K = 32 +Sparse | K = 64 +2 | Dense | 128xNxK 256xNxK | N = {16, 32, … 256} steps of 16 | K = 32 +Sparse | K = 64 +`.ws` | 1 | Dense | 32xNxK 64xNxK 128xNxK | N = {64, 128, 256} | K = 32 +Sparse | N = {64, 128} | K = 64 +2 | Dense | Invalid +Sparse +`.kind::mxf8f6f4` | No `.ws` | 1 | Dense | `.f32` | `.e4m3`, `.e5m2`, `.e2m3`, `.e3m2`, `.e2m1` X (Scale) `.ue8m0` | 128xNxK | N = {8, 16, … 256} steps of 8 | K = 32 +Sparse | K = 64 +2 | Dense | 128xNxK 256xNxK | N = {16, 32, … 256} steps of 16 | K = 32 +Sparse | 256xNxK | K = 64 +`.ws` | 1 | Dense | Invalid +Sparse +2 | Dense +Sparse +`.kind::i8` | No `.ws` | 1 | Dense | `.s32` | `.s8`, `.u8` | 64xNxK 128xNxK | N = {8, 16, 24, 32, 48, … 256} steps of 16 after N > 32 | K = 32 +Sparse | K = 64 +2 | Dense | 128xNxK 256xNxK | N = {32, 64, … 256} steps of 32 | K = 32 +Sparse | K = 64 +`.ws` | 1 | Dense | 32xNxK 64xNxK 128xNxK | N = {64, 128, 256} | K = 32 +Sparse | N = {64, 128} | K = 64 +2 | Dense | Invalid +Sparse +`.kind::mxf4` | No `.ws` | 1 | Dense | `.f32` | `.e2m1` X (Scale) `.ue8m0` | 128xNxK | N = {8, 16, … 256} steps of 8 | K = 64 +Sparse | K = 128 +2 | Dense | 128xNxK 256xNxK 256xNxK1 | N = {16, 32, … 256} steps of 16 | K = 64 K1 = 96 +Sparse | 256xNxK | K = 128 +`.ws` | 1 / 2 | Either | Invalid +`.kind::mxf4nvf4` | No `.ws` | 1 | Dense | `.f32` | `.e2m1` X (Scale) `.ue8m0`, `.ue4m3` | 128xNxK | N = {8, 16, … 256} steps of 8 | K = 64 +Sparse | K = 128 +2 | Dense | 128xNxK 256xNxK 256xNxK1 | N = {16, 32, … 256} steps of 16 | K = 64 K1 = 96 +Sparse | 256xNxK | K = 128 +`.ws` | 1 / 2 | Either | Invalid + +###### 9.7.16.2.1.1. [Target ISA Note](<#tcgen05-matrix-shape-target-isa-note>) + + * K = 96 is only supported for target architecture `sm_103a`. + +##### 9.7.16.2.2. [Specifying Matrix Shape](<#tcgen05-specify-matrix-shape>) + +_M_ and _N_ can be specified in the [Instruction descriptor](<#tcgen05-instruction-descriptor>). + +_K_ cannot be explicitly specified but is implicitly determined by the MMA-kind and the sparsity, as shown in the [Table 39](<#tcgen05-kind-shapes>). + +##### 9.7.16.2.3. [Data Movement Shape](<#tcgen05-data-movement-shape>) + +The data movement shape indicates the dimension of the data to be moved to or from the [Tensor Memory](<#tensor-memory>). These shapes are described as a tuple `lane x size` where: + + * `lane` indicates the number of rows in the [Tensor Memory](<#tensor-memory>); and + + * `size` indicates the amount of data, in units of bits (b), across the columns in the [Tensor Memory](<#tensor-memory>). + + +The following shapes are supported by various tcgen05 operations: + +Shape | tcgen05. +---|--- +`.16x64b`, `.16x128b`, `.16x256b`, `.16x32bx2`, `.32x32b` | `.ld` / `.st` +`.4x256b`, `.32x128b`, `.64x128b`, `.128x256b`, `.128x128b` | `.cp` +`.31x256b` (implicit) | `.shift` + +###### 9.7.16.2.3.1. [Memory Layout](<#tcgen05-memory-layout>) + +The following shows the layout of the matrix fragments across threads of the warp. + +####### 9.7.16.2.3.1.1. [Matrix fragments for shape .32x32b](<#tcgen05-matrix-fragments-shape-3232b>) + +A `tcgen05{.ld,.st}.32x32b` instruction has the following data vector register. + +Fragment | Elements (low to high) +---|--- +A vector expression containing `.num` number of `.b32` registers as mentioned in the [Table 49](<#tcgen05-num-shapes-ld>). | r0, r1, … + +A warp executing `tcgen05{.ld,.st}.32x32b` will access 32 lanes of the Tensor Memory. It loads from or stores to each of the lane (32 * .num)-bits of data as shown in [Figure 183](<#tcgen05-mma-fragment-3232b>). + +![_images/tcgen05-mma-fragment-3232b.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-mma-fragment-3232b.png) + +Figure 183 Matrix Fragment for shape .32x32b + +####### 9.7.16.2.3.1.2. [Matrix fragments for shape .16x64b](<#tcgen05-matrix-fragments-shape-6464b>) + +A `tcgen05{.ld,.st}.16x64b` instruction has the following data vector register. + +Fragment | Elements (low to high) +---|--- +A vector expression containing `.num` number of `.b32` registers as mentioned in the [Table 49](<#tcgen05-num-shapes-ld>). | r0, r1, … + +A warp executing `tcgen05{.ld,.st}.16x64b` will access 16 lanes of the Tensor Memory. It loads from or stores to each of the lane (64 * .num)-bits of data as shown in [Figure 184](<#tcgen05-mma-fragment-1664b>). + +![_images/tcgen05-mma-fragment-1664b.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-mma-fragment-1664b.png) + +Figure 184 Matrix Fragment for shape .16x64b + +####### 9.7.16.2.3.1.3. [Matrix fragments for shape .16x128b](<#tcgen05-matrix-fragments-shape-16128b>) + +A `tcgen05{.ld,.st}.16x128b` instruction has the following data vector register. + +Fragment | Elements (low to high) +---|--- +A vector expression containing `.num` number of `.b32` registers as mentioned in the [Table 49](<#tcgen05-num-shapes-ld>). | r0, r1, … + +A warp executing `tcgen05{.ld,.st}.16x128b` will access 16 lanes of the Tensor Memory. It loads from or stores to each of the lane (128 * .num)-bits of data as shown in [Figure 185](<#tcgen05-mma-fragment-16128b>). + +![_images/tcgen05-mma-fragment-16128b.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-mma-fragment-16128b.png) + +Figure 185 Matrix Fragment for shape .16x128b + +####### 9.7.16.2.3.1.4. [Matrix fragments for shape .16x256b](<#tcgen05-matrix-fragments-shape-16256b>) + +A `tcgen05{.ld,.st}.16x256b` instruction has the following data vector register. + +Fragment | Elements (low to high) +---|--- +A vector expression containing `.num` number of `.b32` registers as mentioned in the [Table 49](<#tcgen05-num-shapes-ld>). | r0, r1, r2, r3, … + +A warp executing `tcgen05{.ld,.st}.16x256b` will access 16 lanes of the Tensor Memory. It loads from or stores to each of the lane (256 * .num)-bits of data as shown in [Figure 186](<#tcgen05-mma-fragment-16256b>). + +![_images/tcgen05-mma-fragment-16256b.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-mma-fragment-16256b.png) + +Figure 186 Matrix Fragment for shape .16x256b + +####### 9.7.16.2.3.1.5. [Matrix fragments for shape .16x32bx2](<#tcgen05-matrix-fragments-shape-1632b2>) + +A `tcgen05{.ld,.st}.16x32bx2` instruction has the following data vector register. + +Fragment | Elements (low to high) +---|--- +A vector expression containing `.num` number of `.b32` registers as mentioned in the [Table 49](<#tcgen05-num-shapes-ld>). | r0, r1, … + +A warp executing `tcgen05{.ld,.st}.16x32bx2` will access 16 lanes of the Tensor Memory. It loads from or stores to each of the lane (32 * .num)-bits of data as shown in [Figure 187](<#tcgen05-mma-fragment-1632b2>). + +![_images/tcgen05-mma-fragment-1632b2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tcgen05-mma-fragment-1632b2.png) + +Figure 187 Matrix Fragment for shape .16x32bx2 \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-data-types/DOC.md b/content/cuda/docs/ptx-matrix-data-types/DOC.md new file mode 100644 index 00000000..f52c802c --- /dev/null +++ b/content/cuda/docs/ptx-matrix-data-types/DOC.md @@ -0,0 +1,41 @@ +--- +name: ptx-matrix-data-types +description: The matrix multiply and accumulate operation is supported separately + on integer, floating-point, sub-byte integer and single bit data-types. All operands + must contain the same basic type kind, i.e., i... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.14.2. Matrix Data-types + +--- +title: "9.7.14.2. Matrix Data-types" +section: 9.7.14.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.14.2. Matrix Data-types + + +The matrix multiply and accumulate operation is supported separately on integer, floating-point, sub-byte integer and single bit data-types. All operands must contain the same basic type kind, i.e., integer or floating-point. + +For floating-point matrix multiply and accumulate operation, different matrix operands may have different precision, as described later. + +Data-type | Multiplicands (A or B) | Accumulators (C or D) +---|---|--- +Integer | `.u8`, `.s8` | `.s32` +Floating Point | `.f16` | `.f16`, `.f32` +Alternate floating Point | `.bf16` | `.f32` +Alternate floating Point | `.tf32` | `.f32` +Alternate floating Point | `.e4m3` or `.e5m2` or `.e3m2` or `.e2m3` or `.e2m1` | `.f16`, `.f32` +Alternate floating Point with scale | `.e4m3` or `.e5m2` or `.e3m2` or `.e2m3` or `.e2m1` X (Scale) `.ue8m0` | `.f32` +Alternate floating Point with scale | `.e2m1` X (Scale) `.ue8m0` or `.ue4m3` | `.f32` +Floating Point | `.f64` | `.f64` +Sub-byte integer | both `.u4` or both `.s4` | `.s32` +Single-bit integer | `.b1` | `.s32` \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-descriptors/DOC.md b/content/cuda/docs/ptx-matrix-descriptors/DOC.md new file mode 100644 index 00000000..9e2cbd7f --- /dev/null +++ b/content/cuda/docs/ptx-matrix-descriptors/DOC.md @@ -0,0 +1,226 @@ +--- +name: ptx-matrix-descriptors +description: There are three kinds of matrix descriptors used by the `tcgen05` family + of instructions. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.4. Matrix Descriptors + +--- +title: "9.7.16.4. Matrix Descriptors" +section: 9.7.16.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.4. Matrix Descriptors + + +There are three kinds of matrix descriptors used by the `tcgen05` family of instructions. + +##### 9.7.16.4.1. [Shared memory descriptor](<#tcgen05-shared-memory-descriptor>) + +The shared memory descriptor describes the properties of multiplicand matrix in shared memory including its location in the shared memory of the current _CTA_. It is a 64-bit value contained in a register with the following layout: + +Table 40 Shared memory descriptor layout Bit-field | Size in bits | Description +---|---|--- +0-13 | 14 | matrix-descriptor-encode (Matrix start address) +16-29 | 14 | matrix-descriptor-encode ([Leading dimension byte offset relative](<#tcgen05-leading-dimension-byte-offset>)) OR matrix-descriptor-encode ([Leading dimension byte address absolute](<#tcgen05-leading-dimension-byte-offset>)) +32-45 | 14 | matrix-descriptor-encode ([Stride dimension byte offset](<#tcgen05-stride-dimension-byte-offset>)) +46-48 | 3 | Fixed constant value of 0b001 +49-51 | 3 | Matrix base offset +52 | 1 | Leading dimension stride mode: \- 0: byte offset relative \- 1: byte address absolute +53-60 | 8 | Fixed constant value of 0xb00000000 +61-63 | 3 | Specifies the swizzling mode to be used: 0\. No swizzling 1\. 128-Byte with 32B atomic swizzling 2\. 128-Byte swizzling 4\. 64-Byte swizzling 6\. 32-Byte swizzling Note: Values 3, 5 and 7 are invalid + +where matrix-descriptor-encode(x) = (x & 0x3FFFF) >> 4 + +The value of base offset is 0 when the repeating pattern of the specified swizzling mode starts as per shown in [Table 41](<#tcgen05-start-addr-swizzle-mode>). + +Table 41 Starting address of repeating pattern for various swizzling modes Swizzling mode | Starting address of the repeating pattern +---|--- +128-Byte swizzle | 1024-Byte boundary +64-Byte swizzle | 512-Byte boundary +32-Byte swizzle | 256-Byte boundary + +Otherwise, the base offset must be a non-zero value, computed using the following formula: `base offset = (pattern start addr >> 0x7) & 0x7` + +The following must be 16-byte aligned: + + 1. Matrix start address + + 2. Leading dimension byte offset + + 3. Stride dimension byte offset + + +###### 9.7.16.4.1.1. [Target ISA Note](<#tcgen05-shared-memory-descriptor-target-isa-note>) + + * The byte address mode for the leading dimension stride is supported on `sm_103a`. + +##### 9.7.16.4.2. [Instruction descriptor](<#tcgen05-instruction-descriptor>) + +The instruction descriptor describes the shapes, types and other details of all the matrices and the matrix-multiplication-and-accumulation operation. It is a 32-bit value in registers and the exact layout is dependent on the MMA-Kind: + +Table 42 Instruction descriptor format for .kind::tf32, .kind::f16, .kind::f8f6f4 and .kind::i8 Bits | Size (bits) | Description | Values +---|---|---|--- +.kind::tf32 | .kind::f16 | .kind::f8f6f4 | .kind::i8 +0-1 | 2 | [Sparsity selector](<#tcgen05-sparse-matrices-sparsity-selector>), if Sparsity is enabled | 0-3 +2 | 1 | Sparsity | Dense = 0 Sparse = 1 +3 | 1 | Saturate for integer types | 0 (NA) | No Saturate = 0 Saturate = 1 +4-5 | 2 | dtype (Matrix D type) | F32 = 1 | F16 = 0 F32 = 1 | S32 = 2 +6 | 1 | Reserved | 0 +7-9 | 3 | atype (Matrix A type) | TF32 = 2 | F16 = 0 BF16 = 1 | E4M3 = 0 E5M2 = 1 E2M3 = 3 E3M2 = 4 E2M1 = 5 | Unsigned 8b = 0 Signed 8b = 1 +10-12 | 3 | btype (Matrix B type) +13 | 1 | Negate A Matrix | No Negate = 0 Negate = 1 | No Negate = 0 +14 | 1 | Negate B Matrix +15 | 1 | Transpose A Matrix | No Transpose = 0 Transpose = 1 +16 | 1 | Transpose B Matrix +17-22 | 6 | N, Dimension of Matrix B (3 LSBs not included) | N >> 3 +23 | 1 | Reserved | 0 +24-28 | 5 | M, Dimension of Matrix A (4 LSBs not included) | M >> 4 +29 | 1 | Reserved | 0 +30-31 | 2 | Maximum shift while attempting B matrix -reuse in `.ws` | no shift = 0 maximum shift of 8 = 1 maximum shift of 16 = 2 maximum shift of 32 = 3 +Table 43 Instruction descriptor format for .kind::mxf8f6f4 Bits | Size (bits) | Description | Values +---|---|---|--- +.kind::mxf8f6f4 +0-1 | 2 | Reserved | 0 +2 | 1 | Sparsity | Dense = 0 Sparse = 1 +3 | 1 | Reserved | 0 +4-5 | 2 | [Matrix B Scale Factor Data ID](<#tcgen05-mma-scale-factor-b>) | 0-3 +6 | 1 | Reserved | 0 +7-9 | 3 | atype (Matrix A type) | E4M3 = 0 E5M2 = 1 E2M3 = 3 E3M2 = 4 E2M1 = 5 +10-12 | 3 | btype (Matrix B type) +13 | 1 | Negate A Matrix | No Negate = 0 Negate = 1 +14 | 1 | Negate B Matrix +15 | 1 | Transpose A Matrix | No Transpose = 0 Transpose = 1 +16 | 1 | Transpose B Matrix +17-22 | 6 | N, Dimension of Matrix B (3 LSBs not included) | N >> 3 +23 | 1 | Scale Matrix Type, for both scale_A / scale_B | UE8M0 = 1 +24-26 | 3 | Reserved | 0 +27-28 | 2 | M, Dimension of Matrix A (7 LSBs not included) | M >> 7 +29-30 | 2 | [Matrix A Scale Factor Data ID](<#tcgen05-mma-scale-factor-a>) | 0-3 +31 | 1 | Reserved | 0 +Table 44 Instruction descriptor format for .kind::mxf4 and .kind::mxf4nvf4 Bits | Size (bits) | Description | Values +---|---|---|--- +.kind::mxf4 | .kind::mxf4nvf4 +0-1 | 2 | Reserved | 0 +2 | 1 | Sparsity | Dense = 0 Sparse = 1 +3 | 1 | Reserved | 0 +4-5 | 2 | [Matrix B Scale Factor Data ID](<#tcgen05-mma-scale-factor-b>) | 0 or 2 +6 | 1 | Reserved | 0 +7-9 | 3 | atype (Matrix A type) | E2M1 = 1 +10-11 | 2 | btype (Matrix B type) +12 | 1 | Reserved | 0 +13 | 1 | Negate A Matrix | No Negate = 0 Negate = 1 +14 | 1 | Negate B Matrix +15 | 1 | Transpose A Matrix | No Transpose = 0 +16 | 1 | Transpose B Matrix +17-22 | 6 | N, Dimension of Matrix B (3 LSBs not included) | N >> 3 +23 | 1 | Scale Matrix Type, for both scale_A / scale_B | UE8M0 = 1 | UE4M3 = 0 +24-26 | 3 | Reserved | 0 +27-28 | 2 | M, Dimension of Matrix A (7 LSBs not included) | M >> 7 +29-30 | 2 | [Matrix A Scale Factor Data ID](<#tcgen05-mma-scale-factor-a>) | 0 or 2 +31 | 1 | K Dimension | (Dense K=64 / Sparse K=128) = 0 (Dense K=96) = 1 + +##### 9.7.16.4.3. [Zero-Column Mask Descriptor](<#tcgen05-zero-column-mask-descriptor>) + +The zero-column mask descriptor is used to generate a mask that specifies which columns of `B` matrix will have zero value for the MMA operation regardless of the values present in the shared memory. The total size of the generated mask is N-bits. + +A 0-bit in the mask specifies that values of the corresponding column in matrix `B` should be used for the MMA operation. A 1-bit in the mask specifies 0s must be used for the entire column for the MMA operation. + +The zero-column mask descriptor is a 64-bit value in registers with the following layout: + +Table 45 Zero-Column Mask descriptor layout Bits | Size (bits) | Field Name | Description +---|---|---|--- +0-7 | 8 | Start Count 0 (sc0) | Specifies the LSBs that must be skipped for sub-mask mask-i +8-15 | 8 | Start Count 1 (sc1) +16-23 | 8 | Start Count 2 (sc2) +24-31 | 8 | Start Count 3 (sc3) +32 | 1 | First Span 0 (fs0) | Specifies the starting value for sub-mask mask-i +33 | 1 | First Span 1 (fs1) +34 | 1 | First Span 2 (fs2) +35 | 1 | First Span 3 (fs3) +36-38 | 3 | Reserved | +39 | 1 | Non-Zero Mask | Value 0 indicates generated mask will have all 0s Value 1 indicates the mask has to be generated +40-47 | 8 | Skip Span | (Count of consecutive columns where B matrix is used) - 1 +48-55 | 8 | Use Span | (Count of consecutive columns where 0s ar used) - 1 +56-61 | 6 | Column Shift | Shifts column by specified amount. Thus allows MMA on non-0 starting column. Max shift amount = 16 for M=32 Max shift amount = 32 otherwise + +The zero-column mask is made up of one or more sub-mask depending on M, as shown in the table: + +M | Zero-Column Mask breakup | Sub-masks | First Span used | Start Column used +---|---|---|---|--- +128 | Single sub-mask of size N-bits | mask0 | fs0 | sc0 +64 | Two sub-masks, each with size of N/2 bits | mask0, mask1 | fs0, fs1 | sc0, sc1 +32 | Four sub-masks, each with size of N/4 bits | mask0, mask1 mask2, mask3 | fs0, fs1, fs2, fs3 | sc0, sc1, sc2, sc3 + +The following table shows the coverage of the sub-masks across N-dimension: + +Sub-mask | M +---|--- +128 | 64 | 32 +mask0 | Columns [0, N-1] | Columns [0, N/2-1] | Columns [0, N/4-1] +mask1 | – | Columns [N/2, N-1] | Columns [N/4, N/2-1] +mask2 | – | – | Columns [N/2, (N/4*3)-1] +mask3 | – | – | Columns [(N/4*3), N-1] + +The following examples shows zero-column mask descriptor and their corresponding mask generated: + + 1. Example 1: M = 128 + +Input zero-column mask descriptor: + +Start count | First span | Non-Zero Mask | Skip Span | Use Span | Shift +---|---|---|---|---|--- +{0, 0, 0, 0} | {0, 0, 0, 0} | 0 | 4 | 3 | 0 + +Output zero-column mask: 0x0. + +As Non-Zero Mask field is 0, the mask is 0x0. All the columns of the matrix `B` will be used for the MMA operation. + + 2. Example 2: M = 128 + +Input zero-column mask descriptor: + +Start count | First span | Non-Zero Mask | Skip Span | Use Span | Shift +---|---|---|---|---|--- +{-, -, -, 0} | {-, -, -, 0} | 1 | 2 | 3 | 0 + +Output mask0: 0b … 111 0000 111 0000 (size = N) + + 3. Example 3: M = 64 + +Input zero-column mask descriptor: + +Start count {.., sc1, sc0} | First span {.., fs1, fs0} | Non-Zero Mask | Skip Span | Use Span | Shift +---|---|---|---|---|--- +{-, -, 0, 0} | {-, -, 0, 1} | 1 | 2 | 3 | 0 + +Output mask0: 0b … 111 0000 111 0000 111 + +Output masl1: 0b … 0000 111 0000 111 0000 + + 4. Example 4: M = 32 + +Input zero-column mask descriptor: + +Start count {sc3, sc2, sc1, sc0} | First span {fs3, fs2, fs1, fs0} | Non-Zero Mask | Skip Span | Use Span | Shift +---|---|---|---|---|--- +{1, 2, 1, 0} | {0, 0, 1, 1} | 1 | 2 | 3 | 2 + +Output mask0: 0b … 0000 111 0000 111 + +Output mask1: 0b … 0000 111 0000 11 + +Output mask2: 0b … 111 0000 111 00 + +Output mask3: 0b … 111 0000 111 000 + +If N = 128 then `B` Matrix with columns from 2 to 129 will be used for the MMA operation, due to the shift of 2. \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmainstruction/DOC.md b/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmainstruction/DOC.md new file mode 100644 index 00000000..549cc233 --- /dev/null +++ b/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmainstruction/DOC.md @@ -0,0 +1,2336 @@ +--- +name: ptx-matrix-multiply-accumulate-operation-usingmmainstruction +description: This section describes warp-level `mma`, `ldmatrix`, `stmatrix`, and + `movmatrix` instructions and the organization of various matrices involved in these + instructions. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.14.5. Matrix multiply-accumulate operation usingmmainstruction + +--- +title: "9.7.14.5. Matrix multiply-accumulate operation usingmmainstruction" +section: 9.7.14.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.14.5. Matrix multiply-accumulate operation usingmmainstruction + + +This section describes warp-level `mma`, `ldmatrix`, `stmatrix`, and `movmatrix` instructions and the organization of various matrices involved in these instructions. + +##### 9.7.14.5.1. [Matrix Fragments for `mma.m8n8k4` with `.f16` floating point type](<#warp-level-matrix-fragment-mma-884-f16>) + +A warp executing `mma.m8n8k4` with `.f16` floating point type will compute 4 MMA operations of shape `.m8n8k4`. + +Elements of 4 matrices need to be distributed across the threads in a warp. The following table shows distribution of matrices for MMA operations. + +MMA Computation | Threads participating in MMA computation +---|--- +MMA computation 1 | Threads with `%laneid` 0-3 (low group) and 16-19 (high group) +MMA computation 2 | Threads with `%laneid` 4-7 (low group) and 20-23 (high group) +MMA computation 3 | Threads with `%laneid` 8-11 (low group) and 24-27 (high group) +MMA computation 4 | Threads with `%laneid` 12-15 (low group) and 28-31 (high group) + +For each of the individual MMA computation shown above, each of the required thread holds a fragment of the matrix for performing mma operation as follows: + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix A. | a0, a1, a2, a3 + +The layout of the fragments held by different threads is shown below: + + * Fragment layout for Row Major matrix A is shown in [Figure 46](<#mma-884-a-row-f16>). + +![_images/mma-884-A-row-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-A-row-f16.png) + +Figure 46 MMA .m8n8k4 fragment layout for row-major matrix A with `.f16` type + +The row and column of a matrix fragment can be computed as: + + row = %laneid % 4 if %laneid < 16 + (%laneid % 4) + 4 otherwise + + col = i for ai where i = {0,..,3} + + + * Fragment layout for Column Major matrix A is shown in [Figure 47](<#mma-884-a-col-f16>). + +The layout of the fragments held by different threads is shown below: + +![_images/mma-884-A-col-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-A-col-f16.png) + +Figure 47 MMA .m8n8k4 fragment layout for column-major matrix A with `.f16` type + +The row and column of a matrix fragment can be computed as: + + row = i % 4 for ai where i = {0,..,3} if %laneid < 16 + (i % 4) + 4 for ai where i = {0,..,3} otherwise + + col = %laneid % 4 + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix B. | b0, b1, b2, b3 + +The layout of the fragments held by different threads is shown below: + + * Fragment layout for Row Major matrix B is shown in [Figure 48](<#mma-884-b-row-f16>). + +![_images/mma-884-B-row-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-B-row-f16.png) + +Figure 48 MMA .m8n8k4 fragment layout for row-major matrix B with `.f16` type + +The row and column of a matrix fragment can be computed as: + + row = %laneid % 4 + + col = i for bi where i = {0,..,3} if %laneid < 16 + i+4 for bi where i = {0,..,3} otherwise + + + * Fragment layout for Column Major matrix B is shown in [Figure 49](<#mma-884-b-col-f16>). + +![_images/mma-884-B-col-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-B-col-f16.png) + +Figure 49 MMA .m8n8k4 fragment layout for column-major matrix B with `.f16` type + +The row and column of a matrix fragment can be computed as: + + row = i for bi where i = {0,..,3} + + col = %laneid % 4 if %laneid < 16 + (%laneid % 4) + 4 otherwise + + + * Accumulators C (or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.f16` | A vector expression containing four `.f16x2` registers, with each register containing two `.f16` elements from the matrix C (or D). | c0, c1, c2, c3, c4, c5, c6, c7 +`.f32` | A vector expression of eight `.f32` registers. + +The layout of the fragments held by different threads is shown below: + + * Fragment layout for accumulator matrix when `.ctype` is `.f16` is shown in [Figure 50](<#mma-884-c-f16>). + +![_images/mma-884-C-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-C-f16.png) + +Figure 50 MMA .m8n8k4 fragment layout for matrix C/D with `.ctype` = `.f16` + +The row and column of a matrix fragment can be computed as: + + row = %laneid % 4 if %laneid < 16 + (%laneid % 4) + 4 otherwise + + col = i for ci where i = {0,..,7} + + + * Fragment layout for accumulator matrix when `.ctype` is `.f32` is shown in [Figure 51](<#mma-884-c-f32-1>) and [Figure 52](<#mma-884-c-f32-2>). + +![_images/mma-884-C-f32-1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-C-f32-1.png) + +Figure 51 MMA .m8n8k4 computation 1 and 2 fragment layout for matrix C/D with `.ctype` = `.f32` + +![_images/mma-884-C-f32-2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-C-f32-2.png) + +Figure 52 MMA .m8n8k4 computation 3 and 4 fragment layout for matrix C/D with `.ctype` = `.f32` + +The row and column of a matrix fragment can be computed as: + + row = X if %laneid < 16 + X + 4 otherwise + + where X = (%laneid & 0b1) + (i & 0b10) for ci where i = {0,..,7} + + col = (i & 0b100) + (%laneid & 0b10) + (i & 0b1) for ci where i = {0,..,7} + +##### 9.7.14.5.2. [Matrix Fragments for `mma.m8n8k4` with `.f64` floating point type](<#warp-level-matrix-fragment-mma-884-f64>) + +A warp executing `mma.m8n8k4` with `.f64` floating point type will compute an MMA operation of shape `.m8n8k4`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.f64` | A vector expression containing a single `.f64` register, containing single `.f64` element from the matrix A. | a0 + +The layout of the fragments held by different threads is shown in [Figure 53](<#mma-884-a-f64>). + +![_images/mma-884-A-f64.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-A-f64.png) + +Figure 53 MMA .m8n8k4 fragment layout for matrix A with `.f64` type + +The row and column of a matrix fragment can be computed as: + + row = %laneid >> 2 + + col = %laneid % 4 + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.f64` | A vector expression containing a single `.f64` register, containing a single `.f64` element from the matrix B. | b0 + +The layout of the fragments held by different threads is shown in [Figure 54](<#mma-884-b-f64>). + +![_images/mma-884-B-f64.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-B-f64.png) + +Figure 54 MMA .m8n8k4 fragment layout for matrix B with `.f64` type + +The row and column of a matrix fragment can be computed as: + + row = %laneid % 4 + + col = %laneid >> 2 + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.f64` | A vector expression containing of two `.f64` registers containing two `.f64` elements from the matrix C. | c0, c1 + +The layout of the fragments held by different threads is shown in [Figure 55](<#mma-884-c-f64>). + +![_images/mma-884-C-f64.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-884-C-f64.png) + +Figure 55 MMA .m8n8k4 fragment layout for accumulator matrix C/D with `.f64` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0, 1} + +##### 9.7.14.5.3. [Matrix Fragments for `mma.m8n8k16`](<#warp-level-matrix-fragment-mma-8816>) + +A warp executing `mma.m8n8k16` will compute an MMA operation of shape `.m8n8k16`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.s8` / `.u8` | A vector expression containing a single `.b32` register, containing four `.s8` or `.u8` elements from the matrix A. | a0, a1, a2, a3 + +The layout of the fragments held by different threads is shown in [Figure 56](<#mma-8816-a-i8>). + +![_images/mma-8816-A-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8816-A-i8.png) + +Figure 56 MMA .m8n8k16 fragment layout for matrix A with `.u8`/`.s8` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 4) + i for ai where i = {0,..,3} + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.s8` / `.u8` | A vector expression containing a single `.b32` register, containing four `.s8` or `.u8` elements from the matrix B. | b0, b1, b2, b3 + +The layout of the fragments held by different threads is shown in [Figure 57](<#mma-8816-b-i8>). + +![_images/mma-8816-B-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8816-B-i8.png) + +Figure 57 MMA .m8n8k16 fragment layout for matrix B with `.u8`/`.s8` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 4) + i for bi where i = {0,..,3} + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing of two `.s32` registers. | c0, c1 + +The layout of the fragments held by different threads is shown in [Figure 58](<#mma-8816-c-i8>). + +![_images/mma-8816-C-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8816-C-i8.png) + +Figure 58 MMA .m8n8k16 fragment layout for accumulator matrix C/D with `.s32` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 2) + i for ci where i = {0, 1} + +##### 9.7.14.5.4. [Matrix Fragments for `mma.m8n8k32`](<#warp-level-matrix-fragment-mma-8832>) + +A warp executing `mma.m8n8k32` will compute an MMA operation of shape `.m8n8k32`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.s4` / `.u4` | A vector expression containing a single `.b32` register, containing eight `.s4` or `.u4` elements from the matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 + +The layout of the fragments held by different threads is shown in [Figure 59](<#mma-8832-a-i4>). + +![_images/mma-8832-A-i4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8832-A-i4.png) + +Figure 59 MMA .m8n8k32 fragment layout for matrix A with `.u4`/`.s4` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 8) + i for ai where i = {0,..,7} + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.s4` / `.u4` | A vector expression containing a single `.b32` register, containing eight `.s4` or `.u4` elements from the matrix B. | b0, b1, b2, b3, b4, b5, b6, b7 + +The layout of the fragments held by different threads is shown in [Figure 60](<#mma-8832-b-i4>). + +![_images/mma-8832-B-i4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8832-B-i4.png) + +Figure 60 MMA .m8n8k32 fragment layout for matrix B with `.u4`/`.s4` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 8) + i for bi where i = {0,..,7} + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression of two `.s32` registers. | c0, c1 + +The layout of the fragments held by different threads is shown in [Figure 61](<#mma-8832-c-i4>): + +![_images/mma-8832-C-i4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-8832-C-i4.png) + +Figure 61 MMA .m8n8k32 fragment layout for accumulator matrix C/D with `.s32` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + col = (threadID_in_group * 2) + i for ci where i = {0, 1} + +##### 9.7.14.5.5. [Matrix Fragments for `mma.m8n8k128`](<#warp-level-matrix-fragment-mma-88128>) + +A warp executing `mma.m8n8k128` will compute an MMA operation of shape `.m8n8k128`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing a single `.b32` register, containing thirty two `.b1` elements from the matrix A. | a0, a1, … a30, a31 + +The layout of the fragments held by different threads is shown in [Figure 62](<#mma-88128-a>). + +![_images/mma-88128-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-88128-A.png) + +Figure 62 MMA .m8n8k128 fragment layout for matrix A with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 32) + i for ai where i = {0,..,31} + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing a single `.b32` register, containing thirty two `.b1` elements from the matrix B. | b0, b1, …, b30, b31 + +The layout of the fragments held by different threads is shown in [Figure 63](<#mma-88128-b>). + +![_images/mma-88128-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-88128-B.png) + +Figure 63 MMA .m8n8k128 fragment layout for matrix B with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 32) + i for bi where i = {0,..,31} + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing two `.s32` registers, containing two `.s32` elements from the matrix C (or D). | c0, c1 + +The layout of the fragments held by different threads is shown in [Figure 64](<#mma-88128-c>). + +![_images/mma-88128-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-88128-C.png) + +Figure 64 MMA .m8n8k128 fragment layout for accumulator matrix C/D with `.s32` type + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID + + col = (threadID_in_group * 2) + i for ci where i = {0, 1} + +##### 9.7.14.5.6. [Matrix Fragments for `mma.m16n8k4`](<#warp-level-matrix-fragment-mma-1684>) + +A warp executing `mma.m16n8k4` will compute an MMA operation of shape `.m16n8k4`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + + * `.tf32`: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.tf32` | A vector expression containing two `.b32` registers, containing two `.tf32` elements from the matrix A. | a0, a1 + +The layout of the fragments held by different threads is shown in [Figure 65](<#mma-1684-a-tf32>). + +![_images/mma-1684-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-A.png) + +Figure 65 MMA .m16n8k4 fragment layout for matrix A with `.tf32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for a0 + groupID + 8 for a1 + + col = threadID_in_group + + + * `.f64`: + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression containing two `.f64` registers, containing two `.f64` elements from the matrix A. | a0, a1 +> +> The layout of the fragments held by different threads is shown in [Figure 66](<#mma-1684-a-f64>). +> +> ![_images/mma-1684-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-A.png) +> +> Figure 66 MMA .m16n8k4 fragment layout for matrix A with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for a0 +> groupID + 8 for a1 +> +> col = threadID_in_group +> + + * Multiplicand B: + + * `.tf32`: + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.tf32` | A vector expression of a single `.b32` register, containing a single `.tf32` element from the matrix B. | b0 +> +> The layout of the fragments held by different threads is shown in [Figure 67](<#mma-1684-b-tf32>). +> +> ![_images/mma-1684-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-B.png) +> +> Figure 67 MMA .m16n8k4 fragment layout for matrix B with `.tf32` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = threadID_in_group +> +> col = groupID +> + + * `.f64`: + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression of a single `.f64` register, containing a single `.f64` element from the matrix B. | b0 +> +> The layout of the fragments held by different threads is shown in [Figure 68](<#mma-1684-b-f64>). +> +> ![_images/mma-1684-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-B.png) +> +> Figure 68 MMA .m16n8k4 fragment layout for matrix B with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = threadID_in_group +> +> col = groupID +> + + * Accumulators (C or D): + + * `.tf32`: + +> .ctype / .dtype | Fragment | Elements (low to high) +> ---|---|--- +> `.f32` | A vector expression containing four `.f32` registers, containing four `.f32` elements from the matrix C (or D). | c0, c1, c2, c3 +> +> The layout of the fragments held by different threads is shown in [Figure 69](<#mma-1684-c-f32>). +> +> ![_images/mma-1684-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-C.png) +> +> Figure 69 MMA .m16n8k4 fragment layout for accumulator matrix C/D with `.f32` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for c0 and c1 +> groupID + 8 for c2 and c3 +> +> col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} +> + + * `.f64`: + +> .ctype / .dtype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression containing four `.f64` registers, containing four `.f64` elements from the matrix C (or D). | c0, c1, c2, c3 +> +> The layout of the fragments held by different threads is shown in [Figure 70](<#mma-1684-c-f64>). +> +> ![_images/mma-1684-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1684-C.png) +> +> Figure 70 MMA .m16n8k4 fragment layout for accumulator matrix C/D with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for c0 and c1 +> groupID + 8 for c2 and c3 +> +> col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} +> + +##### 9.7.14.5.7. [Matrix Fragments for `mma.m16n8k8`](<#warp-level-matrix-fragment-mma-1688>) + +A warp executing `mma.m16n8k8` will compute an MMA operation of shape `.m16n8k8`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + + * `.f16` and `.bf16` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.f16` / `.bf16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` / `.bf16` elements from the matrix A. | a0, a1, a2, a3 +> +> The layout of the fragments held by different threads is shown in [Figure 71](<#mma-1688-a-f16>). +> +> ![_images/mma-1688-A-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-A-f16.png) +> +> Figure 71 MMA .m16n8k8 fragment layout for matrix A with `.f16` / `.bf16` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for a0 and a1 +> groupID + 8 for a2 and a3 +> +> col = threadID_in_group * 2 + (i & 0x1) for ai where i = {0,..,3} +> + + * `.tf32` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.tf32` | A vector expression containing four `.b32` registers, containing four `.tf32` elements from the matrix A. | a0, a1, a2, a3 +> +> The layout of the fragments held by different threads is shown in [Figure 72](<#mma-1688-a-tf32>). +> +> ![_images/mma-1688-A-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-A-tf32.png) +> +> Figure 72 MMA .m16n8k8 fragment layout for matrix A with `.tf32` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for a0 and a2 +> groupID + 8 for a1 and a3 +> +> col = threadID_in_group for a0 and a1 +> threadID_in_group + 4 for a2 and a3 +> + + * `.f64` : + +.atype | Fragment | Elements (low to high) +---|---|--- +`.f64` | A vector expression containing four `.f64` registers, containing four `.f64` elements from the matrix A. | a0, a1, a2, a3 + +The layout of the fragments held by different threads is shown in [Figure 73](<#mma-1688-a-f64>). + +![_images/mma-1688-A-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-A-tf32.png) + +Figure 73 MMA .m16n8k8 fragment layout for matrix A with `.f64` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for a0 and a2 + groupID + 8 for a1 and a3 + + col = threadID_in_group for a0 and a1 + threadID_in_group + 4 for a2 and a3 + + + * Multiplicand B: + + * `.f16` and `.bf16` : + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.f16` / `.bf16` | A vector expression containing a single `.f16x2` register, containing two `.f16` / `.bf16` elements from the matrix B. | b0, b1 +> +> The layout of the fragments held by different threads is shown in [Figure 74](<#mma-1688-b-f16>). +> +> ![_images/mma-1688-B-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-B-f16.png) +> +> Figure 74 MMA .m16n8k8 fragment layout for matrix B with `.f16` / `.bf16` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = (threadID_in_group * 2) + i for bi where i = {0, 1} +> +> col = groupID +> + + * `.tf32` : + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.tf32` | A vector expression containing two `.b32` registers, containing two `.tf32` elements from the matrix B. | b0, b1 +> +> The layout of the fragments held by different threads is shown in [Figure 75](<#mma-1688-b-tf32>). +> +> ![_images/mma-1688-B-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-B-tf32.png) +> +> Figure 75 MMA .m16n8k8 fragment layout for matrix B with `.tf32` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = threadID_in_group for b0 +> threadID_in_group + 4 for b1 +> +> col = groupID +> + + * `.f64` : + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression containing two `.f64` registers, containing two `.f64` elements from the matrix B. | b0, b1 +> +> The layout of the fragments held by different threads is shown in [Figure 76](<#mma-1688-b-f64>). +> +> ![_images/mma-1688-B-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-B-tf32.png) +> +> Figure 76 MMA .m16n8k8 fragment layout for matrix B with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = threadID_in_group for b0 +> threadID_in_group + 4 for b1 +> +> col = groupID +> + + * Accumulators (C or D): + + * `.f16`, `.bf16` and `.tf32`: + +> .ctype / .dtype | Fragment | Elements (low to high) +> ---|---|--- +> `.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix C (or D). | c0, c1, c2, c3 +> `.f32` | A vector expression of four `.f32` registers. | +> +> The layout of the fragments held by different threads is shown in [Figure 77](<#mma-1688-c-f16-f32>). +> +> ![_images/mma-1688-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-C.png) +> +> Figure 77 MMA .m16n8k8 fragment layout for accumulator matrix C/D with `.f16x2`/`.f32` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for c0 and c1 +> groupID + 8 for c2 and c3 +> +> col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} +> + + * `.f64` : + +> .ctype / .dtype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression of four `.f64` registers containing four `.f64` elements from the matrix C (or D). | c0, c1, c2, c3 +> +> The layout of the fragments held by different threads is shown in [Figure 78](<#mma-1688-c-f64>). +> +> ![_images/mma-1688-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-1688-C.png) +> +> Figure 78 MMA .m16n8k8 fragment layout for accumulator matrix C/D with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for c0 and c1 +> groupID + 8 for c2 and c3 +> +> col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} +> + +##### 9.7.14.5.8. [Matrix Fragments for `mma.m16n8k16` with floating point type](<#warp-level-matrix-fragment-mma-16816-float>) + +A warp executing `mma.m16n8k16` floating point types will compute an MMA operation of shape `.m16n8k16`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + + * `.f16` and `.bf16` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.f16` / `.bf16` | A vector expression containing four `.f16x2` registers, with each register containing two `.f16` / `.bf16` elements from the matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 +> +> The layout of the fragments held by different threads is shown in [Figure 79](<#mma-16816-a-f16>). +> +> ![_images/mma-16816-A-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-A-f16.png) +> +> Figure 79 MMA .m16n8k16 fragment layout for matrix A with `.f16` / `.bf16` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for ai where 0 <= i < 2 || 4 <= i < 6 +> groupID + 8 Otherwise +> +> col = (threadID_in_group * 2) + (i & 0x1) for ai where i < 4 +> (threadID_in_group * 2) + (i & 0x1) + 8 for ai where i >= 4 +> + + * `.f64` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression containing eight `.f64` registers, with each register containing one `.f64` element from the matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 +> +> The layout of the fragments held by different threads is shown in [Figure 80](<#mma-16816-a-f64>). +> +> ![_images/mma-16816-A-f64.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-A-f64.png) +> +> Figure 80 MMA .m16n8k16 fragment layout for matrix A with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for ai where i % 2 = 0 +> groupID + 8 Otherwise +> +> col = (i * 2) + threadID_in_group for ai where i % 2 = 0 +> (i * 2) - 2 + (threadID_in_group Otherwise +> + + * Multiplicand B: + + * `.f16` and `.bf16` : + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.f16` / `.bf16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` / `.bf16` elements from the matrix B. | b0, b1, b2, b3 +> +> The layout of the fragments held by different threads is shown in [Figure 81](<#mma-16816-b-f16>). +> +> ![_images/mma-16816-B-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-B-f16.png) +> +> Figure 81 MMA .m16n8k16 fragment layout for matrix B with `.f16` / `.bf16` type. +> +> where the row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = (threadID_in_group * 2) + (i & 0x1) for bi where i < 2 +> (threadID_in_group * 2) + (i & 0x1) + 8 for bi where i >= 2 +> +> col = groupID +> + + * `.f64` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.f64` | A vector expression containing four `.f64` registers, with each register containing one `.f64` element from the matrix B. | b0, b1, b2, b3 +> +> The layout of the fragments held by different threads is shown in [Figure 82](<#mma-16816-b-f64>). +> +> ![_images/sparse-mma-16816-tf32-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16816-tf32-B.png) +> +> Figure 82 MMA .m16n8k16 fragment layout for matrix B with `.f64` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = threadID_in_group + (i * 4) for bi where i < 4 +> +> col = groupID +> + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.f64` | A vector expression containing four `.f64` registers containing `.f64` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f32` | A vector expression containing four `.f32` registers containing four `.f32` elements from the matrix C (or D). +`.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix C (or D). + +The layout of the fragments held by different threads is shown in [Figure 83](<#mma-16816-c>). + +![_images/mma-16816-C-f16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-C-f16.png) + +Figure 83 MMA .m16n8k16 fragment layout for accumulator matrix matrix C/D. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} + +##### 9.7.14.5.9. [Matrix Fragments for `mma.m16n8k16` with integer type](<#warp-level-matrix-fragment-mma-16816-i8-f8>) + +A warp executing `mma.m16n8k16` will compute an MMA operation of shape `.m16n8k16`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.u8` / `.s8` | A vector expression containing two `.b32` registers, with each register containing four `.u8` / `.s8` elements from the matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 +`.e4m3` / `.e5m2` | A vector expression containing two `.b32` registers, with each register containing four `.e4m3` / `.e5m2` elements from the matrix A. | a0, a1, a2, a3, a4, a5, a6, a7 + +The layout of the fragments held by different threads is shown in [Figure 84](<#mma-16816-a-i8>). + +![_images/mma-16816-A-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-A-i8.png) + +Figure 84 MMA .m16n8k16 fragment layout for matrix A with `.u8` / `.s8` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where i < 4 + groupID + 8 for ai where i >= 4 + + col = (threadID_in_group * 4) + (i & 0x3) for ai where i = {0,..,7} + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.u8` / `.s8` | A vector expression containing a single `.b32` register, containing four `.u8` / `.s8` elements from the matrix B. | b0, b1, b2, b3 +`.e4m3` / `.e5m2` | A vector expression containing a single `.b32` register, containing four `.e4m3` / `.e5m2` elements from the matrix B. | b0, b1. b2. b3 + +The layout of the fragments held by different threads is shown in [Figure 85](<#mma-16816-b-i8>). + +![_images/mma-16816-B-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-B-i8.png) + +Figure 85 MMA .m16n8k16 fragment layout for matrix B with `.u8` / `.s8` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 4) + i for bi where i = {0,..,3} + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing four `.s32` registers, containing four `.s32` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f32` | A vector expression containing four `.f32` registers, containing four `.f32` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix C (or D). | c0, c1, c1, c2 + +The layout of the fragments held by different threads is shown in [Figure 86](<#mma-16816-c-i8>). + +![_images/mma-16816-C-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16816-C-i8.png) + +Figure 86 MMA .m16n8k16 fragment layout for accumulator matrix C/D with `.s32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} + +##### 9.7.14.5.10. [Matrix Fragments for `mma.m16n8k32`](<#warp-level-matrix-fragment-mma-16832>) + +A warp executing `mma.m16n8k32` will compute an MMA operation of shape `.m16n8k32`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + + * `.s4` or `.u4` : + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.s4` / `.u4` | A vector expression containing two `.b32` registers, with each register containing eight `.u4` / `.s4` elements from the matrix A. | a0, a1, …, a14, a15 +> +> The layout of the fragments held by different threads is shown in [Figure 87](<#mma-16832-a-i4>). +> +> ![_images/mma-16832-A-i4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-A-i4.png) +> +> Figure 87 MMA .m16n8k32 fragment layout for matrix A with `.u4` / `.s4` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for ai where i < 8 +> groupID + 8 for ai where i >= 8 +> +> col = (threadID_in_group * 8) + (i & 0x7) for ai where i = {0,..,15} +> + + * `.s8` or `.u8` or `.e4m3` or `.e5m2` or `.e3m2` or `.e2m3` or `.e2m1`: + +> .atype | Fragment | Elements (low to high) +> ---|---|--- +> `.s8` / `.u8` | A vector expression containing four `.b32` registers, with each register containing four `.s8` / `.u8` elements from the matrix A. | a0, a1, .., a14, a15 +> `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` | A vector expression containing four `.b32` registers, with each register containing four `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` elements from the matrix A. | a0, a1, …, a14, a15 +> +> The layout of the fragments held by different threads is shown in [Figure 88](<#mma-16832-a-i8>). +> +> ![_images/mma-16832-A-i8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-A-i8.png) +> +> Figure 88 MMA .m16n8k32 fragment layout for matrix A with `.u8` / `.s8` / `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = groupID for ai where 0 <= i < 4 || 8 <= i < 12 +> groupID + 8 otherwise +> +> col = (threadID_in_group * 4) + (i & 0x3) for ai where i < 8 +> (threadID_in_group * 4) + (i & 0x3) + 16 for ai where i >= 8 +> + + * Multiplicand B: + + * `.s4` or `.u4` : + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.s4` / `.u4` | A vector expression containing a single `.b32` register, containing eight `.s4` / `.u4` elements from the matrix B. | b0, b1, b2, b3, b4, b5, b6, b7 +> +> The layout of the fragments held by different threads is shown in [Figure 89](<#mma-16832-b-i4>). +> +> ![_images/mma-16832-B-i4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-B-i4.png) +> +> Figure 89 MMA .m16n8k32 fragment layout for matrix B with `.u4` / `.s4` type. +> +> The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 8) + (i & 0x7) for bi where i = {0,..,7} + col = groupID + + + * `.s8` or `.u8` or `.e4m3` or `.e5m2` or `.e3m2` or `.e2m3` or `.e2m1`: + +> .btype | Fragment | Elements (low to high) +> ---|---|--- +> `.s8` / `.u8` | A vector expression containing two `.b32` registers, with each register containing four `.s8` / `.u8` elements from the matrix B. | b0, b1, b2, b3, b4, b5, b6, b7 +> `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` | A vector expression containing two `.b32` registers, with each register containing four `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` elements from the matrix B. | b0, b1, b2, b3, b4, b5, b6, b7 +> +> The layout of the fragments held by different threads is shown in [Figure 90](<#mma-16832-b-i8-1>) and [Figure 91](<#mma-16832-b-i8-2>). +> +> ![_images/mma-16832-B-i8_1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-B-i8_1.png) +> +> Figure 90 MMA .m16n8k32 fragment layout for rows 0–15 of matrix B with `.u8` / `.s8` / `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` type. +> +> ![_images/mma-16832-B-i8_2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-B-i8_2.png) +> +> Figure 91 MMA .m16n8k32 fragment layout for rows 16–31 of matrix B with `.u8` / `.s8` / `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` type. +> +> The row and column of a matrix fragment can be computed as: +> +> groupID = %laneid >> 2 +> threadID_in_group = %laneid % 4 +> +> row = (threadID_in_group * 4) + (i & 0x3) for bi where i < 4 +> (threadID_in_group * 4) + (i & 0x3) + 16 for bi where i >= 4 +> +> col = groupID +> + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing four `.s32` registers, containing four `.s32` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f32` | A vector expression containing four `.f32` registers, containing four `.f32` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f16` | A vector expression containing two `.f16x2` registers, with each register containing two `.f16` elements from the matrix C (or D). | c0, c1, c2, c3 + +The layout of the fragments held by different threads is shown in [Figure 92](<#mma-16832-c>). + +![_images/mma-16832-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16832-C.png) + +Figure 92 MMA .m16n8k32 fragment layout for accumulator matrix C/D with `.s32` / `.f32` / `.f16` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} + +##### 9.7.14.5.11. [Matrix Fragments for `mma.m16n8k64`](<#warp-level-matrix-fragment-mma-16864>) + +A warp executing `mma.m16n8k64` will compute an MMA operation of shape `.m16n8k64`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.s4` / `.u4` | A vector expression containing four `.b32` registers, with each register containing eight `.s4` / `.u4` elements from the matrix A. | a0, a1, …, a30, a31 +`.e2m1` | A vector expression containing four `.b32` registers, with each register containing eight `.e2m1` elements from the matrix A. | a0, a1, …, a30, a31 + +The layout of the fragments held by different threads is shown in [Figure 93](<#mma-16864-a>). + +![_images/mma-16864-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16864-A.png) + +Figure 93 MMA .m16n8k64 fragment layout for matrix A with `.u4` / `.s4` / `.e2m1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 8 || 16 <= i < 24 + groupID + 8 otherwise + + col = (threadID_in_group * 8) + (i & 0x7) for ai where i < 16 + (threadID_in_group * 8) + (i & 0x7) + 32 for ai where i >= 16 + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.s4` / `.u4` | A vector expression containing two `.b32` registers, with each register containing eight `.s4` / `.u4` elements from the matrix B. | b0, b1, …, b14, b15 +`.e2m1` | A vector expression containing two `.b32` registers, with each register containing eight `.e2m1` elements from the matrix B. | b0, b1, …, b14, b15 + +The layout of the fragments held by different threads is shown in [Figure 94](<#mma-16864-b-1>) and [Figure 95](<#mma-16864-b-2>). + +![_images/mma-16864-B_1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16864-B_1.png) + +Figure 94 MMA .m16n8k64 fragment layout for rows 0–31 of matrix B with `.u4` / `.s4` / `.e2m1` type. + +![_images/mma-16864-B_2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16864-B_2.png) + +Figure 95 MMA .m16n8k64 fragment layout for rows 32–63 of matrix B with `.u4` / `.s4` / `.e2m1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 8) + (i & 0x7) for bi where i < 8 + (threadID_in_group * 8) + (i & 0x7) + 32 for bi where i >= 8 + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing four `.s32` registers, containing four `.s32` elements from the matrix C (or D). | c0, c1, c2, c3 +`.f32` | A vector expression containing four `.f32` registers, containing four `.f32` elements from the matrix C (or D). | c0, c1, c2, c3 + +The layout of the fragments held by different threads is shown in [Figure 96](<#mma-16864-c>). + +![_images/mma-16864-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-16864-C.png) + +Figure 96 MMA .m16n8k64 fragment layout for accumulator matrix C/D with `.s32` / `.f32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0,..,3} + +##### 9.7.14.5.12. [Matrix Fragments for `mma.m16n8k128`](<#warp-level-matrix-fragment-mma-168128>) + +A warp executing `mma.m16n8k128` will compute an MMA operation of shape `.m16n8k128`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing two `.b32` registers, with each register containing thirty two `.b1` elements from the matrix A. | a0, a1, …, a62, a63 + +The layout of the fragments held by different threads is shown in [Figure 97](<#mma-168128-a>). + +![_images/mma-168128-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168128-A.png) + +Figure 97 MMA .m16n8k128 fragment layout for matrix A with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where i < 32 + groupID + 8 for ai where i >= 32 + + col = (threadID_in_group * 32) + (i & 0x1F) for ai where i = {0, ...,63} + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing a single `.b32` register containing thirty two `.b1` elements from the matrix B. | b0, b1, … , b30, b31 + +The layout of the fragments held by different threads is shown in [Figure 98](<#mma-168128-b>). + +![_images/mma-168128-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168128-B.png) + +Figure 98 MMA .m16n8k128 fragment layout for matrix B with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 32) + i for bi where i = {0,...,31} + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing four `.s32` registers, containing four `.s32` elements from the matrix C (or D). | c0, c1, c2, c3 + +The layout of the fragments held by different threads is shown in [Figure 99](<#mma-168128-c>). + +![_images/mma-168128-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168128-C.png) + +Figure 99 MMA .m16n8k128 fragment layout for accumulator matrix C/D with `.s32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0, 1, 2, 3} + +##### 9.7.14.5.13. [Matrix Fragments for `mma.m16n8k256`](<#warp-level-matrix-fragment-mma-168256>) + +A warp executing `mma.m16n8k256` will compute an MMA operation of shape `.m16n8k256`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing four `.b32` registers, with each register containing thirty two `.b1` elements from the matrix A. | a0, a1, …, a126, a127 + +The layout of the fragments held by different threads is shown in [Figure 100](<#mma-168256-a>). + +![_images/mma-168256-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168256-A.png) + +Figure 100 MMA .m16n8k256 fragment layout for matrix A with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 32 || 64 <= i < 96 + groupID + 8 otherwise + + col = (threadID_in_group * 32) + i for ai where i < 64 + (threadID_in_group * 32) + (i & 0x1F) + 128 for ai where i >= 64 + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.b1` | A vector expression containing two `.b32` registers, with each register containing thirty two `.b1` elements from the matrix B. | b0, b1, …, b62, b63 + +The layout of the fragments held by different threads is shown in [Figure 101](<#mma-168256-b-1>) and [Figure 102](<#mma-168256-b-2>). + +![_images/mma-168256-B_1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168256-B_1.png) + +Figure 101 MMA .m16n8k256 fragment layout for rows 0–127 of matrix B with `.b1` type. + +![_images/mma-168256-B_2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168256-B_2.png) + +Figure 102 MMA .m16n8k256 fragment layout for rows 128–255 of matrix B with `.b1` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = (threadID_in_group * 32) + (i & 0x1F) for bi where i < 32 + (threadID_in_group * 32) + (i & 0x1F) + 128 for bi where i >= 32 + + col = groupID + + + * Accumulators (C or D): + +.ctype / .dtype | Fragment | Elements (low to high) +---|---|--- +`.s32` | A vector expression containing four `.s32` registers, containing four `.s32` elements from the matrix C (or D). | c0, c1, c2, c3 + +The layout of the fragments held by different threads is shown in [Figure 103](<#mma-168256-c>). + +![_images/mma-168256-C.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-168256-C.png) + +Figure 103 MMA .m16n8k256 fragment layout for accumulator matrix C/D with `.s32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ci where i < 2 + groupID + 8 for ci where i >= 2 + + col = (threadID_in_group * 2) + (i & 0x1) for ci where i = {0, 1, 2, 3} + +##### 9.7.14.5.14. [Multiply-and-Accumulate Instruction: `mma`](<#warp-level-matrix-instructions-mma>) + +`mma` + +Perform matrix multiply-and-accumulate operation + +Syntax + +Half precision floating point type: + + + mma.sync.aligned.m8n8k4.alayout.blayout.dtype.f16.f16.ctype d, a, b, c; + mma.sync.aligned.m16n8k8.row.col.dtype.f16.f16.ctype d, a, b, c; + mma.sync.aligned.m16n8k16.row.col.dtype.f16.f16.ctype d, a, b, c; + + .alayout = {.row, .col}; + .blayout = {.row, .col}; + .ctype = {.f16, .f32}; + .dtype = {.f16, .f32}; + + +Alternate floating point type: + + + mma.sync.aligned.m16n8k4.row.col.f32.tf32.tf32.f32 d, a, b, c; + mma.sync.aligned.m16n8k8.row.col.f32.atype.btype.f32 d, a, b, c; + mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 d, a, b, c; + mma.sync.aligned.shape.row.col.dtype.f8type.f8type.ctype d, a, b, c; + mma.sync.aligned.m16n8k32.row.col.kind.dtype.f8f6f4type.f8f6f4type.ctype d, a, b, c; + + .atype = {.bf16, .tf32}; + .btype = {.bf16, .tf32}; + .f8type = {.e4m3, .e5m2}; + .f8f6f4type = {.e4m3, .e5m2, .e3m2, .e2m3, .e2m1}; + .ctype = {.f16, .f32}; + .dtype = {.f16, .f32}; + .shape = {.m16n8k16, .m16n8k32}; + .kind = {.kind::f8f6f4}; + + +Alternate floating point type with block scaling: + + + mma.sync.aligned.m16n8k64.row.col.kind.block_scale{.scale_vec_size}.f32.e2m1.e2m1.f32.stype d, a, b, c, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .kind = {.kind::mxf4}; + .scale_vec_size = {.scale_vec::2X}; + .stype = {.ue8m0}; + + mma.sync.aligned.m16n8k64.row.col.kind.block_scale.scale_vec_size.f32.e2m1.e2m1.f32.stype d, a, b, c, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .kind = {.kind::mxf4nvf4}; + .scale_vec_size = {.scale_vec::2X, .scale_vec::4X}; + .stype = {.ue8m0, .ue4m3}; + + mma.sync.aligned.m16n8k32.row.col.kind.block_scale{.scale_vec_size}.f32.f8f6f4type.f8f6f4type.f32.stype d, a, b, c, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .kind = {.kind::mxf8f6f4}; + .scale_vec_size = {.scale_vec::1X}; + .f8f6f4type = {.e4m3, .e5m2, .e3m2, .e2m3, .e2m1}; + .stype = {.ue8m0}; + + +Double precision floating point type: + + + mma.sync.aligned.shape.row.col.f64.f64.f64.f64 d, a, b, c; + + .shape = {.m8n84, .m16n8k4, .m16n8k8, .m16n8k16}; + + +Integer type: + + + mma.sync.aligned.shape.row.col{.satfinite}.s32.atype.btype.s32 d, a, b, c; + + .shape = {.m8n8k16, .m16n8k16, .m16n8k32} + .atype = {.u8, .s8}; + .btype = {.u8, .s8}; + + mma.sync.aligned.shape.row.col{.satfinite}.s32.atype.btype.s32 d, a, b, c; + + .shape = {.m8n8k32, .m16n8k32, .m16n8k64} + .atype = {.u4, .s4}; + .btype = {.u4, .s4}; + + +Single bit: + + + mma.sync.aligned.shape.row.col.s32.b1.b1.s32.bitOp.popc d, a, b, c; + + .bitOp = {.xor, .and} + .shape = {.m8n8k128, .m16n8k128, .m16n8k256} + + +Description + +Perform a `MxNxK` matrix multiply and accumulate operation, `D = A*B+C`, where the A matrix is `MxK`, the B matrix is `KxN`, and the C and D matrices are `MxN`. + +Qualifier `.block_scale` specifies that the matrices A and B are scaled with `scale_A` and `scale_B` matrices respectively before performing the matrix multiply and accumulate operation as specified in the section [Block Scaling](<#warp-level-block-scaling>). The data type corresponding to each of the element within `scale_A` and `Scale_B` matrices is specified by `.stype`. Qualifier `.scale_vec_size` specifies the number of columns of `scale_A` matrix and number of rows in the matrix `scale_B`. + +The valid combinations of `.kind`, `.stype` and `.scale_vec_size` are described in [Table 36](<#mma-scaling-kind-type-valid-combination>). For `mma` with `.kind::mxf4` when the qualifier `.scale_vec_size` is not specified, then it defaults to `2X`. In contrast, when `.kind` is specified as `.kind::mxf8f6f4` then the qualifier `.scale_vec_size` defaults to `1X`. However, for `.kind::mxf4nvf4`, it is mandatory to provide valid `.scale_vec_size`. + +A warp executing `mma.sync.m8n8k4` instruction computes 4 matrix multiply and accumulate operations. Rest of the `mma.sync` operations compute a single matrix mutliply and accumulate operation per warp. + +For single-bit `mma.sync`, multiplication is replaced by a sequence of logical operations; specifically, `mma.xor.popc` and `mma.and.popc` computes the XOR, AND respectively of a k-bit row of A with a k-bit column of B, then counts the number of set bits in the result (`popc`). This result is added to the corresponding element of C and written into D. + +Operands `a` and `b` represent two multiplicand matrices A and B, while `c` and `d` represent the accumulator and destination matrices, distributed across the threads in warp. When `.block_scale` qualifier is specified, operand `scale-a-data`, `scale-b-data` represents the scale matrix metadata corresponding to `scale_A` and `scale_B` matrices respectively. The tuple `{byte-id-a, thread-id-a}` and `{byte-id-b, thread-id-b}` represent selectors for matrices `scale_A` and `scale_B` respectively from their corresponding metadata arguments `scale-a-data`, `scale-b-data`. The operands `scale-a-data`, `scale-b-data` are of type `.b32`. The operands `byte-id-a`, `thread-id-a`, `byte-id-b`, `thread-id-b` are unsigned 16-bit integer values. For more details on selector arguments refer [Block Scaling](<#warp-level-block-scaling>) section. + +The registers in each thread hold a fragment of matrix as described in [Matrix multiply-accumulate operation using mma instruction](<#warp-level-matrix-instructions-for-mma>). + +The qualifiers `.dtype`, `.atype`, `.btype` and `.ctype` indicate the data-type of the elements in the matrices D, A, B and C respectively. The qualifier `.stype` indicate the data-type of the elements in the matrices `scale_A` and `scale_B`. Specific shapes have type restrictions : + + * `.m8n8k4` : When `.ctype` is `.f32`, `.dtype` must also be `.f32`. + + * `.m16n8k8` : + + * `.dtype` must be the same as `.ctype`. + + * `.atype` must be the same as `.btype`. + + * `.m16n8k16` and `.m16n8k32` : + + * `.dtype` must be the same as `.ctype`. + + +The qualifiers `.alayout` and `.blayout` indicate the row-major or column-major layouts of matrices A and B respectively. + +When `.kind` is either of `.kind::mxf8f6f4` or `.kind::f8f6f4`, the individual 4-bit and the 6-bit floating point type elements must be packed in an 8-bit container. The matrix element of type `.e2m1` resides in central 4 bits of the 8-bit container with padding in the upper 2 bits and lower 2 bits of the container. When the matrix element is of type `.e3m2` or `.e2m3`, the matrix element resides in the lower 6 bits of the 8-bit container with padding in the upper 2 bits of the container. In contrast, note that when using `mma` with `.kind::mxf4` or `.kind::mxf4nvf4`, no explicit padding is necessary even though matrix elements are of type `.e2m1`. + +Precision and rounding : + + + * `.f16` floating point operations: + +Element-wise multiplication of matrix A and B is performed with at least single precision. When `.ctype` or `.dtype` is `.f32`, accumulation of the intermediate values is performed with at least single precision. When both `.ctype` and `.dtype` are specified as `.f16`, the accumulation is performed with at least half precision. + +The accumulation order, rounding and handling of subnormal inputs are unspecified. + + * `.e4m3`, `.e5m2`, `.e3m2`, `.e2m3`, `.e2m1` floating point operations : + +Element-wise multiplication of matrix A and B is performed with specified precision. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * `.bf16` and `.tf32` floating point operations : + +Element-wise multiplication of matrix A and B is performed with specified precision. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * `.f64` floating point operations : + +Precision of the element-wise multiplication and addition operation is identical to that of `.f64` precision fused multiply-add. Supported rounding modifiers are : + + * `.rn` : mantissa LSB rounds to nearest even. This is the default. + + * `.rz` : mantissa LSB rounds towards zero. + + * `.rm` : mantissa LSB rounds towards negative infinity. + + * `.rp` : mantissa LSB rounds towards positive infinity. + + * Integer operations : + +The integer `mma` operation is performed with `.s32` accumulators. The `.satfinite` qualifier indicates that on overflow, the accumulated value is limited to the range _MIN_INT32_.. _MAX_INT32_ (where the bounds are defined as the minimum negative signed 32-bit integer and the maximum positive signed 32-bit integer respectively). + +If `.satfinite` is not specified, the accumulated value is wrapped instead. + + +The mandatory `.sync` qualifier indicates that `mma` instruction causes the executing thread to wait until all threads in the warp execute the same `mma` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `mma` instruction. In conditionally executed code, a `mma` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + +The behavior of `mma` instruction is undefined if all threads in the same warp do not use the same qualifiers, or if any thread in the warp has exited. + +Notes + +Programs using double precision floating point `mma` instruction with shapes `.m16n8k4`, `.m16n8k8`, and `.m16n8k16` require at least 64 registers for compilation. + +PTX ISA Notes + +Introduced in PTX ISA version 6.4. + +`.f16` floating point type `mma` operation with `.m8n8k4` shape introduced in PTX ISA version 6.4. + +`.f16` floating point type `mma` operation with `.m16n8k8` shape introduced in PTX ISA version 6.5. + +`.u8/.s8` integer type `mma` operation with `.m8n8k16` shape introduced in PTX ISA version 6.5. + +`.u4/.s4` integer type `mma` operation with `.m8n8k32` shape introduced in PTX ISA version 6.5. + +`.f64` floating point type `mma` operation with `.m8n8k4` shape introduced in PTX ISA version 7.0. + +`.f16` floating point type `mma` operation with `.m16n8k16` shape introduced in PTX ISA version 7.0. + +`.bf16` alternate floating point type `mma` operation with `.m16n8k8` and `.m16n8k16` shapes introduced in PTX ISA version 7.0. + +`.tf32` alternate floating point type `mma` operation with `.m16n8k4` and `.m16n8k8` shapes introduced in PTX ISA version 7.0. + +`.u8/.s8` integer type `mma` operation with `.m16n8k16` and `.m16n8k32` shapes introduced in PTX ISA version 7.0. + +`.u4/.s4` integer type `mma` operation with `.m16n8k32` and `.m16n8k64` shapes introduced in PTX ISA version 7.0. + +`.b1` single-bit integer type `mma` operation with `.m8n8k128`, `.m16n8k128` and `.m16n8k256` shapes introduced in PTX ISA version 7.0. + +Support for `.and` operation in single-bit `mma` introduced in PTX ISA version 7.1. + +`.f64` floating point type `mma` operation with `.m16n8k4`, `.m16n8k8`, and `.m16n8k16` shapes introduced in PTX ISA version 7.8. + +Support for `.e4m3` and `.e5m2` alternate floating point type `mma` operation introduced in PTX ISA version 8.4. + +Support for shape `.m16n8k16` and `.f16` `dtype`/`ctype` with `.e4m3`/`.e5m2` alternate floating point type mma operation introduced in PTX ISA version 8.7. + +Support for `.e3m2`, `.e2m3`, `.e2m1` alternate floating point type `mma` operation introduced in PTX ISA version 8.7. + +Support for `.kind`, `.block_scale`, `.scale_vec_size` qualifier introduced in PTX ISA version 8.7. + +Support for `.scale_vec::4X` on `.ue8m0` as `.stype` with `.kind::mxf4nvf4` is introduced in PTX ISA version 9.1. + +Target ISA Notes + +Requires `sm_70` or higher. + +`.f16` floating point type `mma` operation with `.m8n8k4` shape requires `sm_70` or higher. + +Note + +`mma.sync.m8n8k4` is optimized for target architecture `sm_70` and may have substantially reduced performance on other target architectures. + +`.f16` floating point type `mma` operation with `.m16n8k8` shape requires `sm_75` or higher. + +`.u8/.s8` integer type `mma` operation with `.m8n8k16` shape requires `sm_75` or higher. + +`.u4/.s4` integer type `mma` operation with `.m8n8k32` shape `sm_75` or higher. + +`.b1` single-bit integer type `mma` operation with `.m8n8k128` shape `sm_75` or higher. + +`.f64` floating point type `mma` operation with `.m8n8k4` shape requires `sm_80` or higher. + +`.f16` floating point type `mma` operation with `.m16n8k16` shape requires `sm_80` or higher. + +`.bf16` alternate floating point type `mma` operation with `.m16n8k8` and `.m16n8k16` shapes requires `sm_80` or higher. + +`.tf32` alternate floating point type `mma` operation with `.m16n8k4` and `.m16n8k8` shapes requires `sm_80` or higher. + +`.u8/.s8` integer type `mma` operation with `.m16n8k16` and `.m16n8k32` shapes requires `sm_80` or higher. + +`.u4/.s4` integer type `mma` operation with `.m16n8k32` and `.m16n8k64` shapes requires `sm_80` or higher. + +`.b1` single-bit integer type `mma` operation with `.m16n8k128` and `.m16n8k256` shapes requires `sm_80` or higher. + +`.and` operation in single-bit `mma` requires `sm_80` or higher. + +`.f64` floating point type `mma` operation with `.m16n8k4`, `.m16n8k8`, and `.m16n8k16` shapes require `sm_90` or higher. + +`.e4m3` and `.e5m2` alternate floating point type `mma` operation requires `sm_89` or higher. + +`.e3m2`, `.e2m3` and `.e2m1` alternate floating point type `mma` operation requires `sm_120a` and is supported on `sm_120f` from PTX ISA version 8.8. + +Support for `.kind`, `.block_scale`, `.scale_vec_size` qualifier requires `sm_120a` and are supported on `sm_120f` or higher in the same family from PTX ISA version 8.8. + +Examples of half precision floating point type + + + // f16 elements in C and D matrix + .reg .f16x2 %Ra<2> %Rb<2> %Rc<4> %Rd<4> + mma.sync.aligned.m8n8k4.row.col.f16.f16.f16.f16 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + + // f16 elements in C and f32 elements in D + .reg .f16x2 %Ra<2> %Rb<2> %Rc<4> + .reg .f32 %Rd<8> + mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f16 + {%Rd0, %Rd1, %Rd2, %Rd3, %Rd4, %Rd5, %Rd6, %Rd7}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + // f32 elements in C and D + .reg .f16x2 %Ra<2>, %Rb<1>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .f16x2 %Ra<4>, %Rb<2>, %Rc<2>, %Rd<2>; + mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1}; + + .reg .f16 %Ra<4>, %Rb<2>; + .reg .f32 %Rc<2>, %Rd<2>; + mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + +Examples of alternate floating point type + + + .reg .b32 %Ra<2>, %Rb<1>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k4.row.col.f32.tf32.tf32.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .f16x2 %Ra<2>, %Rb<1>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k8.row.col.f32.bf16.bf16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<2>, %Rb<1>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Rb2, %Rb3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .f16x2 %Ra<2>, %Rb<1>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e5m2.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k16.row.col.f32.e5m2.e4m3.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .b32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.f16.e4m3.e5m2.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .b32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k16.row.col.f16.e5m2.e5m2.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.kind::f8f6f4.f32.e3m2.e2m3.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .b32 %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.kind::f8f6f4.f16.e2m3.e2m1.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1}; + + +Examples of integer type + + + .reg .b32 %Ra, %Rb, %Rc<2>, %Rd<2>; + + // s8 elements in A and u8 elements in B + mma.sync.aligned.m8n8k16.row.col.satfinite.s32.s8.u8.s32 + {%Rd0, %Rd1}, + {%Ra}, + {%Rb}, + {%Rc0, %Rc1}; + + // u4 elements in A and B matrix + mma.sync.aligned.m8n8k32.row.col.satfinite.s32.u4.u4.s32 + {%Rd0, %Rd1}, + {%Ra}, + {%Rb}, + {%Rc0, %Rc1}; + + // s8 elements in A and u8 elements in B + .reg .b32 %Ra<2>, %Rb, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k16.row.col.satfinite.s32.s8.u8.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + // u4 elements in A and s4 elements in B + .reg .b32 %Ra<2>, %Rb, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.satfinite.s32.u4.s4.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + // s8 elements in A and s8 elements in B + .reg .b32 %Ra<4>, %Rb<2>, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k32.row.col.satfinite.s32.s8.s8.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + // u8 elements in A and u8 elements in B + .reg .b32 %Ra<4>, %Rb<2>, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k64.row.col.satfinite.s32.u4.u4.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1 }, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + +Examples of single bit type + + + // b1 elements in A and B + .reg .b32 %Ra, %Rb, %Rc<2>, %Rd<2>; + mma.sync.aligned.m8n8k128.row.col.s32.b1.b1.s32.and.popc + {%Rd0, %Rd1}, + {%Ra}, + {%Rb}, + {%Rc0, %Rc1}; + + // b1 elements in A and B + .reg .b32 %Ra, %Rb, %Rc<2>, %Rd<2>; + mma.sync.aligned.m8n8k128.row.col.s32.b1.b1.s32.xor.popc + {%Rd0, %Rd1}, + {%Ra}, + {%Rb}, + {%Rc0, %Rc1}; + + .reg .b32 %Ra<2>, %Rb, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k128.row.col.s32.b1.b1.s32.xor.popc + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<2>, %Rb, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k128.row.col.s32.b1.b1.s32.and.popc + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<2>, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k256.row.col.s32.b1.b1.s32.xor.popc + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + .reg .b32 %Ra<4>, %Rb<2>, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k256.row.col.s32.b1.b1.s32.and.popc + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + +Examples of `.f64` floating point type + + + .reg .f64 %Ra, %Rb, %Rc<2>, %Rd<2>; + mma.sync.aligned.m8n8k4.row.col.f64.f64.f64.f64 + {%Rd0, %Rd1}, + {%Ra}, + {%Rb}, + {%Rc0, %Rc1}; + + .reg .f64 %Ra<8>, %Rb<4>, %Rc<4>, %Rd<4>; + mma.sync.aligned.m16n8k4.row.col.f64.f64.f64.f64.rn + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + mma.sync.aligned.m16n8k8.row.col.f64.f64.f64.f64.rn + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + mma.sync.aligned.m16n8k16.row.col.f64.f64.f64.f64.rn + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3, %Ra4, %Ra5, %Ra6, %Ra7}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}; + + +Examples of `mma` with block scale + + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + mma.sync.aligned.m16n8k64.row.col.kind::mxf4.block_scale.f32.e2m1.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + scaleAData, {2, 1}, scaleBData, {2, 3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .u16 bidA, bidB, tidA, tidB; + mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue4m3 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + scaleAData, {bidA, tidA}, scaleBData, {bidB, tidB}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .u16 bidA, bidB, tidA, tidB; + mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + scaleAData, {bidA, tidA}, scaleBData, {bidB, tidB}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + mma.sync.aligned.m16n8k32.row.col.kind::mxf8f6f4.block_scale.scale_vec::1X.f32.e3m2.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + scaleAData, {0, 1}, scaleBData, {0, 1}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + mma.sync.aligned.m16n8k32.row.col.kind::mxf8f6f4.block_scale.scale_vec::1X.f32.e4m3.e5m2.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + scaleAData, {0, 1}, scaleBData, {0, 0}; + +##### 9.7.14.5.15. [Warp-level matrix load instruction: `ldmatrix`](<#warp-level-matrix-instructions-ldmatrix>) + +`ldmatrix` + +Collectively load one or more matrices from shared memory for `mma` instruction + +Syntax + + + ldmatrix.sync.aligned.shape.num{.trans}{.ss}.type r, [p]; + + ldmatrix.sync.aligned.m8n16.num{.ss}.dst_fmt.src_fmt r, [p]; + ldmatrix.sync.aligned.m16n16.num.trans{.ss}.dst_fmt.src_fmt r, [p]; + + .shape = {.m8n8, .m16n16}; + .num = {.x1, .x2, .x4}; + .ss = {.shared{::cta}}; + .type = {.b16, .b8}; + .dst_fmt = { .b8x16 }; + .src_fmt = { .b6x16_p32, .b4x16_p64 }; + + +Description + +Collectively load one or more matrices across all threads in a warp from the location indicated by the address operand `p`, from `.shared` state space into destination register `r`. If no state space is provided, generic addressing is used, such that the address in `p` points into `.shared` space. If the generic address doesn’t fall in `.shared` state space, then the behavior is undefined. + +The `.shape` qualifier indicates the dimensions of the matrices being loaded. Each matrix element holds 16-bit or 8-bit or 6-bit or 4-bit data. + +Following table shows the matrix load case for each `.shape`. + +.shape | Matrix shape | Element size +---|---|--- +`.m8n8` | 8x8 | 16-bit +`.m16n16` | 16x16 | 8-bit or 6-bit or 4-bit +`.m8n16` | 8x16 | 6-bit or 4-bit + +Following table shows the valid use of 6-bit or 4-bit data load. + +.src_fmt | .shape | Source data | Padding | .dst_fmt +---|---|---|---|--- +`.b6x16_p32` | `.m8n16` | 16 6-bit elements | 32 bits | `.b8x16` (16 8-bit elements) +`.m16n16` +`.b4x16_p64` | `.m8n16` | 16 4-bit elements | 64 bits +`.m16n16` + +For `.b6x16_p32` format source data is 16 unsigned 6-bit elements with 32 bits padding. For `.b4x16_p64` format source data is 16 unsigned 4-bit elements with 64 bits padding. + +The values `.x1`, `.x2` and `.x4` for `.num` indicate one, two or four matrices respectively. When `.shape` is `.m16n16`, only `.x1` and `.x2` are valid values for `.num`. + +The mandatory `.sync` qualifier indicates that `ldmatrix` causes the executing thread to wait until all threads in the warp execute the same `ldmatrix` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `ldmatrix` instruction. In conditionally executed code, an `ldmatrix` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise the behavior is undefined. + +The behavior of `ldmatrix` is undefined if all threads do not use the same qualifiers, or if any thread in the warp has exited. + +The destination operand `r` is a brace-enclosed vector expression consisting of 1, 2, or 4 32-bit registers as per the value of `.num`. Each component of the vector expression holds a fragment from the corresponding matrix. + +Supported addressing modes for `p` are described in [Addresses as Operands](<#addresses-as-operands>). + +Consecutive instances of row need not be stored contiguously in memory. The eight addresses required for each matrix are provided by eight threads, depending upon the value of `.num` as shown in the following table. Each address corresponds to the start of a matrix row. Addresses addr0–addr7 correspond to the rows of the first matrix, addresses addr8–addr15 correspond to the rows of the second matrix, and so on. + +`.num` | Threads 0–7 | Threads 8–15 | Threads 16–23 | Threads 24–31 +---|---|---|---|--- +`.x1` | addr0–addr7 | – | – | – +`.x2` | addr0–addr7 | addr8–addr15 | – | – +`.x4` | addr0–addr7 | addr8–addr15 | addr16–addr23 | addr24–addr31 + +Note + +For .target `sm_75` or below, all threads must contain valid addresses. Otherwise, the behavior is undefined. For `.num = .x1` and `.num = .x2`, addresses contained in lower threads can be copied to higher threads to achieve the expected behavior. + +When reading 8x8 matrices, a group of four consecutive threads loads 16 bytes. The matrix addresses must be naturally aligned accordingly. + +Each thread in a warp loads fragments of a row, with thread 0 receiving the first fragment in its register `r`, and so on. A group of four threads loads an entire row of the matrix as shown in [Figure 104](<#mma-ldmatrix-fragments>). + +![_images/mma-ldmatrix-fragments.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-ldmatrix-fragments.png) + +Figure 104 ldmatrix fragment layout for one 8x8 Matrix with 16-bit elements + +When `.num` = `.x2`, the elements of the second matrix are loaded in the next destination register in each thread as per the layout in above table. Similarly, when `.num` = `.x4`, elements of the third and fourth matrices are loaded in the subsequent destination registers in each thread. + +For matrix shape 16x16, two destination registers `r0` and `r1` of type `.b32` must be specified and in each register four 8-bit elements are loaded. For 4-bit or 6-bit data, 8-bit element will have 4 bits or 2 bits of padding respectively. Refer [Optional Decompression](<#tcgen05-optional-decompression>) for more details on these formats. + +An entire row of the matrix can be loaded by a group of four consecutive and aligned threads. Each thread in a warp loads 4 consecutive columns across 2 rows as shown in the [Figure 105](<#mma-ldmatrix-fragments-1616>). + +![_images/mma-ldmatrix-fragments-1616.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-ldmatrix-fragments-1616.png) + +Figure 105 ldmatrix fragment layout for one 16x16 matrix with 8-bit elements + +For matrix shape 8x16, one destination register `r0` of type `.b32` must be specified where four 8-bit elements are loaded in the register. For 4-bit or 6-bit data, 8-bit element will have 4 bits or 2 bits of padding respectively. + +An entire row of the matrix can be loaded by a group of four consecutive and aligned threads. Each thread in a warp loads 4 consecutive columns as shown in [Figure 106](<#mma-ldmatrix-fragments-816>). + +![_images/mma-ldmatrix-fragments-816.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-ldmatrix-fragments-816.png) + +Figure 106 ldmatrix fragment layout for one 8x16 matrix with 8-bit elements containing 4-bit/6-bit data + +Optional qualifier `.trans` indicates that the matrix is loaded in column-major format. However, for 16x16 matrices, `.trans` is mandatory. + +The `ldmatrix` instruction is treated as a weak memory operation in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 6.5. + +Support for `::cta` sub-qualifier introduced in PTX ISA version 7.8. + +Support for `.m16n16`, `.m8n16` shapes introduced in PTX ISA version 8.6. + +Support for `.b8` type with `ldmatrix` is introduced in PTX ISA version 8.6. + +Support for `.src_fmt`, `.dst_fmt` qualifiers introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_75` or higher. + +Shapes `.m16n16`, `.m8n16` are supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And are supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) +> +> * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Type `.b8` with `ldmatrix` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And are supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) +> +> * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Qualifiers `.src_fmt`, `.dst_fmt` are supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And are supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) +> +> * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Examples + + + // Load a single 8x8 matrix using 64-bit addressing + .reg .b64 addr; + .reg .b32 d; + ldmatrix.sync.aligned.m8n8.x1.shared::cta.b16 {d}, [addr]; + + // Load two 8x8 matrices in column-major format + .reg .b64 addr; + .reg .b32 d<2>; + ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 {d0, d1}, [addr]; + + // Load four 8x8 matrices + .reg .b64 addr; + .reg .b32 d<4>; + ldmatrix.sync.aligned.m8n8.x4.b16 {d0, d1, d2, d3}, [addr]; + + // Load one 16x16 matrices of 64-bit elements and transpose them + .reg .b64 addr; + .reg .b32 d<2>; + ldmatrix.sync.aligned.m16n16.x1.trans.shared.b8 {d0, d1}, [addr]; + + // Load two 16x16 matrices of 64-bit elements and transpose them + .reg .b64 addr; + .reg .b32 d<4>; + ldmatrix.sync.aligned.m16n16.x2.trans.shared::cta.b8 {d0, d1, d2, d3}, [addr]; + + // Load two 16x16 matrices of 6-bit elements and transpose them + .reg .b64 addr; + .reg .b32 d<4>; + ldmatrix.sync.aligned.m16n16.x2.trans.shared::cta.b8x16.b6x16_p32 {d0, d1, d2, d3}, [addr]; + +##### 9.7.14.5.16. [Warp-level matrix store instruction: `stmatrix`](<#warp-level-matrix-instructions-stmatrix>) + +`stmatrix` + +Collectively store one or more matrices to shared memory. + +Syntax + + + stmatrix.sync.aligned.shape.num{.trans}{.ss}.type [p], r; + + .shape = {.m8n8, .m16n8}; + .num = {.x1, .x2, .x4}; + .ss = {.shared{::cta}}; + .type = {.b16, .b8}; + + +Description + +Collectively store one or more matrices across all threads in a warp to the location indicated by the address operand `p`, in `.shared` state space. If no state space is provided, generic addressing is used, such that the address in `p` points into `.shared` space. If the generic address doesn’t fall in `.shared` state space, then the behavior is undefined. + +The `.shape` qualifier indicates the dimensions of the matrices being loaded. Each matrix element holds 16-bit or 8-bit data as indicated by the `.type` qualifier. + +`.m16n8` shape is valid only for `.b8` type. + +The values `.x1`, `.x2` and `.x4` for `.num` indicate one, two or four matrices respectively. + +The mandatory `.sync` qualifier indicates that `stmatrix` causes the executing thread to wait until all threads in the warp execute the same `stmatrix` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `stmatrix` instruction. In conditionally executed code, an `stmatrix` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise the behavior is undefined. + +The behavior of `stmatrix` is undefined if all threads do not use the same qualifiers, or if any thread in the warp has exited. + +The source operand `r` is a brace-enclosed vector expression consisting of 1, 2, or 4 32-bit registers as per the value of `.num`. Each component of the vector expression holds a fragment from the corresponding matrix. + +Supported addressing modes for `p` are described in [Addresses as Operands](<#addresses-as-operands>). + +Consecutive instances of row need not be stored contiguously in memory. The eight addresses required for each matrix are provided by eight threads, depending upon the value of `.num` as shown in the following table. Each address corresponds to the start of a matrix row. Addresses addr0–addr7 correspond to the rows of the first matrix, addresses addr8–addr15 correspond to the rows of the second matrix, and so on. + +`.num` | Threads 0–7 | Threads 8–15 | Threads 16–23 | Threads 24–31 +---|---|---|---|--- +`.x1` | addr0–addr7 | – | – | – +`.x2` | addr0–addr7 | addr8–addr15 | – | – +`.x4` | addr0–addr7 | addr8–addr15 | addr16–addr23 | addr24–addr31 + +When storing 8x8 matrices, a group of four consecutive threads stores 16 bytes. The matrix addresses must be naturally aligned accordingly. + +Each thread in a warp stores fragments of a row, with thread 0 storing the first fragment from its register `r`, and so on. A group of four threads stores an entire row of the matrix as shown in [Figure 107](<#mma-stmatrix-fragments>). + +![_images/mma-stmatrix-fragments.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-stmatrix-fragments.png) + +Figure 107 stmatrix fragment layout for one 8x8 matrix with 16-bit elements + +When `.num` = `.x2`, the elements of the second matrix are storedd from the next source register in each thread as per the layout in above table. Similarly, when `.num` = `.x4`, elements of the third and fourth matrices are stored from the subsequent source registers in each thread. + +For 16x8 matrix shape, each of the 32 threads in the warp provides four elements of data per matrix. + +Each element in the source operand `r` is of type `.b32` and contains four 8 bit elements `e0`, `e1`, `e2`, `e3` with `e0` and `e3` containing the LSB and MSB respectively of register `r`. + +![_images/mma-stmatrix-fragments-168.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-stmatrix-fragments-168.png) + +Figure 108 stmatrix fragment layout for one 16x8 matrix with 8 bit elements + +Optional qualifier `.trans` indicates that the matrix is stored in column-major format. However, for 16x8 matrices, `.trans` is mandatory. + +The `stmatrix` instruction is treated as a weak memory operation in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Support for `.m16n8` shape is introduced in PTX ISA version 8.6. + +Support for `.b8` type with `stmatrix` is introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_90` or higher. + +Shape `.m16n8` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) +> +> * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Type `.b8` with `stmatrix` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) +> +> * `sm_120f` or higher in the same family + + * `sm_110f` or higher in the same family + + +Examples + + + // Store a single 8x8 matrix using 64-bit addressing + .reg .b64 addr; + .reg .b32 r; + stmatrix.sync.aligned.m8n8.x1.shared.b16 [addr], {r}; + + // Store two 8x8 matrices in column-major format + .reg .b64 addr; + .reg .b32 r<2>; + stmatrix.sync.aligned.m8n8.x2.trans.shared::cta.b16 [addr], {r0, r1}; + + // Store four 8x8 matrices + .reg .b64 addr; + .reg .b32 r<4>; + stmatrix.sync.aligned.m8n8.x4.b16 [addr], {r0, r1, r2, r3}; + + // Store a single 16x8 matrix using generic addressing + .reg .b64 addr; + .reg .b32 r; + stmatrix.sync.aligned.m16n8.x1.trans.shared.b8 [addr], {r}; + + // Store two 16x8 matrices + .reg .b64 addr; + .reg .b32 r<2>; + stmatrix.sync.aligned.m16n8.x2.trans.shared::cta.b8 [addr],{r0, r1}; + + // Store four 16x8 matrices + .reg .b64 addr; + .reg .b32 r<4>; + stmatrix.sync.aligned.m16n8.x4.b8 [addr], {r0, r1, r2, r3}; + +##### 9.7.14.5.17. [Warp-level matrix transpose instruction: `movmatrix`](<#warp-level-matrix-instructions-movmatrix>) + +`movmatrix` + +Transpose a matrix in registers across the warp. + +Syntax + + + movmatrix.sync.aligned.shape.trans.type d, a; + + .shape = {.m8n8}; + .type = {.b16}; + + +Description + +Move a row-major matrix across all threads in a warp, reading elements from source `a`, and writing the transposed elements to destination `d`. + +The `.shape` qualifier indicates the dimensions of the matrix being transposed. Each matrix element holds 16-bit data as indicated by the `.type` qualifier. + +The mandatory `.sync` qualifier indicates that `movmatrix` causes the executing thread to wait until all threads in the warp execute the same `movmatrix` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `movmatrix` instruction. In conditionally executed code, a `movmatrix` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise the behavior is undefined. + +Operands `a` and `d` are 32-bit registers containing fragments of the input matrix and the resulting matrix respectively. The mandatory qualifier `.trans` indicates that the resulting matrix in `d` is a transpose of the input matrix specified by `a`. + +Each thread in a warp holds a fragment of a row of the input matrix, with thread 0 holding the first fragment in register `a`, and so on. A group of four threads holds an entire row of the input matrix as shown in [Figure 109](<#mma-movmatrix-fragments-src>). + +![_images/mma-movmatrix-fragments-src.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-movmatrix-fragments-src.png) + +Figure 109 movmatrix source matrix fragment layout + +Each thread in a warp holds a fragment of a column of the result matrix, with thread 0 holding the first fragment in register `d`, and so on. A group of four threads holds an entire column of the result matrix as shown in [Figure 110](<#mma-movmatrix-fragments-dst>). + +![_images/mma-movmatrix-fragments-dst.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/mma-movmatrix-fragments-dst.png) + +Figure 110 movmatrix result matrix fragment layout + +PTX ISA Notes + +Introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_75` or higher. + +Examples + + + .reg .b32 d, a; + movmatrix.sync.aligned.m8n8.trans.b16 d, a; \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmaspinstruction-with-sparse-matrix-a/DOC.md b/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmaspinstruction-with-sparse-matrix-a/DOC.md new file mode 100644 index 00000000..aff2f814 --- /dev/null +++ b/content/cuda/docs/ptx-matrix-multiply-accumulate-operation-usingmmaspinstruction-with-sparse-matrix-a/DOC.md @@ -0,0 +1,930 @@ +--- +name: ptx-matrix-multiply-accumulate-operation-usingmmaspinstruction-with-sparse-matrix-a +description: This section describes warp-level `mma.sp{::ordered_metadata}` instruction + with sparse matrix A. This variant of the `mma` operation can be used when A is + a structured sparse matrix with 50% zeros in ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.14.6. Matrix multiply-accumulate operation usingmma.spinstruction with sparse matrix A + +--- +title: "9.7.14.6. Matrix multiply-accumulate operation usingmma.spinstruction with sparse matrix A" +section: 9.7.14.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.14.6. Matrix multiply-accumulate operation usingmma.spinstruction with sparse matrix A + + +This section describes warp-level `mma.sp{::ordered_metadata}` instruction with sparse matrix A. This variant of the `mma` operation can be used when A is a structured sparse matrix with 50% zeros in each row distributed in a shape-specific granularity. For an `MxNxK` sparse `mma.sp{::ordered_metadata}` operation, the `MxK` matrix A is packed into `MxK/2` elements. For each K-wide row of matrix A, 50% elements are zeros and the remaining K/2 non-zero elements are packed in the operand representing matrix A. The mapping of these K/2 elements to the corresponding K-wide row is provided explicitly as metadata. + +##### 9.7.14.6.1. [Sparse matrix storage](<#warp-level-sparse-matrix-storage>) + +Granularity of sparse matrix A is defined as the ratio of the number of non-zero elements in a sub-chunk of the matrix row to the total number of elements in that sub-chunk where the size of the sub-chunk is shape-specific. For example, in a `16x16` matrix A, sparsity is expected to be at 2:4 granularity, i.e. each 4-element vector (i.e. a sub-chunk of 4 consecutive elements) of a matrix row contains 2 zeros. Index of each non-zero element in a sub-chunk is stored in the metadata operand. Values `0b0000`, `0b0101`, `0b1010`, `0b1111` are invalid values for metadata and will result in undefined behavior. In a group of four consecutive threads, one or more threads store the metadata for the whole group depending upon the matrix shape. These threads are specified using an additional _sparsity selector_ operand. + +[Figure 111](<#sparse-mma-storage-example>) shows an example of a 16x16 matrix A represented in sparse format and sparsity selector indicating which thread in a group of four consecutive threads stores the metadata. + +![_images/sparse-mma-storage-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-storage-example.png) + +Figure 111 Sparse MMA storage example + +Granularities for different matrix shapes and data types are described below. + +Sparse `mma.sp{::ordered_metadata}` with half-precision and `.bf16` type + +For the `.m16n8k16` and `.m16n8k32` `mma.sp{::ordered_metadata}` operations, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A has two zeros and two non-zero elements. Only the two non-zero elements are stored in the operand representing matrix A and their positions in the four-wide chunk in matrix A are indicated by two 2-bit indices in the metadata operand. For `mma.sp::ordered_metadata`, `0b0100`, `0b1000`, `0b1001`, `0b1100`, `0b1101`, `0b1110` are the meaningful values of indices; any other values result in an undefined behavior. + +![_images/f16-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/f16-metadata-example.png) + +Figure 112 Sparse MMA metadata example for `.f16`/`.bf16` type. + +The sparsity selector indicates the threads which contribute metadata as listed below: + + * `m16n8k16`: One thread within a group of four consecutive threads contributes the metadata for the entire group. This thread is indicated by a value in {0, 1, 2, 3}. + + * `m16n8k32`: A thread-pair within a group of four consecutive threads contributes the sparsity metadata. Hence, the sparsity selector must be either 0 (threads T0, T1) or 1 (threads T2, T3); any other value results in an undefined behavior. + + +Sparse `mma.sp{::ordered_metadata}` with `.tf32` type + +When matrix A has `.tf32` elements, matrix A is structured sparse at a granularity of 1:2. In other words, each chunk of two adjacent elements in a row of matrix A has one zero and one non-zero element. Only the non-zero elements are stored in the operand for matrix A and their positions in a two-wide chunk in matrix A are indicated by the 4-bit index in the metadata. `0b1110` and `0b0100` are the only meaningful index values; any other values result in an undefined behavior. + +![_images/tf32-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tf32-metadata-example.png) + +Figure 113 Sparse MMA metadata example for `.tf32` type. + +The sparsity selector indicates the threads which contribute metadata as listed below: + + * `m16n8k8`: One thread within a group of four consecutive threads contributes the metadata for the entire group. This thread is indicated by a value in {0, 1, 2, 3}. + + * `m16n8k16`: A thread-pair within a group of four consecutive threads contributes the sparsity metadata. Hence, the sparsity selector must be either 0 (threads T0, T1) or 1 (threads T2, T3); any other value results in an undefined behavior. + + +Sparse `mma.sp{::ordered_metadata}` with integer type + +When matrices A and B have `.u8`/`.s8` elements, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A have two zeroes and two non-zero elements. Only the two non-zero elements are stored in sparse matrix and their positions in the four-wide chunk are indicated by two 2-bit indices in the metadata. For `mma.sp::ordered_metadata`, `0b0100`, `0b1000`, `0b1001`, `0b1100`, `0b1101`, `0b1110` are the meaningful values of indices; any other values result in an undefined behavior. + +![_images/u8s8-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/u8s8-metadata-example.png) + +Figure 114 Sparse MMA metadata example for `.u8`/`.s8` type. + +when matrices A and B have `.u4`/`.s4` elements, matrix A is pair-wise structured sparse at a granularity of 4:8. In other words, each chunk of eight adjacent elements in a row of matrix A has four zeroes and four non-zero values. Further, the zero and non-zero values are clustered in sub-chunks of two elements each within the eight-wide chunk. i.e., each two-wide sub-chunk within the eight-wide chunk must be all zeroes or all non-zeros. Only the four non-zero values are stored in sparse matrix and the positions of the two two-wide sub-chunks with non-zero values in the eight-wide chunk of a row of matrix A are indicated by two 2-bit indices in the metadata. For `mma.sp::ordered_metadata`, `0b0100`, `0b1000`, `0b1001`, `0b1100`, `0b1101`, `0b1110` are the meaningful values of indices; any other values result in an undefined behavior. + +![_images/u4s4-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/u4s4-metadata-example.png) + +Figure 115 Sparse MMA metadata example for `.u4`/`.s4` type. + +The sparsity selector indicates the threads which contribute metadata as listed below: + + * `m16n8k32` with `.u8`/`.s8` type and `m16n8k64` with `.u4`/`.s4` type: A thread-pair within a group of four consecutive threads contributes the sparsity metadata. Hence, the sparsity selector must be either 0 (threads T0, T1) or 1 (threads T2, T3); any other value results in an undefined behavior. + + * `m16n8k64` with `.u8`/`.s8` type and `m16n8k128` with `.u4`/`.s4` type: All threads within a group of four consecutive threads contribute the sparsity metadata. Hence, the sparsity selector in this case must be 0. Any other value of sparsity selector results in an undefined behavior. + + +Sparse `mma.sp{::ordered_metadata}` operating on `.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type with `.kind::f8f6f4` or `.kind::mxf8f6f4` + +When matrices A and B have `.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` elements, matrix A is structured sparse at a granularity of 2:4. In other words, each chunk of four adjacent elements in a row of matrix A have two zeroes and two non-zero elements. Only the two non-zero elements are stored in sparse matrix and their positions in the four-wide chunk are indicated by two 2-bit indices in the metadata. `0b0100`, `0b1000`, `0b1001`, `0b1100`, `0b1101`, `0b1110` are the meaningful values of indices; any other values result in an undefined behavior. + +![_images/fp8-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/fp8-metadata-example.png) + +Figure 116 Sparse MMA metadata example for `.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + +The sparsity selector indicates the threads which contribute metadata as listed below: + + * `m16n8k64`: All threads within a group of four consecutive threads contribute the sparsity metadata. Hence, the sparsity selector in this case must be 0. Any other value of sparsity selector results in an undefined behavior. + + +Sparse `mma.sp::ordered_metadata` operating on `.e2m1` type with `.kind::mxf4` or `.kind::mxf4nvf4` + +When matrices A and B have `.e2m1` elements, matrix A is pair-wise structured sparse at a granularity of 4:8. In other words, each chunk of eight adjacent elements in a row of matrix A has four zeroes and four non-zero values. Further, the zero and non-zero values are clustered in sub-chunks of two elements each within the eight-wide chunk. i.e., each two-wide sub-chunk within the eight-wide chunk must be all zeroes or all non-zeros. Only the four non-zero values are stored in sparse matrix and the positions of the two two-wide sub-chunks with non-zero values in the eight-wide chunk of a row of matrix A are indicated by two 2-bit indices in the metadata. `0b0100`, `0b1000`, `0b1001`, `0b1100`, `0b1101`, `0b1110` are the meaningful values of indices; any other values result in an undefined behavior. + +![_images/fp4-metadata-example.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/fp4-metadata-example.png) + +Figure 117 Sparse MMA metadata example for `.e2m1` type with `.kind::mxf4` or `.kind::mxf4nvf4` + +The sparsity selector indicates the threads which contribute metadata as listed below: + + * `m16n8k128`: All threads within a group of four consecutive threads contribute the sparsity metadata. Hence, the sparsity selector in this case must be 0. Any other value of sparsity selector results in an undefined behavior. + +##### 9.7.14.6.2. [Matrix fragments for multiply-accumulate operation with sparse matrix A](<#warp-level-matrix-fragments-for-sparse-mma>) + +In this section we describe how the contents of thread registers are associated with fragments of various matrices and the sparsity metadata. The following conventions are used throughout this section: + + * For matrix A, only the layout of a fragment is described in terms of register vector sizes and their association with the matrix data. + + * For matrix B, when the combination of matrix dimension and the supported data type is not already covered in [Matrix multiply-accumulate operation using mma instruction](<#warp-level-matrix-instructions-for-mma>), a pictorial representation of matrix fragments is provided. + + * For matrices C and D, since the matrix dimension - data type combination is the same for all supported shapes, and is already covered in [Matrix multiply-accumulate operation using mma instruction](<#warp-level-matrix-instructions-for-mma>), the pictorial representations of matrix fragments are not included in this section. + + * For the metadata operand, pictorial representations of the association between indices of the elements of matrix A and the contents of the metadata operand are included. `Tk: [m..n]` present in cell `[x][y..z]` indicates that bits `m` through `n` (with `m` being higher) in the metadata operand of thread with `%laneid=k` contains the indices of the non-zero elements from the chunk `[x][y]..[x][z]` of matrix A. + + +###### 9.7.14.6.2.1. [Matrix Fragments for sparse `mma.m16n8k16` with `.f16` and `.bf16` types](<#warp-level-matrix-fragment-sparse-mma-16816-f16bf16>) + +A warp executing sparse `mma.m16n8k16` with `.f16` / `.bf16` floating point type will compute an MMA operation of shape `.m16n8k16`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.f16` / `.bf16` | A vector expression containing two `.b32` registers, with each register containing two non-zero `.f16` / `.bf16` elements out of 4 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 118](<#sparse-mma-16816-f16-bf16-a>). + +![_images/sparse-mma-16816-f16-bf16-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16816-f16-bf16-A.png) + +Figure 118 Sparse MMA .m16n8k16 fragment layout for matrix A with `.f16`/`.bf16` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for a0 and a1 + groupID + 8 for a2 and a3 + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 4 + lastcol = firstcol + 3 + + + * Matrix fragments for multiplicand B and accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k16 with floating point type](<#warp-level-matrix-fragment-mma-16816-float>) for `.f16`/`.b16` formats. + + * Metadata: A `.b32` register containing 16 2-bit vectors each storing the index of a non-zero element of a 4-wide chunk of matrix A as shown in [Figure 119](<#sparse-mma-metadata-16816-f16bf16>). + +> ![_images/sparse-mma-metadata-16816-f16bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16816-f16bf16.png) +> +> Figure 119 Sparse MMA .m16n8k16 metadata layout for `.f16`/`.bf16` type. + + +###### 9.7.14.6.2.2. [Matrix Fragments for sparse `mma.m16n8k32` with `.f16` and `.bf16` types](<#warp-level-matrix-fragment-sparse-mma-16832-f16bf16>) + +A warp executing sparse `mma.m16n8k32` with `.f16` / `.bf16` floating point type will compute an MMA operation of shape `.m16n8k32`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.f16` / `.bf16` | A vector expression containing four `.b32` registers, with each register containing two non-zero `.f16` / `.bf16` elements out of 4 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 120](<#sparse-mma-16832-f16-bf16-a>). + +![_images/sparse-mma-16832-f16-bf16-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16832-f16-bf16-A.png) + +Figure 120 Sparse MMA .m16n8k32 fragment layout for matrix A with `.f16`/`.bf16` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 2 || 4 <= i < 6 + groupID + 8 Otherwise + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 4 For ai where i < 4 + (threadID_in_group * 4) + 16 for ai where i >= 4 + lastcol = firstcol + 3 + + + * Multiplicand B: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.f16` / `.bf16` | A vector expression containing four `.b32` registers, each containing two `.f16` / `.bf16` elements from matrix B. | b0, b1, b2, b3 + +The layout of the fragments held by different threads is shown in [Figure 121](<#sparse-mma-16832-f16bf16-b>). + +![_images/sparse-mma-16832-f16bf16-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16832-f16bf16-B.png) + +Figure 121 Sparse MMA .m16n8k32 fragment layout for matrix B with `.f16`/`.bf16` type. + + * Matrix fragments for accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k16 with floating point type](<#warp-level-matrix-fragment-mma-16816-float>) for `.f16`/`.b16` formats. + + * Metadata: A `.b32` register containing 16 2-bit vectors with each pair of 2-bit vectors storing the indices of two non-zero element from a 4-wide chunk of matrix A as shown in [Figure 122](<#sparse-mma-metadata-16832-f16bf16>). + +> ![_images/sparse-mma-metadata-16832-f16bf16.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16832-f16bf16.png) +> +> Figure 122 Sparse MMA .m16n8k32 metadata layout for `.f16`/`.bf16` type. + + +###### 9.7.14.6.2.3. [Matrix Fragments for sparse `mma.m16n8k16` with `.tf32` floating point type](<#warp-level-matrix-fragment-sparse-mma-16816-tf32>) + +A warp executing sparse `mma.m16n8k16` with `.tf32` floating point type will compute an MMA operation of shape `.m16n8k16`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.tf32` | A vector expression containing four `.b32` registers, with each register containing one non-zero `.tf32` element out of 2 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 123](<#sparse-mma-16816-tf32-a>). + +![_images/sparse-mma-16816-tf32-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16816-tf32-A.png) + +Figure 123 Sparse MMA .m16n8k16 fragment layout for matrix A with `.tf32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for a0 and a2 + groupID + 8 for a1 and a3 + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 2 for a0 and a1 + (threadID_in_group * 2) + 8 for a2 and a3 + lastcol = firstcol + 1 + + + * Multiplicand B: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.tf32` | A vector expression containing four `.b32` registers, each containing four `.tf32` elements from matrix B. | b0, b1, b2, b3 + +The layout of the fragments held by different threads is shown in [Figure 124](<#sparse-mma-16816-tf32-b>). + +![_images/sparse-mma-16816-tf32-B.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16816-tf32-B.png) + +Figure 124 Sparse MMA .m16n8k16 fragment layout for matrix B with `.tf32` type. + + * Matrix fragments for accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k16 with floating point type](<#warp-level-matrix-fragment-mma-16816-float>). + + * Metadata: A `.b32` register containing 8 4-bit vectors each storing the index of a non-zero element of a 2-wide chunk of matrix A as shown in [Figure 125](<#sparse-mma-metadata-16816-tf32>). + +> ![_images/sparse-mma-metadata-16816-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16816-tf32.png) +> +> Figure 125 Sparse MMA .m16n8k16 metadata layout for `.tf32` type. + + +###### 9.7.14.6.2.4. [Matrix Fragments for sparse `mma.m16n8k8` with `.tf32` floating point type](<#warp-level-matrix-fragment-sparse-mma-1688-tf32>) + +A warp executing sparse `mma.m16n8k8` with `.tf32` floating point type will compute an MMA operation of shape `.m16n8k8`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.tf32` | A vector expression containing two `.b32` registers, each containing one non-zero `.tf32` element out of 2 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 126](<#sparse-mma-1688-tf32>). + +![_images/sparse-mma-1688-tf32-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-1688-tf32-A.png) + +Figure 126 Sparse MMA .m16n8k8 fragment layout for matrix A with `.tf32` type. + +The row and column of a matrix fragment can be computed as: + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for a0 + groupID + 8 for a1 + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 2 + lastcol = firstcol + 1 + + + * Matrix fragments for multiplicand B and accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k8](<#warp-level-matrix-fragment-mma-1688>) for `.tf32` format. + + * Metadata: A `.b32` register containing 8 4-bit vectors each storing the index of a non-zero element of a 2-wide chunk of matrix A as shown in [Figure 127](<#sparse-mma-metadata-1688-tf32>). + +> ![_images/sparse-mma-metadata-1688-tf32.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-1688-tf32.png) +> +> Figure 127 Sparse MMA .m16n8k8 metadata layout for `.tf32` type. + + +###### 9.7.14.6.2.5. [Matrix Fragments for sparse `mma.m16n8k32` with `.u8` / `.s8` integer type](<#warp-level-matrix-fragment-sparse-mma-16832-u8s8>) + +A warp executing sparse `mma.m16n8k32` with `.u8` / `.s8` integer type will compute an MMA operation of shape `.m16n8k32`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.u8` / `.s8` | A vector expression containing two `.b32` registers, with each register containing four non-zero `.u8` / `.s8` elements out of 8 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 128](<#sparse-mma-16832-u8s8-a>). + +![_images/sparse-mma-16832-u8s8-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16832-u8s8-A.png) + +Figure 128 Sparse MMA .m16n8k32 fragment layout for matrix A with `.u8`/`.s8` type. + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 4 + groupID + 8 Otherwise + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 8 + lastcol = firstcol + 7 + + + * Matrix fragments for multiplicand B and accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k32](<#warp-level-matrix-fragment-mma-16832>). + + * Metadata: A `.b32` register containing 16 2-bit vectors with each pair of 2-bit vectors storing the indices of two non-zero elements from a 4-wide chunk of matrix A as shown in [Figure 129](<#sparse-mma-metadata-16832-u8s8>). + +> ![_images/sparse-mma-metadata-16832-u8s8.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16832-u8s8.png) +> +> Figure 129 Sparse MMA .m16n8k32 metadata layout for `.u8`/`.s8` type. + + +###### 9.7.14.6.2.6. [Matrix Fragments for sparse `mma.m16n8k64` with `.u8` / `.s8` / `.e4m3` / `.e5m2` type](<#warp-level-matrix-fragment-sparse-mma-16864-u8s8-fp8>) + +A warp executing sparse `mma.m16n8k64` with `.u8` / `.s8`/ `.e4m3`/ `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` type will compute an MMA operation of shape `.m16n8k64`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.u8` / `.s8` | A vector expression containing four `.b32` registers, with each register containing four non-zero `.u8` / `.s8` elements out of 8 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). +`.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` | A vector expression containing four `.b32` registers, with each register containing four non-zero `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` elements out of 8 consecutive elements from matrix A. + +The layout of the fragments held by different threads is shown in [Figure 130](<#sparse-mma-16864-u8s8-a-first32col>) and [Figure 131](<#sparse-mma-16864-u8s8-a-last32col>). + +![_images/sparse-mma-16864-u8s8-A-first32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-A-first32col.png) + +Figure 130 Sparse MMA .m16n8k64 fragment layout for columns 0–31 of matrix A with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + +![_images/sparse-mma-16864-u8s8-A-last32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-A-last32col.png) + +Figure 131 Sparse MMA .m16n8k64 fragment layout for columns 32–63 of matrix A with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 4 || 8 <= i < 12 + groupID + 8 Otherwise + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 8 For ai where i < 8 + (threadID_in_group * 8) + 32 For ai where i >= 8 + lastcol = firstcol + 7 + + + * Multiplicand B: + +.btype | Fragment | Elements (low to high) +---|---|--- +`.u8` / `.s8` | A vector expression containing four `.b32` registers, each containing four `.u8` / `.s8` elements from matrix B. | b0, b1, b2, b3, …, b15 +`.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` | A vector expression containing four `.b32` registers, each containing four `.e4m3` / `.e5m2` / `.e3m2` / `.e2m3` / `.e2m1` elements from matrix B. + +The layout of the fragments held by different threads is shown in [Figure 132](<#sparse-mma-16864-u8s8-b1>), [Figure 133](<#sparse-mma-16864-u8s8-b2>), [Figure 134](<#sparse-mma-16864-u8s8-b3>) and [Figure 135](<#sparse-mma-16864-u8s8-b4>). + +![_images/sparse-mma-16864-u8s8-B1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-B1.png) + +Figure 132 Sparse MMA .m16n8k64 fragment layout for rows 0–15 of matrix B with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + +![_images/sparse-mma-16864-u8s8-B2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-B2.png) + +Figure 133 Sparse MMA .m16n8k64 fragment layout for rows 16–31 of matrix B with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + +![_images/sparse-mma-16864-u8s8-B3.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-B3.png) + +Figure 134 Sparse MMA .m16n8k64 fragment layout for rows 32–47 of matrix B with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + +![_images/sparse-mma-16864-u8s8-B4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u8s8-B4.png) + +Figure 135 Sparse MMA .m16n8k64 fragment layout for rows 48–63 of matrix B with `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + + * Matrix fragments for accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k16 with integer type](<#warp-level-matrix-fragment-mma-16816-i8-f8>). + + * Metadata: A `.b32` register containing 16 2-bit vectors with each pair of 2-bit vectors storing the indices of two non-zero elements from a 4-wide chunk of matrix A as shown in [Figure 136](<#sparse-mma-metadata-16864-u8s8-first32col>) and [Figure 137](<#sparse-mma-metadata-16864-u8s8-last32col>). + +> ![_images/sparse-mma-metadata-16864-u8s8-first32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16864-u8s8-first32col.png) +> +> Figure 136 Sparse MMA .m16n8k64 metadata layout for columns 0–31 for `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. +> +> ![_images/sparse-mma-metadata-16864-u8s8-last32col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16864-u8s8-last32col.png) +> +> Figure 137 Sparse MMA .m16n8k64 metadata layout for columns 32–63 for `.u8`/`.s8`/`.e4m3`/`.e5m2`/`.e3m2`/`.e2m3`/`.e2m1` type. + + +###### 9.7.14.6.2.7. [Matrix Fragments for sparse `mma.m16n8k64` with `.u4` / `.s4` integer type](<#warp-level-matrix-fragment-sparse-mma-16864-u4s4>) + +A warp executing sparse `mma.m16n8k64` with `.u4` / `.s4` integer type will compute an MMA operation of shape `.m16n8k64`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.u4` / `.s4` | A vector expression containing two `.b32` registers, with each register containing eight non-zero `.u4` / `.s4` elements out of 16 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). + +The layout of the fragments held by different threads is shown in [Figure 138](<#sparse-mma-16864-u4s4-a>). + +![_images/sparse-mma-16864-u4s4-A.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-16864-u4s4-A.png) + +Figure 138 Sparse MMA .m16n8k64 fragment layout for matrix A with `.u4`/`.s4` type. + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 8 + groupID + 8 Otherwise + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 16 + lastcol = firstcol + 15 + + + * Matrix fragments for multiplicand B and accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k64](<#warp-level-matrix-fragment-mma-16864>). + + * Metadata: A `.b32` register containing 16 2-bit vectors with each pair of 2-bit vectors storing the indices of four non-zero elements from a 8-wide chunk of matrix A as shown in [Figure 139](<#sparse-mma-metadata-16864-u4s4>). + +> ![_images/sparse-mma-metadata-16864-u4s4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-16864-u4s4.png) +> +> Figure 139 Sparse MMA .m16n8k64 metadata layout for `.u4`/`.s4` type. + + +###### 9.7.14.6.2.8. [Matrix Fragments for sparse `mma.m16n8k128` with `.u4` / `.s4` integer type](<#warp-level-matrix-fragment-sparse-mma-168128-u4s4>) + +A warp executing sparse `mma.m16n8k128` with `.u4` / `.s4` / `.e2m1` integer type will compute an MMA operation of shape `.m16n8k128`. + +Elements of the matrix are distributed across the threads in a warp so each thread of the warp holds a fragment of the matrix. + + * Multiplicand A: + +.atype | Fragment | Elements +---|---|--- +`.u4` / `.s4` | A vector expression containing four `.b32` registers, with each register containing eight non-zero `.u4` / `.s4` elements out of 16 consecutive elements from matrix A. | Mapping of the non-zero elements is as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>). +`.e2m1` | A vector expression containing four `.b32` registers, with each register containing eight non-zero `.e2m1` elements out of 16 consecutive elements from matrix A. + +The layout of the fragments held by different threads is shown in [Figure 140](<#sparse-mma-168128-u4s4-a-first64col>) and [Figure 141](<#sparse-mma-168128-u4s4-a-last64col>). + +![_images/sparse-mma-168128-u4s4-A-first64col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-A-first64col.png) + +Figure 140 Sparse MMA .m16n8k128 fragment layout for columns 0–63 of matrix A with `.u4`/`.s4`/`.e2m1` type. + +![_images/sparse-mma-168128-u4s4-A-last64col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-A-last64col.png) + +Figure 141 Sparse MMA .m16n8k128 fragment layout for columns 64–127 of matrix A with `.u4`/`.s4`/`.e2m1` type. + + groupID = %laneid >> 2 + threadID_in_group = %laneid % 4 + + row = groupID for ai where 0 <= i < 8 || 16 <= i < 24 + groupID + 8 Otherwise + + col = [firstcol ... lastcol] // As per the mapping of non-zero elements + // as described in Sparse matrix storage + + Where + firstcol = threadID_in_group * 16 For ai where i < 16 + (threadID_in_group * 16) + 64 For ai where i >= 16 + lastcol = firstcol + 15 + + + * Multiplicand B: + +.atype | Fragment | Elements (low to high) +---|---|--- +`.u4` / `.s4` | A vector expression containing four `.b32` registers, each containing eight `.u4` / `.s4` elements from matrix B. | b0, b1, b2, b3, …, b31 +`.e2m1` | A vector expression containing four `.b32` registers, each containing eight `.e2m1` elements from matrix B. + +The layout of the fragments held by different threads is shown in [Figure 142](<#sparse-mma-168128-u4s4-b1>), [Figure 143](<#sparse-mma-168128-u4s4-b2>), [Figure 144](<#sparse-mma-168128-u4s4-b3>), [Figure 145](<#sparse-mma-168128-u4s4-b4>). + +![_images/sparse-mma-168128-u4s4-B1.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-B1.png) + +Figure 142 Sparse MMA .m16n8k128 fragment layout for rows 0–31 of matrix B with `.u4`/`.s4`/`.e2m1` type. + +![_images/sparse-mma-168128-u4s4-B2.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-B2.png) + +Figure 143 Sparse MMA .m16n8k128 fragment layout for rows 32–63 of matrix B with `.u4`/`.s4`/`.e2m1` type. + +![_images/sparse-mma-168128-u4s4-B3.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-B3.png) + +Figure 144 Sparse MMA .m16n8k128 fragment layout for rows 64–95 of matrix B with `.u4`/`.s4`/`.e2m1` type. + +![_images/sparse-mma-168128-u4s4-B4.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-168128-u4s4-B4.png) + +Figure 145 Sparse MMA .m16n8k128 fragment layout for rows 96–127 of matrix B with `.u4`/`.s4`/`.e2m1` type. + + * Matrix fragments for accumulators C and D are the same as in case of [Matrix Fragments for mma.m16n8k64](<#warp-level-matrix-fragment-mma-16864>). + + * Metadata: A `.b32` register containing 16 2-bit vectors with each pair of 2-bit vectors storing the indices of four non-zero elements from a 8-wide chunk of matrix A as shown in [Figure 146](<#sparse-mma-metadata-168128-u4s4-first64col>) and [Figure 147](<#sparse-mma-metadata-168128-u4s4-last64col>). + +> ![_images/sparse-mma-metadata-168128-u4s4-first64col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-168128-u4s4-first64col.png) +> +> Figure 146 Sparse MMA .m16n8k128 metadata layout for columns 0–63 for `.u4`/`.s4`/`.e2m1` type. +> +> ![_images/sparse-mma-metadata-168128-u4s4-last64col.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/sparse-mma-metadata-168128-u4s4-last64col.png) +> +> Figure 147 Sparse MMA .m16n8k128 metadata layout for columns 64–127 for `.u4`/`.s4`/`.e2m1` type. + +##### 9.7.14.6.3. [Multiply-and-Accumulate Instruction: `mma.sp` / `mma.sp::ordered_metadata`](<#warp-level-matrix-instructions-sparse-mma>) + +`mma.sp`, `mma.sp::ordered_metadata` + +Perform matrix multiply-and-accumulate operation with sparse matrix A + +Syntax + +Half precision floating point type: + + + mma.spvariant.sync.aligned.m16n8k16.row.col.dtype.f16.f16.ctype d, a, b, c, e, f; + mma.spvariant.sync.aligned.m16n8k32.row.col.dtype.f16.f16.ctype d, a, b, c, e, f; + + .ctype = {.f16, .f32}; + .dtype = {.f16, .f32}; + .spvariant = {.sp, .sp::ordered_metadata}; + + +Alternate floating point type: + + + mma.spvariant.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 d, a, b, c, e, f; + mma.spvariant.sync.aligned.m16n8k32.row.col.f32.bf16.bf16.f32 d, a, b, c, e, f; + mma.spvariant.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 d, a, b, c, e, f; + mma.spvariant.sync.aligned.m16n8k16.row.col.f32.tf32.tf32.f32 d, a, b, c, e, f; + mma.spvariant.sync.aligned.m16n8k64.row.col.f32.f8type.f8type.f32 d, a, b, c, e, f; + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.kind.dtype.f8f6f4type.f8f6f4type.ctype d, a, b, c, e, f; + + .f8type = {.e4m3, .e5m2}; + .spvariant = {.sp, .sp::ordered_metadata}; + .f8f6f4type = {.e4m3, .e5m2, .e3m2, .e2m3, .e2m1}; + .kind = {kind::f8f6f4}; + .ctype = {.f16, .f32}; + .dtype = {.f16, .f32}; + + +Alternate floating point type with block scaling: + + + mma.spvariant.sync.aligned.m16n8k128.row.col.kind.block_scale{.scale_vec_size}.f32.e2m1.e2m1.f32.stype d, a, b, c, e, f, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .spvariant = {.sp::ordered_metadata}; + .kind = {.kind::mxf4}; + .scale_vec_size = {.scale_vec::2X}; + .stype = {.ue8m0}; + + mma.spvariant.sync.aligned.m16n8k128.row.col.kind.block_scale.scale_vec_size.f32.e2m1.e2m1.f32.stype d, a, b, c, e, f, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .spvariant = {.sp::ordered_metadata}; + .kind = {.kind::mxf4nvf4}; + .scale_vec_size = {.scale_vec::2X, .scale_vec::4X}; + .stype = {.ue8m0, .ue4m3}; + + mma.spvariant.sync.aligned.m16n8k64.row.col.kind.block_scale{.scale_vec_size}.f32.f8f6f4type.f8f6f4type.f32.stype d, a, b, c, e, f, scale-a-data, {byte-id-a, thread-id-a}, scale-b-data, {byte-id-b, thread-id-b}; + + .spvariant = {.sp::ordered_metadata}; + .kind = {.kind::mxf8f6f4}; + .scale_vec_size = {.scale_vec::1X}; + .f8f6f4type = {.e4m3, .e5m2, .e3m2, .e2m3, .e2m1}; + .stype = {.ue8m0}; + + +Integer type: + + + mma.spvariant.sync.aligned.shape.row.col{.satfinite}.s32.atype.btype.s32 d, a, b, c, e, f; + + .shape = {.m16n8k32, .m16n8k64} + .atype = {.u8, .s8}; + .btype = {.u8, .s8}; + .spvariant = {.sp, .sp::ordered_metadata}; + + mma.spvariant.sync.aligned.shape.row.col{.satfinite}.s32.atype.btype.s32 d, a, b, c, e, f; + + .shape = {.m16n8k64, .m16n8k128} + .atype = {.u4, .s4}; + .btype = {.u4, .s4}; + .spvariant = {.sp, .sp::ordered_metadata}; + + +Description + +Perform a `MxNxK` matrix multiply and accumulate operation, `D = A*B+C`, where the A matrix is `MxK`, the B matrix is `KxN`, and the C and D matrices are `MxN`. + +A warp executing `mma.sp.sync/mma.sp::ordered_metadata.sync` instruction compute a single matrix multiply and accumulate operation. + +Qualifier `.block_scale` specifies that the matrices `A` and `B` are scaled with `scale_A` and `scale_B` matrices respectively before performing the matrix multiply and accumulate operation as specified in the section [Block Scaling](<#warp-level-block-scaling>). The data type corresponding to each of the element within `scale_A` and `scale_B` matrices is specified by `.stype`. Qualifier `.scale_vec_size` specifies the number of columns of `scale_A` matrix and number of rows in the matrix `scale_B`. + +The valid combinations of `.kind`, `.stype` and `.scale_vec_size` are described in [Table 36](<#mma-scaling-kind-type-valid-combination>). For `mma` with `.kind::mxf4` when the qualifier `.scale_vec_size` is not specified, then it defaults to `2X`. In contrast, when `.kind` is specified as `.kind::mxf8f6f4` then the qualifier `.scale_vec_size` defaults to `1X`. However, for `.kind::mxf4nvf4`, it is mandatory to provide valid `.scale_vec_size`. + +Operands `a` and `b` represent two multiplicand matrices A and B, while `c` and `d` represent the accumulator and destination matrices, distributed across the threads in warp. Matrix A is structured sparse as described in [Sparse matrix storage](<#warp-level-sparse-matrix-storage>) Operands `e` and `f` represent sparsity metadata and sparsity selector respectively. Operand `e` is a 32-bit integer and operand `f` is a 32-bit integer constant with values in the range 0..3. When `.block_scale` qualifier is specified, operand `scale-a-data`, `scale-b-data` represents the scale matrix metadata corresponding to `scale_A` and `scale_B` matrices respectively. The tuple `{byte-id-a, thread-id-a}` and `{byte-id-b, thread-id-b}` represent selectors for matrices `scale_A` and `scale_B` respectively from their corresponding metadata arguments `scale-a-data`, `scale-b-data`. The operands `scale-a-data`, `scale-b-data` are of type `.b32`. The operands `byte-id-a`, `thread-id-a`, `byte-id-b`, `thread-id-b` are unsigned 16-bit integer values. For more details on selector arguments refer [Block Scaling for mma.sync](<#warp-level-block-scaling>) section. + +Instruction `mma.sp::ordered_metadata` requires the indices in the sparsity metadata to be sorted in an increasing order starting from LSB, otherwise behavior is undefined. + +The registers in each thread hold a fragment of matrix as described in [Matrix fragments for multiply-accumulate operation with sparse matrix A](<#warp-level-matrix-fragments-for-sparse-mma>). + +The qualifiers `.dtype`, `.atype`, `.btype` and `.ctype` indicate the data-type of the elements in the matrices D, A, B and C respectively. The qualifier `.stype` indicate the data-type of the elements in the matrices `scale_A` and `scale_B`. In case of shapes `.m16n8k16`, `.m16n8k32` and `.m16n8k64`, `.dtype` must be the same as `.ctype`. + +When `.kind` is either of `.kind::mxf8f6f4` or `.kind::f8f6f4`, the individual 4-bit and the 6-bit floating point type elements must be packed in an 8-bit container. The matrix element of type `.e2m1` resides in central 4 bits of the 8-bit container with padding in the upper 2 bits and lower 2 bits of the container. When the matrix element is of type `.e3m2` or `.e2m3`, the matrix element resides in the lower 6 bits of the 8-bit container with padding in the upper 2 bits of the container. In contrast, note that when using `mma` with `.kind::mxf4` or `.kind::mxf4nvf4`, no explicit padding is necessary even though matrix elements are of type `.e2m1`. + +Precision and rounding : + + + * `.f16` floating point operations : + +Element-wise multiplication of matrix A and B is performed with at least single precision. When `.ctype` or `.dtype` is `.f32`, accumulation of the intermediate values is performed with at least single precision. When both `.ctype` and `.dtype` are specified as `.f16`, the accumulation is performed with at least half precision. + +The accumulation order, rounding and handling of subnormal inputs are unspecified. + + * `.e4m3`, `.e5m2`, `.e3m2`, `.e2m3`, `.e2m1` floating point operations : + +Element-wise multiplication of matrix A and B is performed with specified precision. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * `.bf16` and `.tf32` floating point operations : + +Element-wise multiplication of matrix A and B is performed with specified precision. Accumulation of the intermediate values is performed with at least single precision. + +The accumulation order, rounding, and handling of subnormal inputs are unspecified. + + * Integer operations : + +The integer `mma.sp/mma.sp::ordered_metadata` operation is performed with `.s32` accumulators. The `.satfinite` qualifier indicates that on overflow, the accumulated value is limited to the range _MIN_INT32_.. _MAX_INT32_ (where the bounds are defined as the minimum negative signed 32-bit integer and the maximum positive signed 32-bit integer respectively). + +If `.satfinite` is not specified, the accumulated value is wrapped instead. + + +The mandatory `.sync` qualifier indicates that `mma.sp/mma.sp::ordered_metadata` instruction causes the executing thread to wait until all threads in the warp execute the same `mma.sp/mma.sp::ordered_metadata` instruction before resuming execution. + +The mandatory `.aligned` qualifier indicates that all threads in the warp must execute the same `mma.sp/mma.sp::ordered_metadata` instruction. In conditionally executed code, a `mma.sp/mma.sp::ordered_metadata` instruction should only be used if it is known that all threads in the warp evaluate the condition identically, otherwise behavior is undefined. + +The behavior of `mma.sp/mma.sp::ordered_metadata` instruction is undefined if all threads in the same warp do not use the same qualifiers, or if any thread in the warp has exited. + +Notes + +`mma.sp` instruction may have substantially reduced performance on some target architectures. Hence, it is advised to use `mma.sp::ordered_metadata` instruction. + +PTX ISA Notes + +Introduced in PTX ISA version 7.1. + +Support for `.e4m3` and `.e5m2` alternate floating point type `mma` operation introduced in PTX ISA version 8.4. + +`mma.sp::ordered_metadata` introduced in PTX ISA version 8.5. + +Support for shape `.m16n8k32` and `.f16` dtype/ctype with `.e4m3`/`.e5m2` alternate floating point type `mma` operation introduced in PTX ISA version 8.7. + +Support for `.e3m2`, `.e2m3`, `.e2m1` alternate floating point type `mma` operation introduced in PTX ISA version 8.7. + +Support for `.kind`, `.block_scale`, `.scale_vec_size` qualifier introduced in PTX ISA version 8.7. + +Support for `.scale_vec::4X` on `.ue8m0` as `.stype` with `.kind::mxf4nvf4` is introduced in PTX ISA version 9.1 + +Target ISA Notes + +Requires `sm_80` or higher. + +`.e4m3` and `.e5m2` alternate floating point type `mma` operation requires `sm_89` or higher. + +`mma.sp::ordered_metadata` requires `sm_80` or higher. + +Support for shape `.m16n8k32` and `.f16` dtype/ctype with `.e4m3`/`.e5m2` alternate floating point type `mma` operation requires `sm_120`. + +`.e3m2`, `.e2m3` and `.e2m1` alternate floating point type `mma` operation requires `sm_120a` and are supported on `sm_120f` or higher in the same family from PTX ISA version 8.8. + +Support for `.kind`, `.block_scale`, `.scale_vec_size` qualifier requires `sm_120a` and are supported on `sm_120f` and later generation targets in the same family from PTX ISA version 8.8 except for `.kind::mxf4nvf4`/`.kind::mxf4`. + +Qualifiers `.kind::mxf4nvf4` and `.kind::mxf4` are supported on following architectures: + + * `sm_120a` + + * `sm_121a` + + +Examples of half precision floating point type + + + // f16 elements in C and D matrix + .reg .f16x2 %Ra<2> %Rb<2> %Rc<2> %Rd<2> + .reg .b32 %Re; + mma.sp.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1}, %Re, 0x1; + + .reg .f16x2 %Ra<2> %Rb<2> %Rc<2> %Rd<2> + .reg .b32 %Re; + + mma.sp::ordered_metadata.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1}, %Re, 0x1; + + +Examples of alternate floating point type + + + .reg .b32 %Ra<2>, %Rb<2>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + .reg .b32 %Ra<2>, %Rb<2>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp.sync.aligned.m16n8k32.row.col.f32.bf16.bf16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp.sync.aligned.m16n8k64.row.col.f32.e5m2.e4m3.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0; + + .reg .b32 %Ra<2>, %Rb<2>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.kind::f8f6f4.f32.e3m2.e2m3.f32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .b32 %Rc<4>, %Rd<4>; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.kind::f8f6f4.f16.e2m3.e2m1.f16 + {%Rd0, %Rd1}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1}, %Re, 0; + + +Examples of integer type + + + .reg .b32 %Ra<4>, %Rb<4>, %Rc<4>, %Rd<4>; + .reg .u32 %Re; + + // u8 elements in A and B matrix + mma.sp.sync.aligned.m16n8k32.row.col.satfinite.s32.u8.u8.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + // s8 elements in A and B matrix + mma.sp.sync.aligned.m16n8k64.row.col.satfinite.s32.s8.s8.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x0; + + // s8 elements in A and B matrix with ordered metadata + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.satfinite.s32.s8.s8.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x0; + + // u4 elements in A and B matrix + mma.sp.sync.aligned.m16n8k64.row.col.s32.s4.s4.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1}, + {%Rb0, %Rb1}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x1; + + // u4 elements in A and B matrix + mma.sp.sync.aligned.m16n8k128.row.col.satfinite.s32.u4.u4.s32 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, %Re, 0x0; + + +Examples of mma with block scale + + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k128.row.col.kind::mxf4.block_scale.f32.e2m1.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + %Re, 0, + scaleAData, {2, 1}, scaleBData, {2, 3}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .u16 bidA, bidB, tidA, tidB; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k128.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue4m3 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + %Re, 0, + scaleAData, {bidA, tidA}, scaleBData, {bidB, tidB}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .u16 bidA, bidB, tidA, tidB; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k128.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + %Re, 0, + scaleAData, {bidA, tidA}, scaleBData, {bidB, tidB}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.kind::mxf8f6f4.block_scale.scale_vec::1X.f32.e3m2.e2m1.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + %Re, 0, + scaleAData, {0, 1}, scaleBData, {0, 1}; + + .reg .b32 %Ra<4>, %Rb<4>; + .reg .f32 %Rc<4>, %Rd<4>; + .reg .b32 scaleAData, scaleBData; + .reg .b32 %Re; + mma.sp::ordered_metadata.sync.aligned.m16n8k64.row.col.kind::mxf8f6f4.block_scale.scale_vec::1X.f32.e4m3.e5m2.f32.ue8m0 + {%Rd0, %Rd1, %Rd2, %Rd3}, + {%Ra0, %Ra1, %Ra2, %Ra3}, + {%Rb0, %Rb1, %Rb2, %Rb3}, + {%Rc0, %Rc1, %Rc2, %Rc3}, + %Re, 0, + scaleAData, {0, 1}, scaleBData, {0, 0}; \ No newline at end of file diff --git a/content/cuda/docs/ptx-matrix-shape/DOC.md b/content/cuda/docs/ptx-matrix-shape/DOC.md new file mode 100644 index 00000000..97034b97 --- /dev/null +++ b/content/cuda/docs/ptx-matrix-shape/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-matrix-shape +description: The matrix multiply and accumulate operations support a limited set of + shapes for the operand matrices A, B and D. The shapes of all three matrix operands + are collectively described by the tuple `MxNx... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.15.2. Matrix Shape + +--- +title: "9.7.15.2. Matrix Shape" +section: 9.7.15.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.15.2. Matrix Shape + + +The matrix multiply and accumulate operations support a limited set of shapes for the operand matrices A, B and D. The shapes of all three matrix operands are collectively described by the tuple `MxNxK`, where A is an `MxK` matrix, B is a `KxN` matrix, while D is a `MxN` matrix. + +The following matrix shapes are supported for the specified types for the `wgmma.mma_async` operation: + +Multiplicand Data type | Sparsity | Shape +---|---|--- +Floating-point - `.f16` | Dense | `.m64n8k16`, `.m64n16k16`, `.m64n24k16`, `.m64n32k16`, `.m64n40k16`, `.m64n48k16`, `.m64n56k16`, `.m64n64k16`, `.m64n72k16`, `.m64n80k16`, `.m64n88k16`, `.m64n96k16`, `.m64n104k16`, `.m64n112k16`, `.m64n120k16`, `.m64n128k16`, `.m64n136k16`, `.m64n144k16`, `.m64n152k16`, `.m64n160k16`, `.m64n168k16`, `.m64n176k16`, `.m64n184k16`, `.m64n192k16`, `.m64n200k16`, `.m64n208k16`, `.m64n216k16`, `.m64n224k16`, `.m64n232k16`, `.m64n240k16`, `.m64n248k16`, `.m64n256k16` +Alternate floating-point format - `.bf16` +Alternate floating-point format - `.tf32` | Sparse +Alternate floating-point format - `.tf32` | Dense | `.m64n8k8`, `.m64n16k8`, `.m64n24k8`, `.m64n32k8`, `.m64n40k8`, `.m64n48k8`, `.m64n56k8`, `.m64n64k8`, `.m64n72k8`, `.m64n80k8`, `.m64n88k8`, `.m64n96k8`, `.m64n104k8`, `.m64n112k8`, `.m64n120k8`, `.m64n128k8`, `.m64n136k8`, `.m64n144k8`, `.m64n152k8`, `.m64n160k8`, `.m64n168k8`, `.m64n176k8`, `.m64n184k8`, `.m64n192k8`, `.m64n200k8`, `.m64n208k8`, `.m64n216k8`, `.m64n224k8`, `.m64n232k8`, `.m64n240k8`, `.m64n248k8`, `.m64n256k8` +Alternate floating-point format - `.e4m3`/ `.e5m2` | Dense | `.m64n8k32`, `.m64n16k32`, `.m64n24k32`, `.m64n32k32`, `.m64n40k32`, `.m64n48k32`, `.m64n56k32`, `.m64n64k32`, `.m64n72k32`, `.m64n80k32`, `.m64n88k32`, `.m64n96k32`, `.m64n104k32`, `.m64n112k32`, `.m64n120k32`, `.m64n128k32`, `.m64n136k32`, `.m64n144k32`, `.m64n152k32`, `.m64n160k32`, `.m64n168k32`, `.m64n176k32`, `.m64n184k32`, `.m64n192k32`, `.m64n200k32`, `.m64n208k32`, `.m64n216k32`, `.m64n224k32`, `.m64n232k32`, `.m64n240k32`, `.m64n248k32`, `.m64n256k32` +Floating point - `.f16` | Sparse +Altername floating-point format - `.bf16` +Integer - `.u8`/`.s8` | Dense | `.m64n8k32`, `.m64n16k32`, `.m64n24k32`, `.m64n32k32`, `.m64n48k32`, `.m64n64k32`, `.m64n80k32`, `.m64n96k32`, `.m64n112k32`, `.m64n128k32`, `.m64n144k32`, `.m64n160k32`, `.m64n176k32`, `.m64n192k32`, `.m64n208k32`, `.m64n224k32`, `.m64n240k32`, `.m64n256k32` +Alternate floating-point format - `.e4m3`/ `.e5m2` | Sparse | `.m64n8k64`, `.m64n16k64`, `.m64n24k64`, `.m64n32k64`, `.m64n40k64`, `.m64n48k64`, `.m64n56k64`, `.m64n64k64`, `.m64n72k64`, `.m64n80k64`, `.m64n88k64`, `.m64n96k64`, `.m64n104k64`, `.m64n112k64`, `.m64n120k64`, `.m64n128k64`, `.m64n136k64`, `.m64n144k64`, `.m64n152k64`, `.m64n160k64`, `.m64n168k64`, `.m64n176k64`, `.m64n184k64`, `.m64n192k64`, `.m64n200k64`, `.m64n208k64`, `.m64n216k64`, `.m64n224k64`, `.m64n232k64`, `.m64n240k64`, `.m64n248k64`, `.m64n256k64` +Integer - `.u8`/`.s8` | Sparse | `.m64n8k64`, `.m64n16k64`, `.m64n24k64`, `.m64n32k64`, `.m64n48k64`, `.m64n64k64`, `.m64n80k64`, `.m64n96k64`, `.m64n112k64`, `.m64n128k64`, `.m64n144k64`, `.m64n160k64`, `.m64n176k64`, `.m64n192k64`, `.m64n208k64`, `.m64n224k64`, `.m64n240k64`, `.m64n256k64` +Single-bit - `.b1` | Dense | `.m64n8k256`, `.m64n16k256`, `.m64n24k256`, `.m64n32k256`, `.m64n48k256`, `.m64n64k256`, `.m64n80k256`, `.m64n96k256`, `.m64n112k256`, `.m64n128k256`, `.m64n144k256`, `.m64n160k256`, `.m64n176k256`, `.m64n192k256`, `.m64n208k256`, `.m64n224k256`, `.m64n240k256`, `.m64n256k256` \ No newline at end of file diff --git a/content/cuda/docs/ptx-max/DOC.md b/content/cuda/docs/ptx-max/DOC.md new file mode 100644 index 00000000..9fdac1bf --- /dev/null +++ b/content/cuda/docs/ptx-max/DOC.md @@ -0,0 +1,149 @@ +--- +name: ptx-max +description: Find the maximum of given values. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.12. Floating Point Instructions:max + +--- +title: "9.7.3.12. Floating Point Instructions:max" +section: 9.7.3.12 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.12. Floating Point Instructions:max + + +`max` + +Find the maximum of given values. + +Syntax + +max{.ftz}{.NaN}{.xorsign.abs}.f32 d, a, b; + max{.ftz}{.NaN}{.abs}.f32 d, a, b, c; + max.f64 d, a, b; + +Description + +Store the maximum of `a`, `b` and optionally `c` in `d`. + +If `.NaN` modifier is specified, the result is canonical `NaN` if any of the inputs is `NaN`. + +If `.abs` modifier is specified, the magnitude of destination operand `d` is the maximum of absolute values of the input arguments. + +If `.xorsign` modifier is specified, the sign bit of destination `d` is equal to the XOR of the sign bits of the inputs: `a` and `b`. The `.xorsign` qualifier cannot be specified for three inputs operation. + +Qualifier `.xorsign` requires qualifier `.abs` to be specified. In such cases, `.xorsign` considers the sign bit of both inputs before applying `.abs` operation. + +If the result of `max` is `NaN` then the `.xorsign` and `.abs` modifiers will be ignored. + +Semantics + +def max_num (z, x, y) { + if (isNaN(x) && isNaN(y)) + z = NaN; + else if (isNaN(x)) + z = y; + else if (isNaN(y)) + z = x; + else + // note: +0.0 > -0.0 here + z = (x > y) ? x : y; + return z; + } + + def max_nan (z, x, y) { + if (isNaN(x) || isNaN(y)) + z = NaN; + else + // note: +0.0 > -0.0 here + z = (x > y) ? x : y; + return z; + } + + def two_inputs_max (z, x, y) { + if (.NaN) + z = max_nan(z, x, y); + else + z = max_num(z, x, y); + return z; + } + + if (.xorsign && !isPresent(c)) { + xorsign = getSignBit(a) ^ getSignBit(b); + } + if (.abs) { + a = |a|; + b = |b|; + if (isPresent(c)) { + c = |c|; + } + } + + d = two_inputs_max (d, a, b) + if (isPresent(c)) { + d = two_inputs_max (d, d, c) + } + + if (.xorsign && !isPresent(c) !isNaN(d)) { + setSignBit(d, xorsign); + } + +Notes + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`max.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`max.f64` supports subnormal numbers. + +`max.f32` flushes subnormal inputs and results to sign-preserving zero. + +If values of both inputs are 0.0, then +0.0 > -0.0. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +`max.NaN` introduced in PTX ISA version 7.0. + +`max.xorsign.abs` introduced in PTX ISA version 7.2. + +`max` with three input arguments introduced in PTX ISA version 8.8. + +Target ISA Notes + +`max.f32` supported on all target architectures. + +`max.f64` requires `sm_13` or higher. + +`max.NaN` requires `sm_80` or higher. + +`max.xorsign.abs` requires `sm_86` or higher. + +`max` with three input arguments requires `sm_100` or higher. + +Examples + +max.ftz.f32 f0,f1,f2; + max.f64 a,b,c; + // fp32 max with .NaN + max.NaN.f32 f0,f1,f2; + // fp32 max with .xorsign.abs + max.xorsign.abs.f32 Rd, Ra, Rb; \ No newline at end of file diff --git a/content/cuda/docs/ptx-mbarrier-protocol-patterns/DOC.md b/content/cuda/docs/ptx-mbarrier-protocol-patterns/DOC.md new file mode 100644 index 00000000..9eda6556 --- /dev/null +++ b/content/cuda/docs/ptx-mbarrier-protocol-patterns/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-mbarrier-protocol-patterns +description: "PTX mbarrier protocol patterns: arrive/test_wait/arrive_drop flows, async-copy integration, and phase-safety rules." +metadata: + languages: "cpp" + versions: "9.2" + revision: 1 + updated-on: "2026-03-20" + source: official + tags: "cuda,ptx,mbarrier,arrive,test_wait,arrive_drop,cp.async,cp-async-mbarrier-arrive,cp.async.wait_group,cp.async.wait_all,async-proxy,phase,completion-protocol,producer-consumer" +--- + +# PTX mbarrier Protocol Patterns + +Use this page for robust phase-based synchronization protocols around async copy/compute pipelines. + +## Core Operations + +- Producer-side phase signal: `mbarrier.arrive` +- Participant drop from future phases: `mbarrier.arrive_drop` +- Consumer-side wait/poll: `mbarrier.test_wait` / `mbarrier.try_wait` +- Async-copy completion bridge: `cp.async.mbarrier.arrive` + +## Protocol Template + +1. Initialize barrier state and participant expectations. +2. Issue producer operations (for example async copy). +3. Signal completion with appropriate arrive semantics. +4. Wait on consumer side before data use. +5. Advance phases safely and apply `arrive_drop` when participation changes. + +## Phase Safety Rules + +- Keep producer and consumer on the same phase contract. +- Respect no-complete restrictions for `.noComplete` variants. +- Use sink `_` rules correctly for remote cluster-only flows. +- Avoid mixing unrelated work into the same mbarrier protocol. + +## Common Failure Modes + +- Deadlock from mismatched participant counts. +- Premature consumer reads due to missing wait checks. +- Undefined behavior by allowing `.noComplete` variant to complete a phase. + +## Related Topics + +- PTX data-movement async references: `../ptx/instructions/data-movement/references/cp-async.md` +- PTX TMA instructions: `../ptx/instructions/tma/DOC.md` +- PTX synchronization instructions: `../ptx/instructions/sync-comm/DOC.md` + +## Official Source Links (Fact Check) + +- PTX mbarrier instruction set: https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-mbarrier +- PTX cp.async.mbarrier.arrive: https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-cp-async-mbarrier-arrive +- PTX Asynchronous Operations: https://docs.nvidia.com/cuda/parallel-thread-execution/#asynchronous-operations + +Last cross-check date: 2026-03-20 diff --git a/content/cuda/docs/ptx-mbarrier/DOC.md b/content/cuda/docs/ptx-mbarrier/DOC.md new file mode 100644 index 00000000..4d4fee43 --- /dev/null +++ b/content/cuda/docs/ptx-mbarrier/DOC.md @@ -0,0 +1,943 @@ +--- +name: ptx-mbarrier +description: '`mbarrier` is a barrier created in shared memory that supports :' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.15. Parallel Synchronization and Communication Instructions:mbarrier + +--- +title: "9.7.13.15. Parallel Synchronization and Communication Instructions:mbarrier" +section: 9.7.13.15 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.15. Parallel Synchronization and Communication Instructions:mbarrier + + +`mbarrier` is a barrier created in shared memory that supports : + +* Synchronizing any subset of threads within a CTA + + * One-way synchronization of threads across CTAs of a cluster. As noted in [mbarrier support with shared memory](<#parallel-synchronization-and-communication-instructions-mbarrier-smem>), threads can perform only _arrive_ operations but not _*_wait_ on an mbarrier located in `shared::cluster` space. + + * Waiting for completion of asynchronous memory operations initiated by a thread and making them visible to other threads. + +An _mbarrier object_ is an opaque object in memory which can be initialized and invalidated using : + +* `mbarrier.init` + + * `mbarrier.inval` + +Operations supported on _mbarrier object_ s are : + +* `mbarrier.expect_tx` + + * `mbarrier.complete_tx` + + * `mbarrier.arrive` + + * `mbarrier.arrive_drop` + + * `mbarrier.test_wait` + + * `mbarrier.try_wait` + + * `mbarrier.pending_count` + + * `cp.async.mbarrier.arrive` + +Performing any _mbarrier_ operation except `mbarrier.init` on an uninitialized _mbarrier object_ results in undefined behavior. Performing any _non-mbarrier_ or `mbarrier.init` operations on an initialized _mbarrier object_ results in undefined behavior. + +Unlike `bar{.cta}`/`barrier{.cta}` instructions which can access a limited number of barriers per CTA, _mbarrier objects_ are user defined and are only limited by the total shared memory size available. + +_mbarrier_ operations enable threads to perform useful work after the arrival at the _mbarrier_ and before waiting for the _mbarrier_ to complete. + +##### 9.7.13.15.1. [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>) + +An mbarrier object is an opaque object with the following type and alignment requirements : + +Type | Alignment (bytes) | Memory space +---|---|--- +`.b64` | 8 | `.shared` + +##### 9.7.13.15.2. [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>) + +An opaque _mbarrier object_ keeps track of the following information : + + * Current phase of the _mbarrier object_ + + * Count of pending arrivals for the current phase of the _mbarrier object_ + + * Count of expected arrivals for the next phase of the _mbarrier object_ + + * Count of pending asynchronous memory operations (or transactions) tracked by the current phase of the _mbarrier object_. This is also referred to as _tx-count_. + + +An _mbarrier object_ progresses through a sequence of phases where each phase is defined by threads performing an expected number of [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operations. + +The valid range of each of the counts is as shown below: + +Count name | Minimum value | Maximum value +---|---|--- +Expected arrival count | 1 | 220 \- 1 +Pending arrival count | 0 | 220 \- 1 +tx-count | -(220 \- 1) | 220 \- 1 + +##### 9.7.13.15.3. [Lifecycle of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-lifecycle>) + +The _mbarrier object_ must be initialized prior to use. + +An _mbarrier object_ is used to synchronize threads and asynchronous memory operations. + +An _mbarrier object_ may be used to perform a sequence of such synchronizations. + +An _mbarrier object_ must be invalidated to repurpose its memory for any purpose, including repurposing it for another mbarrier object. + +##### 9.7.13.15.4. [Phase of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-phase>) + +The phase of an _mbarrier object_ is the number of times the _mbarrier object_ has been used to synchronize threads and [asynchronous](<#program-order-async-operations>) operations. In each phase {0, 1, 2, …}, threads perform in program order : + + * [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operations to complete the current phase and + + * _test_wait_ / _try_wait_ operations to check for the completion of the current phase. + + +An _mbarrier object_ is automatically reinitialized upon completion of the current phase for immediate use in the next phase. The current phase is incomplete and all prior phases are complete. + +For each phase of the mbarrier object, at least one _test_wait_ or _try_wait_ operation must be performed which returns `True` for `waitComplete` before an [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation in the subsequent phase. + +##### 9.7.13.15.5. [Tracking asynchronous operations by the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-tracking-async-operations>) + +Starting with the Hopper architecture (`sm_9x`), _mbarrier object_ supports a new count, called _tx-count_ , which is used for tracking the completion of asynchronous memory operations or transactions. _tx-count_ tracks the number of asynchronous transactions, in units specified by the asynchronous memory operation, that are outstanding and yet to be complete. + +The _tx-count_ of an _mbarrier object_ must be set to the total amount of asynchronous memory operations, in units as specified by the asynchronous operations, to be tracked by the current phase. Upon completion of each of the asynchronous operations, the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation will be performed on the _mbarrier object_ and thus progress the mbarrier towards the completion of the current phase. + +###### 9.7.13.15.5.1. [expect-tx operation](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx-operation>) + +The _expect-tx_ operation, with an `expectCount` argument, increases the _tx-count_ of an _mbarrier object_ by the value specified by `expectCount`. This sets the current phase of the _mbarrier object_ to expect and track the completion of additional asynchronous transactions. + +###### 9.7.13.15.5.2. [complete-tx operation](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) + +The _complete-tx_ operation, with an `completeCount` argument, on an _mbarrier object_ consists of the following: + +mbarrier signaling + + +Signals the completion of asynchronous transactions that were tracked by the current phase. As a result of this, _tx-count_ is decremented by `completeCount`. + +mbarrier potentially completing the current phase + + +If the current phase has been completed then the mbarrier transitions to the next phase. Refer to [Phase Completion of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-phase-completion>) for details on phase completion requirements and phase transition process. + +##### 9.7.13.15.6. [Phase Completion of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-phase-completion>) + +The requirements for completion of the current phase are described below. Upon completion of the current phase, the phase transitions to the subsequent phase as described below. + +Current phase completion requirements + + +An _mbarrier object_ completes the current phase when all of the following conditions are met: + + * The count of the pending arrivals has reached zero. + + * The _tx-count_ has reached zero. + + +Phase transition + + +When an _mbarrier_ object completes the current phase, the following actions are performed atomically: + + * The _mbarrier object_ transitions to the next phase. + + * The pending arrival count is reinitialized to the expected arrival count. + +##### 9.7.13.15.7. [Arrive-on operation on mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) + +An _arrive-on_ operation, with an optional _count_ argument, on an _mbarrier object_ consists of the following 2 steps : + + * mbarrier signalling: + +Signals the arrival of the executing thread OR completion of the asynchronous instruction which signals the arrive-on operation initiated by the executing thread on the _mbarrier object_. As a result of this, the pending arrival count is decremented by _count_. If the _count_ argument is not specified, then it defaults to 1. + + * mbarrier potentially completing the current phase: + +If the current phase has been completed then the mbarrier transitions to the next phase. Refer to [Phase Completion of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-phase-completion>) for details on phase completion requirements and phase transition process. + +##### 9.7.13.15.8. [mbarrier support with shared memory](<#parallel-synchronization-and-communication-instructions-mbarrier-smem>) + +The following table summarizes the support of various mbarrier operations on _mbarrier objects_ located at different shared memory locations: + +mbarrier operations | `.shared::cta` | `.shared::cluster` +---|---|--- +`mbarrier.arrive` | Supported | Supported, cannot return result +`mbarrier.expect_tx` | Supported | Supported +`mbarrier.complete_tx` | Supported | Supported +Other mbarrier operations | Supported | Not supported + +##### 9.7.13.15.9. [Parallel Synchronization and Communication Instructions: `mbarrier.init`](<#parallel-synchronization-and-communication-instructions-mbarrier-init>) + +`mbarrier.init` + +Initialize the _mbarrier object_. + +Syntax + + + mbarrier.init{.shared{::cta}}.b64 [addr], count; + + +Description + +`mbarrier.init` initializes the _mbarrier object_ at the location specified by the address operand `addr` with the unsigned 32-bit integer `count`. The value of operand count must be in the range as specified in [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>). + +Initialization of the _mbarrier object_ involves : + + * Initializing the current phase to 0. + + * Initializing the expected arrival count to `count`. + + * Initializing the pending arrival count to `count`. + + * Initializing the _tx-count_ to 0. + + +The valid range of values for the operand `count` is [1, …, 220 \- 1]. Refer [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>) for the valid range of values for the various constituents of the mbarrier. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +The behavior of performing an `mbarrier.init` operation on a memory location containing a valid _mbarrier object_ is undefined; invalidate the _mbarrier object_ using `mbarrier.inval` first, before repurposing the memory location for any other purpose, including another _mbarrier object_. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + .shared .b64 shMem, shMem2; + .reg .b64 addr; + .reg .b32 %r1; + + cvta.shared.u64 addr, shMem2; + mbarrier.init.b64 [addr], %r1; + bar.cta.sync 0; + // ... other mbarrier operations on addr + + mbarrier.init.shared::cta.b64 [shMem], 12; + bar.sync 0; + // ... other mbarrier operations on shMem + +##### 9.7.13.15.10. [Parallel Synchronization and Communication Instructions: `mbarrier.inval`](<#parallel-synchronization-and-communication-instructions-mbarrier-inval>) + +`mbarrier.inval` + +Invalidates the _mbarrier object_. + +Syntax + + + mbarrier.inval{.shared{::cta}}.b64 [addr]; + + +Description + +`mbarrier.inval` invalidates the _mbarrier object_ at the location specified by the address operand `addr`. + +An _mbarrier object_ must be invalidated before using its memory location for any other purpose. + +Performing any _mbarrier_ operation except `mbarrier.init` on a memory location that does not contain a valid _mbarrier object_ , results in undefined behaviour. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + .shared .b64 shmem; + .reg .b64 addr; + .reg .b32 %r1; + .reg .pred t0; + + // Example 1 : + bar.sync 0; + @t0 mbarrier.init.b64 [addr], %r1; + // ... other mbarrier operations on addr + bar.sync 0; + @t0 mbarrier.inval.b64 [addr]; + + + // Example 2 : + bar.cta.sync 0; + mbarrier.init.shared.b64 [shmem], 12; + // ... other mbarrier operations on shmem + bar.cta.sync 0; + @t0 mbarrier.inval.shared.b64 [shmem]; + + // shmem can be reused here for unrelated use : + bar.cta.sync 0; + st.shared.b64 [shmem], ...; + + // shmem can be re-initialized as mbarrier object : + bar.cta.sync 0; + @t0 mbarrier.init.shared.b64 [shmem], 24; + // ... other mbarrier operations on shmem + bar.cta.sync 0; + @t0 mbarrier.inval.shared::cta.b64 [shmem]; + +##### 9.7.13.15.11. [Parallel Synchronization and Communication Instructions: `mbarrier.expect_tx`](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx>) + +`mbarrier.expect_tx` + +Perfoms [expect-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx-operation>) operation on the _mbarrier object_. + +Syntax + + + mbarrier.expect_tx{.sem.scope}{.space}.b64 [addr], txCount; + + .sem = { .relaxed } + .scope = { .cta, .cluster } + .space = { .shared{::cta}, .shared::cluster } + + +Description + +A thread executing `mbarrier.expect_tx` performs an [expect-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx-operation>) operation on the _mbarrier object_ at the location specified by the address operand `addr`. The 32-bit unsigned integer operand `txCount` specifies the `expectCount` argument to the _expect-tx_ operation. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` or `.shared::cluster` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` are as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). The `.relaxed` qualifier does not provide any memory ordering semantics and visibility guarantees. + +The optional `.scope` qualifier indicates the set of threads that directly observe the memory synchronizing effect of this operation, as described in the [Memory Consistency Model](<#memory-consistency-model>). + +Qualifiers `.sem` and `.scope` must be specified together. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + mbarrier.expect_tx.b64 [addr], 32; + mbarrier.expect_tx.relaxed.cta.shared.b64 [mbarObj1], 512; + mbarrier.expect_tx.relaxed.cta.shared.b64 [mbarObj2], 512; + +##### 9.7.13.15.12. [Parallel Synchronization and Communication Instructions: `mbarrier.complete_tx`](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx>) + +`mbarrier.complete_tx` + +Perfoms [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the _mbarrier object_. + +Syntax + + + mbarrier.complete_tx{.sem.scope}{.space}.b64 [addr], txCount; + + .sem = { .relaxed } + .scope = { .cta, .cluster } + .space = { .shared{::cta}, .shared::cluster } + + +Description + +A thread executing `mbarrier.complete_tx` performs a [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the _mbarrier object_ at the location specified by the address operand `addr`. The 32-bit unsigned integer operand `txCount` specifies the `completeCount` argument to the _complete-tx_ operation. + +`mbarrier.complete_tx` does not involve any asynchronous memory operations and only simulates the completion of an asynchronous memory operation and its side effect of signaling to the _mbarrier object_. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` or `.shared::cluster` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` are as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). The `.relaxed` qualifier does not provide any memory ordering semantics and visibility guarantees. + +The optional `.scope` qualifier indicates the set of threads that directly observe the memory synchronizing effect of this operation, as described in the [Memory Consistency Model](<#memory-consistency-model>). + +Qualifiers `.sem` and `.scope` must be specified together. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + mbarrier.complete_tx.b64 [addr], 32; + mbarrier.complete_tx.shared.b64 [mbarObj1], 512; + mbarrier.complete_tx.relaxed.cta.b64 [addr2], 32; + +##### 9.7.13.15.13. [Parallel Synchronization and Communication Instructions: `mbarrier.arrive`](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive>) + +`mbarrier.arrive` + +Performs [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) on the _mbarrier object_. + +Syntax + + + mbarrier.arrive{.sem.scope}{.shared{::cta}}.b64 state, [addr]{, count}; + mbarrier.arrive{.sem.scope}{.shared::cluster}.b64 _, [addr] {,count} + mbarrier.arrive.expect_tx{.sem.scope}{.shared{::cta}}.b64 state, [addr], txCount; + mbarrier.arrive.expect_tx{.sem.scope}{.shared::cluster}.b64 _, [addr], txCount; + mbarrier.arrive.noComplete{.release.cta}{.shared{::cta}}.b64 state, [addr], count; + + .sem = { .release, .relaxed } + .scope = { .cta, .cluster } + + +Description + +A thread executing `mbarrier.arrive` performs an [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation on the _mbarrier object_ at the location specified by the address operand `addr`. The 32-bit unsigned integer operand `count` specifies the _count_ argument to the [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +The optional qualifier `.expect_tx` specifies that an [expect-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx-operation>) operation is performed prior to the [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation. The 32-bit unsigned integer operand `txCount` specifies the _expectCount_ argument to the _expect-tx_ operation. When both qualifiers `.arrive` and `.expect_tx` are specified, then the count argument of the _arrive-on_ operation is assumed to be 1. + +A `mbarrier.arrive` operation with `.noComplete` qualifier must not cause the `mbarrier` to complete its current phase, otherwise the behavior is undefined. + +The value of the operand `count` must be in the range as specified in [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>). + +Note: for `sm_8x`, when the argument `count` is specified, the modifier `.noComplete` is required. + +`mbarrier.arrive` operation on an _mbarrier object_ located in `.shared::cta` returns an opaque 64-bit register capturing the phase of the _mbarrier object_ prior to the [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) in the destination operand `state.` Contents of the `state` operand are implementation specific. Optionally, sink symbol `'_'` can be used for the `state` argument. + +`mbarrier.arrive` operation on an _mbarrier object_ located in `.shared::cluster` but not in `.shared::cta` cannot return a value. Sink symbol ‘_’ is mandatory for the destination operand for such cases. + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.sem` qualifier is absent, `.release` is assumed by default. + +The `.relaxed` qualifier does not provide any memory ordering semantics and visibility guarantees. + +The optional `.scope` qualifier indicates the set of threads that directly observe the memory synchronizing effect of this operation, as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.scope` qualifier is not specified then it defaults to `.cta`. In contrast, the `.shared::` indicates the state space where the mbarrier resides. + +Qualifiers `.sem` and `.scope` must be specified together. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for sink symbol ‘_’ as the destination operand is introduced in PTX ISA version 7.1. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Support for `count` argument without the modifier `.noComplete` introduced in PTX ISA version 7.8. + +Support for sub-qualifier `::cluster` introduced in PTX ISA version 8.0. + +Support for qualifier `.expect_tx` is introduced in PTX ISA version 8.0. + +Support for `.scope` and `.sem` qualifiers introduced in PTX ISA version 8.0 + +Support for `.relaxed` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_80` or higher. + +Support for `count` argument without the modifier `.noComplete` requires `sm_90` or higher. + +Qualifier `.expect_tx` requires `sm_90` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Support for `.cluster` scope requires `sm_90` or higher. + +Support for `.relaxed` qualifier requires `sm_90` or higher. + +Examples + + + .reg .b32 cnt, remoteAddr32, remoteCTAId, addr32; + .reg .b64 %r<5>, addr, remoteAddr64; + .shared .b64 shMem, shMem2; + + cvta.shared.u64 addr, shMem2; + mov.b32 addr32, shMem2; + mapa.shared::cluster.u32 remoteAddr32, addr32, remoteCTAId; + mapa.u64 remoteAddr64, addr, remoteCTAId; + + cvta.shared.u64 addr, shMem2; + + mbarrier.arrive.shared.b64 %r0, [shMem]; + mbarrier.arrive.shared::cta.b64 %r0, [shMem2]; + mbarrier.arrive.release.cta.shared::cluster.b64 _, [remoteAddr32]; + mbarrier.arrive.release.cluster.b64 _, [remoteAddr64], cnt; + mbarrier.arrive.expect_tx.release.cluster.b64 _, [remoteAddr64], tx_count; + mbarrier.arrive.noComplete.b64 %r1, [addr], 2; + mbarrier.arrive.relaxed.cta.b64 %r2, [addr], 4; + mbarrier.arrive.b64 %r2, [addr], cnt; + +##### 9.7.13.15.14. [Parallel Synchronization and Communication Instructions: `mbarrier.arrive_drop`](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-drop>) + +`mbarrier.arrive_drop` + +Decrements the expected count of the _mbarrier object_ and performs [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>). + +Syntax + + + mbarrier.arrive_drop{.sem.scope}{.shared{::cta}}.b64 state, [addr]{, count}; + mbarrier.arrive_drop{.sem.scope}{.shared::cluster}.b64 _, [addr] {,count}; + mbarrier.arrive_drop.expect_tx{.sem.scope}{.shared{::cta}}.b64 state, [addr], tx_count; + mbarrier.arrive_drop.expect_tx{.sem.scope}{.shared::cluster}.b64 _, [addr], tx_count; + mbarrier.arrive_drop.noComplete{.release.cta}{.shared{::cta}}.b64 state, [addr], count; + + .sem = { .release, .relaxed } + .scope = { .cta, .cluster } + + +Description + +A thread executing `mbarrier.arrive_drop` on the _mbarrier object_ at the location specified by the address operand `addr` performs the following steps: + + * Decrements the expected arrival count of the _mbarrier object_ by the value specified by the 32-bit integer operand `count`. If `count` operand is not specified, it defaults to 1. + + * Performs an [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) on the _mbarrier object_. The operand `count` specifies the _count_ argument to the [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>). + + +The decrement done in the expected arrivals count of the _mbarrier object_ will be for all the subsequent phases of the _mbarrier object_. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` or `.shared::cluster` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +The optional qualifier `.expect_tx` specifies that an [expect-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-expect-tx-operation>) operation is performed prior to the `arrive_drop` operation, i.e. the decrement of arrival count and [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation. The 32-bit unsigned integer operand `txCount` specifies the _expectCount_ argument to the _expect-tx_ operation. When both qualifiers `.arrive_drop` and `.expect_tx` are specified, then the count argument of the _arrive-on_ operation is assumed to be 1. + +`mbarrier.arrive_drop` operation with `.release` qualifier forms the _release_ pattern as described in the Memory Consistency Model and synchronizes with the _acquire_ patterns. + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.sem` qualifier is absent, `.release` is assumed by default. The `.relaxed` qualifier does not provide any memory ordering semantics and visibility guarantees. + +The optional `.scope` qualifier indicates the set of threads that an `mbarrier.arrive_drop` instruction can directly synchronize. If the `.scope` qualifier is not specified then it defaults to `.cta`. In contrast, the `.shared::` indicates the state space where the mbarrier resides. + +A `mbarrier.arrive_drop` with `.noComplete` qualifier must not complete the `mbarrier,` otherwise the behavior is undefined. + +The value of the operand `count` must be in the range as specified in [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>). + +Note: for `sm_8x`, when the argument `count` is specified, the modifier `.noComplete` is required. + +A thread that wants to either exit or opt out of participating in the [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) can use `mbarrier.arrive_drop` to drop itself from the `mbarrier`. + +`mbarrier.arrive_drop` operation on an _mbarrier object_ located in `.shared::cta` returns an opaque 64-bit register capturing the phase of the _mbarrier object_ prior to the [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) in the destination operand `state`. Contents of the returned state are implementation specific. Optionally, sink symbol `'_'` can be used for the `state` argument. + +`mbarrier.arrive_drop` operation on an _mbarrier_ object located in `.shared::cluster` but not in `.shared::cta` cannot return a value. Sink symbol ‘_’ is mandatory for the destination operand for such cases. + +Qualifiers `.sem` and `.scope` must be specified together. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Support for `count` argument without the modifier `.noComplete` introduced in PTX ISA version 7.8. + +Support for qualifier `.expect_tx` is introduced in PTX ISA version 8.0. + +Support for sub-qualifier `::cluster` introduced in PTX ISA version 8.0. + +Support for `.scope` and `.sem` qualifiers introduced in PTX ISA version 8.0 + +Support for `.relaxed` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_80` or higher. + +Support for `count` argument without the modifier `.noComplete` requires `sm_90` or higher. + +Qualifier `.expect_tx` requires `sm_90` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Support for `.cluster` scope requires `sm_90` or higher. + +Support for `.relaxed` qualifier requires `sm_90` or higher. + +Examples + + + .reg .b32 cnt; + .reg .b64 %r1; + .shared .b64 shMem; + + // Example 1 + @p mbarrier.arrive_drop.shared.b64 _, [shMem]; + @p exit; + @p2 mbarrier.arrive_drop.noComplete.shared.b64 _, [shMem], %a; + @p2 exit; + .. + @!p mbarrier.arrive.shared.b64 %r1, [shMem]; + @!p mbarrier.test_wait.shared.b64 q, [shMem], %r1; + + // Example 2 + mbarrier.arrive_drop.shared::cluster.b64 _, [addr]; + mbarrier.arrive_drop.shared::cta.release.cluster.b64 _, [addr], cnt; + + // Example 3 + mbarrier.arrive_drop.expect_tx.shared::cta.relaxed.cluster.b64 state, [addr], tx_count; + +##### 9.7.13.15.15. [Parallel Synchronization and Communication Instructions: `cp.async.mbarrier.arrive`](<#parallel-synchronization-and-communication-instructions-cp-async-mbarrier-arrive>) + +`cp.async.mbarrier.arrive` + +Makes the _mbarrier object_ track all prior [cp.async](<#data-movement-and-conversion-instructions-cp-async>) operations initiated by the executing thread. + +Syntax + + + cp.async.mbarrier.arrive{.noinc}{.shared{::cta}}.b64 [addr]; + + +Description + +Causes an [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) to be triggered by the system on the _mbarrier object_ upon the completion of all prior [cp.async](<#data-movement-and-conversion-instructions-cp-async>) operations initiated by the executing thread. The _mbarrier object_ is at the location specified by the operand `addr`. The [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) is asynchronous to execution of `cp.async.mbarrier.arrive`. + +When `.noinc` modifier is not specified, the pending count of the mbarrier object is incremented by 1 prior to the asynchronous [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>). This results in a zero-net change for the pending count from the asynchronous [arrive-on](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) operation during the current phase. The pending count of the _mbarrier object_ after the increment should not exceed the limit as mentioned in [Contents of the mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-contents>). Otherwise, the behavior is undefined. + +When the `.noinc` modifier is specified, the increment to the pending count of the _mbarrier object_ is not performed. Hence the decrement of the pending count done by the asynchronous [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) must be accounted for in the initialization of the _mbarrier object_. + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + // Example 1: no .noinc + mbarrier.init.shared.b64 [shMem], threadCount; + .... + cp.async.ca.shared.global [shard1], [gbl1], 4; + cp.async.cg.shared.global [shard2], [gbl2], 16; + .... + // Absence of .noinc accounts for arrive-on from completion of prior cp.async operations. + // So mbarrier.init must only account for arrive-on from mbarrier.arrive. + cp.async.mbarrier.arrive.shared.b64 [shMem]; + .... + mbarrier.arrive.shared.b64 state, [shMem]; + + waitLoop: + mbarrier.test_wait.shared.b64 p, [shMem], state; + @!p bra waitLoop; + + + + // Example 2: with .noinc + + // Tracks arrive-on from mbarrier.arrive and cp.async.mbarrier.arrive. + + // All threads participating in the mbarrier perform cp.async + mov.b32 copyOperationCnt, threadCount; + + // 3 arrive-on operations will be triggered per-thread + mul.lo.u32 copyArrivalCnt, copyOperationCnt, 3; + + add.u32 totalCount, threadCount, copyArrivalCnt; + + mbarrier.init.shared.b64 [shMem], totalCount; + .... + cp.async.ca.shared.global [shard1], [gbl1], 4; + cp.async.cg.shared.global [shard2], [gbl2], 16; + ... + // Presence of .noinc requires mbarrier initalization to have accounted for arrive-on from cp.async + cp.async.mbarrier.arrive.noinc.shared.b64 [shMem]; // 1st instance + .... + cp.async.ca.shared.global [shard3], [gbl3], 4; + cp.async.ca.shared.global [shard4], [gbl4], 16; + cp.async.mbarrier.arrive.noinc.shared::cta.b64 [shMem]; // 2nd instance + .... + cp.async.ca.shared.global [shard5], [gbl5], 4; + cp.async.cg.shared.global [shard6], [gbl6], 16; + cp.async.mbarrier.arrive.noinc.shared.b64 [shMem]; // 3rd and last instance + .... + mbarrier.arrive.shared.b64 state, [shMem]; + + waitLoop: + mbarrier.test_wait.shared.b64 p, [shMem], state; + @!p bra waitLoop; + +##### 9.7.13.15.16. [Parallel Synchronization and Communication Instructions: `mbarrier.test_wait` / `mbarrier.try_wait`](<#parallel-synchronization-and-communication-instructions-mbarrier-test-wait-try-wait>) + +`mbarrier.test_wait`, `mbarrier.try_wait` + +Checks whether the _mbarrier object_ has completed the phase. + +Syntax + + + mbarrier.test_wait{.sem.scope}{.shared{::cta}}.b64 waitComplete, [addr], state; + mbarrier.test_wait.parity{.sem.scope}{.shared{::cta}}.b64 waitComplete, [addr], phaseParity; + + mbarrier.try_wait{.sem.scope}{.shared{::cta}}.b64 waitComplete, [addr], state + {, suspendTimeHint}; + + mbarrier.try_wait.parity{.sem.scope}{.shared{::cta}}.b64 waitComplete, [addr], phaseParity + {, suspendTimeHint}; + + .sem = { .acquire, .relaxed } + .scope = { .cta, .cluster } + + +Description + +The _test_wait_ and _try_wait_ operations test for the completion of the current or the immediately preceding phase of an _mbarrier object_ at the location specified by the operand `addr`. + +`mbarrier.test_wait` is a non-blocking instruction which tests for the completion of the phase. + +`mbarrier.try_wait` is a potentially blocking instruction which tests for the completion of the phase. If the phase is not complete, the executing thread may be suspended. Suspended thread resumes execution when the specified phase completes OR before the phase completes following a system-dependent time limit. The optional 32-bit unsigned integer operand `suspendTimeHint` specifies the time limit, in nanoseconds, that may be used for the time limit instead of the system-dependent limit. + +`mbarrier.test_wait` and `mbarrier.try_wait` test for completion of the phase : + + * Specified by the 64-bit unsigned integer operand `state`, which was returned by an `mbarrier.arrive` instruction on the same _mbarrier object_ during the current or the immediately preceding phase. Or + + * Indicated by the 32-bit unsigned integer operand `phaseParity`, which is the integer parity of either the current phase or the immediately preceding phase of the _mbarrier object_. + + +The `.parity` variant of the instructions test for the completion of the phase indicated by the operand `phaseParity`, which is the integer parity of either the current phase or the immediately preceding phase of the _mbarrier object_. An even phase has integer parity 0 and an odd phase has integer parity of 1. So the valid values of `phaseParity` operand are 0 and 1. + +Note: the use of the `.parity` variants of the instructions requires tracking the phase of an _mbarrier object_ throughout its lifetime. + +The _test_wait_ and _try_wait_ operations are valid only for : + + * the current incomplete phase, for which `waitComplete` returns `False`. + + * the immediately preceding phase, for which `waitComplete` returns `True`. + + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `addr` does not fall within the address window of `.shared::cta` state space then the behavior is undefined. + +Supported addressing modes for operand `addr` is as described in [Addresses as Operands](<#addresses-as-operands>). Alignment for operand `addr` is as described in the [Size and alignment of mbarrier object](<#parallel-synchronization-and-communication-instructions-mbarrier-size-alignment>). + +When `mbarrier.test_wait` and `mbarrier.try_wait` operations with `.acquire` qualifier returns `True`, they form the _acquire_ pattern as described in the [Memory Consistency Model](<#memory-consistency-model>). + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.sem` qualifier is absent, `.acquire` is assumed by default. The `.relaxed` qualifier does not provide any memory ordering semantics and visibility guarantees. + +The optional `.scope` qualifier indicates the set of threads that the `mbarrier.test_wait` and `mbarrier.try_wait` instructions can directly synchronize. If the `.scope` qualifier is not specified then it defaults to `.cta`. In contrast, the `.shared::` indicates the state space where the mbarrier resides. + +Qualifiers `.sem` and `.scope` must be specified together. + +The following ordering of memory operations hold for the executing thread when `mbarrier.test_wait` or `mbarrier.try_wait` having acquire semantics returns `True` : + + 1. All memory accesses (except [async operations](<#data-movement-and-conversion-instructions-cp-async>)) requested prior, in program order, to `mbarrier.arrive` having release semantics during the completed phase by the participating threads of the CTA are performed and are visible to the executing thread. + + 2. All [cp.async](<#data-movement-and-conversion-instructions-cp-async>) operations requested prior, in program order, to `cp.async.mbarrier.arrive` during the completed phase by the participating threads of the CTA are performed and made visible to the executing thread. + + 3. All `cp.async.bulk` asynchronous operations using the same _mbarrier object_ requested prior, in program order, to `mbarrier.arrive` having release semantics during the completed phase by the participating threads of the CTA are performed and made visible to the executing thread. + + 4. All memory accesses requested after the `mbarrier.test_wait` or `mbarrier.try_wait`, in program order, are not performed and not visible to memory accesses performed prior to `mbarrier.arrive` having release semantics, in program order, by other threads participating in the `mbarrier`. + + 5. There is no ordering and visibility guarantee for memory accesses requested by the thread after `mbarrier.arrive` having release semantics and prior to `mbarrier.test_wait`, in program order. + + +PTX ISA Notes + +`mbarrier.test_wait` introduced in PTX ISA version 7.0. + +Modifier `.parity` is introduced in PTX ISA version 7.1. + +`mbarrier.try_wait` introduced in PTX ISA version 7.8. + +Support for sub-qualifier `::cta` on `.shared` introduced in PTX ISA version 7.8. + +Support for `.scope` and `.sem` qualifiers introduced in PTX ISA version 8.0 + +Support for `.relaxed` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +`mbarrier.test_wait` requires `sm_80` or higher. + +`mbarrier.try_wait` requires `sm_90` or higher. + +Support for `.cluster` scope requires `sm_90` or higher. + +Support for `.relaxed` qualifier requires `sm_90` or higher. + +Examples + + + // Example 1a, thread synchronization with test_wait: + + .reg .b64 %r1; + .shared .b64 shMem; + + mbarrier.init.shared.b64 [shMem], N; // N threads participating in the mbarrier. + ... + mbarrier.arrive.shared.b64 %r1, [shMem]; // N threads executing mbarrier.arrive + + // computation not requiring mbarrier synchronization... + + waitLoop: + mbarrier.test_wait.shared.b64 complete, [shMem], %r1; + @!complete nanosleep.u32 20; + @!complete bra waitLoop; + + // Example 1b, thread synchronization with try_wait : + + .reg .b64 %r1; + .shared .b64 shMem; + + mbarrier.init.shared.b64 [shMem], N; // N threads participating in the mbarrier. + ... + mbarrier.arrive.shared.b64 %r1, [shMem]; // N threads executing mbarrier.arrive + + // computation not requiring mbarrier synchronization... + + waitLoop: + mbarrier.try_wait.relaxed.cluster.shared.b64 complete, [shMem], %r1; + @!complete bra waitLoop; + + + // Example 2, thread synchronization using phase parity : + + .reg .b32 i, parArg; + .reg .b64 %r1; + .shared .b64 shMem; + + mov.b32 i, 0; + mbarrier.init.shared.b64 [shMem], N; // N threads participating in the mbarrier. + ... + loopStart : // One phase per loop iteration + ... + mbarrier.arrive.shared.b64 %r1, [shMem]; // N threads + ... + and.b32 parArg, i, 1; + waitLoop: + mbarrier.test_wait.parity.shared.b64 complete, [shMem], parArg; + @!complete nanosleep.u32 20; + @!complete bra waitLoop; + ... + add.u32 i, i, 1; + setp.lt.u32 p, i, IterMax; + @p bra loopStart; + + + // Example 3, Asynchronous copy completion waiting : + + .reg .b64 state; + .shared .b64 shMem2; + .shared .b64 shard1, shard2; + .global .b64 gbl1, gbl2; + + mbarrier.init.shared.b64 [shMem2], threadCount; + ... + cp.async.ca.shared.global [shard1], [gbl1], 4; + cp.async.cg.shared.global [shard2], [gbl2], 16; + + // Absence of .noinc accounts for arrive-on from prior cp.async operation + cp.async.mbarrier.arrive.shared.b64 [shMem2]; + ... + mbarrier.arrive.shared.b64 state, [shMem2]; + + waitLoop: + mbarrier.test_wait.shared::cta.b64 p, [shMem2], state; + @!p bra waitLoop; + + // Example 4, Synchronizing the CTA0 threads with cluster threads + .reg .b64 %r1, addr, remAddr; + .shared .b64 shMem; + + cvta.shared.u64 addr, shMem; + mapa.u64 remAddr, addr, 0; // CTA0's shMem instance + + // One thread from CTA0 executing the below initialization operation + @p0 mbarrier.init.shared::cta.b64 [shMem], N; // N = no of cluster threads + + barrier.cluster.arrive; + barrier.cluster.wait; + + // Entire cluster executing the below arrive operation + mbarrier.arrive.release.cluster.b64 _, [remAddr]; + + // computation not requiring mbarrier synchronization ... + + // Only CTA0 threads executing the below wait operation + waitLoop: + mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 complete, [shMem], 0; + @!complete bra waitLoop; + +##### 9.7.13.15.17. [Parallel Synchronization and Communication Instructions: `mbarrier.pending_count`](<#parallel-synchronization-and-communication-instructions-mbarrier-pending-count>) + +`mbarrier.pending_count` + +Query the pending arrival count from the opaque mbarrier state. + +Syntax + + + mbarrier.pending_count.b64 count, state; + + +Description + +The pending count can be queried from the opaque mbarrier state using `mbarrier.pending_count`. + +The `state` operand is a 64-bit register that must be the result of a prior `mbarrier.arrive.noComplete` or `mbarrier.arrive_drop.noComplete` instruction. Otherwise, the behavior is undefined. + +The destination register `count` is a 32-bit unsigned integer representing the pending count of the _mbarrier object_ prior to the [arrive-on operation](<#parallel-synchronization-and-communication-instructions-mbarrier-arrive-on>) from which the `state` register was obtained. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + + + .reg .b32 %r1; + .reg .b64 state; + .shared .b64 shMem; + + mbarrier.arrive.noComplete.b64 state, [shMem], 1; + mbarrier.pending_count.b64 %r1, state; \ No newline at end of file diff --git a/content/cuda/docs/ptx-membarfence/DOC.md b/content/cuda/docs/ptx-membarfence/DOC.md new file mode 100644 index 00000000..3ed32ca8 --- /dev/null +++ b/content/cuda/docs/ptx-membarfence/DOC.md @@ -0,0 +1,176 @@ +--- +name: ptx-membarfence +description: Enforce an ordering of memory operations. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.4. Parallel Synchronization and Communication Instructions:membar/fence + +--- +title: "9.7.13.4. Parallel Synchronization and Communication Instructions:membar/fence" +section: 9.7.13.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.4. Parallel Synchronization and Communication Instructions:membar/fence + + +`membar`, `fence` + +Enforce an ordering of memory operations. + +Syntax + +// Thread fence: + fence{.sem}.scope; + + // Thread fence: + fence.acquire.sync_restrict::shared::cluster.cluster; + fence.release.sync_restrict::shared::cta.cluster; + + // Operation fence: + fence.op_restrict.release.cluster; + + // Proxy fence (bi-directional): + fence.proxy.proxykind; + + // Proxy fence (uni-directional): + fence.proxy.to_proxykind::from_proxykind.release.scope; + fence.proxy.to_proxykind::from_proxykind.acquire.scope [addr], size; + fence.proxy.async::generic.acquire.sync_restrict::shared::cluster.cluster; + fence.proxy.async::generic.release.sync_restrict::shared::cta.cluster; + + // Old style membar: + membar.level; + membar.proxy.proxykind; + + .sem = { .sc, .acq_rel, .acquire, .release }; + .scope = { .cta, .cluster, .gpu, .sys }; + .level = { .cta, .gl, .sys }; + .proxykind = { .alias, .async, .async.global, .async.shared::{cta, cluster} }; + .op_restrict = { .mbarrier_init }; + .to_proxykind::from_proxykind = {.tensormap::generic}; + +Description + +The `membar` instruction guarantees that prior memory accesses requested by this thread (`ld`, `st`, `atom` and `red` instructions) are performed at the specified `level`, before later memory operations requested by this thread following the `membar` instruction. The `level` qualifier specifies the set of threads that may observe the ordering effect of this operation. + +A memory read (e.g., by `ld` or `atom`) has been performed when the value read has been transmitted from memory and cannot be modified by another thread at the indicated level. A memory write (e.g., by `st`, `red` or `atom`) has been performed when the value written has become visible to other threads at the specified level, that is, when the previous value can no longer be read. + +The `fence` instruction establishes an ordering between memory accesses requested by this thread (`ld`, `st`, `atom` and `red` instructions) as described in the [Memory Consistency Model](<#memory-consistency-model>). The scope qualifier specifies the set of threads that may observe the ordering effect of this operation. + +`fence.acq_rel` is a light-weight fence that is sufficient for memory synchronization in most programs. Instances of `fence.acq_rel` synchronize when combined with additional memory operations as described in `acquire` and `release` patterns in the [Memory Consistency Model](<#memory-consistency-model>). If the optional `.sem` qualifier is absent, `.acq_rel` is assumed by default. + +`fence.sc` is a slower fence that can restore _sequential consistency_ when used in sufficient places, at the cost of performance. Instances of `fence.sc` with sufficient scope always synchronize by forming a total order per scope, determined at runtime. This total order can be constrained further by other synchronization in the program. + +Qualifiers `.op_restrict` and `.sync_restrict` restrict the class of memory operations for which the `fence` instruction provides the memory ordering guarantees. When `.op_restrict` is `.mbarrier_init`, the synchronizing effect of the fence only applies to the prior `mbarrier.init` operations executed by the same thread on _mbarrier objects_ in `.shared::cta` state space. When `.sync_restrict` is `.sync_restrict::shared::cta`, `.sem` must be `.release`, and the effect of the fence only applies to operations performed on objects in `.shared::cta` state space. Likewise, when `.sync_restrict` is `.sync_restrict::shared::cluster`, `.sem` must be `.acquire`, and the effect of the fence only applies to operations performed on objects in `.shared::cluster` state space. When either `.sync_restrict::shared::cta` or `.sync_restrict::shared::cluster` is present, the `.scope` must be specified as `.cluster`. + +The address operand `addr` and the operand `size` together specify the memory range `[addr, addr+size-1]` on which the ordering guarantees on the memory accesses across the proxies is to be provided. The only supported value for the `size` operand is 128, which must be a constant integer literal. [Generic Addressing](<#generic-addressing>) is used unconditionally, and the address specified by the operand `addr` must fall within the `.global` state space. Otherwise, the behavior is undefined. + +On `sm_70` and higher `membar` is a synonym for `fence.sc`1, and the `membar` levels `cta`, `gl` and `sys` are synonymous with the `fence` scopes `cta`, `gpu` and `sys` respectively. + +`membar.proxy` and `fence.proxy` instructions establish an ordering between memory accesses that may happen through different _proxies_. + +A _uni-directional_ proxy ordering from the _from-proxykind_ to the _to-proxykind_ establishes ordering between a prior memory access performed via the _from-proxykind_ and a subsequent memory access performed via the _to-proxykind_. + +A _bi-directional_ proxy ordering between two proxykinds establishes two _uni-directional_ proxy orderings : one from the first proxykind to the second proxykind and the other from the second proxykind to the first proxykind. + +The `.proxykind` qualifier indicates the _bi-directional_ proxy ordering that is established between the memory accesses done between the generic proxy and the proxy specified by `.proxykind`. + +Value `.alias` of the `.proxykind` qualifier refers to memory accesses performed using virtually aliased addresses to the same memory location. Value `.async` of the `.proxykind` qualifier specifies that the memory ordering is established between the async proxy and the generic proxy. The memory ordering is limited only to operations performed on objects in the state space specified. If no state space is specified, then the memory ordering applies on all state spaces. + +A `.release` proxy fence can form a release sequence that synchronizes with an acquire sequence that contains a `.acquire` proxy fence. The `.to_proxykind` and `.from_proxykind` qualifiers indicate the _uni-directional_ proxy ordering that is established. + +On `sm_70` and higher, `membar.proxy` is a synonym for `fence.proxy`. + +1 The semantics of `fence.sc` introduced with `sm_70` is a superset of the semantics of `membar` and the two are compatible; when executing on `sm_70` or later architectures, `membar` acquires the full semantics of `fence.sc`. + +PTX ISA Notes + +`membar.{cta,gl}` introduced in PTX ISA version 1.4. + +`membar.sys` introduced in PTX ISA version 2.0. + +`fence` introduced in PTX ISA version 6.0. + +`membar.proxy` and `fence.proxy` introduced in PTX ISA version 7.5. + +`.cluster` scope qualifier introduced in PTX ISA version 7.8. + +`.op_restrict` qualifier introduced in PTX ISA version 8.0. + +`fence.proxy.async` is introduced in PTX ISA version 8.0. + +`.to_proxykind::from_proxykind` qualifier introduced in PTX ISA version 8.3. + +`.acquire` and `.release` qualifiers for `fence` instruction introduced in PTX ISA version 8.6. + +`.sync_restrict` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +`membar.{cta,gl}` supported on all target architectures. + +`membar.sys` requires `sm_20` or higher. + +`fence` requires `sm_70` or higher. + +`membar.proxy` requires `sm_60` or higher. + +`fence.proxy` requires `sm_70` or higher. + +`.cluster` scope qualifier requires `sm_90` or higher. + +`.op_restrict` qualifier requires `sm_90` or higher. + +`fence.proxy.async` requires `sm_90` or higher. + +`.to_proxykind::from_proxykind` qualifier requires `sm_90` or higher. + +`.acquire` and `.release` qualifiers for `fence` instruction require `sm_90` or higher.. + +`.sync_restrict` qualifier requires `sm_90` or higher.. + +Examples + +membar.gl; + membar.cta; + membar.sys; + fence.sc.cta; + fence.sc.cluster; + fence.proxy.alias; + membar.proxy.alias; + fence.mbarrier_init.release.cluster; + fence.proxy.async; + fence.proxy.async.shared::cta; + fence.proxy.async.shared::cluster; + fence.proxy.async.global; + + tensormap.replace.tile.global_address.global.b1024.b64 [gbl], new_addr; + fence.proxy.tensormap::generic.release.gpu; + cvta.global.u64 tmap, gbl; + fence.proxy.tensormap::generic.acquire.gpu [tmap], 128; + cp.async.bulk.tensor.1d.shared::cluster.global.tile [addr0], [tmap, {tc0}], [mbar0]; + + // Acquire remote barrier state via async proxy. + barrier.cluster.wait.acquire; + fence.proxy.async::generic.acquire.sync_restrict::shared::cluster.cluster; + + // Release local barrier state via generic proxy. + mbarrier.init [bar]; + fence.mbarrier_init.release.cluster; + barrier.cluster.arrive.relaxed; + + // Acquire local shared memory via generic proxy. + mbarrier.try_wait.relaxed.cluster.shared::cta.b64 complete, [addr], parity; + fence.acquire.sync_restrict::shared::cluster.cluster; + + // Release local shared memory via generic proxy. + fence.release.sync_restrict::shared::cta.cluster; + mbarrier.arrive.relaxed.cluster.shared::cluster.b64 state, [bar]; \ No newline at end of file diff --git a/content/cuda/docs/ptx-memory-consistency-model-for-5th-generation-of-tensorcore-operations/DOC.md b/content/cuda/docs/ptx-memory-consistency-model-for-5th-generation-of-tensorcore-operations/DOC.md new file mode 100644 index 00000000..90e0b49b --- /dev/null +++ b/content/cuda/docs/ptx-memory-consistency-model-for-5th-generation-of-tensorcore-operations/DOC.md @@ -0,0 +1,296 @@ +--- +name: ptx-memory-consistency-model-for-5th-generation-of-tensorcore-operations +description: 'Ordering of `tcgen05` instructions is described in terms of two key + concepts:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.16.6. Memory Consistency Model for 5th generation of TensorCore operations + +--- +title: "9.7.16.6. Memory Consistency Model for 5th generation of TensorCore operations" +section: 9.7.16.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.16.6. Memory Consistency Model for 5th generation of TensorCore operations + + +Ordering of `tcgen05` instructions is described in terms of two key concepts: + +1. Pipelined tcgen05 instructions + + 2. Specialized tcgen05-specific inter-thread synchronization mechanisms. + +These concepts combine to form four canonical synchronization patterns, as described further below. + +##### 9.7.16.6.1. [Asynchronous Operations](<#tcgen05-memory-consistency-model-async-operations>) + +The tcgen05 family of instructions are divided into 2 categories: + + 1. Asynchronous instructions: + +These `tcgen05` operations are not inherently ordered with respect to other `tcgen05` operations in the same thread (unless pipelined as mentioned below). + + 2. Synchronous instructions: + +These `tcgen05` operations are inherently ordered with respect to other `tcgen05` operations in the same order. + +The Tensor Memory allocation related instructions that access shared memory maintain same-address ordering with respect to non-`tcgen05` instructions. + + +The following table lists the category of each of the `tcgen05` instruction: + +tcgen05.* operation | Category +---|--- +`.alloc` | Synchronous instructions +`.dealloc` +`.relinquish_alloc_permit` +`.fence::*` +`.wait::*` +`.commit` +`.mma` | Asynchronous instructions +`.cp` +`.shift` +`.ld` +`.st` + +##### 9.7.16.6.2. [Pipelined tcgen05 Instructions](<#tcgen05-memory-consistency-model-pipelined-instructions>) + +The asynchronous `tcgen05` operations may execute and complete in a different order than they were issued. However, some specific pairs of the asynchronous `tcgen05` instructions form `tcgen05` pipelines, where in the two asynchronous operations are guaranteed to execute in the same order as the instructions that issued them. The specific pairings are as follows: + + 1. `tcgen05.mma.cta_group::N` -> `tcgen05.mma.cta_group::N` (same N and accumulator and shape) + + 2. `tcgen05.copy.cta_group::N` -> `tcgen05.mma.cta_group::N` (same N) + + 3. `tcgen05.shift.cta_group::N` -> `tcgen05.mma.cta_group::N` (same N) + + 4. `tcgen05.shift.cta_group::N` -> `tcgen05.cp.4x256b.cta_group::N` (same N) + + 5. `tcgen05.mma.cta_group::N` -> `tcgen05.shift.cta_group::N` (same N) + + +###### 9.7.16.6.2.1. [Implicitly pipelined tcgen05 Instructions](<#tcgen05-memory-consistency-model-pipelined-instructions-implicit>) + +Instructions `tcgen05.commit` and `tcgen05.wait` are implicitly pipelined with respect to previously issued `tcgen05.{mma,cp,shift}` and `tcgen05.{ld,st}` instructions respectively that they track from the same thread. + +####### 9.7.16.6.2.1.1. [mbarrier based completion mechanism](<#tcgen05-memory-consistency-model-mbarrier-completion>) + +Completion of the following instruction’s asynchronous operations is observed through the mbarrier based waiting mechanism: + + 1. `tcgen05.mma` + + 2. `tcgen05.cp` + + 3. `tcgen05.shift` + + +`tcgen05.commit` is used to track the completion of the above asynchronous instructions. + +Following are the implicitly pipelined `tcgen05` instruction pairing that uses mbarrier based completion mechanism: + + * `tcgen05.mma.cta_group::N` -> `tcgen05.commit.cta_group::N` (same N) + + * `tcgen05.cp.cta_group::N` -> `tcgen05.commit.cta_group::N` (same N) + + * `tcgen05.shift.cta_group::N` -> `tcgen05.commit.cta_group::N` (same N) + + +####### 9.7.16.6.2.1.2. [`tcgen05.wait` instruction based completion mechanism](<#tcgen05-memory-consistency-model-wait-completion>) + +Completion of the following instruction’s asynchronous operations is observed through `tcgen05.wait` based waiting mechanism: + + 1. `tcgen05.ld` + + 2. `tcgen05.st` + + +`tcgen05.wait::ld` and `tcgen05.wait::st` is used to track the completion of the `tcgen05.ld` and `tcgen05.st` asynchronous instructions. + +Following are the implicitly pipelined `tcgen05` instruction pairing that uses `tcgen05.wait` based completion mechanism: + + * `tcgen05.ld` -> `tcgen05.wait::ld` + + * `tcgen05.st` -> `tcgen05.wait::st` + +##### 9.7.16.6.3. [Specialized Inter-thread Synchronization for tcgen05 instructions](<#tcgen05-memory-consistency-model-inter-thread-sync>) + +The `tcgen05` instructions support a specialized inter-thread synchronization which are optimized for `tcgen05` family of instructions. The standard memory consistency model synchronization mechanisms also apply to the `tcgen05` family of instructions. + +The [TensorCore 5th Generation Specialized Synchronization Operations](<#tcgen05-special-sync-operations>) section contains the specialized inter-thread synchronization for tcgen05 instructions. + +The `tcgen05.fence::before_thread_sync` and `tcgen05.fence::after_thread_sync` composes with execution ordering instructions, like morally strong `ld`/`st`/`atom` instructions, `mbarrier` instruction, `barrier` instructions and so on, to establish an ordering between the `tcgen05` operations across threads. The asynchronous `tcgen05` instructions that are ordered across threads also form a `tcgen05` pipeline. + +An asynchronous `tcgen05` operation prior to a `tcgen05.fence::before_thread_sync` is ordered before all subsequent `tcgen05` and the execution ordering operations. + +An asynchronous `tcgen05` operation subsequent to a `tcgen05.fence::after_thread_sync` is ordered after all the prior `tcgen05` and the execution ordering operations. + +##### 9.7.16.6.4. [Canonical synchronization patterns](<#tcgen05-memory-consistency-model-canonical-sync-patterns>) + +Using the above rules, the following are the five canonical synchronization patterns: + +###### 9.7.16.6.4.1. [Pipelined instructions, same thread](<#tcgen05-memory-consistency-model-canonical-sync-patterns-pipelined-same-thread>) + +In this pattern, no explicit ordering mechanism is needed and the ordering guarantee is provided by the pipelined instruction pairing. + +Example: + + + tcgen05.mma + tcgen05.mma (same shape and accumulator) + + +The two instructions will be executed in program order. + +###### 9.7.16.6.4.2. [Non-pipelined instructions, same thread](<#tcgen05-memory-consistency-model-canonical-sync-patterns-non-pipelined-same-thread>) + +In this pattern, explicit waiting mechanisms are used to wait for the completion of the asynchronous `tcgen05` operations. + +Example 1: + + + tcgen05.st + tcgen05.wait::st + tcgen05.ld + + +`tcgen05.wait::st` is used to wait for the completion of the prior asynchronous instruction `tcgen05.st`. + +Example 2: + + + tcgen05.mma [d], ... + tcgen05.commit.mbarrier::arrive::one + mbarrier.try_wait.relaxed.cluster (loop until successful) + tcgen05.fence::after_thread_sync + tcgen05.ld [d], ... + + +For the completion of the asynchronous `tcgen05.mma`, `tcgen05.commit` is used. + +As `tcgen05.ld` is an asynchronous operation, the instruction `tcgen05.fence::after_thread_sync` is needed. + +No explicit `tcgen05.fence::before_thread_sync` is needed as this is implicitly performed by `tcgen05.commit`. The combination of `tcgen05.mma` and `tcgen05.commit` forms a conceptual asynchronous pipeline and establishes execution ordering. + + + tcgen05.mma [d], ... + tcgen05.fence::before_thread_sync + mbarrier::arrive + + +###### 9.7.16.6.4.3. [Pipelined instructions, different thread](<#tcgen05-memory-consistency-model-canonical-sync-patterns-pipelined-diff-thread>) + +In this pattern, no explicit waiting mechanism is needed but proper synchronization between threads is needed. + +Example: + +Thread 0 | Thread 1 +---|--- + + + tcgen05.cp + tcgen05.fence::before_thread_sync + mbarrier.arrive.relaxed.cluster + + +| +| + + + mbarrier.try_wait.relaxed.cluster // loop till success + tcgen05.fence::after_thread_sync + tcgen05.mma + + +###### 9.7.16.6.4.4. [Non-pipelined instructions, different thread](<#tcgen05-memory-consistency-model-canonical-sync-patterns-non-pipelined-diff-thread>) + +In this pattern, the producer threads that issue the asynchronous `tcgen05` instructions must explicitly wait for the instructions’ completion before synchronizing with the consumer threads. + +Example 1: + +Thread 0 | Thread 1 +---|--- + + + tcgen05.ld + tcgen05.wait::ld + tcgen05.fence::before_thread_sync + mbarrier.arrive.relaxed.cluster + + +| +| + + + mbarrier.try_wait.relaxed.cluster // loop till success + tcgen05.fence::after_thread_sync + tcgen05.mma + + +Example 1: + +Thread 0 | Thread 1 +---|--- + + + tcgen05.mma + tcgen05.commit.mbarrier::arrive::one [mbar] + + +| +| + + + mbarrier.try_wait.relaxed.cluster [mbar] // loop till success + tcgen05.fence::after_thread_sync + tcgen05.ld + + +The synchronization mechanisms can also be composed with each other. For example: + +Thread 0 | Thread 1 +---|--- + + + tcgen05.mma + tcgen05.commit.mbarrier::arrive::one [bar1] + mbarrier.try_wait.relaxed.cluster [bar1] // loop + ... + tcgen05.fence::after_thread_sync + ...// completion is guaranteed + tcgen05.fence::before_thread_sync + mbarrier.arrive.relaxed.cluster [bar2] // loop + ... + + +| +| + + + mbarrier.try_wait.relaxed.cluster [bar2] // loop + ... + tcgen05.fence::after_thread_sync + tcgen05.ld + + +###### 9.7.16.6.4.5. [Register dependencies, same thread](<#tcgen05-memory-consistency-model-canonical-sync-patterns-reg-dependency-same-thread>) + +For `tcgen05.ld`, an intra-thread ordering through true register dependency will be respected regardless of the presence or absence of other forms of synchronization. This form of register dependency does not imply any other form of ordering. For example, a register dependency does not imply that a dependee instruction’s memory accesses will be performed before a dependent instruction’s memory accesses. To enforce such memory orderings and avoiding anti-dependency hazards around `tcgen05.ld`, `tcgen05.wait::ld` must be used. + +Example: + + + tcgen05.ld %r1, ...; + tcgen05.mma ..., %r1, ...; + +##### 9.7.16.6.5. [Shared Memory Accesses](<#tcgen05-memory-consistency-model-smem-access>) + +The shared memory accesses by `tcgen05.mma` and `tcgen05.cp` operations are performed in the asynchronous proxy (async proxy). + +Accessing the same memory location across miltiple proxies needs a cross-proxy fence. For the async proxy, `fence.proxy.async` should be used to synchronize memory between generic proxy and the async proxy. \ No newline at end of file diff --git a/content/cuda/docs/ptx-memory-hierarchy/DOC.md b/content/cuda/docs/ptx-memory-hierarchy/DOC.md new file mode 100644 index 00000000..b0c1da1b --- /dev/null +++ b/content/cuda/docs/ptx-memory-hierarchy/DOC.md @@ -0,0 +1,36 @@ +--- +name: ptx-memory-hierarchy +description: PTX threads may access data from multiple state spaces during their execution + as illustrated by [Figure 3](<#memory-hierarchy-memory-hierarchy-with-clusters>) + where cluster level is introduced from ta... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 2.3. Memory Hierarchy + +--- +title: "2.3. Memory Hierarchy" +section: 2.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 2.3. Memory Hierarchy + + +PTX threads may access data from multiple state spaces during their execution as illustrated by [Figure 3](<#memory-hierarchy-memory-hierarchy-with-clusters>) where cluster level is introduced from target architecture `sm_90` onwards. Each thread has a private local memory. Each thread block (CTA) has a shared memory visible to all threads of the block and to all active blocks in the cluster and with the same lifetime as the block. Finally, all threads have access to the same global memory. + +There are additional state spaces accessible by all threads: the constant, param, texture, and surface state spaces. Constant and texture memory are read-only; surface memory is readable and writable. The global, constant, param, texture, and surface state spaces are optimized for different memory usages. For example, texture memory offers different addressing modes as well as data filtering for specific data formats. Note that texture and surface memory is cached, and within the same kernel call, the cache is not kept coherent with respect to global memory writes and surface memory writes, so any texture fetch or surface read to an address that has been written to via a global or a surface write in the same kernel call returns undefined data. In other words, a thread can safely read some texture or surface memory location only if this memory location has been updated by a previous kernel call or memory copy, but not if it has been previously updated by the same thread or another thread from the same kernel call. + +The global, constant, and texture state spaces are persistent across kernel launches by the same application. + +Both the host and the device maintain their own local memory, referred to as _host memory_ and _device memory_ , respectively. The device memory may be mapped and read or written by the host, or, for more efficient transfer, copied from the host memory through optimized API calls that utilize the device’s high-performance _Direct Memory Access (DMA)_ engine. + +![Memory Hierarchy](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/memory-hierarchy-with-clusters.png) + +Figure 3 Memory Hierarchy \ No newline at end of file diff --git a/content/cuda/docs/ptx-memory-operations-on-packed-data-types/DOC.md b/content/cuda/docs/ptx-memory-operations-on-packed-data-types/DOC.md new file mode 100644 index 00000000..43388c42 --- /dev/null +++ b/content/cuda/docs/ptx-memory-operations-on-packed-data-types/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-memory-operations-on-packed-data-types +description: A packed data type consists of two values of the same scalar data type, + as described in [Packed Data Types](<#packed-data-types>). These values are accessed + in adjacent memory locations. A memory oper... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.5. Memory Operations on Packed Data Types + +--- +title: "8.2.5. Memory Operations on Packed Data Types" +section: 8.2.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.5. Memory Operations on Packed Data Types + + +A packed data type consists of two values of the same scalar data type, as described in [Packed Data Types](<#packed-data-types>). These values are accessed in adjacent memory locations. A memory operation on a packed data type is modelled as a pair of equivalent memory operations on the scalar data type, executed in an unspecified order on each element of the packed data. \ No newline at end of file diff --git a/content/cuda/docs/ptx-memory-operations-on-vector-data-types/DOC.md b/content/cuda/docs/ptx-memory-operations-on-vector-data-types/DOC.md new file mode 100644 index 00000000..a00ea55d --- /dev/null +++ b/content/cuda/docs/ptx-memory-operations-on-vector-data-types/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-memory-operations-on-vector-data-types +description: The memory consistency model relates operations executed on memory locations + with scalar data types, which have a maximum size and alignment of 64 bits. Memory + operations with a vector data type are m... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.4. Memory Operations on Vector Data Types + +--- +title: "8.2.4. Memory Operations on Vector Data Types" +section: 8.2.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.4. Memory Operations on Vector Data Types + + +The memory consistency model relates operations executed on memory locations with scalar data types, which have a maximum size and alignment of 64 bits. Memory operations with a vector data type are modelled as a set of equivalent memory operations with a scalar data type, executed in an unspecified order on the elements in the vector. \ No newline at end of file diff --git a/content/cuda/docs/ptx-memory-synchronization/DOC.md b/content/cuda/docs/ptx-memory-synchronization/DOC.md new file mode 100644 index 00000000..e9dd483e --- /dev/null +++ b/content/cuda/docs/ptx-memory-synchronization/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-memory-synchronization +description: Synchronizing operations performed by different threads synchronize with + each other at runtime as described here. The effect of such synchronization is to + establish _causality order_ across threads. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.4. Memory synchronization + +--- +title: "8.9.4. Memory synchronization" +section: 8.9.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.4. Memory synchronization + + +Synchronizing operations performed by different threads synchronize with each other at runtime as described here. The effect of such synchronization is to establish _causality order_ across threads. + +1. A `fence.sc` operation X _synchronizes_ with a `fence.sc` operation Y if X precedes Y in the _Fence-SC_ order. + + 2. A `bar{.cta}.sync` or `bar{.cta}.red` or `bar{.cta}.arrive` operation _synchronizes_ with a `bar{.cta}.sync` or `bar{.cta}.red` operation executed on the same barrier. + + 3. A `barrier.cluster.arrive` operation synchronizes with a `barrier.cluster.wait` operation. + + 4. A _release_ pattern X _synchronizes_ with an _acquire_ pattern Y, if a _write_ operation in X precedes a _read_ operation in Y in _observation order_ , and the first operation in X and the last operation in Y are _morally strong_. + +API synchronization + +A _synchronizes_ relation can also be established by certain CUDA APIs. + +1. Completion of a task enqueued in a CUDA stream _synchronizes_ with the start of the following task in the same stream, if any. + + 2. For purposes of the above, recording or waiting on a CUDA event in a stream, or causing a cross-stream barrier to be inserted due to `cudaStreamLegacy`, enqueues tasks in the associated streams even if there are no direct side effects. An event record task _synchronizes_ with matching event wait tasks, and a barrier arrival task _synchronizes_ with matching barrier wait tasks. + + 3. Start of a CUDA kernel _synchronizes_ with start of all threads in the kernel. End of all threads in a kernel _synchronize_ with end of the kernel. + + 4. Start of a CUDA graph _synchronizes_ with start of all source nodes in the graph. Completion of all sink nodes in a CUDA graph _synchronizes_ with completion of the graph. Completion of a graph node _synchronizes_ with start of all nodes with a direct dependency. + + 5. Start of a CUDA API call to enqueue a task _synchronizes_ with start of the task. + + 6. Completion of the last task queued to a stream, if any, _synchronizes_ with return from `cudaStreamSynchronize`. Completion of the most recently queued matching event record task, if any, _synchronizes_ with return from `cudaEventSynchronize`. Synchronizing a CUDA device or context behaves as if synchronizing all streams in the context, including ones that have been destroyed. + + 7. Returning `cudaSuccess` from an API to query a CUDA handle, such as a stream or event, behaves the same as return from the matching synchronization API. + +In addition to establishing a _synchronizes_ relation, the CUDA API synchronization mechanisms above also participate in _proxy-preserved base causality order_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-min/DOC.md b/content/cuda/docs/ptx-min/DOC.md new file mode 100644 index 00000000..eefdd3e2 --- /dev/null +++ b/content/cuda/docs/ptx-min/DOC.md @@ -0,0 +1,126 @@ +--- +name: ptx-min +description: Find the minimum of two values. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.4.7. Half Precision Floating Point Instructions:min + +--- +title: "9.7.4.7. Half Precision Floating Point Instructions:min" +section: 9.7.4.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.4.7. Half Precision Floating Point Instructions:min + + +`min` + +Find the minimum of two values. + +Syntax + +min{.ftz}{.NaN}{.xorsign.abs}.f16 d, a, b; + min{.ftz}{.NaN}{.xorsign.abs}.f16x2 d, a, b; + min{.NaN}{.xorsign.abs}.bf16 d, a, b; + min{.NaN}{.xorsign.abs}.bf16x2 d, a, b; + +Description + +Store the minimum of `a` and `b` in `d`. + +For `.f16x2` and `.bf16x2` instruction types, input vectors are formed with half-word values from source operands. Half-word operands are then processed in parallel to store `.f16x2` or `.bf16x2` result in destination. + +For `.f16` instruction type, operands `d` and `a` have `.f16` or `.b16` type. For `.f16x2` instruction type, operands `d` and `a` have `.f16x2` or `.b32` type. For `.bf16` instruction type, operands `d` and `a` have `.b16` type. For `.bf16x2` instruction type, operands `d` and `a` have `.b32` type. + +If `.NaN` modifier is specified, then the result is canonical `NaN` if either of the inputs is `NaN`. + +If `.abs` modifier is specified, the magnitude of destination operand `d` is the minimum of absolute values of both the input arguments. + +If `.xorsign` modifier is specified, the sign bit of destination `d` is equal to the XOR of the sign bits of both the inputs. + +Modifiers `.abs` and `.xorsign` must be specified together and `.xorsign` considers the sign bit of both inputs before applying `.abs` operation. + +If the result of `min` is `NaN` then the `.xorsign` and `.abs` modifiers will be ignored. + +Semantics + +if (type == f16 || type == bf16) { + if (.xorsign) { + xorsign = getSignBit(a) ^ getSignBit(b); + if (.abs) { + a = |a|; + b = |b|; + } + } + if (isNaN(a) && isNaN(b)) d = NaN; + if (.NaN && (isNaN(a) || isNaN(b))) d = NaN; + else if (isNaN(a)) d = b; + else if (isNaN(b)) d = a; + else d = (a < b) ? a : b; + if (.xorsign && !isNaN(d)) { + setSignBit(d, xorsign); + } + } else if (type == f16x2 || type == bf16x2) { + fA[0] = a[0:15]; + fA[1] = a[16:31]; + fB[0] = b[0:15]; + fB[1] = b[16:31]; + for (i = 0; i < 2; i++) { + if (.xorsign) { + xorsign = getSignBit(fA[i]) ^ getSignBit(fB[i]); + if (.abs) { + fA[i] = |fA[i]|; + fB[i] = |fB[i]|; + } + } + if (isNaN(fA[i]) && isNaN(fB[i])) d[i] = NaN; + if (.NaN && (isNaN(fA[i]) || isNaN(fB[i]))) d[i] = NaN; + else if (isNaN(fA[i])) d[i] = fB[i]; + else if (isNaN(fB[i])) d[i] = fA[i]; + else d[i] = (fA[i] < fB[i]) ? fA[i] : fB[i]; + if (.xorsign && !isNaN(d[i])) { + setSignBit(d[i], xorsign); + } + } + } + +Notes + +Subnormal numbers: + + +By default, subnormal numbers are supported. `min.ftz.{f16, f16x2}` flushes subnormal inputs and results to sign-preserving zero. + +If values of both inputs are 0.0, then +0.0 > -0.0. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +`min.xorsign` introduced in PTX ISA version 7.2. + +Target ISA Notes + +Requires `sm_80` or higher. + +`min.xorsign.abs` support requires `sm_86` or higher. + +Examples + +min.ftz.f16 h0,h1,h2; + min.f16x2 b0,b1,b2; + // SIMD fp16 min with .NaN + min.NaN.f16x2 b0,b1,b2; + min.bf16 h0, h1, h2; + // SIMD bf16 min with NaN + min.NaN.bf16x2 b0, b1, b2; + // scalar bf16 min with xorsign.abs + min.xorsign.abs.bf16 Rd, Ra, Rb \ No newline at end of file diff --git a/content/cuda/docs/ptx-mipmaps/DOC.md b/content/cuda/docs/ptx-mipmaps/DOC.md new file mode 100644 index 00000000..35178114 --- /dev/null +++ b/content/cuda/docs/ptx-mipmaps/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-mipmaps +description: A _mipmap_ is a sequence of textures, each of which is a progressively + lower resolution representation of the same image. The height and width of each + image, or level of detail (LOD), in the mipmap is... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.10.2. Mipmaps + +--- +title: "9.7.10.2. Mipmaps" +section: 9.7.10.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.10.2. Mipmaps + + +A _mipmap_ is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level of detail (LOD), in the mipmap is a power of two smaller than the previous level. Mipmaps are used in graphics applications to improve rendering speed and reduce aliasing artifacts. For example, a high-resolution mipmap image is used for objects that are close to the user; lower-resolution images are used as the object appears farther away. Mipmap filtering modes are provided when switching between two levels of detail (LODs) in order to avoid abrupt changes in visual fidelity. + +**Example:** If the texture has a basic size of 256 by 256 pixels, then the associated mipmap set may contain a series of eight images, each one-fourth the total area of the previous one: 128x128 pixels, 64x64, 32x32, 16x16, 8x8, 4x4, 2x2, 1x1 (a single pixel). If, for example, a scene is rendering this texture in a space of 40x40 pixels, then either a scaled up version of the 32x32 (without trilinear interpolation) or an interpolation of the 64x64 and the 32x32 mipmaps (with trilinear interpolation) would be used. + +The total number of LODs in a complete mipmap pyramid is calculated through the following equation: + +numLODs = 1 + floor(log2(max(w, h, d))) + +The finest LOD is called the base level and is the 0th level. The next (coarser) level is the 1st level, and so on. The coarsest level is the level of size (1 x 1 x 1). Each successively smaller mipmap level has half the {width, height, depth} of the previous level, but if this half value is a fractional value, it’s rounded down to the next largest integer. Essentially, the size of a mipmap level can be specified as: + +max(1, floor(w_b / 2^i)) x + max(1, floor(h_b / 2^i)) x + max(1, floor(d_b / 2^i)) + +where _i_ is the ith level beyond the 0th level (the base level). And _w_b_ , _h_b_ and _d_b_ are the width, height and depth of the base level respectively. + +PTX support for mipmaps + +The PTX `tex` instruction supports three modes for specifying the LOD: _base_ , _level_ , and _grad_ ient. In base mode, the instruction always picks level 0. In level mode, an additional argument is provided to specify the LOD to fetch from. In gradmode, two floating-point vector arguments provide _partials_ (e.g., `{ds/dx, dt/dx}` and `{ds/dy, dt/dy}` for a 2d texture), which the `tex` instruction uses to compute the LOD. + +These instructions provide access to texture memory. + +* `tex` + + * `tld4` + + * `txq` \ No newline at end of file diff --git a/content/cuda/docs/ptx-miscellaneous-directivesblocksareclusters/DOC.md b/content/cuda/docs/ptx-miscellaneous-directivesblocksareclusters/DOC.md new file mode 100644 index 00000000..db00ab67 --- /dev/null +++ b/content/cuda/docs/ptx-miscellaneous-directivesblocksareclusters/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-miscellaneous-directivesblocksareclusters +description: '`.blocksareclusters`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.8.1. Miscellaneous Directives:.blocksareclusters + +--- +title: "11.8.1. Miscellaneous Directives:.blocksareclusters" +section: 11.8.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.8.1. Miscellaneous Directives:.blocksareclusters + + +`.blocksareclusters` + +Specify that CUDA thread blocks are mapped to clusters. + +Syntax + +.blocksareclusters + +Description + +Default behavior of CUDA API is to specify the grid launch configuration by specifying the number of thread blocks and the number of threads per block. + +When `.blocksareclusters` directive is specified, it implies that the grid launch configuration for the corresponding `.entry` function is specifying the number of clusters, i.e. the launch configuration is specifying number of clusters instead of the number of thread blocks. In this case, the number of thread blocks per cluster is specified by `.reqnctapercluster` directive and the thread block size is specified with the `.reqntid` directive. + +`.blocksareclusters` directive is only allowed for `.entry` functions and also needs `.reqntid` and `.reqnctapercluster` directives to be specified. + +Refer to _CUDA Programming Guide_ for more details. + +PTX ISA Notes + +Introduced in PTX ISA version 9.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +.entry foo .reqntid 32, 32, 1 .reqnctapercluster 32, 32, 1 .blocksareclusters { ... } \ No newline at end of file diff --git a/content/cuda/docs/ptx-mmio-operation/DOC.md b/content/cuda/docs/ptx-mmio-operation/DOC.md new file mode 100644 index 00000000..79506a63 --- /dev/null +++ b/content/cuda/docs/ptx-mmio-operation/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-mmio-operation +description: An _mmio_ operation is a memory operation with `.mmio` qualifier specified. + It is usually performed on a memory location which is mapped to the control registers + of peer I/O devices. It can also be us... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.4.1. mmio Operation + +--- +title: "8.4.1. mmio Operation" +section: 8.4.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.4.1. mmio Operation + + +An _mmio_ operation is a memory operation with `.mmio` qualifier specified. It is usually performed on a memory location which is mapped to the control registers of peer I/O devices. It can also be used for communication between threads but has poor performance relative to non-_mmio_ operations. + +The semantic meaning of _mmio_ operations cannot be defined precisely as it is defined by the underlying I/O device. For formal specification of semantics of _mmio_ operation from Memory Consistency Model perspective, it is equivalent to the semantics of a _strong_ operation. But it follows a few implementation-specific properties, if it meets the _CUDA atomicity requirements_ at the specified scope: + +* Writes are always performed and are never combined within the scope specified. + + * Reads are always performed, and are not forwarded, prefetched, combined, or allowed to hit any cache within the scope specified. + + * As an exception, in some implementations, the surrounding locations may also be loaded. In such cases the amount of data loaded is implementation specific and varies between 32 and 128 bytes in size. \ No newline at end of file diff --git a/content/cuda/docs/ptx-mov/DOC.md b/content/cuda/docs/ptx-mov/DOC.md new file mode 100644 index 00000000..b8e654c5 --- /dev/null +++ b/content/cuda/docs/ptx-mov/DOC.md @@ -0,0 +1,100 @@ +--- +name: ptx-mov +description: Move vector-to-scalar (pack) or scalar-to-vector (unpack). +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.4. Data Movement and Conversion Instructions:mov + +--- +title: "9.7.9.4. Data Movement and Conversion Instructions:mov" +section: 9.7.9.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.4. Data Movement and Conversion Instructions:mov + + +`mov` + +Move vector-to-scalar (pack) or scalar-to-vector (unpack). + +Syntax + +mov.type d, a; + + .type = { .b16, .b32, .b64, .b128 }; + +Description + +Write scalar register `d` with the packed value of vector register `a`, or write vector register `d` with the unpacked values from scalar register `a`. + +When destination operand `d` is a vector register, the sink symbol `'_'` may be used for one or more elements provided that at least one element is a scalar register. + +For bit-size types, `mov` may be used to pack vector elements into a scalar register or unpack sub-fields of a scalar register into a vector. Both the overall size of the vector and the size of the scalar must match the size of the instruction type. + +Semantics + +// pack two 8-bit elements into .b16 + d = a.x | (a.y << 8) + // pack four 8-bit elements into .b32 + d = a.x | (a.y << 8) | (a.z << 16) | (a.w << 24) + // pack two 16-bit elements into .b32 + d = a.x | (a.y << 16) + // pack four 16-bit elements into .b64 + d = a.x | (a.y << 16) | (a.z << 32) | (a.w << 48) + // pack two 32-bit elements into .b64 + d = a.x | (a.y << 32) + // pack four 32-bit elements into .b128 + d = a.x | (a.y << 32) | (a.z << 64) | (a.w << 96) + // pack two 64-bit elements into .b128 + d = a.x | (a.y << 64) + + // unpack 8-bit elements from .b16 + { d.x, d.y } = { a[0..7], a[8..15] } + // unpack 8-bit elements from .b32 + { d.x, d.y, d.z, d.w } + { a[0..7], a[8..15], a[16..23], a[24..31] } + + // unpack 16-bit elements from .b32 + { d.x, d.y } = { a[0..15], a[16..31] } + // unpack 16-bit elements from .b64 + { d.x, d.y, d.z, d.w } = + { a[0..15], a[16..31], a[32..47], a[48..63] } + + // unpack 32-bit elements from .b64 + { d.x, d.y } = { a[0..31], a[32..63] } + + // unpack 32-bit elements from .b128 + { d.x, d.y, d.z, d.w } = + { a[0..31], a[32..63], a[64..95], a[96..127] } + // unpack 64-bit elements from .b128 + { d.x, d.y } = { a[0..63], a[64..127] } + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Support for `.b128` type introduced in PTX ISA version 8.3. + +Target ISA Notes + +Supported on all target architectures. + +Support for `.b128` type requires `sm_70` or higher. + +Examples + +mov.b32 %r1,{a,b}; // a,b have type .u16 + mov.b64 {lo,hi}, %x; // %x is a double; lo,hi are .u32 + mov.b32 %r1,{x,y,z,w}; // x,y,z,w have type .b8 + mov.b32 {r,g,b,a},%r1; // r,g,b,a have type .u8 + mov.b64 {%r1, _}, %x; // %x is.b64, %r1 is .b32 + mov.b128 {%b1, %b2}, %y; // %y is.b128, %b1 and % b2 are .b64 + mov.b128 %y, {%b1, %b2}; // %y is.b128, %b1 and % b2 are .b64 \ No newline at end of file diff --git a/content/cuda/docs/ptx-mul/DOC.md b/content/cuda/docs/ptx-mul/DOC.md new file mode 100644 index 00000000..2f1aeb64 --- /dev/null +++ b/content/cuda/docs/ptx-mul/DOC.md @@ -0,0 +1,123 @@ +--- +name: ptx-mul +description: Multiply two values. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.4.3. Half Precision Floating Point Instructions:mul + +--- +title: "9.7.4.3. Half Precision Floating Point Instructions:mul" +section: 9.7.4.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.4.3. Half Precision Floating Point Instructions:mul + + +`mul` + +Multiply two values. + +Syntax + +mul{.rnd}{.ftz}{.sat}.f16 d, a, b; + mul{.rnd}{.ftz}{.sat}.f16x2 d, a, b; + + mul{.rnd}.bf16 d, a, b; + mul{.rnd}.bf16x2 d, a, b; + + .rnd = { .rn }; + +Description + +Performs multiplication and writes the resulting value into a destination register. + +For `.f16x2` and `.bf16x2` instruction type, forms input vectors by half word values from source operands. Half-word operands are then multiplied in parallel to produce `.f16x2` or `.bf16x2` result in destination. + +For `.f16` instruction type, operands `d`, `a` and `b` have `.f16` or `.b16` type. For `.f16x2` instruction type, operands `d`, `a` and `b` have `.b32` type. For `.bf16` instruction type, operands `d`, `a`, `b` have `.b16` type. For `.bf16x2` instruction type, operands `d`, `a`, `b` have `.b32` type. + +Semantics + +if (type == f16 || type == bf16) { + d = a * b; + } else if (type == f16x2 || type == bf16x2) { + fA[0] = a[0:15]; + fA[1] = a[16:31]; + fB[0] = b[0:15]; + fB[1] = b[16:31]; + for (i = 0; i < 2; i++) { + d[i] = fA[i] * fB[i]; + } + } + +Notes + +Rounding modifiers: + +`.rn` + + +mantissa LSB rounds to nearest even + +The default value of rounding modifier is `.rn`. Note that a `mul` instruction with an explicit rounding modifier is treated conservatively by the code optimizer. A `mul` instruction with no rounding modifier defaults to round-to-nearest-even and may be optimized aggressively by the code optimizer. In particular, `mul`/`add` and `mul/sub` sequences with no rounding modifiers may be optimized to use fused-multiply-add instructions on the target device. + +Subnormal numbers: + + +By default, subnormal numbers are supported. `mul.ftz.{f16, f16x2}` flushes subnormal inputs and results to sign-preserving zero. + +Saturation modifier: + + +`mul.sat.{f16, f16x2}` clamps the result to [0.0, 1.0]. `NaN` results are flushed to `+0.0f`. + +PTX ISA Notes + +Introduced in PTX ISA version 4.2. + +`mul{.rnd}.bf16` and `mul{.rnd}.bf16x2` introduced in PTX ISA version 7.8. + +Target ISA Notes + +Requires `sm_53` or higher. + +`mul{.rnd}.bf16` and `mul{.rnd}.bf16x2` requires `sm_90` or higher. + +Examples + +// scalar f16 multiplications + mul.f16 d0, a0, b0; + mul.rn.f16 d1, a1, b1; + mul.bf16 bd0, ba0, bb0; + mul.rn.bf16 bd1, ba1, bb1; + + // SIMD f16 multiplication + cvt.rn.f16.f32 h0, f0; + cvt.rn.f16.f32 h1, f1; + cvt.rn.f16.f32 h2, f2; + cvt.rn.f16.f32 h3, f3; + mov.b32 p1, {h0, h1}; // pack two f16 to 32bit f16x2 + mov.b32 p2, {h2, h3}; // pack two f16 to 32bit f16x2 + mul.f16x2 p3, p1, p2; // SIMD f16x2 multiplication + + // SIMD bf16 multiplication + cvt.rn.bf16x2.f32 p4, f4, f5; // Convert two f32 into packed bf16x2 + cvt.rn.bf16x2.f32 p5, f6, f7; // Convert two f32 into packed bf16x2 + mul.bf16x2 p6, p4, p5; // SIMD bf16x2 multiplication + + // SIMD fp16 multiplication + ld.global.b32 f0, [addr]; // load 32 bit which hold packed f16x2 + ld.global.b32 f1, [addr + 4]; // load 32 bit which hold packed f16x2 + mul.f16x2 f2, f0, f1; // SIMD f16x2 multiplication + + // SIMD bf16 multiplication + ld.global.b32 f3, [addr + 8]; // load 32 bit which hold packed bf16x2 + ld.global.b32 f4, [addr + 12]; // load 32 bit which hold packed bf16x2 + mul.bf16x2 f5, f3, f4; // SIMD bf16x2 multiplication \ No newline at end of file diff --git a/content/cuda/docs/ptx-mul24/DOC.md b/content/cuda/docs/ptx-mul24/DOC.md new file mode 100644 index 00000000..8fca8495 --- /dev/null +++ b/content/cuda/docs/ptx-mul24/DOC.md @@ -0,0 +1,67 @@ +--- +name: ptx-mul24 +description: Multiply two 24-bit integer values. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.5. Integer Arithmetic Instructions:mul24 + +--- +title: "9.7.1.5. Integer Arithmetic Instructions:mul24" +section: 9.7.1.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.5. Integer Arithmetic Instructions:mul24 + + +`mul24` + +Multiply two 24-bit integer values. + +Syntax + +mul24.mode.type d, a, b; + + .mode = { .hi, .lo }; + .type = { .u32, .s32 }; + +Description + +Compute the product of two 24-bit integer values held in 32-bit source registers, and return either the high or low 32-bits of the 48-bit result. + +Semantics + +t = a * b; + d = t<47..16>; // for .hi variant + d = t<31..0>; // for .lo variant + +Notes + +Integer multiplication yields a result that is twice the size of the input operands, i.e., 48-bits. + +`mul24.hi` performs a 24x24-bit multiply and returns the high 32 bits of the 48-bit result. + +`mul24.lo` performs a 24x24-bit multiply and returns the low 32 bits of the 48-bit result. + +All operands are of the same type and size. + +`mul24.hi` may be less efficient on machines without hardware support for 24-bit multiply. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +mul24.lo.s32 d,a,b; // low 32-bits of 24x24-bit signed multiply. \ No newline at end of file diff --git a/content/cuda/docs/ptx-multimem-addresses/DOC.md b/content/cuda/docs/ptx-multimem-addresses/DOC.md new file mode 100644 index 00000000..6b013b85 --- /dev/null +++ b/content/cuda/docs/ptx-multimem-addresses/DOC.md @@ -0,0 +1,27 @@ +--- +name: ptx-multimem-addresses +description: A multimem address is a virtual address which points to multiple distinct + memory locations across devices. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.3. Multimem Addresses + +--- +title: "8.2.3. Multimem Addresses" +section: 8.2.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.3. Multimem Addresses + + +A multimem address is a virtual address which points to multiple distinct memory locations across devices. + +Only _multimem._ * operations are valid on multimem addresses. That is, the behavior of accessing a multimem address in any other memory operation is undefined. \ No newline at end of file diff --git a/content/cuda/docs/ptx-multimemcpasyncbulk/DOC.md b/content/cuda/docs/ptx-multimemcpasyncbulk/DOC.md new file mode 100644 index 00000000..c3392f50 --- /dev/null +++ b/content/cuda/docs/ptx-multimemcpasyncbulk/DOC.md @@ -0,0 +1,65 @@ +--- +name: ptx-multimemcpasyncbulk +description: '`multimem.cp.async.bulk`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.26. Data Movement and Conversion Instructions:multimem.cp.async.bulk + +--- +title: "9.7.9.26. Data Movement and Conversion Instructions:multimem.cp.async.bulk" +section: 9.7.9.26 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.26. Data Movement and Conversion Instructions:multimem.cp.async.bulk + + +`multimem.cp.async.bulk` + +Initiates an asynchronous copy operation to a multimem address range. + +Syntax + +multimem.cp.async.bulk.dst.src.completion_mechanism{.cp_mask} + [dstMem], [srcMem], size{, byteMask}; + + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + +Description + +Instruction `multimem.cp.async.bulk` initiates an asynchronous bulk-copy operation from source address range `[srcMem, srcMem + size)` to memory locations residing on each GPU’s memory referred to by the destination multimem address range `[dstMem, dstMem + size)`. The direction of bulk-copy is from the state space specified by the `.src` modifier to the state space specified by the `.dst` modifiers. + +The 32-bit operand `size` specifies the amount of memory to be copied, in terms of number of bytes. Operand `size` must be a multiple of `16`. The memory range `[dstMem, dstMem + size)` must not overflow the destination multimem memory space. The memory range `[srcMem, srcMem + size)` must not overflow the source memory space. The addresses `dstMem` and `srcMem` must be aligned to `16` bytes. If any of these pre-conditions is not met, the behavior is undefined. + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported by the instruction. The modifier `.bulk_group` specifies that the `multimem.cp.async.bulk` instruction uses bulk async-group based completion mechanism. + +When the optional modifier `.cp_mask` is specified, the argument `byteMask` is required. The i-th bit in the 16-bit wide `byteMask` operand specifies whether the i-th byte of each 16-byte wide chunk of source data is copied to the destination. If the bit is set, the byte is copied. + +The reads and writes of the copy operation in `multimem.cp.async.bulk` are weak memory operations as described in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 9.1. + +Target ISA Notes + +Requires `sm_90` or higher. + +Support for `.cp_mask` qualifier requires `sm_100` or higher. + +Examples + +multimem.cp.async.bulk.global.shared::cta.bulk_group [dstMem], [srcMem], size; + + multimem.cp.async.bulk.global.shared::cta.bulk_group [dstMem], [srcMem], 512; + + multimem.cp.async.bulk.global.shared::cta.bulk_group.cp_mask [dstMem], [srcMem], size, byteMask; \ No newline at end of file diff --git a/content/cuda/docs/ptx-multimemcpreduceasyncbulk/DOC.md b/content/cuda/docs/ptx-multimemcpreduceasyncbulk/DOC.md new file mode 100644 index 00000000..c6ff596d --- /dev/null +++ b/content/cuda/docs/ptx-multimemcpreduceasyncbulk/DOC.md @@ -0,0 +1,703 @@ +--- +name: ptx-multimemcpreduceasyncbulk +description: '`multimem.cp.reduce.async.bulk`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.27. Data Movement and Conversion Instructions:multimem.cp.reduce.async.bulk + +--- +title: "9.7.9.27. Data Movement and Conversion Instructions:multimem.cp.reduce.async.bulk" +section: 9.7.9.27 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.27. Data Movement and Conversion Instructions:multimem.cp.reduce.async.bulk + + +`multimem.cp.reduce.async.bulk` + +Initiates an asynchronous reduction operation to a multimem address range. + +Syntax + +multimem.cp.reduce.async.bulk.dst.src.completion_mechanism.redOp.type [dstMem], [srcMem], size; + + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + .redOp = { .and, .or, .xor, + .add, .inc, .dec, + .min, .max } + .type = { .f16, .bf16, + .b32, .u32, .s32, + .b64, .u64, .s64, + .f32, .f64 } + + multimem.cp.reduce.async.bulk.dst.src.completion_mechanism.add.noftz.type [dstMem], [srcMem], size; + + .dst = { .global } + .src = { .shared::cta } + .completion_mechanism = { .bulk_group } + .type = { .f16, .bf16 } + +Description + +Instruction `multimem.cp.reduce.async.bulk` initiates an element-wise asynchronous reduction operation with elements from source memory address range `[srcMem, srcMem + size)` to memory locations residing on each GPU’s memory referred to by the multimem destination address range `[dstMem, dstMem + size)`. + +Each data element in the destination array is reduced inline with the corresponding data element in the source array with the reduction operation specified by the modifier `.redOp`. The type of each data element in the source and the destination array is specified by the modifier `.type`. + +The source address operand `srcMem` is in the state space specified by `.src` and the destination address operand `dstMem` is in the state specified by the `.dst`. + +The 32-bit operand `size` specifies the amount of memory to be copied from the source location and used in the reduction operation, in terms of number of bytes. Operand `size` must be a multiple of 16. The memory range `[dstMem, dstMem + size)` must not overflow the destination multimem memory space. The memory range `[srcMem, srcMem + size)` must not overflow the source memory space. The addresses `dstMem` and `srcMem` must be aligned to 16 bytes. If any of these preconditions is not met, the behavior is undefined. + +The operations supported by `.redOp` are classified as follows: + +The bit-size operations are `.and`, `.or`, and `.xor`. + +The integer operations are `.add`, `.inc`, `.dec`, `.min`, and `.max`. The `.inc` and `.dec` operations return a result in the range `[0..x]` where `x` is the value at the source state space. + +The floating point operation `.add` rounds to the nearest even, preserve input and result subnormals, and does not flush them to zero, except for the current implementation of `multimem.cp.reduce.async.bulk.add.f32` which flushes subnormal inputs and results to sign-preserving zero. The `multimem.cp.reduce.async.bulk.add.f16` and `multimem.cp.reduce.async.bulk.add.bf16` operations require `.noftz` qualifier. It preserves input and result subnormals, and does not flush them to zero. + +The following table describes the valid combinations of `.redOp` and element type: + +.redOp | element type +---|--- +.add | .u32, .s32, .u64, .f32, .f64, .f16, .bf16 +.min, .max | .u32, .s32, .u64, .s64, .f16, .bf16 +.inc, .dec | .u32 +.and, .or, .xor | .b32, .b64 + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported by the instruction. The modifier `.bulk_group` specifies that the `multimem.cp.reduce.async.bulk` uses bulk async-group based completion mechanism. + +Each reduction operation performed by the `multimem.cp.reduce.async.bulk` has individually `.relaxed.sys` memory ordering semantics. The load operations in `multimem.cp.reduce.async.bulk` are treated as weak memory operations as described in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 9.1. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + +multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.add.u32 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.xor.b64 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.inc.u32 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.dec.u32 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.max.s32 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.add.noftz.f16 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.min.bf16 [dstMem], [srcMem], size; + + multimem.cp.reduce.async.bulk.global.shared::cta.bulk_group.add.noftz.bf16 [dstMem], [srcMem], size; + +##### 9.7.9.27.1. [Data Movement and Conversion Instructions: Tensor copy](<#data-movement-and-conversion-instructions-tensor-copy>) + +###### 9.7.9.27.1.1. [Restriction on Tensor Copy instructions](<#data-movement-and-conversion-instructions-tensor-copy-restrictions>) + +Following are the restrictions on the types `.b4x16`, `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`: + + 1. `cp.reduce.async.bulk` doesn’t support the types `.b4x16`, `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`. + + 2. `cp.async.bulk.tensor` with the direction `.global.shared::cta` doesn’t support the type `.b4x16_p64`. + + 3. `cp.async.bulk.tensor` with the direction `.shared::cluster.global` doesn’t support the sub-byte types on `sm_120a`. + + 4. OOB-NaN fill mode doesn’t support the types `.b4x16`, `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`. + + 5. Box-Size[0] must be exactly: + + 1. 96B for `b6x16_p32` and `.b6p2x16`. + + 2. 64B for `b4x16_p64`. + + 6. Tensor-Size[0] must be a multiple of: + + 1. 96B for `b6x16_p32` and `.b6p2x16`. + + 2. 64B for `b4x16_p64`. + + 7. For `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`, the first coordinate in the tensorCoords argument vector must be a multiple of 128. + + 8. For `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`, the global memory address must be 32B aligned. Additionally, tensor stride in every dimension must be 32B aligned. + + 9. `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16` supports the following swizzling modes: + + 1. None. + + 2. 128B (With all potential swizzle atomicity values except: 32B with 8B flip) + + +Following are the restrictions on the 96B swizzle mode: + + 1. The `.swizzle_atomicity` must be 16B. + + 2. The `.interleave_layout` must not be set. + + 3. Box-Size[0] must be less than or equal to 96B. + + 4. The type must not be among following: `.b4x16_p64`, `.b6x16_p32` and `.b6p2x16`. + + 5. The `.load_mode` must not be set to `.im2col::w::128`. + + +Following are the restrictions on the `.global.shared::cta` direction: + + 1. Starting co-ordinates for Bounding Box (`tensorCoords`) must be non-negative. + + 2. The bounding box along the D, W and H dimensions must stay within the tensor boundaries. This implies: + + 1. Bounding-Box Lower-Corner must be non-negative. + + 2. Bounding-Box Upper-Corner must be non-positive. + + +Following are the restrictions for `sm_120a`: + + 1. `cp.async.bulk.tensor` with the direction `.shared::cluster.global` doesn’t support: + + 1. the sub-byte types + + 2. the qualifier `.swizzle_atomicity` + + +Following are the restrictions for `sm_103a` while using type `.b6p2x16` on `cp.async.bulk.tensor` with the direction `.global.shared::cta`: + + 1. Box-Size[0] must be exactly either of 48B or 96B. + + 2. The global memory address must be 16B aligned. + + 3. Tensor Stride in every dimension must be 16B aligned. + + 4. The first coordinate in the tensorCoords argument vector must be a multiple of 64. + + 5. Tensor-Size[0] must be a multiple of 48B. + + 6. The following swizzle modes are supported: + + 1. None. + + 2. 128B (With all potential swizzle atomicity values except: 32B with 8B flip) + + 3. 64B swizzle with 16B swizzle atomicity + + +###### 9.7.9.27.1.2. [Data Movement and Conversion Instructions: `cp.async.bulk.tensor`](<#data-movement-and-conversion-instructions-cp-async-bulk-tensor>) + +`cp.async.bulk.tensor` + +Initiates an asynchronous copy operation on the tensor data from one state space to another. + +Syntax + + + // global -> shared::cta + cp.async.bulk.tensor.dim.dst.src{.load_mode}.completion_mechanism{.cta_group}{.level::cache_hint} + [dstMem], [tensorMap, tensorCoords], [mbar]{, im2colInfo} {, cache-policy} + + .dst = { .shared::cta } + .src = { .global } + .dim = { .1d, .2d, .3d, .4d, .5d } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + .cta_group = { .cta_group::1, .cta_group::2 } + .load_mode = { .tile, .tile::gather4, .im2col, .im2col::w, .im2col::w::128 } + .level::cache_hint = { .L2::cache_hint } + + + // global -> shared::cluster + cp.async.bulk.tensor.dim.dst.src{.load_mode}.completion_mechanism{.multicast}{.cta_group}{.level::cache_hint} + [dstMem], [tensorMap, tensorCoords], [mbar]{, im2colInfo} + {, ctaMask} {, cache-policy} + + .dst = { .shared::cluster } + .src = { .global } + .dim = { .1d, .2d, .3d, .4d, .5d } + .completion_mechanism = { .mbarrier::complete_tx::bytes } + .cta_group = { .cta_group::1, .cta_group::2 } + .load_mode = { .tile, .tile::gather4, .im2col, .im2col::w, .im2col::w::128 } + .level::cache_hint = { .L2::cache_hint } + .multicast = { .multicast::cluster } + + + // shared::cta -> global + cp.async.bulk.tensor.dim.dst.src{.load_mode}.completion_mechanism{.level::cache_hint} + [tensorMap, tensorCoords], [srcMem] {, cache-policy} + + .dst = { .global } + .src = { .shared::cta } + .dim = { .1d, .2d, .3d, .4d, .5d } + .completion_mechanism = { .bulk_group } + .load_mode = { .tile, .tile::scatter4, .im2col_no_offs } + .level::cache_hint = { .L2::cache_hint } + + +Description + +`cp.async.bulk.tensor` is a non-blocking instruction which initiates an asynchronous copy operation of tensor data from the location in `.src` state space to the location in the `.dst` state space. + +The operand `dstMem` specifies the location in the `.dst` state space into which the tensor data has to be copied and `srcMem` specifies the location in the `.src` state space from which the tensor data has to be copied. + +When `.dst` is specified as `.shared::cta`, the address `dstMem` must be in the shared memory of the executing CTA within the cluster, otherwise the behavior is undefined. + +When `.dst` is specified as `.shared::cluster`, the address `dstMem` can be in the shared memory of any of the CTAs within the current cluster. + +The operand `tensorMap` is the generic address of the opaque tensor-map object which resides in `.param` space or `.const` space or `.global` space. The operand `tensorMap` specifies the properties of the tensor copy operation, as described in [Tensor-map](<#tensor-tensormap>). The `tensorMap` is accessed in tensormap proxy. Refer to the _CUDA programming guide_ for creating the tensor-map objects on the host side. + +The dimension of the tensor data is specified by the `.dim` modifier. + +The vector operand `tensorCoords` specifies the starting coordinates in the tensor data in the global memory from or to which the copy operation has to be performed. The individual tensor coordinates in `tensorCoords` are of type `.s32`. The format of vector argument `tensorCoords` is dependent on `.load_mode` specified and is as follows: + +.load_mode | tensorCoords | Semantics +---|---|--- +`.tile::scatter4` | {col_idx, row_idx0, row_idx1, row_idx2, row_idx3} | Fixed length vector of size 5. The five elements together specify the start co-ordinates of the four rows. +`.tile::gather4` +Rest all | {d0, .., dn} for n = .dim | Vector of n elements where n = .dim. The elements indicate the offset in each of the dimension. + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported on the instruction variant. The completion mechanisms that are supported for different variants are summarized in the following table: + +.completion-mechanism | `.dst` | `.src` | Completion mechanism +---|---|---|--- +Needed for completion of entire Async operation | optionally can be used for the completion of reading of the tensormap object +`.mbarrier::...` | `.shared::cta` | `.global` | mbarrier based | _Bulk async-group_ based +`.shared::cluster` | `.global` +`.bulk_group` | `.global` | `.shared::cta` | _Bulk async-group_ based + +The modifier `.mbarrier::complete_tx::bytes` specifies that the `cp.async.bulk.tensor` variant uses mbarrier based completion mechanism. Upon the completion of the asynchronous copy operation, the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation, with `completeCount` argument equal to amount of data copied in bytes, will be performed on the mbarrier object specified by the operand `mbar`. This instruction accesses its `mbarrier` operand using generic-proxy. + +The modifier `.cta_group` can only be specified with the mbarrier based completion mechanism. The modifier `.cta_group` is used to signal either the odd numbered CTA or the even numbered CTA among the [CTA-Pair](<#tcgen05-cta-pair>). When `.cta_group::1` is specified, the mbarrier object `mbar` that is specified must be in the shared memory of the same CTA as the shared memory destination `dstMem`. When `.cta_group::2` is specified, the mbarrier object `mbar` can be in shared memory of either the same CTA as the shared memory destination `dstMem` or in its [peer-CTA](<#tcgen05-peer-cta>). If `.cta_group` is not specified, then it defaults to `.cta_group::1`. + +The modifier `.bulk_group` specifies that the `cp.async.bulk.tensor` variant uses _bulk async-group_ based completion mechanism. + +The qualifier `.load_mode` specifies how the data in the source location is copied into the destination location. If `.load_mode` is not specified, it defaults to `.tile`. + +In `.tile` mode, the multi-dimensional layout of the source tensor is preserved at the destination. In `.tile::gather4` mode, four rows in 2-dimnesional source tensor are combined to form a single 2-dimensional destination tensor. In `.tile::scatter4` mode, single 2-dimensional source tensor is divided into four rows in 2-dimensional destination tensor. Details of `.tile::scatter4`/`.tile::gather4` modes are described in [.tile::scatter4 and .tile::gather4 modes](<#tensor-tiled-scatter4-gather4-modes>). + +In `.im2col` and `.im2col::*` modes, some dimensions of the source tensors are unrolled in a single dimensional column at the destination. Details of the `im2col` and `.im2col::*` modes are described in [im2col mode](<#tensor-im2col-mode>) and [im2col::w and im2col::w::128 modes](<#tensor-im2col-w-w128-modes>) respectively. In `.im2col` and `.im2col::*` modes, the tensor has to be at least 3-dimensional. The vector operand `im2colInfo` can be specified only when `.load_mode` is `.im2col` or `.im2col::w` or `.im2col::w::128`. The format of the vector argument `im2colInfo` is dependent on the exact im2col mode and is as follows: + +Exact im2col mode | im2colInfo argument | Semantics +---|---|--- +`.im2col` | { i2cOffW , i2cOffH , i2cOffD } for `.dim` = `.5d` | A vector of im2col offsets whose vector size is two less than number of dimensions .dim. +`.im2col::w` | { wHalo, wOffset } | A vector of 2 arguments containing [wHalo](<#tensor-im2col-w-w128-modes-whalo>) and [wOffset](<#tensor-im2col-w-w128-modes-woffset>) arguments. +`.im2col::w::128` +`.im2col_no_offs` | `im2colInfo` is not applicable. | `im2colInfo` is not applicable. + +Argument `wHalo` is a 16bit unsigned integer whose valid set of values differs on the load-mode and is as follows: \- Im2col::w mode : valid range is [0, 512). \- Im2col::w::128 mode : valid range is [0, 32). + +Argument `wOffset` is a 16bit unsigned integer whose valid range of values is [0, 32). + +The optional modifier `.multicast::cluster` allows copying of data from global memory to shared memory of multiple CTAs in the cluster. Operand `ctaMask` specifies the destination CTAs in the cluster such that each bit position in the 16-bit `ctaMask` operand corresponds to the `%ctaid` of the destination CTA. The source data is multicast to the same offset as `dstMem` in the shared memory of each destination CTA. When `.cta_group` is specified as: + + * `.cta_group::1` : The mbarrier signal is also multicasted to the same offset as `mbar` in the shared memory of the destination CTA. + + * `.cta_group::2` : The mbarrier signal is multicasted either to all the odd numbered CTAs or the even numbered CTAs within the corresponding [CTA-Pair](<#tcgen05-cta-pair>). For each destination CTA specified in the `ctaMask`, the mbarrier signal is sent either to the destination CTA or its [peer-CTA](<#tcgen05-peer-cta>) based on CTAs `%cluster_ctarank` parity of shared memory where the mbarrier object `mbar` resides. + + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +The copy operation in `cp.async.bulk.tensor` is treated as a weak memory operation and the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the mbarrier has `.release` semantics at the `.cluster` scope as described in the [Memory Consistency Model](<#memory-consistency-model>). + +Notes + +`.multicast::cluster` qualifier is optimized for target architecture `sm_90a`/`sm_100f`/`sm_100a`/ `sm_103f`/`sm_103a`/`sm_110f`/`sm_110a` and may have substantially reduced performance on other targets and hence `.multicast::cluster` is advised to be used with `.target` `sm_90a`/`sm_100f`/ `sm_100a`/`sm_103f`/`sm_103a`/`sm_110f`/`sm_110a`. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Support for `.shared::cta` as destination state space is introduced in PTX ISA version 8.6. + +Support for qualifiers `.tile::gather4` and `.tile::scatter4` introduced in PTX ISA version 8.6. + +Support for qualifiers `.im2col::w` and `.im2col::w::128` introduced in PTX ISA version 8.6. + +Support for qualifier `.cta_group` introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_90` or higher. + +`.multicast::cluster` qualifier advised to be used with `.target` `sm_90a` or `sm_100f` or `sm_100a` or `sm_103f` or `sm_103a` or `sm_110f` or `sm_110a`. + +Qualifiers `.tile::gather4` and `.im2col::w` require: + + * `sm_100a` when destination state space is `.shared::cluster` and is supported on `sm_100f` from PTX ISA version 8.8. + + * `sm_100` or higher when destination state space is `.shared::cta`. + + +Qualifier `.tile::scatter4` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Qualifier `.im2col::w::128` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Qualifier `.cta_group` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Examples + + + .reg .b16 ctaMask; + .reg .u16 i2cOffW, i2cOffH, i2cOffD; + .reg .b64 l2CachePolicy; + + cp.async.bulk.tensor.1d.shared::cta.global.mbarrier::complete_tx::bytes.tile [sMem0], [tensorMap0, {tc0}], [mbar0]; + + @p cp.async.bulk.tensor.5d.shared::cta.global.im2col.mbarrier::complete_tx::bytes + [sMem2], [tensorMap2, {tc0, tc1, tc2, tc3, tc4}], [mbar2], {i2cOffW, i2cOffH, i2cOffD}; + + cp.async.bulk.tensor.1d.shared::cluster.global.mbarrier::complete_tx::bytes.tile [sMem0], [tensorMap0, {tc0}], [mbar0]; + + @p cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster + [sMem1], [tensorMap1, {tc0, tc1}], [mbar2], ctaMask; + + @p cp.async.bulk.tensor.5d.shared::cluster.global.im2col.mbarrier::complete_tx::bytes + [sMem2], [tensorMap2, {tc0, tc1, tc2, tc3, tc4}], [mbar2], {i2cOffW, i2cOffH, i2cOffD}; + + @p cp.async.bulk.tensor.3d.im2col.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint + [sMem3], [tensorMap3, {tc0, tc1, tc2}], [mbar3], {i2cOffW}, policy; + + @p cp.async.bulk.tensor.1d.global.shared::cta.bulk_group [tensorMap3, {tc0}], [sMem3]; + + cp.async.bulk.tensor.2d.tile::gather4.shared::cluster.global.mbarrier::complete_tx::bytes + [sMem5], [tensorMap6, {x0, y0, y1, y2, y3}], [mbar5]; + + cp.async.bulk.tensor.3d.im2col::w.shared::cluster.global.mbarrier::complete_tx::bytes + [sMem4], [tensorMap5, {t0, t1, t2}], [mbar4], {im2colwHalo, im2colOff}; + + cp.async.bulk.tensor.1d.shared::cluster.global.tile.cta_group::2 + [sMem6], [tensorMap7, {tc0}], [peerMbar]; + + +###### 9.7.9.27.1.3. [Data Movement and Conversion Instructions: `cp.reduce.async.bulk.tensor`](<#data-movement-and-conversion-instructions-cp-reduce-async-bulk-tensor>) + +`cp.reduce.async.bulk.tensor` + +Initiates an asynchronous reduction operation on the tensor data. + +Syntax + + + // shared::cta -> global: + cp.reduce.async.bulk.tensor.dim.dst.src.redOp{.load_mode}.completion_mechanism{.level::cache_hint} + [tensorMap, tensorCoords], [srcMem] {,cache-policy} + + .dst = { .global } + .src = { .shared::cta } + .dim = { .1d, .2d, .3d, .4d, .5d } + .completion_mechanism = { .bulk_group } + .load_mode = { .tile, .im2col_no_offs } + .redOp = { .add, .min, .max, .inc, .dec, .and, .or, .xor} + + +Description + +`cp.reduce.async.bulk.tensor` is a non-blocking instruction which initiates an asynchronous reduction operation of tensor data in the `.dst` state space with tensor data in the `.src` state space. + +The operand `srcMem` specifies the location of the tensor data in the `.src` state space using which the reduction operation has to be performed. + +The operand `tensorMap` is the generic address of the opaque tensor-map object which resides in `.param` space or `.const` space or `.global` space. The operand `tensorMap` specifies the properties of the tensor copy operation, as described in [Tensor-map](<#tensor-tensormap>). The `tensorMap` is accessed in tensormap proxy. Refer to the _CUDA programming guide_ for creating the tensor-map objects on the host side. + +Each element of the tensor data in the `.dst` state space is reduced inline with the corresponding element from the tensor data in the `.src` state space. The modifier `.redOp` specifies the reduction operation used for the inline reduction. The type of each tensor data element in the source and the destination tensor is specified in [Tensor-map](<#tensor-tensormap>). + +The dimension of the tensor is specified by the `.dim` modifier. + +The vector operand `tensorCoords` specifies the starting coordinates of the tensor data in the global memory on which the reduce operation is to be performed. The number of tensor coordinates in the vector argument `tensorCoords` should be equal to the dimension specified by the modifier `.dim`. The individual tensor coordinates are of the type `.s32`. + +The following table describes the valid combinations of `.redOp` and element type: + +`.redOp` | Element type +---|--- +`.add` | `.u32`, `.s32`, `.u64`, `.f32`, `.f16`, `.bf16` +`.min`, `.max` | `.u32`, `.s32`, `.u64`, `.s64`, `.f16`, `.bf16` +`.inc`, `.dec` | `.u32` +`.and`, `.or`, `.xor` | `.b32`, `.b64` + +The modifier `.completion_mechanism` specifies the completion mechanism that is supported on the instruction variant. Value `.bulk_group` of the modifier `.completion_mechanism` specifies that `cp.reduce.async.bulk.tensor` instruction uses _bulk async-group_ based completion mechanism. + +The qualifier `.load_mode` specifies how the data in the source location is copied into the destination location. If `.load_mode` is not specified, it defaults to `.tile`. In `.tile` mode, the multi-dimensional layout of the source tensor is preserved at the destination. In `.im2col_no_offs` mode, some dimensions of the source tensors are unrolled in a single dimensional column at the destination. Details of the `im2col` mode are described in [im2col mode](<#tensor-im2col-mode>). In `.im2col` mode, the tensor has to be at least 3-dimensional. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. The qualifier `.level::cache_hint` is only supported when at least one of the `.src` or `.dst` statespaces is `.global` state space. + +Each reduction operation performed by `cp.reduce.async.bulk.tensor` has individually `.relaxed.gpu` memory ordering semantics. The load operations in `cp.reduce.async.bulk.tensor` are treated as weak memory operations and the [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation on the mbarrier has `.release` semantics at the `.cluster` scope as described in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + cp.reduce.async.bulk.tensor.1d.global.shared::cta.add.tile.bulk_group + [tensorMap0, {tc0}], [sMem0]; + + cp.reduce.async.bulk.tensor.2d.global.shared::cta.and.bulk_group.L2::cache_hint + [tensorMap1, {tc0, tc1}], [sMem1] , policy; + + cp.reduce.async.bulk.tensor.3d.global.shared::cta.xor.im2col.bulk_group + [tensorMap2, {tc0, tc1, tc2}], [sMem2] + + +###### 9.7.9.27.1.4. [Data Movement and Conversion Instructions: `cp.async.bulk.prefetch.tensor`](<#data-movement-and-conversion-instructions-cp-async-bulk-prefetch-tensor>) + +`cp.async.bulk.prefetch.tensor` + +Provides a hint to the system to initiate the asynchronous prefetch of tensor data to the cache. + +Syntax + + + // global -> shared::cluster: + cp.async.bulk.prefetch.tensor.dim.L2.src{.load_mode}{.level::cache_hint} [tensorMap, tensorCoords] + {, im2colInfo } {, cache-policy} + + .src = { .global } + .dim = { .1d, .2d, .3d, .4d, .5d } + .load_mode = { .tile, .tile::gather4, .im2col, .im2col::w, .im2col::w::128 } + .level::cache_hint = { .L2::cache_hint } + + +Description + +`cp.async.bulk.prefetch.tensor` is a non-blocking instruction which may initiate an asynchronous prefetch of tensor data from the location in `.src` statespace to the L2 cache. + +The operand `tensorMap` is the generic address of the opaque tensor-map object which resides in `.param` space or `.const` space or `.global` space. The operand `tensorMap` specifies the properties of the tensor copy operation, as described in [Tensor-map](<#tensor-tensormap>). The `tensorMap` is accessed in tensormap proxy. Refer to the _CUDA programming guide_ for creating the tensor-map objects on the host side. + +The dimension of the tensor data is specified by the `.dim` modifier. + +The vector operand `tensorCoords` specifies the starting coordinates in the tensor data in the global memory from which the copy operation has to be performed. The individual tensor coordinates in `tensorCoords` are of type `.s32`. The format of vector argument `tensorCoords` is dependent on `.load_mode` specified and is as follows: + +.load_mode | tensorCoords | Semantics +---|---|--- +`.tile::gather4` | {col_idx, row_idx0, row_idx1, row_idx2, row_idx3} | Fixed length vector of size 5. The five elements together specify the start co-ordinates of the four rows. +Rest all | {d0, .., dn} for n = .dim | Vector of n elements where n = .dim. The elements indicate the offset in each of the dimension. + +The qualifier `.load_mode` specifies how the data in the source location is copied into the destination location. If `.load_mode` is not specified, it defaults to `.tile`. + +In `.tile` mode, the multi-dimensional layout of the source tensor is preserved at the destination. In `.tile::gather4` mode, four rows in the 2-dimnesional source tensor are fetched to L2 cache. Details of `.tile::gather4` modes are described in [.tile::scatter4 and .tile::gather4 modes](<#tensor-tiled-scatter4-gather4-modes>). + +In `.im2col` and `.im2col::*` modes, some dimensions of the source tensors are unrolled in a single dimensional column at the destination. Details of the `im2col` and `.im2col::*` modes are described in [im2col mode](<#tensor-im2col-mode>) and [im2col::w and im2col::w::128 modes](<#tensor-im2col-w-w128-modes>) respectively. In `.im2col` and `.im2col::*` modes, the tensor has to be at least 3-dimensional. The vector operand `im2colInfo` can be specified only when `.load_mode` is `.im2col` or `.im2col::w` or `.im2col::w::128`. The format of the vector argument `im2colInfo` is dependent on the exact im2col mode and is as follows: + +Exact im2col mode | im2colInfo argument | Semantics +---|---|--- +`.im2col` | { i2cOffW , i2cOffH , i2cOffD } for `.dim` = `.5d` | A vector of im2col offsets whose vector size is two less than number of dimensions .dim. +`.im2col::w` | { wHalo, wOffset } | A vector of 2 arguments containing [wHalo](<#tensor-im2col-w-w128-modes-whalo>) and [wOffset](<#tensor-im2col-w-w128-modes-woffset>) arguments. +`.im2col::w::128` + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +`cp.async.bulk.prefetch.tensor` is treated as a weak memory operation in the [Memory Consistency Model](<#memory-consistency-model>). + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Support for qualifier `.tile::gather4` introduced in PTX ISA version 8.6. + +Support for qualifiers `.im2col::w` and `.im2col::w::128` introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_90` or higher. + +Qualifier `.tile::gather4` is supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Qualifiers `.im2col::w` and `.im2col::w::128` are supported on following architectures: + + * `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * And are supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + + +Examples + + + .reg .b16 ctaMask, im2colwHalo, im2colOff; + .reg .u16 i2cOffW, i2cOffH, i2cOffD; + .reg .b64 l2CachePolicy; + + cp.async.bulk.prefetch.tensor.1d.L2.global.tile [tensorMap0, {tc0}]; + + @p cp.async.bulk.prefetch.tensor.2d.L2.global [tensorMap1, {tc0, tc1}]; + + @p cp.async.bulk.prefetch.tensor.5d.L2.global.im2col + [tensorMap2, {tc0, tc1, tc2, tc3, tc4}], {i2cOffW, i2cOffH, i2cOffD}; + + @p cp.async.bulk.prefetch.tensor.3d.L2.global.im2col.L2::cache_hint + [tensorMap3, {tc0, tc1, tc2}], {i2cOffW}, policy; + + cp.async.bulk.prefetch.tensor.2d.L2.global.tile::gather4 [tensorMap5, {col_idx, row_idx0, row_idx1, row_idx2, row_idx3}]; + + cp.async.bulk.prefetch.tensor.4d.L2.global.im2col::w::128 + [tensorMap4, {t0, t1, t2, t3}], {im2colwHalo, im2colOff}; + +##### 9.7.9.27.2. [Data Movement and Conversion Instructions: Bulk and Tensor copy completion instructions](<#data-movement-and-conversion-instructions-bulk-tensor-copy-completion>) + +###### 9.7.9.27.2.1. [Data Movement and Conversion Instructions: `cp.async.bulk.commit_group`](<#data-movement-and-conversion-instructions-cp-async-bulk-commit-group>) + +`cp.async.bulk.commit_group` + +Commits all prior initiated but uncommitted `cp.async.bulk` instructions into a _cp.async.bulk-group_. + +Syntax + + + cp.async.bulk.commit_group; + + +Description + +`cp.async.bulk.commit_group` instruction creates a new per-thread _bulk async-group_ and batches all prior `cp{.reduce}.async.bulk.{.prefetch}{.tensor}` instructions satisfying the following conditions into the new _bulk async-group_ : + + * The prior `cp{.reduce}.async.bulk.{.prefetch}{.tensor}` instructions use _bulk_group_ based completion mechanism, and + + * They are initiated by the executing thread but not committed to any _bulk async-group_. + + +If there are no uncommitted `cp{.reduce}.async.bulk.{.prefetch}{.tensor}` instructions then `cp.async.bulk.commit_group` results in an empty _bulk async-group_. + +An executing thread can wait for the completion of all `cp{.reduce}.async.bulk.{.prefetch}{.tensor}` operations in a _bulk async-group_ using `cp.async.bulk.wait_group`. + +There is no memory ordering guarantee provided between any two `cp{.reduce}.async.bulk.{.prefetch}{.tensor}` operations within the same _bulk async-group_. + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + cp.async.bulk.commit_group; + + +###### 9.7.9.27.2.2. [Data Movement and Conversion Instructions: `cp.async.bulk.wait_group`](<#data-movement-and-conversion-instructions-cp-async-bulk-wait-group>) + +`cp.async.bulk.wait_group` + +Wait for completion of _bulk async-groups_. + +Syntax + + + cp.async.bulk.wait_group{.read} N; + + +Description + +`cp.async.bulk.wait_group` instruction will cause the executing thread to wait until only N or fewer of the most recent _bulk async-groups_ are pending and all the prior _bulk async-groups_ committed by the executing threads are complete. For example, when N is 0, the executing thread waits on all the prior _bulk async-groups_ to complete. Operand N is an integer constant. + +By default, `cp.async.bulk.wait_group` instruction will cause the executing thread to wait until completion of all the bulk async operations in the specified _bulk async-group_. A bulk async operation includes the following: + + * Optionally, reading from the tensormap. + + * Reading from the source locations. + + * Writing to their respective destination locations. + + * Writes being made visible to the executing thread. + + +The optional `.read` modifier indicates that the waiting has to be done until all the bulk async operations in the specified _bulk async-group_ have completed: + + 1. reading from the tensormap + + 2. the reading from their source locations. + + +PTX ISA Notes + +Introduced in PTX ISA version 8.0. + +Target ISA Notes + +Requires `sm_90` or higher. + +Examples + + + cp.async.bulk.wait_group.read 0; + cp.async.bulk.wait_group 2; \ No newline at end of file diff --git a/content/cuda/docs/ptx-multimemld-reducemultimemstmultimemred/DOC.md b/content/cuda/docs/ptx-multimemld-reducemultimemstmultimemred/DOC.md new file mode 100644 index 00000000..e3a48efd --- /dev/null +++ b/content/cuda/docs/ptx-multimemld-reducemultimemstmultimemred/DOC.md @@ -0,0 +1,191 @@ +--- +name: ptx-multimemld-reducemultimemstmultimemred +description: The multimem.* operations operate on multimem addresses and accesses + all of the multiple memory locations which the multimem address points to. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.14. Data Movement and Conversion Instructions:multimem.ld_reduce,multimem.st,multimem.red + +--- +title: "9.7.9.14. Data Movement and Conversion Instructions:multimem.ld_reduce,multimem.st,multimem.red" +section: 9.7.9.14 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.14. Data Movement and Conversion Instructions:multimem.ld_reduce,multimem.st,multimem.red + + +The multimem.* operations operate on multimem addresses and accesses all of the multiple memory locations which the multimem address points to. + +Multimem addresses can only be accessed only by multimem.* operations. Accessing a multimem address with `ld`, `st` or any other memory operations results in undefined behavior. + +Refer to _CUDA programming guide_ for creation and management of the multimem addresses. + +`multimem.ld_reduce`, `multimem.st`, `multimem.red` + +Perform memory operations on the multimem address. + +Syntax + +// Integer type: + + multimem.ld_reduce{.ldsem}{.scope}{.ss}.op.type d, [a]; + multimem.ld_reduce.weak{.ss}.op.type d, [a]; + + multimem.st{.stsem}{.scope}{.ss}.type [a], b; + multimem.st.weak{.ss}.type [a], b; + + multimem.red{.redsem}{.scope}{.ss}.op.type [a], b; + + .ss = { .global } + .ldsem = { .relaxed, .acquire } + .stsem = { .relaxed, .release } + .redsem = { .relaxed, .release } + .scope = { .cta, .cluster, .gpu, .sys } + .op = { .min, .max, .add, .and, .or, .xor } + .type = { .b32, .b64, .u32, .u64, .s32, .s64 } + + // Floating point type: + + multimem.ld_reduce{.ldsem}{.scope}{.ss}.op{.acc_prec}{.vec}.type d, [a]; + multimem.ld_reduce.weak{.ss}.op{.acc_prec}{.vec}.type d, [a]; + + multimem.st{.stsem}{.scope}{.ss}{.vec}.type [a], b; + multimem.st.weak{.ss}{.vec}.type [a], b; + + multimem.red{.redsem}{.scope}{.ss}.redop{.vec}.redtype [a], b; + + .ss = { .global } + .ldsem = { .relaxed, .acquire } + .stsem = { .relaxed, .release } + .redsem = { .relaxed, .release } + .scope = { .cta, .cluster, .gpu, .sys } + .op = { .min, .max, .add } + .redop = { .add } + .acc_prec = { .acc::f32, .acc::f16 } + .vec = { .v2, .v4, .v8 } + .type= { .f16, .f16x2, .bf16, .bf16x2, .f32, .f64, .e5m2, .e5m2x2, .e5m2x4, .e4m3, .e4m3x2, .e4m3x4 } + .redtype = { .f16, .f16x2, .bf16, .bf16x2, .f32, .f64 } + +Description + +Instruction `multimem.ld_reduce` performs the following operations: + +* load operation on the multimem address `a`, which involves loading of data from all of the multiple memory locations pointed to by the multimem address `a`, + + * reduction operation specified by `.op` on the multiple data loaded from the multimem address `a`. + +The result of the reduction operation in returned in register `d`. + +Instruction `multimem.st` performs a store operation of the input operand `b` to all the memory locations pointed to by the multimem address `a`. + +Instruction `multimem.red` performs a reduction operation on all the memory locations pointed to by the multimem address `a`, with operand `b`. + +Instruction `multimem.ld_reduce` performs reduction on the values loaded from all the memory locations that the multimem address points to. In contrast, the `multimem.red` perform reduction on all the memory locations that the multimem address points to. + +Address operand `a` must be a multimem address. Otherwise, the behavior is undefined. Supported addressing modes for operand a and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>). + +If no state space is specified then [Generic Addressing](<#generic-addressing>) is used. If the address specified by `a` does not fall within the address window of `.global` state space then the behavior is undefined. + +For floating-point type multi- operations, the size of the specified type along with `.vec` must equal either 32-bits or 64-bits or 128-bits. No other combinations of `.vec` and type are allowed. Type `.f64` cannot be used with `.vec` qualifier. The following table describes the valid usage of `.vec` and base floating-point type: + +.vec | Base float-type supported +---|--- +No `.vec` specified | `.f16x2`, `.bf16x2`, `.f32`, `.f64`, `.e5m2x4`, `.e4m3x4` +`.v2` | `.f16`, `.f16x2`, `.bf16`, `.bf16x2` `.f32`, `.e5m2x2`, `.e5m2x4`, `.e4m3x2`, `.e4m3x4` +`.v4` | `.f16`, `.f16x2`, `.bf16`, `.bf16x2` `.f32`, `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` +`.v8` | `.f16`, `.bf16`, `.e5m2`, `.e4m3`, `.e5m2x2`, `.e4m3x2` + +The following table describes the valid combinations of `.op` and base type: + +op | Base type +---|--- +`.add` | `.u32`, `.u64`, `.s32` `.f16`, `.f16x2`, `.bf16`, `.bf16x2` `.f32`, `.f64`, `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` +`.and`, `.or`, `.xor` | `.b32`, `.b64` +`.min`, `.max` | `.u32`, `.s32`, `.u64`, `.s64` `.f16`, `.f16x2`, `.bf16`, `.bf16x2` `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` + +For `multimem.ld_reduce`, the default precision of the intermediate accumulation is same as the specified type. + +Optionally, `.acc_prec` qualifier can be specified to change the precision of intermediate accumulation as follows: + +.type | .acc::prec | Changes precision to +---|---|--- +`.f16`, `.f16x2`, `.bf16`, `.bf16x2` | `.acc::f32` | `.f32` +`.e5m2`, `.e4m3`, `.e5m2x2`, `.e4m3x2`, `.e4m3x4`, `.e5m2x4` | `.acc::f16` | `.f16` + +Optional qualifiers `.ldsem`, `.stsem` and `.redsem` specify the memory synchronizing effect of the `multimem.ld_reduce`, `multimem.st` and `multimem.red` respectively, as described in [Memory Consistency Model](<#memory-consistency-model>). If explicit semantics qualifiers are not specified, then `multimem.ld_reduce` and `multimem.st` default to `.weak` and `multimem.red` defaults to `.relaxed`. + +The optional `.scope` qualifier specifies the set of threads that can directly observe the memory synchronizing effect of this operation, as described in [Memory Consistency Model](<#memory-consistency-model>). If the `.scope` qualifier is not specified for `multimem.red` then `.sys` scope is assumed by default. + +PTX ISA Notes + +Introduced in PTX ISA version 8.1. + +Support for `.acc::f32` qualifier introduced in PTX ISA version 8.2. + +Support for types `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` introduced in PTX ISA version 8.6. + +Support for `.acc::f16` qualifier introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_90` or higher. + +Types `.e5m2`, `.e5m2x2`, `.e5m2x4`, `.e4m3`, `.e4m3x2`, `.e4m3x4` are supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * `sm_121a` + + * And are supported on following family-specific architectures from PTX ISA version 8.8: + + * `sm_100f` or higher in the same family + + * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + +Qualifier `.acc::f16` is supported on following architectures: + +* `sm_100a` + + * `sm_101a` (Renamed to `sm_110a` from PTX ISA version 9.0) + + * `sm_120a` + + * `sm_121a` + + * And is supported on following family-specific architectures from PTX ISA version 8.8: + +> * `sm_100f` or higher in the same family +> +> * `sm_101f` or higher in the same family (Renamed to `sm_110f` from PTX ISA version 9.0) + + * `sm_110f` or higher in the same family + +Examples + +multimem.ld_reduce.and.b32 val1_b32, [addr1]; + multimem.ld_reduce.acquire.gpu.global.add.u32 val2_u32, [addr2]; + + multimem.st.relaxed.gpu.b32 [addr3], val3_b32; + multimem.st.release.cta.global.u32 [addr4], val4_u32; + + multimem.red.relaxed.gpu.max.f64 [addr5], val5_f64; + multimem.red.release.cta.global.add.v4.f32 [addr6], {val6, val7, val8, val9}; + multimem.ld_reduce.add.acc::f32.v2.f16x2 {val_10, val_11}, [addr7]; + + multimem.ld_reduce.relaxed.cta.min.v2.e4m3x2 {val_12, val_13}, [addr8]; + multimem.ld_reduce.relaxed.cta.add.v4.e4m3 {val_14, val_15, val_16, val_17}, [addr9]; + multimem.ld_reduce.add.acc::f16.v4.e5m2 {val_18, val_19, val_20, val_21}, [addr10]; \ No newline at end of file diff --git a/content/cuda/docs/ptx-nanosleep/DOC.md b/content/cuda/docs/ptx-nanosleep/DOC.md new file mode 100644 index 00000000..afcb4ced --- /dev/null +++ b/content/cuda/docs/ptx-nanosleep/DOC.md @@ -0,0 +1,53 @@ +--- +name: ptx-nanosleep +description: Suspend the thread for an approximate delay given in nanoseconds. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.19.2. Miscellaneous Instructions:nanosleep + +--- +title: "9.7.19.2. Miscellaneous Instructions:nanosleep" +section: 9.7.19.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.19.2. Miscellaneous Instructions:nanosleep + + +`nanosleep` + +Suspend the thread for an approximate delay given in nanoseconds. + +Syntax + +nanosleep.u32 t; + +Description + +Suspends the thread for a sleep duration approximately close to the delay `t`, specified in nanoseconds. `t` may be a register or an immediate value. + +The sleep duration is approximated, but guaranteed to be in the interval `[0, 2*t]`. The maximum sleep duration is 1 millisecond. The implementation may reduce the sleep duration for individual threads within a warp such that all sleeping threads in the warp wake up together. + +PTX ISA Notes + +`nanosleep` introduced in PTX ISA 6.3. + +Target ISA Notes + +`nanosleep` requires `sm_70` or higher. + +Examples + +.reg .b32 r; + .reg .pred p; + + nanosleep.u32 r; + nanosleep.u32 42; + @p nanosleep.u32 r; \ No newline at end of file diff --git a/content/cuda/docs/ptx-neg/DOC.md b/content/cuda/docs/ptx-neg/DOC.md new file mode 100644 index 00000000..e0926a5e --- /dev/null +++ b/content/cuda/docs/ptx-neg/DOC.md @@ -0,0 +1,73 @@ +--- +name: ptx-neg +description: Arithmetic negate. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.10. Floating Point Instructions:neg + +--- +title: "9.7.3.10. Floating Point Instructions:neg" +section: 9.7.3.10 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.10. Floating Point Instructions:neg + + +`neg` + +Arithmetic negate. + +Syntax + +neg{.ftz}.f32 d, a; + neg.f64 d, a; + +Description + +Negate the sign of `a` and store the result in `d`. + +Semantics + +d = -a; + +Notes + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`neg.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`neg.f64` supports subnormal numbers. + +`neg.f32` flushes subnormal inputs and results to sign-preserving zero. + +`NaN` inputs yield an unspecified `NaN`. Future implementations may comply with the IEEE 754 standard by preserving payload and modifying only the sign bit. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +`neg.f32` supported on all target architectures. + +`neg.f64` requires `sm_13` or higher. + +Examples + +neg.ftz.f32 x,f0; \ No newline at end of file diff --git a/content/cuda/docs/ptx-no-thin-air/DOC.md b/content/cuda/docs/ptx-no-thin-air/DOC.md new file mode 100644 index 00000000..65884d98 --- /dev/null +++ b/content/cuda/docs/ptx-no-thin-air/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-no-thin-air +description: "Values may not appear \u201Cout of thin air\u201D: an execution cannot\ + \ speculatively produce a value in such a way that the speculation becomes self-satisfying\ + \ through chains of instruction dependencies and int..." +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.10.4. No Thin Air + +--- +title: "8.10.4. No Thin Air" +section: 8.10.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.10.4. No Thin Air + + +Values may not appear “out of thin air”: an execution cannot speculatively produce a value in such a way that the speculation becomes self-satisfying through chains of instruction dependencies and inter-thread communication. This matches both programmer intuition and hardware reality, but is necessary to state explicitly when performing formal analysis. + +Litmus Test: Load Buffering + +.global .u32 x = 0; + .global .u32 y = 0; + + +--- +T1 | T2 + + + A1: ld.global.u32 %r0, [x]; + B1: st.global.u32 [y], %r0; + + +| + + + A2: ld.global.u32 %r1, [y]; + B2: st.global.u32 [x], %r1; + + + + FINAL STATE: x == 0 AND y == 0 + +The litmus test known as “LB” (Load Buffering) checks such forbidden values that may arise out of thin air. Two threads T1 and T2 each read from a first variable and copy the observed result into a second variable, with the first and second variable exchanged between the threads. If each variable is initially zero, the final result shall also be zero. If A1 reads from B2 and A2 reads from B1, then values passing through the memory operations in this example form a cycle: A1->B1->A2->B2->A1. Only the values x == 0 and y == 0 are allowed to satisfy this cycle. If any of the memory operations in this example were to speculatively associate a different value with the corresponding memory location, then such a speculation would become self-fulfilling, and hence forbidden. \ No newline at end of file diff --git a/content/cuda/docs/ptx-not/DOC.md b/content/cuda/docs/ptx-not/DOC.md new file mode 100644 index 00000000..a4673cc5 --- /dev/null +++ b/content/cuda/docs/ptx-not/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-not +description: "Bitwise negation; one\u2019s complement." +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.8.4. Logic and Shift Instructions:not + +--- +title: "9.7.8.4. Logic and Shift Instructions:not" +section: 9.7.8.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.8.4. Logic and Shift Instructions:not + + +`not` + +Bitwise negation; one’s complement. + +Syntax + +not.type d, a; + + .type = { .pred, .b16, .b32, .b64 }; + +Description + +Invert the bits in `a`. + +Semantics + +d = ~a; + +Notes + +The size of the operands must match, but not necessarily the type. + +Allowed types include predicates. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +not.b32 mask,mask; + not.pred p,q; \ No newline at end of file diff --git a/content/cuda/docs/ptx-notice/DOC.md b/content/cuda/docs/ptx-notice/DOC.md new file mode 100644 index 00000000..69335656 --- /dev/null +++ b/content/cuda/docs/ptx-notice/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-notice +description: "This document is provided for information purposes only and shall not\ + \ be regarded as a warranty of a certain functionality, condition, or quality of\ + \ a product. NVIDIA Corporation (\u201CNVIDIA\u201D) makes no r..." +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 14.1. Notice + +--- +title: "14.1. Notice" +section: 14.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 14.1. Notice + + +This document is provided for information purposes only and shall not be regarded as a warranty of a certain functionality, condition, or quality of a product. NVIDIA Corporation (“NVIDIA”) makes no representations or warranties, expressed or implied, as to the accuracy or completeness of the information contained in this document and assumes no responsibility for any errors contained herein. NVIDIA shall have no liability for the consequences or use of such information or for any infringement of patents or other rights of third parties that may result from its use. This document is not a commitment to develop, release, or deliver any Material (defined below), code, or functionality. + +NVIDIA reserves the right to make corrections, modifications, enhancements, improvements, and any other changes to this document, at any time without notice. + +Customer should obtain the latest relevant information before placing orders and should verify that such information is current and complete. + +NVIDIA products are sold subject to the NVIDIA standard terms and conditions of sale supplied at the time of order acknowledgement, unless otherwise agreed in an individual sales agreement signed by authorized representatives of NVIDIA and customer (“Terms of Sale”). NVIDIA hereby expressly objects to applying any customer general terms and conditions with regards to the purchase of the NVIDIA product referenced in this document. No contractual obligations are formed either directly or indirectly by this document. + +NVIDIA products are not designed, authorized, or warranted to be suitable for use in medical, military, aircraft, space, or life support equipment, nor in applications where failure or malfunction of the NVIDIA product can reasonably be expected to result in personal injury, death, or property or environmental damage. NVIDIA accepts no liability for inclusion and/or use of NVIDIA products in such equipment or applications and therefore such inclusion and/or use is at customer’s own risk. + +NVIDIA makes no representation or warranty that products based on this document will be suitable for any specified use. Testing of all parameters of each product is not necessarily performed by NVIDIA. It is customer’s sole responsibility to evaluate and determine the applicability of any information contained in this document, ensure the product is suitable and fit for the application planned by customer, and perform the necessary testing for the application in order to avoid a default of the application or the product. Weaknesses in customer’s product designs may affect the quality and reliability of the NVIDIA product and may result in additional or different conditions and/or requirements beyond those contained in this document. NVIDIA accepts no liability related to any default, damage, costs, or problem which may be based on or attributable to: (i) the use of the NVIDIA product in any manner that is contrary to this document or (ii) customer product designs. + +No license, either expressed or implied, is granted under any NVIDIA patent right, copyright, or other NVIDIA intellectual property right under this document. Information published by NVIDIA regarding third-party products or services does not constitute a license from NVIDIA to use such products or services or a warranty or endorsement thereof. Use of such information may require a license from a third party under the patents or other intellectual property rights of the third party, or a license from NVIDIA under the patents or other intellectual property rights of NVIDIA. + +Reproduction of information in this document is permissible only if approved in advance by NVIDIA in writing, reproduced without alteration and in full compliance with all applicable export laws and regulations, and accompanied by all associated conditions, limitations, and notices. + +THIS DOCUMENT AND ALL NVIDIA DESIGN SPECIFICATIONS, REFERENCE BOARDS, FILES, DRAWINGS, DIAGNOSTICS, LISTS, AND OTHER DOCUMENTS (TOGETHER AND SEPARATELY, “MATERIALS”) ARE BEING PROVIDED “AS IS.” NVIDIA MAKES NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL NVIDIA BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF ANY USE OF THIS DOCUMENT, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Notwithstanding any damages that customer might incur for any reason whatsoever, NVIDIA’s aggregate and cumulative liability towards customer for the products described herein shall be limited in accordance with the Terms of Sale for the product. \ No newline at end of file diff --git a/content/cuda/docs/ptx-observation-order/DOC.md b/content/cuda/docs/ptx-observation-order/DOC.md new file mode 100644 index 00000000..a810ad04 --- /dev/null +++ b/content/cuda/docs/ptx-observation-order/DOC.md @@ -0,0 +1,31 @@ +--- +name: ptx-observation-order +description: _Observation order_ relates a write W to a read R through an optional + sequence of atomic read-modify-write operations. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.9.2. Observation Order + +--- +title: "8.9.2. Observation Order" +section: 8.9.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.9.2. Observation Order + + +_Observation order_ relates a write W to a read R through an optional sequence of atomic read-modify-write operations. + +A write W precedes a read R in _observation order_ if: + +1. R and W are _morally strong_ and R reads the value written by W, or + + 2. For some atomic operation Z, W precedes Z and Z precedes R in _observation order_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-on-chip-shared-memory/DOC.md b/content/cuda/docs/ptx-on-chip-shared-memory/DOC.md new file mode 100644 index 00000000..9fd275ee --- /dev/null +++ b/content/cuda/docs/ptx-on-chip-shared-memory/DOC.md @@ -0,0 +1,35 @@ +--- +name: ptx-on-chip-shared-memory +description: 'As illustrated by [Figure 4](<#set-of-simt-multiprocessors-hardware-model>), + each multiprocessor has on-chip memory of the four following types:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 3.3. On-chip Shared Memory + +--- +title: "3.3. On-chip Shared Memory" +section: 3.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 3.3. On-chip Shared Memory + + +As illustrated by [Figure 4](<#set-of-simt-multiprocessors-hardware-model>), each multiprocessor has on-chip memory of the four following types: + +* One set of local 32-bit _registers_ per processor, + + * A parallel data cache or _shared memory_ that is shared by all scalar processor cores and is where the shared memory space resides, + + * A read-only _constant cache_ that is shared by all scalar processor cores and speeds up reads from the constant memory space, which is a read-only region of device memory, + + * A read-only _texture cache_ that is shared by all scalar processor cores and speeds up reads from the texture memory space, which is a read-only region of device memory; each multiprocessor accesses the texture cache via a _texture unit_ that implements the various addressing modes and data filtering. + +The local and global memory spaces are read-write regions of device memory. \ No newline at end of file diff --git a/content/cuda/docs/ptx-opencl/DOC.md b/content/cuda/docs/ptx-opencl/DOC.md new file mode 100644 index 00000000..ff9fda75 --- /dev/null +++ b/content/cuda/docs/ptx-opencl/DOC.md @@ -0,0 +1,25 @@ +--- +name: ptx-opencl +description: OpenCL is a trademark of Apple Inc. used under license to the Khronos + Group Inc. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 14.2. OpenCL + +--- +title: "14.2. OpenCL" +section: 14.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 14.2. OpenCL + + +OpenCL is a trademark of Apple Inc. used under license to the Khronos Group Inc. \ No newline at end of file diff --git a/content/cuda/docs/ptx-operand-costs/DOC.md b/content/cuda/docs/ptx-operand-costs/DOC.md new file mode 100644 index 00000000..c2c8e2d8 --- /dev/null +++ b/content/cuda/docs/ptx-operand-costs/DOC.md @@ -0,0 +1,38 @@ +--- +name: ptx-operand-costs +description: Operands from different state spaces affect the speed of an operation. + Registers are fastest, while global memory is slowest. Much of the delay to memory + can be hidden in a number of ways. The first i... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.6. Operand Costs + +--- +title: "6.6. Operand Costs" +section: 6.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 6.6. Operand Costs + + +Operands from different state spaces affect the speed of an operation. Registers are fastest, while global memory is slowest. Much of the delay to memory can be hidden in a number of ways. The first is to have multiple threads of execution so that the hardware can issue a memory operation and then switch to other execution. Another way to hide latency is to issue the load instructions as early as possible, as execution is not blocked until the desired result is used in a subsequent (in time) instruction. The register in a store operation is available much more quickly. [Table 19](<#operand-costs-cost-estimates-for-sccessing-state-spaces>) gives estimates of the costs of using different kinds of memory. + +Table 19 Cost Estimates for Accessing State-Spaces Space | Time | Notes +---|---|--- +Register | 0 | +Shared | 0 | +Constant | 0 | Amortized cost is low, first access is high +Local | > 100 clocks | +Parameter | 0 | +Immediate | 0 | +Global | > 100 clocks | +Texture | > 100 clocks | +Surface | > 100 clocks | \ No newline at end of file diff --git a/content/cuda/docs/ptx-operand-size-exceeding-instruction-type-size/DOC.md b/content/cuda/docs/ptx-operand-size-exceeding-instruction-type-size/DOC.md new file mode 100644 index 00000000..ced0be1e --- /dev/null +++ b/content/cuda/docs/ptx-operand-size-exceeding-instruction-type-size/DOC.md @@ -0,0 +1,86 @@ +--- +name: ptx-operand-size-exceeding-instruction-type-size +description: For convenience, `ld`, `st`, and `cvt` instructions permit source and + destination data operands to be wider than the instruction-type size, so that narrow + values may be loaded, stored, and converted u... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.4.1. Operand Size Exceeding Instruction-Type Size + +--- +title: "9.4.1. Operand Size Exceeding Instruction-Type Size" +section: 9.4.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 9.4.1. Operand Size Exceeding Instruction-Type Size + + +For convenience, `ld`, `st`, and `cvt` instructions permit source and destination data operands to be wider than the instruction-type size, so that narrow values may be loaded, stored, and converted using regular-width registers. For example, 8-bit or 16-bit values may be held directly in 32-bit or 64-bit registers when being loaded, stored, or converted to other types and sizes. The operand type checking rules are relaxed for bit-size and integer (signed and unsigned) instruction types; floating-point instruction types still require that the operand type-size matches exactly, unless the operand is of bit-size type. + +When a source operand has a size that exceeds the instruction-type size, the source data is truncated (chopped) to the appropriate number of bits specified by the instruction type-size. + +[Table 27](<#operand-size-exceeding-instruction-type-size-relaxed-type-checking-rules-source-operands>) summarizes the relaxed type-checking rules for source operands. Note that some combinations may still be invalid for a particular instruction; for example, the `cvt` instruction does not support `.bX` instruction types, so those rows are invalid for `cvt`. + +Table 27 Relaxed Type-checking Rules for Source Operands | **Source Operand Type** +---|--- +**b8** | **b16** | **b32** | **b64** | **b128** | **s8** | **s16** | **s32** | **s64** | **u8** | **u16** | **u32** | **u64** | **f16** | **f32** | **f64** +**Instruction Type** | **b8** | – | chop | chop | chop | chop | – | chop | chop | chop | – | chop | chop | chop | chop | chop | chop +**b16** | inv | – | chop | chop | chop | inv | – | chop | chop | inv | – | chop | chop | – | chop | chop +**b32** | inv | inv | – | chop | chop | inv | inv | – | chop | inv | inv | – | chop | inv | – | chop +**b64** | inv | inv | inv | – | chop | inv | inv | inv | – | inv | inv | inv | – | inv | inv | – +**b128** | inv | inv | inv | inv | – | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv +**s8** | – | chop | chop | chop | chop | – | chop | chop | chop | – | chop | chop | chop | inv | inv | inv +**s16** | inv | – | chop | chop | chop | inv | – | chop | chop | inv | – | chop | chop | inv | inv | inv +**s32** | inv | inv | – | chop | chop | inv | inv | – | chop | inv | inv | – | chop | inv | inv | inv +**s64** | inv | inv | inv | – | chop | inv | inv | inv | – | inv | inv | inv | – | inv | inv | inv +**u8** | – | chop | chop | chop | chop | – | chop | chop | chop | – | chop | chop | chop | inv | inv | inv +**u16** | inv | – | chop | chop | chop | inv | – | chop | chop | inv | – | chop | chop | inv | inv | inv +**u32** | inv | inv | – | chop | chop | inv | inv | – | chop | inv | inv | – | chop | inv | inv | inv +**u64** | inv | inv | inv | – | chop | inv | inv | inv | – | inv | inv | inv | – | inv | inv | inv +**f16** | inv | – | chop | chop | chop | inv | inv | inv | inv | inv | inv | inv | inv | – | inv | inv +**f32** | inv | inv | – | chop | chop | inv | inv | inv | inv | inv | inv | inv | inv | inv | – | inv +**f64** | inv | inv | inv | – | chop | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv | – +**Notes** | chop = keep only low bits that fit; “–” = allowed, but no conversion needed; inv = invalid, parse error. + + 1. Source register size must be of equal or greater size than the instruction-type size. + 2. Bit-size source registers may be used with any appropriately-sized instruction type. The data are truncated (“chopped”) to the instruction-type size and interpreted according to the instruction type. + 3. Integer source registers may be used with any appropriately-sized bit-size or integer instruction type. The data are truncated to the instruction-type size and interpreted according to the instruction type. + 4. Floating-point source registers can only be used with bit-size or floating-point instruction types. When used with a narrower bit-size instruction type, the data are truncated. When used with a floating-point instruction type, the size must match exactly. + +When a destination operand has a size that exceeds the instruction-type size, the destination data is zero- or sign-extended to the size of the destination register. If the corresponding instruction type is signed integer, the data is sign-extended; otherwise, the data is zero-extended. + +[Table 28](<#operand-size-exceeding-instruction-type-size-relaxed-type-checking-rules-destination-operands>) summarizes the relaxed type-checking rules for destination operands. + +Table 28 Relaxed Type-checking Rules for Destination Operands | **Destination Operand Type** +---|--- +**b8** | **b16** | **b32** | **b64** | **b128** | **s8** | **s16** | **s32** | **s64** | **u8** | **u16** | **u32** | **u64** | **f16** | **f32** | **f64** +**Instruction Type** | **b8** | – | zext | zext | zext | zext | – | zext | zext | zext | – | zext | zext | zext | zext | zext | zext +**b16** | inv | – | zext | zext | zext | inv | – | zext | zext | inv | – | zext | zext | – | zext | zext +**b32** | inv | inv | – | zext | zext | inv | inv | – | zext | inv | inv | – | zext | inv | – | zext +**b64** | inv | inv | inv | – | zext | inv | inv | inv | – | inv | inv | inv | – | inv | inv | – +**b128** | inv | inv | inv | inv | – | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv +**s8** | – | sext | sext | sext | sext | – | sext | sext | sext | – | sext | sext | sext | inv | inv | inv +**s16** | inv | – | sext | sext | sext | inv | – | sext | sext | inv | – | sext | sext | inv | inv | inv +**s32** | inv | inv | – | sext | sext | inv | inv | – | sext | inv | inv | – | sext | inv | inv | inv +**s64** | inv | inv | inv | – | sext | inv | inv | inv | – | inv | inv | inv | – | inv | inv | inv +**u8** | – | zext | zext | zext | zext | – | zext | zext | zext | – | zext | zext | zext | inv | inv | inv +**u16** | inv | – | zext | zext | zext | inv | – | zext | zext | inv | – | zext | zext | inv | inv | inv +**u32** | inv | inv | – | zext | zext | inv | inv | – | zext | inv | inv | – | zext | inv | inv | inv +**u64** | inv | inv | inv | – | zext | inv | inv | inv | – | inv | inv | inv | – | inv | inv | inv +**f16** | inv | – | zext | zext | zext | inv | inv | inv | inv | inv | inv | inv | inv | – | inv | inv +**f32** | inv | inv | – | zext | zext | inv | inv | inv | inv | inv | inv | inv | inv | inv | – | inv +**f64** | inv | inv | inv | – | zext | inv | inv | inv | inv | inv | inv | inv | inv | inv | inv | – +**Notes** | sext = sign-extend; zext = zero-extend; “–” = allowed, but no conversion needed; inv = invalid, parse error. + + 1. Destination register size must be of equal or greater size than the instruction-type size. + 2. Bit-size destination registers may be used with any appropriately-sized instruction type. The data are sign-extended to the destination register width for signed integer instruction types, and are zero-extended to the destination register width otherwise. + 3. Integer destination registers may be used with any appropriately-sized bit-size or integer instruction type. The data are sign-extended to the destination register width for signed integer instruction types, and are zero-extended to the destination register width for bit-size an d unsigned integer instruction types. + 4. Floating-point destination registers can only be used with bit-size or floating-point instruction types. When used with a narrower bit-size instruction type, the data are zero-extended. When used with a floating-point instruction type, the size must match exactly. \ No newline at end of file diff --git a/content/cuda/docs/ptx-operand-type-information/DOC.md b/content/cuda/docs/ptx-operand-type-information/DOC.md new file mode 100644 index 00000000..a450c792 --- /dev/null +++ b/content/cuda/docs/ptx-operand-type-information/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-operand-type-information +description: All operands in instructions have a known type from their declarations. + Each operand type must be compatible with the type determined by the instruction + template and instruction type. There is no auto... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.1. Operand Type Information + +--- +title: "6.1. Operand Type Information" +section: 6.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 6.1. Operand Type Information + + +All operands in instructions have a known type from their declarations. Each operand type must be compatible with the type determined by the instruction template and instruction type. There is no automatic conversion between types. + +The bit-size type is compatible with every type having the same size. Integer types of a common size are compatible with each other. Operands having type different from but compatible with the instruction type are silently cast to the instruction type. \ No newline at end of file diff --git a/content/cuda/docs/ptx-or/DOC.md b/content/cuda/docs/ptx-or/DOC.md new file mode 100644 index 00000000..5cd08a49 --- /dev/null +++ b/content/cuda/docs/ptx-or/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-or +description: Biwise OR. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.8.2. Logic and Shift Instructions:or + +--- +title: "9.7.8.2. Logic and Shift Instructions:or" +section: 9.7.8.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.8.2. Logic and Shift Instructions:or + + +`or` + +Biwise OR. + +Syntax + +or.type d, a, b; + + .type = { .pred, .b16, .b32, .b64 }; + +Description + +Compute the bit-wise or operation for the bits in `a` and `b`. + +Semantics + +d = a | b; + +Notes + +The size of the operands must match, but not necessarily the type. + +Allowed types include predicate registers. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +or.b32 mask mask,0x00010001 + or.pred p,q,r; \ No newline at end of file diff --git a/content/cuda/docs/ptx-out-of-boundary-access/DOC.md b/content/cuda/docs/ptx-out-of-boundary-access/DOC.md new file mode 100644 index 00000000..d703a3f9 --- /dev/null +++ b/content/cuda/docs/ptx-out-of-boundary-access/DOC.md @@ -0,0 +1,39 @@ +--- +name: ptx-out-of-boundary-access +description: 'PTX Tensor operation can detect and handle the case when the Bounding + Box crosses the tensor boundary in any dimension. There are 2 modes:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.5.3.3. Out of Boundary Access + +--- +title: "5.5.3.3. Out of Boundary Access" +section: 5.5.3.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.5.3.3. Out of Boundary Access + + +PTX Tensor operation can detect and handle the case when the Bounding Box crosses the tensor boundary in any dimension. There are 2 modes: + +* Zero fill mode: + +Elements in the Bounding Box which fall outside of the tensor boundary are set to 0. + + * `OOB-NaN` fill mode: + +Elements in the Bounding Box which fall outside of the tensor boundary are set to a special NaN called `OOB-NaN`. + +[Figure 9](<#tensor-oob-access>) shows an example of the out of boundary access. + +![_images/tensor-oob-access.png](https://docs.nvidia.com/cuda/parallel-thread-execution/_images/tensor-oob-access.png) + +Figure 9 Out of boundary access \ No newline at end of file diff --git a/content/cuda/docs/ptx-overlap/DOC.md b/content/cuda/docs/ptx-overlap/DOC.md new file mode 100644 index 00000000..d3bf5ba9 --- /dev/null +++ b/content/cuda/docs/ptx-overlap/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-overlap +description: Two memory locations are said to overlap when the starting address of + one location is within the range of bytes constituting the other location. Two memory + operations are said to overlap when they spe... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.2.1. Overlap + +--- +title: "8.2.1. Overlap" +section: 8.2.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.2.1. Overlap + + +Two memory locations are said to overlap when the starting address of one location is within the range of bytes constituting the other location. Two memory operations are said to overlap when they specify the same virtual address and the corresponding memory locations overlap. The overlap is said to be complete when both memory locations are identical, and it is said to be partial otherwise. \ No newline at end of file diff --git a/content/cuda/docs/ptx-packed-fixed-point-data-types/DOC.md b/content/cuda/docs/ptx-packed-fixed-point-data-types/DOC.md new file mode 100644 index 00000000..0e613f4b --- /dev/null +++ b/content/cuda/docs/ptx-packed-fixed-point-data-types/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-packed-fixed-point-data-types +description: PTX supports `.s2f6x2` packed fixed-point data type consisting of two + `.s2f6` packed fixed-point values. A register variable containing `.s2f6x2` value + must be declared with `.b16` type. Packed fixed-... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.5.3. Packed Fixed-Point Data Types + +--- +title: "5.2.5.3. Packed Fixed-Point Data Types" +section: 5.2.5.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.2.5.3. Packed Fixed-Point Data Types + + +PTX supports `.s2f6x2` packed fixed-point data type consisting of two `.s2f6` packed fixed-point values. A register variable containing `.s2f6x2` value must be declared with `.b16` type. Packed fixed-point data type cannot be used as fundamental type and is only supported as instruction type. \ No newline at end of file diff --git a/content/cuda/docs/ptx-packed-floating-point-data-types/DOC.md b/content/cuda/docs/ptx-packed-floating-point-data-types/DOC.md new file mode 100644 index 00000000..3f7867cc --- /dev/null +++ b/content/cuda/docs/ptx-packed-floating-point-data-types/DOC.md @@ -0,0 +1,44 @@ +--- +name: ptx-packed-floating-point-data-types +description: PTX supports various variants of packed floating point data types. Out + of them, only `.f16x2` is supported as a fundamental type, while others cannot be + used as fundamental types - they are supported ... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.5.1. Packed Floating Point Data Types + +--- +title: "5.2.5.1. Packed Floating Point Data Types" +section: 5.2.5.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.2.5.1. Packed Floating Point Data Types + + +PTX supports various variants of packed floating point data types. Out of them, only `.f16x2` is supported as a fundamental type, while others cannot be used as fundamental types - they are supported as instruction types on certain instructions. When using an instruction with such non-fundamental types, the operand data variables must be of bit type of appropriate size. For example, all of the operand variables must be of type `.b32` for an instruction with instruction type as `.bf16x2`. [Table 9](<#operand-types-for-packed-floating-point-instruction-type>) described various variants of packed floating point data types in PTX. + +Table 9 Operand types for packed floating point instruction type. Packed floating point type | Number of elements contained in a packed format | Type of each element | Register variable type to be used in the declaration +---|---|---|--- +`.f16x2` | Two | `.f16` | `.f16x2` or `.b32` +`.f32x2` | `.f32` | `.b64` +`.bf16x2` | `.bf16` | `.b32` +`.e4m3x2` | `.e4m3` | `.b16` +`.e5m2x2` | `.e5m2` +`.e2m3x2` | `.e2m3` +`.e3m2x2` | `.e3m2` +`.ue8m0x2` | `.ue8m0` +`.s2f6x2` | `.s2f6` +`.e2m1x2` | `.e2m1` | `.b8` +`.e4m3x4` | Four | `.e4m3` | `.b32` +`.e5m2x4` | `.e5m2` +`.e2m3x4` | `.e2m3` +`.e3m2x4` | `.e3m2` +`.e2m1x4` | `.e2m1` | `.b16` \ No newline at end of file diff --git a/content/cuda/docs/ptx-packed-integer-data-types/DOC.md b/content/cuda/docs/ptx-packed-integer-data-types/DOC.md new file mode 100644 index 00000000..ab19793b --- /dev/null +++ b/content/cuda/docs/ptx-packed-integer-data-types/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-packed-integer-data-types +description: 'PTX supports two variants of packed integer data types: `.u16x2` and + `.s16x2`. The packed data type consists of two `.u16` or `.s16` values. A register + variable containing `.u16x2` or `.s16x2` data mu...' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.5.2. Packed Integer Data Types + +--- +title: "5.2.5.2. Packed Integer Data Types" +section: 5.2.5.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 5.2.5.2. Packed Integer Data Types + + +PTX supports two variants of packed integer data types: `.u16x2` and `.s16x2`. The packed data type consists of two `.u16` or `.s16` values. A register variable containing `.u16x2` or `.s16x2` data must be declared with `.b32` type. Packed integer data types cannot be used as fundamental types. They are supported as instruction types on certain instructions. \ No newline at end of file diff --git a/content/cuda/docs/ptx-parameterized-variable-names/DOC.md b/content/cuda/docs/ptx-parameterized-variable-names/DOC.md new file mode 100644 index 00000000..51e0154c --- /dev/null +++ b/content/cuda/docs/ptx-parameterized-variable-names/DOC.md @@ -0,0 +1,32 @@ +--- +name: ptx-parameterized-variable-names +description: Since PTX supports virtual registers, it is quite common for a compiler + frontend to generate a large number of register names. Rather than require explicit + declaration of every name, PTX supports a sy... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.4.6. Parameterized Variable Names + +--- +title: "5.4.6. Parameterized Variable Names" +section: 5.4.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.4.6. Parameterized Variable Names + + +Since PTX supports virtual registers, it is quite common for a compiler frontend to generate a large number of register names. Rather than require explicit declaration of every name, PTX supports a syntax for creating a set of variables having a common prefix string appended with integer suffixes. + +For example, suppose a program uses a large number, say one hundred, of `.b32` variables, named `%r0`, `%r1`, …, `%r99`. These 100 register variables can be declared as follows: + +.reg .b32 %r<100>; // declare %r0, %r1, ..., %r99 + +This shorthand syntax may be used with any of the fundamental types and with any state space, and may be preceded by an alignment specifier. Array variables cannot be declared this way, nor are initializers permitted. \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve-control/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve-control/DOC.md new file mode 100644 index 00000000..c39b7801 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve-control/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-performance-tuning-directivesabi-preserve-control +description: '`.abi_preserve_control`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.9. Performance-Tuning Directives:.abi_preserve_control + +--- +title: "11.4.9. Performance-Tuning Directives:.abi_preserve_control" +section: 11.4.9 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.9. Performance-Tuning Directives:.abi_preserve_control + + +`.abi_preserve_control` + +Specify number of control registers that should be preserved by the callers of this function. + +Syntax + +.abi_preserve_control N + +Description + +It is an architecture agnostic value specifying the number of divergent program points that happen in the calltree leading to current function call. Internally ABI defines some control registers as preserved (callee save) registers. Integer N specifies the actual number of control registers that should be preserved by the function. + +`.abi_preserve_control` directive can only be specified on device functions and must appear between a `.func` directive and its body. + +Semantics + +When this directive is specified compiler backend modifies low level ABI components to ensure that number of live control variables in the callers of this function that are stored in the callee save control registers are less than specified value. + +PTX ISA Notes + +Introduced in PTX ISA version 9.0. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + +.func foo() .abi_preserve_control 14 + + // Indirect call via call prototype + .func (.param .b32 out[30]) bar (.param .b32 in[30]) .abi_preserve_control 10 { ... } + ... + mov.b64 lpbar, bar; + prot: .callprototype (.param .b32 out[30]) _ (.param .b32 in[30]) .abi_preserve_control 10; + call (out), lpbar, (in), prot; \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve/DOC.md new file mode 100644 index 00000000..432d3aa2 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesabi-preserve/DOC.md @@ -0,0 +1,60 @@ +--- +name: ptx-performance-tuning-directivesabi-preserve +description: Specify number of general purpose registers that should be preserved + by the callers of this function. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.8. Performance-Tuning Directives:.abi_preserve + +--- +title: "11.4.8. Performance-Tuning Directives:.abi_preserve" +section: 11.4.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.8. Performance-Tuning Directives:.abi_preserve + + +`.abi_preserve` + +Specify number of general purpose registers that should be preserved by the callers of this function. + +Syntax + +.abi_preserve N + +Description + +It is an architecture agnostic value specifying actual number of general purpose registers. Internally ABI defines some general purpose registers as preserved (callee save) registers. Integer N specifies the actual number of general purpose registers that should be preserved by the function. + +`.abi_preserve` directive can only be specified on device functions and must appear between a `.func` directive and its body. + +Semantics + +When this directive is specified compiler backend modifies low level ABI components to ensure that number of live data variables in the callers of this function that are stored in the callee save registers are less than specified value. + +PTX ISA Notes + +Introduced in PTX ISA version 9.0. + +Target ISA Notes + +Requires `sm_80` or higher. + +Examples + +.func bar() .abi_preserve 8 + + // Indirect call via call prototype + .func (.param .b32 out[30]) foo (.param .b32 in[30]) .abi_preserve 10 { ... } + ... + mov.b64 lpfoo, foo; + prot: .callprototype (.param .b32 out[30]) _ (.param .b32 in[30]) .abi_preserve 10; + call (out), lpfoo, (in), prot; \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesmaxnctapersmdeprecated/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesmaxnctapersmdeprecated/DOC.md new file mode 100644 index 00000000..c0c7a993 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesmaxnctapersmdeprecated/DOC.md @@ -0,0 +1,50 @@ +--- +name: ptx-performance-tuning-directivesmaxnctapersmdeprecated +description: Maximum number of CTAs per SM. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.5. Performance-Tuning Directives:.maxnctapersm(deprecated) + +--- +title: "11.4.5. Performance-Tuning Directives:.maxnctapersm(deprecated)" +section: 11.4.5 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.5. Performance-Tuning Directives:.maxnctapersm(deprecated) + + +`.maxnctapersm` + +Maximum number of CTAs per SM. + +Syntax + +.maxnctapersm ncta + +Description + +Declare the maximum number of CTAs from the kernel’s grid that may be mapped to a single multiprocessor (SM). + +Notes + +Optimizations based on .maxnctapersm generally need `.maxntid` to be specified as well. The optimizing backend compiler uses `.maxntid` and `.maxnctapersm` to compute an upper-bound on per-thread register usage so that the specified number of CTAs can be mapped to a single multiprocessor. However, if the number of registers used by the backend is sufficiently lower than this bound, additional CTAs may be mapped to a single multiprocessor. For this reason, `.maxnctapersm` has been renamed to .minnctapersm in PTX ISA version 2.0. + +PTX ISA Notes + +Introduced in PTX ISA version 1.3. Deprecated in PTX ISA version 2.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo .maxntid 256 .maxnctapersm 4 { ... } \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesmaxnreg/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesmaxnreg/DOC.md new file mode 100644 index 00000000..a6063a59 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesmaxnreg/DOC.md @@ -0,0 +1,50 @@ +--- +name: ptx-performance-tuning-directivesmaxnreg +description: Maximum number of registers that can be allocated per thread. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.1. Performance-Tuning Directives:.maxnreg + +--- +title: "11.4.1. Performance-Tuning Directives:.maxnreg" +section: 11.4.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.1. Performance-Tuning Directives:.maxnreg + + +`.maxnreg` + +Maximum number of registers that can be allocated per thread. + +Syntax + +.maxnreg n + +Description + +Declare the maximum number of registers per thread in a CTA. + +Semantics + +The compiler guarantees that this limit will not be exceeded. The actual number of registers used may be less; for example, the backend may be able to compile to fewer registers, or the maximum number of registers may be further constrained by `.maxntid` and `.maxctapersm`. + +PTX ISA Notes + +Introduced in PTX ISA version 1.3. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo .maxnreg 16 { ... } // max regs per thread = 16 \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesmaxntid/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesmaxntid/DOC.md new file mode 100644 index 00000000..71436105 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesmaxntid/DOC.md @@ -0,0 +1,55 @@ +--- +name: ptx-performance-tuning-directivesmaxntid +description: Maximum number of threads in the thread block (CTA). +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.2. Performance-Tuning Directives:.maxntid + +--- +title: "11.4.2. Performance-Tuning Directives:.maxntid" +section: 11.4.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.2. Performance-Tuning Directives:.maxntid + + +`.maxntid` + +Maximum number of threads in the thread block (CTA). + +Syntax + +.maxntid nx + .maxntid nx, ny + .maxntid nx, ny, nz + +Description + +Declare the maximum number of threads in the thread block (CTA). This maximum is specified by giving the maximum extent of each dimension of the 1D, 2D, or 3D CTA. The maximum number of threads is the product of the maximum extent in each dimension. + +Semantics + +The maximum number of threads in the thread block, computed as the product of the maximum extent specified for each dimension, is guaranteed not to be exceeded in any invocation of the kernel in which this directive appears. Exceeding the maximum number of threads results in a runtime error or kernel launch failure. + +Note that this directive guarantees that the _total_ number of threads does not exceed the maximum, but does not guarantee that the limit in any particular dimension is not exceeded. + +PTX ISA Notes + +Introduced in PTX ISA version 1.3. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo .maxntid 256 { ... } // max threads = 256 + .entry bar .maxntid 16,16,4 { ... } // max threads = 1024 \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesminnctapersm/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesminnctapersm/DOC.md new file mode 100644 index 00000000..0359ab05 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesminnctapersm/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-performance-tuning-directivesminnctapersm +description: Minimum number of CTAs per SM. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.4. Performance-Tuning Directives:.minnctapersm + +--- +title: "11.4.4. Performance-Tuning Directives:.minnctapersm" +section: 11.4.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.4. Performance-Tuning Directives:.minnctapersm + + +`.minnctapersm` + +Minimum number of CTAs per SM. + +Syntax + +.minnctapersm ncta + +Description + +Declare the minimum number of CTAs from the kernel’s grid to be mapped to a single multiprocessor (SM). + +Notes + +Optimizations based on `.minnctapersm` need either `.maxntid` or `.reqntid` to be specified as well. + +If the total number of threads on a single SM resulting from `.minnctapersm` and `.maxntid` / `.reqntid` exceed maximum number of threads supported by an SM then directive `.minnctapersm` will be ignored. + +In PTX ISA version 2.1 or higher, a warning is generated if `.minnctapersm` is specified without specifying either `.maxntid` or `.reqntid`. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0 as a replacement for `.maxnctapersm`. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo .maxntid 256 .minnctapersm 4 { ... } \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesnoreturn/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesnoreturn/DOC.md new file mode 100644 index 00000000..a5784047 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesnoreturn/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-performance-tuning-directivesnoreturn +description: Indicate that the function does not return to its caller function. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.6. Performance-Tuning Directives:.noreturn + +--- +title: "11.4.6. Performance-Tuning Directives:.noreturn" +section: 11.4.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.6. Performance-Tuning Directives:.noreturn + + +`.noreturn` + +Indicate that the function does not return to its caller function. + +Syntax + +.noreturn + +Description + +Indicate that the function does not return to its caller function. + +Semantics + +An optional `.noreturn` directive indicates that the function does not return to caller function. `.noreturn` directive can only be specified on device functions and must appear between a `.func` directive and its body. + +The directive cannot be specified on functions which have return parameters. + +If a function with `.noreturn` directive returns to the caller function at runtime, then the behavior is undefined. + +PTX ISA Notes + +Introduced in PTX ISA version 6.4. + +Target ISA Notes + +Requires `sm_30` or higher. + +Examples + +.func foo .noreturn { ... } \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivespragma/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivespragma/DOC.md new file mode 100644 index 00000000..a210e656 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivespragma/DOC.md @@ -0,0 +1,55 @@ +--- +name: ptx-performance-tuning-directivespragma +description: Pass directives to PTX backend compiler. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.7. Performance-Tuning Directives:.pragma + +--- +title: "11.4.7. Performance-Tuning Directives:.pragma" +section: 11.4.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.7. Performance-Tuning Directives:.pragma + + +`.pragma` + +Pass directives to PTX backend compiler. + +Syntax + +.pragma list-of-strings ; + +Description + +Pass module-scoped, entry-scoped, or statement-level directives to the PTX backend compiler. + +The `.pragma` directive may occur at module-scope, at entry-scope, or at statement-level. + +Semantics + +The interpretation of `.pragma` directive strings is implementation-specific and has no impact on PTX semantics. See [Descriptions of .pragma Strings](<#descriptions-pragma-strings>) for descriptions of the pragma strings defined in `ptxas`. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.pragma "nounroll"; // disable unrolling in backend + + // disable unrolling for current kernel + .entry foo .pragma "nounroll"; { ... } \ No newline at end of file diff --git a/content/cuda/docs/ptx-performance-tuning-directivesreqntid/DOC.md b/content/cuda/docs/ptx-performance-tuning-directivesreqntid/DOC.md new file mode 100644 index 00000000..9f413f83 --- /dev/null +++ b/content/cuda/docs/ptx-performance-tuning-directivesreqntid/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-performance-tuning-directivesreqntid +description: Number of threads in the thread block (CTA). +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.4.3. Performance-Tuning Directives:.reqntid + +--- +title: "11.4.3. Performance-Tuning Directives:.reqntid" +section: 11.4.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.4.3. Performance-Tuning Directives:.reqntid + + +`.reqntid` + +Number of threads in the thread block (CTA). + +Syntax + +.reqntid nx + .reqntid nx, ny + .reqntid nx, ny, nz + +Description + +Declare the number of threads in the thread block (CTA) by specifying the extent of each dimension of the 1D, 2D, or 3D CTA. The total number of threads is the product of the number of threads in each dimension. + +Semantics + +The size of each CTA dimension specified in any invocation of the kernel is required to be equal to that specified in this directive. Specifying a different CTA dimension at launch will result in a runtime error or kernel launch failure. + +Notes + +The `.reqntid` directive cannot be used in conjunction with the `.maxntid` directive. + +PTX ISA Notes + +Introduced in PTX ISA version 2.1. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo .reqntid 256 { ... } // num threads = 256 + .entry bar .reqntid 16,16,4 { ... } // num threads = 1024 \ No newline at end of file diff --git a/content/cuda/docs/ptx-pmevent/DOC.md b/content/cuda/docs/ptx-pmevent/DOC.md new file mode 100644 index 00000000..77cd89e1 --- /dev/null +++ b/content/cuda/docs/ptx-pmevent/DOC.md @@ -0,0 +1,63 @@ +--- +name: ptx-pmevent +description: Trigger one or more Performance Monitor events. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.19.3. Miscellaneous Instructions:pmevent + +--- +title: "9.7.19.3. Miscellaneous Instructions:pmevent" +section: 9.7.19.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.19.3. Miscellaneous Instructions:pmevent + + +`pmevent` + +Trigger one or more Performance Monitor events. + +Syntax + +pmevent a; // trigger a single performance monitor event + pmevent.mask a; // trigger one or more performance monitor events + +Description + +Triggers one or more of a fixed number of performance monitor events, with event index or mask specified by immediate operand `a`. + +`pmevent` (without modifier `.mask`) triggers a single performance monitor event indexed by immediate operand `a`, in the range `0..15`. + +`pmevent.mask` triggers one or more of the performance monitor events. Each bit in the 16-bit immediate operand `a` controls an event. + +Programmatic performance moniter events may be combined with other hardware events using Boolean functions to increment one of the four performance counters. The relationship between events and counters is programmed via API calls from the host. + +Notes + +Currently, there are sixteen performance monitor events, numbered 0 through 15. + +PTX ISA Notes + +`pmevent` introduced in PTX ISA version 1.4. + +`pmevent.mask` introduced in PTX ISA version 3.0. + +Target ISA Notes + +pmevent supported on all target architectures. + +`pmevent.mask` requires `sm_20` or higher. + +Examples + +pmevent 1; + @p pmevent 7; + @q pmevent.mask 0xff; \ No newline at end of file diff --git a/content/cuda/docs/ptx-popc/DOC.md b/content/cuda/docs/ptx-popc/DOC.md new file mode 100644 index 00000000..4b99c0eb --- /dev/null +++ b/content/cuda/docs/ptx-popc/DOC.md @@ -0,0 +1,57 @@ +--- +name: ptx-popc +description: Population count. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.14. Integer Arithmetic Instructions:popc + +--- +title: "9.7.1.14. Integer Arithmetic Instructions:popc" +section: 9.7.1.14 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.14. Integer Arithmetic Instructions:popc + + +`popc` + +Population count. + +Syntax + +popc.type d, a; + + .type = { .b32, .b64 }; + +Description + +Count the number of one bits in `a` and place the resulting _population count_ in 32-bit destination register `d`. Operand `a` has the instruction type and destination `d` has type `.u32`. + +Semantics + +.u32 d = 0; + while (a != 0) { + if (a & 0x1) d++; + a = a >> 1; + } + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +`popc` requires `sm_20` or higher. + +Examples + +popc.b32 d, a; + popc.b64 cnt, X; // cnt is .u32 \ No newline at end of file diff --git a/content/cuda/docs/ptx-pragma-stringsenable-smem-spilling/DOC.md b/content/cuda/docs/ptx-pragma-stringsenable-smem-spilling/DOC.md new file mode 100644 index 00000000..13e1dbaa --- /dev/null +++ b/content/cuda/docs/ptx-pragma-stringsenable-smem-spilling/DOC.md @@ -0,0 +1,65 @@ +--- +name: ptx-pragma-stringsenable-smem-spilling +description: '`"enable_smem_spilling"`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 12.3. Pragma Strings: + +--- +title: "12.3. Pragma Strings:"enable_smem_spilling"" +section: 12.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 12.3. Pragma Strings:"enable_smem_spilling" + + +`"enable_smem_spilling"` + +Enable shared memory spilling for CUDA kernels. + +Syntax + +.pragma "enable_smem_spilling"; + +Description + +The `"enable_smem_spilling" pragma` is a directive that enables register spilling into shared memory. During the spilling process, registers are first spilled into shared memory, and once the allocated shared memory is full, any additional spills are redirected to local memory. This can enhance performance by reducing memory access latency since shared memory accesses are faster than local memory. + +The `"enable_smem_spilling" pragma` is only allowed within the function scope. When applied, it enables shared memory spilling for the specified function. + +The usage of pragma is valid only in certain scenarios and specific compilation modes. The usage of pragma is disallowed under following cases and may result in an error: + +* Per-function compilation mode: e.g., Separate Compilation, Device-debug, Whole program with recursive function calls, Extensible-whole-program + + * Kernels utilizing dynamically allocated shared memory + + * Kernels using `setmaxnreg` instruction + +Note + +If launch bounds are not explicitly specified, the compiler assumes the maximum possible number of threads per CTA to estimate shared memory allocated per CTA and corresponding spill size. However, if the kernel is launched with fewer threads per CTA than estimated, the shared memory allocated per CTA may exceed the compiler estimated size, thereby potentially limiting the number of CTAs that can be launched on an SM. Due to this, using the pragma without launch bounds may lead to performance regressions. Hence it is recommended to use this pragma only when launch bounds are explicitly specified. + +PTX ISA Notes + +Introduced in PTX ISA version 9.0. + +Target ISA Notes + +Requires `sm_75` or higher. + +Examples + +.entry foo (...) + { + ... + .pragma "enable_smem_spilling"; // Enable shared memory spilling for this function + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-pragma-stringsfrequency/DOC.md b/content/cuda/docs/ptx-pragma-stringsfrequency/DOC.md new file mode 100644 index 00000000..9c67d4ea --- /dev/null +++ b/content/cuda/docs/ptx-pragma-stringsfrequency/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-pragma-stringsfrequency +description: Specify frequency for basic block execution. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 12.4. Pragma Strings: + +--- +title: "12.4. Pragma Strings:"frequency"" +section: 12.4 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 12.4. Pragma Strings:"frequency" + + +`"frequency"` + +Specify frequency for basic block execution. + +Syntax + +.pragma "frequency n"; + +Description + +The `"frequency" pragma` is a directive that specifies the number of times a basic block is executed by an executing thread. The optimizing compiler backend treats this pragma as a hint which will be used for optimizations. + +Operand `n` is a 64-bit non-negative integer constant that specifies the execution frequency. + +Note that in order to have the desired effect of this pragma, it should be specified at the start of the basic block. Basic block is defined as a straight-line sequence of instructions with only one entry point and one exit point. + +PTX ISA Notes + +Introduced in PTX ISA version 9.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.entry foo (...) + { + .pragma "frequency 32"; + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-pragma-stringsnounroll/DOC.md b/content/cuda/docs/ptx-pragma-stringsnounroll/DOC.md new file mode 100644 index 00000000..90f28d10 --- /dev/null +++ b/content/cuda/docs/ptx-pragma-stringsnounroll/DOC.md @@ -0,0 +1,84 @@ +--- +name: ptx-pragma-stringsnounroll +description: Disable loop unrolling in optimizing the backend compiler. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 12.1. Pragma Strings: + +--- +title: "12.1. Pragma Strings:"nounroll"" +section: 12.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 12.1. Pragma Strings:"nounroll" + + +`"nounroll"` + +Disable loop unrolling in optimizing the backend compiler. + +Syntax + +.pragma "nounroll"; + +Description + +The `"nounroll" pragma` is a directive to disable loop unrolling in the optimizing backend compiler. + +The `"nounroll" pragma` is allowed at module, entry-function, and statement levels, with the following meanings: + +module scope + + +disables unrolling for all loops in module, including loops preceding the `.pragma`. + +entry-function scope + + +disables unrolling for all loops in the entry function body. + +statement-level pragma + + +disables unrolling of the loop for which the current block is the loop header. + +Note that in order to have the desired effect at statement level, the `"nounroll"` directive must appear before any instruction statements in the loop header basic block for the desired loop. The loop header block is defined as the block that dominates all blocks in the loop body and is the target of the loop backedge. Statement-level `"nounroll"` directives appearing outside of loop header blocks are silently ignored. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +Requires `sm_20` or higher. Ignored for `sm_1x` targets. + +Examples + +.entry foo (...) + .pragma "nounroll"; // do not unroll any loop in this function + { + ... + } + + .func bar (...) + { + ... + L1_head: + .pragma "nounroll"; // do not unroll this loop + ... + @p bra L1_end; + L1_body: + ... + L1_continue: + bra L1_head; + L1_end: + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-pragma-stringsused-bytes-mask/DOC.md b/content/cuda/docs/ptx-pragma-stringsused-bytes-mask/DOC.md new file mode 100644 index 00000000..aba5c39c --- /dev/null +++ b/content/cuda/docs/ptx-pragma-stringsused-bytes-mask/DOC.md @@ -0,0 +1,66 @@ +--- +name: ptx-pragma-stringsused-bytes-mask +description: Mask for indicating used bytes in data of ld operation. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 12.2. Pragma Strings: + +--- +title: "12.2. Pragma Strings:"used_bytes_mask"" +section: 12.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 12.2. Pragma Strings:"used_bytes_mask" + + +`"used_bytes_mask"` + +Mask for indicating used bytes in data of ld operation. + +Syntax + +.pragma "used_bytes_mask mask"; + +Description + +The `"used_bytes_mask" pragma` is a directive that specifies used bytes in a load operation based on the mask provided. + +`"used_bytes_mask" pragma` needs to be specified prior to a load instruction for which information about bytes used from the load operation is needed. Pragma is ignored if instruction following it is not a load instruction. + +For a load instruction without this pragma, all bytes from the load operation are assumed to be used. + +Operand `mask` is a 32-bit integer with set bits indicating the used bytes in data of load operation. + +Semantics + +Each bit in mask operand corresponds to a byte data where each set bit represents the used byte. + Most-significant bit corresponds to most-significant byte of data. + + // For 4 bytes load with only lower 3 bytes used + .pragma "used_bytes_mask 0x7"; + ld.global.u32 %r0, [gbl]; // Higher 1 byte from %r0 is unused + + // For vector load of 16 bytes with lower 12 bytes used + .pragma "used_bytes_mask 0xfff"; + ld.global.v4.u32 {%r0, %r1, %r2, %r3}, [gbl]; // %r3 unused + +PTX ISA Notes + +Introduced in PTX ISA version 8.3. + +Target ISA Notes + +Requires `sm_50` or higher. + +Examples + +.pragma "used_bytes_mask 0xfff"; + ld.global.v4.u32 {%r0, %r1, %r2, %r3}, [gbl]; // Only lower 12 bytes used \ No newline at end of file diff --git a/content/cuda/docs/ptx-predicate-constants/DOC.md b/content/cuda/docs/ptx-predicate-constants/DOC.md new file mode 100644 index 00000000..28d62578 --- /dev/null +++ b/content/cuda/docs/ptx-predicate-constants/DOC.md @@ -0,0 +1,26 @@ +--- +name: ptx-predicate-constants +description: In PTX, integer constants may be used as predicates. For predicate-type + data initializers and instruction operands, integer constants are interpreted as + in C, i.e., zero values are `False` and non-zer... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 4.5.3. Predicate Constants + +--- +title: "4.5.3. Predicate Constants" +section: 4.5.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 4.5.3. Predicate Constants + + +In PTX, integer constants may be used as predicates. For predicate-type data initializers and instruction operands, integer constants are interpreted as in C, i.e., zero values are `False` and non-zero values are `True`. \ No newline at end of file diff --git a/content/cuda/docs/ptx-prefetchprefetchu/DOC.md b/content/cuda/docs/ptx-prefetchprefetchu/DOC.md new file mode 100644 index 00000000..43bbca34 --- /dev/null +++ b/content/cuda/docs/ptx-prefetchprefetchu/DOC.md @@ -0,0 +1,81 @@ +--- +name: ptx-prefetchprefetchu +description: '`prefetch`, `prefetchu`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.15. Data Movement and Conversion Instructions:prefetch,prefetchu + +--- +title: "9.7.9.15. Data Movement and Conversion Instructions:prefetch,prefetchu" +section: 9.7.9.15 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.15. Data Movement and Conversion Instructions:prefetch,prefetchu + + +`prefetch`, `prefetchu` + +Prefetch line containing a generic address at a specified level of memory hierarchy, in specified state space. + +Syntax + +prefetch{.space}.level [a]; // prefetch to data cache + prefetch.global.level::eviction_priority [a]; // prefetch to data cache + + prefetchu.L1 [a]; // prefetch to uniform cache + + prefetch{.tensormap_space}.tensormap [a]; // prefetch the tensormap + + .space = { .global, .local }; + .level = { .L1, .L2 }; + .level::eviction_priority = { .L2::evict_last, .L2::evict_normal }; + .tensormap_space = { .const, .param }; + +Description + +The `prefetch` instruction brings the cache line containing the specified address in global or local memory state space into the specified cache level. + +If the `.tensormap` qualifier is specified then the `prefetch` instruction brings the cache line containing the specified address in the `.const` or `.param` memory state space for subsequent use by the `cp.async.bulk.tensor` instruction. + +If no state space is given, the `prefetch` uses [Generic Addressing](<#generic-addressing>). + +Optionally, the eviction priority to be applied on the prefetched cache line can be specified by the modifier `.level::eviction_priority`. + +Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>) + +The `prefetchu` instruction brings the cache line containing the specified generic address into the specified uniform cache level. + +A `prefetch` to a shared memory location performs no operation. + +A `prefetch` into the uniform cache requires a generic address, and no operation occurs if the address maps to a `const`, `local`, or `shared` memory location. + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Support for `.level::eviction_priority` qualifier introduced in PTX ISA version 7.4. + +Support for the `.tensormap` qualifier is introduced in PTX ISA version 8.0. + +Target ISA Notes + +`prefetch` and `prefetchu` require `sm_20` or higher. + +Support for `.level::eviction_priority` qualifier requires `sm_80` or higher. + +Support for the `.tensormap` qualifier requires `sm_90` or higher. + +Examples + +prefetch.global.L1 [ptr]; + prefetch.global.L2::evict_last [ptr]; + prefetchu.L1 [addr]; + prefetch.const.tensormap [ptr]; \ No newline at end of file diff --git a/content/cuda/docs/ptx-prmt/DOC.md b/content/cuda/docs/ptx-prmt/DOC.md new file mode 100644 index 00000000..50bba42f --- /dev/null +++ b/content/cuda/docs/ptx-prmt/DOC.md @@ -0,0 +1,106 @@ +--- +name: ptx-prmt +description: Permute bytes from register pair. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.9.7. Data Movement and Conversion Instructions:prmt + +--- +title: "9.7.9.7. Data Movement and Conversion Instructions:prmt" +section: 9.7.9.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.9.7. Data Movement and Conversion Instructions:prmt + + +`prmt` + +Permute bytes from register pair. + +Syntax + +prmt.b32{.mode} d, a, b, c; + + .mode = { .f4e, .b4e, .rc8, .ecl, .ecr, .rc16 }; + +Description + +Pick four arbitrary bytes from two 32-bit registers, and reassemble them into a 32-bit destination register. + +In the generic form (no mode specified), the permute control consists of four 4-bit selection values. The bytes in the two source registers are numbered from 0 to 7: `{b, a} = {{b7, b6, b5, b4}, {b3, b2, b1, b0}}`. For each byte in the target register, a 4-bit selection value is defined. + +The 3 lsbs of the selection value specify which of the 8 source bytes should be moved into the target position. The msb defines if the byte value should be copied, or if the sign (msb of the byte) should be replicated over all 8 bits of the target position (sign extend of the byte value); `msb=0` means copy the literal value; `msb=1` means replicate the sign. Note that the sign extension is only performed as part of generic form. + +Thus, the four 4-bit values fully specify an arbitrary byte permute, as a `16b` permute code. + +default mode | `d.b3` source select | `d.b2` source select | `d.b1` source select | `d.b0` source select +---|---|---|---|--- +index | `c[15:12]` | `c[11:8]` | `c[7:4]` | `c[3:0]` + +The more specialized form of the permute control uses the two lsb’s of operand `c` (which is typically an address pointer) to control the byte extraction. + +mode | selector `c[1:0]` | `d.b3` source | `d.b2` source | `d.b1` source | `d.b0` source +---|---|---|---|---|--- +`f4e` (forward 4 extract) | 0 | 3 | 2 | 1 | 0 +| 1 | 4 | 3 | 2 | 1 +| 2 | 5 | 4 | 3 | 2 +| 3 | 6 | 5 | 4 | 3 +`b4e` (backward 4 extract) | 0 | 5 | 6 | 7 | 0 +| 1 | 6 | 7 | 0 | 1 +| 2 | 7 | 0 | 1 | 2 +| 3 | 0 | 1 | 2 | 3 +`rc8` (replicate 8) | 0 | 0 | 0 | 0 | 0 +| 1 | 1 | 1 | 1 | 1 +| 2 | 2 | 2 | 2 | 2 +| 3 | 3 | 3 | 3 | 3 +`ecl` (edge clamp left) | 0 | 3 | 2 | 1 | 0 +| 1 | 3 | 2 | 1 | 1 +| 2 | 3 | 2 | 2 | 2 +| 3 | 3 | 3 | 3 | 3 +`ecr` (edge clamp right) | 0 | 0 | 0 | 0 | 0 +| 1 | 1 | 1 | 1 | 0 +| 2 | 2 | 2 | 1 | 0 +| 3 | 3 | 2 | 1 | 0 +`rc16` (replicate 16) | 0 | 1 | 0 | 1 | 0 +| 1 | 3 | 2 | 3 | 2 +| 2 | 1 | 0 | 1 | 0 +| 3 | 3 | 2 | 3 | 2 + +Semantics + +tmp64 = (b<<32) | a; // create 8 byte source + + if ( ! mode ) { + ctl[0] = (c >> 0) & 0xf; + ctl[1] = (c >> 4) & 0xf; + ctl[2] = (c >> 8) & 0xf; + ctl[3] = (c >> 12) & 0xf; + } else { + ctl[0] = ctl[1] = ctl[2] = ctl[3] = (c >> 0) & 0x3; + } + + tmp[07:00] = ReadByte( mode, ctl[0], tmp64 ); + tmp[15:08] = ReadByte( mode, ctl[1], tmp64 ); + tmp[23:16] = ReadByte( mode, ctl[2], tmp64 ); + tmp[31:24] = ReadByte( mode, ctl[3], tmp64 ); + +PTX ISA Notes + +Introduced in PTX ISA version 2.0. + +Target ISA Notes + +`prmt` requires `sm_20` or higher. + +Examples + +prmt.b32 r1, r2, r3, r4; + prmt.b32.f4e r1, r2, r3, r4; \ No newline at end of file diff --git a/content/cuda/docs/ptx-proxies/DOC.md b/content/cuda/docs/ptx-proxies/DOC.md new file mode 100644 index 00000000..35040d18 --- /dev/null +++ b/content/cuda/docs/ptx-proxies/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-proxies +description: A _memory proxy_ , or a _proxy_ is an abstract label applied to a method + of memory access. When two memory operations use distinct methods of memory access, + they are said to be different _proxies_. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.6. Proxies + +--- +title: "8.6. Proxies" +section: 8.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 8.6. Proxies + + +A _memory proxy_ , or a _proxy_ is an abstract label applied to a method of memory access. When two memory operations use distinct methods of memory access, they are said to be different _proxies_. + +Memory operations as defined in [Operation types](<#operation-types>) use _generic_ method of memory access, i.e. a _generic proxy_. Other operations such as textures and surfaces all use distinct methods of memory access, also distinct from the _generic_ method. + +A _proxy fence_ is required to synchronize memory operations across different _proxies_. Although virtual aliases use the _generic_ method of memory access, since using distinct virtual addresses behaves as if using different _proxies_ , they require a _proxy fence_ to establish memory ordering. \ No newline at end of file diff --git a/content/cuda/docs/ptx-ptx-isa-version-91/DOC.md b/content/cuda/docs/ptx-ptx-isa-version-91/DOC.md new file mode 100644 index 00000000..fb469ee9 --- /dev/null +++ b/content/cuda/docs/ptx-ptx-isa-version-91/DOC.md @@ -0,0 +1,34 @@ +--- +name: ptx-ptx-isa-version-91 +description: 'PTX ISA version 9.1 introduces the following new features:' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 1.3. PTX ISA Version 9.1 + +--- +title: "1.3. PTX ISA Version 9.1" +section: 1.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 1.3. PTX ISA Version 9.1 + + +PTX ISA version 9.1 introduces the following new features: + +* Adds support for `.volatile` qualifier with `.local` state space for `ld` and `st` instructions. + + * Adds support for `.f16x2` and `.bf16x2` source types for `cvt` instruction with destination types `.e2m1x2`, `.e2m3x2`, `.e3m2x2`, `.e4m3x2`, `.e5m2x2`. + + * Adds support for `.scale_vec::4X` with `.ue8m0` as `.stype` with `.kind::mxf4nvf4` for `mma`/`mma.sp` instructions. + + * Adds support for `.s2f6x2` instruction type for `cvt` instruction. + + * Adds support for `multimem.cp.async.bulk` and `multimem.cp.reduce.async.bulk` instructions. \ No newline at end of file diff --git a/content/cuda/docs/ptx-ptx-module-directivesaddress-size/DOC.md b/content/cuda/docs/ptx-ptx-module-directivesaddress-size/DOC.md new file mode 100644 index 00000000..d08a2631 --- /dev/null +++ b/content/cuda/docs/ptx-ptx-module-directivesaddress-size/DOC.md @@ -0,0 +1,66 @@ +--- +name: ptx-ptx-module-directivesaddress-size +description: Address size used throughout PTX module. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.1.3. PTX Module Directives:.address_size + +--- +title: "11.1.3. PTX Module Directives:.address_size" +section: 11.1.3 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.1.3. PTX Module Directives:.address_size + + +`.address_size` + +Address size used throughout PTX module. + +Syntax + +.address_size address-size + address-size = { 32, 64 }; + +Description + +Specifies the address size assumed throughout the module by the PTX code and the binary DWARF information in PTX. + +Redefinition of this directive within a module is not allowed. In the presence of separate compilation all modules must specify (or default to) the same address size. + +The `.address_size` directive is optional, but it must immediately follow the `.target`directive if present within a module. + +Semantics + +If the `.address_size` directive is omitted, the address size defaults to 32. + +PTX ISA Notes + +Introduced in PTX ISA version 2.3. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +// example directives + .address_size 32 // addresses are 32 bit + .address_size 64 // addresses are 64 bit + + // example of directive placement within a module + .version 2.3 + .target sm_20 + .address_size 64 + ... + .entry foo () { + ... + } \ No newline at end of file diff --git a/content/cuda/docs/ptx-ptx-module-directivestarget/DOC.md b/content/cuda/docs/ptx-ptx-module-directivestarget/DOC.md new file mode 100644 index 00000000..6e66d4fb --- /dev/null +++ b/content/cuda/docs/ptx-ptx-module-directivestarget/DOC.md @@ -0,0 +1,252 @@ +--- +name: ptx-ptx-module-directivestarget +description: Architecture and Platform target. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.1.2. PTX Module Directives:.target + +--- +title: "11.1.2. PTX Module Directives:.target" +section: 11.1.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.1.2. PTX Module Directives:.target + + +`.target` + +Architecture and Platform target. + +Syntax + +.target stringlist // comma separated list of target specifiers + string = { sm_120a, sm_120f, sm_120, // sm_12x target architectures + sm_121a, sm_121f, sm_121, // sm_12x target architectures + sm_110a, sm_110f, sm_110, // sm_11x target architectures + sm_100a, sm_100f, sm_100, // sm_10x target architectures + sm_101a, sm_101f, sm_101, // sm_10x target architectures + sm_103a, sm_103f, sm_103 // sm_10x target architectures + sm_90a, sm_90, // sm_9x target architectures + sm_80, sm_86, sm_87, sm_88, sm_89, // sm_8x target architectures + sm_70, sm_72, sm_75, // sm_7x target architectures + sm_60, sm_61, sm_62, // sm_6x target architectures + sm_50, sm_52, sm_53, // sm_5x target architectures + sm_30, sm_32, sm_35, sm_37, // sm_3x target architectures + sm_20, // sm_2x target architectures + sm_10, sm_11, sm_12, sm_13, // sm_1x target architectures + texmode_unified, texmode_independent, // texturing mode + debug, // platform option + map_f64_to_f32 }; // platform option + +Description + +Specifies the set of features in the target architecture for which the current PTX code was generated. In general, generations of SM architectures follow an _onion layer_ model, where each generation adds new features and retains all features of previous generations. The onion layer model allows the PTX code generated for a given target to be run on later generation devices. + +Target architectures with suffix “`a`”, such as `sm_90a`, include architecture-specific features that are supported on the specified architecture only, hence such targets do not follow the onion layer model. Therefore, PTX code generated for such targets cannot be run on later generation devices. Architecture-specific features can only be used with targets that support these features. + +Target architectures with suffix “`f`”, such as `sm_100f`, include family-specific features that are supported only within the same architecture family. Therefore, PTX code generated for such targets can run only on later generation devices in the same family. Family-specific features can be used with f-targets as well as a-targets of later generation devices in the same family. + +[Table 58](<#architecture-family-definition>) defines the architecture families. + +Table 58 Architecture Families Family | Target SM architectures included +---|--- +sm_10x family | sm_100f, sm_103f, future targets in sm_10x family +sm_11x family | sm_110f, sm_101f, future targets in sm_11x family +sm_12x family | sm_120f, sm_121f, future targets in sm_12x family + +Semantics + +Each PTX module must begin with a `.version` directive, immediately followed by a `.target` directive containing a target architecture and optional platform options. A `.target` directive specifies a single target architecture, but subsequent `.target` directives can be used to change the set of target features allowed during parsing. A program with multiple `.target` directives will compile and run only on devices that support all features of the highest-numbered architecture listed in the program. + +PTX features are checked against the specified target architecture, and an error is generated if an unsupported feature is used. The following table summarizes the features in PTX that vary according to target architecture. + +Target | Description +---|--- +`sm_120` | Baseline feature set for `sm_120` architecture. +`sm_120f` | Adds support for `sm_120f` family specific features. +`sm_120a` | Adds support for `sm_120a` architecture-specific features. +`sm_121` | Baseline feature set for `sm_121` architecture. +`sm_121f` | Adds support for `sm_121f` family specific features. +`sm_121a` | Adds support for `sm_121a` architecture-specific features. + +Target | Description +---|--- +`sm_110` | Baseline feature set for `sm_110` architecture. +`sm_110f` | Adds support for `sm_110f` family specific features. +`sm_110a` | Adds support for `sm_110a` architecture-specific features. + +Target | Description +---|--- +`sm_100` | Baseline feature set for `sm_100` architecture. +`sm_100f` | Adds support for `sm_100f` family specific features. +`sm_100a` | Adds support for `sm_100a` architecture-specific features. +`sm_101` | Baseline feature set for `sm_101` architecture. (Renamed to `sm_110`) +`sm_101f` | Adds support for `sm_101f` family specific features. (Renamed to `sm_110f`) +`sm_101a` | Adds support for `sm_101a` architecture-specific features. (Renamed to `sm_110a`) +`sm_103` | Baseline feature set for `sm_103` architecture. +`sm_103f` | Adds support for `sm_103f` family specific features. +`sm_103a` | Adds support for `sm_103a` architecture-specific features. + +Target | Description +---|--- +`sm_90` | Baseline feature set for `sm_90` architecture. +`sm_90a` | Adds support for `sm_90a` architecture-specific features. + +Target | Description +---|--- +`sm_80` | Baseline feature set for `sm_80` architecture. +`sm_86` | Adds support for `.xorsign` modifier on `min` and `max` instructions. +`sm_87` | Baseline feature set for `sm_87` architecture. +`sm_88` | Baseline feature set for `sm_88` architecture. +`sm_89` | Baseline feature set for `sm_89` architecture. + +Target | Description +---|--- +`sm_70` | Baseline feature set for `sm_70` architecture. +`sm_72` | Adds support for integer multiplicand and accumulator matrices in `wmma` instructions. Adds support for `cvt.pack` instruction. +`sm_75` | Adds support for sub-byte integer and single-bit multiplicant matrices in `wmma` instructions. Adds support for `ldmatrix` instruction. Adds support for `movmatrix` instruction. Adds support for `tanh` instruction. + +Target | Description +---|--- +`sm_60` | Baseline feature set for `sm_60` architecture. +`sm_61` | Adds support for `dp2a` and `dp4a` instructions. +`sm_62` | Baseline feature set for `sm_61` architecture. + +Target | Description +---|--- +`sm_50` | Baseline feature set for `sm_50` architecture. +`sm_52` | Baseline feature set for `sm_50` architecture. +`sm_53` | Adds support for arithmetic, comparsion and texture instructions for `.f16` and `.f16x2` types. + +Target | Description +---|--- +`sm_30` | Baseline feature set for `sm_30` architecture. +`sm_32` | Adds 64-bit `{atom,red}.{and,or,xor,min,max}` instructions. Adds `shf` instruction. Adds `ld.global.nc` instruction. +`sm_35` | Adds support for CUDA Dynamic Parallelism. +`sm_37` | Baseline feature set for `sm_35` architecture. + +Target | Description +---|--- +`sm_20` | Baseline feature set for `sm_20` architecture. + +Target | Description +---|--- +`sm_10` | Baseline feature set for `sm_10` architecture. Requires `map_f64_to_f32` if any `.f64` instructions used. +`sm_11` | Adds 64-bit `{atom,red}.{and,or,xor,min,max}` instructions. Requires `map_f64_to_f32` if any `.f64` instructions used. +`sm_12` | Adds `{atom,red}.shared`, 64-bit `{atom,red}.global`, `vote` instructions. Requires `map_f64_to_f32` if any `.f64` instructions used. +`sm_13` | Adds double-precision support, including expanded rounding modifiers. Disallows use of `map_f64_to_f32`. + +The texturing mode is specified for an entire module and cannot be changed within the module. + +The `.target` debug option declares that the PTX file contains DWARF debug information, and subsequent compilation of PTX will retain information needed for source-level debugging. If the debug option is declared, an error message is generated if no DWARF information is found in the file. The debug option requires PTX ISA version 3.0 or later. + +`map_f64_to_f32` indicates that all double-precision instructions map to single-precision regardless of the target architecture. This enables high-level language compilers to compile programs containing type double to target device that do not support double-precision operations. Note that `.f64` storage remains as 64-bits, with only half being used by instructions converted from `.f64` to `.f32`. + +Notes + +Targets of the form `compute_xx` are also accepted as synonyms for `sm_xx` targets. + +Targets `sm_{101,101f,101a}` are renamed to targets `sm_{110,110f,110a}` from PTX ISA version 9.0. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target strings `sm_10` and `sm_11` introduced in PTX ISA version 1.0. + +Target strings `sm_12` and `sm_13` introduced in PTX ISA version 1.2. + +Texturing mode introduced in PTX ISA version 1.5. + +Target string `sm_20` introduced in PTX ISA version 2.0. + +Target string `sm_30` introduced in PTX ISA version 3.0. + +Platform option `debug` introduced in PTX ISA version 3.0. + +Target string `sm_35` introduced in PTX ISA version 3.1. + +Target strings `sm_32` and `sm_50` introduced in PTX ISA version 4.0. + +Target strings `sm_37` and `sm_52` introduced in PTX ISA version 4.1. + +Target string `sm_53` introduced in PTX ISA version 4.2. + +Target string `sm_60`, `sm_61`, `sm_62` introduced in PTX ISA version 5.0. + +Target string `sm_70` introduced in PTX ISA version 6.0. + +Target string `sm_72` introduced in PTX ISA version 6.1. + +Target string `sm_75` introduced in PTX ISA version 6.3. + +Target string `sm_80` introduced in PTX ISA version 7.0. + +Target string `sm_86` introduced in PTX ISA version 7.1. + +Target string `sm_87` introduced in PTX ISA version 7.4. + +Target string `sm_88` introduced in PTX ISA version 9.0. + +Target string `sm_89` introduced in PTX ISA version 7.8. + +Target string `sm_90` introduced in PTX ISA version 7.8. + +Target string `sm_90a` introduced in PTX ISA version 8.0. + +Target string `sm_100` introduced in PTX ISA version 8.6. + +Target string `sm_100f` introduced in PTX ISA version 8.8. + +Target string `sm_100a` introduced in PTX ISA version 8.6. + +Target string `sm_101` introduced in PTX ISA version 8.6. (Renamed to `sm_110`) + +Target string `sm_101f` introduced in PTX ISA version 8.8. (Renamed to `sm_110f`) + +Target string `sm_101a` introduced in PTX ISA version 8.6. (Renamed to `sm_110a`) + +Target string `sm_103` introduced in PTX ISA version 8.8. + +Target string `sm_103f` introduced in PTX ISA version 8.8. + +Target string `sm_103a` introduced in PTX ISA version 8.8. + +Target string `sm_110` introduced in PTX ISA version 9.0. + +Target string `sm_110f` introduced in PTX ISA version 9.0. + +Target string `sm_110a` introduced in PTX ISA version 9.0. + +Target string `sm_120` introduced in PTX ISA version 8.7. + +Target string `sm_120f` introduced in PTX ISA version 8.8. + +Target string `sm_120a` introduced in PTX ISA version 8.7. + +Target string `sm_121` introduced in PTX ISA version 8.8. + +Target string `sm_121f` introduced in PTX ISA version 8.8. + +Target string `sm_121a` introduced in PTX ISA version 8.8. + +Target ISA Notes + +The `.target` directive is supported on all target architectures. + +Examples + +.target sm_10 // baseline target architecture + .target sm_13 // supports double-precision + .target sm_20, texmode_independent + .target sm_90 // baseline target architecture + .target sm_90a // PTX using architecture-specific features + .target sm_100f // PTX using family-specific features \ No newline at end of file diff --git a/content/cuda/docs/ptx-ptx-module-directivesversion/DOC.md b/content/cuda/docs/ptx-ptx-module-directivesversion/DOC.md new file mode 100644 index 00000000..4a280e69 --- /dev/null +++ b/content/cuda/docs/ptx-ptx-module-directivesversion/DOC.md @@ -0,0 +1,58 @@ +--- +name: ptx-ptx-module-directivesversion +description: PTX ISA version number. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 11.1.1. PTX Module Directives:.version + +--- +title: "11.1.1. PTX Module Directives:.version" +section: 11.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 11.1.1. PTX Module Directives:.version + + +`.version` + +PTX ISA version number. + +Syntax + +.version major.minor // major, minor are integers + +Description + +Specifies the PTX language version number. + +The _major_ number is incremented when there are incompatible changes to the PTX language, such as changes to the syntax or semantics. The version major number is used by the PTX compiler to ensure correct execution of legacy PTX code. + +The _minor_ number is incremented when new features are added to PTX. + +Semantics + +Indicates that this module must be compiled with tools that support an equal or greater version number. + +Each PTX module must begin with a `.version` directive, and no other `.version` directive is allowed anywhere else within the module. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +.version 3.1 + .version 3.0 + .version 2.3 \ No newline at end of file diff --git a/content/cuda/docs/ptx-rcp/DOC.md b/content/cuda/docs/ptx-rcp/DOC.md new file mode 100644 index 00000000..eb418707 --- /dev/null +++ b/content/cuda/docs/ptx-rcp/DOC.md @@ -0,0 +1,120 @@ +--- +name: ptx-rcp +description: Take the reciprocal of a value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.13. Floating Point Instructions:rcp + +--- +title: "9.7.3.13. Floating Point Instructions:rcp" +section: 9.7.3.13 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.13. Floating Point Instructions:rcp + + +`rcp` + +Take the reciprocal of a value. + +Syntax + +rcp.approx{.ftz}.f32 d, a; // fast, approximate reciprocal + rcp.rnd{.ftz}.f32 d, a; // IEEE 754 compliant rounding + rcp.rnd.f64 d, a; // IEEE 754 compliant rounding + + .rnd = { .rn, .rz, .rm, .rp }; + +Description + +Compute `1/a`, store result in `d`. + +Semantics + +d = 1 / a; + +Notes + +Fast, approximate single-precision reciprocal: + +`rcp.approx.f32` implements a fast approximation to reciprocal. The maximum ulp error is 1 across the full range of inputs. + +Input | Result +---|--- +-Inf | -0.0 +-0.0 | -Inf ++0.0 | +Inf ++Inf | +0.0 +NaN | NaN + +Reciprocal with IEEE 754 compliant rounding: + +Rounding modifiers (no default): + +`.rn` + + +mantissa LSB rounds to nearest even + +`.rz` + + +mantissa LSB rounds towards zero + +`.rm` + + +mantissa LSB rounds towards negative infinity + +`.rp` + + +mantissa LSB rounds towards positive infinity + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`rcp.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`rcp.f64` supports subnormal numbers. + +`rcp.f32` flushes subnormal inputs and results to sign-preserving zero. + +PTX ISA Notes + +`rcp.f32` and `rcp.f64` introduced in PTX ISA version 1.0. `rcp.rn.f64` and explicit modifiers `.approx` and `.ftz` were introduced in PTX ISA version 1.4. General rounding modifiers were added in PTX ISA version 2.0. + +For PTX ISA version 1.4 and later, one of `.approx` or `.rnd` is required. + +For PTX ISA versions 1.0 through 1.3, `rcp.f32` defaults to `rcp.approx.ftz.f32`, and `rcp.f64` defaults to `rcp.rn.f64`. + +Target ISA Notes + +`rcp.approx.f32` supported on all target architectures. + +`rcp.rnd.f32` requires `sm_20` or higher. + +`rcp.rn.f64` requires `sm_13` or higher, or `.target map_f64_to_f32.` + +`rcp.{rz,rm,rp}.f64` requires `sm_20` or higher. + +Examples + +rcp.approx.ftz.f32 ri,r; + rcp.rn.ftz.f32 xi,x; + rcp.rn.f64 xi,x; \ No newline at end of file diff --git a/content/cuda/docs/ptx-rcpapproxftzf64/DOC.md b/content/cuda/docs/ptx-rcpapproxftzf64/DOC.md new file mode 100644 index 00000000..54617ba0 --- /dev/null +++ b/content/cuda/docs/ptx-rcpapproxftzf64/DOC.md @@ -0,0 +1,78 @@ +--- +name: ptx-rcpapproxftzf64 +description: '`rcp.approx.ftz.f64`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.14. Floating Point Instructions:rcp.approx.ftz.f64 + +--- +title: "9.7.3.14. Floating Point Instructions:rcp.approx.ftz.f64" +section: 9.7.3.14 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.14. Floating Point Instructions:rcp.approx.ftz.f64 + + +`rcp.approx.ftz.f64` + +Compute a fast, gross approximation to the reciprocal of a value. + +Syntax + +rcp.approx.ftz.f64 d, a; + +Description + +Compute a fast, gross approximation to the reciprocal as follows: + +1. extract the most-significant 32 bits of `.f64` operand `a` in 1.11.20 IEEE floating-point format (i.e., ignore the least-significant 32 bits of `a`), + + 2. compute an approximate `.f64` reciprocal of this value using the most-significant 20 bits of the mantissa of operand `a`, + + 3. place the resulting 32-bits in 1.11.20 IEEE floating-point format in the most-significant 32-bits of destination `d`,and + + 4. zero the least significant 32 mantissa bits of `.f64` destination `d`. + +Semantics + +tmp = a[63:32]; // upper word of a, 1.11.20 format + d[63:32] = 1.0 / tmp; + d[31:0] = 0x00000000; + +Notes + +`rcp.approx.ftz.f64` implements a fast, gross approximation to reciprocal. + +Input a[63:32] | Result d[63:32] +---|--- +-Inf | -0.0 +-subnormal | -Inf +-0.0 | -Inf ++0.0 | +Inf ++subnormal | +Inf ++Inf | +0.0 +NaN | NaN + +Input `NaN`s map to a canonical `NaN` with encoding `0x7fffffff00000000`. + +Subnormal inputs and results are flushed to sign-preserving zero. + +PTX ISA Notes + +`rcp.approx.ftz.f64` introduced in PTX ISA version 2.1. + +Target ISA Notes + +`rcp.approx.ftz.f64` requires `sm_20` or higher. + +Examples + +rcp.approx.ftz.f64 xi,x; \ No newline at end of file diff --git a/content/cuda/docs/ptx-red/DOC.md b/content/cuda/docs/ptx-red/DOC.md new file mode 100644 index 00000000..37d83506 --- /dev/null +++ b/content/cuda/docs/ptx-red/DOC.md @@ -0,0 +1,212 @@ +--- +name: ptx-red +description: Reduction operations on global and shared memory. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.6. Parallel Synchronization and Communication Instructions:red + +--- +title: "9.7.13.6. Parallel Synchronization and Communication Instructions:red" +section: 9.7.13.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.6. Parallel Synchronization and Communication Instructions:red + + +`red` + +Reduction operations on global and shared memory. + +Syntax + +Reduction operation with scalar type: + +red{.sem}{.scope}{.space}.op{.level::cache_hint}.type [a], b{, cache-policy}; + + red{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.f16 [a], b{, cache-policy}; + + red{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.f16x2 [a], b{, cache-policy}; + + red{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.bf16 + [a], b {, cache-policy}; + + red{.sem}{.scope}{.space}.add.noftz{.level::cache_hint}.bf16x2 + [a], b {, cache-policy}; + + .space = { .global, .shared{::cta, ::cluster} }; + .sem = {.relaxed, .release}; + .scope = {.cta, .cluster, .gpu, .sys}; + + .op = { .and, .or, .xor, + .add, .inc, .dec, + .min, .max }; + .level::cache_hint = { .L2::cache_hint }; + .type = { .b32, .b64, .u32, .u64, .s32, .s64, .f32, .f64 }; + +Reduction operation with vector type: + +red{.sem}{.scope}{.global}.add{.level::cache_hint}.vec_32_bit.f32 [a], b{, cache-policy}; + red{.sem}{.scope}{.global}.op.noftz{.level::cache_hint}. vec_16_bit.half_word_type [a], b{, cache-policy}; + red{.sem}{.scope}{.global}.op.noftz{.level::cache_hint}.vec_32_bit.packed_type [a], b {, cache-policy}; + + .sem = { .relaxed, .release }; + .scope = { .cta, .cluster, .gpu, .sys }; + .op = { .add, .min, .max }; + .half_word_type = { .f16, .bf16 }; + .packed_type = { .f16x2,.bf16x2 }; + .vec_16_bit = { .v2, .v4, .v8 } + .vec_32_bit = { .v2, .v4 }; + .level::cache_hint = { .L2::cache_hint } + +Description + +Performs a reduction operation with operand `b` and the value in location `a`, and stores the result of the specified operation at location `a`, overwriting the original value. Operand `a` specifies a location in the specified state space. If no state space is given, perform the memory accesses using [Generic Addressing](<#generic-addressing>). `red` with scalar type may be used only with `.global` and `.shared` spaces and with generic addressing, where the address points to `.global` or `.shared` space. `red` with vector type may be used only with `.global` space and with generic addressing where the address points to `.global` space. + +For `red` with vector type, operand `b` is brace-enclosed vector expressions, size of which is equal to the size of vector qualifier. + +If no sub-qualifier is specified with `.shared` state space, then `::cta` is assumed by default. + +The optional `.sem` qualifier specifies a memory synchronizing effect as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.sem` qualifier is absent, `.relaxed` is assumed by default. + +The optional `.scope` qualifier specifies the set of threads that can directly observe the memory synchronizing effect of this operation, as described in the [Memory Consistency Model](<#memory-consistency-model>). If the `.scope` qualifier is absent, `.gpu` scope is assumed by default. + +For `red` with vector type, the supported combinations of vector qualifier, types and reduction operations supported on these combinations are depicted in following table: + +Vector qualifier | Types +---|--- +`.f16`/ `bf16` | `.f16x2`/ `bf16x2` | `.f32` +`.v2` | `.add`, `.min`, `.max` | `.add`, `.min`, `.max` | `.add` +`.v4` | `.add`, `.min`, `.max` | `.add`, `.min`, `.max` | `.add` +`.v8` | `.add`, `.min`, `.max` | Not supported | Not Supported + +Two atomic operations (`atom` or `red`) are performed atomically with respect to each other only if each operation specifies a scope that includes the other. When this condition is not met, each operation observes the other operation being performed as if it were split into a read followed by a dependent write. + +`red` instruction on packed type or vector type, accesses adjacent scalar elements in memory. In such case, the atomicity is guaranteed separately for each of the individual scalar elements; the entire `red` is not guaranteed to be atomic as a single access. + +For `sm_6x` and earlier architectures, `red` operations on `.shared` state space do not guarantee atomicity with respect to normal store instructions to the same address. It is the programmer’s responsibility to guarantee correctness of programs that use shared memory reduction instructions, e.g., by inserting barriers between normal stores and reduction operations to a common address, or by using `atom.exch` to store to locations accessed by other reduction operations. + +Supported addressing modes for operand `a` and alignment requirements are described in [Addresses as Operands](<#addresses-as-operands>) + +The bit-size operations are `.and`, `.or`, and `.xor`. + +The integer operations are `.add`, `.inc`, `.dec`, `.min`, `.max`. The `.inc` and `.dec` operations return a result in the range `[0..b]`. + +The floating-point operation `.add` operation rounds to nearest even. Current implementation of `red.add.f32` on global memory flushes subnormal inputs and results to sign-preserving zero; whereas `red.add.f32` on shared memory supports subnormal inputs and results and doesn’t flush them to zero. + +`red.add.f16`, `red.add.f16x2`, `red.add.bf16` and `red.add.bf16x2` operation requires the `.noftz` qualifier; it preserves subnormal inputs and results, and does not flush them to zero. + +When the optional argument `cache-policy` is specified, the qualifier `.level::cache_hint` is required. The 64-bit operand `cache-policy` specifies the cache eviction policy that may be used during the memory access. + +The qualifier `.level::cache_hint` is only supported for `.global` state space and for generic addressing where the address points to the `.global` state space. + +`cache-policy` is a hint to the cache subsystem and may not always be respected. It is treated as a performance hint only, and does not change the memory consistency behavior of the program. + +Semantics + +*a = operation(*a, b); + + where + inc(r, s) = (r >= s) ? 0 : r+1; + dec(r, s) = (r==0 || r > s) ? s : r-1; + +PTX ISA Notes + +Introduced in PTX ISA version 1.2. + +`red.add.f32` and `red.shared.add.u64` introduced in PTX ISA 2.0. + +64-bit `red.{and,or,xor,min,max}` introduced in PTX ISA 3.1. + +`red.add.f64` introduced in PTX ISA 5.0. + +`.scope` qualifier introduced in PTX ISA 5.0. + +`.sem` qualifier introduced in PTX ISA version 6.0. + +`red.add.noftz.f16x2` introduced in PTX ISA 6.2. + +`red.add.noftz.f16` introduced in PTX ISA 6.3. + +Per-element atomicity of `red.f16x2` clarified in PTX ISA version 6.3, with retrospective effect from PTX ISA version 6.2 + +Support for `.level::cache_hint` qualifier introduced in PTX ISA version 7.4. + +`red.add.noftz.bf16` and `red.add.noftz.bf16x2` introduced in PTX ISA 7.8. + +Support for `.cluster` scope qualifier introduced in PTX ISA version 7.8. + +Support for `::cta` and `::cluster` sub-qualifiers introduced in PTX ISA version 7.8. + +Support for vector types introduced in PTX ISA version 8.1. + +Target ISA Notes + +`red.global` requires `sm_11` or higher + +`red.shared` requires `sm_12` or higher. + +`red.global.add.u64` requires `sm_12` or higher. + +`red.shared.add.u64` requires `sm_20` or higher. + +64-bit `red.{and,or,xor,min,max}` require `sm_32` or higher. + +`red.add.f32` requires `sm_20` or higher. + +`red.add.f64` requires `sm_60` or higher. + +`.scope` qualifier requires `sm_60` or higher. + +`.sem` qualifier requires `sm_70` or higher. + +Use of generic addressing requires `sm_20` or higher. + +`red.add.noftz.f16x2` requires `sm_60` or higher. + +`red.add.noftz.f16` requires `sm_70` or higher. + +Support for `.level::cache_hint` qualifier requires `sm_80` or higher. + +`red.add.noftz.bf16` and `red.add.noftz.bf16x2` require `sm_90` or higher. + +Support for `.cluster` scope qualifier requires `sm_90` or higher. + +Sub-qualifier `::cta` requires `sm_30` or higher. + +Sub-qualifier `::cluster` requires `sm_90` or higher. + +Support for vector types requires `sm_90` or higher. + +Examples + +red.global.add.s32 [a],1; + red.shared::cluster.max.u32 [x+4],0; + @p red.global.and.b32 [p],my_val; + red.global.sys.add.u32 [a], 1; + red.global.acquire.sys.add.u32 [gbl], 1; + red.add.noftz.f16x2 [a], b; + red.add.noftz.bf16 [a], hb; + red.add.noftz.bf16x2 [b], bb; + red.global.cluster.relaxed.add.u32 [a], 1; + red.shared::cta.min.u32 [x+4],0; + + createpolicy.fractional.L2::evict_last.b64 cache-policy, 0.25; + red.global.and.L2::cache_hint.b32 [a], 1, cache-policy; + + red.global.v8.f16.add.noftz [gbl], {%h0, %h1, %h2, %h3, %h4, %h5, %h6, %h7}; + red.global.v8.bf16.min.noftz [gbl], {%h0, %h1, %h2, %h3, %h4, %h5, %h6, %h7}; + red.global.v2.f16.add.noftz [gbl], {%h0, %h1}; + red.global.v2.bf16.add.noftz [gbl], {%h0, %h1}; + red.global.v4.f16x2.max.noftz [gbl], {%h0, %h1, %h2, %h3}; + red.global.v4.f32.add [gbl], {%f0, %f1, %f2, %f3}; + red.global.v2.f16x2.max.noftz {%bd0, %bd1}, [g], {%b0, %b1}; + red.global.v2.bf16x2.add.noftz {%bd0, %bd1}, [g], {%b0, %b1}; + red.global.v2.f32.add {%f0, %f1}, [g], {%f0, %f1}; \ No newline at end of file diff --git a/content/cuda/docs/ptx-redasync/DOC.md b/content/cuda/docs/ptx-redasync/DOC.md new file mode 100644 index 00000000..e6f6d276 --- /dev/null +++ b/content/cuda/docs/ptx-redasync/DOC.md @@ -0,0 +1,167 @@ +--- +name: ptx-redasync +description: Asynchronous reduction operation. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.7. Parallel Synchronization and Communication Instructions:red.async + +--- +title: "9.7.13.7. Parallel Synchronization and Communication Instructions:red.async" +section: 9.7.13.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.7. Parallel Synchronization and Communication Instructions:red.async + + +`red.async` + +Asynchronous reduction operation. + +Syntax + +// Increment and Decrement reductions + red.async.sem.scope{.ss}.completion_mechanism.op.type [a], b, [mbar]; + + .sem = { .relaxed }; + .scope = { .cluster }; + .ss = { .shared::cluster }; + .op = { .inc, .dec }; + .type = { .u32 }; + .completion_mechanism = { .mbarrier::complete_tx::bytes }; + + + // MIN and MAX reductions + red.async.sem.scope{.ss}.completion_mechanism.op.type [a], b, [mbar]; + + .sem = { .relaxed }; + .scope = { .cluster }; + .ss = { .shared::cluster }; + .op = { .min, .max }; + .type = { .u32, .s32 }; + .completion_mechanism = { .mbarrier::complete_tx::bytes }; + + // Bitwise AND, OR and XOR reductions + red.async.sem.scope{.ss}.completion_mechanism.op.type [a], b, [mbar]; + + .sem = { .relaxed }; + .scope = { .cluster }; + .ss = { .shared::cluster }; + .op = { .and, .or, .xor }; + .type = { .b32 }; + .completion_mechanism = { .mbarrier::complete_tx::bytes }; + + // ADD reductions + red.async.sem.scope{.ss}.completion_mechanism.add.type [a], b, [mbar]; + + .sem = { .relaxed }; + .scope = { .cluster }; + .ss = { .shared::cluster }; + .type = { .u32, .s32, .u64 }; + .completion_mechanism = { .mbarrier::complete_tx::bytes }; + + red.async{.mmio}.sem.scope{.ss}.add.type [a], b; + + .sem = { .release }; + .scope = { .gpu, .cluster }; + .ss = { .global }; + .type = { .u32, .s32, .u64, .s64 }; + +Description + +`red.async` is a non-blocking instruction which initiates an asynchronous reduction operation specified by `.op`, with the operand `b` and the value at destination shared memory location specified by operand `a`. + +Operands + +* `a` is a destination address, and must be either a register, or of the form `register + immOff`, as described in [Addresses as Operands](<#addresses-as-operands>). + + * `b` is a source value, of the type indicated by qualifier `.type`. + + * `mbar` is an mbarrier object address. + +Qualifiers + +* `.mmio` indicates whether this is an [mmio Operation](<#mmio-operation>). + + * `.sem` specifies the memory ordering semantics as described in the [Memory Consistency Model](<#memory-consistency-model>). + + * `.scope` specifies the set of threads with which this instruction can directly synchronize. + + * `.ss` specifies the state space of the destination operand `a` and the mbarrier operand `mbar`. + + * If `.ss` is not specified, [Generic Addressing](<#generic-addressing>) is used. + + * `.completion_mechanism` specifies the mechanism for observing the completion of the asynchronous operation. + + * When `.completion_mechanism` is `.mbarrier::complete_tx::bytes`: upon completion of the asynchronous operation, a [complete-tx](<#parallel-synchronization-and-communication-instructions-mbarrier-complete-tx-operation>) operation will be performed on the mbarrier object specified by the operand `mbar`, with `completeCount` argument equal to the amount of data stored in bytes. + + * When `.completion_mechanism` is not specified: the completion of the store synchronizes with the end of the CTA. This instruction accesses its `mbarrier` operand using generic-proxy. + + * `.op` specifies the reduction operation. + + * The `.inc` and `.dec` operations return a result in the range `[0..b]`. + + * `.type` specifies the type of the source operand `b`. + +Conditions + +When `.sem` is `.relaxed`: + +* The reduce operation is a relaxed memory operation. + + * The complete-tx operation on the mbarrier has `.release` semantics at `.cluster` scope. + + * The shared-memory addresses of the destination operand `a` and the mbarrier operand `mbar` must meet all of the following conditions: + + * They belong to the same CTA. + + * The CTA to which they belong is different from the CTA of the executing thread, but must be within the same cluster. + +Otherwise, the behavior is undefined. + + * `.mmio` must not be specified. + + * If `.ss` is specified, it must be `.shared::cluster`. + + * If `.ss` is not specified, generic addressing is used for operands `a` and `mbar`. If the generic addresses specified do not fall within the address window of `.shared::cluster` state space, the behavior is undefined. + + * If `.completion_mechanism` is specified, it must be `.mbarrier::complete_tx::bytes`. + + * If `.completion_mechanism` is not specified, it defaults to `.mbarrier::complete_tx::bytes`. + +When `.sem` is `.release`: + +* The reduce operation is a strong memory operation with `.release` semantics at the scope specified by `.scope`. + + * If `.mmio` is specified, `.scope` must be `.sys`. + + * If `.ss` is specified, it must be `.global`. + + * If `.ss` is not specified, generic addressing is used for operand `a`. If the generic address specified does not fall within the address window of `.global` state space, the behavior is undefined. + + * `.completion_mechanism` must not be specified. + +PTX ISA Notes + +Introduced in PTX ISA version 8.1. + +Support for `.mmio` qualifier, `.release` semantics, `.global` state space, and `.gpu` and `.sys` scopes introduced in PTX ISA version 8.7. + +Target ISA Notes + +Requires `sm_90` or higher. + +`.mmio` qualifier, `.release` semantics, `.global` state space, and `.gpu` and `.sys` scopes require `sm_100` or higher. + +Examples + +red.async.relaxed.cluster.shared::cluster.mbarrier::complete_tx::bytes.min.u32 [addr], b, [mbar_addr]; + + red.async.release.sys.global.add.u32 [addr], b; \ No newline at end of file diff --git a/content/cuda/docs/ptx-reductions-do-not-form-acquire-patterns/DOC.md b/content/cuda/docs/ptx-reductions-do-not-form-acquire-patterns/DOC.md new file mode 100644 index 00000000..6a62d5e9 --- /dev/null +++ b/content/cuda/docs/ptx-reductions-do-not-form-acquire-patterns/DOC.md @@ -0,0 +1,52 @@ +--- +name: ptx-reductions-do-not-form-acquire-patterns +description: Atomic reduction operations like `red` do not form acquire patterns with + acquire fences. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.11.1. Reductions do not form Acquire Patterns + +--- +title: "8.11.1. Reductions do not form Acquire Patterns" +section: 8.11.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 8.11.1. Reductions do not form Acquire Patterns + + +Atomic reduction operations like `red` do not form acquire patterns with acquire fences. + +**Litmus Test: Message Passing with a Red Instruction** + +.global .u32 x = 0; + .global .u32 flag = 0; + + +--- +T1 | T2 + + + W1: st.u32 [x], 42; + W2: st.release.gpu.u32 [flag], 1; + + +| + + + RMW1: red.sys.global.add.u32 [flag], 1; + F2: fence.acquire.gpu; + R2: ld.weak.u32 %r1, [x]; + + + + %r1 == 0 AND flag == 2 + +The litmus test known as “MP” (Message Passing) demonstrates the consequence of reductions being excluded from acquire patterns. It is possible to observe the outcome where `R2` reads the value `0` from `x` and `flag` has the final value of `2`. This outcome is possible since the release pattern in `T1` does not synchronize with any acquire pattern in `T2`. Using the `atom` instruction instead of `red` forbids this outcome. \ No newline at end of file diff --git a/content/cuda/docs/ptx-reduxsync/DOC.md b/content/cuda/docs/ptx-reduxsync/DOC.md new file mode 100644 index 00000000..9ccd39c8 --- /dev/null +++ b/content/cuda/docs/ptx-reduxsync/DOC.md @@ -0,0 +1,89 @@ +--- +name: ptx-reduxsync +description: Perform reduction operation on the data from each predicated active thread + in the thread group. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.13.12. Parallel Synchronization and Communication Instructions:redux.sync + +--- +title: "9.7.13.12. Parallel Synchronization and Communication Instructions:redux.sync" +section: 9.7.13.12 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.13.12. Parallel Synchronization and Communication Instructions:redux.sync + + +`redux.sync` + +Perform reduction operation on the data from each predicated active thread in the thread group. + +Syntax + +redux.sync.op.type dst, src, membermask; + .op = {.add, .min, .max} + .type = {.u32, .s32} + + redux.sync.op.b32 dst, src, membermask; + .op = {.and, .or, .xor} + + redux.sync.op{.abs.}{.NaN}.f32 dst, src, membermask; + .op = { .min, .max } + +Description + +`redux.sync` will cause the executing thread to wait until all non-exited threads corresponding to `membermask` have executed `redux.sync` with the same qualifiers and same `membermask` value before resuming execution. + +Operand `membermask` specifies a 32-bit integer which is a mask indicating threads participating in this instruction where the bit position corresponds to thread’s `laneid`. + +`redux.sync` performs a reduction operation `.op` of the 32 bit source register `src` across all non-exited threads in the `membermask`. The result of the reduction operation is written to the 32 bit destination register `dst`. + +Reduction operation can be one of the bitwise operation in `.and`, `.or`, `.xor` or arithmetic operation in `.add`, `.min` , `.max`. + +For the `.add` operation result is truncated to 32 bits. + +For `.f32` instruction type, if the input value is 0.0 then +0.0 > -0.0. + +If `.abs` qualifier is specified, then the absolute value of the input is considered for the reduction operation. + +If the `.NaN` qualifier is specified, then the result of the reduction operation is canonical NaN if the input to the reduction operation from any participating thread is NaN. + +In the absence of `.NaN` qualifier, only non-NaN values are considered for the reduction operation and the result will be canonical NaN when all inputs are NaNs. + +The behavior of `redux.sync` is undefined if the executing thread is not in the `membermask`. + +PTX ISA Notes + +Introduced in PTX ISA version 7.0. + +Support for `.f32` type is introduced in PTX ISA version 8.6. + +Support for `.abs` and `.NaN` qualifiers is introduced in PTX ISA version 8.6. + +Target ISA Notes + +Requires `sm_80` or higher. + +`.f32` type requires `sm_100a` and is supported on `sm_100f` from PTX ISA version 8.8. + +Qualifiers `.abs` and `.NaN` require `sm_100a` and are supported on `sm_100f` or higher in the same family from PTX ISA version 8.8. + +Release Notes + +Note that `redux.sync` applies to threads in a single warp, not across an entire CTA. + +Examples + +.reg .b32 dst, src, init, mask; + redux.sync.add.s32 dst, src, 0xff; + redux.sync.xor.b32 dst, src, mask; + + redux.sync.min.abs.NaN.f32 dst, src, mask; \ No newline at end of file diff --git a/content/cuda/docs/ptx-register-state-space/DOC.md b/content/cuda/docs/ptx-register-state-space/DOC.md new file mode 100644 index 00000000..375b3576 --- /dev/null +++ b/content/cuda/docs/ptx-register-state-space/DOC.md @@ -0,0 +1,30 @@ +--- +name: ptx-register-state-space +description: Registers (`.reg` state space) are fast storage locations. The number + of registers is limited, and will vary from platform to platform. When the limit + is exceeded, register variables will be spilled t... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.1.1. Register State Space + +--- +title: "5.1.1. Register State Space" +section: 5.1.1 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.1.1. Register State Space + + +Registers (`.reg` state space) are fast storage locations. The number of registers is limited, and will vary from platform to platform. When the limit is exceeded, register variables will be spilled to memory, causing changes in performance. For each architecture, there is a recommended maximum number of registers to use (see the _CUDA Programming Guide_ for details). + +Registers may be typed (signed integer, unsigned integer, floating point, predicate) or untyped. Register size is restricted; aside from predicate registers which are 1-bit, scalar registers have a width of 8-, 16-, 32-, 64-, or 128-bits, and vector registers have a width of 16-, 32-, 64-, or 128-bits. The most common use of 8-bit registers is with `ld`, `st`, and `cvt` instructions, or as elements of vector tuples. + +Registers differ from the other state spaces in that they are not fully addressable, i.e., it is not possible to refer to the address of a register. When compiling to use the Application Binary Interface (ABI), register variables are restricted to function scope and may not be declared at module scope. When compiling legacy PTX code (ISA versions prior to 3.0) containing module-scoped `.reg` variables, the compiler silently disables use of the ABI. Registers may have alignment boundaries required by multi-word loads and stores. \ No newline at end of file diff --git a/content/cuda/docs/ptx-release-and-acquire-patterns/DOC.md b/content/cuda/docs/ptx-release-and-acquire-patterns/DOC.md new file mode 100644 index 00000000..b840f3de --- /dev/null +++ b/content/cuda/docs/ptx-release-and-acquire-patterns/DOC.md @@ -0,0 +1,64 @@ +--- +name: ptx-release-and-acquire-patterns +description: Some sequences of instructions give rise to patterns that participate + in memory synchronization as described later. The _release_ pattern makes prior + operations from the current thread1 visible to som... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 8.8. Release and Acquire Patterns + +--- +title: "8.8. Release and Acquire Patterns" +section: 8.8 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +## 8.8. Release and Acquire Patterns + + +Some sequences of instructions give rise to patterns that participate in memory synchronization as described later. The _release_ pattern makes prior operations from the current thread1 visible to some operations from other threads. The _acquire_ pattern makes some operations from other threads visible to later operations from the current thread. + +A _release_ pattern on a location M consists of one of the following: + +1. A _release_ operation on M + +E.g.: `st.release [M];` or `atom.release [M];` or `mbarrier.arrive.release [M];` + + 2. Or a _release_ or _acquire-release_ operation on M followed by a _strong_ write on M in _program order_ + +E.g.: `st.release [M]`; `st.relaxed [M];` + + 3. Or a _release_ or _acquire-release_ _memory fence_ followed by a _strong_ write on M in _program order_ + +E.g.: `fence.release; st.relaxed [M];` or `fence.release; atom.relaxed [M];` + +Any _memory synchronization_ established by a _release_ pattern only affects operations occurring in _program order_ before the first instruction in that pattern. + +An _acquire_ pattern on a location M consists of one of the following: + +1. An _acquire_ operation on M + +E.g.: `ld.acquire [M];` or `atom.acquire [M];` or `mbarrier.test_wait.acquire [M];` + + 2. Or a _strong_ read on M followed by an _acquire_ operation on M in _program order_ + +E.g.: `ld.relaxed [M]; ld.acquire [M];` + + 3. Or a _strong_ read on M followed by an acquire _memory fence_ in _program order_ + +E.g.: `ld.relaxed [M]; fence.acquire;` or `atom.relaxed [M]; fence.acquire;` + +Any _memory synchronization_ established by an _acquire_ pattern only affects operations occurring in _program order_ after the last instruction in that pattern. + +Note that while atomic reductions conceptually perform a strong read as part of its read-modify-write sequence, this strong read does not form an acquire pattern. + +> E.g.: `red.add [M], 1; fence.acquire;` is not an acquire pattern. + +1 For both _release_ and _acquire_ patterns, this effect is further extended to operations in other threads through the transitive nature of _causality order_. \ No newline at end of file diff --git a/content/cuda/docs/ptx-rem/DOC.md b/content/cuda/docs/ptx-rem/DOC.md new file mode 100644 index 00000000..3576913f --- /dev/null +++ b/content/cuda/docs/ptx-rem/DOC.md @@ -0,0 +1,59 @@ +--- +name: ptx-rem +description: The remainder of integer division. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.9. Integer Arithmetic Instructions:rem + +--- +title: "9.7.1.9. Integer Arithmetic Instructions:rem" +section: 9.7.1.9 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.9. Integer Arithmetic Instructions:rem + + +`rem` + +The remainder of integer division. + +Syntax + +rem.type d, a, b; + + .type = { .u16, .u32, .u64, + .s16, .s32, .s64 }; + +Description + +Divides `a` by `b`, store the remainder in `d`. + +Semantics + +d = a % b; + +Notes + +The behavior for negative numbers is machine-dependent and depends on whether divide rounds towards zero or negative infinity. + +Division by zero yields an unspecified, machine-specific value. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +rem.s32 x,x,8; // x = x%8; \ No newline at end of file diff --git a/content/cuda/docs/ptx-restricted-use-of-sub-word-sizes/DOC.md b/content/cuda/docs/ptx-restricted-use-of-sub-word-sizes/DOC.md new file mode 100644 index 00000000..fa8442fb --- /dev/null +++ b/content/cuda/docs/ptx-restricted-use-of-sub-word-sizes/DOC.md @@ -0,0 +1,28 @@ +--- +name: ptx-restricted-use-of-sub-word-sizes +description: The `.u8`, `.s8`, and `.b8` instruction types are restricted to `ld`, + `st`, and `cvt` instructions. The `.f16` floating-point type is allowed only in + conversions to and from `.f32`, `.f64` types, in h... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 5.2.2. Restricted Use of Sub-Word Sizes + +--- +title: "5.2.2. Restricted Use of Sub-Word Sizes" +section: 5.2.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 5.2.2. Restricted Use of Sub-Word Sizes + + +The `.u8`, `.s8`, and `.b8` instruction types are restricted to `ld`, `st`, and `cvt` instructions. The `.f16` floating-point type is allowed only in conversions to and from `.f32`, `.f64` types, in half precision floating point instructions and texture fetch instructions. The `.f16x2` floating point type is allowed only in half precision floating point arithmetic instructions and texture fetch instructions. + +For convenience, `ld`, `st`, and `cvt` instructions permit source and destination data operands to be wider than the instruction-type size, so that narrow values may be loaded, stored, and converted using regular-width registers. For example, 8-bit or 16-bit values may be held directly in 32-bit or 64-bit registers when being loaded, stored, or converted to other types and sizes. \ No newline at end of file diff --git a/content/cuda/docs/ptx-ret/DOC.md b/content/cuda/docs/ptx-ret/DOC.md new file mode 100644 index 00000000..9d17c0f8 --- /dev/null +++ b/content/cuda/docs/ptx-ret/DOC.md @@ -0,0 +1,53 @@ +--- +name: ptx-ret +description: Return from function to instruction after call. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.12.6. Control Flow Instructions:ret + +--- +title: "9.7.12.6. Control Flow Instructions:ret" +section: 9.7.12.6 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.12.6. Control Flow Instructions:ret + + +`ret` + +Return from function to instruction after call. + +Syntax + +ret{.uni}; + +Description + +Return execution to caller’s environment. A divergent return suspends threads until all threads are ready to return to the caller. This allows multiple divergent `ret` instructions. + +A `ret` is assumed to be divergent unless the `.uni` suffix is present, indicating that the return is guaranteed to be non-divergent. + +Any values returned from a function should be moved into the return parameter variables prior to executing the `ret` instruction. + +A return instruction executed in a top-level entry routine will terminate thread execution. + +PTX ISA Notes + +Introduced in PTX ISA version 1.0. + +Target ISA Notes + +Supported on all target architectures. + +Examples + +ret; + @p ret; \ No newline at end of file diff --git a/content/cuda/docs/ptx-rounding-modifiers/DOC.md b/content/cuda/docs/ptx-rounding-modifiers/DOC.md new file mode 100644 index 00000000..62fbce47 --- /dev/null +++ b/content/cuda/docs/ptx-rounding-modifiers/DOC.md @@ -0,0 +1,42 @@ +--- +name: ptx-rounding-modifiers +description: Conversion instructions may specify a rounding modifier. In PTX, there + are four integer rounding modifiers and six floating-point rounding modifiers. [Table + 17](<#rounding-modifiers-floating-point-rou... +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 6.5.2. Rounding Modifiers + +--- +title: "6.5.2. Rounding Modifiers" +section: 6.5.2 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +### 6.5.2. Rounding Modifiers + + +Conversion instructions may specify a rounding modifier. In PTX, there are four integer rounding modifiers and six floating-point rounding modifiers. [Table 17](<#rounding-modifiers-floating-point-rounding-modifiers>) and [Table 18](<#rounding-modifiers-integer-rounding-modifiers>) summarize the rounding modifiers. + +Table 17 Floating-Point Rounding Modifiers Modifier | Description +---|--- +`.rn` | rounds to nearest even +`.rna` | rounds to nearest, ties away from zero +`.rz` | rounds towards zero +`.rm` | rounds towards negative infinity +`.rp` | rounds towards positive infinity +`.rs` | rounds either towards zero or away from zero based on the carry out of the integer addition of random bits and the discarded bits of mantissa + +Table 18 Integer Rounding Modifiers Modifier | Description +---|--- +`.rni` | round to nearest integer, choosing even integer if source is equidistant between two integers. +`.rzi` | round to nearest integer in the direction of zero +`.rmi` | round to nearest integer in direction of negative infinity +`.rpi` | round to nearest integer in direction of positive infinity \ No newline at end of file diff --git a/content/cuda/docs/ptx-rsqrt/DOC.md b/content/cuda/docs/ptx-rsqrt/DOC.md new file mode 100644 index 00000000..584c03cb --- /dev/null +++ b/content/cuda/docs/ptx-rsqrt/DOC.md @@ -0,0 +1,91 @@ +--- +name: ptx-rsqrt +description: Take the reciprocal of the square root of a value. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.16. Floating Point Instructions:rsqrt + +--- +title: "9.7.3.16. Floating Point Instructions:rsqrt" +section: 9.7.3.16 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.16. Floating Point Instructions:rsqrt + + +`rsqrt` + +Take the reciprocal of the square root of a value. + +Syntax + +rsqrt.approx{.ftz}.f32 d, a; + rsqrt.approx.f64 d, a; + +Description + +Compute `1/sqrt(a)` and store the result in `d`. + +Semantics + +d = 1/sqrt(a); + +Notes + +`rsqrt.approx` implements an approximation to the reciprocal square root. + +Input | Result +---|--- +-Inf | NaN +-normal | NaN +-0.0 | -Inf ++0.0 | +Inf ++Inf | +0.0 +NaN | NaN + +The maximum relative error for `rsqrt.f32` over the entire positive finite floating-point range is 2-22.9. + +Subnormal numbers: + +`sm_20+` + + +By default, subnormal numbers are supported. + +`rsqrt.ftz.f32` flushes subnormal inputs and results to sign-preserving zero. + +`sm_1x` + + +`rsqrt.f64` supports subnormal numbers. + +`rsqrt.f32` flushes subnormal inputs and results to sign-preserving zero. + +Note that `rsqrt.approx.f64` is emulated in software and are relatively slow. + +PTX ISA Notes + +`rsqrt.f32` and `rsqrt.f64` were introduced in PTX ISA version 1.0. Explicit modifiers `.approx` and `.ftz` were introduced in PTX ISA version 1.4. + +For PTX ISA version 1.4 and later, the `.approx` modifier is required. + +For PTX ISA versions 1.0 through 1.3, `rsqrt.f32` defaults to `rsqrt.approx.ftz.f32`, and `rsqrt.f64` defaults to `rsqrt.approx.f64`. + +Target ISA Notes + +`rsqrt.f32` supported on all target architectures. + +`rsqrt.f64` requires `sm_13` or higher. + +Examples + +rsqrt.approx.ftz.f32 isr, x; + rsqrt.approx.f64 ISR, X; \ No newline at end of file diff --git a/content/cuda/docs/ptx-rsqrtapproxftzf64/DOC.md b/content/cuda/docs/ptx-rsqrtapproxftzf64/DOC.md new file mode 100644 index 00000000..12f0667f --- /dev/null +++ b/content/cuda/docs/ptx-rsqrtapproxftzf64/DOC.md @@ -0,0 +1,70 @@ +--- +name: ptx-rsqrtapproxftzf64 +description: '`rsqrt.approx.ftz.f64`' +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.3.17. Floating Point Instructions:rsqrt.approx.ftz.f64 + +--- +title: "9.7.3.17. Floating Point Instructions:rsqrt.approx.ftz.f64" +section: 9.7.3.17 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.3.17. Floating Point Instructions:rsqrt.approx.ftz.f64 + + +`rsqrt.approx.ftz.f64` + +Compute an approximation of the square root reciprocal of a value. + +Syntax + +rsqrt.approx.ftz.f64 d, a; + +Description + +Compute a double-precision (`.f64`) approximation of the square root reciprocal of a value. The least significant 32 bits of the double-precision (`.f64`) destination `d` are all zeros. + +Semantics + +tmp = a[63:32]; // upper word of a, 1.11.20 format + d[63:32] = 1.0 / sqrt(tmp); + d[31:0] = 0x00000000; + +Notes + +`rsqrt.approx.ftz.f64` implements a fast approximation of the square root reciprocal of a value. + +Input | Result +---|--- +-Inf | NaN +-subnormal | -Inf +-0.0 | -Inf ++0.0 | +Inf ++subnormal | +Inf ++Inf | +0.0 +NaN | NaN + +Input `NaN`s map to a canonical `NaN` with encoding `0x7fffffff00000000`. + +Subnormal inputs and results are flushed to sign-preserving zero. + +PTX ISA Notes + +`rsqrt.approx.ftz.f64` introduced in PTX ISA version 4.0. + +Target ISA Notes + +`rsqrt.approx.ftz.f64` requires `sm_20` or higher. + +Examples + +rsqrt.approx.ftz.f64 xi,x; \ No newline at end of file diff --git a/content/cuda/docs/ptx-sad/DOC.md b/content/cuda/docs/ptx-sad/DOC.md new file mode 100644 index 00000000..d9dccf3e --- /dev/null +++ b/content/cuda/docs/ptx-sad/DOC.md @@ -0,0 +1,54 @@ +--- +name: ptx-sad +description: Sum of absolute differences. +metadata: + languages: cuda + versions: '9.1' + revision: 1 + updated-on: '2026-03-28' + source: official + tags: cuda,gpu,ptx,isa +--- + +# 9.7.1.7. Integer Arithmetic Instructions:sad + +--- +title: "9.7.1.7. Integer Arithmetic Instructions:sad" +section: 9.7.1.7 +url: https://docs.nvidia.com/cuda/parallel-thread-execution/ +--- + +#### 9.7.1.7. Integer Arithmetic Instructions:sad + + +`sad` + +Sum of absolute differences. + +Syntax + +sad.type d, a, b, c; + + .type = { .u16, .u32, .u64, + .s16, .s32, .s64 }; + +Description + +Adds the absolute value of `a-b` to `c` and writes the resulting value into `d`. + +Semantics + +d = c + ((a