Repository: pytorch
Issue: [dynamo] `.view([..., -1, ...])` fails on Tensors with unbacked SymInts in the shape
Labels: triaged,oncall: pt2,module: dynamic shapes

### 🐛 Describe the bug

Running this code:

```python
import torch

def fn(x):
    i0 = x.nonzero().size(0)
    y = torch.zeros((i0, 192))
    return y.view([12, -1, 192])

with torch._dynamo.config.patch({"capture_dynamic_output_shape_ops": True}):
    torch.compile(fn, fullgraph=True)(torch.ones((12,)))
```

Leads to this error:

```
Traceback (most recent call last):
  File "/data/users/aakhundov/pytorch/torch/_dynamo/utils.py", line 1454, in get_fake_value
    ret_val = wrap_fake_exception(
              ^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_dynamo/utils.py", line 1003, in wrap_fake_exception
    return fn()
           ^^^^
  File "/data/users/aakhundov/pytorch/torch/_dynamo/utils.py", line 1455, in <lambda>
    lambda: run_node(tx.output, node, args, kwargs, nnmodule)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_dynamo/utils.py", line 1558, in run_node
    raise RuntimeError(fn_str + str(e)).with_traceback(e.__traceback__) from e
  File "/data/users/aakhundov/pytorch/torch/_dynamo/utils.py", line 1539, in run_node
    return getattr(args[0], node.target)(*args[1:], **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/utils/_stats.py", line 20, in wrapper
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_subclasses/fake_tensor.py", line 1381, in __torch_dispatch__
    return self.dispatch(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_subclasses/fake_tensor.py", line 1587, in dispatch
    return decomposition_table[func](*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_refs/__init__.py", line 4455, in view
    return _reshape_view_helper(a, *shape, allow_copy=False)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_refs/__init__.py", line 3585, in _reshape_view_helper
    shape = utils.infer_size(shape, a.numel())
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/_prims_common/__init__.py", line 848, in infer_size
    numel == newsize or (dim is not None and newsize > 0 and numel % newsize == 0),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/__init__.py", line 361, in __bool__
    return self.node.bool_()
           ^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/sym_node.py", line 382, in bool_
    return self.guard_bool("", 0)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/sym_node.py", line 348, in guard_bool
    r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/recording.py", line 250, in wrapper
    return event.run(self)
           ^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/recording.py", line 151, in run
    return self.f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/symbolic_shapes.py", line 3175, in evaluate_expr
    concrete_val = self.size_hint(orig_expr)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/users/aakhundov/pytorch/torch/fx/experimental/symbolic_shapes.py", line 2968, in size_hint
    raise self._make_data_dependent_error(result_expr, expr)
RuntimeError: Failed running call_method view(*(FakeTensor(..., size=(i0, 192)), [12, -1, 192]), **{}):
It appears that you're trying to get a value out of symbolic int/float whose value is data-dependent (and thus we do not know the true value.)  The expression we were trying to evaluate is Eq(192*i0, 2304) (unhinted: Eq(192*i0, 2304)).  Scroll up to see where each of these data-dependent accesses originally occurred.
```

Changing -1 in the code above to `i0 // 12`:

```python
import torch

def fn(x):
    i0 = x.nonzero().size(0)
    y = torch.zeros((i0, 192))
    return y.view([12, i0 // 12, 192])

with torch._dynamo.config.patch({"capture_dynamic_output_shape_ops": True}):
    torch.compile(fn, fullgraph=True)(torch.ones((12,)))
```

Slightly changes the error message (not the stack trace):

```
RuntimeError: Failed running call_method view(*(FakeTensor(..., size=(i0, 192)), [12, (i0//12), 192]), **{}):
It appears that you're trying to get a value out of symbolic int/float whose value is data-dependent (and thus we do not know the true value.)  The expression we were trying to evaluate is Eq(192*i0, 2304*((i0//12))) (unhinted: Eq(192*i0, 2304*((i0//12)))).  Scroll up to see where each of these data-dependent accesses originally occurred.
```

Both errors are likely caused by the check `numel == newsize` in the line below involving the unbacked SymInt `i0`:

https://github.com/pytorch/pytorch/blob/ae72607e5fa31910f979c56bfe5ff0ed5f3db866/torch/_prims_common/__init__.py#L848

With -1 in the target shape, the `Eq(192*i0, 2304)` can't be evaluated, as we don't know the value backing `i0`. When -1 is replaced by `i0 // 12`, the `Eq(192*i0, 2304*((i0//12)))` would evaluate to `True` under the assumption that `i0` is divisible by 12, but this is likely not assumed.

It would be great to support -1 in the `view`'s target shape in this case, as requiring the model authors to stick to expressions like `unbacked_symint // product_of_unmatched_static_dims` instead of -1 seems like hurting the UX / too restrictive.

CC @ezyang. Thanks!

<details>
<summary>Versions</summary>

```
PyTorch version: 2.2.0a0+git8ff0036
Is debug build: False
CUDA used to build PyTorch: 12.0
ROCM used to build PyTorch: N/A

OS: CentOS Stream 9 (x86_64)
GCC version: (GCC) 11.4.1 20230605 (Red Hat 11.4.1-2)
Clang version: 16.0.6 (Red Hat 16.0.6-1.el9)
CMake version: version 3.22.1
Libc version: glibc-2.34

Python version: 3.11.3 (main, May 15 2023, 15:45:52) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.12.0-0_fbk16_zion_7661_geb00762ce6d2-x86_64-with-glibc2.34
Is CUDA available: True
CUDA runtime version: 12.0.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA PG509-210
GPU 1: NVIDIA PG509-210
GPU 2: NVIDIA PG509-210
GPU 3: NVIDIA PG509-210
GPU 4: NVIDIA PG509-210
GPU 5: NVIDIA PG509-210
GPU 6: NVIDIA PG509-210
GPU 7: NVIDIA PG509-210

Nvidia driver version: 525.105.17
cuDNN version: Probably one of the following:
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.9.2
/usr/local/cuda-12.0/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.9.2
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: False

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Address sizes:                   46 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          192
On-line CPU(s) list:             0-191
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Platinum 8339HC CPU @ 1.80GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       4
Stepping:                        11
Frequency boost:                 enabled
CPU max MHz:                     1801.0000
CPU min MHz:                     800.0000
BogoMIPS:                        3600.00
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       3 MiB (96 instances)
L1i cache:                       3 MiB (96 instances)
L2 cache:                        96 MiB (96 instances)
L3 cache:                        132 MiB (4 instances)
NUMA node(s):                    4
NUMA node0 CPU(s):               0-23,96-119
NUMA node1 CPU(s):               24-47,120-143
NUMA node2 CPU(s):               48-71,144-167
NUMA node3 CPU(s):               72-95,168-191
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          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; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] bert-pytorch==0.0.1a4
[pip3] clip-anytorch==2.5.2
[pip3] CoCa-pytorch==0.0.7
[pip3] dalle2-pytorch==1.14.2
[pip3] ema-pytorch==0.2.3
[pip3] flake8==6.0.0
[pip3] flake8-bugbear==23.3.23
[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] functorch==1.14.0a0+b71aa0b
[pip3] mypy==1.4.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.3
[pip3] onnx==1.14.0
[pip3] open-clip-torch==2.20.0
[pip3] optree==0.9.1
[pip3] pytorch-transformers==1.2.0
[pip3] pytorch-warmup==0.1.1
[pip3] rotary-embedding-torch==0.2.3
[pip3] torch==2.2.0a0+gitf5088d2
[pip3] torch-fidelity==0.3.0
[pip3] torch_geometric==2.4.0
[pip3] torch-struct==0.5
[pip3] torchaudio==2.1.0a0+406e9c8
[pip3] torchdata==0.7.0a0+901b483
[pip3] torchdata==0.7.0a0+901b483
[pip3] torchmetrics==0.11.4
[pip3] torchrec-nightly==2023.6.14
[pip3] torchtext==0.16.0a0+60bea66
[pip3] torchvision==0.16.0a0+8324c48
[pip3] triton==2.1.0
[pip3] vector-quantize-pytorch==1.6.14
[conda] bert-pytorch              0.0.1a4                   dev_0    <develop>
[conda] blas                      1.0                         mkl  
[conda] clip-anytorch             2.5.2                    pypi_0    pypi
[conda] coca-pytorch              0.0.7                    pypi_0    pypi
[conda] dalle2-pytorch            1.14.2                   pypi_0    pypi
[conda] ema-pytorch               0.2.3                    pypi_0    pypi
[conda] functorch                 1.14.0a0+b71aa0b          pypi_0    pypi
[conda] magma-cuda116             2.6.1                         1    pytorch
[conda] mkl                       2023.1.0         h6d00ec8_46342  
[conda] mkl-include               2023.1.0         h06a4308_46342  
[conda] mkl-service               2.4.0           py311h5eee18b_1  
[conda] mkl_fft                   1.3.6           py311ha02d727_1  
[conda] mkl_random                1.2.2           py311ha02d727_1  
[conda] numpy                     1.24.3          py311h08b1b3b_1  
[conda] numpy-base                1.24.3          py311hf175353_1  
[conda] open-clip-torch           2.20.0                   pypi_0    pypi
[conda] optree                    0.9.1                    pypi_0    pypi
[conda] pytorch-transformers      1.2.0                    pypi_0    pypi
[conda] pytorch-warmup            0.1.1                    pypi_0    pypi
[conda] rotary-embedding-torch    0.2.3                    pypi_0    pypi
[conda] torch                     2.2.0a0+gitf5088d2           dev_0    <develop>
[conda] torch-fidelity            0.3.0                    pypi_0    pypi
[conda] torch-geometric           2.4.0                    pypi_0    pypi
[conda] torch-struct              0.5                      pypi_0    pypi
[conda] torchaudio                2.1.0a0+406e9c8           dev_0    <develop>
[conda] torchdata                 0.7.0a0+901b483          pypi_0    pypi
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchrec-nightly          2023.6.14                pypi_0    pypi
[conda] torchtext                 0.16.0a0+60bea66           dev_0    <develop>
[conda] torchvision               0.16.0a0+8324c48           dev_0    <develop>
[conda] triton                    2.1.0                    pypi_0    pypi
[conda] vector-quantize-pytorch   1.6.14                   pypi_0    pypi
```

</details>

cc @ezyang @msaroufim @wconstab @bdhirsh @anijain2305 @zou3519