ONNX exported BART model with seq2seq-lm-with-past feature produces error on the initial run.
Author: eublefar
Pull request: no

## Environment info

- `transformers` version: 4.17.0
- Platform: Windows-10-10.0.18362-SP0
- Python version: 3.7.13
- PyTorch version (GPU?): 1.11.0 (True)
- Tensorflow version (GPU?): not installed (NA)
- Flax version (CPU?/GPU?/TPU?): not installed (NA)
- Jax version: not installed
- JaxLib version: not installed
- Using GPU in script?: No
- Using distributed or parallel set-up in script?: No

### Who can help

@mfuntowicz 
@lewtun 
@patil-suraj 

## Information

Model I am using (Bert, XLNet ...): BART (facebook/bart-base)

The problem arises when using:
* [ ] the official example scripts: (give details below)
* [X] my own modified scripts: (give details below)

I am trying to use BART model extracted to ONNX with feature seq2seq-lm-with-past.

The tasks I am working on is:
* [ ] an official GLUE/SQUaD task: (give the name)
* [X] my own task or dataset: (give details below)



## To reproduce

Steps to reproduce the behavior:

1. Extract model with `python -m transformers.onnx --model=facebook/bart-base --feature seq2seq-lm-with-past exported2 --opset 12 --atol 0.0001`
2. Run script below

```python
import onnxruntime as rt
import numpy as np


sess_options = rt.SessionOptions()
sess_options.graph_optimization_level = (
    rt.GraphOptimizationLevel.ORT_DISABLE_ALL
)
model = rt.InferenceSession("exported2\model.onnx", sess_options=sess_options,)

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("npc-engine/bart-base-mse-light")

DTYPE_MAP = {
    'tensor(int64)': np.int64,
    'tensor(float)': np.float32,
    'tensor(double)': np.float64,
    'tensor(int32)': np.int32,
}

def create_starter_inputs(prompt: str = "", is_encdec: bool = False):
    """Create starter inputs for the model.

    Args:
        prompt: Prompt to start generation from.

    Returns:
        Dict of inputs to the model
    """
    model_inputs = model.get_inputs()

    tokens = tokenizer.encode(prompt)
    inputs = {}
    
    dtypes = {i.name: DTYPE_MAP[i.type] for i in model_inputs}

    if is_encdec:
        prompt_start = tokens[-1]
        inputs['input_ids'] = np.asarray(tokens[:-1], dtype=dtypes['input_ids']).reshape([1, -1])
        inputs['decoder_input_ids'] = np.asarray([prompt_start, prompt_start], dtype=dtypes['decoder_input_ids']).reshape([1, 2])
        inputs['attention_mask'] = np.ones_like(inputs['input_ids'], dtype=dtypes['attention_mask'])
        inputs['decoder_attention_mask'] = np.ones_like(inputs['decoder_input_ids'], dtype=dtypes['decoder_attention_mask'])
        inputs['decoder_attention_mask'][0][-1] = 0
    else:
        inputs['input_ids'] = np.asarray(tokens, dtype=dtypes['input_ids']).reshape([1, -1])
        inputs['attention_mask'] = np.ones_like(inputs['input_ids'], dtype=dtypes['attention_mask'])


    shape_dict = {
        "batch": 1,
        "past_encoder_sequence": 0,
        "past_decoder_sequence": 0,
        "past_sequence + sequence": 0,
    }

    for i in model_inputs:
        if "past_key_values" in i.name:
            shape_tuple = [shape_dict.get(dim, dim) for dim in i.shape]
            inputs[i.name] = np.empty(shape_tuple, dtype=dtypes[i.name])
    return inputs

inp = create_starter_inputs("Hello", True)

model.run(None, inp)
```

This produces an error
```
RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Reshape node. Name:'Reshape_945' Status Message: D:\a\_work\1\s\onnxruntime\core\providers\cpu\tensor\reshape_helper.h:26 onnxruntime::ReshapeHelper::ReshapeHelper i < input_shape.NumDimensions() was false. The dimension with value zero exceeds the dimension size of the input tensor.
```

GPT-2 exported model with causal-lm-with-past feature works with the same function (with is_encdec = False).

## Expected behavior

It should be producing output from ONNX model.
Also model expects decoder_input_ids of shape (batch, 2) but should be (batch, 1).



Comments:
Fixing model `decoder_input_ids` expected shape from (batch, 2) to (batch, 1) doesn't help with this error.

Changing the shape of PKVs and masks changes error.
Here is the snippet to modify input shapes:
```python
BATCH = 1
PAST_SEQ_LEN = 2

model_inputs = model.get_inputs()
dtypes = {i.name: DTYPE_MAP[i.type] for i in model_inputs}
inp['attention_mask'] = np.ones([BATCH , PAST_SEQ_LEN + 4], dtype=dtypes['attention_mask'])
inp['decoder_attention_mask'] = np.ones([BATCH, PAST_SEQ_LEN + 1], dtype=dtypes['decoder_attention_mask'])

shape_dict = {
    "batch": BATCH ,
    "past_encoder_sequence": PAST_SEQ_LEN ,
    "past_decoder_sequence": PAST_SEQ_LEN ,
    "past_sequence + sequence": 0,
}
for i in model_inputs:
    if "past_key_values" in i.name:
        shape_tuple = [shape_dict.get(dim, dim) for dim in i.shape]
        inp[i.name] = np.empty(shape_tuple, dtype=dtypes[i.name])
```
Run it after input dict creation and before model execution

1.
```python
BATCH = 1
PAST_SEQ_LEN = 2
```
produces error 
```
RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Add node. Name:'Add_1766' Status Message: D:\a\_work\1\s\onnxruntime\core/providers/cpu/math/element_wise_ops.h:503 onnxruntime::BroadcastIterator::Init axis == 1 || axis == largest was false. Attempting to broadcast an axis by a dimension other than 1. 2 by 6
```

2.
```python
BATCH = 1
PAST_SEQ_LEN = 1
```
produces error 
```
RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Reshape node. Name:'Reshape_1776' Status Message: D:\a\_work\1\s\onnxruntime\core\providers\cpu\tensor\reshape_helper.h:41 onnxruntime::ReshapeHelper::ReshapeHelper gsl::narrow_cast<int64_t>(input_shape.Size()) == size was false. The input tensor cannot be reshaped to the requested shape. Input shape:{1,16,1,5}, requested shape:{16,1,1}
```



This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.