Skip to content

[CuTeDSL] Set the CUDA library up per device on first use, not for all devices - #3929

Open
yunweili3 wants to merge 3 commits into
NVIDIA:mainfrom
yunweili3:fix-3928-lazy-per-device-load
Open

yunweili3 wants to merge 3 commits into
NVIDIA:mainfrom
yunweili3:fix-3928-lazy-per-device-load

Conversation

@yunweili3

Copy link
Copy Markdown
Contributor

Fixes #3928.

Problem

The first launch of a compiled kernel sets the CUDA library up for every visible device, not only the one it runs on. Per-device setup (cuda_load_to_device) applies device scoped kernel attributes, and that driver call (cuKernelSetAttribute) waits while the device is running a kernel. So a first launch on GPU 1 waits for GPU 0, and deadlocks when the kernel on GPU 0 is waiting for GPU 1.

Both paths reach the all-device loop from the Python in this repo:

  • JIT: CudaDialectJitCompiledFunction._load_cuda_library loops cuda_load_to_device over range(num_devices).
  • TVM-FFI (JIT and exported objects): the entry passes cuda_load_to_device as the per-device callback of cuda_dialect_init_library_once, which runs the same loop in the runtime.

Measured on 2x B200 while GPU 0 runs a kernel: setup for GPU 1 returns in 0.34 ms, setup for GPU 0 blocks until that kernel ends.

Change

Only the library handle is created up front. Each device is set up on the first call that runs on it.

  • JIT: CudaDialectJitModule records the devices it is set up for. The executor checks the current device on each call (one cudaGetDevice and a set lookup). fn.to(<device index>) sets that device up ahead of time, which gives the explicit binding the issue asks for.
  • TVM-FFI: the entry passes no callback to cuda_dialect_init_library_once and calls cuda_load_to_device for the device of the call, recorded in a per-module bitmask. The explicit module_init entry still sets up every device.

Testing

2x B200, driver 590.48, nvidia-cutlass-dsl[cu13] 4.9.0.dev1 with these two files replaced, Python 3.10.

Check Before After
Repro from #3928, JIT DEADLOCK PASS (10/10)
Repro from #3928, CUTE_DSL_ENABLE_TVM_FFI=1 DEADLOCK PASS (10/10)
Kernel with 100 KB dynamic smem on both GPUs (serial, 8 threads, either order) PASS PASS
Same kernel from dump_to_object, with and without module_init not run PASS
Unload, then call again on both GPUs not run PASS
test/python/CuTeDSL 8 failed, 30 passed 8 failed, 30 passed
  • With the per-device setup disabled, the 100 KB kernel fails with cudaErrorInvalidDeviceFunction on both paths, so the lazy setup is what applies the attributes.
  • Per-call cost: +0.3 to 0.6 us on the JIT path (about 8 us per call before); within noise on TVM-FFI.
  • New test/python/CuTeDSL/test_multi_gpu_first_launch.py covers the repro and the per-device attributes for both paths. It needs two GPUs and PyTorch, and skips otherwise.

Notes for review

  • The TVM-FFI part relies on cuda_dialect_init_library_once skipping its device loop for a null callback. I observed this, I have no source for it. If you would rather change the runtime, the JIT part stands on its own.
  • Two threads entering the same device for the first time may both call cuda_load_to_device in the TVM-FFI path. This assumes it is safe to repeat.
  • A first launch on a device that is itself busy still waits. This change does not affect that.
  • Not tested: H200, driver 580, free-threaded Python, more than two GPUs, export_to_c.

…l devices

The first launch of a compiled kernel set the library up for every visible
device: _load_cuda_library looped cuda_load_to_device over all devices, and
the TVM-FFI entries handed the same loop to cuda_dialect_init_library_once.
cuda_load_to_device sets device scoped kernel attributes, which makes the
driver load the module into that device's context and wait for the work
already running there. So the first launch on one GPU waited for all other
GPUs, and deadlocked when a kernel on another GPU was waiting for it.

Now only the library handle is created up front and each device is set up
on the first call that runs on it:
- JIT: CudaDialectJitModule tracks the devices it is set up for; the
  executor checks the current device on each call (one cudaGetDevice and a
  set lookup). to(device) with an index sets that device up ahead of time.
- TVM-FFI (JIT and exported objects): the entries pass no per-device
  callback to cuda_dialect_init_library_once and call cuda_load_to_device
  for the device they run on, recorded in a per-module bitmask. The explicit
  module_init entry still sets up every device.

Fixes NVIDIA#3928

@fengxie fengxie left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks a lot for fixing.

How about adding following test (by Gemini Neon 4) and verify if it still works?

import os
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
 
import cutlass
import cutlass.cute as cute
import torch
from cuda.bindings import driver as cu
from cutlass.cute.runtime import from_dlpack
 
 
@cute.kernel
def _smem100k_kernel(out: cute.Tensor, val: cutlass.Int32) -> None:
    tid, _, _ = cute.arch.thread_idx()
    if tid == 0:
        out[0] = val
 
 
@cute.jit
def _smem100k_host(out: cute.Tensor, val: cutlass.Int32, stream: cu.CUstream) -> None:
    _smem100k_kernel(out, val).launch(
        grid=(1, 1, 1), block=(32, 1, 1), smem=100 * 1024, stream=stream
    )
 
 
@unittest.skipUnless(torch.cuda.device_count() >= 2, "needs >= 2 GPUs")
class TestPR3929Regressions(unittest.TestCase):
    def test_1_tvm_ffi_module_init_after_lazy_call_sets_up_other_device(self) -> None:
        """entry(gpu0) -> module_init() -> entry(gpu1) must set up GPU 1."""
        import tvm_ffi
 
        s0 = torch.cuda.Stream(device="cuda:0")
        s1 = torch.cuda.Stream(device="cuda:1")
        o0 = torch.zeros(4, dtype=torch.int32, device="cuda:0")
        o1 = torch.zeros(4, dtype=torch.int32, device="cuda:1")
 
        torch.cuda.set_device(0)
        fn = cute.compile(
            _smem100k_host,
            from_dlpack(o0, enable_tvm_ffi=True),
            0,
            cu.CUstream(s0.cuda_stream),
            options="--enable-tvm-ffi",
        )
 
        with tempfile.TemporaryDirectory() as tmp:
            obj = os.path.join(tmp, "k100.o")
            so = os.path.join(tmp, "k100.so")
            Path(obj).write_bytes(fn.dump_to_object("host100"))
            rt_lib = os.environ["CUTE_DSL_RUNTIME_LIB"]  # libcute_dsl_runtime.so
            subprocess.check_call(
                ["g++", "-shared", "-o", so, obj, rt_lib, f"-Wl,-rpath,{os.path.dirname(rt_lib)}"]
            )
            mod = tvm_ffi.load_module(so)
            entry = mod.get_function("host100")
            mod_init = mod.get_function("module_init")
 
            # 1. Lazy call on GPU 0 initializes *libraryPtr (null callback) and sets bit 0.
            torch.cuda.set_device(0)
            entry(o0, 41, s0.cuda_stream)
            s0.synchronize()
            self.assertEqual(int(o0[0].item()), 41)
 
            # 2. Explicit module_init() after lazy init must not mark GPU 1 loaded
            #    without running cuda_load_to_device(1).
            mod_init()
 
            # 3. Call on GPU 1 requires the 100 KB dynamic smem attribute on GPU 1.
            torch.cuda.set_device(1)
            entry(o1, 42, s1.cuda_stream)
            s1.synchronize()
            self.assertEqual(int(o1[0].item()), 42)

…call

cuda_dialect_init_library_once does nothing once the library handle exists,
so a module_init() that followed a lazy call marked every device as set up
without running cuda_load_to_device for them, and the next call on another
device was launched without its device scoped attributes.

module_init now loops over the visible devices and sets up the ones not set
up yet; the library handle is always created without the per-device callback.
@yunweili3

yunweili3 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks to @fengxie , the test caught a real bug: after a lazy call cuda_dialect_init_library_once is a no-op, but module_init still marked every device as set up, so GPU 1 never got its attributes. Fixed in 37183b9: module_init now loops over the visible devices itself and sets up the ones not done yet. Your test fails on 57d4245 and passes now; I added it to test_multi_gpu_first_launch.py for both orders (module_init first / lazy call first).

@fengxie

fengxie commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Thanks to @fengxie , the test caught a real bug: after a lazy call cuda_dialect_init_library_once is a no-op, but module_init still marked every device as set up, so GPU 1 never got its attributes. Fixed in 37183b9: module_init now loops over the visible devices itself and sets up the ones not done yet. Your test fails on 57d4245 and passes now; I added it to test_multi_gpu_first_launch.py for both orders (module_init first / lazy call first).

Thanks a lot. @brandon-yujie-sun @anakinxc can you take a second look?

@fengxie

fengxie commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

@tqchen as well.

@brandon-yujie-sun brandon-yujie-sun left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for contributing the codes. I've dropped some comments.

"""
if self._load_to_device is None or device in self._loaded_devices:
return
with self._device_lock:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we have per device lock instead of per module? With this lock, seems it would introduce unnecessary wait between devices. Consider the case that A is calling compiled_kernel on GPU0 for the first time and holding the lock, while B is calling the same compiled_kernel on GPU1 for the first time too - will B get blocked on this which seems unnecessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, B would be blocked, and it gets worse than a wait when the kernel running on GPU 0 is itself waiting for B: I added that scenario as a test (test_first_launch_does_not_wait_for_first_launch_on_other_device) and it deadlocks on the previous commit.

Fixed in 7831dbf: one lock per device. The load closure also shared one device_id / err slot between calls, which is not safe once two devices can be set up at the same time, so those are now allocated per call.

)
return current_block

def load_cuda_to_all_devices(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not sure this is equivalent to the base impl? I think the base impl tolerates the GPU failures unless all GPUs failed while this version seems to bail out as long as one fails?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are right, it was not equivalent: cuda_dialect_init_library_once only fails when every device fails (and reports the last error), while this loop stopped at the first failing device.

Fixed in 7831dbf: module_init now keeps going, counts the failures and raises only when all devices failed, with the last error. A device that failed is not recorded in the mask, so a later call that actually runs on it retries the setup and raises there.

Checked by making _cudaKernelSetAttributeForDevice fail for chosen devices (2 GPUs): one device failing -> module_init succeeds, calls on the other device work, a call on the failed device raises; both failing -> module_init raises.

JIT path: the lazy per-device setup took one lock per module, so a first
call waiting for a busy device held back the first call of the same
function on any other device. Use one lock per device, and per-call
device/error slots so that devices can be set up at the same time.

TVM-FFI path: module_init stopped at the first device that could not be
set up. cuda_dialect_init_library_once only fails when every device
fails, and reports the last error; do the same. A device that failed is
not recorded, so a call that runs on it retries and reports the error.

This branch has not been deployed

No deployments
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.

[BUG] CuTe DSL first-launch kernel initialization loads onto all visible GPUs, causing multi-GPU deadlocks and stalls

3 participants