warp icon indicating copy to clipboard operation
warp copied to clipboard

`tile_sort()` silently produces wrong results, or faults, for accepted `block_dim` values

Open christophercrouzet opened this issue 3 months ago • 4 comments

Bug Description

wp.tile_sort() accepts any block_dim that launch_tiled() accepts, but only a narrow set of values sorts correctly. Everything else either returns a mis-sorted tile with no diagnostic, or reads out of bounds and raises CUDA error 700.

The safe set is not simply "a power of two ≥ 32": block_dim=1024 is a power of two and faults, while block_dim=96 and 100 are not powers of two and happen to pass for small tiles. The boundary depends on which of the two sort implementations the tile size selects.

Repro

The repro checks the payload as well as the keys, so that a sort which orders the keys but scrambles the values cannot pass. (In the matrix below the two checks always agreed, but a keys-only assertion would not be sound.)

import numpy as np, warp as wp

DEVICE = "cuda:0"

def check(n, block_dim):
    @wp.kernel(module="unique")
    def sort_kernel(k: wp.array[wp.float32], v: wp.array[wp.int32]):
        keys = wp.tile_load(k, shape=n, storage="shared")
        vals = wp.tile_load(v, shape=n, storage="shared")
        wp.tile_sort(keys, vals)
        wp.tile_store(k, keys)
        wp.tile_store(v, vals)

    host_keys = np.random.default_rng(0).permutation(n).astype(np.float32)
    host_vals = np.arange(n, dtype=np.int32)
    k = wp.array(host_keys, dtype=wp.float32, device=DEVICE)
    v = wp.array(host_vals, dtype=wp.int32, device=DEVICE)

    wp.launch_tiled(sort_kernel, dim=1, inputs=[k, v], block_dim=block_dim, device=DEVICE)

    order = np.argsort(host_keys, kind="stable")
    print(f"N={n:<6} block_dim={block_dim:<5} "
          f"keys_sorted={np.array_equal(k.numpy(), host_keys[order])} "
          f"values_follow_keys={np.array_equal(v.numpy(), host_vals[order])}")

check(64, 16)     # also try (64, 48), (2100, 100), (2100, 96)

Run one configuration per process. (2100, 96) and (2100, 1024) fault, and a faulted CUDA context makes every later configuration in the same process fail too.

Observed

On cuda:0. ok = keys sorted and payload permuted to match; wrong = silently incorrect, no diagnostic; fault = Warp CUDA error 700: an illegal memory access was encountered.

block_dim 4 8 16 32 48 64 96 100 128 256 512 1024
N=8 wrong wrong wrong ok ok ok ok ok ok ok ok ok
N=32 wrong wrong wrong ok ok ok ok ok ok ok ok ok
N=64 wrong wrong wrong ok wrong ok ok ok ok ok ok ok
N=2100 wrong wrong wrong ok wrong ok fault wrong ok ok ok fault

Whenever the keys are wrong the payload is wrong too; no case produced sorted keys with a mismatched payload.

The same kernel sorts correctly on cpu for every block_dim, because launch_tiled() forces block_dim=1 there and the CPU path is serial.

Root cause

tile_sort() in warp/native/tile_radix_sort.h dispatches on tile size: at most BITONIC_SORT_THRESHOLD (2048) elements of a 32-bit type uses bitonic sort, anything larger uses radix_sort_thread_block_core(). The two paths fail differently, which is why the N=64 and N=2100 rows disagree.

Radix path (N > 2048) — safe only for block_dim in {32, 64, 128, 256, 512}

Two independent constraints inside radix_sort_thread_block_core(), with num_warps = ceil(block_dim / 32):

  1. The per-digit scan calls warp_scan_inclusive() with a full-warp mask (0xFFFFFFFF) and reads its result only from lane 31, so a partially populated warp never writes its bucket total and leaves shared_mem[warp_id][b] undefined. This requires block_dim % 32 == 0, and explains the wrong results at block_dim 48 and 100.

  2. The bucket accumulation loop runs to num_warp_passes * num_warps, where num_warp_passes = ceil(16 / num_warps), while buckets has exactly 16 entries. Whenever num_warps does not divide 16, or exceeds it, the product is greater than 16 and the loop writes past the array:

    • block_dim=96 → 3 warps → ceil(16/3) * 3 = 18 entries written into a 16-entry array.
    • block_dim=1024 → 32 warps → 1 * 32 = 32 entries.

    Both are the observed faults. num_warps ∈ {1, 2, 4, 8, 16} gives exactly 16 and is safe.

Together these leave block_dim ∈ {32, 64, 128, 256, 512} — the powers of two from 32 to 512.

Bitonic path (N <= 2048) — more permissive, and undefined outside multiples of 32

Tiles of fewer than 32 elements take a single-warp fast path in bitonic_sort_thread_block_direct(), guarded by if (thread_id < 32). With a smaller block_dim the missing lanes never participate and most of the tile is left unsorted — that is the N=8 row at block_dim 4/8/16.

Tiles of 32 or more elements go through bitonic_sort_pow2_length(), which strip-mines them over num_loops = ceil(N / block_dim) registers per thread and indexes the sort network by thread_id2 = loop_id * block_dim + thread_id, while the exchange itself is a physical warp shuffle in bitonic_sort_single_stage_full_warp(). The two agree only when thread_id2 ≡ thread_id (mod 32), which holds when block_dim is a multiple of 32, and degenerately when num_loops == 1 because then thread_id2 == thread_id. The lanes holding in-range indices must also form complete warps, or their shuffle partners are missing.

That is exactly the observed pattern. block_dim=16 fails from N=32 upward: two or more loops, and a 16-lane stride that breaks the congruence. block_dim=48 sorts N<=32 in one loop but fails N=64, where the second loop shifts by 48 and warp 1 holds only 16 lanes. block_dim=96 and 100 cover N=64 in a single loop, and every lane with an in-range index sits in warp 0 or 1, both full — so they come out correct. Those passes still issue __shfl_xor_sync(0xFFFFFFFFu, ...) from partially populated warps, so they are relying on undefined behavior rather than being supported — they are evidence that the "power of two ≥ 32" rule does not describe the real boundary, not a reason to allow those values.

Why CI does not catch it

test_tile_sort sweeps TILE_DIM = 2**j for j in range(5, 10), i.e. exactly 32, 64, 128, 256, 512 — the set that works. No test exercises a non-multiple of 32, or 1024.

Expected

Document the supported range as powers of two from 32 to 512 inclusive — the intersection of what both paths handle and what the tests cover — and reject anything else at launch or codegen rather than returning silently wrong data. Note that an open-ended "32, 64, 128, …" phrasing would be incorrect, since 1024 faults.

System Information

Warp 1.17.0.dev1 built from source at commit 79a147c.

NumPy:      2.5.0
Python:     3.12.12
Platform:   Linux-6.8.0-136-generic-x86_64-with-glibc2.35
CUDA:       Toolkit 12.9, Driver 12.4, NVRTC 12.9
GPU:        NVIDIA GeForce RTX 3090 Ti (sm_86)
CPU:        znver3

christophercrouzet avatar Aug 06 '26 23:08 christophercrouzet

I could take a look at this, I believe the best way to go would be to add this validation in the tile_sort_value_func in _src/builtins.py

block_dim = warp._src.codegen.options.get("block_dim", 1)
if block_dim not in (1,32,64,128,256,512):
   raise ValueError(f"Block Dimension must be one of (32, 64, 128, 256, 512) got {block_dim}")

Then add the corresponding test to on some of the failing block sizes in test_tile_sort.py

Ali-Nawed avatar Aug 09 '26 19:08 Ali-Nawed

Reproduced on warp 1.16.0, RTX 4070 Laptop, driver 596.47, one configuration per process with the payload check kept. The core report holds: accepted block_dim values return silently mis-sorted data, and one faults.

Two details came out differently here, and the safe set turns out to be describable. block_dim=1024 did not fault (correct at N=64), and 96 is correct at N=64 but faults at N=2100, which supports your point that the implementation chosen by tile size decides the outcome.

Bitonic path, N=64:

block_dim 16 32 48 64 80 96 128
wrong ok wrong ok ok ok ok

Radix path, N=2100:

block_dim 32 64 96 100 128 256
ok ok CUDA 700 wrong ok ok

The rule that fits every point, including N=128 (ok at 32, 64, 96, 128) and N=256 (ok at 32):

  • bitonic: correct when block_dim >= num_elements, or block_dim is a multiple of the 32-lane warp size. So 80 passes at N=64 with one element per thread, while 48 fails with two per thread and no warp alignment.
  • radix: correct when block_dim is a power of two. 96 is a clean 3 warps and still faults.

Why: bitonic_sort_pow2_length gives each thread ceil(max_num_elements / WP_TILE_BLOCK_DIM) elements strided by WP_TILE_BLOCK_DIM, then takes a fast path at stride <= 16 annotated "no inter-warp communication needed". That only holds while the element-to-thread mapping stays inside a warp, which with more than one element per thread requires WP_TILE_BLOCK_DIM to be a warp multiple. That is exactly where the failures land.

Both quantities are compile-time constants (num_elements_to_sort is constexpr, WP_TILE_BLOCK_DIM is a macro), so a static_assert per branch would replace the silent case with a compile-time error naming the valid values, without affecting anything that sorts correctly today. tile_sort_value_func sees only the tile shapes, so the same check is not reachable from Python.

wilyan09007 avatar Aug 09 '26 21:08 wilyan09007

Addressed in commits 1a1c9dc, 90c5bc4, and b4b7612.

christophercrouzet avatar Oct 20 '26 01:10 christophercrouzet

This is addressed by b4b761255b1b15a7fec82b8aac02cd9f253a00fa.

Together with 1a1c9dcbf2f07266a35251b743cb4dad8df171da and 90c5bc4d5c9c7a053ea8badb4ea7c9efa261b828, this fixes both failure mechanisms reported here: partial-warp blocks now sort through shared memory, and the radix histogram merge stays within its 16 buckets for warp counts that do not divide 16, including blocks of 96 and 1024 threads. The radix debug assertion also counts the final bucket correctly. Keys remain sorted with their corresponding payloads. This issue can remain closed as completed.

Public API behavior

The kernel builtin wp.tile_sort(keys, values) supports these previously failing block dimensions instead of rejecting them. Its documentation recommends CUDA block dimensions that are multiples of 32 for better performance; other launch-supported dimensions use a shared-memory fallback and may be slower. No new host-side Python API is introduced.

Test coverage

All three tests are in warp/tests/tile/test_tile_sort.py:

  • test_tile_sort_block_dim_multiple_of_32 checks keys and payloads at block dimensions 96, 160, 192, and 1024, covering 2,100-element float32/int32 radix sorts and a 65-element padded bitonic sort.
  • test_tile_sort_block_dim_not_multiple_of_32 checks block dimensions 1, 16, 33, 48, and 100 across small, power-of-two, padded, and radix-sized tiles, plus int64 keys.
  • test_tile_sort_same_tile_for_keys_and_values checks aliasing with the same tile used for keys and values at block dimensions 33, 48, and 64 for lengths 65 and 2100.

Behavioral verification

On the combined commit head, a targeted reproduction passed all 48 configurations in the report's CUDA matrix, checking both sorted keys and payload correspondence in a separate process for each configuration. Eight additional 2,100-element debug-mode checks and four CPU checks passed. The three added regression tests also passed on both available CUDA devices.

shi-eric avatar Oct 20 '26 16:10 shi-eric