Skip to content

Let the CUDA allocator manage cuBLAS workspaces - #3625

Open
Vtmpas wants to merge 36 commits into
NVIDIA:mainfrom
Vtmpas:fix/cublas-workspace-per-stream
Open

Vtmpas wants to merge 36 commits into
NVIDIA:mainfrom
Vtmpas:fix/cublas-workspace-per-stream

Conversation

@Vtmpas

@Vtmpas Vtmpas commented Oct 5, 2026 •

Copy link
Copy Markdown

Description

Concurrent GEMMs on independent CUDA streams receive the same cuBLAS workspace from the device/mode cache and can overwrite each other's partial sums. On one H200, two FP32 NT GEMMs with a reduction dimension of 16384 produced incorrect results in 35 of 48 calls; separate scratch produced zero mismatches against serial execution.

Replace the Python workspace cache with invocation-local memory owned by PyTorch's CUDA allocator. Ordinary GEMMs allocate a native DataPtr in the PyTorch binding, avoiding per-call Python Tensor creation. The list/multistream grouped path uses one allocation with disjoint, 256-byte-aligned workspace slices. Its helper streams join the caller before the owner is released. Eager reuse remains stream-ordered; captured allocations belong to their graph's private pool. No persistent per-stream cache or new device synchronization is added.

Custom recipes and communication overlap retain explicit Tensor workspaces. Existing explicit-workspace callers remain supported; the private bindings additionally accept None with size zero to request native allocation. Usable workspace sizes, GEMM dtypes and algorithm selection are unchanged. The grouped-tensor backend is unchanged.

Type of change

  • Documentation change
  • Bug fix (non-breaking change which fixes an issue)
  • New feature
  • Breaking change
  • Infra/Build change
  • Code refactoring

Changes

  • Allocate scratch per invocation in the PyTorch native binding for ordinary and list/multistream grouped GEMMs.
  • Remove Linear and BasicLinear's preallocation workaround for globally cached scratch.
  • Test eager ownership, temporary-stream cleanup, graph-pool isolation across capture generations, concurrent FP32/BF16 graph replay, grouped GEMM numerics, and compiled opaque-GEMM graph generations. Observe native allocation requests without retaining Tensor references.
  • Cover router dgrad NN with weight[128,4096], grad_output[8192,128], output [8192,4096], and reduction 128 against exact analytic references in FP32 and BF16. Preserve NT coverage.
  • Include the workspace regression in the PyTorch L0 launcher.

Validation

Exception-path follow-up (efa5063, October 26): the common grouped launch now rejoins helper streams before rethrowing a recoverable GEMM error. On H200, the old core reproduces cudaErrorStreamCaptureUnjoined; the rebuilt core and PyTorch binding pass all 23 workspace tests, including the new partial-group failure/capture/recovery regression. Formatting, cpplint and the license check pass. No host/device-wide synchronization or additional successful-path CUDA calls were added. The earlier performance measurements below were not rerun for this exception-path change.

The following records the earlier native-allocation qualification:

H200, PyTorch 2.13.0+cu130, CUDA toolkit 13.0, cuBLASLt 13.5.1, native PyTorch CUDA allocator. The candidate binding was rebuilt with the same flags as main 9ea05cf2e8dc, using the unchanged common library.

  • All 22 cases in tests/pytorch/test_gemm_workspace.py pass, including the compiled opaque-GEMM capture-generation case, with no skips.
  • Three additional local operational regressions pass. The same independent-stream and concurrent graph-generation fixtures fail on main; both the prior PR revision and native implementation pass. Temporary-stream cleanup and invalid-request checks also pass.
  • A two-H200 quantized-wrapper check confirms that device selection follows actual storage and restores the caller's device.
  • All 288 paired benchmark comparisons have bitwise-identical outputs and module input/parameter gradients; 18 targeted recheck comparisons also match.
  • Six alternating main/candidate process pairs cover three shapes, BF16/block FP8, GEMM/grouped GEMM/Linear/GroupedLinear, and eager/graph execution. Small eager GEMM completion overhead is +1.65% BF16 and +3.48% FP8; grouped GEMM is +0.14%/+0.59%. Small Linear forward/backward is +0.05%/+1.51%, and GroupedLinear is -0.53%/-0.11%. These are paired medians, not universal bounds. CUDA graph replay is measured separately; median changes are within ±1% in these cases. Detailed timing, warmup flags and rechecks are in the benchmark comments below.
  • Pre-commit, scoped pylint/cpplint and the L0 license checker pass on macOS. Changes after GPU qualification are repository formatting only.
  • Follow-up in 48a48c91896a: update both Linear compile-test observers to the native binding. Both edited observers pass H200 capture checks through the compiled-GEMM fixture; the full Linear tests remain capability-skipped (11 cases) on the available PyTorch 2.13 build, pending the compatible opaque-object CI environment.
  • Full L0 validation of the new native revision remains pending CI. These tests do not establish full-model throughput, distributed-overlap performance or alternate allocator support.

Checklist

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

The workspace cache currently ignores the calling CUDA stream. Overlapping
GEMMs can therefore overwrite the same scratch buffer and return incorrect
results.

Include the stream in the cache key, keep reuse on each stream, and add
ownership and FP32/BF16 numerical regression tests.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Oct 5, 2026
@Vtmpas
Vtmpas marked this pull request as ready for review October 5, 2026 10:06
@Vtmpas
Vtmpas requested a review from ksivaman as a code owner October 5, 2026 10:06
@greptile-apps

greptile-apps Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; no new blocking issues were found.RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge; no new blocking issues were found.

Summary

Moves ordinary and list/grouped GEMM scratch from a Python cache to invocation-local allocations owned by PyTorch’s CUDA allocator.

  • Native GEMMs get separate scratch from PyTorch’s CUDA allocator.
  • Grouped GEMMs use separate aligned scratch for each helper stream.

Diagram

sequenceDiagram
    participant P as Python caller
    participant B as Native binding
    participant A as CUDA allocator
    participant G as GEMM streams
    P->>B: "GEMM with workspace=None"
    B->>A: Allocate invocation-local scratch
    A-->>B: Owned memory
    B->>G: Submit GEMMs with separate slices
    G-->>B: Join caller stream, including on launch error
    B->>A: Release owner
    B-->>P: Return outputs or rethrow error
Loading

Reviews (35) · Last reviewed commit: "Merge branch 'main' into fix/cublas-work..." · Reviewed by Greptile

@Vtmpas
Vtmpas marked this pull request as draft October 5, 2026 10:30
Keep scratch local to each invocation so graph captures use their own
private pools and temporary streams do not retain tensors in Python.
Remove Linear's preallocation workaround for the global workspace cache.

Cover concurrent graph replays, graph generations, scratch reclamation,
grouped GEMM stream joins, and compiled Linear forward and backward.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas Vtmpas changed the title Cache cuBLAS workspace by CUDA stream Let the CUDA allocator manage cuBLAS workspaces Oct 5, 2026
@Vtmpas
Vtmpas marked this pull request as ready for review October 5, 2026 10:44
Vtmpas and others added 3 commits October 5, 2026 14:08
Cover NN router dgrad with FP32 and BF16 operands in concurrent eager execution and independent CUDA graphs. Preserve NT wgrad coverage and exact references while retaining only one pair of large eager outputs.

All 22 workspace cases pass on native SM90 H200 with CUDA 13 and PyTorch 2.13, including all four new NN cases.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas

Vtmpas commented Oct 6, 2026

Copy link
Copy Markdown
Author

@Oleg-Goncharov , @ksivaman , hello! can i have your assistance here?

@Vtmpas

Vtmpas commented Oct 8, 2026

Copy link
Copy Markdown
Author

@ksivaman kindly

@ksivaman

ksivaman commented Oct 8, 2026

Copy link
Copy Markdown
Member

/te-ci pytorch L0

@itwastony itwastony left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

had the same trouble, thanks

@greptile-apps

This comment has been minimized.

@greptile-apps

greptile-apps Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

Replace the cold-start test's cache_info assertions with checks for capture-time allocation and release of workspace tensors. Keep output and gradient comparisons across CUDA, CPU and meta initialization.

Remove BasicLinear's obsolete cache preallocation and use the existing opaque-object capability guard for compiled execution.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas
Vtmpas requested a review from timmoon10 as a code owner October 8, 2026 21:45
@Vtmpas

Vtmpas commented Oct 8, 2026

Copy link
Copy Markdown
Author

Fixed in f01b35e, on top of the latest main merge. The cold-start test now checks capture-time workspace allocation and release of Python tensor references instead of cache_info(). BasicLinear no longer preallocates scratch for the removed cache. The six initialization/training combinations, fullgraph capture checks, and output/gradient comparisons are preserved.

On H200 with CUDA 13 and PyTorch 2.13, the original AttributeError reproduced before the fix. Afterward, 22 workspace tests, the fake-initialization test, and three BasicLinear CUDA-graph cases passed. The six compiled cold-start cases are capability-skipped because this PyTorch lacks register_custom_class; execution of those cases on a compatible PyTorch build remains unverified. Formatting, scoped pylint, and the license check passed.

@Vtmpas

Vtmpas commented Oct 22, 2026

Copy link
Copy Markdown
Author

@ksivaman could you rerun PyTorch L0 on 48a48c9 and take another look at the fix when you have a chance? Thanks!

Vtmpas and others added 3 commits October 26, 2026 16:20
Preserve a launch exception until all forked helper streams have rejoined the caller. This keeps earlier GEMMs ordered before caller-owned scratch is released, including when a later operation is rejected.

Add a regression that catches a later native bias-type error during CUDA graph capture, checks the completed prefix and untouched rejected output, and verifies eager recovery.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@zhongbozhu

Copy link
Copy Markdown
Collaborator

/te-ci pytorch L0 L1

@zhongbozhu zhongbozhu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I have found similar issues where upper frameworks enable some overlap features and might run into issues like this.

Beside cublas backend, TE also has cudnn cutedsl grouped gemms which also needs its own workspace buffer, can we apply similar technique for those (without introducing too much cpu overhead)?

@Vtmpas

Vtmpas commented Oct 29, 2026 •

Copy link
Copy Markdown
Author

I have found similar issues where upper frameworks enable some overlap features and might run into issues like this.

Beside cublas backend, TE also has cudnn cutedsl grouped gemms which also needs its own workspace buffer, can we apply similar technique for those (without introducing too much cpu overhead)?

I can do it. It you want me to.

imo, it's important here.

@Vtmpas

Vtmpas commented Nov 2, 2026

Copy link
Copy Markdown
Author

Kr

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas

Vtmpas commented Nov 3, 2026

Copy link
Copy Markdown
Author

@zhongbozhu @ksivaman @timmoon10 I merged current main (b021980) in e1cd588, resolving the Linear conflict while keeping the shared-workspace preallocation removed. DCO, pre-commit and Greptile pass. Could you rerun PyTorch L0/L1 on this head and take another look?

The cuBLAS implementation and evidence are already in the PR:

  • Native allocation: invocation-local DataPtr, with disjoint slices for helper streams. The H200 comparison measured +0.211 µs host enqueue for small BF16 GEMM and +0.056 µs for grouped BF16 versus main 9ea05cf; these are whole-submission timings, not isolated allocator cost.
  • Exception-path fix and regression: join submitted helper-stream work before rethrowing. All 23 workspace tests passed on H200 on October 26. Those GPU results predate today's merge; I haven't rerun them on the merged head.

I also traced the cuDNN/CuTeDSL paths. In our frontend 1.26 runtime, the compiled operators retain mutable workspace, and the wgrad launch closures capture it. The wgrad API does not expose caller workspace, so changing an operator attribute after compilation would not redirect those launches. TE's newer descriptor-workspace path caches by FC role/configuration/device, which doesn't isolate overlapping calls or independent graph generations.

The follow-up should reuse compiled kernels but separate workspace ownership for overlapping calls and graph lifetimes, then measure eager enqueue cost and graph replay separately. I haven't added an unverified cuDNN patch here: we only have H200/H100, while these kernels require SM100+. Could you confirm the frontend version/API to target and provide Blackwell CI coverage for concurrent calls, capture generations and delayed wgrad?

@zhongbozhu

Copy link
Copy Markdown
Collaborator

/te-ci pytorch

@Vtmpas

Vtmpas commented Nov 9, 2026

Copy link
Copy Markdown
Author

Up

@Vtmpas

Vtmpas commented Nov 11, 2026

Copy link
Copy Markdown
Author

@zhongbozhu are any updates or concerns here?

@zhongbozhu

Copy link
Copy Markdown
Collaborator

/te-ci pytorch L1

Preserve main's separate C and D arguments in the grouped GEMM launch. Keep the helper stream joins before rethrowing a launch error.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas

Vtmpas commented Nov 23, 2026

Copy link
Copy Markdown
Author

@zhongbozhu @ksivaman @timmoon10 I resolved the merge conflict in 985b7a23. The merge keeps main's separate C/D handling and the PR's helper-stream joins on exceptions. Local pre-commit, cpplint and the license check passed.

The Nov 18 L1 request stopped at the mergeability check, so no tests ran. PyTorch L0 passed on the earlier Nov 6 run. Could one of you run /te-ci pytorch L0 L1 on the new head and take another look? Thanks!

@zhongbozhu

Copy link
Copy Markdown
Collaborator

/te-ci pytorch L0 L1

Bring in the pack_forward_args lint fix from NVIDIA#3941.

Signed-off-by: Matvey Saprykin <mtvey.s@gmail.com>
@Vtmpas

Vtmpas commented Nov 27, 2026

Copy link
Copy Markdown
Author

@zhongbozhu thanks for running L0/L1. All 12 GPU checks on 985b7a23 passed. The only failing job was L0 lint, which flagged W0613 in activation.py.

I merged current main in 746692fe, bringing in the upstream fix from #3941. I reproduced the warning with pylint 4.1.3 on the old head and verified that it clears after the merge. The workspace patch is unchanged relative to main.

@ksivaman @timmoon10 could one of you rerun PyTorch L0/L1 on 746692fe and take a look when you have a chance? Thanks.

@rohitna

rohitna commented Nov 29, 2026

Copy link
Copy Markdown

Thanks for this change. One thing I noticed while reading it: the description says the grouped-tensor backend is unchanged, and I think that path has the same sharing problem, with one extra buffer involved. It may be worth covering here or in a follow-up.

In transformer_engine/pytorch/cpp_extensions/gemm.py, general_grouped_gemm_for_grouped_tensor takes two persistent buffers from functools.lru_cache:

  • _get_grouped_gemm_setup_workspace(device, num_tensors): the per-group pointer and dimension arrays that the setup kernel writes and the grouped GEMM then reads;
  • _get_grouped_cublas_workspace(device, layout): the cuBLAS scratch, one per layout (TN, NN, NT).

Neither cache key includes the CUDA stream. So two grouped GEMMs with the same number of groups, running on two streams of one device, share the setup buffer, and if they also have the same layout they share the scratch. The second call's setup kernel can overwrite the pointer arrays while the first call's GEMM is still reading them.

Where we saw it: MoE training with the fused grouped MLP, with the expert weight gradients delayed onto a side stream while the main stream ran the next grouped GEMM for the same number of experts. The symptom was a crash or a hang inside the grouped GEMM, and it went away when both buffers were keyed by torch.cuda.current_stream(device).cuda_stream.

To be clear about how solid this is: we hit it on an older TE revision in our own integration branch, and I have not reproduced it on current main with a stand-alone test. The two caches are still keyed the same way on main, which is why I am raising it.

Two questions:

  1. Would you prefer the grouped-tensor path to get the same treatment as this PR (scratch owned by the invocation), or a per-stream key on the existing caches as a smaller step?
  2. If it helps, I can write a test in the style of tests/pytorch/test_gemm_workspace.py for the grouped-tensor path: two streams, same group count, compared against serial execution.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants