Repository: pytorch
Issue: [inductor] [dynamic shape] 5 HF models fails with `Constraints violated` using transformers v4.31.0
Labels: triaged,oncall: pt2,module: dynamic shapes,module: dynamo

### 🐛 Describe the bug

`BertForMaskedLM`, `BertForQuestionAnswering`, `CamemBert`, `RobertaForCausalLM`, `RobertaForQuestionAnswering` in HF fail with `Constraints violated` using transformers `v4.31.0` but work well with transformers `4.30.2`.

The failure is caused by this change in transformers: https://github.com/huggingface/transformers/pull/24510 and more exactly this function:
[warn_if_padding_and_no_attention_mask](https://github.com/huggingface/transformers/blob/78a2b19fc84ed55c65f4bf20a901edb7ceb73c5f/src/transformers/modeling_utils.py#L3480C9-L3480C46).

When running the benchmark, the batch dim is marked as dynamic [here](https://github.com/pytorch/pytorch/blob/ddf36c82b83b2db3be7ce7a85d4aea3507c9d7ef/benchmarks/dynamo/common.py#L3454). But due to the HF model change of adding [warn_if_padding_and_no_attention_mask](https://github.com/huggingface/transformers/blob/78a2b19fc84ed55c65f4bf20a901edb7ceb73c5f/src/transformers/modeling_utils.py#L3480C9-L3480C46), the batch dim in the generated code becomes a Constant instead of a dynamic dim, which has ended up with this failure:

```
[2023-08-14 13:53:15,380] torch._dynamo.output_graph: [INFO] Step 2: done compiler function inductor
ERROR:common:Backend dynamo failed in warmup()
Traceback (most recent call last):
  File "/home/user/pytorch/benchmarks/dynamo/common.py", line 2226, in warmup
    fn(model, example_inputs)
  File "/home/user/pytorch/torch/_dynamo/eval_frame.py", line 307, in _fn
    return fn(*args, **kwargs)
  File "benchmarks/dynamo/huggingface.py", line 544, in forward_pass
    return mod(**inputs)
  File "/home/user/pytorch/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/user/pytorch/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/user/transformers/src/transformers/models/bert/modeling_bert.py", line 1358, in forward
    outputs = self.bert(
  File "/home/user/pytorch/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/user/pytorch/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/user/transformers/src/transformers/models/bert/modeling_bert.py", line 970, in forward
    self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  File "/home/user/pytorch/torch/_dynamo/eval_frame.py", line 467, in catch_errors
    return callback(frame, cache_size, hooks, frame_state)
  File "/home/user/pytorch/torch/_dynamo/convert_frame.py", line 559, in _convert_frame
    result = inner_convert(frame, cache_size, hooks, frame_state)
  File "/home/user/pytorch/torch/_dynamo/convert_frame.py", line 130, in _fn
    return fn(*args, **kwargs)
  File "/home/user/pytorch/torch/_dynamo/convert_frame.py", line 378, in _convert_frame_assert
    return _compile(
  File "/home/user/pytorch/torch/_dynamo/utils.py", line 194, in time_wrapper
    r = func(*args, **kwargs)
  File "/home/user/pytorch/torch/_dynamo/convert_frame.py", line 506, in _compile
    check_fn = CheckFunctionManager(
  File "/home/user/pytorch/torch/_dynamo/guards.py", line 887, in __init__
    guard.create(local_builder, global_builder)
  File "/home/user/pytorch/torch/_guards.py", line 215, in create
    return self.create_fn(self.source.select(local_builder, global_builder), self)
  File "/home/user/pytorch/torch/_dynamo/guards.py", line 564, in SHAPE_ENV
    guards = output_graph.shape_env.produce_guards(
  File "/home/user/pytorch/torch/fx/experimental/symbolic_shapes.py", line 2809, in produce_guards
    raise ConstraintViolationError(f"Constraints violated!\n{err}")
torch.fx.experimental.symbolic_shapes.ConstraintViolationError: Constraints violated!
  1. Could not validate constraint RelaxedUnspecConstraint(L['input_ids'].size()[0]) as L['input_ids'].size()[0] was inferred to be constant (16).  For more information about why it is constant, run with TORCH_LOGS=dynamic
```

### Minified repro
You could change `BertForMaskedLM` in the below line to other model names to reproduce the corresponding failures.
You'll need to install transformers `v4.31.0` to reproduce the failure.
```bash
python -u benchmarks/dynamo/huggingface.py --dynamic-shapes --dynamic-batch-only --performance --float32 -dcpu --inference -n5 --inductor --no-skip --dashboard --cold-start-latency --freezing --timeout 9000 --only=BertForMaskedLM
```

### Versions

Collecting environment information...
PyTorch version: 2.1.0a0+git236eda4
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.24.3
Libc version: glibc-2.31

Python version: 3.8.13 (default, Oct 21 2022, 23:50:54)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-78-generic-x86_64-with-glibc2.17
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                   52 bits physical, 57 bits virtual
CPU(s):                          128
On-line CPU(s) list:             0-127
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           106
Model name:                      Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
Stepping:                        6
CPU MHz:                         1195.781
CPU max MHz:                     3400.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5200.00
L1d cache:                       3 MiB
L1i cache:                       2 MiB
L2 cache:                        80 MiB
L3 cache:                        96 MiB
NUMA node0 CPU(s):               0-31,64-95
NUMA node1 CPU(s):               32-63,96-127
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
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 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 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 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities

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] intel-extension-for-pytorch==1.13.0+cpu
[pip3] mypy==0.960
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.21.2
[pip3] open-clip-torch==2.20.0
[pip3] pytorch-warmup==0.1.1
[pip3] rotary-embedding-torch==0.2.7
[pip3] torch==2.1.0a0+git0341408
[pip3] torch-fidelity==0.3.0
[pip3] torch_geometric==2.4.0
[pip3] torchaudio==2.0.2
[pip3] torchdata==0.6.1
[pip3] torchmetrics==1.0.3
[pip3] torchmultimodal==0.1.0b0
[pip3] torchtext==0.16.0a0+b5e2a1b
[pip3] torchvision==0.16.0a0+bb3aae7
[pip3] triton==2.0.0
[pip3] vector-quantize-pytorch==1.6.30
[conda] bert-pytorch              0.0.1a4                   dev_0    <develop>
[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] intel-extension-for-pytorch 1.13.0+cpu               pypi_0    pypi
[conda] mkl                       2022.1.0           hc2b9512_224    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
[conda] mkl-include               2022.2.1                 pypi_0    pypi
[conda] mkl-static                2022.2.1                 pypi_0    pypi
[conda] numpy                     1.21.2                   pypi_0    pypi
[conda] open-clip-torch           2.20.0                   pypi_0    pypi
[conda] pytorch-warmup            0.1.1                    pypi_0    pypi
[conda] rotary-embedding-torch    0.2.7                    pypi_0    pypi
[conda] torch                     2.1.0a0+git0341408           dev_0    <develop>
[conda] torch-fidelity            0.3.0                    pypi_0    pypi
[conda] torch-geometric           2.4.0                    pypi_0    pypi
[conda] torchaudio                2.0.2                    pypi_0    pypi
[conda] torchdata                 0.6.1                    pypi_0    pypi
[conda] torchmetrics              1.0.3                    pypi_0    pypi
[conda] torchmultimodal           0.1.0b0                  pypi_0    pypi
[conda] torchtext                 0.16.0a0+b5e2a1b           dev_0    <develop>
[conda] torchvision               0.16.0a0+bb3aae7           dev_0    <develop>
[conda] triton                    2.0.0                    pypi_0    pypi
[conda] vector-quantize-pytorch   1.6.30                   pypi_0    pypi

cc @ezyang @msaroufim @wconstab @bdhirsh @anijain2305 @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @Xia-Weiwen @wenzhe-nrv @jiayisunx @ipiszy @chenyang78 @aakhundov