diff --git a/docs/api/c/cuda_context.rst b/docs/api/c/cuda_context.rst new file mode 100644 index 00000000000..998a5c85f86 --- /dev/null +++ b/docs/api/c/cuda_context.rst @@ -0,0 +1,166 @@ +.. + Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + See LICENSE for license information. + +CUDA state lifecycle +==================== + +TE provides two explicit, process-wide lifecycle operations: + +* ``nvte_release_cuda_state()`` releases registered resources while all their + primary CUDA contexts and borrowed communicators remain usable. Use this for a + context-preserving restart or before planned context destruction. +* ``nvte_reset_cuda_state()`` invalidates registered state after the external + owner has destroyed every primary context backing those resources. Dead + stream/event/module handles are abandoned instead of passed to CUDA destroy + functions. Using reset while any affected context is live leaks resources and + is unsupported. + +There is no device argument or selective-device recovery. Stop all TE calls, +object construction and destruction in every host thread before either operation. +For release, complete GPU work and retire captured graphs first. TE does not own +context teardown, detect context replacement, reset framework allocators, or +restore model tensors. Multiple live CUDA contexts per device are unsupported. + +Compute streams/events, CUDA-library handles, RTC modules, normalization plans, +fused-attention graphs, and registered frontend owners share one registry. A +resource may own state for one or several GPUs. Operations recreate released +resources lazily; compiled RTC bytes remain cached on the CPU. Thread-local +library handles have process-owned slots, so handles from finished threads can +still be released. + +Live cleanup retains device affinity: callbacks for one GPU run with its existing +primary context current, and the caller's context is restored afterward. Cleanup +does not initialize primary contexts on unused devices. Owners spanning several +GPUs select the appropriate devices themselves. Both operations use dependency +phases: plans precede library handles, modules and streams. Within a phase, +cleanup follows reverse registration order. Callback errors propagate after +remaining callbacks run; cleanup is not transactional. Finish it before resuming +work after an error. + +Reset performs a process-wide preflight before mutating resources or publishing a +new generation. Active communication/IPC/VMM owners, CuTeDSL executors and JAX +pinned transfers can reject unsupported post-loss cleanup. Release such resources +while CUDA and their transport remain usable. If that boundary was missed, restart +the worker. Reset itself is host-only and does not query or synchronize CUDA. + +Generation and registration +--------------------------- + +``nvte_get_cuda_state_version()`` returns the single process-wide generation, +initially one, through an acquire load. Release or reset publishes one increment +after cleanup, including when there are no registered resources. A rejected +preflight leaves the version unchanged. A release with a callback error advances +it because resources may already have been released. + +This notification does not pin resources, wait for an in-progress lifecycle call, +or permit concurrent reset and TE work. Callers must discard cached TE stream and +event handles after either operation. Pointer equality does not identify a +resource lifetime. + +The native ``Resource`` base and the C-ABI ``FrontendResource`` adapter register +objects automatically during base construction and unregister during destruction, +including constructor unwinding. The caller must exclude construction and +destruction while lifecycle callbacks run; they cannot observe partial objects. +Cleanup affinity and priority are explicit constructor parameters, rather than +virtual calls on an incompletely constructed derived object. + +Bindings use ``nvte_register_cuda_state`` and ``nvte_unregister_cuda_state``. +Registration is host-only. Its device ordinal is +an affinity for live cleanup, not a reset filter; ``-1`` identifies host-only or +multi-device owners whose callbacks manage device selection. Registered addresses +remain stable until unregistration. Check callbacks cannot mutate state; +invalidation callbacks cannot throw. Callbacks must not register new resources +or re-enter lifecycle APIs, but cleanup may destroy and unregister child owners. + +``nvte_set_cuda_state_device`` changes an existing registration's live-cleanup +affinity without changing its original registration order. Standard dependency +phases are named by ``NVTECudaStateReleaseOrder``; custom integer priorities remain +supported. Reset and release both process ascending priority and reverse +registration order within each priority. Unregistered children are skipped even +if they were present in the lifecycle snapshot. + +Lazy initialization +------------------- + +``LazyResource`` provides an optional ``ensure_valid(initializer)`` for library +handles, RTC modules and context-local kernel attributes. ``InitializationState`` +serializes initialization with a mutex and a second validity check, and publishes +success with release/acquire ordering. A throwing initializer remains invalid and +can be retried. The fast path does not query CUDA or lock the resource registry. + +Initializers receive their parameters from their caller; a cache container need +not implement a parameterless virtual initializer. Owners provide distinct live +release and post-loss invalidation hooks. Cleanup visits partially initialized +owners too, since an initializer may acquire resources before failing. Every +lifecycle operation invalidates successful initialization after the owner finishes +cleanup. Users must still stop all calls before teardown; ``ensure_valid`` does +not make concurrent reset or destruction safe. + +Grouped operation recovery +-------------------------- + +After context loss, replace the caller's device allocations and construct grouped +tensors with current data and metadata pointers. Grouped MXFP8 operations rebuild +their context-local tensor maps from these pointers on execution. Retire old CUDA +graphs and recapture with valid allocations. This lifecycle API does not change +the grouped operations' descriptor-storage or stream-concurrency contract. + +Framework cleanup +----------------- + +``transformer_engine.pytorch.release_cuda_state()`` checks capture boundaries on +all active devices before mutating state, synchronizes those devices, clears +PyTorch's process-wide compilation cache, finalizes TE EP/Userbuffers, detaches +FP8 reduction registrations, and clears TE-owned tensor caches across devices. +CPU tensor cache entries and FP8 numerical history survive. Model and optimizer +tensors, RNG state and the framework runtime are retained. + +Call outside FP8 autocast and graph capture, after backward completes. Release +independently retained communication owners first. Borrowed process groups must +remain valid until cleanup finishes, and every collective participant performs +cleanup in the same order. Reinitialize EP/Userbuffers explicitly before reuse; +old EP routing buffers are rejected after finalization or rebootstrap. + +``transformer_engine.jax.release_cuda_state()`` waits for effects and work on all +local GPU devices, clears JAX's compilation caches, finalizes TE EP across local +devices, and releases registered collective-GEMM plans/communicators, pinned +transfers and score-mod graphs. Explicitly reinitialize communication before +reuse. External executable and communication references must be retired first. + +Each frontend wrapper cleans its own Python state and then invokes global common +cleanup. Applications using multiple frontends must coordinate all their owners +and stop their work at the same boundary. + +CuTeDSL cleanup drops native TVM-FFI references and TE-generated Python registry +entries while CUDA remains live. Dispatch keys retain device identity and use the +global version to avoid reusing executors from earlier lifetimes. Private caches +of third-party compiler runtimes remain owned by those runtimes. + +For a caller-controlled, context-preserving PyTorch restart:: + + # Complete backward, stop all TE callers and retire captured graphs. + # Every rank cleans up before destroying borrowed process groups. + transformer_engine.pytorch.release_cuda_state() + # Reinitialize TE communication if used, then reuse the existing tensors. + +Context-loss limits +------------------ + +TE does not reconstruct the initialized PyTorch allocator/stream pool or the +JAX/XLA runtime. The Python ``reset_cuda_state()`` wrappers reject unsupported +framework recovery instead of touching stale tensors. Native owners with an +independently recovered allocator can use the common API for supported resources. +The global generation does not make stale framework allocations safe to reuse. + +Dependency-owned host allocations may also survive context loss. On CUDA 13.5 / +cuDNN 9.28, the saved standalone ``cudnnCreate`` → ``cudaDeviceReset`` → +``cudnnDestroy`` probe crashes, so dead handles are abandoned. Recreating handles +without destruction increased allocated host heap in that probe. Leak-free +post-loss cleanup of opaque host state requires a dependency-supported strategy. + +C/C++ reference +-------------- + +.. doxygenfile:: cuda_context.h diff --git a/docs/api/c/index.rst b/docs/api/c/index.rst index 82024e25b02..480fd44fbf7 100644 --- a/docs/api/c/index.rst +++ b/docs/api/c/index.rst @@ -17,6 +17,7 @@ directly from C/C++, without Python. cast_transpose_noop.h cast.h cudnn.h + cuda_context.h fused_attn.h fused_rope.h gemm.h diff --git a/docs/api/jax.rst b/docs/api/jax.rst index 99282be422c..41057df4492 100644 --- a/docs/api/jax.rst +++ b/docs/api/jax.rst @@ -6,6 +6,14 @@ Jax === +CUDA state lifecycle +-------------------- + +See :doc:`c/cuda_context` for restart boundaries, ordering and context-loss limits. + +.. autoapifunction:: transformer_engine.jax.release_cuda_state +.. autoapifunction:: transformer_engine.jax.reset_cuda_state + Pre-defined Variable of Logical Axes ------------------------------------ Variables are available in `transformer_engine.jax.sharding`. diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 2d8cc87827e..4c3e7be7cff 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -6,6 +6,17 @@ PyTorch ======= +CUDA state lifecycle +-------------------- + +See :doc:`c/cuda_context` for restart boundaries, ordering and context-loss limits. + +.. autoapifunction:: transformer_engine.pytorch.release_cuda_state +.. autoapifunction:: transformer_engine.pytorch.reset_cuda_state + +Modules +------- + .. autoapiclass:: transformer_engine.pytorch.Linear(in_features, out_features, **kwargs) :members: forward, set_tensor_parallel_group diff --git a/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index 2aa02340018..462a88e5508 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -34,6 +34,7 @@ pip3 install pytest==8.2.1 || error_exit "Failed to install pytest" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_optional_flash_attn_import.xml $TE_PATH/tests/pytorch/test_optional_flash_attn_import.py || test_fail "test_optional_flash_attn_import.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_sanity.xml $TE_PATH/tests/pytorch/test_sanity.py || test_fail "test_sanity.py" +python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_cuda_context.xml $TE_PATH/tests/pytorch/test_cuda_context.py || test_fail "test_cuda_context.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_recipe.xml $TE_PATH/tests/pytorch/test_recipe.py || test_fail "test_recipe.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_custom_recipe.xml $TE_PATH/tests/pytorch/test_custom_recipe.py || test_fail "test_custom_recipe.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_deferred_init.xml $TE_PATH/tests/pytorch/test_deferred_init.py || test_fail "test_deferred_init.py" diff --git a/tests/cpp/CMakeLists.txt b/tests/cpp/CMakeLists.txt index 477ed522d27..adf412f24e7 100644 --- a/tests/cpp/CMakeLists.txt +++ b/tests/cpp/CMakeLists.txt @@ -59,7 +59,7 @@ if(TE_LIB_UNDEFINED_SYMBOLS MATCHES "[ \t]U _?Py[A-Za-z_]") message(STATUS "${TE_LIB} requires CPython symbols, linking the tests against libpython") # Find the interpreter too so older CMake versions use its version to locate libpython. find_package(Python COMPONENTS Interpreter Development.Embed REQUIRED) - foreach(test_target test_operator test_util) + foreach(test_target test_operator test_util test_cuda_context) target_link_libraries(${test_target} PRIVATE "-Wl,--no-as-needed" Python::Python diff --git a/tests/cpp/util/CMakeLists.txt b/tests/cpp/util/CMakeLists.txt index b80a588fe35..8e05dcc9855 100644 --- a/tests/cpp/util/CMakeLists.txt +++ b/tests/cpp/util/CMakeLists.txt @@ -24,3 +24,9 @@ include(GoogleTest) # MALLOC_PERTURB_ makes glibc overwrite freed memory, so a destructor that reads a destroyed object # at exit crashes the test process, which ctest reports as a failure, instead of passing silently. gtest_discover_tests(test_util DISCOVERY_TIMEOUT 600 PROPERTIES ENVIRONMENT "MALLOC_PERTURB_=165") + +# Context teardown is isolated from ordinary utility tests and their GPU state. +add_executable(test_cuda_context test_cuda_context.cu) +target_link_libraries(test_cuda_context PRIVATE GTest::gtest_main ${TE_LIB} + CUDA::cudart CUDA::cuda_driver CUDA::nvrtc CUDNN::cudnn Threads::Threads) +gtest_discover_tests(test_cuda_context DISCOVERY_TIMEOUT 600) diff --git a/tests/cpp/util/test_cuda_context.cu b/tests/cpp/util/test_cuda_context.cu new file mode 100644 index 00000000000..ec62a30865b --- /dev/null +++ b/tests/cpp/util/test_cuda_context.cu @@ -0,0 +1,694 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "util/cuda_context.h" +#include "util/cuda_state_registration.h" +#include "util/rtc.h" + +extern "C" cudnnHandle_t nvte_get_cudnn_handle(); +using namespace transformer_engine; + +namespace { +struct RegisteredOwner : cuda_context::FrontendResource { + RegisteredOwner(std::vector &events, int id, int phase = NVTE_CUDA_STATE_RELEASE_PLANS, + bool fail = false) + : FrontendResource(-1, phase), events(events), id(id) { + if (fail) throw std::runtime_error("owner construction failed"); + } + void release_context() override { events.push_back(id); } + void invalidate_context() noexcept override { events.push_back(id); } + std::vector &events; + int id; +}; + +TEST(CudaContextHostTest, ConstructorRegistrationAndRollbackUnregister) { + std::vector events; + events.reserve(8); + RegisteredOwner first(events, 1); + { RegisteredOwner removed(events, 2); } + EXPECT_THROW(RegisteredOwner(events, 3, NVTE_CUDA_STATE_RELEASE_PLANS, true), std::runtime_error); + RegisteredOwner last(events, 4); + const NVTECudaStateCallbacks invalid{nullptr, nullptr, nullptr, nullptr, 0}; + EXPECT_THROW(nvte_register_cuda_state(-1, invalid, nullptr), std::runtime_error); + nvte_reset_cuda_state(); + EXPECT_EQ(events, (std::vector{4, 1})); +} + +TEST(CudaContextHostTest, CleanupPhasesAndReverseRegistrationOrder) { + std::vector events; + events.reserve(16); + RegisteredOwner handle(events, 1, NVTE_CUDA_STATE_RELEASE_HANDLES); + RegisteredOwner plan_first(events, 2, NVTE_CUDA_STATE_RELEASE_PLANS); + RegisteredOwner module(events, 3, NVTE_CUDA_STATE_RELEASE_MODULES); + RegisteredOwner plan_last(events, 4, NVTE_CUDA_STATE_RELEASE_PLANS); + RegisteredOwner stream(events, 5, NVTE_CUDA_STATE_RELEASE_STREAMS); + const std::vector expected{4, 2, 1, 3, 5}; + nvte_reset_cuda_state(); + EXPECT_EQ(events, expected); + events.clear(); + nvte_release_cuda_state(); + EXPECT_EQ(events, expected); +} + +TEST(CudaContextHostTest, AffinityChangesPreserveOriginalRegistrationOrder) { + std::vector events; + events.reserve(8); + RegisteredOwner first(events, 1), last(events, 2); + first.set_device(0); + last.set_device(-1); + EXPECT_THROW(first.set_device(-2), std::runtime_error); + EXPECT_THROW(nvte_set_cuda_state_device(nullptr, 0), std::runtime_error); + nvte_reset_cuda_state(); + EXPECT_EQ(events, (std::vector{2, 1})); +} + +TEST(CudaContextHostTest, SharedInitializationPublishesOnceAndCanBeInvalidated) { + cuda_context::InitializationState state; + std::atomic initialized{0}; + std::atomic waiting{0}; + std::promise start; + auto begin = start.get_future().share(); + std::array observed{}; + int value = 0; + std::vector threads; + for (size_t i = 0; i < observed.size(); ++i) { + threads.emplace_back([&, i] { + waiting.fetch_add(1); + begin.wait(); + state.ensure_valid([&] { + initialized.fetch_add(1); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + value = 37; + }); + observed[i] = value; + }); + } + while (waiting.load() != observed.size()) std::this_thread::yield(); + start.set_value(); + for (auto &thread : threads) thread.join(); + EXPECT_EQ(initialized.load(), 1); + for (auto result : observed) EXPECT_EQ(result, 37); + state.invalidate(); + state.ensure_valid([&] { + ++initialized; + value = 41; + }); + EXPECT_EQ(initialized.load(), 2); + EXPECT_EQ(value, 41); +} + +TEST(CudaContextHostTest, FailedInitializationCanBeRetried) { + cuda_context::InitializationState state; + int attempts = 0; + EXPECT_THROW(state.ensure_valid([&] { + ++attempts; + throw std::runtime_error("initialization failure"); + }), + std::runtime_error); + state.ensure_valid([&] { ++attempts; }); + state.ensure_valid([&] { ++attempts; }); + EXPECT_EQ(attempts, 2); +} + +std::string lifetime_test_ptx() { + auto check = [](nvrtcResult status) { + if (status != NVRTC_SUCCESS) throw std::runtime_error(nvrtcGetErrorString(status)); + }; + int count; + check(nvrtcGetNumSupportedArchs(&count)); + std::vector architectures(count); + check(nvrtcGetSupportedArchs(architectures.data())); + const auto option = "--gpu-architecture=compute_" + + std::to_string(*std::min_element(architectures.begin(), architectures.end())); + const char *options[] = {option.c_str()}; + constexpr auto source = R"( + extern "C" __global__ void first(int *p) { *p = 11; } + extern "C" __global__ void second(int *p) { *p = 22; } + )"; + nvrtcProgram program; + check(nvrtcCreateProgram(&program, source, "lifetime.cu", 0, nullptr, nullptr)); + std::string ptx; + try { + check(nvrtcCompileProgram(program, 1, options)); + size_t bytes; + check(nvrtcGetPTXSize(program, &bytes)); + ptx.resize(bytes); + check(nvrtcGetPTX(program, ptx.data())); + } catch (...) { + nvrtcDestroyProgram(&program); + throw; + } + check(nvrtcDestroyProgram(&program)); + return ptx; +} + +class ContextResetTest : public ::testing::Test { + protected: + void SetUp() override { + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || count == 0) GTEST_SKIP(); + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + } + void reset() { + int count; + ASSERT_EQ(cudaGetDeviceCount(&count), cudaSuccess); + for (int ordinal = 0; ordinal < count; ++ordinal) { + CUdevice device; + unsigned flags; + int active; + ASSERT_EQ(cuDeviceGet(&device, ordinal), CUDA_SUCCESS); + ASSERT_EQ(cuDevicePrimaryCtxGetState(device, &flags, &active), CUDA_SUCCESS); + if (active) { + ASSERT_EQ(cudaSetDevice(ordinal), cudaSuccess); + ASSERT_EQ(cudaDeviceReset(), cudaSuccess); + } + } + const auto before = nvte_get_cuda_state_version(); + ASSERT_NO_THROW(nvte_reset_cuda_state()); + EXPECT_EQ(nvte_get_cuda_state_version(), before + 1); + // The external caller recreates a usable context after the host-only reset. + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + } +}; + +TEST(CudaContextHostTest, GenerationDoesNotInitializeCuda) { + ASSERT_EQ(cuInit(0), CUDA_SUCCESS); + CUcontext before = nullptr, after = nullptr; + ASSERT_EQ(cuCtxGetCurrent(&before), CUDA_SUCCESS); + const auto initial = nvte_get_cuda_state_version(); + nvte_reset_cuda_state(); + EXPECT_EQ(nvte_get_cuda_state_version(), initial + 1); + nvte_reset_cuda_state(); + EXPECT_EQ(nvte_get_cuda_state_version(), initial + 2); + ASSERT_EQ(cuCtxGetCurrent(&after), CUDA_SUCCESS); + EXPECT_EQ(before, after); +} + +TEST(CudaContextHostTest, LiveReleaseDoesNotCreateUnusedContexts) { + ASSERT_EQ(cuInit(0), CUDA_SUCCESS); + int count; + ASSERT_EQ(cuDeviceGetCount(&count), CUDA_SUCCESS); + std::vector before(count); + for (int device = 0; device < count; ++device) { + unsigned flags; + ASSERT_EQ(cuDevicePrimaryCtxGetState(device, &flags, &before[device]), CUDA_SUCCESS); + } + CUcontext previous, current; + ASSERT_EQ(cuCtxGetCurrent(&previous), CUDA_SUCCESS); + int calls = 0; + auto callback = [](void *data) { ++*static_cast(data); }; + const NVTECudaStateCallbacks callbacks{nullptr, nullptr, callback, callback, 0}; + const auto registration = nvte_register_cuda_state(0, callbacks, &calls); + const auto global = nvte_register_cuda_state(-1, callbacks, &calls); + const auto version = nvte_get_cuda_state_version(); + EXPECT_NO_THROW(nvte_release_cuda_state()); + EXPECT_EQ(nvte_get_cuda_state_version(), version + 1); + EXPECT_EQ(calls, 2); + EXPECT_EQ(cuCtxGetCurrent(¤t), CUDA_SUCCESS); + EXPECT_EQ(previous, current); + for (int device = 0; device < count; ++device) { + unsigned flags; + int active; + EXPECT_EQ(cuDevicePrimaryCtxGetState(device, &flags, &active), CUDA_SUCCESS); + EXPECT_EQ(active, before[device]); + } + nvte_unregister_cuda_state(registration); + nvte_unregister_cuda_state(global); +} + +TEST(CudaContextHostTest, PartialReleaseContinuesAndPublishesOneVersion) { + int failed = 0, released = 0; + auto release = [](void *data) { ++*static_cast(data); }; + auto fail = [](void *data) { + ++*static_cast(data); + throw std::runtime_error("release failure"); + }; + const NVTECudaStateCallbacks bad{nullptr, nullptr, fail, release, 0}; + const NVTECudaStateCallbacks good{nullptr, nullptr, release, release, 0}; + const auto second = nvte_register_cuda_state(-1, good, &released); + const auto first = nvte_register_cuda_state(-1, bad, &failed); + const auto version = nvte_get_cuda_state_version(); + EXPECT_THROW(nvte_release_cuda_state(), std::runtime_error); + EXPECT_EQ(failed, 1); + EXPECT_EQ(released, 1); + EXPECT_EQ(nvte_get_cuda_state_version(), version + 1); + nvte_unregister_cuda_state(first); + nvte_unregister_cuda_state(second); +} + +TEST_F(ContextResetTest, StreamsAndRtcRecoverRepeatedly) { + auto &manager = rtc::KernelManager::instance(); + constexpr auto code = R"(__global__ void recovered(int *p) { *p = 37; })"; + manager.compile("context recovery test", "recovered", code, "recovered.cu"); + for (int cycle = 0; cycle < 4; ++cycle) { + auto stream = nvte_get_compute_stream(0); + auto event = nvte_get_compute_stream_event(0); + int *data = nullptr; + ASSERT_EQ(cudaMalloc(&data, sizeof(int)), cudaSuccess); + manager.launch("context recovery test", 1, 1, 0, stream, data); + ASSERT_EQ(cudaEventRecord(event, stream), cudaSuccess); + ASSERT_EQ(cudaEventSynchronize(event), cudaSuccess); + int value = 0; + ASSERT_EQ(cudaMemcpy(&value, data, sizeof(int), cudaMemcpyDeviceToHost), cudaSuccess); + EXPECT_EQ(value, 37); + reset(); + // The allocation died with the context; do not cudaFree the old pointer. + EXPECT_TRUE(manager.is_compiled("context recovery test", 0)); + } +} + +TEST_F(ContextResetTest, GlobalResetRecoversBothDevicesAndKeepsRtcCode) { + int count; + ASSERT_EQ(cudaGetDeviceCount(&count), cudaSuccess); + if (count < 2) GTEST_SKIP() << "Requires two CUDA devices"; + auto &manager = rtc::KernelManager::instance(); + constexpr auto code = R"(__global__ void recovered(int *p, int value) { *p = value; })"; + for (int device = 0; device < 2; ++device) { + ASSERT_EQ(cudaSetDevice(device), cudaSuccess); + manager.compile("global recovery test", "recovered", code, "recovered.cu"); + } + for (int cycle = 0; cycle < 3; ++cycle) { + for (int device = 0; device < 2; ++device) { + ASSERT_EQ(cudaSetDevice(device), cudaSuccess); + EXPECT_TRUE(manager.is_compiled("global recovery test", device)); + int *data; + ASSERT_EQ(cudaMalloc(&data, sizeof(int)), cudaSuccess); + auto stream = nvte_get_compute_stream(0); + const int expected = 10 * cycle + device; + manager.launch("global recovery test", 1, 1, 0, stream, data, expected); + ASSERT_EQ(cudaStreamSynchronize(stream), cudaSuccess); + int value = -1; + ASSERT_EQ(cudaMemcpy(&value, data, sizeof(int), cudaMemcpyDeviceToHost), cudaSuccess); + EXPECT_EQ(value, expected); + } + reset(); + } +} + +TEST_F(ContextResetTest, GlobalReleaseRecreatesBothDevicesAndRestoresContext) { + int count; + ASSERT_EQ(cudaGetDeviceCount(&count), cudaSuccess); + if (count < 2) GTEST_SKIP() << "Requires two CUDA devices"; + auto &manager = rtc::KernelManager::instance(); + constexpr auto code = R"(__global__ void recovered(int *p, int value) { *p = value; })"; + std::vector storage(2); + for (int device = 0; device < 2; ++device) { + ASSERT_EQ(cudaSetDevice(device), cudaSuccess); + ASSERT_EQ(cudaMalloc(&storage[device], sizeof(int)), cudaSuccess); + manager.compile("global release test", "recovered", code, "recovered.cu"); + } + for (int cycle = 0; cycle < 3; ++cycle) { + for (int device = 0; device < 2; ++device) { + ASSERT_EQ(cudaSetDevice(device), cudaSuccess); + auto stream = nvte_get_compute_stream(0); + auto event = nvte_get_compute_stream_event(0); + auto handle = nvte_get_cudnn_handle(); + ASSERT_EQ(cudnnSetStream(handle, stream), CUDNN_STATUS_SUCCESS); + const int expected = cycle + device; + manager.launch("global release test", 1, 1, 0, stream, storage[device], expected); + ASSERT_EQ(cudaEventRecord(event, stream), cudaSuccess); + ASSERT_EQ(cudaEventSynchronize(event), cudaSuccess); + int value = -1; + ASSERT_EQ(cudaMemcpy(&value, storage[device], sizeof(int), cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(value, expected); + } + CUcontext before, after; + ASSERT_EQ(cuCtxGetCurrent(&before), CUDA_SUCCESS); + const auto version = nvte_get_cuda_state_version(); + nvte_release_cuda_state(); + EXPECT_EQ(nvte_get_cuda_state_version(), version + 1); + ASSERT_EQ(cuCtxGetCurrent(&after), CUDA_SUCCESS); + EXPECT_EQ(before, after); + int current; + ASSERT_EQ(cudaGetDevice(¤t), cudaSuccess); + EXPECT_EQ(current, 1); + } + for (int device = 0; device < 2; ++device) { + ASSERT_EQ(cudaSetDevice(device), cudaSuccess); + ASSERT_EQ(cudaFree(storage[device]), cudaSuccess); + } + reset(); +} + +TEST_F(ContextResetTest, GlobalReleaseErrorRestoresContextAndVisitsOtherDevices) { + int count; + ASSERT_EQ(cudaGetDeviceCount(&count), cudaSuccess); + if (count < 2) GTEST_SKIP() << "Requires two CUDA devices"; + ASSERT_EQ(cudaSetDevice(1), cudaSuccess); + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + struct Owner { + int device; + bool fail; + int calls = 0; + } first{0, true}, second{1, false}; + auto cleanup = [](void *data) { + auto &owner = *static_cast(data); + int current; + EXPECT_EQ(cudaGetDevice(¤t), cudaSuccess); + EXPECT_EQ(current, owner.device); + ++owner.calls; + if (owner.fail) throw std::runtime_error("affine release failure"); + }; + const NVTECudaStateCallbacks callbacks{nullptr, nullptr, cleanup, [](void *) {}, 0}; + auto b = nvte_register_cuda_state(1, callbacks, &second); + auto a = nvte_register_cuda_state(0, callbacks, &first); + CUcontext before, after; + ASSERT_EQ(cuCtxGetCurrent(&before), CUDA_SUCCESS); + const auto version = nvte_get_cuda_state_version(); + EXPECT_THROW(nvte_release_cuda_state(), std::runtime_error); + EXPECT_EQ(first.calls, 1); + EXPECT_EQ(second.calls, 1); + EXPECT_EQ(nvte_get_cuda_state_version(), version + 1); + ASSERT_EQ(cuCtxGetCurrent(&after), CUDA_SUCCESS); + EXPECT_EQ(before, after); + nvte_unregister_cuda_state(a); + nvte_unregister_cuda_state(b); + reset(); +} + +TEST_F(ContextResetTest, MovedRtcKernelReinitializesWithItsCurrentParameters) { + const auto ptx = lifetime_test_ptx(); + rtc::Kernel first("first", ptx), second("second", ptx); + swap(first, second); + int *data; + ASSERT_EQ(cudaMalloc(&data, sizeof(int)), cudaSuccess); + const auto execute = [&](rtc::Kernel &kernel, int expected) { + kernel.launch(0, 1, 1, 0, nullptr, data); + int value = 0; + ASSERT_EQ(cudaMemcpy(&value, data, sizeof(int), cudaMemcpyDeviceToHost), cudaSuccess); + EXPECT_EQ(value, expected); + }; + execute(first, 22); + rtc::Kernel moved(std::move(first)); + nvte_release_cuda_state(); + execute(moved, 22); + execute(second, 11); + nvte_release_cuda_state(); + ASSERT_EQ(cudaFree(data), cudaSuccess); +} + +TEST_F(ContextResetTest, FailedRtcInitializationDiscardsPartialStateOnReset) { + rtc::Kernel kernel("missing_symbol", lifetime_test_ptx()); + const auto lookup_error = [&]() -> std::string { + try { + kernel.get_function(0); + } catch (const std::runtime_error &error) { + return error.what(); + } + return {}; + }; + const auto first_error = lookup_error(); + ASSERT_FALSE(first_error.empty()); + ASSERT_NO_THROW(nvte_release_cuda_state()); + // Acquire another partial module before context loss. Its initializer never + // becomes valid, but reset must still discard the dead module handle. + EXPECT_EQ(lookup_error(), first_error); + reset(); + EXPECT_EQ(lookup_error(), first_error); + nvte_release_cuda_state(); +} + +TEST_F(ContextResetTest, OtherThreadsCudnnHandleRecovers) { + std::promise ready, resume; + auto resumed = resume.get_future(); + std::atomic errors{0}; + std::thread worker([&] { + try { + if (cudaSetDevice(0) != cudaSuccess) ++errors; + auto handle = nvte_get_cudnn_handle(); + if (cudnnSetStream(handle, nvte_get_compute_stream(0)) != CUDNN_STATUS_SUCCESS) ++errors; + } catch (...) { + ++errors; + } + ready.set_value(); + resumed.wait(); + try { + if (cudaSetDevice(0) != cudaSuccess) ++errors; + auto handle = nvte_get_cudnn_handle(); + if (cudnnSetStream(handle, nvte_get_compute_stream(0)) != CUDNN_STATUS_SUCCESS) ++errors; + } catch (...) { + ++errors; + } + }); + ready.get_future().wait(); + reset(); + resume.set_value(); + worker.join(); + EXPECT_EQ(errors.load(), 0); + reset(); +} + +TEST_F(ContextResetTest, FinishedThreadsReturnHandlesForReleaseAndReuse) { + cudnnHandle_t first = nullptr, second = nullptr; + std::thread([&]() { + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + first = nvte_get_cudnn_handle(); + }).join(); + std::thread([&]() { + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + second = nvte_get_cudnn_handle(); + }).join(); + ASSERT_NE(first, nullptr); + // Deliberate handoff of the same live cached handle to a subsequent thread. + EXPECT_EQ(first, second); + nvte_release_cuda_state(); + std::thread([&]() { + ASSERT_EQ(cudaSetDevice(0), cudaSuccess); + auto handle = nvte_get_cudnn_handle(); + EXPECT_EQ(cudnnSetStream(handle, nvte_get_compute_stream(0)), CUDNN_STATUS_SUCCESS); + }).join(); + nvte_release_cuda_state(); +} + +TEST_F(ContextResetTest, CudnnNormalizationPlanRecoversNumerically) { + nvte_enable_cudnn_norm_fwd(true); + constexpr size_t hidden = 128, rows = 4; + for (int cycle = 0; cycle < 3; ++cycle) { + float *buffer = nullptr; + ASSERT_EQ(cudaMalloc(&buffer, (3 * rows * hidden + 2 * hidden + 2 * rows) * sizeof(float)), + cudaSuccess); + auto *x = buffer; + auto *gamma = x + rows * hidden; + auto *beta = gamma + hidden; + auto *output = beta + hidden; + auto *mu = output + rows * hidden; + auto *rsigma = mu + rows; + std::vector input(rows * hidden); + for (size_t i = 0; i < input.size(); ++i) input[i] = static_cast(i % hidden); + std::vector weights(hidden, 1.0f); + ASSERT_EQ(cudaMemcpy(x, input.data(), input.size() * sizeof(float), cudaMemcpyHostToDevice), + cudaSuccess); + ASSERT_EQ(cudaMemcpy(gamma, weights.data(), hidden * sizeof(float), cudaMemcpyHostToDevice), + cudaSuccess); + ASSERT_EQ(cudaMemset(beta, 0, hidden * sizeof(float)), cudaSuccess); + TensorWrapper tx(x, std::vector{rows, hidden}, DType::kFloat32); + TensorWrapper tg(gamma, std::vector{hidden}, DType::kFloat32); + TensorWrapper tb(beta, std::vector{hidden}, DType::kFloat32); + TensorWrapper tz(output, std::vector{rows, hidden}, DType::kFloat32); + TensorWrapper tm(mu, std::vector{rows}, DType::kFloat32); + TensorWrapper tr(rsigma, std::vector{rows}, DType::kFloat32); + TensorWrapper workspace; + const auto run = [&] { + nvte_layernorm_fwd(tx.data(), tg.data(), tb.data(), 1e-5f, tz.data(), tm.data(), tr.data(), + workspace.data(), cuda::sm_count(0), false, nullptr); + }; + run(); + void *scratch = nullptr; + const auto shape = workspace.shape(); + size_t bytes = typeToSize(workspace.dtype()); + for (size_t i = 0; i < shape.ndim; ++i) bytes *= shape.data[i]; + ASSERT_EQ(cudaMalloc(&scratch, bytes), cudaSuccess); + workspace.set_rowwise_data(scratch, workspace.dtype(), shape); + run(); + std::vector actual(input.size()); + ASSERT_EQ( + cudaMemcpy(actual.data(), output, actual.size() * sizeof(float), cudaMemcpyDeviceToHost), + cudaSuccess); + const float mean = (hidden - 1) / 2.0f; + const float variance = (hidden * hidden - 1) / 12.0f; + for (size_t i = 0; i < actual.size(); ++i) { + EXPECT_NEAR(actual[i], (input[i] - mean) / std::sqrt(variance + 1e-5f), 2e-5f); + } + reset(); + } + nvte_enable_cudnn_norm_fwd(false); +} + +TEST_F(ContextResetTest, CublasGemmRecoversNumerically) { + constexpr size_t dim = 16, elements = dim * dim; + constexpr size_t scratch_bytes = 32 * 1024 * 1024; + for (int cycle = 0; cycle < 3; ++cycle) { + float *data = nullptr; + void *scratch = nullptr; + ASSERT_EQ(cudaMalloc(&data, 3 * elements * sizeof(float)), cudaSuccess); + ASSERT_EQ(cudaMalloc(&scratch, scratch_bytes), cudaSuccess); + std::vector a(elements, 1.0f + cycle), b(elements, 2.0f), actual(elements); + ASSERT_EQ(cudaMemcpy(data, a.data(), elements * sizeof(float), cudaMemcpyHostToDevice), + cudaSuccess); + ASSERT_EQ( + cudaMemcpy(data + elements, b.data(), elements * sizeof(float), cudaMemcpyHostToDevice), + cudaSuccess); + TensorWrapper ta(data, std::vector{dim, dim}, DType::kFloat32); + TensorWrapper tb(data + elements, std::vector{dim, dim}, DType::kFloat32); + TensorWrapper td(data + 2 * elements, std::vector{dim, dim}, DType::kFloat32); + TensorWrapper workspace(scratch, std::vector{scratch_bytes}, DType::kByte); + TensorWrapper absent; + nvte_cublas_gemm(ta.data(), tb.data(), td.data(), absent.data(), absent.data(), true, false, + false, workspace.data(), false, true, 0, nullptr); + ASSERT_EQ(cudaMemcpy(actual.data(), data + 2 * elements, elements * sizeof(float), + cudaMemcpyDeviceToHost), + cudaSuccess); + for (auto value : actual) EXPECT_EQ(value, 2.0f * dim * (cycle + 1)); + reset(); + } +} + +TEST_F(ContextResetTest, GroupedMxfp8RecoversNumerically) { + cudaDeviceProp properties; + ASSERT_EQ(cudaGetDeviceProperties(&properties, 0), cudaSuccess); + if (properties.major < 10) GTEST_SKIP() << "Grouped MXFP8 requires Blackwell"; + constexpr size_t groups = 3; + for (int cycle = 0; cycle < 3; ++cycle) { + const std::vector rows{128, 256, 128}; + const std::vector cols{128, 256, 128 * (cycle + 2)}; + std::vector offsets(groups + 1, 0); + for (size_t i = 0; i < groups; ++i) offsets[i + 1] = offsets[i] + rows[i] * cols[i]; + const size_t elements = offsets.back(); + std::vector expected(elements), actual(elements); + for (size_t i = 0; i < elements; ++i) { + expected[i] = (static_cast(i % 15) - 7) * static_cast(1 << cycle); + } + std::vector allocations; + const auto allocate = [&](size_t bytes) { + void *ptr = nullptr; + const auto status = cudaMalloc(&ptr, bytes); + if (status != cudaSuccess) throw std::runtime_error(cudaGetErrorString(status)); + allocations.push_back(ptr); + return ptr; + }; + const auto upload = [&](const auto &values) { + const size_t bytes = values.size() * sizeof(values[0]); + void *ptr = allocate(bytes); + const auto status = cudaMemcpy(ptr, values.data(), bytes, cudaMemcpyHostToDevice); + if (status != cudaSuccess) throw std::runtime_error(cudaGetErrorString(status)); + return ptr; + }; + // Exactly representable values give an independent reference for both kernels. + void *input_data = upload(expected); + void *rows_data = upload(rows); + void *cols_data = upload(cols); + void *offsets_data = upload(offsets); + void *quantized = allocate(elements); + void *scales = allocate(elements / 32); + void *dequantized = allocate(elements * sizeof(float)); + { + const std::vector shape{1, elements}, metadata_shape{groups}; + GroupedTensorWrapper input(groups, shape); + GroupedTensorWrapper output(groups, shape, NVTE_MXFP8_1D_SCALING); + GroupedTensorWrapper recovered(groups, shape); + for (auto *tensor : {&input, &output, &recovered}) { + tensor->set_first_dims(rows_data, DType::kInt64, metadata_shape) + .set_last_dims(cols_data, DType::kInt64, metadata_shape) + .set_tensor_offsets(offsets_data, DType::kInt64, std::vector{groups + 1}); + } + input.set_rowwise_data(input_data, DType::kFloat32, std::vector{elements}); + output.set_rowwise_data(quantized, DType::kFloat8E4M3, std::vector{elements}) + .set_rowwise_scale_inv(scales, DType::kFloat8E8M0, std::vector{elements / 32}); + recovered.set_rowwise_data(dequantized, DType::kFloat32, std::vector{elements}); + nvte_group_quantize(input.data(), output.data(), nullptr, nullptr); + nvte_group_dequantize(output.data(), recovered.data(), nullptr); + ASSERT_EQ( + cudaMemcpy(actual.data(), dequantized, elements * sizeof(float), cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(actual, expected) << "cycle " << cycle; + } + for (auto ptr : allocations) ASSERT_EQ(cudaFree(ptr), cudaSuccess); + reset(); + } +} + +struct CallbackOwner { + NVTECudaStateRegistration child = nullptr; + int calls = 0; + static void invalidate(void *data) { + auto &self = *static_cast(data); + ++self.calls; + nvte_unregister_cuda_state(self.child); + self.child = nullptr; + } + static void reject(void *) { throw std::runtime_error("resource requires pre-loss cleanup"); } +}; + +TEST(CudaContextHostTest, CallbackPreflightAndNestedUnregister) { + CallbackOwner parent, child; + const NVTECudaStateCallbacks normal{nullptr, nullptr, CallbackOwner::invalidate, + CallbackOwner::invalidate, 0}; + parent.child = nvte_register_cuda_state(0, normal, &child); + auto registration = nvte_register_cuda_state(1, normal, &parent); + const NVTECudaStateCallbacks rejecting{CallbackOwner::reject, nullptr, CallbackOwner::invalidate, + CallbackOwner::invalidate, 0}; + auto rejected = nvte_register_cuda_state(-1, rejecting, &child); + const auto initial = nvte_get_cuda_state_version(); + EXPECT_THROW(nvte_reset_cuda_state(), std::runtime_error); + EXPECT_EQ(nvte_get_cuda_state_version(), initial); + EXPECT_EQ(parent.calls, 0); + EXPECT_EQ(child.calls, 0); + nvte_unregister_cuda_state(rejected); + nvte_reset_cuda_state(); + EXPECT_EQ(parent.calls, 1); + EXPECT_EQ(child.calls, 0); + EXPECT_EQ(nvte_get_cuda_state_version(), initial + 1); + nvte_unregister_cuda_state(registration); +} + +TEST_F(ContextResetTest, LiveReleaseRecreatesStreamsAndLibraryHandles) { + auto &manager = rtc::KernelManager::instance(); + constexpr auto code = R"(__global__ void recovered(int *p, int value) { *p = value; })"; + manager.compile("live release test", "recovered", code, "recovered.cu"); + int *storage = nullptr; + ASSERT_EQ(cudaMalloc(&storage, sizeof(int)), cudaSuccess); + for (int cycle = 0; cycle < 4; ++cycle) { + auto stream = nvte_get_compute_stream(0); + auto event = nvte_get_compute_stream_event(0); + auto handle = nvte_get_cudnn_handle(); + ASSERT_EQ(cudnnSetStream(handle, stream), CUDNN_STATUS_SUCCESS); + manager.launch("live release test", 1, 1, 0, stream, storage, cycle); + ASSERT_EQ(cudaEventRecord(event, stream), cudaSuccess); + ASSERT_EQ(cudaEventSynchronize(event), cudaSuccess); + int value = -1; + ASSERT_EQ(cudaMemcpy(&value, storage, sizeof(int), cudaMemcpyDeviceToHost), cudaSuccess); + EXPECT_EQ(value, cycle); + const auto previous = nvte_get_cuda_state_version(); + nvte_release_cuda_state(); + EXPECT_EQ(nvte_get_cuda_state_version(), previous + 1); + EXPECT_EQ(cudaGetLastError(), cudaSuccess); + } + ASSERT_EQ(cudaFree(storage), cudaSuccess); +} +} // namespace diff --git a/tests/jax/test_cuda_context.py b/tests/jax/test_cuda_context.py new file mode 100644 index 00000000000..85a04474632 --- /dev/null +++ b/tests/jax/test_cuda_context.py @@ -0,0 +1,91 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Explicit TE cleanup while the XLA runtime and model arrays remain alive.""" + +import jax +import jax.numpy as jnp +import numpy as np +import pytest +import transformer_engine.jax as te +import transformer_engine_jax as tex +from transformer_engine.jax.layernorm import layernorm +from transformer_engine.jax import cpp_extensions as extensions +from transformer_engine.jax.quantize.tensor import GroupedNoScaleTensor + + +def test_context_loss_rejects_framework_without_mutation(): + generation = tex.get_cuda_state_version() + with pytest.raises(RuntimeError, match="JAX/XLA CUDA runtime"): + te.reset_cuda_state() + assert tex.get_cuda_state_version() == generation + + +def test_live_cleanup_preserves_arrays_and_recreates_normalization(): + device = jax.devices("gpu")[0] + x = jax.device_put(jnp.arange(32 * 128, dtype=jnp.float32).reshape(32, 128) / 1000, device) + gamma = jax.device_put(jnp.linspace(0.8, 1.2, 128), device) + beta = jax.device_put(jnp.linspace(-0.1, 0.1, 128), device) + epsilon = 1e-5 + + @jax.jit + def compute(value): + return layernorm(value, gamma, beta, "layernorm", False, epsilon) + + mean = jnp.mean(x, axis=-1, keepdims=True) + reference = (x - mean) * jax.lax.rsqrt( + jnp.mean((x - mean) ** 2, axis=-1, keepdims=True) + epsilon + ) * gamma + beta + generation = tex.get_cuda_state_version() + for _ in range(3): + np.testing.assert_allclose(compute(x), reference, rtol=1e-4, atol=1e-4) + te.release_cuda_state() + assert tex.get_cuda_state_version() > generation + generation = tex.get_cuda_state_version() + np.testing.assert_allclose(compute(x), reference, rtol=1e-4, atol=1e-4) + + +def test_live_cleanup_rebuilds_grouped_gemm_pinned_transfers(): + sizes = jnp.array([32, 64], dtype=jnp.int32) + lhs = jnp.arange(96 * 64, dtype=jnp.float16).reshape(96, 64) / 8192 + rhs = jnp.ones((2, 64, 32), dtype=jnp.float16) / 64 + left = GroupedNoScaleTensor( + data=lhs, amax=None, first_dims=sizes, last_dims=None, original_shape=lhs.shape + ) + right = GroupedNoScaleTensor( + data=rhs, amax=None, first_dims=None, last_dims=None, original_shape=rhs.shape + ) + copy = jax.jit(extensions.grouped_gemm_copy_group_sizes, static_argnames=("num_gemms",)) + compute = jax.jit( + extensions.grouped_gemm, static_argnames=("contracting_dims", "use_async_d2h_group_sizes") + ) + reference = jnp.concatenate((lhs[:32] @ rhs[0], lhs[32:] @ rhs[1])) + for _ in range(2): + copy(sizes, num_gemms=2).block_until_ready() + output = compute(left, right, contracting_dims=((1,), (1,)), use_async_d2h_group_sizes=True) + np.testing.assert_allclose(output, reference, rtol=2e-3, atol=2e-3) + te.release_cuda_state() + + +@pytest.mark.skipif(len(jax.local_devices(backend="gpu")) < 2, reason="Two CUDA devices required") +def test_global_release_preserves_arrays_and_rebuilds_plans_on_two_devices(): + compute = jax.jit(lambda x, gamma, beta: layernorm(x, gamma, beta, "layernorm", False, 1e-5)) + states = [] + for device in jax.local_devices(backend="gpu")[:2]: + with jax.default_device(device): + x = jax.device_put( + jnp.arange(8 * 128, dtype=jnp.float32).reshape(8, 128) / 1000, device + ) + gamma = jax.device_put(jnp.ones(128), device) + beta = jax.device_put(jnp.zeros(128), device) + values = np.asarray(x) + centered = values - values.mean(axis=-1, keepdims=True) + reference = centered / np.sqrt((centered**2).mean(axis=-1, keepdims=True) + 1e-5) + states.append((x, gamma, beta, reference)) + for _ in range(3): + for x, gamma, beta, reference in states: + np.testing.assert_allclose(compute(x, gamma, beta), reference, rtol=1e-4, atol=1e-4) + version = tex.get_cuda_state_version() + te.release_cuda_state() + assert tex.get_cuda_state_version() == version + 1 diff --git a/tests/jax/test_mxfp8_cutedsl_backend.py b/tests/jax/test_mxfp8_cutedsl_backend.py index 2ee82f8c5d5..268cfe753f1 100644 --- a/tests/jax/test_mxfp8_cutedsl_backend.py +++ b/tests/jax/test_mxfp8_cutedsl_backend.py @@ -22,6 +22,8 @@ from transformer_engine.common import _get_shared_object_file from transformer_engine.common.CuTeDSL.utils import device_compute_capability +import transformer_engine.jax as te +import transformer_engine_jax as native_tex from transformer_engine.jax import cpp_extensions as tex from transformer_engine.jax.quantize import ( QuantizerFactory, @@ -185,6 +187,8 @@ def get_cfg_key(method, act_desc, in_dtype, fp8_dtype, q_layout): + "_".join("1" if f else "0" for f in flags) + "_" + desc + + f"_device_{jax.devices('gpu')[0].local_hardware_id}_generation_" + + str(native_tex.get_cuda_state_version()) ) @@ -255,6 +259,35 @@ def run_test_case(method, act_type, act_desc, shape, q_layout, in_dtype, fp8_dty # Test cases with only cast kernels (mirrors C++ test's OperatorTest_FusedCastMXFP8_CastOnly). +def test_release_retires_and_recompiles_cutedsl_executors(): + """Release JAX's native and Python CuTeDSL owners before recompiling.""" + te.release_cuda_state() + previous_key = None + for _ in range(2): + run_test_case( + "CAST_ONLY", + ("gelu",), + "none", + (128, 128), + QuantizeLayout.ROWWISE_COLWISE, + jnp.bfloat16, + jnp.float8_e4m3fn, + ) + key = get_cfg_key( + "CAST_ONLY", "none", jnp.bfloat16, jnp.float8_e4m3fn, QuantizeLayout.ROWWISE_COLWISE + ) + assert key != previous_key + assert tvm_ffi.get_global_func(key, allow_missing=True) is not None + version = native_tex.get_cuda_state_version() + with pytest.raises(RuntimeError, match="CuTeDSL"): + native_tex.reset_cuda_state() + assert native_tex.get_cuda_state_version() == version + te.release_cuda_state() + assert native_tex.get_cuda_state_version() > version + assert tvm_ffi.get_global_func(key, allow_missing=True) is None + previous_key = key + + @pytest.mark.parametrize("shape", MATRIX_SIZES, ids=get_shape_id) @pytest.mark.parametrize("q_layout", Q_LAYOUTS, ids=get_layout_id) @pytest.mark.parametrize("in_dtype", IN_DTYPES, ids=get_dtype_id) diff --git a/tests/pytorch/attention/test_flex_attention.py b/tests/pytorch/attention/test_flex_attention.py index beed4069917..bbdc0ba17e0 100644 --- a/tests/pytorch/attention/test_flex_attention.py +++ b/tests/pytorch/attention/test_flex_attention.py @@ -9,7 +9,7 @@ import pytest import torch -from transformer_engine.pytorch import DotProductAttention, is_bf16_available +from transformer_engine.pytorch import DotProductAttention, is_bf16_available, release_cuda_state from transformer_engine.pytorch.attention.dot_product_attention import _attention_backends import transformer_engine.pytorch.attention.dot_product_attention.flex_attention as flex_attention from transformer_engine.pytorch.utils import get_device_compute_capability @@ -705,3 +705,24 @@ def test_dot_product_attention_score_mod(dtype, qkv_format, score_mod_case, scal torch.testing.assert_close(q.grad, q_ref.grad, **tols) torch.testing.assert_close(k.grad, k_ref.grad, **tols) torch.testing.assert_close(v.grad, v_ref.grad, **tols) + + if ( + dtype == torch.bfloat16 + and qkv_format == "bshd" + and score_mod_case == "causal" + and not scalar_loss + ): + device = q.device.index + assert flex_attention._cudnn_score_mod_graph_cache + release_cuda_state() + assert torch.device("cuda", device) not in flex_attention._cudnn_score_mod_handles + assert not flex_attention._cudnn_score_mod_graph_cache + for tensor in (q, k, v): + tensor.grad = None + actual = flex_attn( + q, k, v, qkv_format=qkv_format, attn_mask_type="no_mask", **score_mod_kwargs + ) + actual.backward(d_out) + torch.testing.assert_close(actual, out_ref, **tols) + for tensor, reference in zip((q, k, v), (q_ref, k_ref, v_ref)): + torch.testing.assert_close(tensor.grad, reference.grad, **tols) diff --git a/tests/pytorch/distributed/run_cuda_context.py b/tests/pytorch/distributed/run_cuda_context.py new file mode 100644 index 00000000000..f29fbee61a8 --- /dev/null +++ b/tests/pytorch/distributed/run_cuda_context.py @@ -0,0 +1,63 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Run with torchrun: live TE cleanup must retire Userbuffers on every rank.""" + +from datetime import timedelta +import os + +import torch +import torch.distributed as dist +import transformer_engine.pytorch as te +import transformer_engine_torch as tex +from transformer_engine.pytorch.module.base import UserBufferQuantizationMode, get_ub + + +def main(): + device = int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(device) + dist.init_process_group( + "nccl", timeout=timedelta(seconds=90), device_id=torch.device("cuda", device) + ) + world_size = dist.get_world_size() + try: + for _ in range(2): + te.initialize_ub( + (32, 128), + tp_size=world_size, + quantization_modes=[UserBufferQuantizationMode.NONE], + bootstrap_backend="gloo", + ) + owner = get_ub("qkv_fprop", False) + generation = tex.get_cuda_state_version() + try: + tex.reset_cuda_state() + except RuntimeError as error: + assert "communication" in str(error) + else: + raise AssertionError("Active communication must reject post-loss reset") + assert tex.get_cuda_state_version() == generation + # A retained public owner must fail explicitly even after the global + # manager has been cleared. Destruction must happen while NCCL is live. + dist.barrier() + try: + te.release_cuda_state() + except RuntimeError as error: + assert "Release all owners" in str(error) + else: + raise AssertionError("A retained communication owner must reject release") + del owner + dist.barrier() + te.release_cuda_state() + value = torch.tensor(float(dist.get_rank() + 1), device="cuda") + dist.all_reduce(value) + torch.testing.assert_close(value, value.new_tensor(world_size * (world_size + 1) / 2)) + if dist.get_rank() == 0: + print("CUDA STATE CLEANUP PASSED") + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tests/pytorch/distributed/test_comm_gemm_overlap.py b/tests/pytorch/distributed/test_comm_gemm_overlap.py index a7c311fe9d5..e8fa41acb99 100644 --- a/tests/pytorch/distributed/test_comm_gemm_overlap.py +++ b/tests/pytorch/distributed/test_comm_gemm_overlap.py @@ -87,6 +87,23 @@ def _assert_subprocess_succeeded(result): ) +@pytest.mark.skipif(tex.ubuf_built_with_mpi(), reason="Lifecycle test uses torchrun bootstrap") +def test_cuda_state_cleanup(): + """Exercise retained-owner errors and repeated Userbuffers bootstrap/cleanup.""" + test_env = dict(os.environ) + test_env["PYTHONPATH"] = str(TEST_ROOT.parents[2]) + os.pathsep + test_env.get("PYTHONPATH", "") + result = subprocess.run( + ["torchrun", "--standalone", "--nproc_per_node=2", str(TEST_ROOT / "run_cuda_context.py")], + env=test_env, + capture_output=True, + text=True, + check=False, + timeout=240, + ) + assert result.returncode == 0, result.stdout[-4000:] + result.stderr[-4000:] + assert "CUDA STATE CLEANUP PASSED" in result.stdout + + # Fall back on CUDA IPC if the platform does not support CUDA multicast if not tex.device_supports_multicast(): os.environ["UB_SKIPMC"] = "1" diff --git a/tests/pytorch/mxfp8/test_mxfp8_cutedsl_backend.py b/tests/pytorch/mxfp8/test_mxfp8_cutedsl_backend.py index 5d7feeb6ce6..5e9cf2719e4 100644 --- a/tests/pytorch/mxfp8/test_mxfp8_cutedsl_backend.py +++ b/tests/pytorch/mxfp8/test_mxfp8_cutedsl_backend.py @@ -241,6 +241,8 @@ def get_cfg_key(method, act, in_dtype, fp8_dtype, rowwise, colwise, swizzled): + "_".join("1" if f else "0" for f in flags) + "_" + desc + + f"_device_{torch.cuda.current_device()}_generation_" + + str(tex.get_cuda_state_version()) ) @@ -334,6 +336,34 @@ def test_cast_only(swizzled, fp8_dtype, in_dtype, block_size, shape): run_test_case("CAST_ONLY", IDENTITY, shape, block_size, in_dtype, fp8_dtype, swizzled) +def test_release_retires_and_recompiles_cutedsl_executors(): + """Do not retain a context-bound executor through a live-context release.""" + x = torch.randn(128, 128, device="cuda", dtype=torch.bfloat16) + quantizer = MXFP8Quantizer(fp8_dtype=tex.DType.kFloat8E4M3, rowwise=True, columnwise=True) + set_cutedsl_backend(False) + reference = extract_quantized_output(quantizer(x), True, True, False) + set_cutedsl_backend(True) + try: + for _ in range(2): + output = extract_quantized_output(quantizer(x), True, True, False) + for name, expected in reference.items(): + assert torch.equal(output[name], expected) + key = get_cfg_key( + "CAST_ONLY", IDENTITY, x.dtype, tex.DType.kFloat8E4M3, True, True, False + ) + assert tvm_ffi.get_global_func(key, allow_missing=True) is not None + # Even a mistaken post-loss call must reject active opaque executors + # before advancing the generation or mutating registered state. + generation = tex.get_cuda_state_version() + with pytest.raises(RuntimeError, match="CuTeDSL"): + tex.reset_cuda_state() + assert tex.get_cuda_state_version() == generation + te.release_cuda_state() + assert tvm_ffi.get_global_func(key, allow_missing=True) is None + finally: + set_cutedsl_backend(False) + + def test_cast_only_rowwise_specialized_grid_y_overflow(): """Fall back when the specialized rowwise launch would exceed CUDA's grid.y limit.""" # The specialized kernel covers four rows per CTA, so this shape would require diff --git a/tests/pytorch/mxfp8/test_mxfp8_requantize_cutedsl.py b/tests/pytorch/mxfp8/test_mxfp8_requantize_cutedsl.py index 81d12771566..286dde9bab4 100644 --- a/tests/pytorch/mxfp8/test_mxfp8_requantize_cutedsl.py +++ b/tests/pytorch/mxfp8/test_mxfp8_requantize_cutedsl.py @@ -4,6 +4,8 @@ """Validate compact-input requantization against independent PyTorch arithmetic.""" +import os + import pytest import torch @@ -12,6 +14,9 @@ cuda = pytest.importorskip("cuda.bindings.driver") from cutlass.cute.runtime import from_dlpack +import transformer_engine.pytorch as te +import transformer_engine_torch as tex +from transformer_engine.common.CuTeDSL._cuda_state import _registered_kernels from transformer_engine.common.CuTeDSL.cast.mxfp8 import requantize_mxfp8 from transformer_engine.common.CuTeDSL.cast.mxfp8.requantize_mxfp8 import GroupedRequantize from mxfp8_utils import swizzle_mxfp8_scale @@ -41,6 +46,75 @@ def columnwise_reference(values): return quantized.reshape(rows, hidden).view(torch.uint8), (exponent + 127).to(torch.uint8) +@pytest.mark.parametrize("device_count", [1, 2]) +def test_release_retires_and_recompiles_requantization_executors(device_count): + """Rebuild shape-specialized executors on each device after global cleanup.""" + if os.environ.get("NVTE_ENABLE_CUTEDSL_BACKEND", "0") == "0": + pytest.skip("NVTE_ENABLE_CUTEDSL_BACKEND is not set") + if torch.cuda.device_count() < device_count: + pytest.skip(f"Requires {device_count} CUDA devices") + tvm_ffi = pytest.importorskip("tvm_ffi") + rows, hidden = 256, 256 + previous_keys = set() + te.release_cuda_state() + for _ in range(2): + for device in range(device_count): + with torch.cuda.device(device): + x = torch.randn(rows, hidden, device="cuda", dtype=torch.bfloat16) + splits = torch.tensor([128, 128], device="cuda", dtype=torch.int64) + wire_quantizer = te.MXFP8Quantizer( + fp8_dtype=te.DType.kFloat8E4M3, rowwise=True, columnwise=False + ) + wire_quantizer.optimize_for_gemm = False + wire = tex.group_quantize(x, wire_quantizer, 2, splits) + decoded = tex.group_dequantize(wire, te.DType.kBFloat16).rowwise_data.view( + rows, hidden + ) + expected = [columnwise_reference(group) for group in decoded.split(128)] + quantizer = te.MXFP8Quantizer( + fp8_dtype=te.DType.kFloat8E4M3, rowwise=True, columnwise=True + ) + quantizer.optimize_for_gemm = True + actual = tex.group_requantize_inplace( + wire, quantizer, 2, splits, te.DType.kBFloat16, return_dequantized=True + ) + torch.testing.assert_close(actual, decoded, rtol=0, atol=0) + torch.testing.assert_close( + wire.columnwise_data.view(torch.uint8).flatten(), + torch.cat([data.flatten() for data, _ in expected]), + rtol=0, + atol=0, + ) + torch.testing.assert_close( + wire.columnwise_scale_inv.flatten(), + torch.cat( + [swizzle_mxfp8_scale(128, hidden, sf, True).flatten() for _, sf in expected] + ), + rtol=0, + atol=0, + ) + keys = {key for key in _registered_kernels if key.startswith("cutedsl_mxfp8_requant_")} + assert len(keys) == device_count + assert keys.isdisjoint(previous_keys) + for key in keys: + assert tvm_ffi.get_global_func(key, allow_missing=True) is not None + version = tex.get_cuda_state_version() + with pytest.raises(RuntimeError, match="CuTeDSL"): + tex.reset_cuda_state() + assert tex.get_cuda_state_version() == version + # Both native cache key types share the Python executor registry. + for device in range(device_count): + with torch.cuda.device(device): + quantizer = te.MXFP8Quantizer(fp8_dtype=te.DType.kFloat8E4M3) + quantizer(torch.ones((128, 128), device="cuda", dtype=torch.bfloat16)) + te.release_cuda_state() + assert tex.get_cuda_state_version() > version + assert not _registered_kernels + for key in keys: + assert tvm_ffi.get_global_func(key, allow_missing=True) is None + previous_keys = keys + + @pytest.mark.parametrize("return_dequantized", [False, True]) @pytest.mark.parametrize("hidden", [128, 256, 384, 512, 4096, 7168]) @pytest.mark.parametrize("input_dtype", [torch.float8_e4m3fn, torch.float8_e5m2]) diff --git a/tests/pytorch/test_cuda_context.py b/tests/pytorch/test_cuda_context.py new file mode 100644 index 00000000000..e83d81f0123 --- /dev/null +++ b/tests/pytorch/test_cuda_context.py @@ -0,0 +1,276 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Restart-boundary cleanup without replacing PyTorch's CUDA runtime.""" + +import pytest +import torch +import transformer_engine.pytorch as te +import transformer_engine_torch as tex +from transformer_engine.pytorch.utils import get_cached_ones_tensor +from transformer_engine.pytorch.cpp_extensions.gemm import ( + get_cublas_workspace, + strided_batched_gemm, +) +from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer +from transformer_engine.common.recipe import DelayedScaling +from transformer_engine.pytorch.quantization import FP8GlobalStateManager +from transformer_engine.pytorch.tensor.grouped_tensor import GroupedTensor +from transformer_engine.pytorch.cpp_extensions.gemm import general_grouped_gemm_for_grouped_tensor + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_context_loss_rejects_initialized_framework_without_mutation(): + x = torch.ones(32, device="cuda") + generation = tex.get_cuda_state_version() + with pytest.raises(RuntimeError, match="initialized PyTorch CUDA runtime"): + te.reset_cuda_state() + assert tex.get_cuda_state_version() == generation + torch.testing.assert_close(x, torch.ones_like(x)) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_live_cleanup_rebuilds_gemm_caches_and_preserves_model(): + device = torch.cuda.current_device() + model = te.Linear(128, 128, bias=False, params_dtype=torch.float32) + x = torch.randn(8, 128, device="cuda") + reference = torch.nn.functional.linear(x, model.weight) + before = model(x) + old_ones = get_cached_ones_tensor(32, torch.float32, x.device) + old_scratch = get_cublas_workspace(device, False, False) + cpu_ones = get_cached_ones_tensor(16, torch.float32, torch.device("cpu")) + initial = tex.get_cuda_state_version() + for _ in range(3): + te.release_cuda_state() + assert tex.get_cuda_state_version() > initial + initial = tex.get_cuda_state_version() + torch.testing.assert_close(model(x), reference) + torch.testing.assert_close(before, reference) + torch.testing.assert_close(old_ones, torch.ones_like(old_ones)) + assert get_cached_ones_tensor(32, torch.float32, x.device) is not old_ones + assert get_cublas_workspace(device, False, False) is not old_scratch + assert get_cached_ones_tensor(16, torch.float32, torch.device("cpu")) is cpu_ones + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_live_cleanup_rebuilds_strided_batched_gemm_handle(): + a = torch.ones((2, 16, 16), dtype=torch.bfloat16, device="cuda") + b = a * 2 + b[1] *= 2 + output = torch.empty_like(a) + expected = torch.bmm(b, a.transpose(1, 2)) + for _ in range(3): + strided_batched_gemm(a, b, output, layout="TN") + torch.testing.assert_close(output, expected, rtol=0, atol=0) + te.release_cuda_state() + + +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Two CUDA devices required") +def test_global_cleanup_rebuilds_all_device_caches_and_preserves_current_device(): + a = get_cached_ones_tensor(32, torch.float32, torch.device("cuda:0")) + b = get_cached_ones_tensor(32, torch.float32, torch.device("cuda:1")) + cpu = get_cached_ones_tensor(32, torch.float32, torch.device("cpu")) + scratch = [get_cublas_workspace(device, False, False) for device in (0, 1)] + version = tex.get_cuda_state_version() + with torch.cuda.device(1): + te.release_cuda_state() + assert torch.cuda.current_device() == 1 + assert tex.get_cuda_state_version() == version + 1 + for device, old in enumerate((a, b)): + assert get_cached_ones_tensor(32, torch.float32, torch.device("cuda", device)) is not old + assert get_cublas_workspace(device, False, False) is not scratch[device] + torch.testing.assert_close(old, torch.ones_like(old)) + assert get_cached_ones_tensor(32, torch.float32, torch.device("cpu")) is cpu + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 10, + reason="Blackwell required for grouped MXFP8", +) +def test_grouped_tma_storage_is_rebuilt_after_release(): + quantizer = MXFP8Quantizer(fp8_dtype=tex.DType.kFloat8E4M3) + quantizer.set_usage(rowwise=True, columnwise=True) + for groups in (2, 64): + first = [128] * groups + last = [128] * groups + last[-1] = 256 + x = torch.randn( + 1, sum(m * n for m, n in zip(first, last)), device="cuda", dtype=torch.bfloat16 + ) + rows = torch.tensor(first, device="cuda", dtype=torch.int64) + cols = torch.tensor(last, device="cuda", dtype=torch.int64) + expected = tex.group_quantize(x, quantizer, groups, rows, cols) + for _ in range(3): + te.release_cuda_state() + actual = tex.group_quantize(x, quantizer, groups, rows, cols) + assert torch.equal(actual.rowwise_data, expected.rowwise_data) + assert torch.equal(actual.columnwise_data, expected.columnwise_data) + assert torch.equal(actual.scale_inv, expected.scale_inv) + assert torch.equal(actual.columnwise_scale_inv, expected.columnwise_scale_inv) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_release_is_rejected_during_graph_capture(): + stream = torch.cuda.Stream() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + torch.ones(1, device="cuda").add_(1) + with pytest.raises(RuntimeError, match="outside graph capture"): + te.release_cuda_state() + + +@pytest.mark.skipif(not te.is_fp8_available(), reason="FP8 required") +def test_release_preserves_fp8_history_and_rebuilds_registrations(): + model = te.Linear(128, 128, params_dtype=torch.bfloat16) + x = torch.randn(32, 128, device="cuda", dtype=torch.bfloat16, requires_grad=True) + recipe = DelayedScaling(amax_history_len=4) + for _ in range(2): + with te.autocast(recipe=recipe): + model(x).float().square().mean().backward() + index_key = FP8GlobalStateManager.get_buffer_info() + assert index_key in model.fp8_meta + history = model.fp8_meta["scaling_fwd"].amax_history.clone() + scale = model.fp8_meta["scaling_fwd"].scale.clone() + te.release_cuda_state() + assert index_key not in model.fp8_meta + torch.testing.assert_close(model.fp8_meta["scaling_fwd"].amax_history, history) + torch.testing.assert_close(model.fp8_meta["scaling_fwd"].scale, scale) + model.zero_grad(set_to_none=True) + x.grad = None + with te.autocast(recipe=recipe): + output = model(x) + output.float().square().mean().backward() + assert index_key in model.fp8_meta + assert torch.isfinite(output).all() + assert torch.isfinite(x.grad).all() + assert torch.isfinite(model.weight.grad).all() + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_release_rejects_active_fp8_autocast(): + generation = tex.get_cuda_state_version() + with te.autocast(): + with pytest.raises(RuntimeError, match="outside FP8 autocast"): + te.release_cuda_state() + assert tex.get_cuda_state_version() == generation + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_release_recreates_sequence_and_nvfp4_tensor_caches(): + from transformer_engine.pytorch.attention.dot_product_attention.utils import get_full_cu_seqlens + from transformer_engine.pytorch.attention.dot_product_attention.context_parallel import ( + get_seq_chunk_ids_for_reordering_before_attn, + ) + from transformer_engine.pytorch.tensor.nvfp4_tensor import get_rht_matrix + from transformer_engine.pytorch.tensor.storage.nvfp4_tensor_storage import _fp4_e2m1_vals + + device = torch.device("cuda", torch.cuda.current_device()) + values = ( + get_full_cu_seqlens(4, 128, device), + get_seq_chunk_ids_for_reordering_before_attn(2, device), + get_rht_matrix(False, device.index), + _fp4_e2m1_vals(device, torch.float32), + ) + te.release_cuda_state() + recreated = ( + get_full_cu_seqlens(4, 128, device), + get_seq_chunk_ids_for_reordering_before_attn(2, device), + get_rht_matrix(False, device.index), + _fp4_e2m1_vals(device, torch.float32), + ) + for old, new in zip(values, recreated): + assert old is not new + torch.testing.assert_close(old, new) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or tex.get_cublasLt_build_version() < 130300, + reason="cuBLASLt grouped GEMM requires CUDA 13.3+", +) +def test_live_cleanup_recreates_grouped_gemm_handle(): + device = torch.device("cuda", torch.cuda.current_device()) + groups, m, n, k = 2, 32, 64, 64 + + def grouped(rows, cols): + return GroupedTensor.make_grouped_tensor( + num_tensors=groups, + first_dims=None, + last_dims=None, + logical_first_dim=groups * rows, + logical_last_dim=cols, + quantizer=None, + device=device, + dtype=torch.bfloat16, + ) + + weight, value, output = grouped(n, k), grouped(m, k), grouped(m, n) + weight.rowwise_data.copy_((torch.arange(groups * n * k, device=device) % 7 - 3) / 8) + value.rowwise_data.copy_((torch.arange(groups * m * k, device=device) % 5 - 2) / 8) + reference = torch.bmm( + value.rowwise_data.view(groups, m, k), + weight.rowwise_data.view(groups, n, k).transpose(1, 2), + ) + for _ in range(3): + general_grouped_gemm_for_grouped_tensor(weight, value, output, layout="TN") + torch.testing.assert_close(output.rowwise_data.view_as(reference), reference) + te.release_cuda_state() + + +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Two CUDA devices required") +def test_global_release_rejects_capture_on_another_device_before_mutation(): + cached = [get_cached_ones_tensor(32, torch.float32, torch.device("cuda", d)) for d in (0, 1)] + version = tex.get_cuda_state_version() + with torch.cuda.device(1): + stream = torch.cuda.Stream() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + torch.ones(1, device="cuda:1").add_(1) + with torch.cuda.device(0): + with pytest.raises(RuntimeError, match="outside graph capture"): + te.release_cuda_state() + assert tex.get_cuda_state_version() == version + for device, old in enumerate(cached): + assert get_cached_ones_tensor(32, torch.float32, torch.device("cuda", device)) is old + + +@pytest.mark.skipif( + torch.cuda.device_count() < 2 or not te.is_fp8_available(), + reason="Two FP8 CUDA devices required", +) +def test_global_release_preserves_fp8_history_on_two_devices(monkeypatch): + # The existing fused recipe updater uses the calling device's stream even + # when processing another device's reduction bucket. Exercise the supported + # unfused path here; the single-device regression above covers fused update. + monkeypatch.setenv("NVTE_UNFUSED_FP8_UPDATE", "1") + states = [] + key = FP8GlobalStateManager.get_buffer_info() + for device in (0, 1): + with torch.cuda.device(device): + # Delayed-scaling buffers are keyed by recipe/group, not by device. + # Keep the two models in independent reduction buckets. + recipe = DelayedScaling(amax_history_len=4 + device) + model = te.Linear(128, 128, params_dtype=torch.bfloat16) + x = torch.randn(32, 128, device="cuda", dtype=torch.bfloat16, requires_grad=True) + with te.autocast(recipe=recipe): + model(x).float().square().mean().backward() + assert key in model.fp8_meta + states.append((model, x, recipe)) + # A later model's autocast also updates earlier reduction buckets. Snapshot + # both histories at the actual restart boundary, after both warmup passes. + histories = [model.fp8_meta["scaling_fwd"].amax_history.clone() for model, _, _ in states] + te.release_cuda_state() + for (model, _, _), history in zip(states, histories): + assert key not in model.fp8_meta + torch.testing.assert_close(model.fp8_meta["scaling_fwd"].amax_history, history) + for device, (model, x, recipe) in enumerate(states): + with torch.cuda.device(device): + model.zero_grad(set_to_none=True) + x.grad = None + with te.autocast(recipe=recipe): + output = model(x) + output.float().square().mean().backward() + assert key in model.fp8_meta + assert torch.isfinite(x.grad).all() + assert torch.isfinite(model.weight.grad).all() + te.release_cuda_state() diff --git a/transformer_engine/common/CMakeLists.txt b/transformer_engine/common/CMakeLists.txt index f90f74449c5..4e4b4725e10 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -269,6 +269,7 @@ list(APPEND transformer_engine_cpp_sources normalization/rtc_dispatch.cpp normalization/layernorm/ln_api.cpp normalization/rmsnorm/rmsnorm_api.cpp + util/cuda_context.cpp util/cuda_driver.cpp util/cuda_nvml.cpp util/cuda_runtime.cpp diff --git a/transformer_engine/common/CuTeDSL/__init__.py b/transformer_engine/common/CuTeDSL/__init__.py index 15aae1aba2d..ed9aca9fc37 100644 --- a/transformer_engine/common/CuTeDSL/__init__.py +++ b/transformer_engine/common/CuTeDSL/__init__.py @@ -10,6 +10,7 @@ import tvm_ffi +from transformer_engine.common.CuTeDSL._cuda_state import release_cuda_state from transformer_engine.common.CuTeDSL.cast.mxfp8.quantize_mxfp8_common import ( get_mxfp8_quantization_function, ) @@ -28,3 +29,4 @@ def register_cutedsl_backends(): tvm_ffi.register_global_func( "get_mxfp8_requantization_function", get_mxfp8_requantization_function, override=True ) + tvm_ffi.register_global_func("release_cutedsl_cuda_state", release_cuda_state, override=True) diff --git a/transformer_engine/common/CuTeDSL/_cuda_state.py b/transformer_engine/common/CuTeDSL/_cuda_state.py new file mode 100644 index 00000000000..30685b9b6a0 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/_cuda_state.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Lifetime of TE-owned CuTeDSL executors registered through TVM-FFI.""" + +import tvm_ffi + + +# Keep executors alive until native references and registry entries are released. +_registered_kernels = {} + + +def register_kernel(name: str, compiled) -> None: + """Register a compiled executor and retain its Python owner until cleanup.""" + native = getattr(compiled, "__tvm_ffi_object__", lambda: None)() + tvm_ffi.register_global_func(name, native if native is not None else compiled, override=True) + _registered_kernels[name] = compiled + + +def release_cuda_state(device=None) -> None: + """Remove TE-owned compiled entries globally or for one live cleanup callback.""" + for name in tuple(_registered_kernels): + if device is not None and f"_device_{device}_generation_" not in name: + continue + tvm_ffi.remove_global_func(name) + del _registered_kernels[name] diff --git a/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_common.py b/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_common.py index 8a66b55e48f..6200df3f11c 100644 --- a/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_common.py +++ b/transformer_engine/common/CuTeDSL/cast/mxfp8/quantize_mxfp8_common.py @@ -14,6 +14,7 @@ from cutlass import Boolean, Float32, Int32, Int64 from cuda.bindings.driver import CUstream # pylint: disable=no-name-in-module import tvm_ffi +from transformer_engine.common.CuTeDSL._cuda_state import register_kernel from transformer_engine.common.CuTeDSL.utils import ( str_to_cutlass_dtype, @@ -594,10 +595,7 @@ def get_mxfp8_quantization_function( # https://github.com/NVIDIA/cutlass/pull/3589 recommends using an explicit positional only marker (/) # in the function signature, however it is not merged and it is something easy to miss and silently # introduce unnecessarry overhead. - native = getattr(compiled, "__tvm_ffi_object__", lambda: None)() - tvm_ffi.register_global_func( - fn_name, native if native is not None else compiled, override=True - ) + register_kernel(fn_name, compiled) return True except Exception as e: # pylint: disable=broad-exception-caught logger.error( diff --git a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py index 00cac332891..e7ef834afac 100644 --- a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py +++ b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py @@ -21,6 +21,7 @@ from cutlass.cute.typing import AddressSpace from cutlass.memory import SmemAllocator import tvm_ffi +from transformer_engine.common.CuTeDSL._cuda_state import register_kernel logger = logging.getLogger("transformer_engine.cutedsl.requantize") @@ -1001,10 +1002,7 @@ def tensor(element_type, shape): cute.runtime.make_fake_stream(), options="--enable-tvm-ffi", ) - native = getattr(compiled, "__tvm_ffi_object__", lambda: None)() - tvm_ffi.register_global_func( - fn_name, native if native is not None else compiled, override=True - ) + register_kernel(fn_name, compiled) return True except Exception as error: # pylint: disable=broad-exception-caught logger.warning("CuTeDSL grouped requantization unavailable; using CUDA: %s", error) diff --git a/transformer_engine/common/cast/mxfp8/quantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/quantize_mxfp8_cutedsl.cuh index 6380dda21da..db40e1aefb2 100644 --- a/transformer_engine/common/cast/mxfp8/quantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/quantize_mxfp8_cutedsl.cuh @@ -62,7 +62,7 @@ struct MXFP8QuantConfig { } std::optional get_kernel() const { - static TVMFFIConfigCache &cache = TVMFFIConfigCache::create(); + static auto &cache = TVMFFIConfigCache<>::create(); return cache.get_or_load(*this); } diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index ca78a77fa4d..945ea2dc161 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -7,11 +7,8 @@ #ifndef TRANSFORMER_ENGINE_COMMON_CAST_MXFP8_REQUANTIZE_MXFP8_CUTEDSL_CUH_ #define TRANSFORMER_ENGINE_COMMON_CAST_MXFP8_REQUANTIZE_MXFP8_CUTEDSL_CUH_ -#include #include -#include #include -#include #include "../../common.h" #include "../../tvm_ffi_bridge.h" @@ -45,29 +42,12 @@ struct MXFP8RequantConfig { .value_or(false); } + std::string to_id() const { return to_key(); } + std::optional get_kernel() const { - using namespace tvm_ffi_bridge; - // Shape-specialized keys do not fit the quantization cache's 32-bit ID. - // Preserve cached TVM handles until process exit, as TVMFFIConfigCache does. - struct Cache { - std::shared_mutex mutex; - std::unordered_map> kernels; - }; - static auto *cache = new Cache(); - auto ¢ral = TVMFFICentral::getInstance(); - if (!central.get_cutedsl_backend_enabled()) return std::nullopt; - const auto key = to_key(); - { - std::shared_lock lock(cache->mutex); - auto it = cache->kernels.find(key); - if (it != cache->kernels.end()) return it->second; - } - std::unique_lock lock(cache->mutex); - auto it = cache->kernels.find(key); - if (it != cache->kernels.end()) return it->second; - auto kernel = central.load_tvm_ffi_function(*this); - cache->kernels.emplace(key, kernel); - return kernel; + // Requantization keys include shapes and do not fit the quantization cache's 32-bit ID. + static auto &cache = tvm_ffi_bridge::TVMFFIConfigCache::create(); + return cache.get_or_load(*this); } }; diff --git a/transformer_engine/common/comm_gemm/comm_gemm.cpp b/transformer_engine/common/comm_gemm/comm_gemm.cpp index b05d7d7eeab..7eae3edd13d 100644 --- a/transformer_engine/common/comm_gemm/comm_gemm.cpp +++ b/transformer_engine/common/comm_gemm/comm_gemm.cpp @@ -20,6 +20,8 @@ #include #include "../common.h" +#include "../util/cuda_context.h" +#include "../util/cuda_runtime.h" #include "../util/logging.h" #ifdef NVTE_WITH_CUBLASMP @@ -150,6 +152,7 @@ struct NVTECommGemmCtx { CudaDeviceFloats device_scalars; void* workspace; size_t workspace_size; + std::shared_ptr context_lifetime; }; namespace { @@ -663,6 +666,8 @@ NVTECommGemmCtx* nvte_comm_gemm_ctx_create(ncclComm_t comm, int nranks, int rank .device_scalars = std::move(device_scalars), .workspace = nullptr, .workspace_size = 0, + .context_lifetime = std::make_shared( + transformer_engine::cuda::current_device(), "cuBLASMp communication context"), }; } diff --git a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp index b8ba4c500d3..44d2d64c17d 100644 --- a/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp +++ b/transformer_engine/common/comm_gemm_overlap/comm_gemm_overlap.cpp @@ -10,9 +10,13 @@ #include #include +#include +#include +#include #include #include "common/common.h" +#include "common/util/cuda_context.h" #include "common/util/cuda_driver.h" #include "common/util/cuda_runtime.h" #include "common/util/logging.h" @@ -34,6 +38,24 @@ bool nvte_built_with_cublasmp() { namespace transformer_engine { +namespace { +struct OverlapLifetimes { + std::mutex mutex; + std::map> owners; +}; +OverlapLifetimes &overlap_lifetimes() { + static auto &state = *new OverlapLifetimes; + return state; +} +void register_overlap(const CommOverlapCore *owner) { + auto &state = overlap_lifetimes(); + std::lock_guard lock(state.mutex); + state.owners.emplace(owner, + std::make_unique( + cuda::current_device(), "Userbuffers communication overlap object")); +} +} // namespace + namespace { std::vector shape_to_vector(const NVTEShape &shape) { @@ -77,6 +99,7 @@ CommOverlapCore::CommOverlapCore(int myrank, int numranks, int mylocal, int numl initialize(tp_size, num_splits, num_max_streams, comm_cga_size, gemm_priority, comm_priority, num_comm_sm, set_sm_margin, use_ce, atomic_gemm); + register_overlap(this); } // Constructor for cuBLASMp backend @@ -178,6 +201,11 @@ void CommOverlapCore::initialize(int tp_size, int num_splits, int num_max_stream } CommOverlapCore::~CommOverlapCore() { + { + auto &state = overlap_lifetimes(); + std::lock_guard lock(state.mutex); + state.owners.erase(this); + } if (_with_cublasmp) { nvte_comm_gemm_ctx_destroy(_cublasmp_ctx); } else { diff --git a/transformer_engine/common/cudnn_utils.cpp b/transformer_engine/common/cudnn_utils.cpp index 718147ff5d8..4929c8710dd 100644 --- a/transformer_engine/common/cudnn_utils.cpp +++ b/transformer_engine/common/cudnn_utils.cpp @@ -86,6 +86,8 @@ void CreateCuDNNHandle(cudnnHandle_t* handle) { NVTE_CHECK_CUDNN(cudnnCreate(handle)); } +void DestroyCuDNNHandle(cudnnHandle_t handle) { NVTE_CHECK_CUDNN(cudnnDestroy(handle)); } + } // namespace detail } // namespace transformer_engine diff --git a/transformer_engine/common/cudnn_utils.h b/transformer_engine/common/cudnn_utils.h index 712268639ba..01283b5bd6a 100644 --- a/transformer_engine/common/cudnn_utils.h +++ b/transformer_engine/common/cudnn_utils.h @@ -21,6 +21,7 @@ namespace transformer_engine { namespace detail { void CreateCuDNNHandle(cudnnHandle_t* handle); +void DestroyCuDNNHandle(cudnnHandle_t handle); } // namespace detail @@ -28,7 +29,8 @@ cudnnDataType_t get_cudnn_dtype(const transformer_engine::DType t); cudnn_frontend::DataType_t get_cudnn_fe_dtype(const transformer_engine::DType t); -using cudnnExecutionPlanManager = detail::HandleManager; +using cudnnExecutionPlanManager = + detail::HandleManager; } // namespace transformer_engine diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 73f7ad96dbf..ad9c53571e0 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -145,7 +145,7 @@ EPBackend& EPBackend::instance(int device) { std::lock_guard lock(devices_mutex_); auto it = devices_.find(device); if (it == devices_.end()) { - it = devices_.emplace(device, std::unique_ptr(new EPBackend())).first; + it = devices_.emplace(device, std::unique_ptr(new EPBackend(device))).first; } return *it->second; } @@ -270,6 +270,17 @@ void EPBackend::shutdown_locked() { initialized_ = false; } +void EPBackend::check_context_loss() const { + NVTE_CHECK(!initialized_, + "Active NCCL EP state cannot be freed safely after CUDA context loss. " + "Finalize EP before destroying its communicator/context, or restart the worker."); +} + +void EPBackend::release_context() { + std::lock_guard lock(mutex_); + shutdown_locked(); +} + ncclEpHandle_t EPBackend::open_handle(void* handle_mem, size_t handle_mem_size, int num_topk, size_t dispatch_output_per_expert_alignment) { size_t hm_sizes[1] = {handle_mem_size}; diff --git a/transformer_engine/common/ep/ep_backend.h b/transformer_engine/common/ep/ep_backend.h index dd9d2a4454e..ab0ad43092a 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -24,11 +24,13 @@ #include #include +#include "../util/cuda_context.h" + namespace transformer_engine { namespace ep { /*! \brief EP backend per CUDA device; owns the NCCL EP group, borrows the comm. */ -class EPBackend { +class EPBackend : public cuda_context::Resource { public: /*! \brief Access the current device's backend. Aborts if not initialized. */ static EPBackend& get(); @@ -92,7 +94,10 @@ class EPBackend { ~EPBackend(); private: - EPBackend() = default; + explicit EPBackend(int device) : cuda_context::Resource(device) {} + void check_context_loss() const override; + void release_context() override; + void invalidate_context() noexcept override {} EPBackend(const EPBackend&) = delete; EPBackend& operator=(const EPBackend&) = delete; diff --git a/transformer_engine/common/fused_attn/graph_cache.h b/transformer_engine/common/fused_attn/graph_cache.h index d52a0daf70b..15a1ad67893 100644 --- a/transformer_engine/common/fused_attn/graph_cache.h +++ b/transformer_engine/common/fused_attn/graph_cache.h @@ -23,6 +23,7 @@ #include "../common.h" #include "../cudnn_utils.h" +#include "../util/cuda_context.h" #include "config_and_params.h" #include "graph_cache_debug.h" @@ -42,7 +43,10 @@ struct CacheEntry { // The graph cache; a process-wide map that maps a normalized FusedAttnConfig to a CacheEntry template -struct GraphCache { +struct GraphCache : cuda_context::Resource { + explicit GraphCache(int device) : cuda_context::Resource(device) {} + void invalidate_context() noexcept override { entries.clear(); } + void release_context() override { entries.clear(); } std::mutex mutex; std::map>> entries; }; @@ -132,9 +136,21 @@ template auto get_graph(const FusedAttnConfig &cfg, cudnnHandle_t handle) { // Never destroyed: destroying cached cuDNN plans calls into CUDA, which must not be used during // program termination. - static auto &cache = *new GraphCache; + using Cache = GraphCache; + static auto &mutex = *new std::mutex; + static auto &devices = *new std::map>; cfg.check_derived(); - return detail::cache_graph(cache, cfg.make_cache_key(kPass), kBackend, kPass, handle, + // Backend queries allow -1 to mean the current device. Registration needs + // the actual ordinal even when the query's cache key keeps that sentinel. + const int device = cfg.device_id < 0 ? cuda::current_device() : cfg.device_id; + Cache *cache; + { + std::lock_guard lock(mutex); + auto &entry = devices[device]; + if (!entry) entry = std::make_unique(device); + cache = entry.get(); + } + return detail::cache_graph(*cache, cfg.make_cache_key(kPass), kBackend, kPass, handle, [&] { return kCreateGraphFn(cfg); }); } diff --git a/transformer_engine/common/gemm/cublaslt_batched_gemm.cu b/transformer_engine/common/gemm/cublaslt_batched_gemm.cu index d329bf93f57..68bc2bc4daf 100644 --- a/transformer_engine/common/gemm/cublaslt_batched_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_batched_gemm.cu @@ -27,8 +27,13 @@ inline void CreateCublasHandle(cublasLtHandle_t *handle) { NVTE_CHECK_CUBLAS(cublasLtCreate(handle)); } +inline void DestroyCublasHandle(cublasLtHandle_t handle) { + NVTE_CHECK_CUBLAS(cublasLtDestroy(handle)); +} + using cublasHandleManager = - transformer_engine::detail::HandleManager; + transformer_engine::detail::HandleManager; uint32_t GetAlignment(uintptr_t address) { // Alignment in bytes diff --git a/transformer_engine/common/gemm/cublaslt_gemm.cu b/transformer_engine/common/gemm/cublaslt_gemm.cu index 4cb12229b44..68e2aafefde 100644 --- a/transformer_engine/common/gemm/cublaslt_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_gemm.cu @@ -29,15 +29,10 @@ namespace { /* Use CUDA const memory to store scalar 1 and 0 for cublas usage */ -__device__ __constant__ float one_device; -__device__ __constant__ float zero_device; +__device__ __constant__ float one_device = 1.0f; +__device__ __constant__ float zero_device = 0.0f; inline float *GetScalarOne() { - static std::once_flag init_flag; - std::call_once(init_flag, []() { - float one = 1.0f; - NVTE_CHECK_CUDA(cudaMemcpyToSymbol(one_device, &one, sizeof(float))); - }); // return address by cudaGetSymbolAddress float *dev_ptr; NVTE_CHECK_CUDA(cudaGetSymbolAddress(reinterpret_cast(&dev_ptr), one_device)); @@ -45,11 +40,6 @@ inline float *GetScalarOne() { } inline float *GetScalarZero() { - static std::once_flag init_flag; - std::call_once(init_flag, []() { - float zero = 0.0f; - NVTE_CHECK_CUDA(cudaMemcpyToSymbol(zero_device, &zero, sizeof(float))); - }); // return address by cudaGetSymbolAddress float *dev_ptr; NVTE_CHECK_CUDA(cudaGetSymbolAddress(reinterpret_cast(&dev_ptr), zero_device)); @@ -72,6 +62,10 @@ inline void CreateCublasHandle(cublasLtHandle_t *handle) { NVTE_CHECK_CUBLAS(cublasLtCreate(handle)); } +inline void DestroyCublasHandle(cublasLtHandle_t handle) { + NVTE_CHECK_CUBLAS(cublasLtDestroy(handle)); +} + /* Parameters for cuBLAS GEMM * * cuBLAS follows the BLAS convention of column-major ordering. This @@ -404,7 +398,8 @@ GemmParam CanonicalizeGemmInput(const transformer_engine::Tensor &A, const cubla namespace transformer_engine { -using cublasHandleManager = detail::HandleManager; +using cublasHandleManager = + detail::HandleManager; void cublas_gemm(const Tensor *inputA, const Tensor *inputB, const Tensor *inputC, Tensor *outputD, const Tensor *inputBias, Tensor *outputPreGelu, cublasOperation_t transa, @@ -1217,7 +1212,8 @@ void nvte_multi_stream_cublas_gemm(const NVTETensor *A, const NVTETensor *B, NVT namespace transformer_engine { -using cublasHandleManager = detail::HandleManager; +using cublasHandleManager = + detail::HandleManager; void nvte_cublas_handle_init() { auto _ = cublasHandleManager::Instance().GetHandle(); } diff --git a/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu b/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu index e907151004e..2ffa28e3b33 100644 --- a/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu +++ b/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu @@ -29,6 +29,10 @@ inline void CreateCublasHandle(cublasLtHandle_t *handle) { NVTE_CHECK_CUBLAS(cublasLtCreate(handle)); } +inline void DestroyCublasHandle(cublasLtHandle_t handle) { + NVTE_CHECK_CUBLAS(cublasLtDestroy(handle)); +} + } // namespace // MXFP8 support for grouped GEMM requires cuBLAS 13.3+ @@ -1102,7 +1106,8 @@ inline void execute_grouped_gemm(const GroupedGemmSetupWorkspace &setup_workspac const GroupedGemmConfig &config, void *cublas_workspace_ptr, cudaStream_t stream) { using cublasHandleManager = - transformer_engine::detail::HandleManager; + transformer_engine::detail::HandleManager; cublasLtHandle_t handle = cublasHandleManager::Instance().GetHandle(); cublasOperation_t op_A = A_sel.trans ? CUBLAS_OP_T : CUBLAS_OP_N; diff --git a/transformer_engine/common/include/transformer_engine/cuda_context.h b/transformer_engine/common/include/transformer_engine/cuda_context.h new file mode 100644 index 00000000000..f3e9d786947 --- /dev/null +++ b/transformer_engine/common/include/transformer_engine/cuda_context.h @@ -0,0 +1,105 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +/*! \file cuda_context.h + * \brief Explicit release and invalidation of registered CUDA-dependent state. + */ + +#ifndef TRANSFORMER_ENGINE_CUDA_CONTEXT_H_ +#define TRANSFORMER_ENGINE_CUDA_CONTEXT_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*! Invalidate all registered TE CUDA-dependent state after external context loss. + * Every primary context backing a registered resource must already be destroyed. + * This is a process-wide boundary, not selective recovery of one device. + * Calling reset with any such context still alive abandons live resources and + * is unsupported. Use release while contexts are usable instead. + * + * Stop ALL TE calls and object construction/destruction in every host thread. + * The caller owns context teardown/recreation, framework allocator recovery, + * and replacement of device tensors and captured graphs. Reset is host-only: + * it does not query CUDA, synchronize, or destroy dead stream/event/module + * handles. Supported resources are recreated lazily after recovery. + * Opaque vendor host-state cleanup may require dependency support. + */ +void nvte_reset_cuda_state(void); + +/*! Release all registered TE CUDA-dependent state while its contexts and + * borrowed communicators remain usable. Stop all TE calls, finish GPU work, + * retire captured graphs, and release frontend-owned TE state first. This is + * process-wide and does not destroy CUDA contexts, model tensors, or RNG state. + * Device-affine callbacks run with their existing primary context current; + * unused devices are not initialized. The calling thread's context is restored. + * A callback registered with device=-1 manages its own device selection. + * Cleanup errors propagate after remaining callbacks run. Finish cleanup before + * resuming work after an error. Resources are recreated lazily on next use. + */ +void nvte_release_cuda_state(void); + +/*! Single process-wide generation, initially one. A completed release/reset + * publishes an increment with release/acquire semantics. Rejected preflight + * does not advance it; a partially failed release does. This host-only query + * is a cheap notification, not a resource pin or permission to race cleanup. + */ +uint64_t nvte_get_cuda_state_version(void); + +/*! Cleanup phases, in dependency order. Callbacks in the same phase run in + * reverse registration order for both release and post-loss invalidation. + * Custom integer priorities may be used between these standard phases. + */ +typedef enum { + NVTE_CUDA_STATE_RELEASE_PLANS = 0, + NVTE_CUDA_STATE_RELEASE_HANDLES = 100, + NVTE_CUDA_STATE_RELEASE_MODULES = 200, + NVTE_CUDA_STATE_RELEASE_STREAMS = 300, + NVTE_CUDA_STATE_RELEASE_COLLECTIVE_CONFIG = 800, + NVTE_CUDA_STATE_RELEASE_COMMUNICATORS = 900, + NVTE_CUDA_STATE_RELEASE_EXTERNAL_OWNERS = 1000 +} NVTECudaStateReleaseOrder; + +/*! Callbacks for framework bindings which own context-dependent state. All + * callbacks run at an externally serialized lifecycle boundary; they must not + * register new resources or re-enter lifecycle APIs. Check callbacks must not + * mutate state. C++ check/release callbacks may throw; invalidate must not. + * Cleanup order is ascending priority, then reverse registration order. + * The same ordering applies to live release and post-loss invalidation. + */ +typedef void (*NVTECudaStateCallback)(void *user_data); +typedef struct { + NVTECudaStateCallback check_context_loss; + NVTECudaStateCallback check_release; + NVTECudaStateCallback release; + NVTECudaStateCallback invalidate; + int release_order; +} NVTECudaStateCallbacks; +typedef struct NVTECudaStateRegistrationImpl *NVTECudaStateRegistration; + +/*! Register stable user_data in the process-wide registry without querying CUDA. + * Device is a live-cleanup affinity, not a reset scope. Use -1 for host-only or + * multi-device owners; those callbacks select their own devices when needed. + * Keep user_data alive until unregister returns. Registration/destruction is + * serialized with lifecycle calls. Cleanup may unregister destroyed children. + */ +NVTECudaStateRegistration nvte_register_cuda_state(int device, NVTECudaStateCallbacks callbacks, + void *user_data); +void nvte_unregister_cuda_state(NVTECudaStateRegistration registration); + +/*! Update live-cleanup affinity without changing registration order. This is + * host-only and must be serialized with lifecycle calls. Device must be -1 or + * a nonnegative ordinal, as for registration. Registration must not be null. + */ +void nvte_set_cuda_state_device(NVTECudaStateRegistration registration, int device); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // TRANSFORMER_ENGINE_CUDA_CONTEXT_H_ diff --git a/transformer_engine/common/normalization/common.cpp b/transformer_engine/common/normalization/common.cpp index a7095aa0570..caf421cf513 100644 --- a/transformer_engine/common/normalization/common.cpp +++ b/transformer_engine/common/normalization/common.cpp @@ -523,6 +523,10 @@ NormalizationPlanBase* NormalizationPlanRegistry::getNormalizationPlan( DType itype, DType otype, const size_t batch_size, const size_t hidden_size, const size_t sm_count, const bool zero_centered_gamma, const bool is_aligned, const NVTEScalingMode mode, const bool training, const bool gamma_in_weight_dtype) { + const int device = cuda::current_device(); + auto& device_plans = device_plans_[device]; + if (!device_plans) device_plans = std::make_unique(device); + auto& normalizationPlanMap = device_plans->plans; const DType ctype = DType::kFloat32; bool is_tuned = is_aligned && (batch_size % 4 == 0); auto key = diff --git a/transformer_engine/common/normalization/common.h b/transformer_engine/common/normalization/common.h index 26fbaf04351..e852ee311e6 100644 --- a/transformer_engine/common/normalization/common.h +++ b/transformer_engine/common/normalization/common.h @@ -240,8 +240,13 @@ class NormalizationPlanRegistry { NormalizationPlanRegistry(const NormalizationPlanRegistry&) = delete; NormalizationPlanRegistry& operator=(const NormalizationPlanRegistry&) = delete; - std::unordered_map, TupleHash> - normalizationPlanMap; + struct DevicePlans : cuda_context::Resource { + explicit DevicePlans(int device) : cuda_context::Resource(device) {} + void invalidate_context() noexcept override { plans.clear(); } + void release_context() override { plans.clear(); } + std::unordered_map, TupleHash> plans; + }; + std::unordered_map> device_plans_; }; using byte = uint8_t; diff --git a/transformer_engine/common/swizzle/swizzle_block_scaling.cu b/transformer_engine/common/swizzle/swizzle_block_scaling.cu index 7cb888c2b70..a766dd366ec 100644 --- a/transformer_engine/common/swizzle/swizzle_block_scaling.cu +++ b/transformer_engine/common/swizzle/swizzle_block_scaling.cu @@ -14,6 +14,7 @@ #include #include "../common.h" +#include "../util/cuda_context.h" #include "../util/cuda_runtime.h" #include "../util/logging.h" #include "transformer_engine/transformer_engine.h" @@ -458,8 +459,8 @@ void enable_table_smem(const size_t smem_bytes, const size_t num_tensors) { NVTE_CHECK(smem_bytes <= max_smem_bytes, "Too many tensors (", num_tensors, ") to convert FP8 block scaling to MXFP8 scales: needs ", smem_bytes, " bytes of shared memory, but the device allows ", max_smem_bytes, "."); - static std::vector flags(cuda::num_devices()); - std::call_once(flags[device], [&]() { + static std::vector flags(cuda::num_devices()); + flags[device].call(device, [&]() { NVTE_CHECK_CUDA(cudaFuncSetAttribute(grouped_swizzle_block_scaling_to_mxfp8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, static_cast(max_smem_bytes))); diff --git a/transformer_engine/common/tvm_ffi_bridge.h b/transformer_engine/common/tvm_ffi_bridge.h index 1c2e7fffe6a..83d734e12ae 100644 --- a/transformer_engine/common/tvm_ffi_bridge.h +++ b/transformer_engine/common/tvm_ffi_bridge.h @@ -8,6 +8,7 @@ #define TRANSFORMER_ENGINE_COMMON_TVM_FFI_BRIDGE_H_ #include +#include #include #include #include @@ -26,6 +27,7 @@ #include #include "common.h" +#include "util/cuda_context.h" #include "util/cuda_runtime.h" #include "util/logging.h" #include "util/system.h" @@ -228,22 +230,23 @@ namespace tvm_ffi_bridge { // // - std::optional get_kernel() const // Retrieves the possibly cached function. If the config provides a -// `uint32_t to_id() const` method, it can reuse TVMFFIConfigCache with the +// `Key to_id() const` method, it can reuse TVMFFIConfigCache with the // canonical implementation: // ``` // std::optional get_kernel() const { -// static TVMFFIConfigCache &cache = TVMFFIConfigCache::create(); +// static auto &cache = TVMFFIConfigCache::create(); // return cache.get_or_load(*this); // } // ``` // The ID only has to be unique within the config type because the function-local // cache belongs to that type. Configs that need a different key type or caching -// policy may implement get_kernel() themselves. +// policy may select a different Key type or implement get_kernel() themselves. // // Note: TVMFFIConfigCache::create() intentionally gives its cache process lifetime. // This prevents cached tvm::ffi::Function handles from being destroyed during // static teardown, when Python or TVM-FFI runtime state may already have been // finalized. The OS reclaims the allocation when the process exits. +template class TVMFFIConfigCache; namespace detail { @@ -287,7 +290,10 @@ class TVMFFICentral { }); return std::nullopt; } - const std::string key = cfg.to_key(); + int device; + NVTE_CHECK_CUDA(cudaGetDevice(&device)); + const std::string key = cfg.to_key() + "_device_" + std::to_string(device) + "_generation_" + + std::to_string(nvte_get_cuda_state_version()); bool success = false; { PythonGCPause gc_pause; @@ -436,17 +442,17 @@ class TVMFFICentral { }; // A utility class that each Config struct can use to cache the registered TVM-FFI functions -// via `to_id` method, where an id is a unique integer that represents a specific config. +// via `to_id`, whose key uniquely represents a config within its config type. // Defined after TVMFFICentral because get_or_load names it. // +template class TVMFFIConfigCache { public: static TVMFFIConfigCache &create() { return *new TVMFFIConfigCache(); } // Lazy-load the CuTeDSL function for this config and cache the result. // Returns std::nullopt if the config is unsupported or CuTeDSL backend is disabled. - // This requires the config to have a `uint32_t to_id() const` method, which returns an unique - // identifier among all configs of this type. + // This requires a `Key to_id() const` method returning a unique key within the config type. template std::optional get_or_load(const Config &cfg) { TVMFFICentral ¢ral = TVMFFICentral::getInstance(); @@ -456,35 +462,60 @@ class TVMFFIConfigCache { return std::nullopt; } // Otherwise try the cache first, and ask Python to compile/register the kernel if not found. - const uint32_t id = cfg.to_id(); + const Key id = cfg.to_id(); + int device; + NVTE_CHECK_CUDA(cudaGetDevice(&device)); { std::shared_lock read_lock(mutex_); - auto it = map_.find(id); - if (it != map_.end()) { - return it->second; + auto cache = devices_.find(device); + if (cache != devices_.end()) { + auto it = cache->second->functions.find(id); + if (it != cache->second->functions.end()) return it->second; } } std::unique_lock write_lock(mutex_); // After I grab the write lock, check again in case another thread already loaded it. - auto it = map_.find(id); - if (it != map_.end()) { + auto &cache = devices_[device]; + if (!cache) cache = std::make_unique(device); + auto it = cache->functions.find(id); + if (it != cache->functions.end()) { // Another thread must have loaded it before I obtained the write lock, so just return it. return it->second; } // No other thread has loaded it, and none can load it now while I hold the write lock. std::optional fn = central.load_tvm_ffi_function(cfg); - map_.emplace(id, fn); + cache->functions.emplace(id, fn); return fn; } private: + struct DeviceFunctions : cuda_context::Resource { + explicit DeviceFunctions(int device) : cuda_context::Resource(device), device(device) {} + void check_context_loss() const override { + for (const auto &entry : functions) { + NVTE_CHECK(!entry.second.has_value(), + "Loaded CuTeDSL/TVM-FFI functions retain context-specific executors. " + "Release the backend while the context is usable before destroying it; " + "otherwise restart the worker."); + } + } + void release_context() override { + functions.clear(); + auto cleanup = tvm::ffi::Function::GetGlobal("release_cutedsl_cuda_state"); + NVTE_CHECK(cleanup.has_value(), "CuTeDSL CUDA-state cleanup callback is not registered."); + (*cleanup)(device); + } + void invalidate_context() noexcept override { functions.clear(); } + int device; + std::unordered_map> functions; + }; TVMFFIConfigCache() = default; ~TVMFFIConfigCache() = default; std::shared_mutex mutex_; - std::unordered_map> map_; + std::unordered_map> devices_; }; // Optionally warn or fail when CuTeDSL kernels are not chosen based on NVTE_REPORT_IF_CUTEDSL_BACKEND_NOT_CHOSEN. diff --git a/transformer_engine/common/util/cuda_context.cpp b/transformer_engine/common/util/cuda_context.cpp new file mode 100644 index 00000000000..f559969666e --- /dev/null +++ b/transformer_engine/common/util/cuda_context.cpp @@ -0,0 +1,208 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#include "cuda_context.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include "cuda_driver.h" +#include "logging.h" + +namespace transformer_engine::cuda_context { + +namespace { +struct Registry { + // Lifecycle callbacks may destroy other registered objects. Membership uses + // its own mutex, so their destructors can unregister without re-entering the + // lifecycle lock. The global version is published after the full operation. + std::mutex lifecycle_mutex; + std::mutex mutex; + std::vector resources; + std::atomic generation{1}; +}; + +Registry ®istry() { + // TLS resource destructors can run after ordinary static destruction. + static auto &instance = *new Registry; + return instance; +} +// Only attach primary contexts that already exist. Cached RTC device entries +// may be registered for devices that have never had a context in this process. +template +void with_primary_context(int ordinal, Function &&function) { + if (ordinal < 0) { + function(); + return; + } + NVTE_CALL_CHECK_CUDA_DRIVER(cuInit, 0); + CUdevice device; + NVTE_CALL_CHECK_CUDA_DRIVER(cuDeviceGet, &device, ordinal); + unsigned flags; + int active; + NVTE_CALL_CHECK_CUDA_DRIVER(cuDevicePrimaryCtxGetState, device, &flags, &active); + if (!active) { + function(); + return; + } + CUcontext context; + NVTE_CALL_CHECK_CUDA_DRIVER(cuDevicePrimaryCtxRetain, &context, device); + const auto push_status = cuda_driver::call("cuCtxPushCurrent", context); + if (push_status != CUDA_SUCCESS) { + cuda_driver::call("cuDevicePrimaryCtxRelease", device); + NVTE_CHECK_CUDA_DRIVER(push_status); + } + CUcontext popped; + try { + function(); + } catch (...) { + cuda_driver::call("cuCtxPopCurrent", &popped); + cuda_driver::call("cuDevicePrimaryCtxRelease", device); + throw; + } + const auto pop_status = cuda_driver::call("cuCtxPopCurrent", &popped); + const auto release_status = cuda_driver::call("cuDevicePrimaryCtxRelease", device); + NVTE_CHECK_CUDA_DRIVER(pop_status); + NVTE_CHECK_CUDA_DRIVER(release_status); +} +} // namespace + +Resource::Resource(int device, int release_order) : device_(device), release_order_(release_order) { + NVTE_CHECK(device >= -1, "Invalid CUDA cleanup device ordinal."); + auto &state = registry(); + std::lock_guard lock(state.mutex); + state.resources.push_back(this); +} + +Resource::~Resource() { + auto &state = registry(); + std::lock_guard lock(state.mutex); + auto &resources = state.resources; + resources.erase(std::remove(resources.begin(), resources.end(), this), resources.end()); +} + +ExternalResource::ExternalResource(int device, const char *owner) + : Resource(device, NVTE_CUDA_STATE_RELEASE_EXTERNAL_OWNERS), owner_(owner) {} + +void ExternalResource::check_context_loss() const { + NVTE_ERROR("Cannot recover active ", owner_, + " after CUDA context loss. Its communicator/IPC/VMM state must be released " + "before context destruction; otherwise restart the worker."); +} + +void ExternalResource::check_release() const {} + +void ExternalResource::release_context() { + NVTE_ERROR("Release all owners of ", owner_, + " while the CUDA context and communicator are usable, then release TE state."); +} + +void Resource::set_device(int device) { + NVTE_CHECK(device >= -1, "Invalid CUDA cleanup device ordinal."); + auto &state = registry(); + std::lock_guard lock(state.mutex); + device_ = device; +} + +uint64_t generation() { return registry().generation.load(std::memory_order_acquire); } + +void reset() { + auto &state = registry(); + std::lock_guard lifecycle_lock(state.lifecycle_mutex); + std::unique_lock lock(state.mutex); + NVTE_CHECK( + state.generation.load(std::memory_order_relaxed) != std::numeric_limits::max(), + "CUDA state generation overflow."); + for (auto *resource : state.resources) resource->check_context_loss(); + auto resources = state.resources; + std::reverse(resources.begin(), resources.end()); + std::stable_sort(resources.begin(), resources.end(), + [](auto *a, auto *b) { return a->release_order_ < b->release_order_; }); + // All users are stopped and all contexts backing registered resources have + // been lost. No CUDA calls or new registrations are allowed during reset. + for (auto *resource : resources) { + if (std::find(state.resources.begin(), state.resources.end(), resource) == + state.resources.end()) + continue; + lock.unlock(); + resource->invalidate_context(); + lock.lock(); + } + state.generation.fetch_add(1, std::memory_order_release); +} + +void release() { + auto &state = registry(); + std::lock_guard lifecycle_lock(state.lifecycle_mutex); + std::unique_lock lock(state.mutex); + NVTE_CHECK( + state.generation.load(std::memory_order_relaxed) != std::numeric_limits::max(), + "CUDA state generation overflow."); + for (auto *resource : state.resources) resource->check_release(); + auto resources = state.resources; + std::reverse(resources.begin(), resources.end()); + std::stable_sort(resources.begin(), resources.end(), + [](auto *a, auto *b) { return a->release_order_ < b->release_order_; }); + std::exception_ptr error; + for (auto *resource : resources) { + if (std::find(state.resources.begin(), state.resources.end(), resource) == + state.resources.end()) + continue; + lock.unlock(); + try { + with_primary_context(resource->device_, [&] { resource->release_context(); }); + } catch (...) { + if (!error) error = std::current_exception(); + } + lock.lock(); + } + state.generation.fetch_add(1, std::memory_order_release); + if (error) std::rethrow_exception(error); +} + +} // namespace transformer_engine::cuda_context + +struct NVTECudaStateRegistrationImpl : transformer_engine::cuda_context::Resource { + NVTECudaStateRegistrationImpl(int device, NVTECudaStateCallbacks callbacks, void *data) + : Resource(device, callbacks.release_order), callbacks(callbacks), data(data) { + NVTE_CHECK(callbacks.release != nullptr && callbacks.invalidate != nullptr, + "CUDA state release/invalidate callbacks must not be null."); + } + void check_context_loss() const override { + if (callbacks.check_context_loss) callbacks.check_context_loss(data); + } + void check_release() const override { + if (callbacks.check_release) callbacks.check_release(data); + } + void release_context() override { callbacks.release(data); } + void invalidate_context() noexcept override { callbacks.invalidate(data); } + NVTECudaStateCallbacks callbacks; + void *data; +}; + +NVTECudaStateRegistration nvte_register_cuda_state(int device, NVTECudaStateCallbacks callbacks, + void *user_data) { + return new NVTECudaStateRegistrationImpl(device, callbacks, user_data); +} + +void nvte_unregister_cuda_state(NVTECudaStateRegistration registration) { delete registration; } + +void nvte_set_cuda_state_device(NVTECudaStateRegistration registration, int device) { + NVTE_CHECK(registration != nullptr, "CUDA state registration must not be null."); + registration->set_device(device); +} + +void nvte_reset_cuda_state() { transformer_engine::cuda_context::reset(); } + +void nvte_release_cuda_state() { transformer_engine::cuda_context::release(); } + +uint64_t nvte_get_cuda_state_version() { return transformer_engine::cuda_context::generation(); } diff --git a/transformer_engine/common/util/cuda_context.h b/transformer_engine/common/util/cuda_context.h new file mode 100644 index 00000000000..020b9f5f0ae --- /dev/null +++ b/transformer_engine/common/util/cuda_context.h @@ -0,0 +1,129 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_UTIL_CUDA_CONTEXT_H_ +#define TRANSFORMER_ENGINE_UTIL_CUDA_CONTEXT_H_ + +#include + +#include +#include +#include +#include + +namespace transformer_engine::cuda_context { + +// Registered objects keep stable addresses. Reset and destruction must be +// externally serialized with all TE calls and resource construction. Base +// construction registers the address using host operations only. +class Resource { + public: + explicit Resource(int device = -1, int release_order = NVTE_CUDA_STATE_RELEASE_PLANS); + Resource(const Resource &) = delete; + Resource &operator=(const Resource &) = delete; + virtual ~Resource(); + // Device affinity selects a live cleanup context; -1 is host-only or multi-device. + // Updating affinity does not change the original registration order. + void set_device(int device); + + private: + friend void reset(); + friend void release(); + // Preflight runs before any resource or generation changes. An owner can + // reject a lifecycle operation that its dependency cannot safely perform. + virtual void check_context_loss() const {} + virtual void check_release() const {} + virtual void release_context() = 0; + virtual void invalidate_context() noexcept = 0; + int device_; + const int release_order_; +}; + +// Communicators and VMM/IPC registrations are not owned by a CUDA context. +// Their public owner must be destroyed while its transport is still usable. +// Refuse a false-success reset if a caller retains such an owner. +class ExternalResource final : public Resource { + public: + ExternalResource(int device, const char *owner); + + private: + void check_context_loss() const override; + void check_release() const override; + void release_context() override; + void invalidate_context() noexcept override {} + const char *owner_; +}; + +// Synchronizes successful lazy initialization. A throwing initializer leaves +// the state invalid and may be retried. Invalidation requires quiescent users. +class InitializationState { + public: + template + void ensure_valid(Function &&initialize) { + if (initialized_.load(std::memory_order_acquire)) return; + std::lock_guard lock(mutex_); + if (initialized_.load(std::memory_order_relaxed)) return; + initialize(); + initialized_.store(true, std::memory_order_release); + } + void invalidate() noexcept { initialized_.store(false, std::memory_order_release); } + + private: + std::atomic initialized_{false}; + std::mutex mutex_; +}; + +// Optional lazy initialization for owners such as library handles and modules. +// Parameters belong to the caller's initializer, not to a universal virtual init. +class LazyResource : public Resource { + public: + using Resource::Resource; + template + void ensure_valid(Function &&initialize) { + initialization_.ensure_valid(std::forward(initialize)); + } + + private: + void release_context() final { + // Always visit the owner: failed initialization may have acquired part of + // its state before throwing. Empty owners must support no-op cleanup. + release_resources(); + initialization_.invalidate(); + } + void invalidate_context() noexcept final { + invalidate_resources(); + initialization_.invalidate(); + } + virtual void release_resources() = 0; + virtual void invalidate_resources() noexcept = 0; + InitializationState initialization_; +}; + +// Resettable context-local kernel attributes share the same initialization state. +class InitializationFlag final : public LazyResource { + public: + template + void call(int device, Function &&initialize) { + ensure_valid([&] { + set_device(device); + initialize(); + }); + } + + private: + void release_resources() override {} + void invalidate_resources() noexcept override {} +}; + +// Process-wide notification for host TLS that needs to recheck CUDA following +// a global lifecycle operation. Device affinity is only used for live cleanup. +uint64_t generation(); +void reset(); +void release(); + +} // namespace transformer_engine::cuda_context + +#endif // TRANSFORMER_ENGINE_UTIL_CUDA_CONTEXT_H_ diff --git a/transformer_engine/common/util/cuda_driver.cpp b/transformer_engine/common/util/cuda_driver.cpp index 1e98528e52f..053a2f839bd 100644 --- a/transformer_engine/common/util/cuda_driver.cpp +++ b/transformer_engine/common/util/cuda_driver.cpp @@ -8,6 +8,7 @@ #include "../common.h" #include "../util/cuda_runtime.h" +#include "cuda_context.h" namespace transformer_engine { @@ -45,7 +46,9 @@ void *get_symbol(const char *symbol, int cuda_version) { } void ensure_context_exists() { - static thread_local bool need_check = []() { + static thread_local uint64_t checked_generation = 0; + const auto generation = cuda_context::generation(); + if (checked_generation != generation) { CUcontext context; NVTE_CALL_CHECK_CUDA_DRIVER(cuCtxGetCurrent, &context); if (context == nullptr) { @@ -56,8 +59,8 @@ void ensure_context_exists() { NVTE_CALL_CHECK_CUDA_DRIVER(cuCtxSetCurrent, context); NVTE_CALL_CHECK_CUDA_DRIVER(cuDevicePrimaryCtxRelease, device); } - return false; - }(); + checked_generation = generation; + } } } // namespace cuda_driver diff --git a/transformer_engine/common/util/cuda_state_registration.h b/transformer_engine/common/util/cuda_state_registration.h new file mode 100644 index 00000000000..11a7919329d --- /dev/null +++ b/transformer_engine/common/util/cuda_state_registration.h @@ -0,0 +1,42 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_UTIL_CUDA_STATE_REGISTRATION_H_ +#define TRANSFORMER_ENGINE_UTIL_CUDA_STATE_REGISTRATION_H_ + +#include + +namespace transformer_engine::cuda_context { + +// Framework bindings use only the common C ABI, not common's hidden C++ RTTI. +class FrontendResource { + public: + explicit FrontendResource(int device = -1, int release_order = NVTE_CUDA_STATE_RELEASE_PLANS) { + // Store the explicit priority; virtual dispatch is not available for the + // derived owner during base construction. Trampolines run after construction. + const NVTECudaStateCallbacks callbacks{ + [](void *p) { static_cast(p)->check_context_loss(); }, + [](void *p) { static_cast(p)->check_release(); }, + [](void *p) { static_cast(p)->release_context(); }, + [](void *p) { static_cast(p)->invalidate_context(); }, release_order}; + registration_ = nvte_register_cuda_state(device, callbacks, this); + } + FrontendResource(const FrontendResource &) = delete; + FrontendResource &operator=(const FrontendResource &) = delete; + virtual ~FrontendResource() { nvte_unregister_cuda_state(registration_); } + void set_device(int device) { nvte_set_cuda_state_device(registration_, device); } + + private: + virtual void check_context_loss() const {} + virtual void check_release() const {} + virtual void release_context() = 0; + virtual void invalidate_context() noexcept = 0; + NVTECudaStateRegistration registration_ = nullptr; +}; + +} // namespace transformer_engine::cuda_context + +#endif // TRANSFORMER_ENGINE_UTIL_CUDA_STATE_REGISTRATION_H_ diff --git a/transformer_engine/common/util/handle_manager.h b/transformer_engine/common/util/handle_manager.h index 1a538eaff02..ae2b3698935 100644 --- a/transformer_engine/common/util/handle_manager.h +++ b/transformer_engine/common/util/handle_manager.h @@ -7,14 +7,16 @@ #ifndef TRANSFORMER_ENGINE_UTIL_HANDLE_MANAGER_H_ #define TRANSFORMER_ENGINE_UTIL_HANDLE_MANAGER_H_ +#include #include +#include "cuda_context.h" #include "cuda_runtime.h" #include "logging.h" namespace transformer_engine::detail { -template +template class HandleManager { public: static HandleManager& Instance() { @@ -23,28 +25,79 @@ class HandleManager { } Handle GetHandle() { - static thread_local std::vector initialized(handles_.size(), false); const int device_id = cuda::current_device(); NVTE_CHECK(0 <= device_id && device_id < handles_.size(), "invalid CUDA device ID"); - if (!initialized[device_id]) { - Create(&(handles_[device_id])); - initialized[device_id] = true; - } - return handles_[device_id]; + auto& slot = handles_[device_id]; + if (!slot) slot = acquire_slot(device_id); + slot->ensure_valid([&] { + Handle handle = nullptr; + Create(&handle); + slot->handle = handle; + }); + return slot->handle; } + private: + struct Slot : cuda_context::LazyResource { + explicit Slot(int device) : LazyResource(device, NVTE_CUDA_STATE_RELEASE_HANDLES) {} + // Explicit release owns teardown. Calling CUDA from TLS/static destruction + // is unsafe when the runtime is already terminating. + void release_resources() override { + if (handle == nullptr) return; + Destroy(handle); + handle = nullptr; + } + void invalidate_resources() noexcept override { + // The context has already destroyed its device resources. Do not pass + // dead handles to a vendor destructor that may call CUDA. + handle = nullptr; + } + Handle handle = nullptr; + Slot* next_idle = nullptr; + }; + + HandleManager() : handles_(cuda::num_devices()) {} ~HandleManager() { - if (Destroy != nullptr) { - for (auto& handle : handles_) { - Destroy(handle); + // A finished thread must not strand vendor allocations outside the reset + // registry. Return ownership to the process pool using host operations only. + for (size_t device = 0; device < handles_.size(); ++device) { + if (auto* slot = handles_[device]) { + auto& state = pool(); + std::lock_guard lock(state.mutex); + slot->next_idle = state.idle[device]; + state.idle[device] = slot; } } } - private: - HandleManager() : handles_(cuda::num_devices(), nullptr) {} + struct Pool { + explicit Pool(int devices) : idle(devices, nullptr) {} + std::mutex mutex; + std::vector> owners; + std::vector idle; + }; + static Pool& pool() { + // Avoid CUDA calls during process/static teardown. The number of slots is + // bounded by peak concurrent thread use, and live release frees their handles. + static auto& state = *new Pool(cuda::num_devices()); + return state; + } + static Slot* acquire_slot(int device) { + auto& state = pool(); + std::lock_guard lock(state.mutex); + auto* slot = state.idle[device]; + if (slot) { + state.idle[device] = slot->next_idle; + slot->next_idle = nullptr; + return slot; + } + auto owner = std::make_unique(device); + slot = owner.get(); + state.owners.emplace_back(std::move(owner)); + return slot; + } - std::vector handles_ = nullptr; + std::vector handles_; }; } // namespace transformer_engine::detail diff --git a/transformer_engine/common/util/multi_stream.cpp b/transformer_engine/common/util/multi_stream.cpp index 6b19f367415..c62aeeb4069 100644 --- a/transformer_engine/common/util/multi_stream.cpp +++ b/transformer_engine/common/util/multi_stream.cpp @@ -11,42 +11,96 @@ #include +#include +#include +#include #include #include +#include "cuda_context.h" #include "cuda_runtime.h" #include "logging.h" namespace transformer_engine::detail { +namespace { +struct ComputeResources : cuda_context::Resource { + struct Slot { + std::atomic stream{nullptr}; + std::atomic event{nullptr}; + }; + explicit ComputeResources(int device) + : Resource(device, NVTE_CUDA_STATE_RELEASE_STREAMS), slots(nvte_get_num_compute_streams()) {} + void invalidate_context() noexcept override { + for (auto &slot : slots) { + slot.stream.store(nullptr, std::memory_order_release); + slot.event.store(nullptr, std::memory_order_release); + } + } + void release_context() override { + for (auto &slot : slots) { + if (auto event = slot.event.load(std::memory_order_acquire)) { + NVTE_CHECK_CUDA(cudaEventDestroy(event)); + slot.event.store(nullptr, std::memory_order_release); + } + if (auto stream = slot.stream.load(std::memory_order_acquire)) { + NVTE_CHECK_CUDA(cudaStreamDestroy(stream)); + slot.stream.store(nullptr, std::memory_order_release); + } + } + } + std::mutex mutex; + std::vector slots; +}; + +ComputeResources &compute_resources() { + static auto &mutex = *new std::mutex; + static auto &devices = *new std::map>; + int device; + NVTE_CHECK_CUDA(cudaGetDevice(&device)); + static thread_local std::map local; + const auto found = local.find(device); + if (found != local.end()) return *found->second; + std::lock_guard lock(mutex); + auto &resources = devices[device]; + if (!resources) resources = std::make_unique(device); + local.emplace(device, resources.get()); + return *resources; +} +} // namespace + cudaStream_t get_compute_stream(int idx) { const size_t num_streams = nvte_get_num_compute_streams(); NVTE_CHECK(0 <= idx && idx < num_streams, "Invalid compute stream (requested idx ", idx, ", but there are ", num_streams, " streams)"); - static std::vector streams(num_streams); - static std::once_flag stream_init_flag; - auto init = [&]() { - for (size_t i = 0; i < num_streams; i++) { - NVTE_CHECK_CUDA(cudaStreamCreateWithPriority(&streams[i], cudaStreamNonBlocking, -1)); - } - }; - std::call_once(stream_init_flag, init); - return streams[idx]; + auto &resources = compute_resources(); + auto &cached = resources.slots[idx].stream; + auto stream = cached.load(std::memory_order_acquire); + if (stream != nullptr) return stream; + std::lock_guard lock(resources.mutex); + stream = cached.load(std::memory_order_acquire); + if (stream == nullptr) { + NVTE_CHECK_CUDA(cudaStreamCreateWithPriority(&stream, cudaStreamNonBlocking, -1)); + cached.store(stream, std::memory_order_release); + } + return stream; } cudaEvent_t get_compute_stream_event(int idx) { const size_t num_streams = nvte_get_num_compute_streams(); NVTE_CHECK(0 <= idx && idx < num_streams, "Invalid compute stream (requested idx ", idx, ", but there are ", num_streams, " streams)"); - static std::vector events(num_streams); - static std::once_flag event_init_flag; - auto init = [&]() { - for (size_t i = 0; i < num_streams; i++) { - NVTE_CHECK_CUDA(cudaEventCreate(&events[i])); - } - }; - std::call_once(event_init_flag, init); - return events[idx]; + auto &resources = compute_resources(); + auto &cached = resources.slots[idx].event; + auto event = cached.load(std::memory_order_acquire); + if (event != nullptr) return event; + std::lock_guard lock(resources.mutex); + event = cached.load(std::memory_order_acquire); + if (event == nullptr) { + NVTE_CHECK_CUDA(cudaEventCreate(&event)); + cached.store(event, std::memory_order_release); + } + return event; } int get_num_compute_streams() { diff --git a/transformer_engine/common/util/rtc.cpp b/transformer_engine/common/util/rtc.cpp index f591620124c..391613e276c 100644 --- a/transformer_engine/common/util/rtc.cpp +++ b/transformer_engine/common/util/rtc.cpp @@ -12,6 +12,7 @@ #include #include "../common.h" +#include "../util/cuda_context.h" #include "../util/cuda_driver.h" #include "../util/cuda_runtime.h" #include "../util/string.h" @@ -63,34 +64,47 @@ bool is_enabled() { return is_enabled_; } -Kernel::Kernel(std::string mangled_name, std::string compiled_code) - : mangled_name_{std::move(mangled_name)}, - compiled_code_{std::move(compiled_code)}, - modules_(cuda::num_devices(), null_module), - functions_(cuda::num_devices(), null_function), - init_flags_{std::make_unique>(cuda::num_devices())} {} - -Kernel::~Kernel() { - for (int device_id = 0; device_id < static_cast(modules_.size()); ++device_id) { - // Unload CUDA modules if needed - if (modules_[device_id] != null_module) { - CUdevice device; - CUcontext context; - if (cuda_driver::call("cuDeviceGet", &device, device_id) != CUDA_SUCCESS) { - continue; - } - if (cuda_driver::call("cuDevicePrimaryCtxRetain", &context, device) != CUDA_SUCCESS) { - continue; - } - if (cuda_driver::call("cuCtxSetCurrent", context) != CUDA_SUCCESS) { - continue; - } - cuda_driver::call("cuModuleUnload", modules_[device_id]); - cuda_driver::call("cuDevicePrimaryCtxRelease", device); +struct Kernel::DeviceKernel : cuda_context::LazyResource { + explicit DeviceKernel(int device) + : LazyResource(device, NVTE_CUDA_STATE_RELEASE_MODULES), device(device) {} + ~DeviceKernel() override { + if (module == null_module) return; + CUdevice gpu; + CUcontext context; + if (cuda_driver::call("cuDeviceGet", &gpu, device) != CUDA_SUCCESS) return; + if (cuda_driver::call("cuDevicePrimaryCtxRetain", &context, gpu) != CUDA_SUCCESS) return; + CUcontext previous; + if (cuda_driver::call("cuCtxGetCurrent", &previous) == CUDA_SUCCESS && + cuda_driver::call("cuCtxSetCurrent", context) == CUDA_SUCCESS) { + cuda_driver::call("cuModuleUnload", module); + cuda_driver::call("cuCtxSetCurrent", previous); } + cuda_driver::call("cuDevicePrimaryCtxRelease", gpu); + } + void invalidate_resources() noexcept override { + module = null_module; + function = null_function; + } + void release_resources() override { + if (module == null_module) return; + NVTE_CALL_CHECK_CUDA_DRIVER(cuModuleUnload, module); + module = null_module; + function = null_function; + } + int device; + CUmodule module = null_module; + CUfunction function = null_function; +}; + +Kernel::Kernel(std::string mangled_name, std::string compiled_code) + : mangled_name_{std::move(mangled_name)}, compiled_code_{std::move(compiled_code)} { + for (int device = 0; device < cuda::num_devices(); ++device) { + devices_.push_back(std::make_unique(device)); } } +Kernel::~Kernel() = default; + Kernel::Kernel(Kernel&& other) noexcept { swap(*this, other); } Kernel& Kernel::operator=(Kernel other) noexcept { @@ -103,36 +117,38 @@ void swap(Kernel& first, Kernel& second) noexcept { using std::swap; swap(first.mangled_name_, second.mangled_name_); swap(first.compiled_code_, second.compiled_code_); - swap(first.modules_, second.modules_); - swap(first.functions_, second.functions_); - swap(first.init_flags_, second.init_flags_); + swap(first.devices_, second.devices_); } CUfunction Kernel::get_function(int device_id) { - // Load kernel on device if needed - auto load_on_device = [&]() { - // Set driver context to proper device + auto& kernel = *devices_.at(device_id); + // The callable obtains the current Kernel's strings, which move/swap with + // devices_. DeviceKernel must not retain references into a movable Kernel. + kernel.ensure_valid([&] { CUdevice device; - CUcontext context; + CUcontext context, previous; NVTE_CALL_CHECK_CUDA_DRIVER(cuDeviceGet, &device, device_id); + NVTE_CALL_CHECK_CUDA_DRIVER(cuCtxGetCurrent, &previous); NVTE_CALL_CHECK_CUDA_DRIVER(cuDevicePrimaryCtxRetain, &context, device); - NVTE_CALL_CHECK_CUDA_DRIVER(cuCtxSetCurrent, context); - - // Load function into driver context - NVTE_CALL_CHECK_CUDA_DRIVER(cuModuleLoadDataEx, &modules_[device_id], compiled_code_.c_str(), - 0, // numOptions - nullptr, // options - nullptr); // optionValues - NVTE_CALL_CHECK_CUDA_DRIVER(cuModuleGetFunction, &functions_[device_id], modules_[device_id], - mangled_name_.c_str()); - - // Reset driver context - NVTE_CALL_CHECK_CUDA_DRIVER(cuDevicePrimaryCtxRelease, device); - }; - std::call_once(init_flags_->at(device_id), load_on_device); - - // Return CUDA function - return functions_[device_id]; + try { + NVTE_CALL_CHECK_CUDA_DRIVER(cuCtxSetCurrent, context); + if (kernel.module == null_module) { + NVTE_CALL_CHECK_CUDA_DRIVER(cuModuleLoadDataEx, &kernel.module, compiled_code_.c_str(), 0, + nullptr, nullptr); + } + NVTE_CALL_CHECK_CUDA_DRIVER(cuModuleGetFunction, &kernel.function, kernel.module, + mangled_name_.c_str()); + } catch (...) { + cuda_driver::call("cuCtxSetCurrent", previous); + cuda_driver::call("cuDevicePrimaryCtxRelease", device); + throw; + } + const auto restore = cuda_driver::call("cuCtxSetCurrent", previous); + const auto release = cuda_driver::call("cuDevicePrimaryCtxRelease", device); + NVTE_CHECK_CUDA_DRIVER(restore); + NVTE_CHECK_CUDA_DRIVER(release); + }); + return kernel.function; } void Kernel::set_function_cache_config(int device_id, CUfunc_cache cache_config) { diff --git a/transformer_engine/common/util/rtc.h b/transformer_engine/common/util/rtc.h index 803f3c23a58..717f5e55bd9 100644 --- a/transformer_engine/common/util/rtc.h +++ b/transformer_engine/common/util/rtc.h @@ -130,13 +130,9 @@ class Kernel { std::string mangled_name_; /*! \brief Compiled assembly, either in PTX or cubin format */ std::string compiled_code_; - /*! CUDA module for each CUDA device */ - std::vector modules_; - /*! CUDA function for each CUDA device */ - std::vector functions_; - - /*! Flags for thread-safe kernel initialization */ - std::unique_ptr> init_flags_; + struct DeviceKernel; + /*! Stable, registered owners of loaded modules; compiled bytes survive reset. */ + std::vector> devices_; /*! \brief Uninitialized CUDA module */ static constexpr CUmodule null_module = static_cast(nullptr); diff --git a/transformer_engine/jax/__init__.py b/transformer_engine/jax/__init__.py index 7505a53ab60..b7b1307b66c 100644 --- a/transformer_engine/jax/__init__.py +++ b/transformer_engine/jax/__init__.py @@ -37,6 +37,7 @@ from . import flax from . import quantize +from .cuda_context import release_cuda_state, reset_cuda_state from .quantize import autocast, fp8_autocast, update_collections from .quantize import NVTE_FP8_COLLECTION_NAME @@ -48,6 +49,8 @@ __all__ = [ + "release_cuda_state", + "reset_cuda_state", "NVTE_FP8_COLLECTION_NAME", "autocast", "fp8_autocast", diff --git a/transformer_engine/jax/csrc/extensions/attention.cpp b/transformer_engine/jax/csrc/extensions/attention.cpp index def5e0149b8..df22e379537 100644 --- a/transformer_engine/jax/csrc/extensions/attention.cpp +++ b/transformer_engine/jax/csrc/extensions/attention.cpp @@ -19,6 +19,7 @@ #include "../extensions.h" #include "common/cudnn_utils.h" +#include "common/util/cuda_state_registration.h" #include "transformer_engine/fused_attn.h" #include "transformer_engine/transformer_engine.h" @@ -937,8 +938,8 @@ using ScoreModGraphPtr = std::shared_ptr; std::unordered_map & getScoreModeGraphCache() { - static std::unordered_map - cache; + static auto &cache = + *new std::unordered_map; return cache; } @@ -947,6 +948,30 @@ std::mutex &getScoreModGraphCacheMutex() { return mutex; } +struct ScoreModCacheLifetime : cuda_context::FrontendResource { + explicit ScoreModCacheLifetime(int device) : FrontendResource(device), device(device) {} + void release_context() override { + std::lock_guard lock(getScoreModGraphCacheMutex()); + auto &cache = getScoreModeGraphCache(); + for (auto it = cache.begin(); it != cache.end();) { + if (it->first.device_id == device) + it = cache.erase(it); + else + ++it; + } + } + void invalidate_context() noexcept override { release_context(); } + int device; +}; + +void track_score_mod_cache(int device) { + static auto &mutex = *new std::mutex; + static auto &owners = *new std::unordered_map>; + std::lock_guard lock(mutex); + auto &owner = owners[device]; + if (!owner) owner = std::make_unique(device); +} + ScoreModGraphCacheKey GetScoreModGraphCacheKey(Dictionary &attrs) { const int64_t frontend_version = get_attr_value(attrs, "cudnn_frontend_version"); NVTE_CHECK(frontend_version == CUDNN_FRONTEND_VERSION, @@ -968,6 +993,7 @@ ScoreModGraphCacheKey GetScoreModGraphCacheKey(Dictionary &attrs) { ScoreModGraphPtr GetScoreModGraph(cudaStream_t stream, Dictionary &attrs) { const auto key = GetScoreModGraphCacheKey(attrs); + track_score_mod_cache(key.device_id); { std::lock_guard lock(getScoreModGraphCacheMutex()); auto &cache = getScoreModeGraphCache(); diff --git a/transformer_engine/jax/csrc/extensions/cgemm_helper.cpp b/transformer_engine/jax/csrc/extensions/cgemm_helper.cpp index da25e3676a5..d6260932f83 100644 --- a/transformer_engine/jax/csrc/extensions/cgemm_helper.cpp +++ b/transformer_engine/jax/csrc/extensions/cgemm_helper.cpp @@ -133,6 +133,8 @@ void CommunicatorHandler::init(int num_total_devices, int num_devices_per_proces NVTE_CHECK_CUDA(cudaMalloc(&handler._device_barrier, sizeof(int))); handler._initialize = true; + // Cleanup starts in the barrier allocation's context; the registry is global. + handler.set_device(handler.local_device_ids_within_process.back()); // Bootstrap UB/cuBlasMp via creating a dummy CommOverlapP2PBase object std::vector buffer_shape{1, 1}; @@ -164,6 +166,11 @@ int GetCgemmNumMaxStreams() { CommOverlapCore *CollectiveGemmPlanRegistry::get_executor(std::vector buffer_shape, DType dtype, JAXX_Collective_Op collective_op) { + int device; + NVTE_CHECK_CUDA(cudaGetDevice(&device)); + auto &cache = devices_[device]; + if (!cache) cache = std::make_unique(device); + auto &plan_map = cache->plans; auto &comm_handler = CommunicatorHandler::get(); auto &cgemm_config = CgemmConfig::get(); @@ -245,7 +252,8 @@ void CommunicatorHandler::nccl_allgather_impl(void *output_buf, size_t output_by cudaDeviceSynchronize(); } -CommunicatorHandler::CommunicatorHandler() : _device_barrier(nullptr) { +CommunicatorHandler::CommunicatorHandler() + : FrontendResource(-1, NVTE_CUDA_STATE_RELEASE_COMMUNICATORS), _device_barrier(nullptr) { allgather_func = [this](void *output_buf, size_t output_bytes, void *input_buf, size_t input_bytes, ExtComm comm) { this->nccl_allgather_impl(output_buf, output_bytes, input_buf, input_bytes, comm); @@ -268,5 +276,40 @@ CommunicatorHandler::~CommunicatorHandler() { } } +void CommunicatorHandler::check_context_loss() const { + NVTE_CHECK(!_initialize, + "Active JAX collective-GEMM communicators must be released before context loss; " + "the XLA/NCCL runtime cannot be recovered by a TE cache reset."); +} + +void CommunicatorHandler::release_context() { + if (!_initialize) return; + int previous; + NVTE_CHECK_CUDA(cudaGetDevice(&previous)); + try { + for (size_t i = 0; i < tp_comms.size(); ++i) { + if (tp_comms[i] != nullptr) { + NVTE_CHECK_CUDA(cudaSetDevice(local_device_ids_within_process[i])); + NVTE_CHECK_NCCL(ncclCommDestroy(tp_comms[i])); + tp_comms[i] = nullptr; + } + } + if (_device_barrier != nullptr) { + // init allocates the barrier after selecting the last local device. + NVTE_CHECK_CUDA(cudaSetDevice(local_device_ids_within_process.back())); + NVTE_CHECK_CUDA(cudaFree(_device_barrier)); + _device_barrier = nullptr; + } + } catch (...) { + cudaSetDevice(previous); + throw; + } + NVTE_CHECK_CUDA(cudaSetDevice(previous)); + for (const auto &path : _nccl_id_file_name) std::remove(path.c_str()); + _nccl_id_file_name.clear(); + tp_comms.clear(); + _initialize = false; +} + } // namespace jax } // namespace transformer_engine diff --git a/transformer_engine/jax/csrc/extensions/cgemm_helper.h b/transformer_engine/jax/csrc/extensions/cgemm_helper.h index 9bc8c9cf8d4..3c21b2d1f19 100644 --- a/transformer_engine/jax/csrc/extensions/cgemm_helper.h +++ b/transformer_engine/jax/csrc/extensions/cgemm_helper.h @@ -20,6 +20,7 @@ #include "../extensions.h" #include "common/comm_gemm_overlap/userbuffers/userbuffers.h" #include "common/util/cuda_runtime.h" +#include "common/util/cuda_state_registration.h" #include "common/util/logging.h" #include "transformer_engine/comm_gemm_overlap.h" @@ -27,7 +28,7 @@ namespace transformer_engine { namespace jax { // Configuration singleton for CGEMM parameters -class CgemmConfig { +class CgemmConfig : public cuda_context::FrontendResource { public: int num_max_streams; int gemm_priority; @@ -62,7 +63,9 @@ class CgemmConfig { CgemmConfig &operator=(const CgemmConfig &) = delete; private: - CgemmConfig() = default; + void release_context() override { _initialized = false; } + void invalidate_context() noexcept override { _initialized = false; } + CgemmConfig() : FrontendResource(-1, NVTE_CUDA_STATE_RELEASE_COLLECTIVE_CONFIG) {} ~CgemmConfig() = default; bool _initialized = false; }; @@ -75,7 +78,7 @@ class CollectiveGemmPlanRegistry; // Two scenarios: // 1. Single process multiple devices: TP domain = process (num_devices_per_process == tp_size) // 2. Single process single device: TP domain spans processes (num_devices_per_process == 1) -class CommunicatorHandler { +class CommunicatorHandler : public cuda_context::FrontendResource { public: int num_total_devices = -1; int num_devices_per_process = -1; @@ -152,6 +155,9 @@ class CommunicatorHandler { private: CommunicatorHandler(); ~CommunicatorHandler(); + void check_context_loss() const override; + void release_context() override; + void invalidate_context() noexcept override {} bool _initialize = false; int *_device_barrier = nullptr; @@ -174,7 +180,13 @@ class CollectiveGemmPlanRegistry { CollectiveGemmPlanRegistry(const CollectiveGemmPlanRegistry &) = delete; CollectiveGemmPlanRegistry &operator=(const CollectiveGemmPlanRegistry &) = delete; - std::unordered_map> plan_map; + struct DevicePlans : cuda_context::FrontendResource { + explicit DevicePlans(int device) : FrontendResource(device) {} + void release_context() override { plans.clear(); } + void invalidate_context() noexcept override { plans.clear(); } + std::unordered_map> plans; + }; + std::unordered_map> devices_; }; // Function declarations diff --git a/transformer_engine/jax/csrc/extensions/gemm.cpp b/transformer_engine/jax/csrc/extensions/gemm.cpp index ef9a91f2858..5d8f372cb38 100644 --- a/transformer_engine/jax/csrc/extensions/gemm.cpp +++ b/transformer_engine/jax/csrc/extensions/gemm.cpp @@ -5,6 +5,7 @@ ************************************************************************/ #include "transformer_engine/gemm.h" +#include #include #include #include @@ -481,19 +482,63 @@ XLA_FFI_DEFINE_HANDLER_SYMBOL(GemmHandler, GemmFFI, .Attr("collective_op"), FFI_CudaGraph_Traits); +namespace { +struct GroupSizesTransfer { + cudaEvent_t event = nullptr; + int32_t *sizes = nullptr; + size_t count = 0; +}; + +struct GroupSizesTransfers : cuda_context::FrontendResource { + explicit GroupSizesTransfers(int device) : FrontendResource(device) {} + std::mutex mutex; + std::map streams; + + private: + void check_context_loss() const override { + NVTE_CHECK(streams.empty(), + "Release JAX grouped GEMM pinned transfers before CUDA context destruction; " + "the XLA runtime cannot recover after context loss."); + } + void release_context() override { + for (auto &[stream, transfer] : streams) { + if (transfer.event) { + NVTE_CHECK_CUDA(cudaEventDestroy(transfer.event)); + transfer.event = nullptr; + } + if (transfer.sizes) { + NVTE_CHECK_CUDA(cudaFreeHost(transfer.sizes)); + transfer.sizes = nullptr; + } + } + streams.clear(); + } + void invalidate_context() noexcept override {} +}; + +GroupSizesTransfers &group_sizes_transfers() { + static auto &mutex = *new std::mutex; + static auto &devices = *new std::map>; + std::lock_guard lock(mutex); + auto &state = devices[cuda::current_device()]; + if (!state) state = std::make_unique(cuda::current_device()); + return *state; +} +} // namespace + size_t GroupedGemmGetGroupSizes(cudaStream_t stream, size_t num_gemms, int32_t *dev_group_sizes, int32_t *host_group_sizes) { - static std::once_flag init_flag; - static cudaEvent_t d2h_event; - static size_t host_num_gemms; - static const size_t max_num_gemms = 1024; - //static int32_t host_group_sizes_internal[max_num_gemms]; - static int32_t *host_group_sizes_internal = nullptr; - auto init = [&]() { - NVTE_CHECK_CUDA(cudaEventCreate(&d2h_event)); - NVTE_CHECK_CUDA(cudaMallocHost(&host_group_sizes_internal, sizeof(int32_t) * max_num_gemms)); - }; - std::call_once(init_flag, init); + constexpr size_t max_num_gemms = 1024; + auto &state = group_sizes_transfers(); + std::lock_guard lock(state.mutex); + auto &transfer = state.streams[stream]; + if (!transfer.event) NVTE_CHECK_CUDA(cudaEventCreate(&transfer.event)); + if (!transfer.sizes) { + NVTE_CHECK_CUDA(cudaMallocHost(&transfer.sizes, sizeof(int32_t) * max_num_gemms)); + } + auto d2h_event = transfer.event; + auto host_group_sizes_internal = transfer.sizes; + auto &host_num_gemms = transfer.count; NVTE_CHECK(dev_group_sizes == nullptr || host_group_sizes == nullptr, "Only one of dev_group_sizes and host_group_sizes can be non-nullptr."); @@ -524,6 +569,7 @@ size_t GroupedGemmGetGroupSizes(cudaStream_t stream, size_t num_gemms, int32_t * memcpy(host_group_sizes, host_group_sizes_internal, sizeof(int32_t) * host_num_gemms); return host_num_gemms; } + return 0; } Error_Type GroupedGemmD2HGroupSizesFFI(cudaStream_t stream, Buffer_Type group_sizes, diff --git a/transformer_engine/jax/csrc/extensions/pybind.cpp b/transformer_engine/jax/csrc/extensions/pybind.cpp index d82d109f650..e5611988930 100644 --- a/transformer_engine/jax/csrc/extensions/pybind.cpp +++ b/transformer_engine/jax/csrc/extensions/pybind.cpp @@ -8,6 +8,7 @@ #include "cgemm_helper.h" #include "common/util/cuda_runtime.h" #include "ffi_collectives.h" // FfiRequestCliqueHandler (borrowed-comm prepare) +#include "transformer_engine/cuda_context.h" #include "transformer_engine/gemm.h" namespace transformer_engine { @@ -159,6 +160,23 @@ pybind11::dict Registrations() { } PYBIND11_MODULE(transformer_engine_jax, m) { + m.def("get_cuda_state_version", &nvte_get_cuda_state_version); + m.def("release_cuda_state", &nvte_release_cuda_state, + pybind11::call_guard()); + m.def("reset_cuda_state", &nvte_reset_cuda_state, + pybind11::call_guard()); + m.def( + "synchronize_cuda_device", + [](int device) { + int previous; + NVTE_CHECK_CUDA(cudaGetDevice(&previous)); + NVTE_CHECK_CUDA(cudaSetDevice(device)); + const auto status = cudaDeviceSynchronize(); + const auto restore = cudaSetDevice(previous); + NVTE_CHECK_CUDA(status); + NVTE_CHECK_CUDA(restore); + }, + pybind11::arg("device"), pybind11::call_guard()); m.def("registrations", &Registrations); m.def("get_fused_attn_backend", &GetFusedAttnBackend, "Get Fused Attention backend", pybind11::arg("fused_attn_params")); diff --git a/transformer_engine/jax/cuda_context.py b/transformer_engine/jax/cuda_context.py new file mode 100644 index 00000000000..9c2e0a9ecc3 --- /dev/null +++ b/transformer_engine/jax/cuda_context.py @@ -0,0 +1,44 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Explicit TE cleanup while the JAX/XLA CUDA runtime remains usable.""" + +import sys + +import jax +import transformer_engine_jax as tex + + +def release_cuda_state() -> None: + """Release all TE-owned CUDA state at a process-wide restart boundary. + + Stop TE submissions on all host threads/ranks and retire captured graphs + first. This waits for local GPU work, clears JAX compilation caches, and + finalizes TE EP across all local devices. Borrowed NCCL communicators remain + usable through cleanup; every collective rank participates in the same order. + Model arrays and the XLA runtime survive. + """ + from .cpp_extensions import ep as ep_extension # pylint: disable=import-outside-toplevel + + jax.effects_barrier() + for device in jax.local_devices(backend="gpu"): + tex.synchronize_cuda_device(device.local_hardware_id) + jax.clear_caches() + if ep_extension._ep_config is not None: # pylint: disable=protected-access + from . import ep # pylint: disable=import-outside-toplevel + + ep.ep_finalize() + triton = sys.modules.get("transformer_engine.jax.triton_extensions.utils") + if triton is not None: + triton.release_cuda_state() + tex.release_cuda_state() + + +def reset_cuda_state() -> None: + """Reject a false-success reset of a lost JAX/XLA-owned CUDA runtime.""" + raise RuntimeError( + "TE cannot recreate a lost JAX/XLA CUDA runtime. Restart the worker after " + "context loss; use release_cuda_state while CUDA is usable for a " + "context-preserving in-process restart. Native owners may use the common C API." + ) diff --git a/transformer_engine/jax/triton_extensions/utils.py b/transformer_engine/jax/triton_extensions/utils.py index b98de38602a..4faf9b87e31 100644 --- a/transformer_engine/jax/triton_extensions/utils.py +++ b/transformer_engine/jax/triton_extensions/utils.py @@ -210,6 +210,12 @@ def _check_triton_compatibility(): # Triton kernel cache (module-level, shared across all kernels) _TRITON_KERNEL_CACHE = {} + +def release_cuda_state(): + """Drop TE's process-wide kernel owners after JAX executables are retired.""" + _TRITON_KERNEL_CACHE.clear() + + # Alignment (bytes) assumed for every array argument, as declared to the launcher by # gpu_triton.create_array_parameter(0, _ARRAY_ALIGNMENT_BYTES). _ARRAY_ALIGNMENT_BYTES = 16 diff --git a/transformer_engine/pytorch/__init__.py b/transformer_engine/pytorch/__init__.py index c408de1e52c..d8141b11d30 100644 --- a/transformer_engine/pytorch/__init__.py +++ b/transformer_engine/pytorch/__init__.py @@ -179,3 +179,5 @@ _make_identity_tensor_in_reduce_ex, ] ) + +from .cuda_context import release_cuda_state, reset_cuda_state diff --git a/transformer_engine/pytorch/_cuda_state.py b/transformer_engine/pytorch/_cuda_state.py new file mode 100644 index 00000000000..98fe914a585 --- /dev/null +++ b/transformer_engine/pytorch/_cuda_state.py @@ -0,0 +1,237 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Device-scoped ownership of Python caches used by CUDA operations.""" + +from collections import namedtuple +import functools +import inspect +import sys +import threading +import weakref + +import torch + +_CACHES = [] +_MODULES = weakref.WeakSet() +_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize") + + +def register_module(module): + """Track modules without extending their lifetime or allocating GPU memory.""" + _MODULES.add(module) + + +def device_cache(device_arg, maxsize=None): + """An LRU per CUDA device, with explicit device-scoped cleanup. + + ``device_arg`` is the positional index of the ``device`` argument, or None + for a function using the current device. CPU entries survive CUDA cleanup. + Signature inspection happens only at decoration, not on the dispatch path. + """ + + def decorate(function): + parameters = tuple(inspect.signature(function).parameters.values()) + parameter = parameters[device_arg] if device_arg is not None else None + caches = {} + lock = threading.RLock() + + @functools.wraps(function) + def cached(*args, **kwargs): + if parameter is None: + device = None + elif len(args) > device_arg: + device = args[device_arg] + else: + device = kwargs.get(parameter.name, parameter.default) + if device is None: + key = torch.cuda.current_device() + elif isinstance(device, int): + key = device + else: + device = torch.device(device) + key = ( + (device.index if device.index is not None else torch.cuda.current_device()) + if device.type == "cuda" + else (device.type, device.index) + ) + cache = caches.get(key) + if cache is None: + with lock: + cache = caches.get(key) + if cache is None: + cache = functools.lru_cache(maxsize=maxsize)(function) + caches[key] = cache + return cache(*args, **kwargs) + + def clear_device(device): + with lock: + cache = caches.pop(device, None) + if cache is not None: + cache.cache_clear() + + def clear_all(): + with lock: + for cache in caches.values(): + cache.cache_clear() + caches.clear() + + def cache_info(): + with lock: + infos = [cache.cache_info() for cache in caches.values()] + return _CacheInfo( + sum(info.hits for info in infos), + sum(info.misses for info in infos), + maxsize, + sum(info.currsize for info in infos), + ) + + cached.clear_device = clear_device + cached.cache_clear = clear_all + cached.cache_info = cache_info + cached.cache_parameters = lambda: {"maxsize": maxsize, "typed": False} + _CACHES.append(cached) + return cached + + return decorate + + +def release_device_caches(device): + """Release TE-owned tensor caches while their CUDA context is still usable.""" + for cache in _CACHES: + cache.clear_device(device) + for module in tuple(_MODULES): + workspaces = getattr(module, "_fp8_workspaces", {}) + for name, value in tuple(workspaces.items()): + tensors = value.get_data_tensors() if hasattr(value, "get_data_tensors") else (value,) + if any( + isinstance(tensor, torch.Tensor) + and tensor.device.type == "cuda" + and tensor.device.index == device + for tensor in tensors + ): + del workspaces[name] + # These are host caches, but their keys retain borrowed process groups. + from .distributed import ( # pylint: disable=import-outside-toplevel + get_distributed_rank, + get_distributed_world_size, + ) + + get_distributed_rank.cache_clear() + get_distributed_world_size.cache_clear() + for name in ("utils", "context_parallel", "flex_attention", "dot_product_attention"): + module = sys.modules.get( + f"transformer_engine.pytorch.attention.dot_product_attention.{name}" + ) + if module is not None: + module._release_cuda_state(device) # pylint: disable=protected-access + + +def clear_tensor_cache(cache, device): + """Remove entries retaining tensors on the selected device, including tuples.""" + + def contains(value): + if isinstance(value, torch.Tensor): + return value.device.type == "cuda" and value.device.index == device + if isinstance(value, dict): + return any(contains(item) for item in value.values()) + if isinstance(value, (tuple, list)): + return any(contains(item) for item in value) + return False + + for key, value in tuple(cache.items()): + if contains(value): + del cache[key] + + +def check_release_boundary(): + """Do not detach FP8 reduction registrations inside an active autocast.""" + from .quantization import FP8GlobalStateManager # pylint: disable=import-outside-toplevel + + state = FP8GlobalStateManager.quantization_state + if state.autocast_depth or state.fp8_graph_capturing: + raise RuntimeError("Release CUDA state outside FP8 autocast and graph capture") + + +def release_fp8_registrations(device): + """Remove device-scoped global references, preserving each model's numeric history. + + Buffer lists can contain registrations from several devices. Compact them + together and repair surviving modules' indices, rather than resetting all + quantization state or leaving holes in the reduction lists. + """ + from .quantization import FP8GlobalStateManager # pylint: disable=import-outside-toplevel + + manager = FP8GlobalStateManager + state = manager.quantization_state + index_key = manager.get_buffer_info() + metas = {} + for module in tuple(_MODULES): + meta = getattr(module, "fp8_meta", None) + if isinstance(meta, dict): + metas[id(meta)] = meta + for meta in (getattr(module, "_fp8_metas", None) or {}).values(): + if isinstance(meta, dict): + metas[id(meta)] = meta + target_metas = set() + for identity, meta in metas.items(): + registration = meta.get(index_key, ()) + for index, key in zip(registration[::2], registration[1::2]): + values = state.global_amax_buffer.get(key, ()) + if index < len(values) and values[index].device.index == device: + target_metas.add(identity) + for key, values in tuple(state.global_amax_buffer.items()): + keep = [index for index, tensor in enumerate(values) if tensor.device.index != device] + if len(keep) == len(values): + continue + remap = {old: new for new, old in enumerate(keep)} + for identity, meta in metas.items(): + registration = meta.get(index_key) + if registration is None: + continue + if identity in target_metas: + meta.pop(index_key, None) + meta["fp8_group"] = None + else: + for position in range(0, len(registration), 2): + if registration[position + 1] == key: + registration[position] = remap[registration[position]] + for buffers in ( + state.global_amax_buffer, + state.global_amax_history_buffer, + state.global_scale_buffer, + ): + if keep: + buffers[key] = [buffers[key][index] for index in keep] + else: + buffers.pop(key, None) + recompute_key = "global_fp8_buffer_pos_fwd_recompute" + removed = { + meta[recompute_key] + for identity, meta in metas.items() + if identity in target_metas and recompute_key in meta + } + if removed: + keep = [ + index + for index in range(len(state.fp8_tensors_recompute_buffer)) + if index not in removed + ] + remap = {old: new for new, old in enumerate(keep)} + state.fp8_tensors_recompute_buffer = [ + state.fp8_tensors_recompute_buffer[index] for index in keep + ] + for meta in metas.values(): + index = meta.get(recompute_key) + if index in removed: + meta.pop(recompute_key, None) + elif index is not None: + meta[recompute_key] = remap[index] + used = {manager.split_key_in_buffer(key)[1] for key in state.global_amax_buffer} + for key in tuple(state.autocast_arguments): + if key not in used: + del state.autocast_arguments[key] + skip = state.skip_fp8_weight_update_tensor + if skip is not None and skip.device.index == device: + state.skip_fp8_weight_update_tensor = None diff --git a/transformer_engine/pytorch/attention/dot_product_attention/context_parallel.py b/transformer_engine/pytorch/attention/dot_product_attention/context_parallel.py index 42fea51cecf..c2df4c23b72 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/context_parallel.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/context_parallel.py @@ -58,6 +58,19 @@ _softmax_offset_chunk_ids_cache = {} +def _release_cuda_state(device): + """Release cached sequence/chunk tensors on this CUDA device.""" + from ..._cuda_state import clear_tensor_cache # pylint: disable=import-outside-toplevel + + for cache in ( + _cu_seqlens_info_with_cp_cache, + _seq_chunk_ids_cache_for_reordering_before_attn, + _seq_chunk_ids_cache_for_reordering_after_attn, + _softmax_offset_chunk_ids_cache, + ): + clear_tensor_cache(cache, device) + + # Float8CurrentScaling: fused_attn_bwd takes O in FP8 by default, this flag allows it in F16 _dpa_fp8_cs_o_in_f16 = os.getenv("NVTE_DPA_FP8CS_O_in_F16", "1") == "1" diff --git a/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py b/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py index 80844adca43..774159fcc8a 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py @@ -110,6 +110,19 @@ "_alibi_bias_require_update": False, } + +def _release_cuda_state(device): + """Drop global ALiBi tensors while retaining other devices' entries.""" + for key, dirty in ( + ("_alibi_slopes", "_alibi_slopes_require_update"), + ("_alibi_bias", "_alibi_bias_require_update"), + ): + tensor = _alibi_cache[key] + if tensor is not None and tensor.device.type == "cuda" and tensor.device.index == device: + _alibi_cache[key] = None + _alibi_cache[dirty] = True + + # Sequence-ID validation synchronizes once to report malformed policy metadata. Share # successful validations across DPA layers, and retain only a small number of recent # policy sets so dynamically constructed batches do not grow the cache without bound. diff --git a/transformer_engine/pytorch/attention/dot_product_attention/flex_attention.py b/transformer_engine/pytorch/attention/dot_product_attention/flex_attention.py index c122b8faa43..a6f9a86a160 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/flex_attention.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/flex_attention.py @@ -17,6 +17,21 @@ _SCORE_MOD_UNCACHEABLE = object() +def _release_cuda_state(device): + """Destroy device-scoped cuDNN plans before their borrowed Python handles.""" + # Forward and backward keys put the query metadata at different positions; + # both metadata tuples end with the normalized CUDA device pair. + for key in tuple(_cudnn_score_mod_graph_cache): + query_meta = key[6] if key[0] == "fwd" else key[7] + if query_meta[-1] == ("cuda", device): + del _cudnn_score_mod_graph_cache[key] + key = torch.device("cuda", device) + handle = _cudnn_score_mod_handles.get(key) + if handle is not None: + _import_cudnn_frontend().destroy_handle(handle) + del _cudnn_score_mod_handles[key] + + def _import_cudnn_frontend(): """Import the cuDNN frontend Python package.""" try: diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 2ecf8a60090..3cbde0a6588 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -75,6 +75,13 @@ _cu_seqlens_cache = {} +def _release_cuda_state(device): + """Release device-resident sequence metadata at a serialized restart boundary.""" + from ..._cuda_state import clear_tensor_cache # pylint: disable=import-outside-toplevel + + clear_tensor_cache(_cu_seqlens_cache, device) + + class AttentionLogging: """ Manage logging for attention module diff --git a/transformer_engine/pytorch/cpp_extensions/gemm.py b/transformer_engine/pytorch/cpp_extensions/gemm.py index 96bbd490a04..05bc88529ed 100644 --- a/transformer_engine/pytorch/cpp_extensions/gemm.py +++ b/transformer_engine/pytorch/cpp_extensions/gemm.py @@ -12,6 +12,7 @@ import torch import transformer_engine_torch as tex from transformer_engine.pytorch.device import te_device_type +from .._cuda_state import device_cache from ..constants import TE_DType, DType from ..utils import ( get_device_compute_capability, @@ -54,7 +55,7 @@ def get_cublas_workspace_size_bytes() -> None: return 4_194_304 -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=0) def get_cublas_workspace(device: int, ub: bool, grouped_gemm: bool) -> torch.Tensor: """Returns workspace for cublas GEMM.""" assert not (ub and grouped_gemm), "UB is unsupported for grouped GEMM." @@ -623,19 +624,19 @@ def get_grouped_gemm_setup_workspace_size(num_tensors: int) -> int: return tex.get_grouped_gemm_setup_workspace_size(num_tensors) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=1) def _get_fp32_ones_tensor(num_tensors: int, device: torch.device) -> torch.Tensor: """Cached ones tensor.""" return torch.ones(num_tensors, dtype=torch.float32, device=device) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=1) def _get_fp32_zeros_tensor(num_tensors: int, device: torch.device) -> torch.Tensor: """Cached zeros tensor.""" return torch.zeros(num_tensors, dtype=torch.float32, device=device) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=0) def _get_grouped_gemm_setup_workspace(device: int, num_tensors: int) -> torch.Tensor: """Persistent setup workspace (per-group pointer/dim arrays) for grouped-tensor GEMM.""" return torch.empty( @@ -645,7 +646,7 @@ def _get_grouped_gemm_setup_workspace(device: int, num_tensors: int) -> torch.Te ) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=0) def _get_grouped_cublas_workspace(device: int, layout: str) -> torch.Tensor: """Persistent cuBLAS workspace for the grouped-tensor GEMM path, one per GEMM layout. diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index 2c25aae11bf..ef2280b33f9 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -198,6 +199,9 @@ void bind_quantize_with_amax_extensions(py::module_ &m) { #include "common/util/pybind_helper.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("reset_cuda_state", &nvte_reset_cuda_state, py::call_guard()); + m.def("release_cuda_state", &nvte_release_cuda_state, py::call_guard()); + m.def("get_cuda_state_version", &nvte_get_cuda_state_version); NVTE_DECLARE_COMMON_PYBIND11_HANDLES(m) // Register __eq__/__ne__ on the pybind ``DType`` enum so it compares by integer. diff --git a/transformer_engine/pytorch/cuda_context.py b/transformer_engine/pytorch/cuda_context.py new file mode 100644 index 00000000000..9a0b59f38b8 --- /dev/null +++ b/transformer_engine/pytorch/cuda_context.py @@ -0,0 +1,79 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Explicit Transformer Engine cleanup at an externally serialized restart boundary.""" + +import sys + +import torch +import transformer_engine_torch as tex + +from ._cuda_state import check_release_boundary, release_device_caches, release_fp8_registrations + + +def release_cuda_state() -> None: + """Release all TE-owned CUDA state at a process-wide restart boundary. + + Stop every TE caller, finish backward, and retire captured/compiled graphs + and external communication owners first. All ranks perform collective + cleanup before destroying borrowed process groups. Model tensors, optimizer + state, FP8 numerical history, RNG and the framework runtime are retained. + Only devices with an existing primary context are synchronized and visited. + This never resets CUDA or the framework allocator. + """ + check_release_boundary() + if torch.cuda.is_initialized(): + devices = [ + device + for device in range(torch.cuda.device_count()) + if torch._C._cuda_hasPrimaryContext(device) # pylint: disable=protected-access + ] + # Check every device before mutating any cache or entering synchronization. + for device in devices: + with torch.cuda.device(device): + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError("Release CUDA state outside graph capture") + for device in devices: + torch.cuda.synchronize(device) + torch.compiler.reset() + from . import ep # pylint: disable=import-outside-toplevel + from . import distributed # pylint: disable=import-outside-toplevel + from .module import base # pylint: disable=import-outside-toplevel + + if ep._BOOTSTRAPPED: # pylint: disable=protected-access + with torch.cuda.device(ep._BOOTSTRAP_DEVICE): # pylint: disable=protected-access + ep.ep_finalize() + pool_device = distributed._SYMM_MEM_POOL_DEVICE # pylint: disable=protected-access + if pool_device is not None: + with torch.cuda.device(pool_device): + distributed.release_symm_mem_pool() + if base._ub_initialized: # pylint: disable=protected-access + with torch.cuda.device(base._ub_device): # pylint: disable=protected-access + base.destroy_ub() + for device in devices: + with torch.cuda.device(device): + release_fp8_registrations(device) + release_device_caches(device) + tex.release_cuda_state() + backend = sys.modules.get("transformer_engine.common.CuTeDSL") + if backend is not None: + backend.release_cuda_state() + + +def reset_cuda_state() -> None: + """Invalidate common state after loss of all TE contexts, before CUDA initialization. + + A CUDA runtime already initialized by PyTorch cannot be repaired by TE: + allocator blocks, streams and generators are framework-owned. In that case + fail before touching stale tensors; restart the worker after actual context + loss. For a context-preserving restart use release_cuda_state instead. + Native callers with their own recovered allocator may use the common C API. + """ + if torch.cuda.is_initialized(): + raise RuntimeError( + "TE cannot recover an initialized PyTorch CUDA runtime after context loss. " + "Restart the worker, or call release_cuda_state while the context is usable " + "for a context-preserving in-process restart." + ) + tex.reset_cuda_state() diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index cf4c7b1e51b..2fc99dd39ed 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -81,6 +81,8 @@ def _check_nccl_runtime_version() -> None: _BOOTSTRAPPED = False +_BOOTSTRAP_DEVICE: Optional[int] = None +_EP_GENERATION = 0 _ATEXIT_REGISTERED = False # EP group captured at bootstrap; used by the zero-copy symm-mem pool allocator. _EP_GROUP: Optional[dist.ProcessGroup] = None @@ -125,7 +127,7 @@ class EpConfig: def _atexit_finalize() -> None: """Best-effort teardown at interpreter shutdown; swallows errors.""" - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _BOOTSTRAP_DEVICE if _BOOTSTRAPPED: try: tex.ep_finalize() @@ -135,6 +137,7 @@ def _atexit_finalize() -> None: traceback.print_exc() finally: _BOOTSTRAPPED = False + _BOOTSTRAP_DEVICE = None _EP_GROUP = None _EAGER = False _BOOTSTRAP_SETTINGS = None @@ -173,7 +176,7 @@ def ep_bootstrap( ``drop_on_overflow`` drops tokens exceeding ``recv_capacity_per_rank`` instead of trapping. Requires ``recv_capacity_per_rank``. """ - global _BOOTSTRAPPED, _ATEXIT_REGISTERED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS + global _BOOTSTRAPPED, _ATEXIT_REGISTERED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _BOOTSTRAP_DEVICE, _EP_GENERATION eager = recv_capacity_per_rank is None if _BOOTSTRAPPED: raise RuntimeError("ep_bootstrap was already called in this process") @@ -217,6 +220,8 @@ def ep_bootstrap( int(num_topk), bool(drop_on_overflow), ) + _EP_GENERATION += 1 + _BOOTSTRAP_DEVICE = torch.cuda.current_device() _BOOTSTRAPPED = True _EP_GROUP = ep_group _EAGER = bool(eager) @@ -269,7 +274,7 @@ def ep_finalize() -> None: a caller that used ``symm_mem_alloc(use_pool=True)`` does not need a separate ``release_symm_mem_pool()`` before destroying the PG. """ - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _BOOTSTRAP_DEVICE if not _BOOTSTRAPPED: return try: @@ -278,6 +283,7 @@ def ep_finalize() -> None: tex.ep_finalize() finally: _BOOTSTRAPPED = False + _BOOTSTRAP_DEVICE = None _EP_GROUP = None _EAGER = False _BOOTSTRAP_SETTINGS = None @@ -315,6 +321,7 @@ class EpBuffer: """ __slots__ = ( + "_generation", "handle_mem", "top_k", "alignment", @@ -349,6 +356,7 @@ def __init__( ) -> None: if not _BOOTSTRAPPED: raise RuntimeError("EpBuffer requires ep_bootstrap() to be called first.") + self._generation = _EP_GENERATION if device is None: device = torch.device("cuda", torch.cuda.current_device()) alignment = int(alignment) @@ -395,6 +403,11 @@ def __init__( self.total_recv_tokens = torch.empty(1, dtype=torch.int64, device=device) mark_not_offload(self.total_recv_tokens) + def check_generation(self): + """A routing buffer belongs to one bootstrap session, even with live CUDA.""" + if not _BOOTSTRAPPED or self._generation != _EP_GENERATION: + raise RuntimeError("EpBuffer belongs to a finalized EP session; create a new EpBuffer") + # torch.library custom ops (so they don't graph-break under torch.compile) @@ -1227,6 +1240,7 @@ def ep_dispatch( Returns (recv_tokens, recv_topk_weights, tokens_per_expert); tokens_per_expert is non-diff. See ``buffer.total_recv_tokens`` for the per-step recv total. """ + buffer.check_generation() if topk_weights.dtype is not torch.float32: raise TypeError( f"topk_weights must be float32; got dtype={topk_weights.dtype}. " @@ -1285,6 +1299,7 @@ def ep_combine( capture a graph. Result shape is (num_local_tokens, hidden_dim); num_local_tokens defaults to buffer.max_tokens_per_rank. """ + buffer.check_generation() _require_bf16("expert_out", expert_out) if buffer.eager and grad_out is not None: raise ValueError( diff --git a/transformer_engine/pytorch/module/base.py b/transformer_engine/pytorch/module/base.py index bf4f9bba1d5..72968b1436d 100644 --- a/transformer_engine/pytorch/module/base.py +++ b/transformer_engine/pytorch/module/base.py @@ -22,6 +22,7 @@ import transformer_engine_torch as tex from transformer_engine.pytorch.device import te_device_type +from .._cuda_state import register_module from ._common import _ParameterInitMeta, noop_cat, sum_bias_grad from .._extra_state import ( extra_state_pickle_advisory, @@ -90,6 +91,7 @@ _dummy_wgrads = {} _ub_communicators = None _ub_initialized = False +_ub_device: Optional[int] = None _ub_with_cublasmp = False _MIN_STREAM_PRIORITY, _MAX_STREAM_PRIORITY = None, None layers_atomic_ring_exchange = [] @@ -629,7 +631,8 @@ def add_ub( ub_cfg["fp8_buf"] = fp8_buf add_ub(name, quantization_mode, **ub_cfg) - global _ub_initialized + global _ub_initialized, _ub_device + _ub_device = torch.cuda.current_device() _ub_initialized = True @@ -654,10 +657,11 @@ def get_ub_is_fp8(name: str, use_fp8: bool) -> bool: def destroy_ub(): """Destroy all allocated userbuffer communicators.""" - global _ub_communicators, _ub_with_cublasmp, _ub_initialized + global _ub_communicators, _ub_with_cublasmp, _ub_initialized, _ub_device _ub_communicators = None _ub_with_cublasmp = False _ub_initialized = False + _ub_device = None global layers_atomic_ring_exchange layers_atomic_ring_exchange = [] # Compiled graphs may have baked is_fp8_ubuf() via assume_constant_result; @@ -1031,6 +1035,7 @@ def __init__(self, name: Optional[str] = None) -> None: self.fsdp_wrapped = False self.fsdp_group = None self._fp8_workspaces: Dict[str, QuantizedTensor] = {} + register_module(self) self.activation_dtype: Optional[torch.dtype] = None self.wgrad_accumulation_and_reduce_hooks = [] self.wgrad_store = None @@ -1041,6 +1046,10 @@ def __init__(self, name: Optional[str] = None) -> None: TEDebugState.initialize() self._validate_name() + def __setstate__(self, state): + super().__setstate__(state) + register_module(self) + def fast_setattr(self, name: str, value: Any) -> None: """ Fast version of the Module's set attribute function. diff --git a/transformer_engine/pytorch/ops/op.py b/transformer_engine/pytorch/ops/op.py index 359c508888c..961df41d9f9 100644 --- a/transformer_engine/pytorch/ops/op.py +++ b/transformer_engine/pytorch/ops/op.py @@ -14,7 +14,9 @@ import torch + from transformer_engine.common.recipe import Recipe +from .._cuda_state import register_module from .._extra_state import is_stateless_recipe, should_load_extra_state_pickle from ..quantization import ( FP8GlobalStateManager, @@ -342,8 +344,13 @@ def __init__(self) -> None: # Objects for quantization self._fp8_metas: Optional[dict[str, dict[str, Any]]] = None + register_module(self) self._quantizers: Optional[dict[str, list[Quantizer]]] = None + def __setstate__(self, state): + super().__setstate__(state) + register_module(self) + def _lock_extra_tensor_channels(self) -> None: """Freeze channel routing after an OperationFuser has captured it.""" self._extra_tensor_channels_locked = True diff --git a/transformer_engine/pytorch/tensor/nvfp4_tensor.py b/transformer_engine/pytorch/tensor/nvfp4_tensor.py index 78dea6cbee0..37424292fc9 100644 --- a/transformer_engine/pytorch/tensor/nvfp4_tensor.py +++ b/transformer_engine/pytorch/tensor/nvfp4_tensor.py @@ -16,6 +16,7 @@ from transformer_engine.pytorch.device import te_device_type from transformer_engine.common.recipe import NVFP4BlockScaling, Recipe +from .._cuda_state import device_cache from ..constants import NVFP4_BLOCK_SCALING_SIZE, dist_group_type, DType from ..utils import ( canonicalize_process_group, @@ -93,7 +94,7 @@ def get_hadamard_matrix(hadamard_dimension: int, device: int) -> torch.Tensor: ) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=1) def get_rht_matrix(with_random_sign_mask: bool, device: int) -> torch.Tensor: """Construct matrix used in random Hadamard transform.""" hadamard_dimension = 16 diff --git a/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py b/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py index 84ceb2a076e..0ff3208d42b 100644 --- a/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py +++ b/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py @@ -6,7 +6,6 @@ from __future__ import annotations from collections.abc import Iterable -import functools import math from typing import Annotated, Any, Dict, Optional, Tuple, Union import warnings @@ -21,9 +20,10 @@ from ...constants import TE_DType as torch_to_transformer_engine_dtype, DType from ...utils import _empty_tensor +from ..._cuda_state import device_cache -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=0) def _fp4_e2m1_vals(device: torch.device, dtype: torch.dtype) -> torch.Tensor: """Values representable in FP4 E2M1 format""" return torch.tensor( diff --git a/transformer_engine/pytorch/utils.py b/transformer_engine/pytorch/utils.py index 1a19476dac2..45eb7821b37 100644 --- a/transformer_engine/pytorch/utils.py +++ b/transformer_engine/pytorch/utils.py @@ -13,6 +13,7 @@ from contextlib import nullcontext import numpy as np import torch +from transformer_engine.pytorch._cuda_state import device_cache from transformer_engine.pytorch.device import te_device_type from ..common import decode_cudnn_version @@ -98,7 +99,7 @@ def warn_compile_eager_fallback(reason: str) -> None: ) -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=2) def get_cached_ones_tensor( num_elements: int, dtype: torch.dtype, @@ -119,7 +120,7 @@ def requires_grad(*tensors: Tuple[Optional[torch.Tensor], ...]) -> None: return False -@functools.lru_cache(maxsize=None) +@device_cache(device_arg=None) def _empty_tensor() -> torch.Tensor: """Get tensor with no entries and no data""" return torch.Tensor().cuda()