Fixes torch jit tracing for LayoutLMv2 model.
Author: mikkeldenker
Pull request: yes

Pytorch seems to reuse memory for input_shape which caused a mismatch in shapes later in the forward pass.

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes #14457


## Before submitting
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/master/CONTRIBUTING.md#start-contributing-pull-requests),
      Pull Request section?
- [x] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [(x)] Did you write any new necessary tests?        <- made some changes to the tests.


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@NielsRogge 
<!-- Your PR 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: @LysandreJik
- blenderbot, bart, marian, pegasus, encoderdecoder,  t5: @patrickvonplaten, @patil-suraj
- longformer, reformer, transfoxl, xlnet: @patrickvonplaten
- fsmt: @stas00
- funnel: @sgugger
- gpt2: @patrickvonplaten, @LysandreJik
- rag: @patrickvonplaten, @lhoestq
- tensorflow: @LysandreJik

Library:

- benchmarks: @patrickvonplaten
- deepspeed: @stas00
- ray/raytune: @richardliaw, @amogkam
- text generation: @patrickvonplaten
- tokenizers: @n1t0, @LysandreJik
- trainer: @sgugger
- pipelines: @LysandreJik

Documentation: @sgugger

HF projects:

- datasets: [different repo](https://github.com/huggingface/datasets)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Examples:

- maintained examples (not research project or legacy): @sgugger, @patil-suraj
- research_projects/bert-loses-patience: @JetRunner
- research_projects/distillation: @VictorSanh

 -->


Comments:
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.

@NielsRogge any idea why this never got merged?

Is the only way to jit.trace layoutlmv2 or a finetuned layoutlmv2 to install transformers in editable mode and add this PR?

For others that find this, I was able to get jit.trace to work on my finetuned layoutlmv2 model:

1. I forked transformers (at v4.17.0 specifically because its required by Sagemaker)
2. I copied the code changes from this PR over
3. I created a public repo where this modified version could be built (git+https://github.com/piercelamb/transformers_fork.git@layoutlmv2_torchscript#egg=transformers)
4. I re-used the encoded dataset I created for training to get a single instance of data for tracing:

```python
cpu_model = best_model.cpu()
cpu_model.eval()

dataset = load_from_disk(encoded_data_path)
train_data = dataset['train']
train_data.set_format(type="torch")
sample_instance = train_data[0]
for key, value in sample_instance.items():
    if key != 'labels':
        sample_instance[key] = value.unsqueeze(0)

traced_cpu = torch.jit.trace(
    func=cpu_model,
    example_inputs=[
        sample_instance['input_ids'].cpu(),
        sample_instance['bbox'].cpu(),
        sample_instance['image'].cpu(),
        sample_instance['attention_mask'].cpu(),
        sample_instance['token_type_ids'].cpu(),
    ],
    check_trace=False # when traced model is checked, an error is produced due to name mangling
)
```

Note the `.unsqueeze(0)` line which appropriately appends a dimension of 1 on each input which is the batch_size expected for a single instance by LayoutLMv2



Hi,

Not sure why this PR was closed. Let's merge in case this works as intended. For some reason I can't reopen the PR, referring this to @LysandreJik 

Indeed, that's on me! I can't reopen the PR either. Feel free to open a PR with the same changes and credit @mikkeldenker as a co-author.

Please ping me on it and we'll have it merged. Thanks!

Pinging @mikkeldenker, can open a PR in case we don't have a response