Repository: pytorch
Issue: TorchDynamo ONNX Export does not work as expected with masking (ScatterElements)
Labels: module: onnx,triaged

### 🐛 Describe the bug

I try to convert a custom PyTorch model to ONNX. The conversion works, however when starting the onnxruntime session I get an error pointing to the [ScatterElements](https://onnx.ai/onnx/operators/onnx__ScatterElements.html) node in a masking process. The problem occurs when I assign 0 to x[mask].

I would greatly appreciate help!

```
import torch
import onnxruntime as rt
import onnx
from torch import nn    

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, x):
        mask = torch.ones((1, 3, 3), dtype=bool)
        x[mask] = 0
        return x

if __name__ =="__main__":
    model = Model()
    input = torch.randn((1, 3, 3))
    onnx_program = torch.onnx.dynamo_export(model, input)
    onnx.save(onnx_program.model_proto, "test.onnx")
    session = rt.InferenceSession("test.onnx")
    try:
        result = session.run(None, {'l_x_': input.cpu().numpy()})
        print(result)
    except Exception as e:
        print(f"ONNX Runtime error: {e}")
```

The error message is the following:

```
usr/local/lib/python3.10/dist-packages/torch/onnx/_internal/exporter.py:136: UserWarning: torch.onnx.dynamo_export only implements opset version 18 for now. If you need to use a different opset version, please register them with register_custom_op.
  warnings.warn(
2024-05-22 07:01:08.758310334 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_cond_6'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758515023 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_tmp_2'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758522949 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_if_then_branch__inlfunc_aten_index_put_bool_tmp_7'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758527238 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_tmp_5'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758533292 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_tmp_4'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758546412 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_accumulate_as_bool'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758553391 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_tmp_3'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.758556793 [W:onnxruntime:, graph.cc:3593 CleanUnusedInitializersAndNodeArgs] Removing initializer '_inlfunc_aten_index_put_bool_accumulate'. It is not used by any node and should be removed from the model.
2024-05-22 07:01:08.763088943 [E:onnxruntime:, sequential_executor.cc:514 ExecuteKernel] Non-zero status code returned while running ScatterElements node. Name:'_if_else_branch_ScatterElements' Status Message: Indices and updates must have the same rank
2024-05-22 07:01:08.763103538 [E:onnxruntime:, sequential_executor.cc:514 ExecuteKernel] Non-zero status code returned while running If node. Name:'_inlfunc_aten_index_put_bool_n7' Status Message: Non-zero status code returned while running ScatterElements node. Name:'_if_else_branch_ScatterElements' Status Message: Indices and updates must have the same rank
ONNX Runtime error: [ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Non-zero status code returned while running If node. Name:'_inlfunc_aten_index_put_bool_n7' Status Message: Non-zero status code returned while running ScatterElements node. Name:'_if_else_branch_ScatterElements' Status Message: Indices and updates must have the same rank
```

### Versions

Collecting environment information...
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-35-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA T500
Nvidia driver version: 535.171.04
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.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
Address sizes:                      39 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             8
On-line CPU(s) list:                0-7
Vendor ID:                          GenuineIntel
Model name:                         11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
CPU family:                         6
Model:                              140
Thread(s) per core:                 2
Core(s) per socket:                 4
Socket(s):                          1
Stepping:                           1
CPU max MHz:                        4700.0000
CPU min MHz:                        400.0000
BogoMIPS:                           5606.40
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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 invpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          192 KiB (4 instances)
L1i cache:                          128 KiB (4 instances)
L2 cache:                           5 MiB (4 instances)
L3 cache:                           12 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-7
Vulnerability Gather data sampling: Mitigation; Microcode
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 rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] ament-flake8==0.12.10
[pip3] flake8==4.0.1
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] onnx==1.16.0
[pip3] onnx-graphsurgeon==0.5.2
[pip3] onnxruntime==1.17.3
[pip3] onnxruntime-gpu==1.17.1
[pip3] onnxscript==0.1.0.dev20240515
[pip3] onnxsim==0.4.36
[pip3] torch==2.3.0+cu121
[pip3] torch-tb-profiler==0.4.3
[pip3] torchinfo==1.8.0
[pip3] torchtyping==0.1.4
[pip3] torchvision==0.18.0+cu121
[pip3] triton==2.3.0
[conda] Could not collect