Skip to content

[dynamo] don't reconstruct live torch.Stream values as StreamContext across graph breaks - #187472

Closed
williamwen42 wants to merge 1 commit into
mainfrom
export-D108682817
Closed

williamwen42 wants to merge 1 commit into
mainfrom
export-D108682817

Conversation

@williamwen42

@williamwen42 williamwen42 commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Summary:
A plain torch.Stream value that is live across a graph break occurring inside a with torch.cuda.stream(side): block was being silently corrupted into a torch.cuda.StreamContext. A subsequent eager Tensor.record_stream(s) then crashed with RuntimeError: unknown parameter type (the C++ arg parser has no STREAM overload to match a StreamContext).

Root cause: OutputGraph._get_stack_values_to_restore records every live value where isinstance(value, ContextWrappingVariable) as an "inactive context variable". The resume function rebuilds those from their context-manager class -- reconstruct_type() pushes the class and the resume prologue calls it with target_values (see the handle_inactive_ctx path in symbolic_convert._create_resume). StreamVariable was a ContextWrappingVariable (it subclassed StreamContextVariable) for code reuse, so a plain stream value s matched this check and was rebuilt as torch.cuda.stream(s) -> a StreamContext.

Why the class-rebuild exists at all: Dynamo recognizes context managers at their construction call, not as opaque pre-built objects, so a context manager that is live-but-not-entered is made re-traceable in the resume function by re-running its constructor. This is the right mechanism for managers like torch.no_grad(), but it is both unnecessary and lossy for a torch.Stream: a stream is registered in the user-object table, reconstructs to the exact original object via get_external_object_by_index, and is re-recognized from its live instance by VariableBuilder (builder.py), so it round-trips perfectly as a value. Rebuilding it from its class instead changes the type (Stream -> StreamContext) and drops the concrete torch.cuda.Stream subtype (e.g. .cuda_stream disappears).

This stayed latent until #184487 (D108074476): before that, StreamContextVariable.reconstruct_type was inherited from FxTracebackAnnotateVariable and raised Unsupported unconditionally, so the misclassification could not silently produce a wrong object. #184487 added a real reconstruct_type (installing a functools.partial(torch.cuda.stream, ...) thunk) to round-trip the genuine with torch.cuda.stream(...) context manager across a graph break, which turned the latent misclassification into silent data corruption for plain stream values.

Fix: introduce ContextWrappingVariable.reconstructs_as_value_in_resume() (default False). A VT returns True when it reconstructs as a concrete, re-traceable object rather than needing the constructor-rebuild; StreamVariable returns True. _get_stack_values_to_restore skips such VTs when populating stack_ctx_args/locals_ctx_args, so a live stream reconstructs as the exact object (full subtype/identity fidelity) instead of being rebuilt as a StreamContext.

Also restructure the class hierarchy to mirror torch's: torch.cuda.Stream subclasses torch.Stream, while torch.cuda.StreamContext is an unrelated class. Previously StreamVariable subclassed StreamContextVariable, which encoded the fiction that a Stream is a kind of StreamContext and is what let a stream value flow into the context-manager rebuild path. Now StreamVariable (torch.Stream) and StreamContextVariable (torch.cuda.StreamContext) are not in a subclass relationship; they share a new StreamContextWrappingVariable base holding the common stream-selecting enter/exit/reconstruct_type (written in terms of get_stream()), and CudaStreamVariable/XpuStreamVariable continue to subclass StreamVariable just as torch.cuda.Stream/torch.xpu.Stream subclass torch.Stream. The genuine active-context cases are unchanged -- with torch.cuda.stream(s): and bare with stream: are restored via the block stack and still rebuild a fresh StreamContext to re-enter.

Authored with Claude Code.

Test Plan:
New regression test test_stream_value_live_across_graph_break_in_stream_context in test/dynamo/test_streams.py fails before the fix (RuntimeError: unknown parameter type) and passes after.

buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true fbcode//caffe2/test/dynamo:test_streams

Full suite on an H100/A100 host: Pass 65. Fail 0. Skip 6 (the legitimate round-trip tests test_target_values_dict_round_trips_through_graph_break and test_stream_context_graph_break still pass).

Differential Revision: D108682817

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

…across graph breaks

Summary:
A plain `torch.Stream` value that is live across a graph break occurring inside a `with torch.cuda.stream(side):` block was being silently corrupted into a `torch.cuda.StreamContext`. A subsequent eager `Tensor.record_stream(s)` then crashed with `RuntimeError: unknown parameter type` (the C++ arg parser has no `STREAM` overload to match a `StreamContext`).

Root cause: `OutputGraph._get_stack_values_to_restore` records every live value where `isinstance(value, ContextWrappingVariable)` as an "inactive context variable". The resume function rebuilds those from their context-manager class -- `reconstruct_type()` pushes the class and the resume prologue calls it with `target_values` (see the `handle_inactive_ctx` path in `symbolic_convert._create_resume`). `StreamVariable` was a `ContextWrappingVariable` (it subclassed `StreamContextVariable`) for code reuse, so a plain stream value `s` matched this check and was rebuilt as `torch.cuda.stream(s)` -> a `StreamContext`.

Why the class-rebuild exists at all: Dynamo recognizes context managers at their construction call, not as opaque pre-built objects, so a context manager that is live-but-not-entered is made re-traceable in the resume function by re-running its constructor. This is the right mechanism for managers like `torch.no_grad()`, but it is both unnecessary and lossy for a `torch.Stream`: a stream is registered in the user-object table, reconstructs to the exact original object via `get_external_object_by_index`, and is re-recognized from its live instance by `VariableBuilder` (`builder.py`), so it round-trips perfectly as a value. Rebuilding it from its class instead changes the type (`Stream` -> `StreamContext`) and drops the concrete `torch.cuda.Stream` subtype (e.g. `.cuda_stream` disappears).

This stayed latent until #184487 (D108074476): before that, `StreamContextVariable.reconstruct_type` was inherited from `FxTracebackAnnotateVariable` and raised `Unsupported` unconditionally, so the misclassification could not silently produce a wrong object. #184487 added a real `reconstruct_type` (installing a `functools.partial(torch.cuda.stream, ...)` thunk) to round-trip the genuine `with torch.cuda.stream(...)` context manager across a graph break, which turned the latent misclassification into silent data corruption for plain stream values.

Fix: introduce `ContextWrappingVariable.reconstructs_as_value_in_resume()` (default `False`). A VT returns `True` when it reconstructs as a concrete, re-traceable object rather than needing the constructor-rebuild; `StreamVariable` returns `True`. `_get_stack_values_to_restore` skips such VTs when populating `stack_ctx_args`/`locals_ctx_args`, so a live stream reconstructs as the exact object (full subtype/identity fidelity) instead of being rebuilt as a `StreamContext`.

Also restructure the class hierarchy to mirror torch's: `torch.cuda.Stream` subclasses `torch.Stream`, while `torch.cuda.StreamContext` is an unrelated class. Previously `StreamVariable` subclassed `StreamContextVariable`, which encoded the fiction that a `Stream` is a kind of `StreamContext` and is what let a stream value flow into the context-manager rebuild path. Now `StreamVariable` (`torch.Stream`) and `StreamContextVariable` (`torch.cuda.StreamContext`) are not in a subclass relationship; they share a new `StreamContextWrappingVariable` base holding the common stream-selecting `enter`/`exit`/`reconstruct_type` (written in terms of `get_stream()`), and `CudaStreamVariable`/`XpuStreamVariable` continue to subclass `StreamVariable` just as `torch.cuda.Stream`/`torch.xpu.Stream` subclass `torch.Stream`. The genuine active-context cases are unchanged -- `with torch.cuda.stream(s):` and bare `with stream:` are restored via the block stack and still rebuild a fresh `StreamContext` to re-enter.

Authored with Claude Code.

Test Plan:
New regression test `test_stream_value_live_across_graph_break_in_stream_context` in `test/dynamo/test_streams.py` fails before the fix (`RuntimeError: unknown parameter type`) and passes after.

```
buck2 test fbcode//mode/opt -c fbcode.enable_gpu_sections=true fbcode//caffe2/test/dynamo:test_streams
```

Full suite on an H100/A100 host: `Pass 65. Fail 0. Skip 6` (the legitimate round-trip tests `test_target_values_dict_round_trips_through_graph_break` and `test_stream_context_graph_break` still pass).

Differential Revision: D108682817
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Jun 16, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 6 Unrelated Failures

As of commit 96813ea with merge base c375ad8 (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but was 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 commented Jun 16, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@meta-codesync

meta-codesync Bot commented Jun 16, 2026

Copy link
Copy Markdown

@williamwen42 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D108682817.

@tfogal tfogal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Instead of introducing a StreamContextWrappingVariable, I think it's an easier fix to just change StreamVariable to derive from the parent instead of deriving from StreamContextVariable. Then we don't have a situation where a StreamVariable is-a StreamContextVariable (which is what's causing a StreamVariable to reconstruct as a StreamContextVariable). It also matches the actual/real type hierarchy of torch.cuda.Stream and torch.cuda.StreamContext (which are unrelated).

You do have to then do some work so that StreamVariable can be used as a context, but that's exactly what torch.cuda.Stream does (by inheriting from THPStreamClass, which itself defines the _enter and _exit methods), so it's again mirrored by the actual implementation.

But anyway +1 from me as you could always do that in a followup, and honestly not doing so at all just means having some extra code here and there, so it really doesn't matter in the scheme of things.

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 16, 2026
@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 16, 2026
@github-actions github-actions Bot closed this Sep 15, 2026
@github-actions
github-actions Bot deleted the export-D108682817 branch October 15, 2026 01:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request meta-exported module: dynamo Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants