diff --git a/pyproject.toml b/pyproject.toml index a9daac3da0..b030c80eb7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -444,6 +444,7 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } +dace = { git = "https://github.com/spcl/dace", branch = "new-gpu-codegen-dev" } # -- versioningit -- [tool.versioningit] diff --git a/src/gt4py/cartesian/backend/dace_backend.py b/src/gt4py/cartesian/backend/dace_backend.py index 68f75f6515..d0e51cd854 100644 --- a/src/gt4py/cartesian/backend/dace_backend.py +++ b/src/gt4py/cartesian/backend/dace_backend.py @@ -538,11 +538,65 @@ class DaCeComputationCodegen: auto allocator = gt::sid::cached_allocator(&${allocator}); ${"\\n".join(tmp_allocs)} __program_${name}(${",".join(["&dace_handle", *dace_args])}); + ${gpu_context_check} }; } """ ) + # The GPU state of a DaCe program lives in a `dace::cuda::Context` owned by the state struct. + # DaCe normally creates it in `__dace_init_()`, which this wrapper does not call (it + # allocates the state struct on the stack and calls `__program_()` directly), so the + # wrapper creates the context itself. All streams are the default (null) stream, matching + # `max_concurrent_streams = -1`; events are created only if the generated code requests any. + gpu_context_template = as_mako( + """\ +dace::cuda::Context gpu_context(${num_streams}, ${num_events}); +for (int i = 0; i < ${num_streams}; ++i) { + gpu_context.internal_streams[i] = nullptr; + gpu_context.streams[i] = nullptr; +} +for (int i = 0; i < ${num_events}; ++i) { + ${gpu_api}EventCreateWithFlags(&gpu_context.events[i], ${gpu_api}EventDisableTiming); +} +dace_handle.gpu_context = &gpu_context; +""" + ) + + gpu_context_check_template = as_mako( + """\ +for (int i = 0; i < ${num_events}; ++i) { + ${gpu_api}EventDestroy(gpu_context.events[i]); +} +if (gpu_context.lasterror != (gpuError_t)0) { + throw std::runtime_error( + std::string("GPU error in DaCe program '${name}': ") + + gpuGetErrorString(gpu_context.lasterror)); +} +""" + ) + + _GPU_CONTEXT_REGEX = re.compile(r"new\s+dace::cuda::Context\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)") + + @classmethod + def _gpu_context_size(cls, code_objects: list[codeobject.CodeObject]) -> tuple[int, int]: + """Return the number of streams and events of the GPU context DaCe generated code expects. + + Args: + code_objects: Code objects generated by DaCe for a GPU SDFG. + + Returns: + A `(num_streams, num_events)` tuple, as passed to `dace::cuda::Context` in the + generated initialization code. + + Raises: + RuntimeError: If the generated code does not create a GPU context. + """ + for co in code_objects: + if match := cls._GPU_CONTEXT_REGEX.search(co.clean_code): + return int(match.group(1)), int(match.group(2)) + raise RuntimeError("DaCe generated GPU code does not create a 'dace::cuda::Context'.") + def generate_tmp_allocs(self, sdfg: SDFG) -> list[str]: global_fmt = ( "__{sdfg_id}_{name} = allocate(allocator, gt::meta::lazy::id<{dtype}>(), {size})();" @@ -624,6 +678,7 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: # changes be under the temporary_config manager if core_defs.CUPY_DEVICE_TYPE == core_defs.DeviceType.ROCM: config.Config.set("compiler", "cuda", "backend", value="hip") + config.Config.set("compiler", "cuda", "implementation", value="experimental") config.Config.set("compiler", "cuda", "max_concurrent_streams", value=-1) config.Config.set( "compiler", @@ -660,9 +715,22 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: omp_threads = "" omp_header = "" + backend_specifics = omp_threads + gpu_context_check = "" + if is_gpu: + num_streams, num_events = cls._gpu_context_size(code_objects) + gpu_api = "hip" if core_defs.CUPY_DEVICE_TYPE == core_defs.DeviceType.ROCM else "cuda" + backend_specifics = cls.gpu_context_template.definition.render( + num_streams=num_streams, num_events=num_events, gpu_api=gpu_api + ) + gpu_context_check = cls.gpu_context_check_template.definition.render( + name=sdfg.name, num_events=num_events, gpu_api=gpu_api + ) + interface = cls.template.definition.render( name=sdfg.name, - backend_specifics=omp_threads, + backend_specifics=backend_specifics, + gpu_context_check=gpu_context_check, dace_args=self.generate_dace_args(builder.gtir, sdfg), functor_args=self.generate_functor_args(sdfg), tmp_allocs=self.generate_tmp_allocs(sdfg), @@ -674,7 +742,7 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: #include #include #include -{"#include " if is_gpu else omp_header} +{"#include \n#include \n#include " if is_gpu else omp_header} namespace gt = gridtools; {computations} diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index 2665354f91..3cd89e9964 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -24,15 +24,18 @@ @dataclasses.dataclass(frozen=True) class DaCeBackend(backend.Backend[Any]): - """DaCe backend with support for injecting an external workspace at load time.""" + """DaCe backend with support for injecting an external workspace and GPU stream at load time.""" external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: program = super().load_artifact(artifact) assert isinstance(program, gtx_wfddecoration.DaCeDecoratedProgram) # Inject the backend-level workspace so it is used when arguments are constructed. program.set_external_workspace(self.external_workspace or {}) + # Inject the backend-level GPU stream, it is passed as argument to the SDFG. + program.set_external_gpu_stream(self.external_gpu_stream) return program @@ -70,6 +73,7 @@ def make_dace_toolchain( allocator=cfg.make_allocator(), transforms=backend.DEFAULT_TRANSFORMS, external_workspace=cfg.external_workspace, + external_gpu_stream=cfg.external_gpu_stream, ) @@ -77,8 +81,9 @@ def make_dace_backend( gpu: bool, *, auto_optimize: bool = True, - async_sdfg_call: bool = True, + sync_sdfg_call: bool = False, optimization_args: dict[str, Any] | None = None, + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None, external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None, unstructured_horizontal_has_unit_stride: bool = config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE, use_metrics: bool = True, @@ -95,11 +100,18 @@ def make_dace_backend( Args: gpu: Enable GPU transformations and code generation. auto_optimize: Enable the SDFG auto-optimize pipeline. - async_sdfg_call: Make an asynchronous SDFG call on GPU to allow overlapping - of GPU kernel execution with the Python driver code. + sync_sdfg_call: Force a synchronous SDFG call on GPU, instead of allowing + the GPU kernel execution to overlap with the Python driver code. optimization_args: A `dict` containing configuration parameters for the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. It also accepts the scan-fusion options `fuse_scan_inputs` and `scan_fusion_scope`. + external_gpu_stream: An external GPU stream to be used for the SDFG call, + which allows to synchronize the execution of GPU kernels with external + workload and to share the stream memory pool. It can be the pointer + value of the stream, as an integer, or a stream object such as + `cupy.cuda.Stream`, see `GPUStreamHandle`. The stream handle is passed + to the SDFG at runtime, on the first call, thus it does not affect the + generated code. If not provided, the default stream is used. external_workspace: Workspace memory externally allocated, which is used for SDFG's transient arrays when `transient_memory_mode` is `EXTERNAL`. unstructured_horizontal_has_unit_stride: When the memory layout has unit stride @@ -133,12 +145,13 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, + external_gpu_stream=external_gpu_stream, unstructured_horizontal_has_unit_stride=unstructured_horizontal_has_unit_stride, ), translation=functools.partial( gtx_wfdfactory.make_dace_translator, auto_optimize_args=optimization_args, - async_sdfg_call=async_sdfg_call, + sync_sdfg_call=sync_sdfg_call, use_metrics=use_metrics, disable_field_origin_on_program_arguments=use_zero_origin, use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 1e9cbb65fd..cae4ef28d5 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -11,6 +11,7 @@ from typing import Any, Final, Generator, Optional, TypeAlias import dace +from typing_extensions import Protocol, runtime_checkable from gt4py._core import definitions as core_defs from gt4py.eve import xtyping @@ -34,6 +35,14 @@ """DaCe datatype of `SDFG_ARG_METRIC_COMPUTE_TIME` argument.""" +SDFG_ARG_EXTERNAL_GPU_STREAM: Final[str] = "gt_external_gpu_stream" +"""Name of SDFG argument to input an external GPU stream to GT4Py.""" + + +SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE: Final[dace.dtypes.typeclass] = dace.int64 +"""DaCe datatype of `SDFG_ARG_EXTERNAL_GPU_STREAM` argument, see `GPUStreamHandle`.""" + + ExternalWorkspace: TypeAlias = dict[ core_defs.DeviceType, xtyping.ArrayInterface | xtyping.CUDAArrayInterface ] @@ -45,6 +54,59 @@ """ +@runtime_checkable +class GPUStream(Protocol): + """A GPU stream object that exposes its handle, for example `cupy.cuda.Stream`.""" + + @property + def ptr(self) -> int: + """The pointer value of the stream (`cudaStream_t` or `hipStream_t`).""" + ... + + def __hash__(self) -> int: + return self.ptr + + +GPUStreamHandle: TypeAlias = int | GPUStream +""" Handle of a GPU stream (`cudaStream_t` or `hipStream_t`). + + Either the pointer value of the stream as an integer, or a stream object that + exposes it as the `ptr` attribute, for example `cupy.cuda.Stream`. It is passed + to the SDFG at runtime as an integer, see `SDFG_ARG_EXTERNAL_GPU_STREAM` and + `get_gpu_stream_ptr()`. +""" + + +DEFAULT_GPU_STREAM: Final[int] = 0 +"""The pointer value of the default GPU stream, i.e. `nullptr`.""" + + +def get_gpu_stream_ptr(stream: GPUStreamHandle | None) -> int: + """Return the pointer value of a GPU stream, as an integer. + + Args: + stream: The GPU stream handle. `None` selects the default stream. + + Returns: + The pointer value of the stream, `DEFAULT_GPU_STREAM` for the default stream. + + Raises: + TypeError: If `stream` is neither an integer nor a stream object that exposes + the `ptr` attribute. + """ + if stream is None: + return DEFAULT_GPU_STREAM + # NOTE: `bool` is a subclass of `int`, but it is not a valid stream handle. + if isinstance(stream, int) and not isinstance(stream, bool): + return stream + if isinstance(stream, GPUStream) and isinstance(stream.ptr, int): + return stream.ptr + raise TypeError( + f"Invalid GPU stream: should be of type 'int' or a stream object with an integer " + f"'ptr' attribute, for example 'cupy.cuda.Stream', got '{type(stream).__name__}'." + ) + + def set_dace_config( device_type: core_defs.DeviceType, cmake_build_type: Optional[gtx_config.CMakeBuildType] = None, @@ -138,14 +200,27 @@ def set_dace_config( # In some stencils, for example `apply_diffusion_to_w`, the cuda codegen messes # up with the cuda streams, i.e. it allocates N streams but uses N+1. The first # idea was to use just one stream. However, even in that case the generator - # generated wrong code. The current approach is to use the default stream, i.e. - # setting `max_concurrent_streams` to `-1`. However, the draw back is, that - # apparently then all synchronization is disabled, even the one at the very - # end of the SDFG call. To correct for that we are using either - # `make_sdfg_call_sync()` or `make_sdfg_call_async()`, see there or in - # [DaCe issue#2120](https://github.com/spcl/dace/issues/2120) for more. + # generated wrong code. The current approach is to use a single stream, i.e. + # setting `max_concurrent_streams` to `-1`. With the experimental CUDA codegen + # (see below), all GPU work is then scheduled on the streams stored in + # `__state->gpu_context->streams`, which are all set to the same stream: the + # default stream or an external stream, see `add_external_gpu_stream_arg()`. + # The synchronization at the end of the SDFG call is controlled by gt4py, see + # `make_sdfg_call_sync()` and [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). dace.Config.set("compiler.cuda.max_concurrent_streams", value=-1) + # Use the experimental CUDA codegen: unlike the legacy one, it launches kernels + # and copies on the streams stored in `__state->gpu_context->streams`, even + # when `max_concurrent_streams` is `-1`. This allows to replace the default + # stream with an external stream, see `add_external_gpu_stream_arg()`. + dace.Config.set("compiler.cuda.implementation", value="experimental") + + # The experimental CUDA codegen synchronizes the GPU streams at the end of + # the SDFG by default, which makes the SDFG call synchronous. We disable it + # because, when a synchronous call is requested, gt4py adds the stream + # synchronization itself, see `make_sdfg_call_sync()`. + dace.Config.set("compiler.cuda.synchronize_on_exit", value=False) + # This assumes that a process will only use one type of GPU. if device_type == core_defs.DeviceType.ROCM: dace.Config.set("compiler.cuda.backend", value="hip") diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 57f45964ce..a6de2d6168 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -34,7 +34,9 @@ class DaCeDecoratedProgram: program. External workspace memory (when the SDFG uses ``TransientMemoryMode.EXTERNAL``) is installed onto the underlying ``CompiledDaceProgram`` before the first call via `set_external_workspace`; - its lifetime is owned by the caller, not by this wrapper. + its lifetime is owned by the caller, not by this wrapper. Similarly, an external + GPU stream can be set before the first call via `set_external_gpu_stream`; it + is passed as argument to the SDFG and applied on SDFG initialization. """ def __init__( @@ -43,6 +45,7 @@ def __init__( device_type: core_defs.DeviceType = core_defs.DeviceType.CPU, ) -> None: self._fun = fun + self._external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None # Retrieve metrics level from GT4Py environment variable. self._collect_time = metrics.is_level_enabled(metrics.PERFORMANCE) self._collect_time_arg = np.array( @@ -85,6 +88,10 @@ def __call__( gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL: metrics.get_current_level(), gtx_wfdcommon.SDFG_ARG_METRIC_COMPUTE_TIME: self._collect_time_arg, } + if gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM in self._fun.sdfg_program.sdfg.symbols: + this_call_args[gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM] = ( + gtx_wfdcommon.get_gpu_stream_ptr(self._external_gpu_stream) + ) self._fun.construct_arguments(**this_call_args) # Perform the call to the SDFG. @@ -98,6 +105,38 @@ def __call__( def set_external_workspace(self, external_workspace: gtx_wfdcommon.ExternalWorkspace) -> None: """Set the external workspace for the underlying compiled program. - This method should be called before the first call to the program. + This method should be called before the first call to the program, because + the workspace is installed when the SDFG arguments are constructed. + + Args: + external_workspace: Mapping from device types to the array-like objects + used as workspace memory for the SDFG transient arrays, when the + transient memory mode is `EXTERNAL`. """ self._fun.external_workspace = external_workspace + + def set_external_gpu_stream( + self, external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None + ) -> None: + """Set the external GPU stream used by the underlying compiled program. + + This method should be called before the first call to the program, because + the stream is applied on SDFG initialization. + + Args: + external_gpu_stream: The handle of the external GPU stream, either as an + integer or as a stream object, see `GPUStreamHandle`. `None` selects + the default stream. + + Raises: + RuntimeError: If the program was already called. + TypeError: If `external_gpu_stream` is not a valid GPU stream handle. + """ + if self._fun.csdfg_argv is not None: + raise RuntimeError( + "The external GPU stream must be set before the first call to the program." + ) + # Validate the stream handle, but store it as given: a stream object is thus + # kept alive as long as the program, which uses its pointer value. + gtx_wfdcommon.get_gpu_stream_ptr(external_gpu_stream) + self._external_gpu_stream = external_gpu_stream diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py index 0295940a68..486e604e14 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -43,18 +43,26 @@ class DaCeConfig(next_backend.ToolchainConfig): #: `EXTERNAL` transient memory mode, which stores the transients in it. The #: workspace is a dict, so a config holding one is not hashable. external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None + #: GPU stream allocated outside the SDFG. The toolchain injects it into the + #: loaded programs, and the translation step then passes it to the SDFG as an + #: argument. The stream is an integer, so a config holding one is hashable. + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None #: Name of the function that binds the SDFG arguments. The bindings and the #: compilation steps must agree on it. bind_func_name: ClassVar[str] = "update_sdfg_args" + def __post_init__(self) -> None: + # Validate the stream handle early, it is only used when the program is loaded. + gtx_wfdcommon.get_gpu_stream_ptr(self.external_gpu_stream) + def make_dace_translator( cfg: DaCeConfig, /, *, auto_optimize_args: dict[str, Any] | None = None, - async_sdfg_call: bool = True, + sync_sdfg_call: bool = True, use_metrics: bool = True, disable_field_origin_on_program_arguments: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, @@ -72,8 +80,8 @@ def make_dace_translator( `transient_memory_mode` defaults to `EXTERNAL`. It also accepts the iterator-IR scan-fusion options `fuse_scan_inputs` and `scan_fusion_scope`, which are applied before SDFG lowering. - async_sdfg_call: Make an asynchronous SDFG call, to overlap GPU kernel - execution with the Python driver code. Only effective on GPU. + sync_sdfg_call: Make a synchronous SDFG call, to ensure that the GPU kernel + execution is completed before the Python driver code continues. Only effective on GPU. use_metrics: Add SDFG instrumentation for stencil compute time. disable_field_origin_on_program_arguments: Assume that all fields passed as program arguments have zero-based origin, which skips the range @@ -134,7 +142,7 @@ def make_dace_translator( device_type=cfg.device_type, auto_optimize=cfg.auto_optimize, auto_optimize_args=optimization_args, - async_sdfg_call=async_sdfg_call and cfg.gpu, + sync_sdfg_call=sync_sdfg_call, unstructured_horizontal_has_unit_stride=cfg.unstructured_horizontal_has_unit_stride, use_metrics=use_metrics, disable_field_origin_on_program_arguments=disable_field_origin_on_program_arguments, diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py index 76956e4579..8cba65a9cb 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -89,44 +89,6 @@ def find_constant_symbols( return constant_symbols -def make_sdfg_call_async(sdfg: dace.SDFG, gpu: bool) -> None: - """Configure an SDFG to immediately return once all work has been scheduled. - - This means that `CompiledSDFG.fast_call()` will return immediately after all - computations have been _scheduled_ on the device. This function only has an effect - for work that runs on the GPU. Furthermore, all work is scheduled on the - default stream. - - Todo: Revisit this function once DaCe changes its behaviour in this regard. - """ - - # This is only a problem on GPU. - # TODO(phimuell): Figuring out what about OpenMP. - if not gpu: - return - - assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( - f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." - ) - - # NOTE: We are using the default stream this means that _**currently**_ the launch is - # already asynchronous, see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120) - # for more. However, DaCe still [generates streams internally](https://github.com/spcl/dace/blob/54c935cfe74a52c5107dc91680e6201ddbf86821/dace/codegen/targets/cuda.py#L467). - # Thus to be absolutely sure we will no set all streams, DaCe uses to the default - # stream. - # NOTE: Another important note here is, that it looks as if no synchronization - # what soever between states is generated if the default stream is used. This - # might lead to problems if a GPU kernel computes something that is needed for a - # condition of an interstate edge. However, we should not have that case. - # TODO(phimuell, edopao): Make sure if this is really the case. - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", - location="cuda", - ) - - def _has_gpu_schedule(sdfg: dace.SDFG) -> bool: """Check if any node (e.g. maps) of the given SDFG is scheduled on GPU.""" return any( @@ -154,6 +116,29 @@ def _make_if_region_for_metrics_collection( return if_region, then_state +def _get_gpu_backend() -> str: + """Return the GPU backend, either 'cuda' or 'hip', configured in DaCe.""" + dace_gpu_backend = dace.Config.get("compiler.cuda.backend") + assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." + return dace_gpu_backend + + +def _for_each_sdfg_gpu_stream(statement: str) -> str: + """Return C++ code that applies `statement` to every GPU stream of the SDFG. + + Args: + statement: C++ statement, which refers to the current GPU stream as `__stream`. + + Returns: + A C++ loop over the streams in `__state->gpu_context->streams`. + """ + return f"""\ +for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ + gpuStream_t& __stream = __state->gpu_context->streams[__i]; + {statement} +}}""" + + def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: """ Instrument SDFG with measurement of total execution time. @@ -171,18 +156,18 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL, gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL_DTYPE ) - #### 1. Synchronize the CUDA device, in order to wait for kernels completion. + #### 1. Synchronize the SDFG GPU streams, in order to wait for kernels completion. + # We synchronize only the streams used by the SDFG, not the entire device, so + # that the measurement does not wait for unrelated work on other streams, e.g. + # external workload when the SDFG runs on an external GPU stream. # Even when the target device is GPU, it can happen that dace emits code without # GPU kernels. In this case, the cuda headers are not imported and the SDFG is # compiled as plain C++. Therefore, we also check here the schedule of SDFG maps. if gpu and _has_gpu_schedule(sdfg): - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - - # NOTE: We should actually wrap the `DeviceSynchronize` function inside a + # NOTE: We should actually wrap the `StreamSynchronize` function inside a # `DACE_GPU_CHECK()` macro. However, this only works in GPU context, but # here we are in CPU context. Thus we cannot do it. - sync_code = f"{dace_gpu_backend}DeviceSynchronize();" + sync_code = _for_each_sdfg_gpu_stream(f"{_get_gpu_backend()}StreamSynchronize(__stream);") has_side_effects = True else: @@ -270,12 +255,45 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: sdfg.validate() +def add_external_gpu_stream_arg(sdfg: dace.SDFG) -> None: + """Add an SDFG argument to set the GPU stream used for all GPU work of the SDFG. + + Running the SDFG on an external GPU stream allows to synchronize the execution + of GPU kernels with external workload and to share the stream memory pool. + The stream handle is a pointer, which in general changes from run to run of + the application, therefore it cannot be a compile-time value. Instead, it is + passed as the SDFG argument `SDFG_ARG_EXTERNAL_GPU_STREAM` and applied in the + SDFG init code, which runs once on the first SDFG call. The value of the + argument is the pointer value of the stream, see `get_gpu_stream_ptr()`, where + `DEFAULT_GPU_STREAM` selects the default stream. + + Args: + sdfg: The SDFG to process, modified in place. + """ + # NOTE: The argument has to be an SDFG symbol, not a scalar data container, + # because DaCe only passes the symbols to the SDFG init functions. + stream_arg = sdfg.add_symbol( + gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM, + gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE, + ) + + # NOTE: `__dace_gpu_set_all_streams()` is defined by DaCe in the GPU code, it + # writes the given stream into every entry of `__state->gpu_context->streams`. + # The handle `DEFAULT_GPU_STREAM`, i.e. `0`, is cast to `nullptr`, that is + # the default stream. + sdfg.append_init_code( + f"__dace_gpu_set_all_streams(__state, reinterpret_cast({stream_arg}));\n", + location="cuda", + ) + + def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: """Process the SDFG such that the call is synchronous. This means that `CompiledSDFG.fast_call()` will return only after all computations have _finished_ and the results are available. This function only has an effect for - work that runs on the GPU. Furthermore, all work is scheduled on the default stream. + work that runs on the GPU: it synchronizes all GPU streams of the SDFG, which by + default are the default stream, or an external stream, see `add_external_gpu_stream_arg()`. """ if not gpu: @@ -288,18 +306,10 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: # are not imported and the SDFG is compiled as plain C++. return - assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( - f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." - ) - - # If we are using the default stream, things are a bit simpler/harder. For some - # reasons when using the default stream, DaCe seems to skip _all_ synchronization, - # for more see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). - # Thus the `CompiledSDFG.fast_call()` call is truly asynchronous, i.e. just - # launches the kernels and then exist. Thus we have to add a synchronization - # at the end to have a synchronous call. We can not use `SDFG.append_exit_code()` - # because that code is only run at the `exit()` stage, not after a call. Thus we - # will generate an SDFGState that contains a Tasklet with the sync call. + # We synchronize the GPU streams explicitly at the end of the SDFG. We cannot + # use `SDFG.append_exit_code()` because that code is only run at the `exit()` + # stage, not after a call. Thus we add an `SDFGState` at the end that contains + # a `Tasklet` with the call to GPU stream synchronization. sync_state = sdfg.add_state("sync_state") for sink_node in sdfg.sink_nodes(): if sink_node is sync_state: @@ -314,25 +324,15 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: # NOTE: We should actually wrap the `StreamSynchronize` function inside a # `DACE_GPU_CHECK()` macro. However, this only works in GPU context, but # here we are in CPU context. Thus we can not do it. - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." sync_state.add_tasklet( - "sync_tlet", + "stream_synchronize", inputs={}, outputs={}, - code=f"{dace_gpu_backend}StreamSynchronize({dace_gpu_backend}StreamDefault);", + code=_for_each_sdfg_gpu_stream(f"{_get_gpu_backend()}StreamSynchronize(__stream);"), language=dace.dtypes.Language.CPP, side_effects=True, ) - # DaCe [still generates a stream](https://github.com/spcl/dace/blob/54c935cfe74a52c5107dc91680e6201ddbf86821/dace/codegen/targets/cuda.py#L467) - # despite not using it. Thus to be absolutely sure, we will not set that stream - # to the default stream. - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", - location="cuda", - ) - #: The parameters of `gt_auto_optimize()` that the translation step derives from #: its own configuration, and which therefore cannot be customized. @@ -401,12 +401,13 @@ class DaCeTranslator( device_type: core_defs.DeviceType auto_optimize: bool auto_optimize_args: dict[str, Any] | None - async_sdfg_call: bool + sync_sdfg_call: bool unstructured_horizontal_has_unit_stride: bool use_metrics: bool disable_field_origin_on_program_arguments: bool = False use_max_domain_range_on_unstructured_shift: bool | None = None + use_external_gpu_stream: bool = True def __post_init__(self) -> None: if self.auto_optimize_args and ( @@ -497,14 +498,28 @@ def _generate_sdfg_without_configuring_dace( sdfg, constant_symbols, validate=True ) - if self.async_sdfg_call: - make_sdfg_call_async(sdfg, on_gpu) - else: + if self.sync_sdfg_call: make_sdfg_call_sync(sdfg, on_gpu) + elif on_gpu: + # All GPU work is scheduled on a single stream and, since we disable the + # synchronization of the GPU stream at the SDFG exit, the call to + # `CompiledSDFG.fast_call()` is asynchronous, i.e. it just launches the + # kernels and exits. This is the default behavior in GT4Py. Note that DaCe + # still synchronizes the stream before the host reads data computed on GPU, + # see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). + assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( + f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." + ) + assert dace.Config.get("compiler.cuda.synchronize_on_exit") is False, ( + f"Expected `synchronize_on_exit == False` but it was `{dace.Config.get('compiler.cuda.synchronize_on_exit')}`." + ) if self.use_metrics: add_instrumentation(sdfg, on_gpu) + if on_gpu and self.use_external_gpu_stream: + add_external_gpu_stream_arg(sdfg) + return sdfg def __call__( diff --git a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py index b75149bf93..fb3aebfe94 100644 --- a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py +++ b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py @@ -7,14 +7,16 @@ # SPDX-License-Identifier: BSD-3-Clause import os +import re + import pytest -from dace import nodes +from dace import config as dace_config, nodes from dace.sdfg.state import LoopRegion import dace.sdfg.analysis.schedule_tree.treenodes as tn from gt4py.cartesian import backend -from gt4py.cartesian.backend.dace_backend import SDFGManager +from gt4py.cartesian.backend.dace_backend import DaCeExtGenerator, SDFGManager from gt4py.cartesian.gtscript import computation, PARALLEL, interval, Field from gt4py.cartesian.stencil_builder import StencilBuilder from gt4py.cartesian.gtc.dace.treeir import Axis @@ -221,3 +223,25 @@ def test_dace_cpu_KJI_loop_structure_parallel(): loop_region = for_nested_nodes[0] assert isinstance(loop_region, LoopRegion) assert loop_region.loop_variable == Axis.K.iteration_symbol() + + +def test_dace_gpu_codegen_initializes_gpu_context(): + # Code generation only: no GPU needed. + builder = StencilBuilder(copy_stencil, backend="dace:gpu") + with dace_config.temporary_config(): + # The backend must select the experimental codegen regardless of the user's DaCe config. + dace_config.Config.set("compiler", "cuda", "implementation", value="legacy") + sources = DaCeExtGenerator("Copy", "m_copy", builder.backend)() + code = sources["computation"]["computation.hpp"] + + assert "__dace_init_experimental_cuda" in code + + # The generated program reads its streams from `__state->gpu_context`, which the wrapper + # must set up because it never calls `__dace_init_()`. + match = re.search(r"new\s+dace::cuda::Context\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)", code) + assert match is not None + context_init = f"dace::cuda::Context gpu_context({match.group(1)}, {match.group(2)});" + context_attach = "dace_handle.gpu_context = &gpu_context;" + program_call = code.rindex("__program_copy_stencil(") + assert code.index(context_init) < code.index(context_attach) < program_call + assert "gpu_context.lasterror" in code[program_call:] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py index 990870bcd1..ecc4b02f57 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py @@ -114,7 +114,7 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args=optimization_args, - async_sdfg_call=True, + sync_sdfg_call=False, use_metrics=True, ), ) @@ -240,6 +240,107 @@ def test_make_backend_warns_external_workspace_without_external_mode(): assert backend.external_workspace[core_defs.DeviceType.CPU] is workspace +def _make_mocked_decorated_program( + sdfg_symbols: dict[str, dace.dtypes.typeclass], +) -> tuple[dace_wf_decoration.DaCeDecoratedProgram, mock.MagicMock]: + """Return a decorated program wrapping a mocked compiled program, and the mock.""" + sdfg = dace.SDFG("mocked_program") + for name, dtype in sdfg_symbols.items(): + sdfg.add_symbol(name, dtype) + + compiled_program = mock.MagicMock() + compiled_program.sdfg_program.sdfg = sdfg + compiled_program.csdfg_argv = None + compiled_program.csdfg_init_argv = None + + def construct_arguments(**kwargs: Any) -> None: + compiled_program.csdfg_argv = [] + compiled_program.csdfg_init_argv = [] + + compiled_program.construct_arguments.side_effect = construct_arguments + # Simulate the first call, where the argument vector is not yet constructed. + compiled_program.update_sdfg_ctype_arglist.side_effect = TypeError + + return dace_wf_decoration.DaCeDecoratedProgram(compiled_program), compiled_program + + +@dataclasses.dataclass(frozen=True) +class _GPUStream: + """Minimal stand-in for a stream object such as `cupy.cuda.Stream`.""" + + ptr: Any + + +@pytest.mark.parametrize( + "stream, expected_ptr", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], +) +def test_get_gpu_stream_ptr(stream, expected_ptr): + assert dace_wf_common.get_gpu_stream_ptr(stream) == expected_ptr + + +@pytest.mark.parametrize( + "stream", + ["0x1234", True, 1.0, _GPUStream(None), object()], + ids=["str", "bool", "float", "stream_object_without_int_ptr", "object"], +) +def test_get_gpu_stream_ptr_rejects_invalid_stream(stream): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_common.get_gpu_stream_ptr(stream) + + +def test_make_backend_rejects_invalid_external_gpu_stream(): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_backend.make_dace_backend(gpu=True, auto_optimize=False, external_gpu_stream="0") + + +@pytest.mark.parametrize( + "external_gpu_stream, expected_arg", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], +) +def test_decorated_program_passes_external_gpu_stream_arg(external_gpu_stream, expected_arg): + program, compiled_program = _make_mocked_decorated_program( + { + dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM: dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE + } + ) + program.set_external_gpu_stream(external_gpu_stream) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + compiled_program.construct_arguments.assert_called_once() + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert call_kwargs[dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM] == expected_arg + compiled_program.fast_call.assert_called_once() + + # The stream is applied on SDFG initialization, it cannot be changed later. + with pytest.raises(RuntimeError, match="before the first call"): + program.set_external_gpu_stream(0x5678) + + +def test_decorated_program_skips_external_gpu_stream_arg_on_cpu(): + # A CPU SDFG does not have the external GPU stream argument. + program, compiled_program = _make_mocked_decorated_program({}) + program.set_external_gpu_stream(0x1234) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in call_kwargs + + def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): """The toolchain and its translation step read the workspace from one config.""" workspace = _RecordingWorkspace() @@ -315,7 +416,7 @@ def test_make_dace_backend_is_deprecated(): with pytest.warns(DeprecationWarning, match="make_dace_toolchain"): deprecated = dace_wf_backend.make_dace_backend( gpu=False, - async_sdfg_call=False, + sync_sdfg_call=True, optimization_args={"blocking_size": 10}, external_workspace=workspace, unstructured_horizontal_has_unit_stride=True, @@ -330,7 +431,7 @@ def test_make_dace_backend_is_deprecated(): translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"blocking_size": 10}, - async_sdfg_call=False, + sync_sdfg_call=True, use_metrics=False, disable_field_origin_on_program_arguments=True, use_max_domain_range_on_unstructured_shift=True, @@ -355,7 +456,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args={"gpu": True}, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) @@ -457,7 +558,7 @@ def test_transient_memory_mode(device_type, transient_memory_mode, monkeypatch): auto_optimize_args={ "transient_memory_mode": transient_memory_mode, }, - async_sdfg_call=False, + sync_sdfg_call=True, ), ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py index 078a5a2620..4924a18dad 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py @@ -13,7 +13,7 @@ import re import uuid -from typing import Callable +from typing import Callable, Iterator, Literal from unittest import mock from gt4py._core import definitions as core_defs @@ -49,14 +49,19 @@ @pytest.fixture( params=[ - pytest.param(core_defs.DeviceType.CPU), - pytest.param(core_defs.DeviceType.CUDA, marks=[pytest.mark.requires_gpu]), - pytest.param(core_defs.DeviceType.ROCM, marks=[pytest.mark.requires_gpu]), - ], - ids=["CPU", "CUDA", "ROCM"], + pytest.param(core_defs.DeviceType.CPU, id="CPU"), + pytest.param(core_defs.DeviceType.CUDA, id="CUDA"), + pytest.param(core_defs.DeviceType.ROCM, id="ROCM"), + ] ) -def device_type(request) -> str: - return request.param +def device_type(request) -> Iterator[core_defs.DeviceType]: + # DaCe caches the GPU backend (`cuda` or `hip`) on first use, see `get_gpu_backend()`, + # because it assumes that a process only targets one type of GPU. These tests generate + # code for both CUDA and ROCm in the same process, so we clear the cache on each test, + # otherwise the code would be generated for the backend of a previous test. + dace.codegen.common.get_gpu_backend.cache_clear() + yield request.param + dace.codegen.common.get_gpu_backend.cache_clear() def _translate_gtir_to_sdfg( @@ -64,8 +69,9 @@ def _translate_gtir_to_sdfg( offset_provider: gtx_common.OffsetProvider, device_type: core_defs.DeviceType, auto_optimize: bool, - async_sdfg_call: bool, + sync_sdfg_call: bool, use_metrics: bool = False, + use_external_gpu_stream: bool = True, ) -> dace.SDFG: with dace.config.set_temporary("cache", value="hash"): # we use the SDFG hash in build cache to avoid clashes between CPU and GPU SDFGs @@ -73,9 +79,10 @@ def _translate_gtir_to_sdfg( device_type=device_type, auto_optimize=auto_optimize, auto_optimize_args=None, - async_sdfg_call=async_sdfg_call, + sync_sdfg_call=sync_sdfg_call, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, + use_external_gpu_stream=use_external_gpu_stream, ).generate_sdfg(ir, offset_provider=offset_provider) @@ -116,7 +123,7 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): offset_provider=SKIP_VALUE_MESH.offset_provider, device_type=core_defs.DeviceType.CPU, auto_optimize=False, - async_sdfg_call=False, + sync_sdfg_call=True, ) constant_symbols = dace_wf_translation.find_constant_symbols( @@ -199,7 +206,7 @@ def test_translation_grid_type(grid_type): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=True, use_metrics=False, ) @@ -250,7 +257,7 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=has_unit_stride, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, @@ -329,48 +336,65 @@ def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_name): ) -def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: +def _gpu_platform(device: core_defs.DeviceType) -> str: + return "cuda" if device == core_defs.DeviceType.CUDA else "hip" + + +def _are_streams_set_by_external_gpu_stream_arg(sdfg: dace.SDFG) -> bool: + """Check that the SDFG init code sets all GPU streams to the external stream argument. + + The external GPU stream is a runtime argument of the SDFG, it has to be a symbol + in order to be passed to the SDFG init functions. + """ if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False + stream_arg = dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM + if sdfg.symbols.get(stream_arg) != dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE: + return False + if re.search(rf"\b{stream_arg}\b", sdfg.init_signature()) is None: + return False return ( - re.match( - r"__dace_gpu_set_all_streams\(__state\s*,\s*(cuda|hip)StreamDefault\);", + re.search( + rf"\b__dace_gpu_set_all_streams\(\s*__state\s*,\s*reinterpret_cast\({stream_arg}\)\s*\);", sdfg.init_code["cuda"].as_string, ) is not None ) -def _are_streams_synchronized(sdfg: dace.SDFG) -> bool: +def _are_streams_synchronized(sdfg: dace.SDFG, device: core_defs.DeviceType) -> bool: re_stream_sync = re.compile(r"\b(cuda|hip)StreamSynchronize\b") + # The code is generated with the DaCe configuration used by GT4Py. + with dace_wf_common.dace_context(device_type=device): + code_objects = sdfg.generate_code() # The synchronization calls are in the CPU not the GPU code. return any( - re_stream_sync.match(code.clean_code) - for code in sdfg.generate_code() + re_stream_sync.search(code.clean_code) is not None + for code in code_objects if code.language == "cpp" ) -def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: - # Because we are using the default stream, the launch is asynchronous. Thus we - # have to check if there is no synchronization state. However, we will do a - # stronger test. Instead we will make sure that there are no synchronization - # calls in the _entire_ generated code. - # NOTE: Even in asynchronous launch, there might be some need for synchronization, - # for example if something is computed in a kernel and used on an interstate - # edge. However, we do not have that case. +def _check_sdfg_with_async_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: + # The GPU work is launched on the SDFG streams and, since the synchronization at + # the SDFG exit is disabled, the call is asynchronous. Thus we have to check that + # there is no synchronization state. However, we will do a stronger test: we make + # sure that there are no synchronization calls in the _entire_ generated code. + # NOTE: Even in asynchronous launch, DaCe synchronizes the stream if something is + # computed in a kernel and read on the host, for example on an interstate edge, + # see `test_generate_sdfg_async_call_multi_state`. The SDFGs checked here do not + # have that case. assert not any( state.label == "sync_state" for state in sdfg.sink_nodes() if isinstance(state, dace.SDFGState) ) - assert not _are_streams_synchronized(sdfg) - assert _are_streams_set_to_default_stream(sdfg) + assert not _are_streams_synchronized(sdfg, device) -def _check_sdfg_without_async_call(sdfg: dace.SDFG) -> None: +def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: states = list(sdfg.states()) sink_states = sdfg.sink_nodes() @@ -386,10 +410,12 @@ def _check_sdfg_without_async_call(sdfg: dace.SDFG) -> None: sync_tlet = next(iter(sync_state.nodes())) assert isinstance(sync_tlet, dace_nodes.Tasklet) assert sync_tlet.side_effects - assert sync_tlet.label == "sync_tlet" + assert sync_tlet.label == "stream_synchronize" - assert re.match(r"(cuda|hip)StreamSynchronize\(\1StreamDefault\)", sync_tlet.code.as_string) - assert _are_streams_set_to_default_stream(sdfg) + assert sync_tlet.code.as_string == dace_wf_translation._for_each_sdfg_gpu_stream( + f"{_gpu_platform(device)}StreamSynchronize(__stream);" + ) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: @@ -399,16 +425,13 @@ def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: for state in sdfg.sink_nodes() if isinstance(state, dace.SDFGState) ) - assert not _are_streams_synchronized(sdfg) + assert not _are_streams_synchronized(sdfg, core_defs.DeviceType.CPU) -@pytest.mark.parametrize( - "make_async_sdfg_call", - [False, True], -) -def test_generate_sdfg_async_call(make_async_sdfg_call: bool, device_type: core_defs.DeviceType): - """Verify that the flag `async_sdfg_call` takes effect on the SDFG generation.""" - program_name = "field_ir_{}_async_call".format("with" if make_async_sdfg_call else "without") +@pytest.mark.parametrize("sync_call", [False, True]) +def test_generate_sdfg_sync_call(sync_call: bool, device_type: core_defs.DeviceType): + """Verify that the flag `sync_sdfg_call` takes effect on the SDFG generation.""" + program_name = "field_ir_{}_sync_call".format("with" if sync_call else "without") ir = itir.Program( id=program_name, @@ -432,19 +455,19 @@ def test_generate_sdfg_async_call(make_async_sdfg_call: bool, device_type: core_ offset_provider={}, device_type=device_type, auto_optimize=False, - async_sdfg_call=make_async_sdfg_call, + sync_sdfg_call=sync_call, ) if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) - elif make_async_sdfg_call: - _check_sdfg_with_async_call(sdfg) + elif sync_call: + _check_sdfg_with_sync_call(sdfg, device_type) else: - _check_sdfg_without_async_call(sdfg) + _check_sdfg_with_async_call(sdfg, device_type) def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): - """Verify that the flag `async_sdfg_call=True` has no effect on an SDFG that does not contain any GPU map.""" + """Verify that the flag `sync_sdfg_call=False` has no effect on an SDFG that does not contain any GPU map.""" ir = itir.Program( id="scalar_ir_with_async_call", @@ -468,13 +491,127 @@ def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): offset_provider={}, device_type=device_type, auto_optimize=False, - async_sdfg_call=True, + sync_sdfg_call=False, ) if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) else: - _check_sdfg_with_async_call(sdfg) + _check_sdfg_with_async_call(sdfg, device_type) + + +def _are_gpu_operations_on_sdfg_streams( + sdfg: dace.SDFG, device: core_defs.DeviceType, gpu_operation: Literal["kernel", "copy"] +) -> bool: + """Check that the GPU operations are scheduled on the streams of the SDFG state. + + The code is generated with the DaCe configuration used by GT4Py, and the check + ensures that kernel launches and copies read their GPU stream from the array + `__state->gpu_context->streams`, which is the one set by the init code, instead + of using the default stream (`nullptr`). + """ + platform = _gpu_platform(device) + re_gpu_operation = { + "kernel": re.compile(r"\b__dace_runkernel_\w+\(__state\b.*,\s*(\w+)\);"), + # The copy call may be wrapped in an error-checking macro, e.g. `DACE_GPU_CHECK(...)`. + "copy": re.compile(rf"\b{platform}Memcpy\w*Async\(.*,\s*(\w+)\)"), + }[gpu_operation] + + with dace_wf_common.dace_context(device_type=device): + # The GPU operations are launched from the CPU code. + code = "\n".join( + code_object.clean_code + for code_object in sdfg.generate_code() + if code_object.language == "cpp" + ) + + if ( + re.search(r"\bgpuStream_t\s*\*\s*gpu_streams\s*=\s*__state->gpu_context->streams;", code) + is None + ): + return False + + gpu_streams = re_gpu_operation.findall(code) + return len(gpu_streams) > 0 and all( + re.search(rf"\bgpuStream_t\s+{stream}\s*=\s*gpu_streams\[\d+\];", code) is not None + for stream in gpu_streams + ) + + +@pytest.mark.parametrize("gpu_operation", ["kernel", "copy"]) +def test_generate_sdfg_external_gpu_stream( + gpu_operation: Literal["kernel", "copy"], + device_type: core_defs.DeviceType, +): + """Verify that the GPU stream used by the SDFG is selected by a runtime argument.""" + if device_type == core_defs.DeviceType.CPU: + pytest.skip("This test is only relevant for GPU execution.") + + ir = itir.Program( + id=f"field_ir_external_gpu_stream_{gpu_operation}", + declarations=[], + function_definitions=[], + params=[ + itir.Sym(id="x", type=IFTYPE), + itir.Sym(id="y", type=IFTYPE), + ], + body=[ + itir.SetAt( + # A field operator is lowered to a GPU kernel, while a plain field + # assignment is lowered to a GPU copy. + expr=im.op_as_fieldop("plus")("x", 1.0) + if gpu_operation == "kernel" + else itir.SymRef(id="x"), + domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", IFTYPE.dims), + target=itir.SymRef(id="y"), + ), + ], + ) + + sdfg = _translate_gtir_to_sdfg( + ir=ir, + offset_provider={}, + device_type=device_type, + auto_optimize=False, + sync_sdfg_call=False, + ) + _check_sdfg_with_async_call(sdfg, device_type) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) + assert _are_gpu_operations_on_sdfg_streams(sdfg, device_type, gpu_operation) + + +def test_generate_sdfg_without_external_gpu_stream(device_type: core_defs.DeviceType): + """Verify that the external GPU stream argument is not added when disabled. + + This is the case of orchestration, where the SDFG is nested in another SDFG. + """ + ir = itir.Program( + id="field_ir_without_external_gpu_stream", + declarations=[], + function_definitions=[], + params=[ + itir.Sym(id="x", type=IFTYPE), + itir.Sym(id="y", type=IFTYPE), + ], + body=[ + itir.SetAt( + expr=im.op_as_fieldop("plus")("x", 1.0), + domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", IFTYPE.dims), + target=itir.SymRef(id="y"), + ), + ], + ) + + sdfg = _translate_gtir_to_sdfg( + ir=ir, + offset_provider={}, + device_type=device_type, + auto_optimize=False, + sync_sdfg_call=False, + use_external_gpu_stream=False, + ) + assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in sdfg.arglist() + assert "cuda" not in sdfg.init_code def _make_multi_state_sdfg_0( @@ -571,55 +708,51 @@ def _make_multi_state_sdfg_3( @pytest.mark.parametrize( "multi_state_config", [ - (True, _make_multi_state_sdfg_0), - (False, _make_multi_state_sdfg_1), - (False, _make_multi_state_sdfg_2), - (False, _make_multi_state_sdfg_3), + (False, _make_multi_state_sdfg_0), + (True, _make_multi_state_sdfg_1), + (True, _make_multi_state_sdfg_2), + (True, _make_multi_state_sdfg_3), ], ) def test_generate_sdfg_async_call_multi_state( multi_state_config: tuple[bool, Callable], device_type: core_defs.DeviceType ): """ - Verify that states are not made async when a data descriptor is accessed - on an outgoing InterState edge. + Verify the synchronization of an asynchronous SDFG call with multiple states. + + The GPU streams of the SDFG have to be synchronized when the result of a + device-to-host copy is used on an outgoing InterState edge or on the host, + otherwise there should be no synchronization. """ - on_gpu = device_type == core_defs.CUPY_DEVICE_TYPE - expect_async_sdfg_call_on_first_state, make_multi_state_sdfg = multi_state_config + if device_type == core_defs.DeviceType.CPU: + pytest.skip("This test is only relevant for GPU execution.") + + expect_sync_after_first_map, make_multi_state_sdfg = multi_state_config sdfg, first_state, second_state = make_multi_state_sdfg() - # NOTE: Here we should use a configuration context. But because of - # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - dace_wf_translation.make_sdfg_call_async(sdfg, on_gpu) - - if on_gpu: - assert _are_streams_set_to_default_stream(sdfg) + dace_wf_translation.add_external_gpu_stream_arg(sdfg) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) # No synchronization state is added. assert sdfg.number_of_nodes() == 2 assert sdfg.out_degree(first_state) == 1 and sdfg.in_degree(first_state) == 0 assert sdfg.out_degree(second_state) == 0 and sdfg.in_degree(second_state) == 1 - # We do never a sync. + # The states are not marked as `nosync`. assert first_state.nosync == False assert second_state.nosync == False - if device_type == core_defs.DeviceType.CPU: - _check_cpu_sdfg_call(sdfg) - elif expect_async_sdfg_call_on_first_state: - # NOTE: This test is plain wrong! Because there is a dependency between the first and the - # second state. This is because the Map in the first state computes something that is - # used on the Interstate edge. Thus there should be a sync at the end of the first - # state. But as the test bellow shows, there is no sync in the enter CPU code (syncs - # are never inside the GPU code). This is plain wrong, but we should not be affected - # by this. See https://github.com/spcl/dace/issues/2120 for more. - # In the case of `_make_multi_state_sdfg_3()` there would be a sync after the Map, before - # the Tasklet, if the default stream was not used! - assert not _are_streams_synchronized(sdfg) + if expect_sync_after_first_map: + # There is a dependency between the first and the second state: the `Map` + # in the first state computes a value that is copied to host memory and + # used either on the InterState edge or inside the first state. Thus, the + # GPU stream has to be synchronized after the device-to-host copy. + # See https://github.com/spcl/dace/issues/2120 for more information. + assert _are_streams_synchronized(sdfg, device_type) else: # There is no dependency between the states, so no sync. - assert not _are_streams_synchronized(sdfg) + assert not _are_streams_synchronized(sdfg, device_type) def _make_simple_field_operator_compilable_program() -> otf_workflow.ConcreteArtifact: @@ -681,7 +814,7 @@ def test_translation_source_code_invariant_under_guid_change(): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index e0ba4f6d04..c003d7e30c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -75,7 +75,7 @@ def translate(program, enabled, **extra_options): device_type=core_defs.DeviceType.CPU, auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": enabled, **extra_options}, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) @@ -226,7 +226,7 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev device_type=core_defs.DeviceType.CPU, auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True}, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ).generate_sdfg(program, offset_provider={}) @@ -585,7 +585,7 @@ def test_invalid_scan_fusion_scope_is_rejected(): device_type=core_defs.DeviceType.CPU, auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True, "scan_fusion_scope": "field_operators"}, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) diff --git a/uv.lock b/uv.lock index 863f5e47ed..435cda549c 100644 --- a/uv.lock +++ b/uv.lock @@ -1012,7 +1012,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0b2" -source = { registry = "https://pypi.org/simple" } +source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#3aa2c595bea1368c20ae5fcf2a77a18e0d34c1be" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1032,7 +1032,6 @@ dependencies = [ { name = "sympy" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6d/39/c0f134464d714b06dedcbbc8d17e509f249a4a2626a8aa68af01abdc92f0/dace-2.0.0b2.tar.gz", hash = "sha256:831fd753e55e94e1ce20cb3246a4724a9832da47af31e6a3ae8c9d08692c4714", size = 7210560, upload-time = "2026-11-16T15:21:32.771Z" } [[package]] name = "debugpy" @@ -1436,7 +1435,7 @@ jax-cuda12 = [ ] jax-cuda13 = [ { name = "cupy-cuda13x" }, - { name = "jax", extra = ["cuda13-local"], marker = "extra == 'extra-5-gt4py-jax-cuda13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "jax", extra = ["cuda13-local"], marker = "extra == 'extra-5-gt4py-jax-cuda13' or extra == 'extra-5-gt4py-cuda12' and (extra == 'extra-5-gt4py-rocm6' or extra == 'extra-5-gt4py-rocm7') or extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7'" }, ] next = [ { name = "hypothesis" }, @@ -1595,7 +1594,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", specifier = "==2.0.0b2" }, + { name = "dace", git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" },