switch to inference_mode from no_gard
Author: kamalkraj
Pull request: yes

# What does this PR do?

Use `torch.inference_mode()` for pipelines. 
https://pytorch.org/docs/stable/generated/torch.inference_mode.html

`with torch.no_grad()`
![Screenshot 2021-09-21 at 11 46 12 AM](https://user-images.githubusercontent.com/17096858/134121830-e16ddaae-77ea-4dc7-8464-6ce80b44ebf9.png)

`with torch.inference_mode()`
![Screenshot 2021-09-21 at 11 48 14 AM](https://user-images.githubusercontent.com/17096858/134121909-4e79ed6c-944e-4c23-9013-53e3d38bd450.png)



<!--
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 # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/master/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/master/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/master/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:

- 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

 -->
@sgugger @Narsil 

Comments:
Hi @kamalkraj,

Thanks for this ! Do you mind sharing on which hardware this was done ?
We ran some tests too and found very little difference between the 2 modes (<1%).

We decided against putting that line because `transformers` needs to support older versions of `pytorch` which do not have `inference_mode` (so we would need an extra switch and maintain remove it when necessary). Because the performance was so little we decided it was not worth the investment.

If we can show performance differences, we're more than happy to add such switches.

Here is a small benchmark I ran on a GTX970:

```python
from transformers import pipeline
from transformers.pipelines.base import KeyDataset
import datasets
import tqdm

pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0)
dataset = datasets.load_dataset("superb", name="asr", split="test")

print("New style of pipeline")
for i, out in tqdm.tqdm(enumerate(pipe(KeyDataset(dataset, "file"))), total=100):
    # print(out)
    if i >= 100:
        break
```

And the results are

`no_grad`:
```
Some weights of Wav2Vec2ForCTC were not initialized from the model checkpoint at facebook/wav2vec2-base-960h and are newly initialized: ['wav2vec2.masked_spec_embed']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
The model 'Wav2Vec2ForCTC' is not supported for automatic-speech-recognition. Supported models are [(<class 'transformers.models.speech_encoder_decoder.configuration_speech_encoder_decoder.SpeechEncoderDecoderConfig'>, <class 'transformers.models.speech_encoder_decoder.modeling_speech_encoder_decoder.SpeechEncoderDecoderModel'>), (<class 'transformers.models.speech_to_text.configuration_speech_to_text.Speech2TextConfig'>, <class 'transformers.models.speech_to_text.modeling_speech_to_text.Speech2TextForConditionalGeneration'>), (<class 'transformers.models.wav2vec2.configuration_wav2vec2.Wav2Vec2Config'>, <class 'transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC'>), (<class 'transformers.models.hubert.configuration_hubert.HubertConfig'>, <class 'transformers.models.hubert.modeling_hubert.HubertForCTC'>)].
Reusing dataset superb (/home/nicolas/.cache/huggingface/datasets/superb/asr/1.9.0/b185de2966d0d6025cd53df6b41f89e2d100ee17139797b793f62b2c7c7612bd)
New style of pipeline
100%|███████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:08<00:00, 12.22it/s]

real    0m21.202s
user    0m23.972s
sys     0m17.884s
```

`inference_mode`:
```
Some weights of Wav2Vec2ForCTC were not initialized from the model checkpoint at facebook/wav2vec2-base-960h and are newly initialized: ['wav2vec2.masked_spec_embed']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
The model 'Wav2Vec2ForCTC' is not supported for automatic-speech-recognition. Supported models are [(<class 'transformers.models.speech_encoder_decoder.configuration_speech_encoder_decoder.SpeechEncoderDecoderConfig'>, <class 'transformers.models.speech_encoder_decoder.modeling_speech_encoder_decoder.SpeechEncoderDecoderModel'>), (<class 'transformers.models.speech_to_text.configuration_speech_to_text.Speech2TextConfig'>, <class 'transformers.models.speech_to_text.modeling_speech_to_text.Speech2TextForConditionalGeneration'>), (<class 'transformers.models.wav2vec2.configuration_wav2vec2.Wav2Vec2Config'>, <class 'transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC'>), (<class 'transformers.models.hubert.configuration_hubert.HubertConfig'>, <class 'transformers.models.hubert.modeling_hubert.HubertForCTC'>)].
Reusing dataset superb (/home/nicolas/.cache/huggingface/datasets/superb/asr/1.9.0/b185de2966d0d6025cd53df6b41f89e2d100ee17139797b793f62b2c7c7612bd)
New style of pipeline
100%|███████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:08<00:00, 12.30it/s]

real    0m21.570s
user    0m23.568s
sys     0m17.807s
```

I ran the benchmark multiple times and basically the numbers are exactly the same for each mode.

Hi @Narsil,

The above screenshot I shared is using TITAN RTX. I have also tested the same on A100.  Similar performance as TITAN RTX

But when I use the below benchmark, I don't really see any performance improvement. (Only tested on A100)
getting the same performance as you shared.
> Here is a small benchmark I ran on a GTX970:
> 
> ```python
> from transformers import pipeline
> from transformers.pipelines.base import KeyDataset
> import datasets
> import tqdm
> 
> pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0)
> dataset = datasets.load_dataset("superb", name="asr", split="test")
> 
> print("New style of pipeline")
> for i, out in tqdm.tqdm(enumerate(pipe(KeyDataset(dataset, "file"))), total=100):
>     # print(out)
>     if i >= 100:
>         break
> ```

- `transformers` version: 4.11.0.dev0
- Platform: Linux-5.4.0-84-generic-x86_64-with-Ubuntu-18.04-bionic
- Python version: 3.6.9
- PyTorch version (GPU?): 1.9.0+cu111 (True)


https://twitter.com/PyTorch/status/1437838236529868803/photo/
![E_Q4D8cXIAki7Yx](https://user-images.githubusercontent.com/17096858/134164937-a12a228d-c546-470c-9d5f-b71dddff45a2.jpeg)
2

Thanks you @kamalkraj.

I checked the numbers and had similar results for `distilbert-base-uncased-finetuned-sst-2-english` as you.
the odd part is that I also had similar total runtime numbers on a much smaller GPU.

I think this model is super small and so the pipeline does showcase a bit more the difference in `inference_mode`.
But only because we're not feeding it enough, so it's starving (and probably inference_mode sync is faster ?)

As the tweet mentions:

> Note that the highest speedups are for lightweight operations that are bottlenecked by the tracking overhead.

However I am currently thinking that maybe we're just under utilizing the GPU for this and re enabling batching could speedup this use case which would result in similar times for both `no_grad` and `inference_mode` again (both much faster than current implementation but with batching which has it's own set of caveats at inference time).

So my opinion, is that we should:

1- Enable the switch as it's is indeed faster on some cases by more than what was anticipated (but current PR needs to be modified to support older `torch` versions)
2- Add again `batch_size` support for pipeline but with a sane default of `1`, clear explanations of the caveats (alignment issues can really blow up the results and worsen inference times) in the docs and enable users to speed up on small-models with pipelines where data is sufficiently aligned. This was already planned, but having a clear use case will definitely help !



This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/master/CONTRIBUTING.md) are likely to be ignored.

unstale

Thank you for your work @kamalkraj!