Repository navigation
[dynamo] don't reconstruct live torch.Stream values as StreamContext across graph breaks - #187472
williamwen42 wants to merge 1 commit into
Conversation
…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
🔗 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 FailuresAs of commit 96813ea with merge base c375ad8 ( 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. |
This PR needs a
|
|
@williamwen42 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D108682817. |
tfogal
left a comment
There was a problem hiding this comment.
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.
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
Summary:
A plain
torch.Streamvalue that is live across a graph break occurring inside awith torch.cuda.stream(side):block was being silently corrupted into atorch.cuda.StreamContext. A subsequent eagerTensor.record_stream(s)then crashed withRuntimeError: unknown parameter type(the C++ arg parser has noSTREAMoverload to match aStreamContext).Root cause:
OutputGraph._get_stack_values_to_restorerecords every live value whereisinstance(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 withtarget_values(see thehandle_inactive_ctxpath insymbolic_convert._create_resume).StreamVariablewas aContextWrappingVariable(it subclassedStreamContextVariable) for code reuse, so a plain stream valuesmatched this check and was rebuilt astorch.cuda.stream(s)-> aStreamContext.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 atorch.Stream: a stream is registered in the user-object table, reconstructs to the exact original object viaget_external_object_by_index, and is re-recognized from its live instance byVariableBuilder(builder.py), so it round-trips perfectly as a value. Rebuilding it from its class instead changes the type (Stream->StreamContext) and drops the concretetorch.cuda.Streamsubtype (e.g..cuda_streamdisappears).This stayed latent until #184487 (D108074476): before that,
StreamContextVariable.reconstruct_typewas inherited fromFxTracebackAnnotateVariableand raisedUnsupportedunconditionally, so the misclassification could not silently produce a wrong object. #184487 added a realreconstruct_type(installing afunctools.partial(torch.cuda.stream, ...)thunk) to round-trip the genuinewith 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()(defaultFalse). A VT returnsTruewhen it reconstructs as a concrete, re-traceable object rather than needing the constructor-rebuild;StreamVariablereturnsTrue._get_stack_values_to_restoreskips such VTs when populatingstack_ctx_args/locals_ctx_args, so a live stream reconstructs as the exact object (full subtype/identity fidelity) instead of being rebuilt as aStreamContext.Also restructure the class hierarchy to mirror torch's:
torch.cuda.Streamsubclassestorch.Stream, whiletorch.cuda.StreamContextis an unrelated class. PreviouslyStreamVariablesubclassedStreamContextVariable, which encoded the fiction that aStreamis a kind ofStreamContextand is what let a stream value flow into the context-manager rebuild path. NowStreamVariable(torch.Stream) andStreamContextVariable(torch.cuda.StreamContext) are not in a subclass relationship; they share a newStreamContextWrappingVariablebase holding the common stream-selectingenter/exit/reconstruct_type(written in terms ofget_stream()), andCudaStreamVariable/XpuStreamVariablecontinue to subclassStreamVariablejust astorch.cuda.Stream/torch.xpu.Streamsubclasstorch.Stream. The genuine active-context cases are unchanged --with torch.cuda.stream(s):and barewith stream:are restored via the block stack and still rebuild a freshStreamContextto re-enter.Authored with Claude Code.
Test Plan:
New regression test
test_stream_value_live_across_graph_break_in_stream_contextintest/dynamo/test_streams.pyfails before the fix (RuntimeError: unknown parameter type) and passes after.Full suite on an H100/A100 host:
Pass 65. Fail 0. Skip 6(the legitimate round-trip teststest_target_values_dict_round_trips_through_graph_breakandtest_stream_context_graph_breakstill pass).Differential Revision: D108682817
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98