Repository navigation
[CUDA] Add fork/join execution on CUDA streams - #199128
MatthiasKohl wants to merge 11 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199128
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 43b371c with merge base d0b8bbb ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Add `execute_in_green_contexts` to fork work from the caller stream into supplied green-context streams and join queued work back to the caller. Same-device execution switches directly between streams and restores the caller once to reduce host-side overheads. Cross-device execution uses stream context managers to restore device and stream state. > Authored with an AI assistant. > > Callbacks that raise still restore the caller state and join work already queued. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat. 56 tests passed. ```sh python test/test_cuda.py TestCudaGreenContextsCUDA TestGreenContextExecution -v ``` ghstack-source-id: a021045 Pull-Request: pytorch#199128
|
AI-assisted Could this be Please reduce the nine-case mocked stream-switching matrix. Success, exceptions, restoration, and joining are already exercised by the hardware tests. At most, keep a focused test for the intended same-device fast path; exact event-construction order and stream-selection call sequences should not become the behavioral contract. Hardware coverage for ordinary streams and capture/replay through this helper would be more useful. |
[ghstack-poisoned]
yes this makes sense, I have updated the PR accordingly, as well as reduced the test matrix. |
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude typically users would want functional callbacks that return some result ( |
|
Claude finished @ngimel's task in 1m 6s —— View job Proposal: make it a Details: proposed API, sketch, and caveatsWhy
|
|
@claude can you learn at some point truly for real and forever that record_stream is banned and no one should ever call it? |
|
Claude finished @ngimel's task in 1m 3s —— View job You're right, and I'm sorry. Here is the corrected proposal with no Details: corrected API and why no lifetime hooks are neededRetractionPlease ignore every Why the fork/join already makes returned tensors and inputs safe
API (same shape as before, minus lifetime hooks)def execute_on_streams(
streams: Sequence[Stream],
fn: Callable[..., T],
*iterables: Iterable[Any],
) -> list[T]:
"""Like ``map(fn, *iterables)``, with call ``i`` enqueued on ``streams[i]``,
forked from and joined back to the caller stream."""ys = torch.cuda.execute_on_streams(streams, shard_fn, xs) # y_i = f(x_i), autograd works
ys = torch.cuda.execute_on_streams(streams, fn, range(len(streams))) # current index formThe implementation is today's fork loop plus Tests worth adding
|
|
@claude but if we are making allocations on stream S we also should activate corresponding mempool there to get advantage of locality domains? |
|
Claude finished @ngimel's task in 1m 11s —— View job Yes. Without a localized pool, the outputs that a green-context callback allocates come from the default pool, so they land on whatever physical memory that pool has. You get compute locality but not memory locality. I'd add an optional per-stream pool argument to the helper rather than tying pools to streams. Details: proposed shape, why it's explicit, and caveatsProposed shapedef execute_on_streams(
streams: Sequence[Stream],
fn: Callable[..., T],
*iterables: Iterable[Any],
mem_pools: Sequence[MemPool | None] | None = None,
) -> list[T]:Per stream pool = mem_pools[i] if mem_pools is not None else None
with use_mem_pool(pool, device=stream.device) if pool is not None else nullcontext():
results.append(fn(*args))Example usage with green contexts: ctxs = GreenContext.split(num_sms=(24, 24), locality_domain_ids=[0, 1], device_id=0)
pools = [MemPool(allocator=LocalizedAllocator(locality_domain_id=c.locality_domain_id, device="cuda:0").allocator()) for c in ctxs]
ys = torch.cuda.execute_on_streams([c.Stream() for c in ctxs], shard_fn, xs, mem_pools=pools)Why an explicit argument instead of auto-detecting
Does the fork/join safety argument still hold?Yes. The caching allocator still only reuses a block on the stream it was allocated on, inside the pool as well. So the ordering from my last comment still applies: Caveats worth documenting or testing
|
|
@ngimel some time ago, you rejected my proposed design of tying the fork/join execution to mem pools. |
|
You want the callback itself to activate mempool? Yes, that should work, we don't have to overcomplicate fork/join wrapper |
[ghstack-poisoned]
yes, it lets the user choose whether they want to use localized outputs or not and keeps the API / implementation here a little cleaner. I'll update the API to the map-style as suggested here, and I'll add this to the docs as well |
[ghstack-poisoned]
ngimel
left a comment
There was a problem hiding this comment.
small doc cleanup, otherwise lgtm
| Python callbacks run sequentially; their CUDA work may execute concurrently. | ||
| Each stream waits for work previously submitted to the caller's current | ||
| stream. Subsequent work on the caller stream waits for every callback's | ||
| queued work, including work queued before a callback raises. These waits |
There was a problem hiding this comment.
"asynchronous and do not synchronize the host." - you are repeating yourself
The localized path imported torch.cuda.green_contexts.execute_in_green_contexts and raised otherwise. No released PyTorch provides it (including the CI image's 2.14.0), and the open upstream proposal (pytorch/pytorch#199128) now names the helper torch.cuda.execute_on_streams. The path therefore failed on every stock PyTorch build. Resolve torch.cuda.execute_on_streams first, then the earlier name, and otherwise use an in-repo helper with the proposal's semantics: each stream waits on an event recorded on the caller stream, and the caller stream waits on a per-callback completion event that is recorded even when the callback raises. Callers keep supplying their green-context streams (for example GreenContext.Stream()). The Rubin GPU test now runs without an executor shim on ordinary and real green-context streams. Mocked tests patch _resolve_stream_executor instead of sys.modules, and the missing-API test now checks the resolution order. AI-assisted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
> AI-assisted: map-style stream execution, localized-output docs, trim redundant tests. [ghstack-poisoned]
[ghstack-poisoned]
|
@pytorchbot merge |
Merge failedReason: This PR needs a If not, please add the To add a label, you can comment to pytorchbot, for example For more information, see Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Fix potential races in green context stream pool slot selection/creation/indexing. > Authored with an AI assistant. > > The lock covers creation through publication; failed creation leaves the index unchanged. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat. All 3 focused stream-pool tests passed. ```sh python test/test_cuda.py TestGreenContextStreamPool -v ``` Pull Request resolved: #199129 Approved by: https://github.com/ngimel ghstack dependencies: #199127, #199128
….t. MPS (#199130) Improve documentation of the NVML based check for locality support: later attachment to MPS isn't supported. > Authored with an AI assistant. > > The limitation concerns the pre-initialization NVML estimate. Already attached clients use the CUDA driver path; query again after attachment rather than reusing an earlier estimate. These regression tests do not test dynamic MPS attachment. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat. All 10 existing locality-query regression tests passed. ```sh python test/test_cuda.py TestCudaGreenContextsCUDA -k locality -v ``` Pull Request resolved: #199130 Approved by: https://github.com/ngimel ghstack dependencies: #199127, #199128, #199129
> Authored with an AI assistant. > > Add `torch.cuda.execute_on_streams` for fork/join execution with ordinary > streams, green-context streams, or mixtures. Queued work is joined and > caller state restored even when a callback raises. Same-device execution switches directly between streams and restores the caller once to reduce host-side overheads. Cross-device execution uses stream context managers to restore device and stream state. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat (56 tests passed) Pull Request resolved: pytorch#199128 Approved by: https://github.com/ngimel ghstack dependencies: pytorch#199127
…9129) Fix potential races in green context stream pool slot selection/creation/indexing. > Authored with an AI assistant. > > The lock covers creation through publication; failed creation leaves the index unchanged. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat. All 3 focused stream-pool tests passed. ```sh python test/test_cuda.py TestGreenContextStreamPool -v ``` Pull Request resolved: pytorch#199129 Approved by: https://github.com/ngimel ghstack dependencies: pytorch#199127, pytorch#199128
….t. MPS (pytorch#199130) Improve documentation of the NVML based check for locality support: later attachment to MPS isn't supported. > Authored with an AI assistant. > > The limitation concerns the pre-initialization NVML estimate. Already attached clients use the CUDA driver path; query again after attachment rather than reusing an earlier estimate. These regression tests do not test dynamic MPS attachment. Test Plan Tested on Rubin with driver R610 + CUDA 13.4 compat. All 10 existing locality-query regression tests passed. ```sh python test/test_cuda.py TestCudaGreenContextsCUDA -k locality -v ``` Pull Request resolved: pytorch#199130 Approved by: https://github.com/ngimel ghstack dependencies: pytorch#199127, pytorch#199128, pytorch#199129
…#6488) <!-- .github/pull_request_template.md --> ## 📌 Description After [#5276 — feat(moe): add Rubin locality-domain execution](#5276) was merged, [PyTorch updated its stream-execution API in pytorch/pytorch#199128](pytorch/pytorch#199128) to require explicit callback input sequences. This PR updates FlashInfer to that upstream API change and restores compatibility with the newer PyTorch nightly builds. The updated API is `execute_on_streams(streams, fn, *inputs)`: callback arguments come from the supplied input sequences, rather than an implicitly supplied stream index. FlashInfer's existing two-argument calls reflected the earlier interface and are incompatible with this newer contract. Both FC1 and FC2 now explicitly pass the locality-domain shard indices: ```python torch.cuda.execute_on_streams( localized_streams, callback, range(len(localized_streams)) ) ``` Use this single upstream interface directly and remove the local fork/join implementation, executor resolver, and legacy callback-arity handling. Keep the existing failure-path stream joins so queued work remains ordered before the exception propagates. Localized execution now explicitly requires a PyTorch build providing `torch.cuda.execute_on_streams`. Non-localized execution does not require that API. This is an API-compatibility fix, not a new kernel or a standalone performance optimization. ## 🔍 Related Issues - Previous implementation: [#5276 — feat(moe): add Rubin locality-domain execution](#5276). - Upstream API: [pytorch/pytorch#199128](pytorch/pytorch#199128); the landed implementation in [commit 5ba7f2bf](pytorch/pytorch@5ba7f2b) defines `execute_on_streams(streams, fn, *inputs)` and rejects calls without input sequences. ## 🚀 Pull Request Checklist Thank you for contributing to FlashInfer! Before we review your pull request, please make sure the following items are complete. ### ✅ Pre-commit Checks - [x] I have installed `pre-commit` by running `pip install pre-commit` (or used your preferred method). - [x] I have installed the hooks with `pre-commit install`. - [x] I have run the hooks manually with `pre-commit run --all-files` and fixed any reported issues. > If you are unsure about how to set up `pre-commit`, see [the pre-commit documentation](https://pre-commit.com/). ## 🧪 Tests - [x] Tests have been added or updated as needed. - [ ] All tests are passing (`unittest`, etc.). ## 🔬 Experimental Track <!-- Only for PRs submitted under the experimental policy (CONTRIBUTING.md → "Experimental APIs and Backends"). Leave this section untouched for normal PRs. --> - [ ] This PR is **experimental**: it adds or changes code under `flashinfer/experimental/` and/or an `@flashinfer_experimental_api`. Tracking issue: # - [ ] The tracking issue names an owner, the reason for the experimental path, and a graduation plan with a target release. - [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff). - [ ] Tests live in `tests/experimental/` and were validated on the intended hardware; a runnable example is included. - [ ] Nothing is registered in `flashinfer/aot.py`, and no experimental backend is reachable from `backend="auto"` without `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. (Calling an `@flashinfer_experimental_api` or naming a backend explicitly is itself the opt-in and needs no environment variable.) - [ ] **Test scope declared below.** The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows. <!-- Required for experimental PRs. Replace the commented lines below with your targets. Do not delete the fence or change its `experimental-tests` tag — the experimental-track watcher reads it verbatim to decide which targets to ask CI for. --> ```experimental-tests # One target per line: a directory or a file. (A pytest ::selector is not # supported -- the sharding runner cannot consume one.) Must be under # tests/experimental/ and must exist. Delete these comment lines and add yours, e.g. # # tests/experimental/test_my_backend.py # tests/experimental/my_backend/ # # Declaring the whole tree (tests/experimental/) is allowed but means every # experimental PR pays for every other feature's tests, in every matrix cell. ``` ## Reviewer Notes <!-- Optional: anything you'd like reviewers to focus on, concerns, etc. --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Compatibility** * Localized MoE execution requires a PyTorch build with the stream-execution API and reports an error when unavailable. Standard MoE execution remains available without it. * **Bug Fixes** * Improved handling of partial-width outputs in grouped GEMM finalization, preventing invalid reductions and ensuring output data is ready before reuse. * Localized execution now joins participating streams before propagating GEMM failures. * **Testing** * Expanded coverage for localized execution failures, partial-width outputs, and CUDA graph capture and replay. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Qidong Su <[email protected]> Co-authored-by: Haobin Guo <[email protected]>
Stack from ghstack (oldest at bottom):
Same-device execution switches directly between streams and restores the caller once to reduce host-side overheads. Cross-device execution uses stream context managers to restore device and stream state.
Test Plan
Tested on Rubin with driver R610 + CUDA 13.4 compat (56 tests passed)