Export LayoutLMv2 to TorchScript
## Environment info
<!-- You can run the command `transformers-cli env` and copy-and-paste its output below.
     Don't forget to fill out the missing fields in that output! -->

- `transformers` version: 4.15.0
- Platform: MacOS
- Python version: 3.8
- PyTorch version (GPU?): 1.10 CPU
- Tensorflow version (GPU?): N/A
- Using GPU in script?: No
- Using distributed or parallel set-up in script?: No

### Who can help
@LysandreJik

<!-- Your issue will be replied to more quickly if you can figure out the right person to tag with @
 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- ALBERT, BERT, XLM, DeBERTa, DeBERTa-v2, ELECTRA, MobileBert, SqueezeBert: @LysandreJik
- T5, BART, Marian, Pegasus, EncoderDecoder: @patrickvonplaten
- Blenderbot, MBART: @patil-suraj
- Longformer, Reformer, TransfoXL, XLNet, FNet, BigBird: @patrickvonplaten
- FSMT: @stas00
- Funnel: @sgugger
- GPT-2, GPT: @patrickvonplaten, @LysandreJik
- RAG, DPR: @patrickvonplaten, @lhoestq
- TensorFlow: @Rocketknight1
- JAX/Flax: @patil-suraj
- TAPAS, LayoutLM, LayoutLMv2, LUKE, ViT, BEiT, DEiT, DETR, CANINE: @NielsRogge
- GPT-Neo, GPT-J, CLIP: @patil-suraj
- Wav2Vec2, HuBERT, SpeechEncoderDecoder, UniSpeech, UniSpeechSAT, SEW, SEW-D, Speech2Text: @patrickvonplaten, @anton-l

If the model isn't in the list, ping @LysandreJik who will redirect you to the correct contributor.



Examples:

- maintained examples (not research project or legacy): @sgugger, @patil-suraj

For research projetcs, please ping the contributor directly. For example, on the following projects:

- research_projects/bert-loses-patience: @JetRunner
- research_projects/distillation: @VictorSanh

 -->

## Information

Model I am using LayoutLMv2:

The problem arises when using:
* [ ] the official example scripts: (give details below)
* [x] my own modified scripts: (give details below)

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:

```
model_dir = "microsoft/layoutlmv2-base-uncased"
model = AutoModelForTokenClassification.from_pretrained(model_dir)
processor = LayoutLMv2Processor.from_pretrained(model_dir)
image = Image.open('./image.jpg').convert("RGB")
encoded_input = processor(
    image, return_tensors="pt"
)

traced_model = torch.jit.trace(func=model,
                                   strict=False,  
                                   example_inputs=[encoded_input['input_ids'], encoded_input['bbox'],
                                                   encoded_input['image'], encoded_input['attention_mask'],
                                                   encoded_input['token_type_ids']])
```
Results in:
<img width="998" alt="Screenshot 2022-01-20 at 15 52 02" src="https://user-images.githubusercontent.com/22592860/150364030-c79e4a1e-b694-48e6-9ed7-175eb516a6ac.png">


```
Traceback (most recent call last):
  File "/some_path/python3.8/site-packages/torch/jit/_trace.py", line 958, in trace_module
    module._c._create_method_from_trace(
  File "/some_path/python3.8/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "/some_path/python3.8/site-packages/torch/nn/modules/module.py", line 1090, in _slow_forward
    result = self.forward(*input, **kwargs)
  File "/some_path/python3.8/site-packages/transformers/models/layoutlmv2/modeling_layoutlmv2.py", line 1179, in forward
    outputs = self.layoutlmv2(
  File "/some_path/python3.8/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "/some_path/python3.8/site-packages/torch/nn/modules/module.py", line 1090, in _slow_forward
    result = self.forward(*input, **kwargs)
  File "/some_path/python3.8/site-packages/transformers/models/layoutlmv2/modeling_layoutlmv2.py", line 888, in forward
    text_layout_emb = self._calc_text_embeddings(
  File "/some_path/python3.8/site-packages/transformers/models/layoutlmv2/modeling_layoutlmv2.py", line 753, in _calc_text_embeddings
    embeddings = inputs_embeds + position_embeddings + spatial_position_embeddings + token_type_embeddings
RuntimeError: The size of tensor a (241) must match the size of tensor b (290) at non-singleton dimension 1
```


<!-- If you have code snippets, error messages, stack traces please provide them here as well.
     Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
     Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.-->

## Expected behavior

<!-- A clear and concise description of what you would expect to happen. -->
1. the torch.jit.trace conversion should not crash

cc @NielsRogge <|||||>I was looking into a bit more and I found out that the reason why the torchscript conversion is crashing are following:
1) torch.jit._trace.py ->line 958 module._c._create_method_from_trace is unsqueezing the inputs thus instead of passing original e.g. attention_mask input as {Tensor:(1,241)} it is passing {Tensor:(tensor(1),tensor(241)}
2) modeling_layoutlmv2.forward (line 804) is expecting input in form of {Tensor:(1,input_size)}. It would be great to add some check that would warn me that the input that I am passing in has invalid shape as `The size of tensor a (241) must match the size of tensor b (290)` is rather hard to track where exactly is the mistake.<|||||>Hi,

Currently, LayoutLMv2 is not supported out-of-the-box to work with TorchScript (see #14457). However, there was an effort to make it work (see #14462). Feel free to work further on this to make it available.<|||||>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/master/CONTRIBUTING.md) are likely to be ignored.