add task_type_id to BERT to support ERNIE-2.0 and ERNIE-3.0 models
# 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 -->

[ERNIE2.0](https://arxiv.org/abs/1907.12412) ![citation](https://img.shields.io/badge/dynamic/json?label=citation&query=citationCount&url=https%3A%2F%2Fapi.semanticscholar.org%2Fgraph%2Fv1%2Fpaper%2F80f9f109d1564cb8f82aa440a5f6f3fbe220c9ef%3Ffields%3DcitationCount) and [ERNIE3.0](https://arxiv.org/abs/2107.02137) ![citation](https://img.shields.io/badge/dynamic/json?label=citation&query=citationCount&url=https%3A%2F%2Fapi.semanticscholar.org%2Fgraph%2Fv1%2Fpaper%2F319b84be7a843250bc81d7086f79a4126d550277%3Ffields%3DcitationCount)  are a series of powerful models based on BERT, especially in Chinese tasks. These models introduce `task_type_embeddings` in the embedding layer, so this PR is to support this feature.

the config of ERNIE2.0 / ERNIE3.0 models have the following two params:
```json
...
"task_type_vocab_size": 3,
"use_task_id": true
...
```
the released ERNIE2.0 / ERNIE3.0 models have the weight of `bert.embeddings.task_type_embeddings.weight`

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/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.  https://github.com/huggingface/transformers/issues?q=is%3Aissue+ernie
- [x] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [x] Did you write any new necessary tests?
I write a [script](https://github.com/nghuyong/ERNIE-Pytorch/blob/master/convert_ernie3.0.py) to convert the official released [ERNIE3.0 model (paddlepaddle version)](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/model_zoo/ernie-3.0). And I have checked that the model results before and after transformation are consistent (with `task_type_embedding` added)

```Python
import paddle
import torch
from paddlenlp.transformers import ErnieForMaskedLM, ErnieTokenizer
# this PR version
from transformers import BertTokenizer, BertForMaskedLM

tokenizer = BertTokenizer.from_pretrained('nghuyong/ernie-3.0-base-zh')
model = BertForMaskedLM.from_pretrained('nghuyong/ernie-3.0-base-zh')
input_ids = torch.tensor([tokenizer.encode(text="[MASK][MASK][MASK]是中国神魔小说的经典之作，与《三国演义》《水浒传》《红楼梦》并称为中国古典四大名著。",
                                           add_special_tokens=True)])
model.eval()
with torch.no_grad():
    predictions = model(input_ids)[0][0]
predicted_index = [torch.argmax(predictions[i]).item() for i in range(predictions.shape[0])]
predicted_token = [tokenizer._convert_id_to_token(predicted_index[i]) for i in
                   range(1, (predictions.shape[0] - 1))]
print('huggingface result')
print('predict result:\t', predicted_token)
print('[CLS] logit:\t', predictions[0].numpy())
tokenizer = ErnieTokenizer.from_pretrained("ernie-3.0-base-zh")
model = ErnieForMaskedLM.from_pretrained("ernie-3.0-base-zh")
inputs = tokenizer("[MASK][MASK][MASK]是中国神魔小说的经典之作，与《三国演义》《水浒传》《红楼梦》并称为中国古典四大名著。")
inputs = {k: paddle.to_tensor([v]) for (k, v) in inputs.items()}
model.eval()
with paddle.no_grad():
    predictions = model(**inputs)[0]
predicted_index = [paddle.argmax(predictions[i]).item() for i in range(predictions.shape[0])]
predicted_token = [tokenizer._convert_id_to_token(predicted_index[i]) for i in
                   range(1, (predictions.shape[0] - 1))]
print('paddle result')
print('predict result:\t', predicted_token)
print('[CLS] logit:\t', predictions[0].numpy())

“”“
huggingface result
predict result:	 ['西', '游', '记', '是', '中', '国', '神', '魔', '小', '说', '的', '经', '典', '之', '作', '，', '与', '《', '三', '国', '演', '义', '》', '《', '水', '浒', '传', '》', '《', '红', '楼', '梦', '》', '并', '称', '为', '中', '国', '古', '典', '四', '大', '名', '著', '。']
[CLS] logit:	 [-20.574057  -29.192085  -15.638802  ...  -1.9127564  -1.4329851  -1.8172828]

paddle result
predict result:	 ['西', '游', '记', '是', '中', '国', '神', '魔', '小', '说', '的', '经', '典', '之', '作', '，', '与', '《', '三', '国', '演', '义', '》', '《', '水', '浒', '传', '》', '《', '红', '楼', '梦', '》', '并', '称', '为', '中', '国', '古', '典', '四', '大', '名', '著', '。']
[CLS] logit:	 [-20.573637  -29.193172  -15.639115  ...  -1.9127647  -1.4330447  -1.816982 ]
”“”
```

## Who can review?

@LysandreJik

<!-- 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

 -->

_The documentation is not available anymore as the PR was closed or merged._<|||||>Hey @nghuyong, thanks for your PR! 

In this situation, we'd rather have a new model class "Ernie" rather than modifying the "Bert" model class. This will result in a larger PR, but it should be very little additional work for you.

I encourage you to follow the following guide: https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model#add-new-model-like-command

It seems like it would be as simple as using the scfript to add a new model like BERT, but with the ERNIE name; then applying the changes above.

@ydshieh, would you be down to help @nghuyong if they run into any problem? 

Thanks a lot!<|||||>Thanks for your advice. I will try to do this work. <|||||>Agree with @LysandreJik to have a new model file for this. And it should be fairly straightforward.

Glad to know you already have the checkpoints available! Let me me if you need any help, @nghuyong for the PR.
Looking forward to review it! Thanks, @nghuyong !

<|||||>@ydshieh @LysandreJik  I have updated this PR and add Ernie model.
Please help to review it, if you have any questions, you can AT me, thanks!<|||||>Wonderful, thank you @nghuyong!<|||||>Hi @nghuyong, Great job! I will review the PR. Currently, the failing tests are caused by 

```bash
E   AttributeError: module transformers.models.ernie has no attribute BasicTokenizer
```
which is from your change in
```
src/transformers/__init__.py
```

I will discuss my colleagues to see how should we do for the tokenizers.<|||||>@ydshieh  So,  is there anything that needs to be updated now?<|||||>Hi @nghuyong Thanks a lot :-). I will take a full review this week.

The current failing tests (most of them) could be fixed by updating your branch. You can do it as
```python
git checkout main
git pull upstream main
git checkout [YOUR-WORKING-BRANCH]
git rebase main
git push --force-with-lease
```

Before doing so, it would be a good idea to keep a backup of current branch in case of the commit history being messed up.
```python
git checkout add_task_type_id
git checkout -b add_task_type_id_backup
```

Once the PR branch is updated, you can also try to fix the style/quality issues by running
```bash
make style
make quality
```

You can check the CI results in 
```bash
ci/circleci: check_code_quality
ci/circleci: check_repository_consistency
```
for the details and suggestions.


Let me know if you encounter any difficulty.<|||||>Thanks, @ydshieh my branch has been synced with master now<|||||>@nghuyong 
你好，你的ernie的分支是已经合并到mater了吗——意思是安装最新的transformers库，就可以直接使用ernie3和你提供的ernie3的中文权重吧；如不需要通过之前重装transformers的方式：
pip install git+https://github.com/nghuyong/transformers@add_task_type_id<|||||>@HUSTHY, still not, and  `add_task_type_id` has been changed, so, you cannot load ernie3 now.
<|||||>已收到！谢谢！                          ——黄洋<|||||>@nghuyong  好吧 我还以为能用了呢  那你实现的这个分支的代码是没有问题的吧。。。 我直接把代码放在本地应该OK的<|||||>@nghuyong When you add argument `task_type_ids` to the other model classes, you will also need to remove some `# copied from`, for example this part

```
# Copied from transformers.models.bert.modeling_bert.BertModel with BERT->ERNIE,Bert->Ernie
class ErnieModel(ErniePreTrainedModel):
```

You can instead do the following (and same for other methods), although it's more tedious
```
    # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with BERT->ERNIE,Bert->Ernie
    def __init__(self, config, add_pooling_layer=True):
```<|||||>@ydshieh Thanks for your review!! I have updated following your advice.<|||||>Thank you, @nghuyong. Here are a few remaining step from my side

- First, address the above 2 review comments.

- Then
```bash
make style
```
it will fix
```
transformers\src\transformers\__init__.py
transformers\src\transformers\models\ernie\__init__.py
```

- Finally
```bash
pip install -U huggingface_hub
make fix-copies
```
to fix some README files.

Then we can have the core maintainers to have a final look 🚀 <|||||>hi, @ydshieh , I run `make style`, It has changed a lot files
<img width="709" alt="image" src="https://user-images.githubusercontent.com/16462374/188933636-991d9eea-3000-4629-9905-592753a181db.png">
and actually the following two files don't change after I run `make style`
```
transformers\src\transformers\__init__.py
transformers\src\transformers\models\ernie\__init__.py
```<|||||>For the style, could you try `pip install -U hf-doc-builder` before `make style`<|||||>If there are still issues, I can make the change and push to this PR directly, if you are OK with this<|||||>Hi @ydshieh , I'd like to describe the problems I encountered in the development environment
First,  I create a new conda env:
```
conda create -n hf python=3.9
```
and run `$ pip install -e ".[dev]"` get this error
```
ERROR: Could not find a version that satisfies the requirement tensorflow<2.10,>=2.3; extra == "dev" (from transformers[dev]) (from versions: none)
ERROR: No matching distribution found for tensorflow<2.10,>=2.3; extra == "dev"
```
Then I install `tensorflow` by conda first
```
conda install tensorflow
brew install mecab
pip install -e ".[dev]"
```
but still get a error
```
ERROR: Could not find a version that satisfies the requirement tensorflow-text; extra == "dev" (from transformers[dev]) (from versions: none)
ERROR: No matching distribution found for tensorflow-text; extra == "dev"
```
I found `tensorflow-text` is not support Apple M1 Pro now, so I comment the `tensorflow-text` in `setup.py` and then run 
```
pip install -e ".[dev]"
```
finally, it installed

---------

Then, in this new env, I run:
```
pip install -U hf-doc-builder
make style
```
it works !<|||||>Glad it works for you. It's probably not working well TF + Mac (not very sure, I rarely use this combination).
I think you haven't run this yet
```
pip install -U huggingface_hub
make fix-copies
```
right? It's necessary to pass the `check_repository_consistency` CI. Let me know if I can help on this.<|||||>I run and push a new commit now<|||||>Thanks a lot. I will take care of the remaining issue in the CI tomorrow. Somehow strange here.<|||||>@ydshieh  Because I use `ERNIE` not `Ernie` in Readme. so the ci get failed<|||||>The solution should be to change this line
https://github.com/huggingface/transformers/blob/ae3132d17a787ffdb1bc6097b06330fb249ae779/src/transformers/models/auto/configuration_auto.py#L319
to
`("ernie", "ERNIE"),` 

`ERNIE` is the good name to use instead of `Ernie`. 

Also, `"tensorflow-text": "tensorflow-text",` should be added back (I know your env. have issue with it, but it shouldn't be removed when push to the remote).

Hopefully everything will be good now with these :-) <|||||>@ydshieh  OK, thanks!!
of course, I do not submit the change to `setup.py`.<|||||>You can ignore the test failure in `ci/circleci: run_tests_hub`.<|||||>@ydshieh  OK,   `run_tests_hub` could be ignored, may be the ci has no problems now.<|||||>Hi @nghuyong I push [a commit](https://github.com/huggingface/transformers/pull/18686/commits/1514ca636152b2a5d7062349089838d7cac7f37b) which adds several `# copied from ...` <|||||>@ydshieh  OK, thanks a lot<|||||>@sgugger This is model is just BERT, but with a new argument `task_type_ids` which is used to create a new embedding to be summed. Time for you to have a final review 🙏 

<|||||>Thanks again for your contribution! @ydshieh can't merge until you change your "Request changes" to an approval.<|||||>Thank you @nghuyong! I pushed a [final commit](https://github.com/huggingface/transformers/pull/18686/commits/685728232335792f1746f2a5772e60545a545810) to remove the remaining `ErnieLMHeadModel` in a log message.

@sgugger I approved :-) <|||||>failed test is irrelevant to this PR.