Skip to content

Handle zero-sized outputs in CUDA random generator kernels - #31997

Merged
Akshay Sonawane (apsonawane) merged 2 commits into
mainfrom
fix/cuda-random-empty-tensor
Aug 13, 2026
Merged

Handle zero-sized outputs in CUDA random generator kernels#31997
Akshay Sonawane (apsonawane) merged 2 commits into
mainfrom
fix/cuda-random-empty-tensor

Conversation

@apsonawane

Copy link
Copy Markdown
Contributor

RandomKernelImpl computed grid_size from CeilDiv(N, block_size * UNROLL), which is zero when the output tensor has no elements. The counter_offset expression then divided by block_size * grid_size * UNROLL, a host-side division by zero that traps before the kernel is launched. Zero-sized tensors are legal in ONNX, so return early when there is nothing to fill.

RandomKernelImpl computed grid_size from CeilDiv(N, block_size * UNROLL),
which is zero when the output tensor has no elements. The counter_offset
expression then divided by block_size * grid_size * UNROLL, a host-side
division by zero that traps before the kernel is launched. Zero-sized
tensors are legal in ONNX, so return early when there is nothing to fill.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a host-side divide-by-zero in the CUDA random generator implementation when producing zero-element outputs (legal in ONNX), by returning early before computing a zero grid_size and using it in counter_offset math.

Changes:

  • Add an N == 0 early-return guard in the CUDA RandomKernelImpl to avoid dividing by block_size * grid_size * UNROLL when grid_size == 0.
  • Add a CUDA-only unit test that exercises RandomNormal/RandomUniform with an empty output shape and expects successful execution.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
onnxruntime/core/providers/cuda/generator/random_impl.cu Adds an early return for N == 0 to prevent host-side division by zero before kernel launch.
onnxruntime/test/providers/cpu/generator/random_test.cc Adds a CUDA-gated test covering zero-sized output tensors for CUDA random ops.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@apsonawane
Akshay Sonawane (apsonawane) merged commit af28b01 into main Aug 13, 2026
96 of 97 checks passed
@apsonawane
Akshay Sonawane (apsonawane) deleted the fix/cuda-random-empty-tensor branch August 13, 2026 17:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants