Skip to content

Fix strided_scan reading/writing out-of-bounds - #4430

Open
zcbenz wants to merge 2 commits into
ml-explore:mainfrom
zcbenz:strided-scan-bounds
Open

Fix strided_scan reading/writing out-of-bounds#4430
zcbenz wants to merge 2 commits into
ml-explore:mainfrom
zcbenz:strided-scan-bounds

Conversation

@zcbenz

@zcbenz zcbenz commented Aug 30, 2026

Copy link
Copy Markdown
Member

The GPU strided_scan kernels can read/write out-of-bounds when the scanned axis is a slice. The test is from #4254.

Note that this is only a correctness fix, and does not try to optimize the mentioned case which currently has most of the threads wasted. At the moment I'm conservative on complicating the kernel for a crafted edge case.

The strided scan kernel writes out[i * stride + j] for i < shape[axis] and
j < stride, so it needs shape[axis] * stride elements. Scan::eval_gpu sized
the output with in.data_size() while handing the kernel in.strides(), so a
size one axis carrying a padded stride, as a sliced view has, made the kernel
write past its allocation. Take the no copy path only when the scanned axis
fits and let the rest fall to the existing contiguous copy. The CUDA scan has
the same dispatch and the same kernel bound, so it changes too.
@TheDarkchip

Copy link
Copy Markdown
Contributor

Hi, the pointer forming here is UB (https://eel.is/c++draft/expr.add) ffor lanes where the result points beyond the position immediately after the buffer.

in += offset + global_index_x + read_offset_x;
out += offset + global_index_x + read_offset_x;

This is only pointer-formation UB, as the later guard correctly prevents the pointers from being dereferenced.

@zcbenz

zcbenz commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

We don't quite care about undefined behaviors when writing GPU kernels, and UB is often abused when we can get a performance gain. Out-of-bound pointers are especially common in GPU kernels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants