# Flan-T5 with Tensorflow-Serving

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fflan-t5-with-tensorflow-serving%2F57931%3E%5C
**Category:** 🤗Transformers\
**Created:** [October 9, 2023, 4:20pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fflan-t5-with-tensorflow-serving%2F57931 "2023-10-09T16:20:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![gargantua42](https://avatars.discourse-cdn.com/v4/letter/g/7ea924/32.png) [@gargantua42](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fgargantua42)%5C
**Post date:** [October 9, 2023, 4:20pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fflan-t5-with-tensorflow-serving%2F57931%2F1 "2023-10-09T16:20:11Z")

</div>

Hi everyone

Is there a way to run the `.generate()` function of a fine-tuned Flan-T5 model with Tensorflow-Serving?

I’d like to use the `.generate()` function with beam search.

I’ve managed to make it run with the basic `.call()` function, however the answer is roughly 55 MB in size when using the REST API as it returns all the `logits` and `encoder_last_hidden_state`.

My model signature looks as follows:

```auto
The given SavedModel SignatureDef contains the following input(s):
  inputs ['attention mask'] tensor_into:
    dtype: DT_INT32
    shape: (-1, -1)
    name: serving_default_attention_mask:0
  inputs ['decoder_attention_mask'] tensor_info:
    dtype: DT_INT32
    shape: (-1, -1)
    name: serving_default_decoder_attention_mask:0
  inputs ['decoder_input_ids'] tensor_info:
    dtype: DT_INT32
    shape: (-1, -1)
    name: serving default_decoder_input_ids:0
  inputs ['input_ids'] tensor_info:
    dtype: DT_INT32
    shape: (-1, -1)
    name: serving_default_input_ids:0
The given SavedModel SignatureDef contains the following output(s):
  outputs ['encoder_last_hidden_state'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, -1, 512)
    name: StatefulPartitionedCall:0
  outputs ['logits'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, -1, 32128)
    name: StatefulPartitionedCall:1
Method name is: tensorflow/serving/predict

```

After some more digging, I found this PR:

> <https://github.com/huggingface/transformers/pull/18372>
>
> \# What does this PR do?
> 
> support dynamic input for tf.function + generate (XLA…). needed for batch tf serving
> 
> export:
> \`\`\`
> import tensorflow as tf
> from transformers import TFAutoModelForSeq2SeqLM
> 
> class MyOwnModel(tf.Module):
> def \_\_init\_\_(self, model\_path="t5-small"):
> super(MyOwnModel, self).\_\_init\_\_()
> self.model = TFAutoModelForSeq2SeqLM.from\_pretrained(model\_path)
> 
> @tf.function(input\_signature=(tf.TensorSpec((None, 32), tf.int32, name="input\_ids"),
> tf.TensorSpec((None, 32), tf.int32, name="attention\_mask")), jit\_compile=True)
> def serving(self, input\_ids, attention\_mask):
> outputs = self.model.generate(input\_ids=input\_ids, attention\_mask=attention\_mask, max\_new\_tokens=32,
> return\_dict\_in\_generate=True)
> return {"sequences": outputs\["sequences"\]}
> 
> model = MyOwnModel()
> export\_dir = "./"
> tf.saved\_model.save(
> model,
> export\_dir,
> signatures={
> "serving\_default":
> model.serving
> })
> \`\`\`
> tf model run
> \`\`\`
> import tensorflow as tf
> from transformers import AutoTokenizer, TFAutoModelForSeq2SeqLM
> export\_dir = "./"
> model = tf.saved\_model.load(export\_dir)
> 
> tokenizer = AutoTokenizer.from\_pretrained("t5-small")
> tokenization\_kwargs = {"pad\_to\_multiple\_of": 32, "padding": True, "return\_tensors": "tf"}
> 
> input\_prompts = \[
> f"translate English to {language}: I have four cats and three dogs."
> for language in \["German", "French", "Romanian"\]
> \]
> 
> def generate\_text(inputs):
> tokenized\_inputs = tokenizer(inputs, \*\*tokenization\_kwargs)
> generated\_texts = model.signatures\["serving\_default"\](\*\*tokenized\_inputs)
> for text in generated\_texts\["sequences"\]:
> print(tokenizer.decode(text, skip\_special\_tokens=True))
> \# The first prompt will be slow (compiling), the others will be very fast!
> generate\_text(input\_prompts\[:2\])
> generate\_text(input\_prompts\[:3\])
> \`\`\`
> xla\_run
> \`\`\`
> import tensorflow as tf
> from transformers import AutoTokenizer, TFAutoModelForSeq2SeqLM
> 
> tokenizer = AutoTokenizer.from\_pretrained("t5-small")
> model = TFAutoModelForSeq2SeqLM.from\_pretrained("t5-small")
> 
> \# Main changes with respect to the original generate workflow: \`tf.function\` and \`pad\_to\_multiple\_of\`
> xla\_generate = tf.function(model.generate, jit\_compile=True)
> tokenization\_kwargs = {"pad\_to\_multiple\_of": 32, "padding": True, "return\_tensors": "tf"}
> 
> \# The first prompt will be slow (compiling), the others will be very fast!
> input\_prompts = \[
> f"translate English to {language}: I have four cats and three dogs."
> for language in \["German", "French", "Romanian"\]
> \]
> tokenized\_inputs = tokenizer(input\_prompts, \*\*tokenization\_kwargs)
> generated\_texts = xla\_generate(\*\*tokenized\_inputs, max\_new\_tokens=32)
> for text in generated\_texts:
> print(tokenizer.decode(text, skip\_special\_tokens=True))
> \`\`\`
> 
> this also works for beam search by changing exported code as 
> \`\`\`
> def serving(self, input\_ids, attention\_mask):
> outputs = self.model.generate(input\_ids=input\_ids, attention\_mask=attention\_mask, max\_new\_tokens=32,
> return\_dict\_in\_generate=True, num\_beams=3, num\_return\_sequences=3)
> return {"sequences": outputs\["sequences"\]}
> \`\`\`
> \<!--
> 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.
> \--\>
> 
> 
> 
> Fixes #18357
> Fixes #16823
> 
> 
> \## 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/main/CONTRIBUTING.md#start-contributing-pull-requests),
> Pull Request section?
> \- \[\] Was this discussed/approved via a Github issue or the \[forum\](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2F)%3F 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).
> \- \[x\] 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
> 
> --\>
> cc @gante @patrickvonplaten

My Exporter Code looks as follows:

```python
import tensorflow as tf
import transformers

class MyModule(tf.Module):
  def _init_(self, model: transformers.TFAutoModelForSeq2SeqLM) - None:
    super(MyModule, self)._init_()
    self.model = model

@tf. function(
  input_signature=(
    tf.TensorSpec(name="input_ids", shape=(None, None), dtype=tf.int32),
    tf.TensorSpec(name="attention_mask", shape=(None, None), dtype=tf.int32)
  ),
  jit_compile=False,
)

def serving(self, input_ids, attention_mask) -> dict:
  outputs = self.model.generate(
    input_ids=input_ids,
    attention_mask=attention_mask,
    max_length=512,
    min_length=10,
    # length_penalty=0.9,
    # repetition_penalty=2.0,
    # num_beams=4,
    # early_stopping=True,
    return_dict_in_generate=True,
  )
  return {"sequences": outputs["sequences"]}

```

Using this exporter I get the following model signature:

```auto
The given SavedModel SignatureDef contains the following input (s):
  inputs['attention mask'] tensor_info:
    dtype: DT_INT32
    shape: (-1, -1)
    name: serving_default_attention_mask:0
  inputs['input_ids"] tensor_info:
    type: DT_INT32
    shape: (-1, -1)
    name: serving_default_input_ids:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['sequences'] tensor info:
    dtype: DT_INT32
    shape: (-1, 512)
    name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict

```

However, when I try to run inference on the model using the default `tensorflow/serving` docker image (REST API), I get the following error:

```json
{
  "error": "XLA compilation disabled\n\t [[{{function node while body_14884}}{{node while/tft5_for_conditional_generation/decoder/block_._0/layer_._0/SelfAttention/XLaDynamicSLice}}]]"
}

```

What is the right way to go to serve a fine-tunes flan-T5 modle using Tensorflow-Serving?

I’m using `transformers` version `4.34.0` and `tensorflow` version `2.13.1`.

Maybe @joaogante?

Thanks in advance!
