Cuda interop

From NVIDIA-Omniverse/ovrtx · View interactive version

Cuda interop is an AI agent skill from the GitHub repository NVIDIA-Omniverse/ovrtx. GPU interop patterns for CUDA arrays, timeline semaphores, Vulkan shared memory, and MIG-safe CUDA-to-Vulkan device matching. Use when user asks about CUDA interop, GPU rendering pipelines, Vulkan interop, shared memory, timeline semaphores, MIG, or multi-GPU output routing.

How to use this skill

Skill file

CUDA Interop

When to Use

Use this skill when the user asks about CUDA interop, GPU rendering pipelines, Vulkan interop, shared memory, or timeline semaphores.

Inputs

Resolve inputs in this order: existing repository files and referenced snippets, explicit user request, then broader agent context.

Prerequisites

Instructions

  1. Identify whether the workflow maps render output to CUDA memory, maps output to a CUDA array, writes attributes from CUDA memory, or coordinates CUDA with Vulkan.
  2. Read the source snippet for the exact map/unmap path before choosing between linear CUDA memory and a CUDA array; both selectors exist in C (OVRTX_MAP_DEVICE_TYPE_CUDA, OVRTX_MAP_DEVICE_TYPE_CUDA_ARRAY) and in Python (Device.CUDA, Device.CUDA_ARRAY).
  3. Preserve the synchronization contract: wait on ovrtx-provided CUDA events before reading unless enqueueing directly on an available borrowed producer stream, record CUDA work completion events before unmapping, and use sync_stream only for the auto-sync path.
  4. For Vulkan interop, keep external-memory ownership, timeline semaphore ordering, and presentation-ring lifetimes aligned with the full vulkan-interop example.
  5. When changing code, run the CUDA render-output or Vulkan interop example/test that owns the snippet whenever practical.
  6. Select a Vulkan device by comparing cuDeviceGetUuid_v2() for the configured or mapped CUDA ordinal with VkPhysicalDeviceIDProperties::deviceUUID. Do not use PCI identity, cudaDeviceProp::uuid, or legacy cuDeviceGetUuid() for MIG selection.

Output Format

Scripts

This skill has no scripts.

Limitations

Overview

ovrtx renders on the GPU and can provide output as CUDA device memory or as a CUDA array (zero-copy). Both are reachable from C and from Python. For advanced pipelines (e.g., Vulkan display, custom CUDA post-processing), you need to handle CUDA synchronization correctly to avoid race conditions between ovrtx's internal GPU work and your own.

Python

Experimental producer-stream handoff

Uniform zero-copy GPU mappings may expose MappedRenderVar.producer_stream

(C: ovrtx_render_var_output_t::cuda_sync.stream). This is a borrowed enqueue

target, not an additional readiness dependency. Consumers using the readiness

event must ignore the output stream rather than synchronize it as well.

Map with sync_stream=0 to avoid Python's default map-time legacy-stream event wait.

Queue short read-only work on the borrowed stream in the tensor device's primary

CUDA context, without an additional readiness wait. Work follows everything already

queued on that stream, including later products, the end of the render graph, and

already-submitted subsequent steps. This gives up per-product readiness, even when

wait_event identifies a per-product event; the same rule applies to the per-device fallback.

Keep the mapping alive through consumer completion and provide completion synchronization

at unmap. The mapping does not retain the stream; serialize use with render-graph rebuild,

reset, and destruction and finish reads before those operations. Never destroy, configure,

capture, or cache this stream. CPU, copied, compressed, and composite mappings retain

the event-based path.

Map render output to CUDA

Source: tests/docs/python/test_camera_sensors.py snippet doc-map-render-output-cuda

Map attribute to CUDA for Warp kernel writes

Source: tests/docs/python/test_attribute_bindings.py snippet doc-map-attribute-cuda

Map render output as CUDA array (zero-copy)

device=Device.CUDA_ARRAY takes the same zero-copy image path as the C API: ovrtx hands back the render target's CUDA array instead of copying it into linear memory. The array is an opaque image handle, so the DLTensor reports an opaque-handle dtype and no DLPack consumer can read it — np.from_dlpack(rv), .numpy(), and Warp DLPack ingest all fail or are meaningless here. Read the handle from tensor.cuda_array.

tensor.cuda_array raises if the tensor is linear memory rather than an array, which is what distinguishes it from reading the raw dl.data field yourself. Use rv["<tensor_name>"] when the render variable carries several tensors.

Source: tests/docs/python/test_camera_sensors.py snippet doc-map-render-output-cuda-array

Reading the handle is your CUDA work, not ovrtx's. ovrtx exposes the handle as a plain int and intentionally ships no Python-CUDA bridge to dereference it. Pick an existing one:

Caveat — pick the device from the tensor, not the default. The render product is not guaranteed to be on CUDA device 0; with several devices active, different render products can land on different ones. Always take the device from tensor.device.device_id and make it current before issuing the copy (wp.ScopedDevice(f"cuda:{tensor.device.device_id}")), otherwise the runtime call is issued against the wrong context. Map-time sync_stream= is awkward here for the same reason — the stream must live on the array's device, which you only learn after the mapping exists — so prefer rv.wait() or rv.wait_on(stream).

C

OVRTX_MAP_DEVICE_TYPE_CUDA_ARRAY is the C spelling of the same zero-copy path (ovrtx_map_render_var_output); the Python equivalent is device=Device.CUDA_ARRAY.

Select the exact Vulkan device, including MIG

CUDA device indices are process-visible ordinals after CUDA_VISIBLE_DEVICES

is applied. Use the same ordinal for the OVRTX active-GPU filter,

RenderProduct deviceIds, and application-side CUDA initialization.

Resolve that ordinal with the CUDA Driver API and query its MIG-aware identity:

Source: examples/c/vulkan-interop/src/cuda/cuda_kernel.cpp snippet resolve-cuda-device-uuid

Enumerate Vulkan physical devices and compare those UUID bytes with

VkPhysicalDeviceIDProperties::deviceUUID:

Source: examples/c/vulkan-interop/src/vk/vulkan_context.cpp snippet select-vulkan-device-by-cuda-uuid

For a simple application, validate the first mapped output against the

configured ordinal, then retain the initialization-time mapping:

Source: examples/c/vulkan-interop/src/main.cpp snippet validate-render-output-cuda-device

For multi-GPU rendering, use each mapped output's DLTensor.device.device_id

to select a Vulkan context cached for that CUDA ordinal. Do not use PCI identity,

cudaDeviceProp::uuid, legacy cuDeviceGetUuid(), Vulkan enumeration order, or

whichever CUDA context happens to be current to distinguish MIG instances.

Map render output to linear CUDA memory

Use OVRTX_MAP_DEVICE_TYPE_CUDA when your CUDA consumer expects a linear device pointer. Image outputs may require an internal copy into linear memory.

Source: tests/docs/c/test_camera_sensors.cpp snippet doc-map-render-output-cuda-c

Map render output as CUDA array (zero-copy)

Use OVRTX_MAP_DEVICE_TYPE_CUDA_ARRAY when your CUDA consumer can read a CUarray through texture/surface APIs and you want the zero-copy image path.

Source: tests/docs/c/test_camera_sensors.cpp snippet doc-map-render-output-cuda-array-c

Wait for render completion before accessing

The output may not be fully written when map returns. Check the wait event:

Source: examples/c/vulkan-interop/src/main.cpp snippet map-rendered-output-cuda-array

Check rendered_output.cuda_sync.wait_event and call cuStreamWaitEvent before accessing.

Both ovrtx_fetch_results() and ovrtx_map_render_var_output() take a timeout,

and passing 0 turns either into a non-blocking poll that returns

OVRTX_API_TIMEOUT. Polling both is what lets an interactive loop keep

presenting the previous frame instead of stalling on the renderer.

Which of the two absorbs the render wait is not part of the contract:

does not promise the output frames are mappable. Poll both and handle a

timeout from each.

the fetch succeeds every output frame of that step is already mappable, and

the map poll effectively never reports a timeout. This is why the sample

attributes renderer time to its Step metric and not to MapCopy.

Write against the guarantee, not the observation. The sample keeps the map poll

even though it never trips, because the ordering is a renderer implementation

detail that is free to change.

The same applies to any other output of the step, not just color. The

vulkan-interop sample polls its OVRTX_RENDER_VAR_PICK_HIT map on the same

terms, since a blocking map on a CPU-mapped output would stall presentation for

a whole readback. Keep the query pending and retry rather than waiting, and keep

the step result alive until every output you asked for has been read — mappings

and reads are what the result has to outlive, not the other way round.

Signal when CUDA work is done, then unmap

Source: examples/c/vulkan-interop/src/main.cpp snippet map-rendered-output-cuda-array

Record a CUDA event after your kernel, then pass it via ovrtx_cuda_sync_t.wait_event on unmap.

Be aware of when that unmap blocks. ovrtx_unmap_render_var_output() can defer

the wait onto the stream only when the mapping owns buffers it has to free

asynchronously. An OVRTX_MAP_DEVICE_TYPE_CUDA_ARRAY mapping is zero-copy and

owns none, so ovrtx waits for before_destroy_cuda_sync.wait_event on the CPU

inside the unmap call. Because the copy is stream-ordered behind the renderer's

own cuda_sync.wait_event, unmapping right after queueing the copy moves the

render wait out of the map and into the unmap rather than removing it.

To keep that wait out of the loop, hold the map_handle and unmap only once

cuEventQuery() reports the copy event complete. The mapping lifetime is

independent of ovrtx_destroy_results(), so the step result can be destroyed

first. This requires one event per in-flight frame: a single shared event is only

safe while the unmap blocks the loop until each copy has landed.

Ring-buffered async pattern (from vulkan-interop example)

For maximum throughput, use several shared images and cycle through them. CUDA

writes to one while a consumer (e.g., Vulkan) reads another.

Two images are enough only when one step yields one frame. With DLSS Frame

Generation a step yields N + 1 frames that all become mappable at once, and

showing them one at a time on a schedule means the ring has to hold the image

being displayed, the frames waiting their turn, and the one being written. With

only two, holding a frame back to pace it also blocks the next copy, which

throttles the renderer.

See examples/c/vulkan-interop/src/main.cpp for the full async rendering pattern

with timeline semaphores and CUDA-Vulkan shared images.

Map with sync_stream (auto-sync)

If you provide sync_stream on the map call, ovrtx inserts the wait automatically:

Source: tests/docs/c/test_camera_sensors.cpp snippet doc-map-render-output-cuda-array-c

The tested snippet sets map_desc.sync_stream = 1 to synchronize the CUDA default stream. The Vulkan example instead sets it to zero and explicitly waits on cuda_sync.wait_event in its own stream.

Key Types / Functions

| Concept | Python | C |

|---------|--------|---|

| Map to CUDA | render_var.map(device=Device.CUDA) | OVRTX_MAP_DEVICE_TYPE_CUDA |

| Map to CUDA array | render_var.map(device=Device.CUDA_ARRAY) | OVRTX_MAP_DEVICE_TYPE_CUDA_ARRAY |

| Get the CUDA array handle | tensor.cuda_array | (CUarray)dl.data |

| Read the CUDA array | wp.Texture2D(cuda_array=...) (Warp 1.15+), CuPy, or your own wrapper | surf2Dwrite/tex2D, cudaMemcpy2DFromArray |

| Wait for render | rv.wait(), rv.wait_on(stream), or sync_stream= on map() | cuStreamWaitEvent(stream, wait_event, 0) |

| Signal done | var.unmap(event=...) or var.unmap(stream=...) | cuda_sync.wait_event = (uintptr_t)event |

| Stream sync on map | sync_stream parameter | map_desc.sync_stream |

C CUDA synchronization uses ovrtx_cuda_sync_t with stream and wait_event

fields. A stream value of 0 means no stream, 1 means the default stream,

and values greater than 1 identify a specific CUDA stream. A wait_event

value of 0 means no event wait.

Troubleshooting

> Source: examples/c/vulkan-interop/src/cuda/cuda_kernel.cpp snippet cuda-device-max-connections

In Attached Mode (ovrtx 0.4+)

Rendered-output mapping (this skill) is unchanged by attached mode — ovrtx still

owns render products and their DLPack surfaces. What changes is the

attribute-side tensor exchange: when reading or writing ovstage-managed

attribute data (transforms, materials, cloned columns), the DLTensor path and

CUDA sync are owned by ovstage. See ovstage

`skills/dlpack-tensor-exchange/SKILL.md` for the copy-in / copy-out / zero-copy

map/unmap model, CPU vs CUDA residency, and `cuda_sync` semantics for

attribute data.

See docs/core/ovstage_integration.rst, skills/update-0_3-0_4-c/SKILL.md and skills/update-0_3-0_4-python/SKILL.md.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.