[`SwitchTransformer`] Significant performance improvement on MoE blocks
Author: ranggihwang
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 is an edited version of the previously closed PR (https://github.com/huggingface/transformers/pull/30490)**

This PR includes a performant implementation of `SwitchTransformersSparseMLP` in the Google SwitchTransformer.
In the current implementation of the SwitchTransformer, it spans all possible experts, including the inactive ones.

```python
for idx, expert in enumerate(self.experts.values()):
            token_indices = router_mask[:, :, idx].bool()
            next_states[token_indices] = expert(hidden_states[token_indices]).to(next_states.dtype)
```

This results in serious performance degradation of the SwitchTransformer.

<img width="923" alt="스크린샷 2024-04-26 오전 2 16 44" src="https://github.com/huggingface/transformers/assets/50730045/3c01da41-7281-43c5-a879-a3e36a56e9de">
As shown in this figure, the current implementation of the SwitchTransformer spans inactive experts, unnecessarily increasing latency.

<img width="900" alt="스크린샷 2024-04-26 오전 2 17 37" src="https://github.com/huggingface/transformers/assets/50730045/a8f5b90c-3e67-4a28-a289-348fe2bc6c9e">
This issue can be particularly severe in models with a larger number of experts, as it needlessly spans more experts.

However, in my custom implementation of `SwitchTransformersSparseMLP`, it only accesses and computes the active experts.

**Advantages**
* This can significantly reduce the latency of the SwitchTransformer and make the model more accessible to a broader range of users.
* This change achieves greater latency reductions when expert parameters are offloaded to the CPU or SSD.
* This change addresses the problem of increasing latency proportional to the number of experts.


## 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#create-a-pull-request),
      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. Feel free to tag
members/contributors who may be interested in your PR.

@ArthurZucker and @younesbelkada

<!-- 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: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- 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:
Thanks @younesbelkada 
I've done `make fixup && make fix-copies` before in https://github.com/huggingface/transformers/pull/30490#pullrequestreview-2025011217
But I was requested to revert in the end.

How do I need to this correctly? Would you please let me know how to do this?

Hi @ranggihwang  
Thanks ! Hmm I think there was a misunderstanding on my side at that time, if you could run the styling checks and push the results here (it should only change 2 files, switch transformers & gpt_san_japanese file), it would be great ! 

Shouldn't the styling check be done for the `src/transformers/models/switch_transformers/modeling_switch_transformers.py`?
I haven't changed anything except the file and it seems like there's no file named gpt_san_japanese_file in my repo.

since gpt_san_japanese uses blocks that are copied from switch transformers, running `make fix-copies` will propagate the changes you introduced in that file as well, see: https://app.circleci.com/pipelines/github/huggingface/transformers/94615/workflows/e1e9d110-614a-411a-a0f5-b7d4146e4db8/jobs/1241937 

@younesbelkada @ranggihwang gpt san has been deprecated, so we don't really want these changes to be propogated. I've just merged in #31153 which removes the `# Copied from` headers for this model. Rebasing on `main` will include this and remove the need to run `make fix-copies` here. Thanks!  

Perfect thanks for the heads up @amyeroberts ! 
@ranggihwang feel free to proceed as suggested by amy 🙏 

@amyeroberts @younesbelkada 
Thank you for your advice, Amy and Younes.

I've just rebase it to main and commit it. Would you please check if it is correct?

Thanks @ranggihwang ! Now styling checks are failing, can you run `make fixup` and commit the changes ?

Okay, now `make fixup` is done!

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

I'll review this as I reviewed the previous PR, want to make sure the suggestions are all applied! 

@ArthurZucker @younesbelkada 
Please let me know if I need to rebase it again :)

Could this be propagated to the qwen code @ranggihwang ? I know that they have some variants with lots of experts!

@ArthurZucker  I think it can be adopted for many MoE models in HuggingFace not only qwen-moe but also for NLLB-MoE, Mixtral, etc.

awesome! Then if you are interested feel free to open a PR and ping me! 🤗 
Some models need compile support which might be a little bit tricky we'll see