Skip to content

[fx_graph_runnable] Add generator for after_aot repro - #179657

Closed
yushangdi wants to merge 1 commit into
gh/yushangdi/21/basefrom
gh/yushangdi/21/head
Closed

yushangdi wants to merge 1 commit into
gh/yushangdi/21/basefrom
gh/yushangdi/21/head

Conversation

@yushangdi

@yushangdi yushangdi commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

When torch.compile generates an fx_graph_runnable repro script for a graph
containing graphsafe_run_with_rng_state, the fwd_rng_state_N argument (a
torch._C.Generator) falls through to InputWriter.unsupported(), producing
reader.unsupported(...) in the repro. At load time, InputReader.unsupported()
returns None, so the repro crashes with
AttributeError: 'NoneType' object has no attribute 'device'.

This adds generator() methods to InputWriter, InputReader, and
NopInputReader that properly serialize/deserialize Generator arguments, and
detects torch._C.Generator in save_graph_repro so it routes through the new
path instead of unsupported.

Authored with Claude.

Test plan

  • python test/dynamo/test_after_aot.py TestAfterAot.test_dump_generator
  • python test/dynamo/test_after_aot.py TestAfterAot.test_graphsafe_rng_repro

E2E Example:

import torch
import torch.utils.checkpoint

torch._logging.set_logs(aot_graphs=True)


def fn(q, k, v):
    return torch.nn.functional.scaled_dot_product_attention(
        q, k, v, dropout_p=0.1, is_causal=True
    )


def checkpointed_fn(q, k, v):
    return torch.utils.checkpoint.checkpoint(fn, q, k, v, use_reentrant=False)


model = torch.compile(checkpointed_fn)

q = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
k = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
v = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)

out = model(q, k, v)
out.sum().backward()

fx_graph_runnable, note the reader.generator('cuda', 0) # fwd_rng_state_0 generated.
Without the PR, it will generate reader.unsupported('fwd_rng_state_0') # unsupported type for dumping: <class 'torch._C.Generator'> and error out with

    device_idx = rng_state.device.index
                 ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'device'
.....
torch._higher_order_ops.triton_kernel_wrap.kernel_side_table.reset_table()

from torch.nn import *
class Repro(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()



    def forward(self, primals_1, primals_2, primals_3, fwd_rng_state_0):
        graphsafe_run_with_rng_state = torch.ops.higher_order.graphsafe_run_with_rng_state(torch.ops.aten._scaled_dot_product_efficient_attention.default, primals_1, primals_2, primals_3, None, True, 0.1, True, rng_state = fwd_rng_state_0);  fwd_rng_state_0 = None
        getitem = graphsafe_run_with_rng_state[0];  graphsafe_run_with_rng_state = None
        return (getitem, primals_1, primals_2, primals_3)

def load_args(reader):
    buf0 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf0, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_1
    buf1 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf1, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_2
    buf2 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf2, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_3
    reader.generator('cuda', 0)  # fwd_rng_state_0

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

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

@pytorch-bot

pytorch-bot Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 1 Pending, 1 Unrelated Failure

As of commit 55b88a7 with merge base 50de2af (image):

NEW FAILURES - The following jobs have failed:

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

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

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

@pytorch-bot

pytorch-bot Bot commented Apr 8, 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.

@yushangdi

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

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

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 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.

Details for Dev Infra team Raised by workflow job

@pytorch-bot

pytorch-bot Bot commented Apr 8, 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.

@yushangdi yushangdi added the topic: not user facing topic category label Apr 8, 2026
@yushangdi

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Apr 9, 2026
### Summary

Replaces the `OpaqueGenerator` Python wrapper from  #179658 by making
`torch._C.Generator` itself a proper opaque reference type. This eliminates the
wrapper class entirely.

C++ changes to `THPGenerator`:
- Set `OpaqueBaseMeta` as the metaclass (same pattern as `ProcessGroup`)
- Add weakref support (`tp_weaklistoffset` + `weakreflist` field)
- Add `tp_richcompare` (identity-based `__eq__`/`__ne__`)
- Add `tp_hash` (identity-based)
- Add `__fx_repr__` method for FX codegen

Also fixes `THPModule_addDocStr` to use `PyType_Check(obj)` instead of
`Py_TYPE(obj) == &PyType_Type`, since Generator's metaclass is now
`OpaqueBaseMeta` rather than `type`.

With these changes, `torch._C.Generator` is registered directly via
`register_opaque_type(torch._C.Generator, typ="value")` and flows through
`make_fx`, FX codegen, and the repro infrastructure without any wrapper.

Authored with Claude.

### Test plan

- `python test/dynamo/test_after_aot.py` (all 6 tests)
- `python test/inductor/test_torchinductor.py -k test_randn_generator_cuda`
- `python test/test_opaque_obj_v2.py TestOpaqueGenerator` (make_fx + correctness)
- ` python test/test_torch.py -k test_pickle_generator` (generator can be pickled)
- `python test/dynamo/test_dynamic_shapes.py -k test_user_getattr1_dynamic_shapes`
- `python agent_space/repro.py` (end-to-end repro)
- `python test/test_fx.py -k test_impure_random` (Generator is a C type, it has __init__ without __code__)

Pull Request resolved: #179661
Approved by: https://github.com/angelayi
ghstack dependencies: #179657
@github-actions
github-actions Bot deleted the gh/yushangdi/21/head branch May 9, 2026 02:25
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
### Summary

When `torch.compile` generates an `fx_graph_runnable` repro script for a graph
containing `graphsafe_run_with_rng_state`, the `fwd_rng_state_N` argument (a
`torch._C.Generator`) falls through to `InputWriter.unsupported()`, producing
`reader.unsupported(...)` in the repro. At load time, `InputReader.unsupported()`
returns `None`, so the repro crashes with
`AttributeError: 'NoneType' object has no attribute 'device'`.

This adds `generator()` methods to `InputWriter`, `InputReader`, and
`NopInputReader` that properly serialize/deserialize Generator arguments, and
detects `torch._C.Generator` in `save_graph_repro` so it routes through the new
path instead of `unsupported`.

Authored with Claude.

### Test plan

- `python test/dynamo/test_after_aot.py TestAfterAot.test_dump_generator`
- `python test/dynamo/test_after_aot.py TestAfterAot.test_graphsafe_rng_repro`

---

E2E Example:

```
import torch
import torch.utils.checkpoint

torch._logging.set_logs(aot_graphs=True)

def fn(q, k, v):
    return torch.nn.functional.scaled_dot_product_attention(
        q, k, v, dropout_p=0.1, is_causal=True
    )

def checkpointed_fn(q, k, v):
    return torch.utils.checkpoint.checkpoint(fn, q, k, v, use_reentrant=False)

model = torch.compile(checkpointed_fn)

q = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
k = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
v = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)

out = model(q, k, v)
out.sum().backward()
```

fx_graph_runnable, note the **reader.generator('cuda', 0)  # fwd_rng_state_0** generated.
Without the PR, it will generate `reader.unsupported('fwd_rng_state_0')  # unsupported type for dumping: <class 'torch._C.Generator'>` and error out with
```
    device_idx = rng_state.device.index
                 ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'device'
```

```
.....
torch._higher_order_ops.triton_kernel_wrap.kernel_side_table.reset_table()

from torch.nn import *
class Repro(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, primals_1, primals_2, primals_3, fwd_rng_state_0):
        graphsafe_run_with_rng_state = torch.ops.higher_order.graphsafe_run_with_rng_state(torch.ops.aten._scaled_dot_product_efficient_attention.default, primals_1, primals_2, primals_3, None, True, 0.1, True, rng_state = fwd_rng_state_0);  fwd_rng_state_0 = None
        getitem = graphsafe_run_with_rng_state[0];  graphsafe_run_with_rng_state = None
        return (getitem, primals_1, primals_2, primals_3)

def load_args(reader):
    buf0 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf0, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_1
    buf1 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf1, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_2
    buf2 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf2, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_3
    reader.generator('cuda', 0)  # fwd_rng_state_0
```

Pull Request resolved: pytorch#179657
Approved by: https://github.com/PaulZhang12
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
### Summary

Replaces the `OpaqueGenerator` Python wrapper from  pytorch#179658 by making
`torch._C.Generator` itself a proper opaque reference type. This eliminates the
wrapper class entirely.

C++ changes to `THPGenerator`:
- Set `OpaqueBaseMeta` as the metaclass (same pattern as `ProcessGroup`)
- Add weakref support (`tp_weaklistoffset` + `weakreflist` field)
- Add `tp_richcompare` (identity-based `__eq__`/`__ne__`)
- Add `tp_hash` (identity-based)
- Add `__fx_repr__` method for FX codegen

Also fixes `THPModule_addDocStr` to use `PyType_Check(obj)` instead of
`Py_TYPE(obj) == &PyType_Type`, since Generator's metaclass is now
`OpaqueBaseMeta` rather than `type`.

With these changes, `torch._C.Generator` is registered directly via
`register_opaque_type(torch._C.Generator, typ="value")` and flows through
`make_fx`, FX codegen, and the repro infrastructure without any wrapper.

Authored with Claude.

### Test plan

- `python test/dynamo/test_after_aot.py` (all 6 tests)
- `python test/inductor/test_torchinductor.py -k test_randn_generator_cuda`
- `python test/test_opaque_obj_v2.py TestOpaqueGenerator` (make_fx + correctness)
- ` python test/test_torch.py -k test_pickle_generator` (generator can be pickled)
- `python test/dynamo/test_dynamic_shapes.py -k test_user_getattr1_dynamic_shapes`
- `python agent_space/repro.py` (end-to-end repro)
- `python test/test_fx.py -k test_impure_random` (Generator is a C type, it has __init__ without __code__)

Pull Request resolved: pytorch#179661
Approved by: https://github.com/angelayi
ghstack dependencies: pytorch#179657
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
### Summary

When `torch.compile` generates an `fx_graph_runnable` repro script for a graph
containing `graphsafe_run_with_rng_state`, the `fwd_rng_state_N` argument (a
`torch._C.Generator`) falls through to `InputWriter.unsupported()`, producing
`reader.unsupported(...)` in the repro. At load time, `InputReader.unsupported()`
returns `None`, so the repro crashes with
`AttributeError: 'NoneType' object has no attribute 'device'`.

This adds `generator()` methods to `InputWriter`, `InputReader`, and
`NopInputReader` that properly serialize/deserialize Generator arguments, and
detects `torch._C.Generator` in `save_graph_repro` so it routes through the new
path instead of `unsupported`.

Authored with Claude.

### Test plan

- `python test/dynamo/test_after_aot.py TestAfterAot.test_dump_generator`
- `python test/dynamo/test_after_aot.py TestAfterAot.test_graphsafe_rng_repro`

---

E2E Example:

```
import torch
import torch.utils.checkpoint

torch._logging.set_logs(aot_graphs=True)

def fn(q, k, v):
    return torch.nn.functional.scaled_dot_product_attention(
        q, k, v, dropout_p=0.1, is_causal=True
    )

def checkpointed_fn(q, k, v):
    return torch.utils.checkpoint.checkpoint(fn, q, k, v, use_reentrant=False)

model = torch.compile(checkpointed_fn)

q = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
k = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)
v = torch.randn(2, 8, 64, 32, device="cuda", dtype=torch.float16, requires_grad=True)

out = model(q, k, v)
out.sum().backward()
```

fx_graph_runnable, note the **reader.generator('cuda', 0)  # fwd_rng_state_0** generated.
Without the PR, it will generate `reader.unsupported('fwd_rng_state_0')  # unsupported type for dumping: <class 'torch._C.Generator'>` and error out with
```
    device_idx = rng_state.device.index
                 ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'device'
```

```
.....
torch._higher_order_ops.triton_kernel_wrap.kernel_side_table.reset_table()

from torch.nn import *
class Repro(torch.nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, primals_1, primals_2, primals_3, fwd_rng_state_0):
        graphsafe_run_with_rng_state = torch.ops.higher_order.graphsafe_run_with_rng_state(torch.ops.aten._scaled_dot_product_efficient_attention.default, primals_1, primals_2, primals_3, None, True, 0.1, True, rng_state = fwd_rng_state_0);  fwd_rng_state_0 = None
        getitem = graphsafe_run_with_rng_state[0];  graphsafe_run_with_rng_state = None
        return (getitem, primals_1, primals_2, primals_3)

def load_args(reader):
    buf0 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf0, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_1
    buf1 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf1, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_2
    buf2 = reader.storage(None, 65536, device=device(type='cuda', index=0), dtype_hint=torch.float16)
    reader.tensor(buf2, (2, 8, 64, 32), dtype=torch.float16, is_leaf=True)  # primals_3
    reader.generator('cuda', 0)  # fwd_rng_state_0
```

Pull Request resolved: pytorch#179657
Approved by: https://github.com/PaulZhang12
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
### Summary

Replaces the `OpaqueGenerator` Python wrapper from  pytorch#179658 by making
`torch._C.Generator` itself a proper opaque reference type. This eliminates the
wrapper class entirely.

C++ changes to `THPGenerator`:
- Set `OpaqueBaseMeta` as the metaclass (same pattern as `ProcessGroup`)
- Add weakref support (`tp_weaklistoffset` + `weakreflist` field)
- Add `tp_richcompare` (identity-based `__eq__`/`__ne__`)
- Add `tp_hash` (identity-based)
- Add `__fx_repr__` method for FX codegen

Also fixes `THPModule_addDocStr` to use `PyType_Check(obj)` instead of
`Py_TYPE(obj) == &PyType_Type`, since Generator's metaclass is now
`OpaqueBaseMeta` rather than `type`.

With these changes, `torch._C.Generator` is registered directly via
`register_opaque_type(torch._C.Generator, typ="value")` and flows through
`make_fx`, FX codegen, and the repro infrastructure without any wrapper.

Authored with Claude.

### Test plan

- `python test/dynamo/test_after_aot.py` (all 6 tests)
- `python test/inductor/test_torchinductor.py -k test_randn_generator_cuda`
- `python test/test_opaque_obj_v2.py TestOpaqueGenerator` (make_fx + correctness)
- ` python test/test_torch.py -k test_pickle_generator` (generator can be pickled)
- `python test/dynamo/test_dynamic_shapes.py -k test_user_getattr1_dynamic_shapes`
- `python agent_space/repro.py` (end-to-end repro)
- `python test/test_fx.py -k test_impure_random` (Generator is a C type, it has __init__ without __code__)

Pull Request resolved: pytorch#179661
Approved by: https://github.com/angelayi
ghstack dependencies: pytorch#179657
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 Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants