Significant performance improvement on MoE block of SwitchTransformer
Author: ranggihwang
Pull request: yes

# What does this PR do?

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.

<!-- 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:
cc @ArthurZucker @younesbelkada 

Is there anything else that I need to do for this PR?

@younesbelkada 
I've changed the coding style using make fixup, but I'm encountering an error when running this command:

```
RUN_SLOW=1 pytest tests/models/switch_transformers/test_modeling_switch_transformers.py
```
I've noticed the same error with the original switch transformer code, so I assume it's not due to my changes. How can I resolve this issue?

If you need the error log, I can attach it here.

@ArthurZucker 
That's a great point.
In the SwitchTransformer model, all experts can be used in the training phase, but in the inference, only some of them are utilized and that's the point where inefficiency is raised that the original code missed.
I'm mainly talking about inference, however, my custom code also can be used for training because it is mathematically equivalent to the original code.

For linting, is it okay for me to revert it to the previous version? Actually, this is the first time for me to contribute codes to HuggingFace, so I'm a bit confused about what to do next to get an acceptance for merging.

Oh, I think I've done something wrong. I just wanted to rebase and revert other unrelated changes but somehow it close the PR :( Can I open a new PR reflecting all the comments? @ArthurZucker 

> Actually a lot better!
> 
> ```
> idx_mask = router_mask.reshape(batch*seq_len, num_experts).transpose(0,1).sum(dim=1) 
> idx_mask = torch.nonzero(idx_mask, as_tuple=True)[0].tolist()
> ```
> 
> to simplify. And indeed, since decoding is only gonna activate at most 2 x batch, this is better.
> 
> Make sure to rebase on main and simply revert the unrelated changes! 🤗 thanks for the contribution

Shouldn't the activated expert at most be batch size as it top-1 gating? @ArthurZucker 

AH it's top1, I was thinking of Mixtral which is top2 😉 
Anyways no worries for the old PR vs new it happens