From 4383dfb61b3dbdeb6cec9c4f244e07a5d14a73dd Mon Sep 17 00:00:00 2001 From: Matvey Saprykin Date: Thu, 3 Dec 2026 13:27:30 +0300 Subject: [PATCH 1/3] Isolate GroupedTensor GEMM workspaces by invocation Allocate the mutable pointer arrays and cuBLAS scratch on the invoking stream. Clear scratch on older cuBLASLt before dispatch to avoid carrying stale descriptors across layouts. Cover independent graph generations and repeated FP8 block-scaling replay. Signed-off-by: Matvey Saprykin --- tests/pytorch/test_grouped_linear.py | 136 +++++++++++++++--- .../pytorch/cpp_extensions/gemm.py | 43 ++---- 2 files changed, 128 insertions(+), 51 deletions(-) diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index a8eee077012..2692bcb9281 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -1188,6 +1188,109 @@ def test_grouped_gemm_grouped_tensor(z, m, n, k, case, layout, accumulate, use_b torch.testing.assert_close(o, o_ref, **tols) +@pytest.mark.parametrize("layouts", [("TN",), ("NN",), ("NT",), ("NN", "NT")]) +def test_grouped_gemm_grouped_tensor_workspace_isolation(layouts, monkeypatch) -> None: + """Independent streams/graphs must not share mutable grouped GEMM workspaces. + + The NN followed by NT case also covers workspace reuse across layouts. + """ + dtype = torch.bfloat16 + if not is_module_grouped_tensor_path_supported(None, dtype): + pytest.skip("BF16 GroupedTensor GEMM is unavailable.") + + torch.manual_seed(0) + device = torch.device("cuda") + z, n, k = 3, 256, 128 + # Same group count and total rows, but different per-group pointer/dimension arrays. + split_sets = ([128, 256, 384], [384, 128, 256]) + invocations = [] + for splits in split_sets: + calls = [] + for layout in layouts: + if layout == "NT": + a = _make_grouped_tensor_from_splits(splits, k, device, dtype) + out = _make_grouped_tensor_uniform(z, n, k, device, dtype) + else: + a = _make_grouped_tensor_uniform(z, n, k, device, dtype) + out = _make_grouped_tensor_from_splits( + splits, n if layout == "TN" else k, device, dtype + ) + b = _make_grouped_tensor_from_splits(splits, k if layout == "TN" else n, device, dtype) + a.rowwise_data.normal_() + b.rowwise_data.normal_() + calls.append((a, b, out, layout)) + invocations.append(calls) + + def run(calls): + for a, b, out, layout in calls: + general_grouped_gemm_for_grouped_tensor(a, b, out, layout=layout) + + # Serial execution is also the warm-up for all layouts before stream use/capture. + expected = [] + for calls in invocations: + run(calls) + expected.append([out.rowwise_data.clone() for _, _, out, _ in calls]) + torch.cuda.synchronize() + + streams = [torch.cuda.Stream(), torch.cuda.Stream()] + for stream in streams: + stream.wait_stream(torch.cuda.current_stream()) + + def check(): + for calls, references in zip(invocations, expected): + for (_, _, out, _), reference in zip(calls, references): + torch.testing.assert_close(out.rowwise_data, reference, **dtype_tols(dtype)) + + # Submit both workloads before synchronizing either stream. + for _ in range(3): + for stream, calls in zip(streams, invocations): + with torch.cuda.stream(stream): + for _, _, out, _ in calls: + out.rowwise_data.fill_(float("nan")) + run(calls) + for stream in streams: + stream.synchronize() + check() + + # Observe the actual native call, without extending any workspace tensor's lifetime. + native = tex.te_general_grouped_gemm_for_grouped_tensor + addresses = [] + + def record_workspaces(*args, **kwargs): + addresses.append((args[9].data_ptr(), args[10].data_ptr())) + return native(*args, **kwargs) + + monkeypatch.setattr(tex, "te_general_grouped_gemm_for_grouped_tensor", record_workspaces) + graphs = [torch.cuda.CUDAGraph(), torch.cuda.CUDAGraph()] + capture_stream = torch.cuda.Stream() + # Inputs and split metadata were initialized on the caller stream. Both graphs + # use one capture stream so a cache keyed by capture stream also fails this test. + capture_stream.wait_stream(torch.cuda.current_stream()) + for graph, calls in zip(graphs, invocations): + # Separate default graph pools: sharing a pool would require serial replay. + with torch.cuda.graph(graph, stream=capture_stream): + run(calls) + for stream in streams: + stream.wait_stream(capture_stream) + + assert len(addresses) == 2 * len(layouts) + # Independent graph pools must not alias. Reuse between ordered calls within + # one graph is legal (and exercises the legacy scratch reset for NN -> NT). + first, second = addresses[: len(layouts)], addresses[len(layouts) :] + assert {setup for setup, _ in first}.isdisjoint(setup for setup, _ in second) + assert {scratch for _, scratch in first}.isdisjoint(scratch for _, scratch in second) + + for _ in range(5): + for graph, stream, calls in zip(graphs, streams, invocations): + with torch.cuda.stream(stream): + for _, _, out, _ in calls: + out.rowwise_data.fill_(float("nan")) + graph.replay() + for stream in streams: + stream.synchronize() + check() + + @pytest.mark.parametrize("out_kind", ["discrete", "grouped"]) @pytest.mark.parametrize("out_dtype", [torch.float32, torch.bfloat16]) @pytest.mark.parametrize("accumulate", [False, True]) @@ -3655,9 +3758,6 @@ def _zero_grads(): else: param.grad.zero_() - def _clone_param_grads(): - return [param.grad.detach().clone() for param in grouped_linear.parameters()] - def _train_step(x, dy, out_buf, *, use_graphed): with autocast(enabled=use_fp8, recipe=fp8_recipe): out = ( @@ -3683,21 +3783,6 @@ def _train_step(x, dy, out_buf, *, use_graphed): static_x.copy_(fresh_x) static_dy.copy_(fresh_dy) - _zero_grads() - graph_out = ( - _train_step( - static_x, - static_dy, - static_out_buf, - use_graphed=True, - ) - .detach() - .clone() - ) - torch.cuda.synchronize() - graph_dx = static_x.grad.detach().clone() - graph_param_grads = _clone_param_grads() - _zero_grads() expected_x = fresh_x.detach().clone().requires_grad_(True) expected_dy = fresh_dy.detach().clone() @@ -3708,11 +3793,16 @@ def _train_step(x, dy, out_buf, *, use_graphed): tols = dict(rtol=1e-2, atol=5e-3) if use_fp8: tols = dict(rtol=0.05, atol=0.05) - torch.testing.assert_close(graph_out.float(), expected_out.float(), **tols) - torch.testing.assert_close(graph_dx.float(), expected_x.grad.float(), **tols) - for graph_grad, param in zip(graph_param_grads, reference_grouped_linear.parameters()): - assert param.grad is not None - torch.testing.assert_close(graph_grad.float(), param.grad.float(), **tols) + # Older cuBLASLt could fail on the second FP8 block-scaling backward replay. + replay_count = 2 if isinstance(fp8_recipe, recipe.Float8BlockScaling) else 1 + for _ in range(replay_count): + _zero_grads() + graph_out = _train_step(static_x, static_dy, static_out_buf, use_graphed=True) + torch.testing.assert_close(graph_out.float(), expected_out.float(), **tols) + torch.testing.assert_close(static_x.grad.float(), expected_x.grad.float(), **tols) + for param, ref in zip(grouped_linear.parameters(), reference_grouped_linear.parameters()): + assert param.grad is not None and ref.grad is not None + torch.testing.assert_close(param.grad.float(), ref.grad.float(), **tols) def test_fp8_block_scaling_grouped_tensor_path_matches_mxfp8_support(): diff --git a/transformer_engine/pytorch/cpp_extensions/gemm.py b/transformer_engine/pytorch/cpp_extensions/gemm.py index b5c6220affb..80c848f7b29 100644 --- a/transformer_engine/pytorch/cpp_extensions/gemm.py +++ b/transformer_engine/pytorch/cpp_extensions/gemm.py @@ -753,28 +753,10 @@ def _get_fp32_zeros_tensor(num_tensors: int, device: torch.device) -> torch.Tens return torch.zeros(num_tensors, dtype=torch.float32, device=device) -@functools.lru_cache(maxsize=None) -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( - get_grouped_gemm_setup_workspace_size(num_tensors), - dtype=torch.uint8, - device=device, - ) - - -@functools.lru_cache(maxsize=None) -def _get_grouped_cublas_workspace(device: int, layout: str) -> torch.Tensor: - """Persistent cuBLAS workspace for the grouped-tensor GEMM path, one per GEMM layout. - - Grouped cuBlasLt GEMM kernels in cuBLAS versions <= 13.7 leave behind stale descriptors in the - workspace that cause back-to-back GEMM kernels to crash/deadlock on 2nd CUDA-graph replay. As a - workaround, we allocate a different workspace for each GEMM layout (TN, NN, NT) to avoid - contamination between subsequent GEMM calls (when there is no other graph node between GEMM - kernels). - """ - assert layout in ("TN", "NN", "NT"), f"unexpected grouped GEMM layout {layout}" - return torch.empty(get_cublas_workspace_size_bytes(), dtype=torch.uint8, device=device) +@functools.lru_cache(maxsize=1) +def _grouped_cublas_workspace_needs_clear() -> bool: + """Whether workspace reuse can carry stale descriptors between grouped GEMMs.""" + return tex.get_cublasLt_version() < 130800 def general_grouped_gemm_for_grouped_tensor( @@ -877,12 +859,17 @@ def general_grouped_gemm_for_grouped_tensor( if not alpha.is_cuda or not beta.is_cuda: raise ValueError("alpha and beta must be CUDA tensors.") - workspace_setup = _get_grouped_gemm_setup_workspace(device.index, num_tensors) - # Each grouped-GEMM layout gets its own persistent cuBLAS workspace: two grouped - # GEMMs sharing one workspace can deadlock under CUDA-graph replay (see - # _get_grouped_cublas_workspace). wgrad (NT) is the case seen in TE; fprop (TN) and - # dgrad (NN) have also been reported to conflict, so all three layouts are isolated. - workspace_cublas = _get_grouped_cublas_workspace(device.index, layout) + # The setup kernel writes the pointer arrays that cuBLAS reads. Allocate both + # buffers on the caller's stream, so the allocator orders eager reuse and + # keeps captured allocations in the graph's private pool. + workspace_setup = torch.empty( + get_grouped_gemm_setup_workspace_size(num_tensors), dtype=torch.uint8, device=device + ) + # A graph can reuse a scratch address for a different layout. Clear stale + # descriptors before each launch on older cuBLASLt, including during replay + # (see the second-replay hang in #3171). + allocate_workspace = torch.zeros if _grouped_cublas_workspace_needs_clear() else torch.empty + workspace_cublas = allocate_workspace(32 * 1024 * 1024, dtype=torch.uint8, device=device) sm_count = get_sm_count() sm_count = sm_count - int(os.getenv("NVTE_EXT_MARGIN_SM", str(sm_count))) From deaa7e818dac9c5ffbc266a37bcffc3c53eb9fa9 Mon Sep 17 00:00:00 2001 From: Matvey Saprykin Date: Thu, 3 Dec 2026 13:30:00 +0300 Subject: [PATCH 2/3] Reset leaf gradients safely between graph replays Signed-off-by: Matvey Saprykin --- tests/pytorch/test_grouped_linear.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index 2692bcb9281..38ada8a1ca6 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -3749,15 +3749,6 @@ def test_grouped_linear_fused_path_cuda_graph_safe(fp8_recipe, bias, monkeypatch static_dy = torch.randn(total_tokens, out_features, dtype=dtype, device=device) static_out_buf = torch.empty(total_tokens, out_features, dtype=dtype, device=device) - def _zero_grads(): - if static_x.grad is not None: - static_x.grad.zero_() - for param in grouped_linear.parameters(): - if param.grad is None: - param.grad = torch.zeros_like(param) - else: - param.grad.zero_() - def _train_step(x, dy, out_buf, *, use_graphed): with autocast(enabled=use_fp8, recipe=fp8_recipe): out = ( @@ -3795,11 +3786,19 @@ def _train_step(x, dy, out_buf, *, use_graphed): tols = dict(rtol=0.05, atol=0.05) # Older cuBLASLt could fail on the second FP8 block-scaling backward replay. replay_count = 2 if isinstance(fp8_recipe, recipe.Float8BlockScaling) else 1 - for _ in range(replay_count): - _zero_grads() + for replay in range(replay_count): + # A previous replay's returned gradient can alias a static graph output. + # Drop the leaf references instead of writing into the graph's buffers. + static_x.grad = None + grouped_linear.zero_grad(set_to_none=True) graph_out = _train_step(static_x, static_dy, static_out_buf, use_graphed=True) torch.testing.assert_close(graph_out.float(), expected_out.float(), **tols) - torch.testing.assert_close(static_x.grad.float(), expected_x.grad.float(), **tols) + torch.testing.assert_close( + static_x.grad.float(), + expected_x.grad.float(), + msg=lambda msg: f"Replay {replay + 1}: {msg}", + **tols, + ) for param, ref in zip(grouped_linear.parameters(), reference_grouped_linear.parameters()): assert param.grad is not None and ref.grad is not None torch.testing.assert_close(param.grad.float(), ref.grad.float(), **tols) From f59f5cde70342dc409fb53d69a6225bb2109e752 Mon Sep 17 00:00:00 2001 From: Matvey Saprykin Date: Thu, 3 Dec 2026 13:30:53 +0300 Subject: [PATCH 3/3] Remove obsolete gradient-reset call from the serial reference Signed-off-by: Matvey Saprykin --- tests/pytorch/test_grouped_linear.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index 38ada8a1ca6..18498fa7e85 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -3774,7 +3774,6 @@ def _train_step(x, dy, out_buf, *, use_graphed): static_x.copy_(fresh_x) static_dy.copy_(fresh_dy) - _zero_grads() expected_x = fresh_x.detach().clone().requires_grad_(True) expected_dy = fresh_dy.detach().clone() with autocast(enabled=use_fp8, recipe=fp8_recipe):