How To Speed Up Deep Learning Inference For Natural Language Processing Transformers

Advanced deep learning models for Natural Language Processing based on Transformers give impressive results, but getting high speed performances is hard. In this article I summarize the best options you have if you want to decrease the latency of your predictions in production.

Use a better CPU or GPU

When one wants to improve the speed of Transformer based Natural Language Processing models, the “naive” approach is to use more advanced hardware.

Most of the time this is an inevitable solution, as pure software-based solutions all have limits. Imagine you’re performing inference on a CPU. You may spend weeks working on low level optimization for your favorite Transformer-based model, it’s very likely that you will still get better speed improvement by simply moving your model to an NVIDIA A100 GPU.

These days the most widely used GPUs for inference in production are the NVIDIA Tesla T4 and V100.

NVIDIA Tesla GPU

But what if you already upgraded your hardware? Or what if your budget is limited and you cannot afford to leverage the last cutting-edge expensive GPUs? Read the following!

Batch Inference

Batch inference is about sending several requests at the same time to your model, so it addresses your requests all at once.

Batch inference is very powerful because it will take almost the same time for your model to address several requests as it takes to address 1 request. Under the hood some operations will be factorized, so that instead of doing everything n times, the model only has to do it once.

Technically speaking, it doesn’t decrease the latency of your requests, because your requests won’t be addressed faster, but it will dramatically improve the throughput of your application (your application can handle more requests with the same hardware).

Batch inference is not perfect though.

First it is not always suited for online inference (i.e. for customer facing applications), because in order to build your batches you will have to buffer some user requests, so some users will have to wait longer than usual.

Second challenge: batch inference works better for similar requests. For example, if you’re deploying a text generation Natural Language Processing model, batching will be more efficient if you create batches of requests that have the same length.

Last of all, batch inference is not performed by your deep learning model itself, but by a higher level layer, like a dedicated inference server. It’s not always easy to implement such a layer. For example, NVIDIA’s Triton Inference Server (see below) is very good at performing batch inference, but you first need to find a way to make your model compliant with Triton.

Once you manage to export your model into Triton, batch inference is dead simple. For example, here is how to create batches made of up to 128 requests, and wait for 5 seconds maximum before processing the batch (this should be put in the “config.pbtxt” file).

max_batch_size: 128
dynamic_batching {
  max_queue_delay_microseconds: 5000000
}

Leverage Custom Implementations

Many people and companies are working hard on low level optimizations for some Transformer-based Natural Language Processing models. It can be a good idea for you to leverage these custom implementations of your model.

Most of the time these custom implementations are easy to use and require almost no additional work from you. Let me mention some of them here:

  • DeepSpeed: this library by Microsoft was initially dedicated to improving performances of model training, especially on multiple GPUs. They recently released specific model kernels for inference, and it seems they are planning to gradually support more and more models.
  • FasterTransformer: this framework was created by NVIDIA in order to make inference of Transformer-based models more efficient. You will have to build a new implementation of your model thanks to their library, if your model is supported. Then you can run your model as-is or load it into their Triton Inference Server by using their FasterTransformer Triton Backend.
  • TurboTransformers: Tencent created this library for WeChat and then open-sourced it. Please refer to their documentation to see if your model is supported.
  • Fast T5: a library dedicated to improving the speed of t5 models.
  • CTranslate2: a library dedicated to improving the speed of models based on OpenNMT and FairSeq.

Here is an example about how you can perform inference for your GPT Neo 2.7B model thanks to DeepSpeed. Not too hard isn’t it?

# Filename: gpt-neo-2.7b-generation.py
import os
import deepspeed
import torch
from transformers import pipeline

local_rank = int(os.getenv('LOCAL_RANK', '0'))
world_size = int(os.getenv('WORLD_SIZE', '1'))
generator = pipeline('text-generation', model='EleutherAI/gpt-neo-2.7B',
                        device=local_rank)

generator.model = deepspeed.init_inference(generator.model,
                                            mp_size=world_size,
                                            dtype=torch.float,
                                            replace_method='auto')

string = generator("DeepSpeed is", do_sample=True, min_length=50)
if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:
    print(string)

When using one of these custom implementations, don’t forget to rigorously test the quality of your new model, as you can never be 100% sure there is no bug in these new implementations.

Use a Dedicated Inference Engine

Microsoft and NVIDIA both worked on advanced inference engines in order to improve inference performances.

ONNX Runtime (“ORT”), by Microsoft, is a cross-platform inference and training machine-learning accelerator (see here). TensorRT (“TRT”), by NVIDIA, is an SDK for high-performance deep learning inference. It includes a deep learning inference optimizer and runtime that delivers low latency and high throughput for deep learning inference applications (see here).

Additionally, the NVIDIA Triton Inference Server is an inference serving software that makes AI inference easier by making it possible to deploy AI models from various frameworks. Thanks to Triton you can for example perform batch inference easily, run multiple deep learning models concurrently on the same GPU, deploy models on multiple GPUs, and more. See here.

The above seems exciting, but of course it’s not that simple… In order for your model to leverage these dedicated inference engines, you first need to convert your existing model into a proper format.

You have several choices:

  • Exporting your Transformer-based model to ONNX. Hugging Face tries to make your job easier by providing you with a ready-to-use script for such an export: convert_graph_to_onnx.py. Unfortunately it’s not compatible with all the models, so it’s possible that you will have to get your hands dirty and write your own export script.
  • Exporting your Transformer-based model to Torchscript, using either the tracing or scripting method. Here too, it won’t work for all the models and you might have to dig deeper into low level code (see here).
  • Converting your ONNX model to TensorRT for better performances and even further optimizations (like quantization). But it first requires your model to be already exported.

When playing with the above methods, you should be very careful with quality of your exported models. You might think that you successfully exported your model, but it’s possible that you lost some accuracy in the process, so be very rigorous about how you’re testing your new exported model.

Conclusion

Modern transformer-based Natural Language Processing models give impressive results, so that more and more companies want to use them in production. But very often it appears that performances are disappointing…

Working on improving the speed of your predictions is crucial but, as you could see above, there is no one size fits all solution.

How To Build a Chatbot With GPT-3 or GPT-J

GPT-3 and GPT-J give amazing results. They are very strong AI models for chatbots as of this writing. Here are a couple of tips in order to help you build a chatbot with GPT-3 or GPT-J. I also make a quick comparison with Blenderbot 2.

GPT-3 and GPT-J

In May 2020, OpenAI released GPT-3 (see GPT-3’s website). This is the biggest Natural Language Processing model ever created, trained on 175 billion parameters (for the Davinci version)! This AI model is not open-source. It is now owned by Microsoft.

GPT-J was released in June 2021 as an open-source model, by EleutherAI and is very similar to GPT-3 Curie (6 billion parameters) (see EleutherAI’s website here).

Both give incredible results in terms of text generation, and especially for chatbots and conversational AI. But it takes a bit of practice! First because these models need to be given a couple of examples before behaving as expected. And also because they are “stateless”, meaning that they don’t keep a history of your conversations. So you need to find a way around that!

Properly Formatting your Requests

If you naively send requests to these models without a bit of context and formatting, you will be disappointed by the responses. This is because these models are very versatile. They can do chatbots but many other things like question answering, summarization, paraphrase, classification, entity extraction, product description generation, and more. So the first thing you need to do is tell the model which “mode” he should adopt.

Here is a request example you could send:

This is a discussion between a [human] and a [robot]. 
The [robot] is very nice and empathetic.

[human]: I broke up with my girlfriend...
[robot]:

In this example, you can note 2 things.

First, I added a simple formatting in order for the model to understand that it is in conversational mode ([human], [robot], …).

Secondly, I added some context at the top in order to help the model understand what it is doing and the tone it should use. Don’t overestimate the importance of this context though. Most of the AI’s attitude and tone are going to come from the discussion itself. So if you really want your AI to sound “nice and empathetic” you should give some examples in your input that show a nice and empathetic character. Here is an example (if you want your model to be rude and sarcastic, simply pass a couple of rude and sarcastic examples instead):

This is a discussion between a [human] and a [robot]. 
The [robot] is very nice and empathetic.

[human]: Hello nice to meet you.
[robot]: Nice to meet you too.
###
[human]: How is it going today?
[robot]: Not so bad, thank you! How about you?
###
[human]: I am ok, but I am a bit sad...
[robot]: Oh? Why that?
###
[human]: I broke up with my girlfriend...
[robot]:

Here you can see that I first start with a couple of examples before passing the actual human message. 3 examples might be enough, but not always, so I encourage you to add more examples, especially in case of complex situations. Sometimes, even passing tons of examples is not enough. In that case, you have no choice but to fine-tune GPT-3 or GPT-J in order to get good results.

Keeping the Conversation History

GPT-3 and GPT-J are “stateless” models, meaning that every request you make is new and the AI is not going to remember anything about the previous requests you made.

In many Natural Language Processing situations it’s not a problem (summarization, classification, paraphrase…), but as far as chatbots are concerned it’s definitely an issue because you do want your chatbot to memorize the discussion history in order to make more relevant responses.

For example, if you tell the AI that you’re a programmer, you want it to keep it in memory because it will have an impact on the following responses it will make.

A reliable way to achieve this is to store every AI response in a local database. For example, the PostgreSQL database supports long texts storing, thanks to the “text” type, with a very good efficiency.

Then, every time you’re making a new request to the chatbot, you should do the following:

  1. Retrieve the conversation history from the local DB
  2. Add your actual request to the conversation history
  3. Send the whole request
  4. In your local DB, replace your old history with the response from the AI

This is both a versatile and robust system that requires little effort, and perfectly leverages the power of GPT-3 and GPT-J.

Quick note: these models cannot address requests bigger than 2048 tokens (i.e. more or less 1700 words), so if your conversation history goes above this, you might want to either truncate the oldest part of the history, or only keep the most important parts of the discussions.

Special Mention: Blenderbot 2

Facebook recently released a chatbot called Blenderbot 2. They are trying to address the conversation history issue by storing some data on the server side in order to keep track of the discussion history. It sounds appealing, but in practice it creates lots of new challenges. For example how do you make sure that each user has its own history and not all histories are mixed together? How do you control the data retention policy? Is the data persistent in case of a server restart, and how do you back up the data in case of a server crash? Etc.

I tried Blenderbot 2 and I am not convinced that it’s a better solution than GPT-3/GPT-J based chatbots. Not only can’t you easily set a context for your chatbot (like I did above), but also the server data storage is creating more challenges than simply maintaining the history on the client side.

Conclusion

GPT-3 and GPT-J really took chatbots and conversational AI to the next level. These huge models are very good at understanding your context and adapting to it. In most cases, setting the right context is enough, but for advanced use cases you should train or fine-tune your own AI model. Good news is that you can achieve great results with few examples (a 500 example dataset is a very good start).

Fine-tuning GPT-J, the GPT-3 open-source alternative

GPT-J may be the most powerful open-source Natural Language Processing model today (it’s the only open-source alternative competing with GPT-3), you might find it too general and not perfectly suited to your use case. In that case, fine-tuning GPT-J with your own data is the key.

The Power of GPT-J

Since it was released in June 2021, GPT-J has attracted tons of Natural Language Processing users - data scientists or developers - who believe that this powerful Natural Language Processing model will help them take their AI application to the next level (see EleutherAI’s website).

GPT-J is so powerful because it was trained on 6 billion parameters. The consequence is that this is a very versatile model that you can use for almost any advanced Natural Language Processing use case (sentiment analysis, text classification, chatbots, translation, code generation, paraphrase generation, and much more). When properly tuned, GPT-J is so fluent that it’s impossible to say that the text is generated by a machine…

It is possible to easily adapt GPT-J to your use case on-the-fly by using few-shot learning. However, if few-shot learning is not enough, you need to go for a more advanced technique: fine-tuning.

What is Fine-Tuning?

When it comes to creating your own model, the traditional technique is about training a new model from scratch with your own data. The problem is that modern models like GPT-J are so huge that it’s almost impossible for anyone to train this model from scratch. EleutherAI said it took them 5 weeks to train GPT-J on TPUs v3-256, which means it cost hundreds of thousands of dollars…

The good news is that re-training GPT-J is not necessary, because fine-tuning exists. Fine-tuning is about taking the existing GPT-J model and slightly adapting it. In the past, training traditional Natural Language Processing models from scratch used to take tons of examples. With the new generation Transformer-based models, it is different: fewer examples are necessary and can lead to great results. If you ever heard of “transfer-learning”, this is what it is about.

How to Fine-Tune GPT-J?

Even if fine-tuning GPT-J is much easier than training the model from scratch, it is still a challenge for several reasons:

  • It is a very compute intensive operation that can be painfully long on GPU. The best option is to use a TPU for that.
  • The fine-tuning process takes some practice, some parameters should be tweaked, and you can easily end up with a suboptimal accuracy.
  • Once you have your brand new fine-tuned model it’s not over: you have to deploy it and reliably use it in production.

If you want to fine-tune GPT-J by yourself, here is how you could do it:

  • Follow the how-to from the Mesh Transformer Jax team here.
  • Make sure to perform the fine-tuning on a TPU V3 as you will run out of memory on a TPU V2. You can ask for a free TPU access for 1 month thanks to the TPU research cloud (TRC) program.
  • Don’t forget to turn your result into a slim GPT-J version that is more suited for production inference.

Conclusion

GPT-J is an amazing Natural Language Processing model. Mix it with few-shot learning and fine-tuning, and you will get a state of the art AI application!

Storing Stripe Payment Data in the Database

It’s hard to know whether Stripe payment data should be stored in the local database or not. Many developers are wondering which kind of Stripe data they should save in their local DB. They might sometimes even be tempted not to store any data locally and only rely on Stripe API calls.

Let me show you how we’re dealing with this problem at NLP Cloud, and why.

NLP Cloud is a Natural Language Processing API based on spaCy and HuggingFace transformers in order to propose Named Entity Recognition (NER), sentiment analysis, text classification, summarization, text generation, and much more. Customers are charged monthly and their payment is processed by Stripe. It is important to us that the API and the user dashboard are lightning fast, so we want to rely on the Stripe API the less we can. We also don’t want to depend too much on Stripe in case of a data loss on their end.

Typical Scenario

Here is a standard scenario for a subscription based service like we have at NLP Cloud:

  1. A customer registers to your website
  2. You save the customer in DB
  3. You create the customer in Stripe through the Stripe API
  4. You save the Stripe customer ID in the local DB

You cannot really do better than this.

Now the fun begins.

For example you might want to keep track of your customer’s subscription in order to grant him access to some paid features, to more API requests, or, if he’s a free user, disable some features (for example). Sometimes, you are going to update a subscription by yourself, but sometimes Stripe will (for example if a payment fails multiple times, Stripe will mark the subscription as canceled). When a subscription is updated by Stripe, they will let you know through a webhook call. If you are using Stripe Portal, everything is going to be handled on the Stripe end, and any change is going to be sent to you through webhooks.

So dealing with Stripe is a bidirectional thing: sometimes you initiate a change, sometimes they do. It is easy to get out of sync!

Speed Considerations

One might be tempted to delegate as much information as possible to Stripe so Stripe is the single source of truth. In such a situation, you would need to make a call to the Stripe API very often. This is a bad idea.

For example, if your customer subscription data is in Stripe only, you will first need to call Stripe before allowing a customer to access or not a specific paid feature. It adds critical milliseconds to your website’s response time, which is not good. And if Stripe is temporarily lagging, your website is lagging too. In case of an API, this is out of the question: you cannot slow down an API call because you’re waiting for Stripe to return.

Disaster Recovery Considerations

Delegating information to Stripe without local data is risky. Even if Stripe is a solid player, you can never be sure that they’re not going to lose your data.

From a safety standpoint, it is paramount to store the customers’ data locally so you can start again you service somewhere else in case of a disaster, without losing any customer subscription (which would be terrible).

Caching Everything Locally

The strategy we follow at NLP Cloud is to cache everything related to Stripe customers and Stripe subscription locally. It is simpler than it might sound thanks to the fact that modern databases like PostgreSQL can store JSON data seamlessly with almost no performance tradeoffs.

Basically, what you should do - if you want to follow this strategy - is the following:

  1. When you create a Stripe customer with their API, save the Stripe JSON response in a JSON DB field (with PostgreSQL, use the JSONB type)
  2. When you create a Stripe subscription for this customer, do the same
  3. Whenever you need to access Stripe customer or subscription information, just query the customer or the subscription DB fields

Here is an example of data INSERT in a PostgreSQL JSONB field:

CREATE TABLE customers (  
  id serial NOT NULL,
  stripe_customer jsonb
  stripe_subscription jsonb
);
INSERT INTO customers VALUES (1, '{id:1, ...}', '{id:1, ...}');

And here is how you could retrieve the Stripe subscription id for example:

SELECT stripe_subscription->'id' AS id FROM customers;  

2 fields in the DB and that’s it! No need to create a bunch of new fields for every customer fields and subscription fields.

Staying in Sync

In order to make sure that your local cache is perfectly in sync with Stripe you should properly listen to Stripe webhooks.

Every time you get a Stripe webhook about a customer or a subscription, update the customer field or the subscription field in DB.

If you really want to be safe, you should also be prepared for potential Stripe webhooks failures. In that case, the best strategy would be to proactively poll Stripe customers and subscription on a regular basis, in order to make sure you never end up out of sync.

Conclusion

As you can see, it is quite easy to create both a simple and robust Stripe local cache. This strategy saves a lot of development time, it is fast, safe in case of Stripe failure, and you no longer have to wonder which Stripe fields you need to store locally or not.

I hope you found this useful. If you have feedbacks, or if you think of a better strategy, please let me know!

Zero-shot learning in Natural Language Processing for text classification

What is zero-shot learning, and how can it be effectively applied, in Natural Language Processing, to text classification, thanks to Hugging Face Transformers?

What is zero-shot learning

Thanks to the recent state-of-the-art transformer-based Natural Language Processing models, zero-shot learning has gained a lot of popularity in the Natural Language Processing world. The idea is that a model can now recognize some classes, even if it has not been trained for that.

This is what human beings naturally do. For example if your kid knows what a camel is, you just need to tell him that there is another animal called dromedary, very similar to a camel, except it has 1 hump on its back instead of 2! Next time your kid sees a picture of a dromedary, he will know what it is while it is the first time he sees one!

Zero-shot techniques associate observed and non observed classes through some form of so-called “auxiliary” information, that encodes distinguishing properties of objects. That has been a very popular technique in computer vision for a long time, that is now more and more used in Natural Language Processing.

Zero-shot learning and text classification

Zero-shot learning works great for text classification. Text classification is about applying one or more categories to a piece of text (space, business, sport, etc.).

Until recently, text classification models could only categorize pieces of text with a predefined number of candidate categories. These categories had to be set in advance during training. This was painful because it meant that, every time you wanted to add a category, you had to re-train your model with more examples.

Since the creation of much bigger Natural Language Processing models (most of the time based on Transformers), it has been possible to train the models only on a specific list of categories, and then let users create new categories on the fly without having to re-train the model.

For example, let’s say that your zero-shot text classification model was trained to recognize only 3 categories: space, nature, and sport. You can still use it to categorize texts for other categories, like for example business, food, or science.

This is a very powerful technique that allows a lot of flexibility while still giving great results.

Best zero-shot classification models

There are excellent open-source Natural Language Processing models out there, based on Hugging Face Transformers, that work really well for zero-shot text classification.

At NLP Cloud I selected these 2 models that are, in my opinion, the best state-of-the-art models for zero-shot text classification for the moment:

  • Facebook’s Bart Large MNLI: this model is great for zero-shot text classification in English. It works with a potentially high number of candidate categories, while remaining fast and accurate.
  • Joe Davison’s XLN Roberta Large XNLI: this model is perfect for non-English languages. It works in more than 100 languages, and it is especially accurate in English, French, Spanish, German, Greek, Bulgarian, Russian, Turkish, Arabic, Vietnamese, Thai, Chinese, Hindi, Swahili, Urdu. It more or less has the same latency as Bart Large MNLI.

Even if their accuracy is impressive and their latency is quite good, these 2 models still are computation intensive models, and latency can easily increase if the text you want to analyze gets too big or the number of candidate categories is too high. If accuracy is not your primary concern, and you would prefer a faster and less resource-intensive model, you could easily select another model. For example, distilled versions of Bart exist, called “DistilBart”, and they are perfect for this.

Conclusion

Zero-shot learning and few-shot learning are modern techniques that appeared with the creation of big Natural Language Processing models. They give a lot of flexibility and make Natural Language Processing more and more impressive!