Skip to content

[CUDA] Add localized CUDA allocator - #199127

Closed
MatthiasKohl wants to merge 8 commits into
gh/MatthiasKohl/1/basefrom
gh/MatthiasKohl/1/head
Closed

MatthiasKohl wants to merge 8 commits into
gh/MatthiasKohl/1/basefrom
gh/MatthiasKohl/1/head

Conversation

@MatthiasKohl

@MatthiasKohl MatthiasKohl commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Initial locality domain support was added in #198279. This stack adds:

  1. convenience functions to allocate localized memory
  2. convenience function to execute operations in several green contexts through the fork/join pattern
  3. minor fixes to green contexts discovered during testing of localized workloads
  4. small fixes to docs

Authored with an AI assistant.

Add LocalizedAllocator for use with the existing MemPool API.
Retain Python callback owners so tensors can outlive the pool, and wait
for allocation-stream work before unmapping reclaimed memory. Validate
domain types and document the current threading restriction.

Test Plan

Tested on Rubin with driver R610 + CUDA 13.4 compat (43 tests: 40 passed, 3 skipped)

). This stack adds:

1. convenience functions to allocate localized memory
2. convenience function to execute operations in several green contexts through the fork/join pattern
3. minor fixes to green contexts discovered during testing of localized workloads

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199127

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit f6749c7 with merge base d0b8bbb (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@MatthiasKohl MatthiasKohl added the ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR label Sep 30, 2026
@MatthiasKohl
MatthiasKohl marked this pull request as ready for review September 30, 2026 10:34
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

CC @ngimel @eqy @slayton58 for review (includes the full stack)

MatthiasKohl added a commit to MatthiasKohl/pytorch that referenced this pull request Sep 30, 2026
Add a convenience custom MemPool to allow allocating memory in a given locality domain.

> Authored with an AI assistant.
>
> Construction initializes CUDA before checking support so validation uses the actual device topology.

Test Plan

Tested on Rubin with driver R610 + CUDA 13.4 compat.
43 tests run: 40 passed, 3 skipped.

```sh
python test/test_cuda.py TestMemPool TestLocalizedMemPoolCUDA TestLocalizedMemPoolAllocator -v
```

ghstack-source-id: d9d0693
Pull-Request: pytorch#199127
@eqy eqy added the release notes: cuda release notes category label Sep 30, 2026
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@claude are the failures from periodic tests related to this PR? Plus, did the 13.4 periodic jobs run successfully and successfully complete the green context / LocalizedMemPool tests?

@claude

claude Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Claude finished @MatthiasKohl's task in 2m 40s —— View job


None of the periodic failures come from this PR. All 39 CUDA 13.4 jobs passed, but they ran on L4 GPUs with driver R580, so the LocalizedMemPool tests that need real hardware were almost certainly skipped and nothing in CI actually exercised a localized allocation.

Details

1. Are the periodic failures related?

No. They fall into three groups:

Failure Jobs Cause Related?
nogpu_AVX512 / nogpu_NO_AVX2: test_cuda, test_cuda_expandable_segments 8 jobs (CUDA 13.0 and 13.2) test_cuda.py crashes at import (traceback below) No. The same code is at line 12317 of the merge base 198a309, before this PR.
KeyboardInterrupt / FATAL: received SIGINT debug, slow-gradcheck, default and distributed shards Shards hit their timeout in slow inductor/gradcheck tests No. The same shards time out on trunk.
s390x: histc double free; acosh missing from ZVECTOR Vectorized<float> 2 jobs CPU-only s390x bugs No

The nogpu traceback:

File "test/test_cuda.py", line 12317, in <module>
    not PLATFORM_SUPPORTS_GREEN_CONTEXT, "Green contexts are not supported"
  ...torch/cuda/green_contexts.py", line 51, in _get_driver_version
    _check_cuda(_get_cuda_library().cuDriverGetVersion(byref(version)))
  ...torch/cuda/_utils.py", line 72, in _get_cuda_library
    return ctypes.CDLL("libcuda.so.1")
OSError: libcuda.so.1: cannot open shared object file: No such file or directory

This is a real bug, not a flake. PLATFORM_SUPPORTS_GREEN_CONTEXT is evaluated when the module is imported. On a machine without libcuda.so.1, _ensure_supported() raises OSError instead of returning False, so the whole test_cuda.py file fails to collect on every no-GPU job. It is already on trunk (the TestCudaGreenContexts class decorator, apparently added in #198279), so Dr.CI labels it "flaky". It would be worth fixing in this stack: catch OSError in evaluate_platform_supports_green_context() in torch/testing/_internal/common_cuda.py.

2. Did the 13.4 periodic jobs run the green context / LocalizedMemPool tests?

All linux-jammy-cuda13.4-py3.11-gcc11 jobs passed: 14 default shards, 10 distributed shards and jit_legacy. The no-ops, clang20 and libtorch-debug builds also passed. The new tests were collected and the shards that ran them succeeded:

  • Shard 4/14 (job), test_cuda 1/2:
    • TestLocalizedMemPoolAllocator::{test_initialization_before_support_check, test_allocation_cleanup_*, test_wrong_device_and_empty_allocation}
    • TestLocalizedMemPoolCUDA::test_invalid_locality_domain_cuda
    • TestCudaGreenContextsCUDA::test_greencontext_locality_{query,backfill,invalid_visibility...} and the split/sm_count tests
  • Shard 5/14 (job), test_cuda 2/2, serial:
    • TestLocalizedMemPoolCUDA::test_localized_allocation_no_split_{False,True}_cuda
    • TestCudaGreenContextsCUDA::{graphs, recursive_sm_partitions, split_workqueue_scope_*, stream_carveout}

The catch is the hardware. These runners are L4 GPUs (mt-l-x86aavx2-11-41-l4) with nvidia-smi reporting Driver 580.178.04 / CUDA Version 13.0. That is single-domain hardware with a driver older than 13.4.

  • Ran for real: the mock-based TestLocalizedMemPoolAllocator tests, which don't need real hardware.
  • Almost certainly skipped: TestLocalizedMemPoolCUDA (_require_localization checks is_localization_supported, i.e. "requires CUDA 13.4 and a multi-domain GPU") and the test_greencontext_locality_* tests.
  • Probably ran: the basic green-context split/carveout tests, since they only need green-context support.

I couldn't read the per-test pass/skip results: the console log only lists collected items, and downloading the XML test-report artifacts needs gh api permission I don't have here. You can confirm on HUD via the test results for this PR.

Bottom line: the 13.4 CI jobs show that the new code imports, the tests skip cleanly and the mocked allocator logic passes on 13.4. They do not test localized allocation on real multi-domain hardware. For now your Rubin + R610 run is the only real test of that.

@ngimel

ngimel commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

AI-assisted

Expose localized allocation through the allocator interface. LocalizedMemPool changes the backing allocator but adds no new pooling behavior. Please expose a localized allocator usable with the existing torch.cuda.MemPool(allocator=...) instead of adding another public MemPool subclass. Device and locality configuration and metadata belong on the allocator. Future allocation policies should compose with the same pool API; they should not each require a new pool class. This does not require implementing two-half storage placement in this PR.

_BaseLocalityAllocator: document the current threading restriction. The caching allocator can invoke the ctypes Python callback while holding its mutex. Entering the callback requires the GIL; another thread can hold the GIL in pool.use_count() while waiting for that same mutex. This is a lock inversion, explicitly warned against in ExpandableSegment::unmapHandles. For the current implementation, document that concurrent allocator activity is unsupported, including allocation, freeing, and allocator-state queries from other threads. General Python-callback integration and lock-order fixes belong in a separate infrastructure follow-up.

The native allocator also receives only integer callback addresses. Its lifetime can exceed that of the Python pool and its callback objects: dropping the pool with a live tensor and running gc.collect() can leave a dangling free callback for a later empty_cache(). Ordinary MemPool supports tensors outliving the Python pool, as tested by test_tensor_delete_after_allocator_delete; _use_uvm already documents this exact ctypes-closure lifetime hazard and keeps allocator alive to avoid this, please follow the same pattern.

_free_callback / _DomainLocalityAllocator.free: preserve stream ordering before unmapping. The callback discards the allocation stream and immediately calls cuMemUnmap. A logically free cached block can still have work queued on its allocation stream. With finite max_split_size, allocation-retry reclamation can release such a block while the pool is still alive. ExpandableSegment::unmapHandles explicitly waits before unmapping because cuMemUnmap/cuMemRelease do not provide cudaFree's synchronization. Please preserve the necessary stream information and synchronize reclamation, with a delayed-kernel regression test.

_DomainLocalityAllocator.__init__: match the splitting API's domain validation. Explicitly require an integer and reject bool before the range check. False and True currently become domains 0 and 1, and noninteger values also pass the range comparison.

test_localized_allocation: verify actual placement. Contents and pointer reuse would also pass with ordinary nonlocalized memory. Please inspect the backing allocation with cuMemRetainAllocationHandle and cuMemGetAllocationPropertiesFromHandle, check its device and locality domain, and release the retained handle. Add the lifetime and asynchronous-reclamation cases above rather than relying on mocked CUDA calls for allocator correctness.

@MatthiasKohl MatthiasKohl changed the title [CUDA] Add localized memory pools [CUDA] Add localized CUDA allocator Oct 2, 2026
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@ngimel Thank you for the review, I tried to address everything in the latest update.

Please let me know if further changes are required !

@eqy

eqy commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@claude analyze the remaining failures, are they likely due to periodic jobs we don't see on most PRs, are they related to this PR?

@claude

claude Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Claude finished @eqy's task in 2m 28s —— View job


None of the 7 remaining failures come from this PR. All of them are in periodic or s390x-periodic, which only run here because of the ciflow/periodic label, so most PRs never see these jobs. Everything that exercises the new code passed, and so did every CUDA 13.4 job.

Details

Failing jobs

Job What failed Related?
cuda13.2 nogpu_AVX512 1/3 Exit code 132 (SIGILL) in aten/tools/run_tests.sh: Illegal instruction (core dumped) valgrind ... build/bin/basic --gtest_filter='-*CUDA'. Valgrind crashes on an AVX-512 instruction in the CPU mse_loss kernel of the C++ basic test. All Python tests in the shard passed, including test_cuda_expandable_segments. No. The C++ ATen test doesn't touch torch/cuda/memory.py.
cuda13.2 nogpu_NO_AVX2 2/2 inductor/test_cpu_repro.py::CPUReproTests::test_interpolate_mutated_input_backward_activation_memory_budget_0: "Tensor-likes are not close!" on 3 of 3 attempts No. It is a CPU inductor numerics failure, and DrCI found the same failure on trunk (e1756ff).
cuda13.2 default 2/5 Some tests hit the 60-minute per-test timeout (KeyboardInterrupt), e.g. during inductor/test_torchinductor_dynamic_shapes. The job then ran out of time and got SIGINT around 14:55. test_cuda 1/2 passed in this shard, twice. No. The same timeout pattern is on trunk (251c826).
cuda13.2-debug 6/7 The job timed out (SIGINT) while running parallel inductor tests (the last file to finish was inductor/test_control_flow 2/5) No. Same as trunk (251c826).
cuda13.2 slow-gradcheck 6/8 test_ops_gradients ran for about 4.4 hours (10:11 to 14:33) until the job was killed with SIGINT No. Slow gradcheck never uses the allocator, and DrCI's AI check found the same timeout on trunk shards 2 and 5.
s390x 3/10 histc float16 "double free or corruption" on CPU No. The same crash shows up on several unrelated PRs.
s390x 9/10 test_compile_subprocess::CpuTests::test_hyperbolic_op_acosh_cpu No. The same failure is on trunk (e1756ff).

The slow-gradcheck job is the one DrCI lists as "unclassified" only because that workflow didn't run on the merge base. The log shows the usual timeout, not a crash.

Compared with the last run

  • Fixed: last time, test_cuda.py failed at import on nogpu runners with OSError: libcuda.so.1 from PLATFORM_SUPPORTS_GREEN_CONTEXT. On this run, test_cuda 1/1 was successful on nogpu_NO_AVX2 (twice), and test_cuda_expandable_segments passed on nogpu_AVX512.
  • Passed: all linux-jammy-cuda13.4-py3.11-gcc11 jobs (14 default shards, 10 distributed shards, jit_legacy), plus the 13.4 clang20, no-ops and libtorch-debug builds.
  • Still not covered: the CI runners are still single-domain L4/T4 GPUs. The hardware-dependent LocalizedAllocator placement tests most likely skipped. The Rubin + R610 run remains the only real test of localized allocation.

Verdict

These are all periodic-only failures that trunk has too: job timeouts, a valgrind/AVX-512 SIGILL, a CPU inductor numerics failure, and s390x CPU bugs. None of them should block this PR.

@ngimel

ngimel commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@claude were the comments addressed?

@claude

claude Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 55s —— View job


Yes. All six points from your review were addressed in the current head (ee1c408), and I found nothing blocking. The caveat is that the new hardware-dependent tests skip on CI's single-domain GPUs, so only the author's Rubin run has exercised them.

Details

Status of each point

Review point Status Where
Expose through the allocator interface, not a MemPool subclass ✅ Done LocalizedAllocator(_CUDAAllocator) in torch/cuda/memory.py. You use it as MemPool(allocator=LocalizedAllocator(...).allocator()), and LocalizedMemPool is gone. Device and domain metadata are now properties on the allocator (device_id, locality_domain_id).
Document the threading restriction ✅ Done The _BaseLocalityAllocator docstring explains the lock inversion. A .. warning:: in the LocalizedAllocator docstring and a {warning} block in docs/source/cuda.md both say concurrent allocation, freeing, and allocator-state queries (including MemPool.use_count()) are unsupported.
Callback-owner lifetime (follow the _use_uvm pattern) ✅ Done A module-level _LOCALITY_ALLOCATORS[(device_id, domain)] keeps one owner per device and domain alive for the whole process, similar to _UVM_ALLOCATOR. The new test_tensor_outlives_pool_and_allocator test drops the pool and allocator, runs gc.collect(), checks that the owner is still alive and the tensor contents are intact, and then checks that empty_cache() frees the record.
Keep stream ordering before unmapping, with a delayed-kernel regression test ✅ Done _free_callback now passes stream through. _DomainLocalityAllocator.free calls cuStreamSynchronize(stream or 0) before cuMemUnmap/cuMemAddressFree/cuMemRelease. The new test_reclamation_waits_for_allocation_stream test sets max_split_size_mb:32 and puts _sleep(1e9) plus queued work on the stream. It then forces one allocation failure, which makes the retry path reclaim the 40 MB block, and asserts the event was not done before free and was done after it. It also checks that the reclaimed stream is the allocation stream. The mocked test_allocation_cleanup additionally checks that the sync is ordered before the unmap.
Domain validation (reject bool and non-integers) ✅ Done Both LocalizedAllocator.__init__ and _DomainLocalityAllocator.__init__ do isinstance(x, bool) or not isinstance(x, int) and then the range check. Like the splitting API, they raise ValueError. test_noninteger_domain covers False, True, 0.0, 1.5, "0" and None, and checks that CUDA isn't initialized first.
Check the actual placement in test_localized_allocation ✅ Done The test calls cuMemRetainAllocationHandle(ptr) and then cuMemGetAllocationPropertiesFromHandle. It asserts CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN, deviceId and localityDomainId for every domain, and releases the retained handle in a finally. Lifetime and reclamation now have real-hardware tests, and the mocks are only used for error-path cleanup.

Minor non-blocking notes

  • No lock on _LOCALITY_ALLOCATORS: filling the dict has no lock, unlike _UVM_ALLOCATOR_LOCK. Concurrent use is documented as unsupported, so this is consistent with the rest of the code, but a lock would cost little.
  • Duplicated check: the bool/int check appears twice, in LocalizedAllocator and in _DomainLocalityAllocator. That's harmless, since the public class needs it before building the cache key.
  • Sync under the allocator mutex: free calls cuStreamSynchronize while the native allocator mutex is held. This matches what ExpandableSegment::unmapHandles does, but it does block other allocator activity during reclamation.
  • CI coverage: as noted in the earlier CI analysis, the CI runners are single-domain L4/T4 GPUs. TestLocalizedAllocator (placement, lifetime and reclamation) skips there. Only the mock-based TestLocalizedAllocatorCallbacks runs in CI.

@claude

claude Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 1m 7s —— View job


Two of your three asks are done in a7a8ebe: the subclassing is gone and the free path is hardened. The third, real GB200/B200 + 13.4 cuda-compat CI, is not in this PR; @MatthiasKohl has moved it to a separate PR. That means CI still never runs the placement, lifetime, reclamation or shutdown tests. Whether that blocks landing is your call.

Details

1. Remove the extra subclassing: ✅ done

_BaseLocalityAllocator and _DomainLocalityAllocator are merged into a single private _LocalizedAllocatorOwner (torch/cuda/memory.py). The owner's constructor runs the support check and the range check. LocalizedAllocator keeps only the bool/int type check, which it needs to build the cache key, plus the _LOCALITY_ALLOCATORS lookup. _lazy_init() is now called only once, and the tests target the new class.

2. Harden the free path: ✅ done (minor gaps below)

Earlier ask Status
Pop the record before doing anything else ✅ self._records.pop(ptr, None) comes first, so the Python state now matches the native state
If the stream sync fails, skip the unmap and leak on purpose ✅ free returns when cuStreamSynchronize fails
Run unmap / address-free / release independently and collect the errors ✅ Each runs through _try_cleanup, and cuMemAddressFree is skipped only when the unmap failed
Stop relying on module globals; replace torch.cuda.device ✅ The driver, the check helper and the prop builders are bound on the instance. The primary context is retained once and used with cuCtxPushCurrent/cuCtxPopCurrent. During finalization free returns early
Keep the owners alive on purpose so the thunks outlive every ~MemPool ✅ Py_IncRef(owner) when the owner is created
Catch BaseException in both callbacks ✅ Both callbacks catch it, and _report_errors itself can't raise
Clean up allocate without hiding the original error ✅ Cleanup errors are collected and the original error is re-raised
Subprocess test: uncaught exception with a pool and tensor kept alive in a reference cycle ✅ test_shutdown_with_localized_pool_cycle. It also clears _LOCALITY_ALLOCATORS, so the test really depends on the Py_IncRef keeping the owner alive

Remaining points, none of them blocking:

  • Ctrl-C is still swallowed. A KeyboardInterrupt raised inside either callback is caught and dropped silently: _report_errors only logs Exception, and nothing re-raises it through _thread.interrupt_main(). The interrupt is lost, and in allocate it turns into an OOM. Either re-raise it or document this.
  • Spurious error logs on the OOM retry path. For a custom-allocator pool, a nullptr from raw_alloc makes the caching allocator release cached blocks and retry. Every first-attempt CUDA_ERROR_OUT_OF_MEMORY therefore logs at logging.error with a traceback, even when the retry succeeds (test_reclamation_waits_for_allocation_stream does exactly this). Consider skipping the log for OOM, or logging at debug level.
  • Global side effect from Py_IncRef. LocalizedAllocator.__init__ sets argtypes/restype on the process-wide ctypes.pythonapi.Py_IncRef object. Calling ctypes.pythonapi.Py_IncRef(ctypes.py_object(owner)) avoids changing shared state.
  • Misleading comment. The comment above _LOCALITY_ALLOCATORS says "a native reference also pins it". What actually keeps the owner alive is the Py_IncRef leak.

3. GB200/GB300 + 13.4 cuda-compat CI: ❌ not in this PR

@MatthiasKohl says the 13.4 B200/B300 runners are coming and will be wired up in a separate PR. Until then, CI runs only the mocked TestLocalizedAllocatorCallbacks. All of TestLocalizedAllocator, including the new shutdown test, skips on the L4/T4 runners. If the CI comes later, ask for the job to assert torch.cuda.green_contexts.is_localization_supported() so that a missing compat driver fails the job instead of passing with everything skipped.

I only read the code. Nothing was run, since there is no multi-domain GPU here.

@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

note: PR #199593 should add the B200 based tests.
We can wait until that's merged, then add the ciflow/b200 label here to get the tests for this PR.

@ngimel ngimel 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.

Small change to the example, and we'd need to harden device handling later, otherwise good to go.

Comment thread docs/source/cuda.md Resolved
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 7, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: periodic / linux-jammy-cuda13.2-py3.11-gcc11 / test (default, 1, 5, mt-l-x86aavx2-11-41-l4)

Details for Dev Infra team Raised by workflow job

@MatthiasKohl MatthiasKohl removed the ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR label Oct 7, 2026
> AI-assisted: map-style stream execution, localized-output docs, trim redundant tests.

[ghstack-poisoned]
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Oct 8, 2026
> 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: #199128
Approved by: https://github.com/ngimel
ghstack dependencies: #199127
pytorchmergebot pushed a commit that referenced this pull request Oct 8, 2026
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
pytorchmergebot pushed a commit that referenced this pull request Oct 8, 2026
….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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
Initial locality domain support was added in pytorch#198279. This stack adds:

1. convenience functions to allocate localized memory
2. convenience function to execute operations in several green contexts through the fork/join pattern
3. minor fixes to green contexts discovered during testing of localized workloads
4. small fixes to docs

> Authored with an AI assistant.
>
> Add `LocalizedAllocator` for use with the existing `MemPool` API.
> Retain Python callback owners so tensors can outlive the pool, and wait
> for allocation-stream work before unmapping reclaimed memory. Validate
> domain types and document the current threading restriction.

Test Plan

Tested on Rubin with driver R610 + CUDA 13.4 compat (43 tests: 40 passed, 3 skipped)
Pull Request resolved: pytorch#199127
Approved by: https://github.com/ngimel
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
> 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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
….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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants