Fix model code to accurately convert fairseq wav2vec2 model
Author: upskyy
Pull request: yes
Labels: name: Audio

name: run-slow

# 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 #28174 

## Reasons and benefits:
- fairseq model weight can be converted correctly.

## Current state:
- fairseq uses nn.Linear only when the dimension of convolution subsampling and the dimension of the encoder block are different. So, if it is the same, nn.Linear is not used.
- But the huggingface implementation unconditionally uses nn.Linear, so when converting, unused weight doesn't appears, but in reality, a random weight nn.Linear is added.

- fairseq uses the layer_norm position dynamically using the layer_norm_first argument.
- However, the implementation of huggingface is different from fairseq because the layer norm position is fixed. Fixed so that this can be controlled as an option.

## Related code

**No. 1**
 **fairseq**
- [facebookresearch/fairseq@main/fairseq/models/wav2vec/wav2vec2.py#L324-L328](https://github.com/facebookresearch/fairseq/blob/main/fairseq/models/wav2vec/wav2vec2.py?rgh-link-date=2023-12-21T02%3A52%3A07Z#L324-L328)

**huggingface**
- [main/src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py#L536](https://github.com/huggingface/transformers/blob/main/src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py?rgh-link-date=2023-12-21T02%3A52%3A07Z#L536)

**No. 2**
 **fairseq**
- https://github.com/facebookresearch/fairseq/blob/main/fairseq/models/wav2vec/wav2vec2.py#L1230-L1231

**huggingface**
- https://github.com/huggingface/transformers/blob/main/src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py#L929


## 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.

<!-- 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:
@ylacombe @sanchit-gandhi 
I opened a PR and I would appreciate it if you could check it out when you have time. 
Thanks : )



@ylacombe @sanchit-gandhi 

The test error seems to change as the model parameters change. Do you have any next steps for me to take?

[workflow test error](https://app.circleci.com/pipelines/github/huggingface/transformers/81359/workflows/60d2764c-fa01-4547-934e-df2cb2915d0d/jobs/1044174)

@sanchit-gandhi  
Thank you for a detailed description.
As you said, the 'official' Wav2Vec2 checkpoints do not exist if `config.conv_dim[-1] != config.hidden_size`.
However, if `config.conv_dim[-1]` and `config.hidden_size` are the same like mine, they cannot use the huggingface inference. What if we took steps to make these cases available as well?

And another story, I think the layernorm location of the 'official' Wav2Vec2 fairseq implementation and the huggingface layernorm location are different. So I added the `layer_norm_first` option. What do you think about this?

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

Hey @sanchit-gandhi , I have a question.

The test code below doesn't work in my environment. Does it work?
```
pytest -sv tests/models/wav2vec2/test_modeling_wav2vec2.py::Wav2Vec2ModelTester::test_model_with_adapter
```

And I have reflected everything you said.

Hey @upskyy - indeed there might have been a minor typo in the above message, but it should work with:
```
pytest -sv tests/models/wav2vec2/test_modeling_wav2vec2.py::Wav2Vec2ModelTest::test_model_with_adapter
```

Hey @sanchit-gandhi 

I added the test code you mentioned and confirmed that it works well.
```
pytest -sv tests/models/wav2vec2/test_modeling_wav2vec2.py::Wav2Vec2ModelTest::test_model_with_projection
pytest -sv tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py::Wav2Vec2ConformerModelTest::test_model_with_projection
pytest -sv tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py::Wav2Vec2ConformerModelTest::test_model_with_no_post_layer_norm
```
We also confirmed that the existing fairseq model test was working well.
```
RUN_SLOW=1 pytest -sv tests/models/wav2vec2/test_modeling_wav2vec2.py::Wav2Vec2ModelIntegrationTest::test_inference_ctc_normal
```

Hey @sanchit-gandhi !
Are there any additional comments?

Gentle ping @sanchit-gandhi 

Another ping @sanchit-gandhi 

@sanchit-gandhi 
I have edited and responded. I'll be waiting for your reply !

cc @ylacombe 

@ylacombe 

I rebased the code and completed the 5 steps in the [guide](https://huggingface.co/docs/transformers/en/contributing#create-a-pull-request).
If there is anything that needs to be corrected, please comment at any time.

Thanks for iterating! Don't forget to make sure the quality checks pass by following step 5 in [this guide](https://huggingface.co/docs/transformers/en/contributing#create-a-pull-request), as you've done before

@ylacombe 
If I follow step 5 in this [guide](https://huggingface.co/docs/transformers/en/contributing#create-a-pull-request), the changes are the same as in the link below. What should I do?

https://github.com/huggingface/transformers/pull/28250/files/2d012c08af19a2fb5d81a122b7b4934418a28d5e#diff-fecb63c15748b527f04a978fed6cf44387dbbad911477cd7da8b7356c122d869

https://github.com/huggingface/transformers/pull/28250/files/2d012c08af19a2fb5d81a122b7b4934418a28d5e#r1741751303

Mmmh you could clean up the `# Copied from...` statements that are problematic in the test_modeling_wav2vec2_bert ?

I think this part should be revised.
Because `Wav2Vec2BertForCTC` output has [`logits`](https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_outputs.py#L648-L674) and `last_hidden_state` has been changed to not exist.

https://github.com/huggingface/transformers/pull/28250/files/2d012c08af19a2fb5d81a122b7b4934418a28d5e#r1741751303

Not sure to follow what you're meaning !

If you remove [this line](https://github.com/huggingface/transformers/blob/d70347726577e9823e35c11883e98c5b2c520b37/tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py#L426C38-L426C39), it should be okay, no ?

I deleted the part you said and proceeded to [step 5](https://huggingface.co/docs/transformers/en/contributing#create-a-pull-request).

Why does an error occur? 🤔
https://app.circleci.com/pipelines/github/huggingface/transformers/103097/workflows/daf7a15e-c06e-4119-8032-67aa88cd1429/jobs/1372090

So the way to do it is actually to revert again the changes on the test_modeling_wav2vec2bert as discussed [in this comment](https://github.com/huggingface/transformers/pull/28250#discussion_r1741751303). I think it's like you did in [this commit](https://github.com/huggingface/transformers/pull/28250/commits/33cd7f84edb879ecdb78b9af028f10f27062d688).

And then to remove the 3 `# Copied from` statements and the `# Ignore copy` statements that are in the [test file](https://github.com/huggingface/transformers/blob/924467718b45c8d9f108455f470815a36d101c8e/tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py).

At the end of the day, besides these changes in the copy statements, the test file of `wav2vec2_bert` should not have any changes since it was not impacted by your PR

@ylacombe 
Thank you for the detailed explanation. I passed all test cases.
Please leave a comment if you have anything to do later, such as rebase.

@ylacombe @amyeroberts @sanchit-gandhi 
How should I proceed further?

A last ask on my side would be to trigger the slow integration tests on the models you've modified: 
You can do it by pushing a commit with the message: `[run_slow] data2vec,speecht5,unispeech,wav2vec2,wav2vec2_conformer,wavlm`. Another HF member or I will need to approve the workflow for it to run.

I committed with the message: `[run_slow] data2vec,speecht5,unispeech,wav2vec2,wav2vec2_conformer,wavlm`.
Please run slow tests.

I think you need to do a proper commit and not a force-pushed !

You can allow an empty commit with `git commit --allow-empty -m "[run_slow] data2vec,speecht5,unispeech,wav2vec2,wav2vec2_conformer,wavlm"`

Hey @upskyy, I think you had bad luck and that current failing tests should pass now.

Feel free to first rebase your branch and then repush the empty commit for slow tests! We'll merge when everything's green!

@ylacombe  It's been almost a year since I opened PR 😂
Only `tests_hub` failed, but when I looked at the log, I saw a 502 error. Please check it out and let me know if there is anything I need to add. thank you!

@ylacombe Are there any further updates?