diff --git a/python/CuTeDSL/cutlass/cutlass_dsl/cuda_jit_executor.py b/python/CuTeDSL/cutlass/cutlass_dsl/cuda_jit_executor.py index 01d295f698..ff1b98d59d 100644 --- a/python/CuTeDSL/cutlass/cutlass_dsl/cuda_jit_executor.py +++ b/python/CuTeDSL/cutlass/cutlass_dsl/cuda_jit_executor.py @@ -19,7 +19,7 @@ import sys import weakref import threading -from typing import Any, List, Optional, Tuple, Union +from typing import Any, Callable, List, Optional, Tuple, Union import cuda.bindings.runtime as cuda_runtime import cuda.bindings.driver as cuda_driver @@ -45,6 +45,10 @@ from .._mlir import ir, execution_engine +_cudaGetDevice = cuda_runtime.cudaGetDevice +_CUDA_SUCCESS = cuda_runtime.cudaError_t.cudaSuccess + + class CudaDialectJitModule: """Holds the execution engine and cuda libraries.""" @@ -54,12 +58,47 @@ def __init__( capi_func: Any, execution_args: ExecutionArgs, cuda_library: list["cuda_runtime.cudaLibrary_t"], + load_to_device: Optional[Callable[[int], None]] = None, ) -> None: self.engine = engine self.capi_func = capi_func self.execution_args = execution_args self.cuda_library = cuda_library self._unloaded = False + # Per-device kernel setup (kernel lookup + device scoped attributes) is + # done lazily, only for the devices this module actually runs on. + self._load_to_device = load_to_device + self._loaded_devices: set[int] = set() + # One lock per device, so that a setup waiting for one device does not + # hold back the first call under another one. + self._device_locks: dict[int, threading.Lock] = {} + self._device_locks_guard = threading.Lock() + + def load_to_device(self, device: int) -> None: + """Resolves the kernels and applies device scoped attributes for ``device``. + + Idempotent and thread safe. Only ``device`` is touched: setting a + device scoped attribute makes the driver load the module into that + device's context, which waits for work already running there, so it + must not be done for devices this module is not about to run on. For + the same reason the setups of different devices do not wait for each + other. + """ + if self._load_to_device is None or device in self._loaded_devices: + return + with self._device_locks_guard: + device_lock = self._device_locks.setdefault(device, threading.Lock()) + with device_lock: + if device in self._loaded_devices: + return + self._load_to_device(device) + self._loaded_devices.add(device) + + def load_to_current_device(self) -> None: + """Calls :meth:`load_to_device` for the calling thread's current device.""" + if self._load_to_device is None: + return + self.load_to_device(checkCudaErrors(cuda_runtime.cudaGetDevice())) def is_unloaded(self) -> bool: return self._unloaded @@ -85,6 +124,30 @@ def __del__(self) -> None: self.unload() +class CudaDialectJitExecutor(JitExecutor): + """A :class:`JitExecutor` for a CUDA library, which is context free. + + The same executor may be called under any device. The device scoped part of + the library setup is done on the first call under each device. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + # Host only modules have nothing to set up per device. + self._per_device_setup = ( + getattr(self.jit_module, "_load_to_device", None) is not None + ) + + def run_compiled_program(self, exe_args: list[Any]) -> int | None: + # This is on the launch path: one cudaGetDevice and one set lookup when + # the device is already set up. + if self._per_device_setup: + err, device = _cudaGetDevice() + if err != _CUDA_SUCCESS or device not in self.jit_module._loaded_devices: + self.jit_module.load_to_current_device() + return super().run_compiled_program(exe_args) + + class CudaDialectJitCompiledFunction(JitCompiledFunction): """Holds a compiled function and its module.""" @@ -253,8 +316,16 @@ def _get_cuda_init_and_load(self) -> Tuple[Any, Any]: return cuda_init, cuda_load_to_device - def _load_cuda_library(self) -> List["cuda_runtime.cudaLibrary_t"]: - """Loads the CUDA library from the engine.""" + def _load_cuda_library( + self, + ) -> Tuple[List["cuda_runtime.cudaLibrary_t"], Callable[[int], None]]: + """Loads the CUDA library from the engine. + + Returns the library and a function that finishes the setup for one + device (see :meth:`CudaDialectJitModule.load_to_device`). No device is + set up here: with several visible devices, doing so for all of them + makes the first call wait for the work running on every other device. + """ cuda_init, cuda_load_to_device = self._get_cuda_init_and_load() @@ -272,26 +343,24 @@ def _load_cuda_library(self) -> List["cuda_runtime.cudaLibrary_t"]: checkCudaErrors((cuda_runtime.cudaError_t(err.value),)) - device_id = ctypes.c_int32(0) - pointer_to_device_id = ctypes.pointer(device_id) - - cuda_load_args: List[Any] = [ - pointer_to_pointer_to_library, - pointer_to_device_id, - pointer_to_err, - ] - packed_args = (ctypes.c_void_p * len(cuda_load_args))() - for i, arg in enumerate(cuda_load_args): - packed_args[i] = ctypes.cast(arg, ctypes.c_void_p) - - for dev in range(self.num_devices): - device_id.value = dev - cuda_load_to_device(packed_args) - checkCudaErrors((cuda_runtime.cudaError_t(err.value),)) - - checkCudaErrors((cuda_runtime.cudaError_t(err.value),)) - - return [cuda_runtime.cudaLibrary_t(library.value)] + # The closure keeps the library handle and the engine function alive. + # The device and error slots are per call: different devices may be set + # up at the same time. + def load_to_device(dev: int) -> None: + device_id = ctypes.c_int32(dev) + load_err = ctypes.c_int32(0) + cuda_load_args: List[Any] = [ + pointer_to_pointer_to_library, + ctypes.pointer(device_id), + ctypes.pointer(load_err), + ] + packed_load_args = (ctypes.c_void_p * len(cuda_load_args))() + for i, arg in enumerate(cuda_load_args): + packed_load_args[i] = ctypes.cast(arg, ctypes.c_void_p) + cuda_load_to_device(packed_load_args) + checkCudaErrors((cuda_runtime.cudaError_t(load_err.value),)) + + return [cuda_runtime.cudaLibrary_t(library.value)], load_to_device def to(self, device: Optional[int] = None) -> JitExecutor: """Returns an executable function bound to the given device. @@ -300,10 +369,13 @@ def to(self, device: Optional[int] = None) -> JitExecutor: the kernel will run. Since CudaJitCompiledFunction uses CUDA libraries, which are context free, - binding to a device is not necessary and the device is ignored. Device is - kept in for compatibility with the JitCompiledFunction. + the returned executor is not bound to a device. The device scoped part of + the library setup is done once per device: here for ``device`` when it is + given as an index, otherwise on the first call under each device. Pass the + index to pay that cost ahead of the first launch on that device. - :param device: Specifies the device for the executor. If None the current device is used. + :param device: Device index to set the library up for now. If None, each + device is set up on the first call under it. :type device: Optional[Union[int, CUdevice]] :return: A callable executor function. :rtype: JitExecutor @@ -315,17 +387,25 @@ def to(self, device: Optional[int] = None) -> JitExecutor: isinstance(self.jit_module, CudaDialectJitModule) and self.jit_module.is_unloaded() ): - cuda_library = self._load_cuda_library() if self.has_gpu_module else [] + cuda_library, load_to_device = ( + self._load_cuda_library() if self.has_gpu_module else ([], None) + ) self.jit_module = CudaDialectJitModule( self.engine, self.capi_func, self.execution_args, cuda_library, + load_to_device, ) + if isinstance(device, int) and isinstance( + self.jit_module, CudaDialectJitModule + ): + self.jit_module.load_to_device(device) + # F-SPEC: the derived executor validates re-entries against the # same sealed record as the handle it came from. - return JitExecutor( + return CudaDialectJitExecutor( self.jit_module, None, self.jit_time_profiling, spec=self._pyir_spec ) diff --git a/python/CuTeDSL/cutlass/cutlass_dsl/tvm_ffi_provider.py b/python/CuTeDSL/cutlass/cutlass_dsl/tvm_ffi_provider.py index 1086398ed2..26efd613b0 100644 --- a/python/CuTeDSL/cutlass/cutlass_dsl/tvm_ffi_provider.py +++ b/python/CuTeDSL/cutlass/cutlass_dsl/tvm_ffi_provider.py @@ -470,6 +470,9 @@ class TVMFFICuteCallProvider(DynamicParamPackCallProvider): def __init__(self, target_func: str, has_gpu_module: bool = True): super().__init__(target_func, struct_call=True) self.cuda_global_state_symbol = f"__{target_func}_cuda_state" + # Bit d is set once the library is set up for device d (see + # ensure_cuda_loaded_to_device). + self.cuda_loaded_devices_symbol = f"__{target_func}_cuda_loaded_devices" self.cuda_device_index = None self.cuda_error_handle_block = None self.has_gpu_module = has_gpu_module @@ -539,6 +542,11 @@ def declare_extern_funcs( [self.ptr_type], self.i32_type, ) + context.builder.find_or_declare_extern_func( + "_cudaGetDeviceCount", + [self.ptr_type], + self.i32_type, + ) context.builder.find_or_declare_extern_func( "_cudaSetDevice", [self.i32_type], @@ -570,24 +578,37 @@ def declare_cuda_module_state(self, context: CallContext) -> None: """Declare the CUDA library handle shared by all TVM-FFI entries.""" assert context.builder is not None with ir.InsertionPoint(context.module.body): - parsed_op = ir.Operation.parse( - f"llvm.mlir.global private @{self.cuda_global_state_symbol}(0 : i64) : i64" - ) - context.module.body.append(parsed_op) + for symbol in ( + self.cuda_global_state_symbol, + self.cuda_loaded_devices_symbol, + ): + parsed_op = ir.Operation.parse( + f"llvm.mlir.global private @{symbol}(0 : i64) : i64" + ) + context.module.body.append(parsed_op) def call_cuda_module_initializer( self, current_block: ir.Block, context: CallContext ) -> ir.Block: - """Initialize the shared CUDA library state, returning the success block.""" + """Initialize the shared CUDA library state, returning the success block. + + Only the library handle is created here. The devices are set up + separately, since ``cuda_dialect_init_library_once`` does nothing once + the handle exists: each entry sets up the device it is about to run on + (``ensure_cuda_loaded_to_device``) and the explicit, eager + ``module_init`` sets up all of them (``load_cuda_to_all_devices``). + Setting a device up waits for the work already running on it, so a call + must not do it for other devices. + """ assert context.builder is not None with ir.InsertionPoint(current_block): cuda_global_state_ptr = self.address_of( self.cuda_global_state_symbol, self.ptr_type ) cuda_init_ptr = self.address_of("cuda_init", self.ptr_type) - cuda_load_to_device_ptr = self.address_of( - "cuda_load_to_device", self.ptr_type - ) + # No per-device callback: cuda_dialect_init_library_once then only + # loads the library. + cuda_load_to_device_ptr = llvm.inttoptr(self.ptr_type, self.i64(0)) set_error_ptr = self.address_of( "TVMFFIErrorSetRaisedFromCStr", self.ptr_type ) @@ -626,6 +647,176 @@ def insert_lazy_init_cuda( self.declare_cuda_module_state(context) return self.call_cuda_module_initializer(current_block, context) + def _cuda_device_bit(self, device: ir.Value) -> ir.Value: + """Bit of ``device`` (an i32 index) in the loaded-devices mask, 0 past bit 63.""" + device_i64 = llvm.zext(self.i64_type, device) + in_range = llvm.icmp(llvm.ICmpPredicate.ult, device_i64, self.i64(64)) + return llvm.select( + in_range, + llvm.shl(self.i64(1), self.and_(device_i64, self.i64(63)), 0), + self.i64(0), + ) + + def _call_cuda_load_to_device(self, device: ir.Value) -> ir.Value: + """Call ``cuda_load_to_device`` for ``device``, returning its error code.""" + return llvm.call( + result=self.i32_type, + callee="cuda_load_to_device", + callee_operands=[ + self.address_of(self.cuda_global_state_symbol, self.ptr_type), + device, + ], + op_bundle_sizes=[], + op_bundle_operands=[], + ) + + def _mark_cuda_device_loaded(self, device_bit: ir.Value) -> None: + """Record a device in the loaded-devices mask.""" + llvm.atomicrmw( + llvm.AtomicBinOp._or, + self.address_of(self.cuda_loaded_devices_symbol, self.ptr_type), + device_bit, + llvm.AtomicOrdering.seq_cst, + ) + + def load_cuda_to_all_devices( + self, current_block: ir.Block, context: CallContext + ) -> ir.Block: + """Set the library up for every visible device not set up yet. + + As in ``cuda_dialect_init_library_once``, a device that cannot be set + up does not fail the initialization: it is an error only when no device + could be set up, and the last error is then reported. A device that + failed here is not recorded, so a call that runs on it retries the + setup and reports the error itself. + """ + assert context.builder is not None + device_count_alloca = context.builder.create_alloca( + context.entry_block, self.i32_type, array_size=1 + ) + device_alloca = context.builder.create_alloca( + context.entry_block, self.i32_type, array_size=1 + ) + failed_count_alloca = context.builder.create_alloca( + context.entry_block, self.i32_type, array_size=1 + ) + last_error_alloca = context.builder.create_alloca( + context.entry_block, self.i32_type, array_size=1 + ) + with ir.InsertionPoint(current_block): + result = llvm.call( + result=self.i32_type, + callee="_cudaGetDeviceCount", + callee_operands=[device_count_alloca], + op_bundle_sizes=[], + op_bundle_operands=[], + ) + current_block = self.check_cuda_error(result, current_block, context) + + header_block = current_block.create_after() + check_block = header_block.create_after() + load_block = check_block.create_after() + loaded_block = load_block.create_after() + failed_block = loaded_block.create_after() + next_block = failed_block.create_after() + done_block = next_block.create_after() + with ir.InsertionPoint(current_block): + device_count = llvm.load(self.i32_type, device_count_alloca) + llvm.store(value=self.i32(0), addr=device_alloca) + llvm.store(value=self.i32(0), addr=failed_count_alloca) + llvm.store(value=self.i32(0), addr=last_error_alloca) + self.br(header_block) + + with ir.InsertionPoint(header_block): + device = llvm.load(self.i32_type, device_alloca) + self.cond_br( + cond=llvm.icmp(llvm.ICmpPredicate.slt, device, device_count), + true_block=check_block, + false_block=done_block, + ) + + with ir.InsertionPoint(check_block): + loaded = llvm.load( + self.i64_type, + self.address_of(self.cuda_loaded_devices_symbol, self.ptr_type), + ) + device_bit = self._cuda_device_bit(device) + self.cond_br( + cond=self.not_equal(self.and_(loaded, device_bit), self.i64(0)), + true_block=next_block, + false_block=load_block, + ) + + with ir.InsertionPoint(load_block): + result = self._call_cuda_load_to_device(device) + self.cond_br( + cond=self.equal(result, self.i32(0)), + true_block=loaded_block, + false_block=failed_block, + branch_weights=self.BRANCH_WEIGHTS_LIKELY, + ) + + with ir.InsertionPoint(loaded_block): + self._mark_cuda_device_loaded(device_bit) + self.br(next_block) + + with ir.InsertionPoint(failed_block): + failed_count = llvm.load(self.i32_type, failed_count_alloca) + llvm.store( + value=llvm.add(failed_count, self.i32(1), 0), + addr=failed_count_alloca, + ) + llvm.store(value=result, addr=last_error_alloca) + self.br(next_block) + + with ir.InsertionPoint(next_block): + llvm.store(value=llvm.add(device, self.i32(1), 0), addr=device_alloca) + self.br(header_block) + + # Devices set up earlier by a call are skipped above and count as set + # up, so this is an error only when every device failed. + with ir.InsertionPoint(done_block): + all_failed = self.equal( + llvm.load(self.i32_type, failed_count_alloca), device_count + ) + error = llvm.select( + all_failed, llvm.load(self.i32_type, last_error_alloca), self.i32(0) + ) + return self.check_cuda_error(error, done_block, context) + + def ensure_cuda_loaded_to_device( + self, current_block: ir.Block, context: CallContext, device: ir.Value + ) -> ir.Block: + """Set the library up for ``device`` (an i32 index) unless already done. + + ``cuda_load_to_device`` resolves the kernels and applies the device scoped + attributes; it is idempotent, so two threads racing here only repeat it. + Devices past bit 63 are not recorded and are set up on every call. + """ + with ir.InsertionPoint(current_block): + loaded = llvm.load( + self.i64_type, + self.address_of(self.cuda_loaded_devices_symbol, self.ptr_type), + ) + device_bit = self._cuda_device_bit(device) + load_block = current_block.create_after() + continuation_block = load_block.create_after() + self.cond_br( + cond=self.not_equal(self.and_(loaded, device_bit), self.i64(0)), + true_block=continuation_block, + false_block=load_block, + branch_weights=self.BRANCH_WEIGHTS_LIKELY, + ) + + with ir.InsertionPoint(load_block): + result = self._call_cuda_load_to_device(device) + load_block = self.check_cuda_error(result, load_block, context) + with ir.InsertionPoint(load_block): + self._mark_cuda_device_loaded(device_bit) + self.br(continuation_block) + + return continuation_block + def attach_module_initializer(self, module: ir.Module) -> None: """Expose controlled eager initialization through a TVM-FFI safe call.""" if not self.has_gpu_module: @@ -670,6 +861,11 @@ def attach_module_initializer(self, module: ir.Module) -> None: ["Expects 0 parameters when calling: `module_init()`"], ) current_block = self.call_cuda_module_initializer(current_block, context) + self.cuda_error_handle_block = self.create_shared_cuda_error_block( + current_block, context + ) + current_block = self.load_cuda_to_all_devices(current_block, context) + self.cuda_error_handle_block = None with ir.InsertionPoint(current_block): fields = ( @@ -834,9 +1030,11 @@ def generate_llvm_call( """Generate the LLVM call operation and check if the call is successful.""" assert context.builder is not None old_cuda_device_index: Optional[ir.Value] = None + current_cuda_device_index: Optional[ir.Value] = None - # If we need to manage CUDA device context - if self.cuda_device_index is not None: + # The current device is needed to manage the CUDA device context, and to + # know which device the kernels are about to run on. + if self.cuda_device_index is not None or self.has_gpu_module: # Create an alloca in the entry block to store the current device index device_index_alloca = context.builder.create_alloca( context.entry_block, self.i32_type, array_size=1 @@ -857,7 +1055,26 @@ def generate_llvm_call( # Load the current device index from the alloca with ir.InsertionPoint(current_block): - old_cuda_device_index = llvm.load(self.i32_type, device_index_alloca) + current_cuda_device_index = llvm.load( + self.i32_type, device_index_alloca + ) + + # Set the library up for the device the call runs on, and only for it. + # Done before the device switch so that an error leaves nothing to restore. + if self.has_gpu_module: + target_device = ( + self.cuda_device_index + if self.cuda_device_index is not None + else current_cuda_device_index + ) + assert target_device is not None + current_block = self.ensure_cuda_loaded_to_device( + current_block, context, target_device + ) + + # If we need to manage CUDA device context + if self.cuda_device_index is not None: + old_cuda_device_index = current_cuda_device_index # Switch to target device if different current_block = self.set_cuda_device_if_mismatch( diff --git a/test/python/CuTeDSL/test_multi_gpu_first_launch.py b/test/python/CuTeDSL/test_multi_gpu_first_launch.py new file mode 100644 index 0000000000..96334f9828 --- /dev/null +++ b/test/python/CuTeDSL/test_multi_gpu_first_launch.py @@ -0,0 +1,314 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-NvidiaProprietary +# +# Use of this software is governed by the terms and conditions of the +# NVIDIA End User License Agreement (EULA), available at: +# https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/license.html +# +# Any use, reproduction, disclosure, or distribution of this software +# and related documentation outside the scope permitted by the EULA +# is strictly prohibited. + +""" +The first launch of a compiled kernel must set the CUDA library up only for +the device it runs on. + +Setting a device up (the device scoped kernel attributes) makes the driver +load the module into that device's context, which waits for the work already +running there. Doing it for every visible device makes the first launch on one +GPU wait for all the others, and deadlocks when a kernel on another GPU is +itself waiting for that launch (NVIDIA/cutlass#3928). + +Each scenario runs in a subprocess: a regression leaves a thread blocked in +the driver, which only a process exit clears. Needs two GPUs and PyTorch. +""" + +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import unittest + +try: + import torch + + _NUM_GPUS = torch.cuda.device_count() +except Exception: # pragma: no cover - PyTorch is optional for this suite + _NUM_GPUS = 0 + +_COMMON = """ +import os, sys, threading, time +import cutlass, cutlass.cute as cute, torch +from cuda.bindings import driver as cu +from cutlass.cute.runtime import from_dlpack +""" + +# GPU 0 runs a kernel that spins until the first launch on GPU 1 returned. +_BUSY_OTHER_DEVICE = _COMMON + """ +@cute.kernel +def spin_kernel(flag: cute.Tensor) -> None: + tid, _, _ = cute.arch.thread_idx() + if tid == 0: + while cute.arch.load(flag.iterator, cutlass.Int32, sem="acquire", scope="sys") == 0: + pass + +@cute.jit +def spin_host(flag: cute.Tensor, stream: cu.CUstream) -> None: + spin_kernel(flag).launch(grid=(1, 1, 1), block=(1, 1, 1), stream=stream) + +@cute.kernel +def noop_kernel() -> None: + pass + +@cute.jit +def noop_host(stream: cu.CUstream) -> None: + noop_kernel().launch(grid=(1, 1, 1), block=(1, 1, 1), stream=stream) + +s0, s1 = torch.cuda.Stream(device="cuda:0"), torch.cuda.Stream(device="cuda:1") +cu_s0, cu_s1 = cu.CUstream(s0.cuda_stream), cu.CUstream(s1.cuda_stream) +flag = torch.ones(1, dtype=torch.int32, pin_memory=True) +flag_cute = from_dlpack(flag) +torch.cuda.set_device(0) +spin_fn = cute.compile(spin_host, flag_cute, cu_s0) +spin_fn(flag_cute, cu_s0) +s0.synchronize() +noop_fn = cute.compile(noop_host, cu_s1) + +flag[0] = 0 +spinning, done = threading.Event(), threading.Event() + +def gpu0() -> None: + torch.cuda.set_device(0) + spin_fn(flag_cute, cu_s0) + time.sleep(0.15) + spinning.set() + s0.synchronize() + +def gpu1() -> None: + spinning.wait() + torch.cuda.set_device(1) + noop_fn(cu_s1) # first launch of this kernel, on GPU 1, while GPU 0 is busy + flag[0] = 1 + s1.synchronize() + done.set() + +threading.Thread(target=gpu0, daemon=True).start() +threading.Thread(target=gpu1, daemon=True).start() +ok = done.wait(timeout=20.0) +print("PASS" if ok else "DEADLOCK", flush=True) +os._exit(0 if ok else 1) +""" + +# GPU 0 is busy, and one thread is already waiting in the first launch of a +# kernel on it. The first launch of the same kernel on GPU 1 must not wait for +# that thread. +_BUSY_FIRST_LAUNCH_ON_OTHER_DEVICE = _COMMON + """ +@cute.kernel +def spin_kernel(flag: cute.Tensor) -> None: + tid, _, _ = cute.arch.thread_idx() + if tid == 0: + while cute.arch.load(flag.iterator, cutlass.Int32, sem="acquire", scope="sys") == 0: + pass + +@cute.jit +def spin_host(flag: cute.Tensor, stream: cu.CUstream) -> None: + spin_kernel(flag).launch(grid=(1, 1, 1), block=(1, 1, 1), stream=stream) + +@cute.kernel +def noop_kernel() -> None: + pass + +@cute.jit +def noop_host(stream: cu.CUstream) -> None: + noop_kernel().launch(grid=(1, 1, 1), block=(1, 1, 1), stream=stream) + +s0, s1 = torch.cuda.Stream(device="cuda:0"), torch.cuda.Stream(device="cuda:1") +cu_s0, cu_s1 = cu.CUstream(s0.cuda_stream), cu.CUstream(s1.cuda_stream) +flag = torch.ones(1, dtype=torch.int32, pin_memory=True) +flag_cute = from_dlpack(flag) +torch.cuda.set_device(0) +spin_fn = cute.compile(spin_host, flag_cute, cu_s0) +spin_fn(flag_cute, cu_s0) +s0.synchronize() +noop_fn = cute.compile(noop_host, cu_s1) + +flag[0] = 0 +spinning, done = threading.Event(), threading.Event() + +def gpu0() -> None: + torch.cuda.set_device(0) + spin_fn(flag_cute, cu_s0) + time.sleep(0.15) + spinning.set() + noop_fn(cu_s0) # first launch on GPU 0: waits for the spinning kernel + s0.synchronize() + +def gpu1() -> None: + spinning.wait() + time.sleep(1.0) # let the other thread get into its first launch + torch.cuda.set_device(1) + noop_fn(cu_s1) # first launch of the same kernel, on GPU 1 + flag[0] = 1 + s1.synchronize() + done.set() + +threading.Thread(target=gpu0, daemon=True).start() +threading.Thread(target=gpu1, daemon=True).start() +ok = done.wait(timeout=20.0) +print("PASS" if ok else "DEADLOCK", flush=True) +os._exit(0 if ok else 1) +""" + +# 100 KB of dynamic shared memory is above the default limit: the launch needs +# the max-dynamic-shared-memory attribute set for the device it runs on. +_ATTRIBUTES_ON_EVERY_DEVICE = _COMMON + """ +@cute.kernel +def k(out: cute.Tensor, val: cutlass.Int32) -> None: + tid, _, _ = cute.arch.thread_idx() + if tid == 0: + out[0] = val + +@cute.jit +def host(out: cute.Tensor, val: cutlass.Int32, stream: cu.CUstream) -> None: + k(out, val).launch(grid=(1, 1, 1), block=(32, 1, 1), smem=100 * 1024, stream=stream) + +order = [int(d) for d in sys.argv[1].split(",")] +outs = [torch.zeros(4, dtype=torch.int32, device=f"cuda:{d}") for d in range(2)] +streams = [torch.cuda.Stream(device=f"cuda:{d}") for d in range(2)] +torch.cuda.set_device(0) +fn = cute.compile(host, from_dlpack(outs[0]), 0, cu.CUstream(streams[0].cuda_stream)) + +def run(d: int) -> None: + torch.cuda.set_device(d) + fn(from_dlpack(outs[d]), 41 + d, cu.CUstream(streams[d].cuda_stream)) + streams[d].synchronize() + +for _ in range(2): + threads = [threading.Thread(target=run, args=(d,)) for d in order for _ in range(4)] + [t.start() for t in threads] + [t.join() for t in threads] +got = [int(o[0].item()) for o in outs] +ok = got == [41, 42] +print("PASS" if ok else f"FAIL {got}", flush=True) +os._exit(0 if ok else 1) +""" + +# An explicit module_init() after a lazy call on GPU 0 finds the library already +# loaded; it must still set GPU 1 up before the entry stops doing it itself. +_MODULE_INIT_AFTER_LAZY_CALL = _COMMON + """ +import subprocess, tempfile +import tvm_ffi +from cutlass.runtime import find_runtime_libraries + +@cute.kernel +def k(out: cute.Tensor, val: cutlass.Int32) -> None: + tid, _, _ = cute.arch.thread_idx() + if tid == 0: + out[0] = val + +@cute.jit +def host(out: cute.Tensor, val: cutlass.Int32, stream: cu.CUstream) -> None: + k(out, val).launch(grid=(1, 1, 1), block=(32, 1, 1), smem=100 * 1024, stream=stream) + +outs = [torch.zeros(4, dtype=torch.int32, device=f"cuda:{d}") for d in range(2)] +streams = [torch.cuda.Stream(device=f"cuda:{d}") for d in range(2)] +torch.cuda.set_device(0) +fn = cute.compile( + host, + from_dlpack(outs[0], enable_tvm_ffi=True), + 0, + cu.CUstream(streams[0].cuda_stream), + options="--enable-tvm-ffi", +) + +def run(entry, d: int) -> None: + torch.cuda.set_device(d) + entry(outs[d], 41 + d, streams[d].cuda_stream) + streams[d].synchronize() + +with tempfile.TemporaryDirectory() as tmp: + obj, so = os.path.join(tmp, "host.o"), os.path.join(tmp, "host.so") + with open(obj, "wb") as f: + f.write(fn.dump_to_object("host")) + libs = find_runtime_libraries(enable_tvm_ffi=True) + rpaths = [f"-Wl,-rpath,{os.path.dirname(lib)}" for lib in libs] + subprocess.check_call(["g++", "-shared", "-o", so, obj, *libs, *rpaths]) + mod = tvm_ffi.load_module(so) + entry = mod.get_function("host") + if sys.argv[1] == "lazy_first": + run(entry, 0) + mod.get_function("module_init")() + run(entry, 1) + run(entry, 0) +got = [int(o[0].item()) for o in outs] +ok = got == [41, 42] +print("PASS" if ok else f"FAIL {got}", flush=True) +os._exit(0 if ok else 1) +""" + + +def _run(script: str, *args: str, tvm_ffi: bool) -> subprocess.CompletedProcess: + env = dict(os.environ) + env.pop("CUTE_DSL_ENABLE_TVM_FFI", None) + if tvm_ffi: + env["CUTE_DSL_ENABLE_TVM_FFI"] = "1" + # The DSL compiles from source, so the scenario has to live in a file. + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "scenario.py") + with open(path, "w") as f: + f.write(textwrap.dedent(script)) + return subprocess.run( + [sys.executable, path, *args], + env=env, + capture_output=True, + text=True, + timeout=300, + ) + + +def _has_tvm_ffi() -> bool: + try: + import tvm_ffi # noqa: F401 + except Exception: + return False + return True + + +@unittest.skipUnless(_NUM_GPUS >= 2, "needs two GPUs and PyTorch") +class TestMultiGpuFirstLaunch(unittest.TestCase): + def _check(self, script: str, *args: str, tvm_ffi: bool) -> None: + if tvm_ffi and not _has_tvm_ffi(): + self.skipTest("apache-tvm-ffi is not installed") + result = _run(script, *args, tvm_ffi=tvm_ffi) + self.assertEqual( + result.returncode, 0, msg=(result.stdout + result.stderr)[-2000:] + ) + + def test_first_launch_does_not_wait_for_other_device(self) -> None: + for tvm_ffi in (False, True): + with self.subTest(tvm_ffi=tvm_ffi): + self._check(_BUSY_OTHER_DEVICE, tvm_ffi=tvm_ffi) + + def test_first_launch_does_not_wait_for_first_launch_on_other_device(self) -> None: + for tvm_ffi in (False, True): + with self.subTest(tvm_ffi=tvm_ffi): + self._check(_BUSY_FIRST_LAUNCH_ON_OTHER_DEVICE, tvm_ffi=tvm_ffi) + + def test_device_attributes_set_on_every_device(self) -> None: + for tvm_ffi in (False, True): + for order in ("0,1", "1,0"): + with self.subTest(tvm_ffi=tvm_ffi, order=order): + self._check(_ATTRIBUTES_ON_EVERY_DEVICE, order, tvm_ffi=tvm_ffi) + + def test_module_init_sets_up_every_device(self) -> None: + if shutil.which("g++") is None: + self.skipTest("g++ is not available") + for order in ("init_first", "lazy_first"): + with self.subTest(order=order): + self._check(_MODULE_INIT_AFTER_LAZY_CALL, order, tvm_ffi=True) + + +if __name__ == "__main__": + unittest.main()