Skip to content

dynamo: round-trip torch.cuda.stream ctx mgr across graph breaks - #184487

Closed
tfogal wants to merge 11 commits into
pytorch:mainfrom
tfogal:tfogal/target-values
Closed

tfogal wants to merge 11 commits into
pytorch:mainfrom
tfogal:tfogal/target-values

Conversation

@tfogal

@tfogal tfogal commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Upstream #166472 ('[user-streams] Switch to fx annotations at trace time') changed StreamContextVariable.target_values from a positional list [stream_var] to a dict {"stream": idx} so that StreamContextVariable.enter() (inherited from FxTracebackAnnotateVariable.enter) could feed it to torch.fx.traceback.annotate. That broke three other consumers of target_values -- output_graph.py's stack_ctx_args / locals_ctx_args population, the base
ContextWrappingVariable.reconstruct, and
BlockStackEntry.resume_fn -> ReenterWith.try_finally -- all of which iterate it as a positional tuple. tuple({"stream": 3}) flattens to ("stream",): the int index is silently dropped and the rebuild call ends up as e.g. torch.cuda.stream("stream"), which fails with a confusing device-string parse error.

The breakage has been latent since #166472 because FxTracebackAnnotateVariable.reconstruct_type raises Unsupported("torch.fx.traceback.annotate escaped from compiled region") unconditionally, short-circuiting the rebuild before the dict-vs-positional mismatch can surface. The visible symptom is a silent ungraceful graph break that drops the post-break body when a graph break occurs inside with torch.cuda.stream(s):.

This fix structurally separates the two purposes of target_values:

  • self.annotation = {"stream": idx} is a new dedicated field that enter() passes to torch.fx.traceback.annotate.
  • target_values = () keeps the positional rebuild contract happy.

Then StreamContextVariable.reconstruct_type is overridden to push a 0-arg callable -- functools.partial(torch.cuda.stream, ) -- installed as a global on the compiled function via OutputGraph.install_global_by_id. The base
ContextWrappingVariable.reconstruct appends CALL 0 (target_values is empty), invoking the partial to produce a fresh StreamContext just in time for the resume prologue's BEFORE_WITH.

functools.partial (rather than a freshly-defined closure) is critical: dynamo retraces the resume prologue, and a closure defined inside torch/_dynamo would be classified as MOD_SKIPLIST'd and refuse-to-trace, breaking the prologue. functools.partial is a builtin that dynamo handles natively, and the wrapped target (torch.cuda.stream) is plainly traceable.

enter() is also inlined (rather than inherited from FxTracebackAnnotateVariable.enter) because the parent passes self.target_values to annotate, but target_values is now the positional rebuild-args tuple; the annotation dict lives on self.annotation. reconstruct_type is overridden alongside to bypass FxTracebackAnnotateVariable.reconstruct_type's unconditional Unsupported raise.

Regression test added at
test/dynamo/test_streams.py::test_target_values_dict_round_trips_through_graph_break: graph break inside with torch.cuda.stream(s):, asserts two graph fragments are captured (rather than the post-break body being silently dropped to eager). Whole test_streams.py suite: 68 pass, 7 platform-skipped, no regressions.

Authored with Claude.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented May 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit e1dfc67 with merge base 404390f (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels May 20, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented May 20, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

One or more co-authors of this pull request were not found. You must specify co-authors in commit message trailer via:

Co-authored-by: name <email>

Supported Co-authored-by: formats include:

  1. Anything <[email protected]> - it will locate your GitHub user by id part.
  2. Anything <[email protected]> - it will locate your GitHub user by login part.
  3. Anything <public-email> - it will locate your GitHub user by public-email part. Note that this email must be made public on Github.
  4. Anything <other-email> - it will locate your GitHub user by other-email part but only if that email was used before for any other CLA as a main commit author.
  5. login <any-valid-email> - it will locate your GitHub user by login part, note that login part must be at least 3 characters long.

Alternatively, if the co-author should not be included, remove the Co-authored-by: line from the commit message.

Please update your commit message(s) by doing git commit --amend and then git push [--force] and then request re-running CLA check via commenting on this pull request:

/easycla

@pytorch-bot

pytorch-bot Bot commented May 20, 2026 •

Copy link
Copy Markdown

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

Comment thread torch/_dynamo/variables/streams.py Resolved
Comment thread torch/_dynamo/variables/streams.py Resolved
Comment thread torch/_dynamo/variables/streams.py Resolved
@kshitij12345

Copy link
Copy Markdown
Collaborator

cc: @riccardofelluga for review

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

@tfogal Thanks! It mostly looks bullet proof to me, a couple of nits with the test and the inheritance but overall I like this!

Comment thread test/dynamo/test_streams.py Resolved

@williamwen42 williamwen42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approach looks good to me - address lint failures and comments.

Comment thread test/dynamo/test_streams.py Resolved
Comment thread torch/_dynamo/variables/streams.py Resolved
Comment thread torch/_dynamo/variables/streams.py Resolved
Comment thread torch/_dynamo/variables/streams.py Resolved
@tfogal
tfogal force-pushed the tfogal/target-values branch from 96ccdeb to 3993fad Compare June 2, 2026 23:48
@tfogal
tfogal marked this pull request as ready for review June 2, 2026 23:50
@tfogal

tfogal commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

I don't think I have any means to fix the CI issue:

ERROR: Cannot install torchcomms==0.2.0.dev20260331+cu129, torchcomms==0.2.0.dev20260401+cu129 and torchcomms==0.2.0.dev20260402+cu129 because these package versions have conflicting dependencies.

Notice:  A new release of pip is available: 26.0.1 -> 26.1.1
Notice:  To update, run: pip install --upgrade pip
ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
Traceback (most recent call last):
  File "/opt/conda/envs/py_3.10/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/opt/conda/envs/py_3.10/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/__w/pytorch/pytorch/.ci/lumen_cli/cli/run.py", line 40, in <module>
    main()
  File "/__w/pytorch/pytorch/.ci/lumen_cli/cli/run.py", line 34, in main
    args.func(args)
INFO: pip is looking at multiple versions of torchcomms to determine which version is compatible with other requirements. This could take a while.
  Downloading https://download.pytorch.org/whl/nightly/cu129/torchcomms-0.2.0.dev20260401%2Bcu129-cp310-cp310-manylinux_2_28_x86_64.whl.metadata (508 bytes)
  Downloading https://download.pytorch.org/whl/nightly/cu129/torchcomms-0.2.0.dev20260331%2Bcu129-cp310-cp310-manylinux_2_28_x86_64.whl.metadata (508 bytes)
Collecting torchao
  Downloading http://pypi-cache-cpu.pypi-cache.svc.cluster.local:8080/whl/cpu/torchao-0.17.0%2Bcpu-py3-none-any.whl.metadata (20 kB)
INFO: pip is still looking at multiple versions of torchcomms to determine which version is compatible with other requirements. This could take a while.

The conflict is caused by:
    torchcomms 0.2.0.dev20260402+cu129 depends on torch==2.12.0.dev20260401
    torchcomms 0.2.0.dev20260401+cu129 depends on torch==2.12.0.dev20260331
    torchcomms 0.2.0.dev20260331+cu129 depends on torch==2.12.0.dev20260330

Additionally, some packages in these conflicts have no matching distributions available for your environment:
    torch

To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip to attempt to solve the dependency conflict

Infra problem? Who can we ping to investigate?

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 3, 2026
@eqy

eqy commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

@pytorchmergebot rebase

1 similar comment
@tfogal

tfogal commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot rebase

@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 tfogal/target-values onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout tfogal/target-values && git pull --rebase)

@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

Tried to rebase and push PR #184487, but it was already up to date. Try rebasing against main by issuing:
@pytorchbot rebase -b main

@tfogal

tfogal commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Looks like the issue is RuntimeError: Could not resolve the process group registered under the name 19 in torchtitan.

@pytorchmergebot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

tfogal and others added 5 commits June 4, 2026 15:55
Upstream pytorch#166472 (mlazos, '[user-streams] Switch to fx annotations at
trace time') changed StreamContextVariable.target_values from a
positional list [stream_var] to a dict {"stream": idx} so
that StreamContextVariable.enter() (inherited from
FxTracebackAnnotateVariable.enter) could feed it to
torch.fx.traceback.annotate.  That broke three other consumers of
target_values -- output_graph.py's stack_ctx_args /
locals_ctx_args population, the base
ContextWrappingVariable.reconstruct, and
BlockStackEntry.resume_fn -> ReenterWith.try_finally -- all of
which iterate it as a positional tuple.  tuple({"stream": 3})
flattens to ("stream",): the int index is silently dropped and
the rebuild call ends up as e.g. torch.cuda.stream("stream"),
which fails with a confusing device-string parse error.

The breakage has been latent since pytorch#166472 because
FxTracebackAnnotateVariable.reconstruct_type raises
Unsupported("torch.fx.traceback.annotate escaped from compiled
region") unconditionally, short-circuiting the rebuild before the
dict-vs-positional mismatch can surface.  The visible symptom is a
silent ungraceful graph break that drops the post-break body when a
graph break occurs inside with torch.cuda.stream(s):.

This fix structurally separates the two purposes of target_values:

  * self.annotation = {"stream": idx} is a new dedicated field
    that enter() passes to torch.fx.traceback.annotate.
  * target_values = () keeps the positional rebuild contract
    happy.

Then StreamContextVariable.reconstruct_type is overridden to push
a 0-arg callable -- functools.partial(torch.cuda.stream, <Stream>)
-- installed as a global on the compiled function via
OutputGraph.install_global_by_id.  The base
ContextWrappingVariable.reconstruct appends CALL 0
(target_values is empty), invoking the partial to produce a fresh
StreamContext just in time for the resume prologue's BEFORE_WITH.

functools.partial (rather than a freshly-defined closure) is
critical: dynamo retraces the resume prologue, and a closure defined
inside torch/_dynamo would be classified as MOD_SKIPLIST'd and
refuse-to-trace, breaking the prologue.  functools.partial is a
builtin that dynamo handles natively, and the wrapped target
(torch.cuda.stream) is plainly traceable.

enter() is also inlined (rather than inherited from
FxTracebackAnnotateVariable.enter) because the parent passes
self.target_values to annotate, but target_values is now
the positional rebuild-args tuple; the annotation dict lives on
self.annotation.  reconstruct_type is overridden alongside to
bypass FxTracebackAnnotateVariable.reconstruct_type's
unconditional Unsupported raise.

Regression test added at
test/dynamo/test_streams.py::test_target_values_dict_round_trips_through_graph_break:
graph break inside with torch.cuda.stream(s):, asserts two graph
fragments are captured (rather than the post-break body being silently
dropped to eager).  Whole test_streams.py suite: 68 pass, 7
platform-skipped, no regressions.

Authored with Claude.

Signed-off-by: Tom Fogal <[email protected]>

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
instead of having a member variable that's only used in 1 place.
instead of FxTracebackAnnotateVariable. Makes the hierarchy
directly mirror the actual types, and importantly deriving from
FxTracebackAnnotateVariable wasn't important anymore as we do the
annotation ourselves manually.

From review comment.

Authored with Claude.
tfogal added a commit to tfogal/pytorch that referenced this pull request Jun 15, 2026
Kshiteej asked for a follow-up to pytorch#184487 (review r3274071294):
the base ctx-manager treats target_values as the positional
rebuild-args contract (iterated as a tuple by reconstruct /
resume_fn / _call_func), so it must be None or a Sequence. A dict
slips through tuple(target_values) as just its keys -- the pytorch#184487
footgun -- so raise TypeError on misuse.

This surfaced FxTracebackAnnotateVariable, which passed the
torch.fx.traceback.annotate() dict straight into target_values
(safe today only because its reconstruct_type raises Unsupported,
so the positional path is never hit). Give it a dedicated
self.annotation attribute and pass target_values=(), mirroring
StreamContextVariable from pytorch#184487.

Similarly surfaced the same issue with NullContextVariable; same
fix.

Authored with Claude.
@williamwen42

Copy link
Copy Markdown
Member

@pytorchbot revert -m="Breaks internal builds" -c=ghfirst

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@tfogal your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Jun 15, 2026
@pytorch-bot
pytorch-bot Bot dismissed stale reviews from williamwen42, williamwen42, and mlazos June 15, 2026 22:49

This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.

@williamwen42

williamwen42 commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Streams were not being reconstructed across graph breaks correctly, e.g.

    @requires_cuda
    def test_stream_value_live_across_graph_break_in_stream_context(self):
        # Regression test: a plain torch.Stream value that is live across a
        # graph break occurring inside `with torch.cuda.stream(side):` must be
        # reconstructed as a Stream, not rebuilt as a StreamContext.
        #
        # StreamVariable subclasses StreamContextVariable for code reuse, so
        # OutputGraph._get_stack_values_to_restore used to misclassify the live
        # stream `s` as an inactive context manager and rebuild it in the resume
        # function via torch.cuda.stream(s) -> a StreamContext.  The eager
        # record_stream() call below then died with "unknown parameter type".

        @torch._dynamo.disable
        def eager_record_stream(t, stream):
            assert isinstance(stream, torch.Stream), type(stream)
            t.record_stream(stream)

        def fn(x):
            s = torch.cuda.current_stream()
            side = torch.cuda.Stream()
            with torch.cuda.stream(side):
                y = x + 1
                torch._dynamo.graph_break()
                out = y + 1
            del y
            eager_record_stream(out, s)
            return out

        x = torch.ones(3, device="cuda")
        out = torch.compile(fn, backend="eager")(x)
        self.assertEqual(out, torch.full((3,), 3.0, device="cuda"))

I have an internal diff (trying to export) that fixes this issue - we should include the fixes into this commit before relanding

@williamwen42

Copy link
Copy Markdown
Member

@tfogal see #187472

atalman added a commit that referenced this pull request Jun 25, 2026
…cross graph breaks (#184487)" (#188197)

Revert "dynamo: round-trip torch.cuda.stream ctx mgr across graph breaks (#184487)"

This reverts commit b0a67c7.

Reverted #184487 on behalf of https://github.com/williamwen42 due to Breaks internal builds ([comment](#184487 (comment)))

(cherry picked from commit 697514a)

Co-authored-by: PyTorch MergeBot <[email protected]>
pytorchmergebot pushed a commit to tfogal/pytorch that referenced this pull request Jun 29, 2026
Kshiteej asked for a follow-up to pytorch#184487 (review r3274071294):
the base ctx-manager treats target_values as the positional
rebuild-args contract (iterated as a tuple by reconstruct /
resume_fn / _call_func), so it must be None or a Sequence. A dict
slips through tuple(target_values) as just its keys -- the pytorch#184487
footgun -- so raise TypeError on misuse.

This surfaced FxTracebackAnnotateVariable, which passed the
torch.fx.traceback.annotate() dict straight into target_values
(safe today only because its reconstruct_type raises Unsupported,
so the positional path is never hit). Give it a dedicated
self.annotation attribute and pass target_values=(), mirroring
StreamContextVariable from pytorch#184487.

Similarly surfaced the same issue with NullContextVariable; same
fix.

Authored with Claude.
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#184487)

Upstream pytorch#166472 ('[user-streams] Switch to fx annotations at trace time') changed `StreamContextVariable.target_values` from a positional list [stream_var] to a dict {"stream": idx} so that StreamContextVariable.enter() (inherited from FxTracebackAnnotateVariable.enter) could feed it to torch.fx.traceback.annotate.  That broke three other consumers of target_values -- output_graph.py's stack_ctx_args / locals_ctx_args population, the base
ContextWrappingVariable.reconstruct, and
BlockStackEntry.resume_fn -> ReenterWith.try_finally -- all of which iterate it as a positional tuple.  tuple({"stream": 3}) flattens to ("stream",): the int index is silently dropped and the rebuild call ends up as e.g. torch.cuda.stream("stream"), which fails with a confusing device-string parse error.

The breakage has been latent since pytorch#166472 because FxTracebackAnnotateVariable.reconstruct_type raises Unsupported("torch.fx.traceback.annotate escaped from compiled region") unconditionally, short-circuiting the rebuild before the dict-vs-positional mismatch can surface.  The visible symptom is a silent ungraceful graph break that drops the post-break body when a graph break occurs inside with torch.cuda.stream(s):.

This fix structurally separates the two purposes of target_values:

  * self.annotation = {"stream": idx} is a new dedicated field that enter() passes to torch.fx.traceback.annotate.
  * target_values = () keeps the positional rebuild contract happy.

Then StreamContextVariable.reconstruct_type is overridden to push a 0-arg callable -- functools.partial(torch.cuda.stream, <Stream>) -- installed as a global on the compiled function via OutputGraph.install_global_by_id.  The base
ContextWrappingVariable.reconstruct appends CALL 0 (target_values is empty), invoking the partial to produce a fresh StreamContext just in time for the resume prologue's BEFORE_WITH.

functools.partial (rather than a freshly-defined closure) is critical: dynamo retraces the resume prologue, and a closure defined inside torch/_dynamo would be classified as MOD_SKIPLIST'd and refuse-to-trace, breaking the prologue.  functools.partial is a builtin that dynamo handles natively, and the wrapped target (torch.cuda.stream) is plainly traceable.

enter() is also inlined (rather than inherited from FxTracebackAnnotateVariable.enter) because the parent passes self.target_values to annotate, but target_values is now the positional rebuild-args tuple; the annotation dict lives on self.annotation.  reconstruct_type is overridden alongside to bypass FxTracebackAnnotateVariable.reconstruct_type's unconditional Unsupported raise.

Regression test added at
test/dynamo/test_streams.py::test_target_values_dict_round_trips_through_graph_break: graph break inside with torch.cuda.stream(s):, asserts two graph fragments are captured (rather than the post-break body being silently dropped to eager).  Whole test_streams.py suite: 68 pass, 7 platform-skipped, no regressions.

Authored with Claude.

Pull Request resolved: pytorch#184487
Approved by: https://github.com/williamwen42, https://github.com/mlazos

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
pytorchmergebot pushed a commit to tfogal/pytorch that referenced this pull request Jul 17, 2026
Kshiteej asked for a follow-up to pytorch#184487 (review r3274071294):
the base ctx-manager treats target_values as the positional
rebuild-args contract (iterated as a tuple by reconstruct /
resume_fn / _call_func), so it must be None or a Sequence. A dict
slips through tuple(target_values) as just its keys -- the pytorch#184487
footgun -- so raise TypeError on misuse.

This surfaced FxTracebackAnnotateVariable, which passed the
torch.fx.traceback.annotate() dict straight into target_values
(safe today only because its reconstruct_type raises Unsupported,
so the positional path is never hit). Give it a dedicated
self.annotation attribute and pass target_values=(), mirroring
StreamContextVariable from pytorch#184487.

Similarly surfaced the same issue with NullContextVariable; same
fix.

Authored with Claude.
pytorchmergebot pushed a commit to tfogal/pytorch that referenced this pull request Jul 28, 2026
Kshiteej asked for a follow-up to pytorch#184487 (review r3274071294):
the base ctx-manager treats target_values as the positional
rebuild-args contract (iterated as a tuple by reconstruct /
resume_fn / _call_func), so it must be None or a Sequence. A dict
slips through tuple(target_values) as just its keys -- the pytorch#184487
footgun -- so raise TypeError on misuse.

This surfaced FxTracebackAnnotateVariable, which passed the
torch.fx.traceback.annotate() dict straight into target_values
(safe today only because its reconstruct_type raises Unsupported,
so the positional path is never hit). Give it a dedicated
self.annotation attribute and pass target_values=(), mirroring
StreamContextVariable from pytorch#184487.

Similarly surfaced the same issue with NullContextVariable; same
fix.

Authored with Claude.
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#184487)

Upstream pytorch#166472 ('[user-streams] Switch to fx annotations at trace time') changed `StreamContextVariable.target_values` from a positional list [stream_var] to a dict {"stream": idx} so that StreamContextVariable.enter() (inherited from FxTracebackAnnotateVariable.enter) could feed it to torch.fx.traceback.annotate.  That broke three other consumers of target_values -- output_graph.py's stack_ctx_args / locals_ctx_args population, the base
ContextWrappingVariable.reconstruct, and
BlockStackEntry.resume_fn -> ReenterWith.try_finally -- all of which iterate it as a positional tuple.  tuple({"stream": 3}) flattens to ("stream",): the int index is silently dropped and the rebuild call ends up as e.g. torch.cuda.stream("stream"), which fails with a confusing device-string parse error.

The breakage has been latent since pytorch#166472 because FxTracebackAnnotateVariable.reconstruct_type raises Unsupported("torch.fx.traceback.annotate escaped from compiled region") unconditionally, short-circuiting the rebuild before the dict-vs-positional mismatch can surface.  The visible symptom is a silent ungraceful graph break that drops the post-break body when a graph break occurs inside with torch.cuda.stream(s):.

This fix structurally separates the two purposes of target_values:

  * self.annotation = {"stream": idx} is a new dedicated field that enter() passes to torch.fx.traceback.annotate.
  * target_values = () keeps the positional rebuild contract happy.

Then StreamContextVariable.reconstruct_type is overridden to push a 0-arg callable -- functools.partial(torch.cuda.stream, <Stream>) -- installed as a global on the compiled function via OutputGraph.install_global_by_id.  The base
ContextWrappingVariable.reconstruct appends CALL 0 (target_values is empty), invoking the partial to produce a fresh StreamContext just in time for the resume prologue's BEFORE_WITH.

functools.partial (rather than a freshly-defined closure) is critical: dynamo retraces the resume prologue, and a closure defined inside torch/_dynamo would be classified as MOD_SKIPLIST'd and refuse-to-trace, breaking the prologue.  functools.partial is a builtin that dynamo handles natively, and the wrapped target (torch.cuda.stream) is plainly traceable.

enter() is also inlined (rather than inherited from FxTracebackAnnotateVariable.enter) because the parent passes self.target_values to annotate, but target_values is now the positional rebuild-args tuple; the annotation dict lives on self.annotation.  reconstruct_type is overridden alongside to bypass FxTracebackAnnotateVariable.reconstruct_type's unconditional Unsupported raise.

Regression test added at
test/dynamo/test_streams.py::test_target_values_dict_round_trips_through_graph_break: graph break inside with torch.cuda.stream(s):, asserts two graph fragments are captured (rather than the post-break body being silently dropped to eager).  Whole test_streams.py suite: 68 pass, 7 platform-skipped, no regressions.

Authored with Claude.

Pull Request resolved: pytorch#184487
Approved by: https://github.com/williamwen42, https://github.com/mlazos

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
pytorchmergebot pushed a commit that referenced this pull request Jul 29, 2026
In #184487, @kshitij12345 recommended we validate that target_values is actually what it should be. This does that validation---and as Kshiteej probably suspected, it indeed flags a bug (also fixed).

This bug was: FxTracebackAnnotateVariable passed the torch.fx.traceback.annotate() dict straight into target_values (safe today only because its reconstruct_type raises Unsupported, so the positional path is never hit). Give it a dedicated self.annotation attribute and pass target_values=(), mirroring StreamContextVariable from #184487.

Authored with Claude.

Pull Request resolved: #186968
Approved by: https://github.com/kshitij12345, https://github.com/jansel
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
In pytorch#184487, @kshitij12345 recommended we validate that target_values is actually what it should be. This does that validation---and as Kshiteej probably suspected, it indeed flags a bug (also fixed).

This bug was: FxTracebackAnnotateVariable passed the torch.fx.traceback.annotate() dict straight into target_values (safe today only because its reconstruct_type raises Unsupported, so the positional path is never hit). Give it a dedicated self.annotation attribute and pass target_values=(), mirroring StreamContextVariable from pytorch#184487.

Authored with Claude.

Pull Request resolved: pytorch#186968
Approved by: https://github.com/kshitij12345, https://github.com/jansel
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Aug 15, 2026
@github-actions github-actions Bot closed this Sep 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo open source release notes: dynamo Reverted Stale 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.

10 participants