don't initialize the output embeddings if we're going to tie them to input embeddings
Author: tom-p-reichel
Pull request: yes


# 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 -->

This small change marks the output embeddings for a model as initialized if we will be tying them to the input embeddings. Without this change, the output embeddings are usually randomly initialized every time affected models (models that tie the output embeddings to input embeddings and do not otherwise initialize the output embeddings) are loaded. This seems to be responsible for *multiple second* startup delays in downstream tools, e.g. insanely-fast-whisper, as every single time the whisper model is loaded a very massive matrix is unnecessarily filled with uniformly random numbers before it is replaced with another matrix.

Before and after applying this patch, downstream tool insanely-fast-whisper transcribed a short audio file in 18 and 13 seconds respectively for a 5 second improvement. The patch does not seem to change the behavior of the tool-- a test transcription of an hour of audio remains unchanged before and after the patch.

I suspect other applications using models that tie their input/output embeddings together will experience a small speedup in loading from this patch.

I ran a portion of the transformers testing locally, which passed, but we'll see how the full test suite fares soon enough.

## 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?
- [ ] 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.
- [ ] 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).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed.

<!-- 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:

- text models: @ArthurZucker and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Hi @tom-p-reichel - thanks for opening this PR! 

Very nice if there's such a big speedup 🔥  cc @sanchit-gandhi 

Could you share some snippets on how this was tested - speed and outputs? 

@amyeroberts Sure. Here's a minimal example:
`python -m timeit -s "from transformers import pipeline; import torch" "pipeline('automatic-speech-recognition',model='openai/whisper-large-v3', torch_dtype=torch.float16)"`

Before patch (origin/main):
`1 loop, best of 5: 6.91 sec per loop`

After patch:
`1 loop, best of 5: 1.72 sec per loop`

Note: If we're not using `dtype=torch.float16` as insanely-fast-whisper does then both versions run much faster and the patch only gives a marginal improvement.  It seems like randomly initializing something in float16 is really expensive!

As a sanity check that nothing terribly bad has happened to the weights as a result of this patch, we can also download some public domain audio and test that the downstream tool works as intended:

```
wget https://www.archive.org/download/metamorphosis_librivox/metamorphosis_librivox_64kb_mp3.zip
unzip metamorphosis_librivox_64kb_mp3.zip
insanely-fast-whisper --file-name metamorphosis_1_kafka_64kb.mp3
```
The resultant `output.json` pre and post patch are identical for the 49 minutes of audio transcribed.

EDIT: Although the tests for this PR are failing, the only test that failed appears to be a documentation check for mistral, which was not touched in this PR.


Rebase took care of the one failing documentation test. Anything else that needs to be done for this PR?

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_28192). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Hi, sorry for the delay, I was doing graduate student things. Here is a rebase onto the current main and a new test.

@ArthurZucker is this what you intended for the test case? There are already test cases that ensure that the model is unchanged while loading and saving, even during fast_init, so I only test the new behavior I added -- which is that the output embedding is never initialized if it's tied.

The commit is broken into two parts, the first which adds the test and the second which implements the fix. You can check out the commit where the test is added (`e1b99fde912d90b50f8d70145bc6d5b75058f6a0`) and run something to the effect of `python -m pytest tests/models/whisper/test_modeling_whisper.py -k "test_fast_init_tied_embeddings"` to see that the test fails on the current transformers `main` branch. Checking out the second commit in this PR causes the test to pass.

@ArthurZucker Good to hear it, rebased. 

Thanks for the PR! 

FYI @pacman100 if we have any deepspeed issues 🤗 

FYI I ran into an issue with this for the ElectraModel with this [test](https://github.com/huggingface/transformers/blob/d628664688b05cabdd69f4e7e295bc4aee0a8d31/tests/test_modeling_common.py#L434). For some reason, the failure only showed up when I modified the source for ElectraModel for an unrelated change. 

The issue appears to be that the `bias` term in the `output_embeddings` is not tied in [`_tie_or_clone_weights()`](https://github.com/huggingface/transformers/blob/d628664688b05cabdd69f4e7e295bc4aee0a8d31/src/transformers/modeling_utils.py#L1712). The test ended up failing because initialization was skipped for the `bias` as well.

I added this [commit](https://github.com/huggingface/transformers/pull/28802/commits/9fa20df3faba1a72fb21cb7eca55e4065836a5f3) to get the test to pass. Let me know if you have any concerns. AFAIT, the whisper model doesn't have `bias` in their embeddings, and so my fix shouldn't affect the gains from this change. 

@hackyon Good catch! Yes, that is an oversight. Curious about needing to edit ElectraModel to see the failure and the passing tests in this PR.