Repository navigation
Conversation
…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
There was a problem hiding this comment.
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.
|
Thanks to @fengxie , the test caught a real bug: after a lazy call |
Thanks a lot. @brandon-yujie-sun @anakinxc can you take a second look? |
|
@tqchen as well. |
brandon-yujie-sun
left a comment
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
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:
CudaDialectJitCompiledFunction._load_cuda_libraryloopscuda_load_to_deviceoverrange(num_devices).cuda_load_to_deviceas the per-device callback ofcuda_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.
CudaDialectJitModulerecords the devices it is set up for. The executor checks the current device on each call (onecudaGetDeviceand a set lookup).fn.to(<device index>)sets that device up ahead of time, which gives the explicit binding the issue asks for.cuda_dialect_init_library_onceand callscuda_load_to_devicefor the device of the call, recorded in a per-module bitmask. The explicitmodule_initentry 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.CUTE_DSL_ENABLE_TVM_FFI=1dump_to_object, with and withoutmodule_inittest/python/CuTeDSLcudaErrorInvalidDeviceFunctionon both paths, so the lazy setup is what applies the attributes.test/python/CuTeDSL/test_multi_gpu_first_launch.pycovers the repro and the per-device attributes for both paths. It needs two GPUs and PyTorch, and skips otherwise.Notes for review
cuda_dialect_init_library_onceskipping 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.cuda_load_to_devicein the TVM-FFI path. This assumes it is safe to repeat.export_to_c.