Skip to content

[MLIR][ExecutionEngine] Tolerate CUDA_ERROR_DEINITIALIZED in mgpuModuleUnload#190563

Merged
joker-eph merged 2 commits intollvm:mainfrom
jaredhoberock:fix-mgpu-module-unload
Apr 6, 2026
Merged

[MLIR][ExecutionEngine] Tolerate CUDA_ERROR_DEINITIALIZED in mgpuModuleUnload#190563
joker-eph merged 2 commits intollvm:mainfrom
jaredhoberock:fix-mgpu-module-unload

Conversation

@jaredhoberock
Copy link
Copy Markdown
Contributor

@jaredhoberock jaredhoberock commented Apr 6, 2026

mgpuModuleUnload may be called from a global destructor (registered by SelectObjectAttr's appendToGlobalDtors) after the CUDA primary context has already been destroyed during program shutdown. In this case, cuModuleUnload returns CUDA_ERROR_DEINITIALIZED, which is benign since the module's resources are already freed with the context.

Reproduction

Any program that uses gpu.launch_func and is AOT-compiled (via mlir-translate --mlir-to-llvmir | llc | cc -lmlir_cuda_runtime) will print 'cuModuleUnload(module)' failed with '<unknown>' on exit. This is because SelectObjectAttr registers the module unload as a global destructor, which runs after the CUDA primary context is released.

This script reproduces the error message from mgpuModuleUnload on my system:

#!/bin/bash
set -e

LLVM_BUILD=${LLVM_BUILD:-$HOME/dev/git/llvm-project-22/build}

cat > /tmp/repro.mlir << 'MLIR'
func.func @main() {
  %c1 = arith.constant 1 : index
  gpu.launch blocks(%bx, %by, %bz) in (%gx = %c1, %gy = %c1, %gz = %c1)
             threads(%tx, %ty, %tz) in (%bsx = %c1, %bsy = %c1, %bsz = %c1) {
    gpu.terminator
  }
  return
}
MLIR

$LLVM_BUILD/bin/mlir-opt /tmp/repro.mlir \
  -gpu-lower-to-nvvm-pipeline="cubin-format=fatbin" \
  | $LLVM_BUILD/bin/mlir-translate --mlir-to-llvmir -o /tmp/repro.ll

$LLVM_BUILD/bin/llc -relocation-model=pic -filetype=obj /tmp/repro.ll -o /tmp/repro.o

cc /tmp/repro.o \
  -L$LLVM_BUILD/lib -Wl,-rpath,$LLVM_BUILD/lib \
  -lmlir_cuda_runtime -lmlir_runner_utils -o /tmp/repro

echo "Running:"
/tmp/repro 2>&1
echo "Exit code: $?"

Context

This matches how other projects handle the same shutdown ordering issue:

  • Clang CUDA (D48613) switched module cleanup from __attribute__((destructor)) to atexit()
  • GCC libgomp checks context validity before cuModuleUnload
  • Apache TVM silently ignores CUDA_ERROR_DEINITIALIZED on module unload

Fixes #170833

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 6, 2026

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Copy Markdown
Member

llvmbot commented Apr 6, 2026

@llvm/pr-subscribers-mlir-gpu
@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-mlir-execution-engine

Author: Jared Hoberock (jaredhoberock)

Changes

mgpuModuleUnload may be called from a global destructor (registered by SelectObjectAttr's appendToGlobalDtors) after the CUDA primary context has already been destroyed during program shutdown. In this case, cuModuleUnload returns CUDA_ERROR_DEINITIALIZED, which is benign since the module's resources are already freed with the context.

Reproduction

Any program that uses gpu.launch_func and is AOT-compiled (via mlir-translate --mlir-to-llvmir | llc | cc -lmlir_cuda_runtime) will print 'cuModuleUnload(module)' failed with '&lt;unknown&gt;' on exit. This is because SelectObjectAttr registers the module unload as a global destructor, which runs after the CUDA primary context is released.

This script reproduces the error message from mgpuModuleUnload on my system:

#!/bin/bash
set -e

LLVM_BUILD=${LLVM_BUILD:-$HOME/dev/git/llvm-project-22/build}

cat &gt; /tmp/repro.mlir &lt;&lt; 'MLIR'
func.func @<!-- -->main() {
  %c1 = arith.constant 1 : index
  gpu.launch blocks(%bx, %by, %bz) in (%gx = %c1, %gy = %c1, %gz = %c1)
             threads(%tx, %ty, %tz) in (%bsx = %c1, %bsy = %c1, %bsz = %c1) {
    gpu.terminator
  }
  return
}
MLIR

$LLVM_BUILD/bin/mlir-opt /tmp/repro.mlir \
  -gpu-lower-to-nvvm-pipeline="cubin-format=fatbin" \
  | $LLVM_BUILD/bin/mlir-translate --mlir-to-llvmir -o /tmp/repro.ll

$LLVM_BUILD/bin/llc -relocation-model=pic -filetype=obj /tmp/repro.ll -o /tmp/repro.o

cc /tmp/repro.o \
  -L$LLVM_BUILD/lib -Wl,-rpath,$LLVM_BUILD/lib \
  -lmlir_cuda_runtime -lmlir_runner_utils -o /tmp/repro

echo "Running:"
/tmp/repro 2&gt;&amp;1
echo "Exit code: $?"

Context

This matches how other projects handle the same shutdown ordering issue:

  • Clang CUDA (D48613) switched module cleanup from __attribute__((destructor)) to atexit()
  • GCC libgomp checks context validity before cuModuleUnload
  • Apache TVM silently ignores CUDA_ERROR_DEINITIALIZED on module unload

Full diff: https://github.com/llvm/llvm-project/pull/190563.diff

1 Files Affected:

  • (modified) mlir/lib/ExecutionEngine/CudaRuntimeWrappers.cpp (+6-1)
diff --git a/mlir/lib/ExecutionEngine/CudaRuntimeWrappers.cpp b/mlir/lib/ExecutionEngine/CudaRuntimeWrappers.cpp
index 7bf6804902479..24c88b9fa587b 100644
--- a/mlir/lib/ExecutionEngine/CudaRuntimeWrappers.cpp
+++ b/mlir/lib/ExecutionEngine/CudaRuntimeWrappers.cpp
@@ -127,7 +127,12 @@ extern "C" MLIR_CUDA_WRAPPERS_EXPORT CUmodule mgpuModuleLoad(void *data) {
 }
 
 extern "C" MLIR_CUDA_WRAPPERS_EXPORT void mgpuModuleUnload(CUmodule module) {
-  CUDA_REPORT_IF_ERROR(cuModuleUnload(module));
+  // At program exit, the CUDA primary context may already be destroyed.
+  // CUDA_ERROR_DEINITIALIZED is benign — the module's resources are already
+  // freed with the context.
+  CUresult result = cuModuleUnload(module);
+  if (result != CUDA_SUCCESS && result != CUDA_ERROR_DEINITIALIZED)
+    CUDA_REPORT_IF_ERROR(result);
 }
 
 extern "C" MLIR_CUDA_WRAPPERS_EXPORT CUfunction

@joker-eph
Copy link
Copy Markdown
Collaborator

This may be fixing #170833 ; we could reenable mlir/test/Integration/GPU/CUDA/async.mlir

Is this the same issue?

@jaredhoberock
Copy link
Copy Markdown
Contributor Author

I believe this is the same class of issue. The async.mlir test hits CUDA_ERROR_CONTEXT_IS_DESTROYED on stream/event dtors during shutdown, while the original report hits CUDA_ERROR_DEINITIALIZED on module unload.

The PR is updated to handle both error codes across all five affected dtors, and re-enabled the FileCheck in async.mlir. async.mlir passes cleanly with the fix on my system.

Copy link
Copy Markdown
Collaborator

@joker-eph joker-eph left a comment

Choose a reason for hiding this comment

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

LGTM, thanks!

@joker-eph joker-eph enabled auto-merge (squash) April 6, 2026 20:41
@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 6, 2026

✅ With the latest revision this PR passed the C/C++ code formatter.

…urce cleanup

During program exit, CUDA resource cleanup functions (module unload,
stream/event destroy, etc.) may be called after the CUDA primary context
has already been destroyed. This produces spurious error messages like
'cuModuleUnload(module)' failed with 'CUDA_ERROR_DEINITIALIZED' or
'cuEventDestroy(event)' failed with 'CUDA_ERROR_CONTEXT_IS_DESTROYED'.

These errors are benign — all resources are already freed when the
context is destroyed.

Add CUDA_REPORT_IF_ERROR_IGNORE_SHUTDOWN macro that silences both
CUDA_ERROR_DEINITIALIZED (4) and CUDA_ERROR_CONTEXT_IS_DESTROYED (709),
and apply it to the five cleanup wrappers: mgpuModuleUnload,
mgpuStreamDestroy, mgpuStreamWaitEvent, mgpuEventDestroy, and
mgpuEventSynchronize.

Re-enable FileCheck in async.mlir integration test.

Fixes llvm#170833, fixes llvm#190563.
auto-merge was automatically disabled April 6, 2026 20:46

Head branch was pushed to by a user without write access

@jaredhoberock jaredhoberock force-pushed the fix-mgpu-module-unload branch from 85a7ec6 to 4ef818b Compare April 6, 2026 20:46
@jaredhoberock
Copy link
Copy Markdown
Contributor Author

Updated to fix clang-format

@joker-eph joker-eph enabled auto-merge (squash) April 6, 2026 21:03
@joker-eph joker-eph merged commit 7087ece into llvm:main Apr 6, 2026
10 checks passed
@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 6, 2026

@jaredhoberock Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@jaredhoberock
Copy link
Copy Markdown
Contributor Author

The buildbot failure on Integration/GPU/CUDA/async.mlir revealed that the test produces wrong output ([42, 42] instead of [84, 84]) intermittently, which is separate from the cleanup errors this PR addresses. I've reverted the FileCheck re-enable to keep the test in its previously-disabled state. The cleanup error fix stands; #170833 remains open.

@joker-eph
Copy link
Copy Markdown
Collaborator

I've reverted the FileCheck re-enable to keep the test in its previously-disabled state.

You need to open a new PR, did you?

jaredhoberock added a commit to jaredhoberock/llvm-project that referenced this pull request Apr 6, 2026
llvm#190563 re-enabled FileCheck on Integration/GPU/CUDA/async.mlir, but
the buildbot has shown intermittent wrong-output failures: the test
produces [42, 42] instead of the expected [84, 84]. This is distinct
from the cleanup-time cuModuleUnload errors that llvm#190563 actually
fixes; it is the underlying flakiness tracked by llvm#170833.

Put the test back in its previously-disabled state.
@jaredhoberock
Copy link
Copy Markdown
Contributor Author

You're right — apologies for the confusion. The revert was on a force-push that landed after the merge, so the merged commit still has FileCheck re-enabled. I've opened #190702 to actually re-disable it.

Also, the merged commit incorrectly claims Fixes #170833; the buildbot failure confirms this fix doesn't address that issue. #170833 should be reopened.

joker-eph pushed a commit that referenced this pull request Apr 6, 2026
…0702)

#190563 re-enabled FileCheck on `Integration/GPU/CUDA/async.mlir`, but
the buildbot has shown intermittent wrong-output failures
([example](https://lab.llvm.org/buildbot/#/builders/116/builds/27026)):
the test produces `[42, 42]` instead of the expected `[84, 84]`.

This wrong-output flakiness is distinct from the cleanup-time
`cuModuleUnload` errors that #190563 actually fixes — it's the
underlying issue tracked by #170833. The merged commit message for
#190563 incorrectly says `Fixes #170833`; that issue should be reopened,
since the cleanup-error fix doesn't address the wrong-output behavior.

This PR puts the test back in its previously-disabled state. The runtime
cleanup fix in #190563 is unaffected.
YonahGoldberg pushed a commit to YonahGoldberg/llvm-project that referenced this pull request Apr 7, 2026
…m#190702)

llvm#190563 re-enabled FileCheck on `Integration/GPU/CUDA/async.mlir`, but
the buildbot has shown intermittent wrong-output failures
([example](https://lab.llvm.org/buildbot/#/builders/116/builds/27026)):
the test produces `[42, 42]` instead of the expected `[84, 84]`.

This wrong-output flakiness is distinct from the cleanup-time
`cuModuleUnload` errors that llvm#190563 actually fixes — it's the
underlying issue tracked by llvm#170833. The merged commit message for
llvm#190563 incorrectly says `Fixes llvm#170833`; that issue should be reopened,
since the cleanup-error fix doesn't address the wrong-output behavior.

This PR puts the test back in its previously-disabled state. The runtime
cleanup fix in llvm#190563 is unaffected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[mlir] Integration/GPU/CUDA/async.mlir is very unstable

3 participants