warp icon indicating copy to clipboard operation
warp copied to clipboard

[REQ] Enhance ease of use for grid-stride loop

Open lmtss opened this issue 8 months ago • 9 comments

Description

  • Provide an interface similar to cudaOccupancyMaxActiveBlocksPerMultiprocessor to facilitate max_blocks estimation
  • Add an option to disable the grid-stride loop

Context

I noticed that the grid-stride loop is used by default in cuda_kernel_template_forward. I have a basic understanding of its benefits, but I've encountered some issues:

  • The grid-stride loop is enabled by default, but in cases where I'm certain it's unnecessary, disabling it could provide a slight performance improvement (possibly due to better register usage).
  • It's not trivial to estimate an appropriate max_blocks value — I typically need to use tools like Nsight Compute to determine how many blocks can run on an SM before arriving at the final max_blocks setting.
  • The grid-stride loop uses size_t (64-bit integer), which may introduce unnecessary 64-bit arithmetic in some cases.

lmtss avatar Mar 05 '26 09:03 lmtss

Thanks for the ideas, I'll do some exploring and see what we can do for you.

shi-eric avatar Mar 06 '26 00:03 shi-eric

Hi @lmtss, thanks for the detailed issue. We've been investigating the performance impact of both wp.tid() and the grid-stride loop. These are two separate concerns, so I'll address them individually.

1. Grid-stride loop overhead

We prototyped a grid_stride=False kernel option that replaces the for-loop with a simple if-guard:

@wp.kernel(grid_stride=False)
def my_kernel(out: wp.array(dtype=float)):
    i = wp.tid()
    out[i] = float(i)

On trivial microbenchmarks (CUDA graph replay, Blackwell), the if-guard is consistently ~1.5–2.5% faster than the for-loop. On real workloads (mujoco_warp), we saw up to ~5% throughput improvement on benchmarks that launch many small kernels per step, though many cases showed negligible gains — the benefit scales inversely with how much actual work each kernel does.

Since the grid-stride loop only matters when max_blocks constrains the grid (the default is effectively unlimited), disabling it for the common case is a clean win with no functional downside.

That said, if your workload is dominated by many small kernels, the best optimization advice is to try to fuse them into fewer, larger kernels where possible — that eliminates not just the grid-stride overhead but also launch overhead, memory traffic from intermediates, etc. The grid_stride=False option helps at the margin, but kernel fusion is where the real wins are.

2. wp.tid() cost (coordinate decomposition)

For multi-dimensional launches, wp.tid() unravels a linear thread index into (i, j, k, ...) coordinates using a chain of modulo/division operations. We investigated several optimizations:

Template-specialized bounds — using launch_bounds_t<N> templated on the number of dimensions, so the compiler eliminates dead branches (e.g., a 2D kernel never evaluates the 3D/4D code paths). This gave ~2–8% improvement on trivial microbenchmarks, particularly for 1D kernels where all division is eliminated.

32-bit arithmetic — the division chain currently operates on size_t (64-bit). Casting to int enables native 32-bit hardware division, but silently produces incorrect results when total threads exceed 2^31 (~2.1 billion). On Blackwell, the benefit over template specialization alone was marginal — native 64-bit integer division appears efficient on this architecture. The benefit may be more significant on older architectures.

Fast division (multiply-high + shift) — replacing hardware division with int_fastdiv (Hacker's Delight algorithm). On Blackwell, this was actually slower than native division due to more instructions and higher register pressure, confirming your intuition about register pressure concerns.

Questions

To help us prioritize, it would be helpful to know more about your use case:

  1. What are typical kernel sizes in your workload (number of threads, dimensionality)? The overhead from both the grid-stride loop and wp.tid() is most pronounced on very lightweight kernels.
  2. Is there potential in your workload to fuse multiple small kernels into fewer larger ones? That would likely yield bigger gains than any of the optimizations discussed here.
  3. Have you observed the register pressure issue with specific kernels? If you have ncu profiles showing elevated register counts, that would help us understand the magnitude.
  4. What GPU architecture(s) are you targeting?

adenzler-nvidia avatar Mar 12 '26 16:03 adenzler-nvidia

Hi @adenzler-nvidia , thanks for the deep dive and detailed write-up — really appreciate the investigation and data!

  1. The total thread count is often large enough that a single wave can't cover all tasks (based on the "wave per SM" metric in ncu reports) — which is why I'm interested in the grid‑stride loop.
  2. Thanks for the suggestion! You're absolutely right — there's definitely room for kernel fusion in the overall pipeline. The reason I'm digging into the grid-stride overhead for this particular issue is that I'm currently profiling a specific kernel that accounts for ~40% of the total runtime, so every little bit helps. Still, I'll keep fusion in mind for broader optimizations!
  3. I did a quick test removing the grid-stride loop and wp.tid(). The ncu showed registers per thread dropped from 56 to 48, and the block limit registers increased from 9 to 10, yielding a small performance gain.
  4. No specific architecture constraints, but based on typical usage, these kernels run on RTX 30/40/50 series cards.

Report

Below are the relevant reports with and without the grid-stride loop and wp.tid() calls:
(windows, RTX3070)

// with the grid-stride loop and `wp.tid()`
Section: Launch Statistics
    -------------------------------- --------------- ---------------
    Metric Name                          Metric Unit    Metric Value
    -------------------------------- --------------- ---------------
    Block Size                                                   128
    Function Cache Configuration                     CachePreferNone
    Grid Size                                                    512
    Registers Per Thread             register/thread              56
    Shared Memory Configuration Size           Kbyte           32.77
    Driver Shared Memory Per Block       Kbyte/block            1.02
    Dynamic Shared Memory Per Block       byte/block               0
    Static Shared Memory Per Block        byte/block             512
    # SMs                                         SM              46
    Threads                                   thread          65,536
    Uses Green Context                                             0
    Waves Per SM                                                1.24
    -------------------------------- --------------- ---------------

 Section: Occupancy
    ------------------------------- ----------- ------------
    Metric Name                     Metric Unit Metric Value
    ------------------------------- ----------- ------------
    Block Limit SM                        block           16
    Block Limit Registers                 block            9
    Block Limit Shared Mem                block           21
    Block Limit Warps                     block           12
    Theoretical Active Warps per SM        warp           36
    Theoretical Occupancy                     %           75
    Achieved Occupancy                        %        57.46
    Achieved Active Warps Per SM           warp        27.58
    ------------------------------- ----------- ------------
// without
Section: Launch Statistics
  -------------------------------- --------------- ---------------
  Metric Name                          Metric Unit    Metric Value
  -------------------------------- --------------- ---------------
  Block Size                                                   128
  Function Cache Configuration                     CachePreferNone
  Grid Size                                                    512
  Registers Per Thread             register/thread              48
  Shared Memory Configuration Size           Kbyte           32.77
  Driver Shared Memory Per Block       Kbyte/block            1.02
  Dynamic Shared Memory Per Block       byte/block               0
  Static Shared Memory Per Block        byte/block             512
  # SMs                                         SM              46
  Threads                                   thread          65,536
  Uses Green Context                                             0
  Waves Per SM                                                1.11
  -------------------------------- --------------- ---------------

 Section: Occupancy
  ------------------------------- ----------- ------------
  Metric Name                     Metric Unit Metric Value
  ------------------------------- ----------- ------------
  Block Limit SM                        block           16
  Block Limit Registers                 block           10
  Block Limit Shared Mem                block           21
  Block Limit Warps                     block           12
  Theoretical Active Warps per SM        warp           40
  Theoretical Occupancy                     %        83.33
  Achieved Occupancy                        %        69.06
  Achieved Active Warps Per SM           warp        33.15
  ------------------------------- ----------- ------------

lmtss avatar Mar 12 '26 17:03 lmtss

FYI, I just added 4e1620ec3dc6623eeb8e8c3ef7a139f2cb9031ad which exposes a wp.get_suggested_block_size()

shi-eric avatar Apr 01 '26 16:04 shi-eric

FYI, I just added 4e1620e which exposes a wp.get_suggested_block_size()

Thank you, that looks exactly like what I need.

lmtss avatar Apr 03 '26 07:04 lmtss

Update: @adenzler-nvidia's templated launch_bounds_t<N> optimization landed on main in b7d4843 and will ship in the next Warp release. This addresses the wp.tid() coordinate-decomposition cost that came up in the discussion above. The two items in the original description are in different states: wp.get_suggested_block_size() (4e1620e) covers the occupancy query ask, but the grid_stride=False kernel option @adenzler-nvidia prototyped earlier is still pending and not in this commit.

What b7d4843 changes

  • launch_bounds_t is now templated on the kernel's dimensionality (launch_bounds_t<N>), with shape[N] and a bool tiled field replacing the old fixed shape[4] plus runtime ndim.
  • launch_coord() and wp.tid() use if constexpr on N, so the compiler eliminates unused dimension branches. 1D kernels no longer pay for 4D unraveling, and higher-D kernels drop the branches they don't need.
  • Kernel dimensionality is inferred at Adjoint init time via a lightweight AST scan of wp.tid() calls (_infer_kernel_dim()), so it's correct even on warm-cache loads where build() is skipped.
  • A _normalize_launch_dim() helper reshapes user-supplied dim to match the inferred kernel dim at all bounds-construction sites (including the JAX FFI path), so existing call sites keep working (e.g. wp.launch(kernel_2d, dim=N) normalizes to (N, 1)).
  • For tiled launches, the tiled flag lets launch_coord divide out block_dim() before unraveling.
  • CPU JIT now compiles with -std=c++17 (needed for if constexpr), matching build_dll.py and NVRTC.
  • 30 new tests in warp/tests/test_template_launch_bounds.py.

Expected impact matches the microbenchmarks @adenzler-nvidia shared earlier in this thread: roughly 2-8% on trivial kernels, with the largest wins on 1D launches where all division is eliminated, plus reduced register pressure on multi-D kernels.

One complication worth flagging

Technically a breaking change for kernels that unpacked fewer wp.tid() return values than the launch dimensionality. Previously, i = wp.tid() inside a kernel launched with dim=(3, 3) would unravel to give the first-dim index (yielding 0, 0, 0, 1, 1, 1, 2, 2, 2). With the new inference, the kernel is treated as 1D and you get the flattened linear index (0, 1, ..., 8). Worth noting that this is actually a return to the pre-v1.5.0 behavior: before the tile-programming merge (1f19a2f) in 1.5.0, the 1-argument tid() didn't take launch bounds at all and simply returned the linear thread index. The v1.5.0 change silently altered that, and b7d4843 restores it for the 1-return-value case. To preserve the 1.5.0-1.11.x behavior, unpack all dimensions and discard the ones you don't need (e.g. i, _ = wp.tid()). This is documented in the Unreleased CHANGELOG entry.

shi-eric avatar Apr 22 '26 06:04 shi-eric

Quick follow-up: the templated launch_bounds_t<N> work from this issue has been reverted on main for the 1.13.0 RC. This isn't a rejection of the approach. The perf win is real, and the alternative MR also cleanly unified the tiled-launch case with the regular one. But the revert also touched wp.tid() semantics (flatten vs alias vs strict, and whether tiled/non-tiled launches should behave the same), and we want more time to discuss the full picture before committing.

The broader wp.tid() semantics concerns are being tracked in #1389. Open questions include:

  • Regular wp.launch with arity mismatch: silent alias (pre-1.13) vs silent flatten (1.13 pre-revert) vs hard error vs warn.
  • wp.launch_tiled with arity mismatch: same question, possibly with a different answer.
  • Deprecation path / configuration option for users relying on older or newer semantics.
  • Downstream impact on C++ consumers of generated kernel signatures (launch_bounds_t ABI and the calling convention change from the APIC work in #1349).

Context: newton-physics/newton#2546 was the trigger. We'll regroup on #1389 post-release and aim to pull pieces of the existing branches into 1.14.

shi-eric avatar Apr 24 '26 07:04 shi-eric

Update: Alain's templated launch-bounds work has landed on main again in ea56dc161349f5be9d7b5c7124ee8418d9874d52.

This reinstates the launch_bounds_t<N> approach for wp.tid() coordinate decomposition, but with behavior-preserving compatibility work. In particular, extra launch dimensions are folded into coord_mult so existing launch-dimension aliasing behavior is preserved, including tiled launches, while lower-dimensional kernels can still compile away unused launch-coordinate branches.

Together with 4e1620ec3dc6623eeb8e8c3ef7a139f2cb9031ad, which added wp.get_suggested_block_size() for CUDA occupancy queries, two parts of this issue have now been addressed.

The grid-stride loop option remains separate from this change and is still under consideration.

shi-eric avatar May 20 '26 00:05 shi-eric

Progress update: 78b81d628e7c6999b5bb35487a195c21c3868d4b landed an opt-in lean CUDA launch path for kernels compiled without the grid-stride loop.

The change keeps grid-stride as the default, so existing kernels continue to support max_blocks capping. Users can opt out with @wp.kernel(grid_stride=False), the "default_grid_stride" module option, or wp.config.default_grid_stride = False. Lean kernels use a 3D CUDA grid without the grid-stride loop; max_blocks > 0 remains unsupported for lean CUDA kernels and now raises an actionable error pointing back to grid-stride.

Together with the earlier wp.get_suggested_block_size() update already discussed above, this appears to cover the original asks. Since this issue was filed externally, leaving it open for @lmtss to verify on their workload before closing.

Public API behavior:

  • Python scope: @wp.kernel(grid_stride=False) opts a kernel into the lean launch path. The module "default_grid_stride" option and wp.config.default_grid_stride provide broader defaults, with explicit per-kernel settings taking precedence.
  • Kernel scope: no new Warp kernel builtins were added. Generated CUDA kernels now choose either the existing grid-stride template or the lean 3D-grid template based on the resolved grid_stride value.

Test coverage:

  • New tests: warp/tests/test_large.py covers lean launch success, max_blocks rejection, large lean launch dimensions, Launch.set_dim(), zero-dimension recorded launches, default-grid-stride behavior, and CPU max_blocks no-op behavior.
  • New tests: warp/tests/test_codegen.py::TestCodeGen.test_grid_stride_precedence covers precedence and frozen build-time resolution.
  • New tests: warp/tests/test_unique_module.py::TestUniqueModule.test_unique_module_generic_kernel_options_disambiguation covers distinct hashing for kernels that differ only by per-kernel options.
  • New/modified tests: warp/tests/cuda/test_cluster_dim.py covers clustered kernels on both grid-stride and lean launch paths, including a zero-dimension recorded clustered lean launch.

shi-eric avatar Jun 26 '26 05:06 shi-eric