[WIP] Adding support for `flax` for `pipelines`.
Author: Narsil
Pull request: yes
Labels: name: WIP

# 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 # (issue)

```python
from transformers import FlaxRobertaModel, RobertaTokenizerFast,
RobertaForMaskedLM, pipeline
import numpy as np
import datetime
import tqdm
import random

def data(n):
    for _ in range(n):
        yield "JAX/Flax is amazing <mask>"

def flax(n):
    print("----")
    print("Flax")
    start = datetime.datetime.now()
    pipe = pipeline(
        model="distilbert-base-uncased-finetuned-sst-2-english",
        device=0,
        framework="flax",
        model_kwargs={"from_pt": True},
    )
    print("Loading flax", datetime.datetime.now() - start)

    for out in tqdm.tqdm(pipe(data(n), batch_size=512)):
        pass

def tf(n):
    print("----")
    print("TF")
    start = datetime.datetime.now()
    pipe =
pipeline(model="distilbert-base-uncased-finetuned-sst-2-english",
device=0, framework="tf")
    print("Loading TF", datetime.datetime.now() - start)

    for out in tqdm.tqdm(pipe(data(n), batch_size=512)):
        pass

def pt(n):
    print("----")
    print("PT")
    start = datetime.datetime.now()
    pipe =
pipeline(model="distilbert-base-uncased-finetuned-sst-2-english",
device=0, framework="pt")
    print("Loading PT", datetime.datetime.now() - start)

    for out in tqdm.tqdm(pipe(data(n), batch_size=512)):
        pass
        # print(out)

if __name__ == "__main__":
    n = 20000
    # pt(n)
    # flax(n)
    tf(n)
```

## 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

 -->

Comments:
@Narsil - please ping me once you would like to have a review on this :-)

@patrickvonplaten I think this should be ready for a first pass review.

Let's focus on the big picture and overall architecture for this. The main pain points I am thinking of:

- Should we force padding to get compilation cache hit on jax.
- Should we enable JIT automatically or not? (If we want `pjit` or others maybe we should delegate that choice to users ?)

> @patrickvonplaten I think this should be ready for a first pass review.
> 
> Let's focus on the big picture and overall architecture for this. The main pain points I am thinking of:
> 
> * Should we force padding to get compilation cache hit on jax.
> * Should we enable JIT automatically or not? (If we want `pjit` or others maybe we should delegate that choice to users ?)

Good questions! 

IMO:

For a) -> yes I would definitely do this. The by far most important application will be to provide a simple and fast demo for large LM models, such as https://huggingface.co/Cedille/fr-boris?text=Mon+nom+est+Thomas+et+mon+principal (which currently doesn't work with PT on GPU). I woulcd actually force padding to a large multiple to something like 64 by default (cc @patil-suraj what do you think?)

For b) -> yeah good question. I think we should delegate it to the user meaning that there will be both a `jit=True/False` and a `parallel=True/False` input that the user can specify. IMO both should default to False, but for the inference widget we should default jit to True I think (if JAX is used for large models)



> > @patrickvonplaten I think this should be ready for a first pass review.
> > Let's focus on the big picture and overall architecture for this. The main pain points I am thinking of:
> > 
> > * Should we force padding to get compilation cache hit on jax.
> > * Should we enable JIT automatically or not? (If we want `pjit` or others maybe we should delegate that choice to users ?)
> 
> Good questions!
> 
> IMO:
> 
> For a) -> yes I would definitely do this. The by far most important application will be to provide a simple and fast demo for large LM models, such as https://huggingface.co/Cedille/fr-boris?text=Mon+nom+est+Thomas+et+mon+principal (which currently doesn't work with PT on GPU). I woulcd actually force padding to a large multiple to something like 64 by default (cc @patil-suraj what do you think?)

Makes sense to me this was in the first iteration, and I removed it since during compilation during tests is still painfully slow because no cache hits there (we're mostly loading different models and sending a handful of inference at them).

> 
> For b) -> yeah good question. I think we should delegate it to the user meaning that there will be both a `jit=True/False` and a `parallel=True/False` input that the user can specify. IMO both should default to False, but for the inference widget we should default jit to True I think (if JAX is used for large models)

Ok, since this is specific to `jax` and I don't intend to add similar `torchscript` stuff to `pt` for instance, I am guessing I will aim for something that would look like

```python
pipe = pipeline(....)
pipe._enable_compilation(type="jit", )
# or
pipe._enable_compilation(type="pjit", **extra_mapping)
# Or add the jitting automatically if it wasn't called by the user with align to = 64
```

@Narsil - that looks good to me. Let's see what @patil-suraj thinks about the API

0Still valuable

Super sorry about being so late here, will take a look this week :) 

Also think this would be a nice addition still - gently ping for @patil-suraj here.