[dynamo][stream] Stream runtime operation in FX graph is ignored by remaining compiler
Labels: oncall: distributed, triaged, ezyang's list, oncall: pt2, module: aotdispatch, module: dynamo

### 🐛 Describe the bug

Hi,

Dynamo can capture the stream and its runtime API with this PR https://github.com/pytorch/pytorch/pull/93808.
Stream APIs can be traced into the FX graph and no graph break will happen, while i found the remaining compiler(AOTAutograd and Inductor) ignore the associated stream operations, for example, `torch.cuda.set_stream`.

Here is a simple reproducer for the issue:

```
import torch

@torch.compile(backend='inductor')
def test(x):
    x = x + 1.0
    stream = torch.cuda.Stream()
    torch.cuda.set_stream(stream)
    x = x * 2.0
    return x

input = torch.randn(16, 16, device='cuda')
for _ in range(10):
    output = test(input)
```

After dynamo and FX, the whole graph is shown as below. No graph break and runtime APIs are traced into the FX graph correctly, which is expected.
```
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]  ===== __compiled_fn_0 =====
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]  <eval_with_key>.0 class GraphModule(torch.nn.Module):
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]     def forward(self, L_x_ : torch.Tensor):
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         l_x_ = L_x_
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         # File: /home/pt-gpu/zejun/issue.py:5, code: x = x + 1.0
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         x = l_x_ + 1.0;  l_x_ = None
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         # File: /home/pt-gpu/zejun/issue.py:6, code: stream = torch.cuda.Stream()
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         stream = torch.cuda.streams.Stream()
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         # File: /home/pt-gpu/zejun/issue.py:7, code: torch.cuda.set_stream(stream)
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         set_stream = torch.cuda.set_stream(stream);  stream = None
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         # File: /home/pt-gpu/zejun/issue.py:8, code: x = x * 2.0
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         x_1 = x * 2.0;  x = None
 [2023-09-22 10:22:45,730] [0/0] torch._dynamo.output_graph.__graph_code: [DEBUG]         return (x_1,)
```

Then the graph after AOTAutograd is:
```
def forward(self, arg0_1):
    add = torch.ops.aten.add.Tensor(arg0_1, 1.0);  arg0_1 = None
    mul = torch.ops.aten.mul.Tensor(add, 2.0);  add = None
    return (mul,)
```

The backend compiler, like inductor, cannot know that the torch.add and the torch.mul need to execute on the different cuda streams. The info about streams switching is ignored, so the compiled triton kernel fuses the add and mul `triton_poi_fused_add_mul_0.run`:

```
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG] def call(args):
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]     arg0_1, = args
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]     args.clear()
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]     assert_size_stride(arg0_1, (16, 16), (16, 1))
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]     with torch.cuda._DeviceGuard(0):
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         torch.cuda.set_device(0) # no-op to ensure context
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         buf0 = empty_strided((16, 16), (16, 1), device='cuda', dtype=torch.float32)
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         # Source Nodes: [x, x_1], Original ATen: [aten.add, aten.mul]
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         stream0 = get_cuda_stream(0)
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         triton_poi_fused_add_mul_0.run(arg0_1, buf0, 256, grid=grid(256), stream=stream0)
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         del arg0_1
[2023-09-22 10:22:46,665] [0/0] torch._inductor.graph.__output_code: [DEBUG]         return (buf0, )
```

Add and mul should not be fused together because they execute on the different streams. I launch the compiled `test` function many times while the `torch.cuda.set_stream` are only called on the 1st iteration.

Solution: Maybe there could be an annotation or a mechanism(weak graph break) to tell the backend compiler(AOTAutograd or inductor) about the operators' execution info, for example, some torch ops are launched on different streams so they cannot be fused. I will try to give a solution candidate.

Thank you.

I found this issue when I support the device agnostic stream capture and trace the stream call methods into the FX graph: https://github.com/pytorch/pytorch/pull/108312

### Versions

Collecting environment information...
PyTorch version: 2.2.0a0+git772e104
Is debug build: False
CUDA used to build PyTorch: 11.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 10.5.0-1ubuntu1~20.04) 10.5.0
Clang version: Could not collect
CMake version: version 3.27.2
Libc version: glibc-2.31

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-79-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.4.152
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100-PCIE-40GB
Nvidia driver version: 470.82.01
cuDNN version: Probably one of the following:
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.6.0
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.6.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   48 bits physical, 48 bits virtual
CPU(s):                          64
On-line CPU(s) list:             0-63
Thread(s) per core:              1
Core(s) per socket:              64
Socket(s):                       1
NUMA node(s):                    8
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7713 64-Core Processor
Stepping:                        1
Frequency boost:                 enabled
CPU MHz:                         1500.000
CPU max MHz:                     3720.7029
CPU min MHz:                     1500.0000
BogoMIPS:                        4000.04
Virtualization:                  AMD-V
L1d cache:                       2 MiB
L1i cache:                       2 MiB
L2 cache:                        32 MiB
L3 cache:                        256 MiB
NUMA node0 CPU(s):               0-7
NUMA node1 CPU(s):               8-15
NUMA node2 CPU(s):               16-23
NUMA node3 CPU(s):               24-31
NUMA node4 CPU(s):               32-39
NUMA node5 CPU(s):               40-47
NUMA node6 CPU(s):               48-55
NUMA node7 CPU(s):               56-63
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Not affected
Vulnerability Retbleed:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm

Versions of relevant libraries:
[pip3] flake8==6.0.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-coding==1.3.3
[pip3] flake8-comprehensions==3.12.0
[pip3] flake8-executable==2.1.3
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==23.3.1
[pip3] flake8-simplify==0.19.3
[pip3] mypy==1.4.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.3
[pip3] pytorch-triton==2.1.0+e6216047b8
[pip3] torch==2.2.0a0+git772e104
[pip3] torchvision==0.15.2a0+fa99a53
[conda] numpy                     1.24.3                   pypi_0    pypi
[conda] pytorch-triton            2.1.0+e6216047b8          pypi_0    pypi
[conda] torch                     2.2.0a0+git772e104           dev_0    <develop>
[conda] torchvision               0.15.2a0+fa99a53          pypi_0    pypi


cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @ezyang @msaroufim @wconstab @bdhirsh @anijain2305 @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @Xia-Weiwen @wenzhe-nrv @jiayisunx @chenyang78 @aakhundov @kadeng