Skip to content

[CUDA] Add locality-domain green context support - #190656

Closed
MatthiasKohl wants to merge 2 commits into
pytorch:mainfrom
MatthiasKohl:mjoux/locality-domain-green-context
Closed

MatthiasKohl wants to merge 2 commits into
pytorch:mainfrom
MatthiasKohl:mjoux/locality-domain-green-context

Conversation

@MatthiasKohl

Copy link
Copy Markdown
Collaborator

CUDA 13.4 adds support for locality domains for NVIDIA Blackwell+ Architectures (compute capabilities 10.X).

This PR adds support for locality domains in torch.cuda.GreenContext, using cuda-python.

It also adds a few other features:

  • support for non-owning GreenContext instances: this allows converting a (potentially external) green context stream into a GreenContext instance, allowing to query resources and attributes from the green context associated with a stream
  • additional tests for stream handling
  • cuda binding version checking in green_contexts.py

Note: subsequent PRs will allow easy allocation of localized memory. These PRs are only dependent on this one due to the additional utilities (cuda bindings version checking, get_num_locality_domains and similar utilities).

Test Plan (run on both Blackwell and Rubin systems using CUDA 13.4)

python test/test_cuda.py TestCudaGreenContextsCUDA

Authored with an AI assistant.

CC @ptrblck @eqy @msaroufim @ngimel @jerryzh168 @ezyang @Aidyn-A

@pytorch-bot

pytorch-bot Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 11 Unrelated Failures, 11 Unclassified Failures

As of commit de02341 with merge base 9b6e452 (image):

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@eqy
eqy requested review from eee4017, galv and ngimel July 21, 2026 14:52
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 21, 2026
@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from 6ecbe75 to 0175ab3 Compare July 27, 2026 14:03
@ngimel

ngimel commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

I take it from @ptrblck there are no public cuda-python 13.4 wheels yet?

@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from 0175ab3 to 6bbb65c Compare August 6, 2026 09:44
pytorchmergebot pushed a commit that referenced this pull request Aug 12, 2026
Small PR building on top of #190639 / #192256 to use the cuda-bindings 13.4 beta for the CUDA 13.4 image specifically.

This unblocks testing of PRs requiring CUDA 13.4 + cuda-bindings (e.g. #190656)

CC: @tinglvv @nWEIdia @atalman @malfet @eqy @ptrblck
Pull Request resolved: #192769
Approved by: https://github.com/tinglvv, https://github.com/atalman
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@ngimel tests should now be possible in the 13.4 CI image. I'll rebase and fix linting, then we can hopefully run all tests here

@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from 6bbb65c to 5fe69c0 Compare August 12, 2026 11:00
@ngimel

ngimel commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Still no 13.4 cuda-python on pypi, so how does docker get it?

@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

There should be a preview release on pypi which we added to CI here #192769

gavinwang269 pushed a commit to gavinwang269/pytorch that referenced this pull request Aug 13, 2026
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@claude the failure in CI seems to be networking related. How can I restart just this one job?

@eqy

eqy commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

@claude I assume CI failures are unrelated, so this should be safe to land?

@claude

claude Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Claude finished @eqy's task in 3m 18s —— View job


CI check: failures are unrelated — safe to land, with two caveats

  • Pull current CI check status for the PR head
  • Inspect the failing job log
  • Assess whether the failure is related to this PR
  • Report verdict

Short answer: yes, the one failure is infra/network, not this PR. But CI green here does not validate the new locality-domain code paths, and the PR still needs a release-notes label.

Details

The failure

At head d80d25e, 3 of 4 workflow runs pass (Lint, BC Lint, docs-build). The pull run has exactly one failing job:

linux-jammy-rocm-py3.10 / build (job 94190779537) — failed in the Build step while CMake fetched a prebuilt aotriton tarball:

CMake Error at .../download-aotriton_image_110x.cmake:163 (message):
  Each download failed!
    error: downloading 'https://github.com/ROCm/aotriton/releases/download/0.13b/aotriton-0.13b-images-amd-gfx110x.tar.gz' failed
          status_code: 56
          status_string: "Failure when receiving data from the peer"
...
ninja: build stopped: subcommand failed.

curl status 56 is a transport-level read failure against github.com:443 — DNS resolved fine, TLS started, the peer dropped the transfer. Same job also logged Credentials could not be loaded ... Could not load credentials from any providers for the sccache/metrics step earlier.

This PR touches docs/source/cuda.md, test/test_cuda.py, torch/cuda/__init__.py, torch/cuda/_utils.py, torch/cuda/green_contexts.py — all Python, none in the ROCm or aotriton build path, and the ROCm build doesn't compile any of it. There is no mechanism by which this diff causes a GitHub release download to be truncated. This agrees with DrCI's own read; it only flagged it "unclassified" because the merge base never ran that job.

Caveat 1: green CI is not evidence the new code works

TestCudaGreenContexts is gated on PLATFORM_SUPPORTS_GREEN_CONTEXT (test/test_cuda.py:11514), and the locality-domain tests additionally self-skip via self.skipTest("Green context localization is not supported") (e.g. test/test_cuda.py:11858-11862, 11920-11922, 11942-11944). On any runner without Blackwell+ and CUDA 13.4 bindings, the entire new surface is skipped rather than exercised.

So the load-bearing validation is your own Blackwell/Rubin runs, not this CI signal. Worth confirming in the PR description which of the 310 new test lines actually executed there (the mocked ones — test_greencontext_nonowning_wrapper_destroys_created_streams, test_greencontext_concurrent_stream_creation_uses_distinct_slots — do run anywhere green contexts exist, since they patch _drv; the real locality-domain ones do not).

Caveat 2: label blocker

pytorch-bot flagged that this PR needs a release notes: label (or topic: not user facing). This is user-facing API (GreenContext locality-domain args, non-owning wrapper, new torch.cuda entries in docs/source/cuda.md), so release notes: cuda looks right rather than topic: not user facing. If it hasn't been added since that bot comment, add it before merging.

On landing mechanics

Since the red job is a genuine infra flake, @pytorchbot merge -i (ignore current checks) is the documented path. Re-running just that single job needs repo write access — I can't trigger workflow re-runs, and neither the "Re-run failed jobs" button nor gh run rerun --failed is available to me. @MatthiasKohl asked the same thing above; that button on the workflow run page is the answer for anyone with write access.

One non-blocking note

The three new mocked tests reach fairly deep into module privates (_STREAM_TO_GREEN_CTX, _STREAM_TO_GREEN_CTX_LOCK, _drv, _check_cuda_bindings_, _init_from_cuda_objects, _curr_stream_idx, _green_ctx_streams) and construct instances with object.__new__. That buys real coverage of the refcounting/destruction logic on non-Blackwell hardware, which is valuable — but it will need updating in lockstep with any refactor of green_contexts.py. Not a landing blocker, just something to know before the follow-up localized-memory PRs land on top.

| Branch: [`mjoux/locality-domain-green-context`](https://github.com/pytorch/pytorch/tree/mjoux/locality-domain-green-context)

@eqy eqy added the release notes: cuda release notes category label Aug 13, 2026
@eqy

eqy commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

@pytorchmergebot merge -i

@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@eqy

eqy commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

@pytorchmergebot rebase

Comment thread test/test_cuda.py Resolved
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased mjoux/locality-domain-green-context onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout mjoux/locality-domain-green-context && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the mjoux/locality-domain-green-context branch from d80d25e to c631b67 Compare August 13, 2026 17:48
@Aidyn-A Aidyn-A added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 14, 2026
@ngimel

ngimel commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

There are 0 13.4 CI jobs

@ngimel

ngimel commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot review this PR, pay special attention to correctness and concurrency issues

@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: argument command: invalid choice: 'review' (choose from 'merge', 'revert', 'rebase', 'label', 'drci', 'lint', 'fix-lint', 'apply-lint', 'cherry-pick')

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

Comment thread torch/cuda/green_contexts.py Outdated

def execute_in_green_contexts(
green_ctx_streams: list[torch.cuda.Stream],
fn: Callable[[int, GreenContext | None], None],

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.

why does the function need GreenContext argument? None of the tests show the need for it

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

that's a good point, it was necessary previously when using the green context as a context manager to activate execution in it. Since we now just use the stream, it's only a convenience thing, but the user can simply extract the green context from the stream through get_green_context_from_stream as it's done in the implementation right now.

I'll update this to remove the GreenContext argument and I'll just add a short comment mentioning that you can get the context through get_green_context_from_stream if necessary

@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from 9014212 to 1d3e64c Compare September 17, 2026 06:26
@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@Aidyn-A Aidyn-A added the ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR label Sep 17, 2026
@MatthiasKohl

MatthiasKohl commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

@ngimel we now have 13.4 CI jobs here through the periodic workflow.

This job shows the new green context tests passing on 13.4: https://github.com/pytorch/pytorch/actions/runs/35190939624/job/105110156370?pr=190656

Right now, there are 10 running/pending CPU-only checks, but they are unrelated to this PR.

The 9 failures are classified as follows:

  • 4 failures for CPU-only jobs using Triton in test_user_defined_triton_kernel_non_builtin_constexpr where a triton kernel is run although no triton backend is active (but triton dependencies installed in the image, selecting those tests).
  • 1 failure in test_layout_TT_dynamic_k : DISABLED test_layout_TT_dynamic_k (__main__.LayoutCoverageWildcardTest) #194900 is tracking this.
  • 4 failures in distributed/multigpu terminated with SIGINT after a 210-min cutoff.

All of the above are unrelated to this PR, so I believe this PR is OK to merge, as soon as CI has run through.

@eqy

eqy commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

@claude any outstanding TODOs before landing?

@claude

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Claude finished @eqy's task in 11m 44s —— View job


Nothing blocking from the review threads — both are addressed. Two small correctness nits and a label check remain.

  • Gather PR context (diff vs merge base 58c0235, review threads, CI status)
  • Check whether each reviewer comment was actually addressed
  • Check CI / merge blockers
  • Re-read the new code for anything left unfinished
  • Report punch list
Details

Outstanding review comments: both done

Thread Ask Status
eqy, test/test_cuda.py "Can we be more precise in e.g., only synchronizing against the necessary stream(s)?" Done in bef72bc. The new tests use stream.synchronize(); there is no torch.cuda.synchronize() anywhere in the +314 test lines.
ngimel, torch/cuda/green_contexts.py "why does the function need GreenContext argument?" Done in 1d3e64c. Signature is now fn: Callable[[int], None] (green_contexts.py:797), and the docstring points at get_green_context_from_stream as the escape hatch (green_contexts.py:803-805).

CI

11 workflow runs at head 1d3e64c: pull, trunk, Lint, BC Lint, TSan, docs-build all green. The 2 red runs are periodic and s390x-periodic, and @MatthiasKohl's triage above matches what DrCI reports — 4x test_user_defined_triton_kernel_non_builtin_constexpr on nogpu shards, test_layout_TT_dynamic_k (tracked in #194900, already disabled), and 4x 210-min SIGINT on distributed/multigpu. None touch this diff, which is Python-only under torch/cuda/.

The 13.4 job does now exercise the real code: periodic / linux-jammy-cuda13.4 test — that resolves the "green CI proves nothing" caveat from my earlier comment.

1. Stream() pool-index bump is unsynchronized (real, low-probability)

green_contexts.py:744-746:

self._curr_stream_idx += 1
curr_idx = self._curr_stream_idx
idx = curr_idx % _STREAMS_PER_GREEN_CONTEXT_POOL

+= on an attribute is LOAD_ATTR / BINARY_OP / STORE_ATTR — a thread switch between the last two gives two callers the same curr_idx. Both then take the curr_idx < 32 branch, both call cuGreenCtxStreamCreate, and the second self._green_ctx_streams[idx] = green_ctx_stream (line 757) overwrites the first. The overwritten handle is never in the list, so __del__ never destroys it: a leaked CUDA stream. Under a free-threaded build this stops being a narrow window.

Note test_greencontext_concurrent_stream_creation_uses_distinct_slots does not cover this: the threading.Barrier sits inside the faked cuGreenCtxStreamCreate, i.e. after both increments have already run, so the test only ever observes the interleaving that already works. Its self.assertEqual(ctx._curr_stream_idx, 1) assertion is in fact the thing that would flake if the race fired.

The registry setdefault at 758-759 already takes _STREAM_TO_GREEN_CTX_LOCK; the cheapest fix is a per-instance lock (or reusing that RLock) around lines 744-757 so index selection, stream creation, and slot assignment are one critical section. Since __del__'s if green_ctx_stream is None: continue guard (line 561) was clearly added in anticipation of holes in the list, closing the race properly seems more in the spirit of the change than tolerating it.

Fix this →

2. cuda.bindings version encoding can false-pass a gate

green_contexts.py:72-76 packs the bindings version as major*1000 + minor*10 + patch. A patch level >= 10 overflows into the minor field: bindings 13.3.10 encodes as 13040, which satisfies the 13040 localization gate (_ensure_localization_supported, line 106-110) even though 13.4 features are absent. The failure mode is an opaque driver/attribute error instead of the intended clear message. cuda-python hasn't shipped a .10 patch, so this is latent rather than live — but dropping the patch term entirely (CUDA's own CUDA_VERSION doesn't encode it, and no gate here uses a patch level) removes the footgun for free.

Fix this →

3. _raw_device_capability_nvml docstring vs behavior

torch/cuda/__init__.py:1087-1115 is documented as returning "None if NVML is unavailable", but two paths raise RuntimeError (lines 1101, 1110-1112) and the except only catches (AttributeError, IndexError, OSError). So a handle/capability query failure propagates.

The sole caller is _get_num_locality_domains (green_contexts.py:144), reached on the pre-CUDA-init fork-safe path. is_localization_supported catches RuntimeError so it degrades fine, but a direct torch.cuda.green_contexts.get_num_locality_domains() before CUDA init would surface a raw NVML error rather than the documented None. Either widen the except or reword the docstring — cosmetic, your call.

4. Label check (can't verify from here)

pytorch-bot flagged a missing release notes: label earlier in the thread and I have no gh access in this run to confirm it landed. This is user-facing (GreenContext locality-domain kwargs, the non-owning wrapper, 4 new entries in docs/source/cuda.md), so release notes: cuda is the right one rather than topic: not user facing.

Things I checked that are fine

  • execute_in_green_contexts restores main_stream via try/finally on the same-device fast path (830-832) and has a covering test (test_execute_in_green_contexts_restores_stream_on_error).
  • __del__ uses len(self._green_ctx_streams) rather than the module constant and pulls _check_cuda_bindings / _drv off the class (_check_cuda_bindings_, _drv_) — correct guarding against module-global teardown at interpreter shutdown.
  • _is_owning is initialized False before _ensure_supported() (line 359) and only set True after full setup, so a constructor that raises partway never destroys a context it doesn't own. The cuCtxFromGreenCtx failure path (527-530) correctly destroys the just-created green ctx.
  • The _STREAM_TO_GREEN_CTX WeakValueDictionary can't hand out a stale wrapper for an owned stream, since the owning ctx keeps its streams alive for exactly as long as the map entry lives.
  • docs/source/cuda.md uses .. currentmodule:: torch.cuda.green_contexts, so the 4 added names resolve correctly even though torch/cuda/__init__.py only re-exports GreenContext.
  • No TODO/FIXME markers in the added code.

Bottom line: no reviewer request is left unaddressed, and nothing here is a hard landing blocker. #1 is the one I'd actually want fixed before merge — it's a 5-line change and the follow-up localized-memory PRs will build on this stream-pool code. #2-#3 are fine as follow-ups; #4 just needs a glance.

| Branch: [`mjoux/locality-domain-green-context`](https://github.com/pytorch/pytorch/tree/mjoux/locality-domain-green-context)

@ngimel

ngimel commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

Let's revisit requests in #195378 - it asks for disjoint partitioning of SMs that's totally unrelated to locality domains, and, in fact, can and should be used on devices that don't support locality domains. That's how we should have structured the rollout:

  1. An explicit operation returning multiple partitions or green contexts. For example, schematically:

    a, b = GreenContext.split(num_sms=[24, 40], device_id=0)
    Its contract guarantees that the returned contexts use mutually disjoint SM subsets. Separate invocations have no such relationship.
    Its contract guarantees that the returned contexts use mutually disjoint SM subsets. Separate invocations have no such relationship.

  2. Partition options independent of locality. Counts, co-scheduling requirements, backfill, and remainder handling belong here. cuDevSmResourceSplit is the
    natural implementation for unequal sizes and per-partition constraints.

  3. Optional locality constraints on each requested partition. A “one context per locality domain” convenience factory can build on this mechanism. A locality
    domain identifies hardware topology; it need not correspond one-to-one with a user’s partition.

“Building on top” should mean supplying locality constraints during SM selection, rather than splitting arbitrarily and assigning domain labels afterward.

Comment thread torch/cuda/green_contexts.py Resolved
Comment thread torch/cuda/green_contexts.py Outdated
# any device with SM < 10.0 or SM == 12.X has 1 locality domain, so
# we can safely provide the result without initializing the CUDA context
# and poisoning the fork. In the future, this might need to be updated.
capability = torch.cuda._raw_device_capability_nvml(device_id)

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.

does this correctly work on heterogenous systems where device are renumbered via CUDA_VISIBLE_DEVICE? Even without renumbering, I think this implicitly relies on cuda runtime and pcie device order being the same, which is not guaranteed

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.

yeah e.g., GB300 stations explicitly have RTX as index 0, GB300 as index 1 in nvidia-smi while the runtime orders by "speed" putting GB300 first

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

thanks for raising it ! I now check against all visible devices, and extended the test to support a few other corner cases.
Ideally, we should remove this logic here entirely and just rely on the CUDA driver, but this logic was requested by the vLLM team, so I kept it in for now.

Comment thread test/test_cuda.py Resolved
@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from 1d3e64c to 6f93160 Compare September 21, 2026 13:16
@MatthiasKohl
MatthiasKohl requested a review from a team as a code owner September 21, 2026 13:16

@MatthiasKohl MatthiasKohl left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for your inputs @ngimel .

I now added everything to fix issue #195378 here, which makes this PR more complicated, but it correctly introduces the constructs to make arbitrary disjoint partitions for green contexts. As the issue came up after this PR, I wanted to keep the PR simple at first.

Comment thread torch/cuda/green_contexts.py Resolved
Comment thread torch/cuda/green_contexts.py Outdated
# any device with SM < 10.0 or SM == 12.X has 1 locality domain, so
# we can safely provide the result without initializing the CUDA context
# and poisoning the fork. In the future, this might need to be updated.
capability = torch.cuda._raw_device_capability_nvml(device_id)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

thanks for raising it ! I now check against all visible devices, and extended the test to support a few other corner cases.
Ideally, we should remove this logic here entirely and just rely on the CUDA driver, but this logic was requested by the vLLM team, so I kept it in for now.

Comment thread test/test_cuda.py Resolved

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

Let's first nail down the splitting public API and implementation (one PR) and then move on to adding locality domain on top. Current design mixes resource spliltting and creating green context from split resources.

Comment thread torch/cuda/green_contexts.py Outdated
num_sms: int | None = None,
workqueue_scope: str | None = None,
workqueue_concurrency_limit: int | None = None,
disjoint_split: tuple[GreenContextSplit, int] | None = None,

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.

Concurrent initialization can invalidate disjointness. The global cache (/tmp/190656.diff:1101) allows simultaneous misses to execute separate CUDA
splits. Each constructor independently selects a group, so sibling contexts can come from different splits and overlap. This was reproduced with a mock driver
returning different valid partitions. Materialize the split once and pass its resources to the constructors. The factory should own that operation;
configuration equality plus a cache should not establish the guarantee.

This is not a problem for existing invocation from split but it is a problem for publicly exposed GreenContext constructor.

In general, this way of construction mixes two separate concerns - creating a green context from resources, and splitting resources. We should separate them

  1. Validate the complete request.
  2. Perform one CUDA split.
  3. Construct each context from its returned resource.

e.g.

     resources, remainder = split_resources(input_resource, specifications)
     contexts = tuple(
         GreenContext._from_sm_resource(resource, ...)
         for resource in resources
     )

This also gives the factory a straightforward way to accept workqueue configuration.

There should be no disjoint_split constructor argument.

For recursively partitioning the remainder, expose a small object representing an actual SM resource, with its device and actual SM count. It could support:

subpartitions = partition.split(...)
ctx = GreenContext(sm_partition=subpartitions[0], ...)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I don't fully understand this concern. The driver's implementation of splits is fully deterministic and this is quite important for how green contexts work internally. If the driver would return different partitions for the same input arguments, that would be a driver bug.

If you still prefer using an upfront split, I can implement that, but it will simply complicate the code further as we need to have two more or less separate code paths, one for non-disjoint green contexts and one for disjoint ones.

I think we should also think about what the goal is here:
"recursively partitioning the remainder" simply doesn't make much sense in the general case as the remainder will have almost 0 guarantees w.r.t. the given constraints of the original split. For example, the remainder of a split by locality domain 0 is not simply "locality domain 1", it has no guarantee on locality domain. Similar things hold for the coscheduled SM count, or even the SM count without backfill. With backfill, there are even less constraints on the remainder, as more or less anything can land in there, and a further split without backfill might not even be possible. It's hard to see how one would want to recursively split that and get something useful out of it.

If you are sure that we want this functionality, I can implement it, but I'd like to verify upfront first.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

concerning separate PRs, I can create a new one of course, but it would be good to have the full code reviewed first as the addition of locality domains changes some of the arguments for the public API that make sense to me

@ngimel

ngimel commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

@MatthiasKohl here's what I had in mind https://github.com/pytorch/pytorch/compare/ngimel/green-context-sm-partitions?expand=1, please take a look at whether it supports the requirements fomr nvidia perspective, it is otherwise more flexible wrt setting workqueue limits and recursive splitting

Add reusable SMPartition resources and disjoint green-context SM allocation
through cuDevSmResourceSplit. Start review with SMPartition.split and its
broadcasting, discovery, co-scheduling, and backfill options, then follow
GreenContext construction and recursive subdivision through sm_partition.

Retain the shared stream execution and lookup helpers, non-owning context
wrappers, cached SM counts, and CUDA bindings version checks. Include their
documentation and test coverage; locality-domain functionality and its NVML
helpers are added separately on top of this commit.

Test Plan

Ran lint with autofixes through spin using the base_env environment:

```bash
PATH=/home/mjoux/base_env/bin:$PATH spin lint -a docs/source/cuda.md test/test_cuda.py torch/cuda/__init__.py torch/cuda/_utils.py torch/cuda/green_contexts.py torch/testing/_internal/common_utils.py
git diff --check
```

Tests were not run, as requested; live-system testing is left to the author.

Authored with an AI assistant.
CUDA 13.4 adds support for locality domains on NVIDIA Blackwell compute
capability 10.x devices. Add locality-domain support to CUDA green contexts
using cuda-python, building on the SM partitioning API in the preceding
commit.

Review the per-group locality constraints and context metadata first, then
the locality-count and support queries. Before driver initialization, these
queries use NVML where possible, warning and falling back to driver queries
when inference fails. Include locality-specific version checks, lazy test
skipping, behavioral tests, and documentation.

Test Plan

Ran lint with autofixes through spin using the base_env environment:

```bash
PATH=/home/mjoux/base_env/bin:$PATH spin lint -a docs/source/cuda.md test/test_cuda.py torch/cuda/__init__.py torch/cuda/_utils.py torch/cuda/green_contexts.py torch/testing/_internal/common_utils.py
git diff --check
git diff --exit-code b5a0445
```

Tests were not run, as requested; live-system testing is left to the author.

Authored with an AI assistant.
@MatthiasKohl
MatthiasKohl force-pushed the mjoux/locality-domain-green-context branch from cf51a33 to de02341 Compare September 22, 2026 10:32
@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

@ngimel Thank you very much for taking the time to create this suggestion. I did the following:

  • Updated this branch to use most of your suggestion, and merge some of the tests and implementation I had originally into it (details below)
  • Created a new PR: [CUDA] Add SM partitioning with cuDevSmResourceSplit #198178 . If you prefer first reviewing and merging just the split / sm resource functionality, feel free to review that PR. We can then rebase and merge this PR with just the locality-domain specific features later on. If it's OK to merge everything in one go, feel free to review this PR, I don't have a strong opinion either way.

There are a few differences I wanted to point out with the current state compared to your proposal:

  • minor API differences: this PR allows broadcasting any values, such as num_sms=0 for the split, and determines the number of groups from any sequence argument. This is just convenience, and I don't have a strong opinion on using something else.
  • this PR allows wrapping a non-owning green context: this is so we can use the remaining functionality and obtain SM resource information from an external stream. This is needed to implement efficient fork-join functionality to execute a function on multiple green-context backed streams
  • minor differences in version handling: your proposal didn't always check cuda bindings version, but that's important for e.g. availability of cuDevSmResourceSplit in cuda bindings
  • NVML-based locality domain check: this was requested by vLLM and seems important for them. I now merged with your proposal s.t. we attempt NVML-based locality domain check (which should work on most systems) but then fall back to initializing driver API and querying the driver if something goes wrong with NVML
  • sm_count is cached per green context instance, as it is invariant for a given context.
  • errors in locality-domain support / number query simply return False / 1 domain. For the count, this is inline with how CUDA works, and avoids propagating the exception to the user. For support, I think it's convenient to get a boolean instead of a potential exception.
  • tests were mainly merged together, keeping functional tests from both proposals. I also used the decorators more than self.skipTest in line with your previous review.

@ngimel

ngimel commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

I've left a few comments in #198178 but main thing, it still pulls in lots of things that it shouldn't. What do you think of me landing my stack first (adding broadcasting, caching and nvml-based checks), and then you can add execute_in_green_context on top

@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

SGTM. Please go ahead and further simplify #198178 , land that first, then I'll add the remainder on top.

@MatthiasKohl

Copy link
Copy Markdown
Collaborator Author

closing as superseded by PR stacks #198279 and #199127

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

Labels

ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR ciflow/trunk Trigger trunk jobs on your pull request open source release notes: cuda release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants