Repository: pytorch
Issue: RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Reshape node. Name:'/Reshape_5' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/reshape_helper.h:45 onnxruntime::ReshapeHelper::ReshapeHelper(const onnxruntime::TensorShape&, onnxruntime::TensorShapeVector&, bool) input_shape_size == size was false. The input tensor cannot be reshaped to the requested shape. Input shape:{1,32,512}, requested shape:{1,1,8,64}
Labels: module: onnx,triaged

### 🐛 Describe the bug

I am trying to convert a pytorch transformer model to onnx. My model architecture consists of multiple nn.modules, so I am converting each to onnx separately. I am having to use a combination of torch.onnx.export() and torch.onnx.dynamo_export(), because some module conversions do not support dynamo_export yet.

I am able to convert all the modules to onnx. However, when I run an inference session through the decoder module, I get the mentioned error. For reference, here is my Decoder class -

```
class Decoder(nn.Module):

    def __init__(self, features: int, layers: nn.ModuleList) -> None:
        super().__init__()
        self.layers = layers
        self.norm = LayerNormalization(features)

    def forward(self, x, encoder_output, src_mask, tgt_mask):
        for layer in self.layers:
            x = layer(x, encoder_output, src_mask, tgt_mask)
        return self.norm(x)
```

Here is my code for onnx conversion of the module -

```
dummy_decoder_input = torch.randint(low=0, high=60, size =(1, 1, 512), dtype=torch.float)
dummy_encoder_output = torch.randint(low=0, high=60, size =(1, 32, 512), dtype=torch.float)
dummy_src_mask = torch.tensor([[[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0]]]], dtype=torch.int)
dummy_tgt_mask = torch.tensor([[1]], dtype=torch.int)

args = (dummy_decoder_input, dummy_encoder_output, dummy_src_mask, dummy_tgt_mask)
# encoder_output, source_mask, decoder_input, decoder_mask
dynamic_axes = {
    'decoder_input': {0: 'batch_size', 1: 'seq_len', 2: 'embed_dim'},
    'encoder_output': {0: 'batch_size', 1: 'seq_len', 2: 'embed_dim'},
    'src_mask': {3: 'seq_len'},
    'tgt_mask': {0: 'seq_len', 1: 'seq_len'},
    'output': {0: 'batch_size', 1: 'sequence_length'}
}

x, encoder_output, src_mask, tgt_mask
torch.onnx.export(test_scripted_decoder,
                  args=args,
                  f="./onnx/decoder.onnx",
                  input_names=['decoder_input', 'encoder_output', 'src_mask', 'tgt_mask'],
                  output_names=['output'],
                  dynamic_axes=dynamic_axes,
                  verbose=True
                )
```

Here is my inference code in onnx -

```
def run_inference(input_string):
  input_tensor = encode_input(eng_tokenizer, input_string)
  encoder_input = prepare_encoder_input(eng_tokenizer, input_tensor)
  src_mask = prepare_encoder_mask(eng_tokenizer, encoder_input)

  # Run encoder
  src_embed_output = src_embed_layer.run(None, {'l_x_': encoder_input.numpy()})[0]

  src_pos_output = src_pos_layer.run(None, {'l_x_': src_embed_output})[0]

  encoder_output = src_encoder_layer.run(None, {'input_1': src_pos_output, 'input_2': src_mask.numpy()})[0]


  # Run decoder
  tgt_input = torch.tensor([[eng_tokenizer.encode('<')[0]]], dtype=torch.int32)

  while True:
      if tgt_input.size(1) == 32:
          break

      tgt_mask = causal_mask(tgt_input.size(1)).numpy().astype(np.int32)


      tgt_embed_output = tgt_embed_layer.run(None, {'l_x_': tgt_input.numpy().astype(np.int32)})[0]


      tgt_pos_output = tgt_pos_layer.run(None, {'input_1': tgt_embed_output})[0]

# ERROR OCCURS ON THE NEXT LINE
      decoder_output = tgt_decoder_layer.run(None, {'decoder_input': tgt_pos_output, 'encoder_output': encoder_output, 'src_mask': src_mask.numpy(), 'tgt_mask': tgt_mask})[0]

      last_dim = decoder_output[:, -1]

      prob = tgt_projection_layer.run(None, {'l_x_': last_dim})[0]
      next_word = np.argmax(prob, axis=1)[0]

      next_word_tensor = torch.tensor([[next_word]], dtype=torch.int64)
      tgt_input = torch.cat((tgt_input, next_word_tensor), dim=1)

      if next_word == eng_tokenizer.encode('>')[0]:
          break

  output_tokens = tgt_input.squeeze().tolist()
  output_string = eng_tokenizer.decode(output_tokens)
  return output_string

run_inference("hello")
```

I have marked the line which throws the error above. Here is the full error -

```
---------------------------------------------------------------------------
RuntimeException                          Traceback (most recent call last)
[<ipython-input-189-ce3f1a0c8e40>](https://localhost:8080/#) in <cell line: 47>()
     45   return output_string
     46 
---> 47 run_inference("hello")

1 frames
[/usr/local/lib/python3.10/dist-packages/onnxruntime/capi/onnxruntime_inference_collection.py](https://localhost:8080/#) in run(self, output_names, input_feed, run_options)
    218             output_names = [output.name for output in self._outputs_meta]
    219         try:
--> 220             return self._sess.run(output_names, input_feed, run_options)
    221         except C.EPFail as err:
    222             if self._enable_fallback:

RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Reshape node. Name:'/Reshape_5' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/reshape_helper.h:45 onnxruntime::ReshapeHelper::ReshapeHelper(const onnxruntime::TensorShape&, onnxruntime::TensorShapeVector&, bool) input_shape_size == size was false. The input tensor cannot be reshaped to the requested shape. Input shape:{1,32,512}, requested shape:{1,1,8,64}
```

Any help in resolving this issue would be appreciated. Thanks.

### Versions

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: 14.0.0-1ubuntu1.1
CMake version: version 3.27.9
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.1.85+-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.6
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:                        46 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               2
On-line CPU(s) list:                  0,1
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) CPU @ 2.20GHz
CPU family:                           6
Model:                                79
Thread(s) per core:                   2
Core(s) per socket:                   1
Socket(s):                            1
Stepping:                             0
BogoMIPS:                             4399.99
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities
Hypervisor vendor:                    KVM
Virtualization type:                  full
L1d cache:                            32 KiB (1 instance)
L1i cache:                            32 KiB (1 instance)
L2 cache:                             256 KiB (1 instance)
L3 cache:                             55 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0,1
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Mitigation; PTE Inversion
Vulnerability Mds:                    Vulnerable; SMT Host state unknown
Vulnerability Meltdown:               Vulnerable
Vulnerability Mmio stale data:        Vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Vulnerable
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Vulnerable
Vulnerability Spectre v1:             Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:             Vulnerable; IBPB: disabled; STIBP: disabled; PBRSB-eIBRS: Not affected; BHI: Vulnerable (Syscall hardening enabled)
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Vulnerable

Versions of relevant libraries:
[pip3] numpy==1.25.2
[pip3] onnx==1.16.1
[pip3] onnxruntime==1.18.1
[pip3] onnxscript==0.1.0.dev20240711
[pip3] torch==2.3.0+cu121
[pip3] torchaudio==2.3.0+cu121
[pip3] torchsummary==1.5.1
[pip3] torchtext==0.18.0
[pip3] torchvision==0.18.0+cu121
[pip3] triton==2.3.0
[conda] Could not collect