Few-shot NER: Entity Extraction Without Annotation And Training Based On GPT

Pre-trained entity extraction models based on spaCy or NLTK give great results but require a tedious annotation and training process in order to detect non-native entities like job titles, VAT numbers, drugs, etc. Thanks to large language models like GPT-3, GPT-J, and GPT-NeoX, it is now possible to extract any type of entities thanks to few-shot learning, without any annotation and training. In this article, I’m showing how to do that.

NER (entity extraction) is basically about extracting structured information from an unstructured text.

NER with spaCy and NLTK: the traditional way

spaCy has pretty much become the de facto standard for NER these last years (see the spaCy website). spaCy is a very attractive framework because it is easy to use, and its speed makes it well suited for production use.

spaCy is a Python natural language processing framework that proposes many pre-trained models in multiple languages, so it is easy to extract several entity types (companies, cities, addresses, dates, etc.) in your own language without having to train your own model.

NLTK is also an interesting choice for entity extraction with Python, but it proposes less entities by default, and in general NLTK is not recommended for production (it is more of an educational and research framework).

However you will quickly hit a limit with these frameworks: the number of natively supported entities is limited. Most companies want to leverage NER in order to extract specific business information like person information, financial data, medical treatments, etc. Of course, these entities are not supported by default by the spaCy pre-trained models, so in order to achieve this, you have to create your own dataset and train your own model out of it.

Training your own spaCy model is a long and tedious annotation process: one or several persons need to collaborate in order to create a huge set of good examples, and annotate them. A very large volume of examples is required in order for the model to properly learn. Good annotation tools exist (like Prodigy, by spaCy), but it still remains a painful task that causes many NLP projects to abort.

Annotation illustration

Annotation illustration

Good news: with the rise of large language models like GPT-3, GPT-J, and GPT-NeoX, it is now possible to extract any entities without annotating and training a new model!

Text Generation with GPT-3, GPT-J, and GPT-NeoX

Large language models for text generation have started appearing recently with GPT-3 (see more about GPT-3 on OpenAI’s website). When OpenAI released their GPT-3 model, made up of 175 billion parameters, it was a revolution because it paved the way for many cutting-edge AI applications based on natural language processing without requiring any additional training.

The initial goal of GPT models like GPT-3 is to generate text: simply give an input to the model and let it generate the rest for you. Based on text generation, pretty much any natural language processing use case can be achieved: classification, summarization, conversational AI, paraphrasing… and of course entity extraction!

Since GPT-3 is not an open-source model, the open-source community has worked on alternatives to GPT-3 and there are now 2 great open-source equivalents: GPT-J and GPT-NeoX. They are still not as big as GPT-3, but no doubt that it’s only a matter of time before the open-source community catches up with OpenAI.

Properly leveraging these models requires a new technique called “few-shot learning”.

Few-shot Learning

These large GPT models are so big that they can very quickly learn from you.

Let’s say you want GPT-3 to generate a short product description for you. Here is an example without few-shot learning:

Generate a product description containing these specific keywords: t-shirt, men, $50

The response you will get will be useless. It could be something like this for example:

Generate a product description containing these specific keywords: t-shirt, men, $50 and short.

The product description needs to be a few words long. Don’t use plurals, use the keywords in the order they are

Good news: you can achieve much better results by simply giving a couple of examples to the model!

Generate a product description containing specific keywords.

Keywords: shoes, women, $59
Result: Beautiful shoes for women at the price of $59.
###
Keywords: trousers, men, $69
Result: Modern trousers for men, for $69 only.
###
Keywords: gloves, winter, $19
Result: Amazingly hot gloves for cold winters, at $19.
###
Keywords: gpu, gaming, $1499
Result:

The result will be something like this:

Generate a product description containing specific keywords.

Keywords: shoes, women, $59
Result: Beautiful shoes for women at the price of $59.
###
Keywords: trousers, men, $69
Result: Modern trousers for men, for $69 only.
###
Keywords: gloves, winter, $19
Result: Amazingly hot gloves for cold winters, at $19.
###
Keywords: gpu, gaming, $1,499
Result: The best gaming GPU on the market, at the price of $1,499 only.

As you can see, the response from the model is now perfectly on purpose, thanks to the 3 examples I first gave it. Yet, this model was never trained on this kind of product description generation task. This is what the “few-shot learning” technique is about: you perform “transfer learning” on the fly with a couple of examples only. In order to achieve this kind of result, you usually expect to train a natural language processing model with tons of examples, but not here.

Entity Extraction With Few-shot Learning

Now I will perform entity extraction thanks to few-shot learning.

Let’s say that you want to extract job titles from websites. Simply give a couple of job title extraction examples before making your actual request:

Extract job titles from the following sentences.

Sentence: John Doe has been working for Microsoft for 20 years as a Linux Engineer.
Job title: Linux Engineer
###
Sentence: John Doe has been working for Microsoft for 20 years and he loved it.
Job title: none
###
Sentence: Marc Simoncini | Director | Meetic
Job title: Director
###
Sentence: Franck Riboud was born on 7 November 1955 in Lyon. He is the son of Antoine Riboud, who transformed the former European glassmaker BSN Group into a leading player in the food industry. He is the CEO at Danone.
Job title: CEO
###
Sentence: Damien is the CTO of Platform.sh, he was previously the CTO of Commerce Guys, a leading ecommerce provider.
Job title:

The result will be the following:

Extract job titles from the following sentences.

Sentence: John Doe has been working for Microsoft for 20 years as a Linux Engineer.
Job title: Linux Engineer
###
Sentence: John Doe has been working for Microsoft for 20 years and he loved it.
Job title: none
###
Sentence: Marc Simoncini | Director | Meetic
Job title: Director
###
Sentence: Franck Riboud was born on 7 November 1955 in Lyon. He is the son of Antoine Riboud, who transformed the former European glassmaker BSN Group into a leading player in the food industry. He is the CEO at Danone.
Job title: CEO
###
Sentence: Damien is the CTO of Platform.sh, he was previously the CTO of Commerce Guys, a leading ecommerce provider.
Job title: CTO

As you noticed, I have to be smart about how I’m making my few-shot examples. It can happen that no job title is found at all, which is why I created an example returning “none” (it avoids false positives). Maybe you want to extract several job titles at the same time? In that case it’s important to create examples returning several job titles too (comma separated job titles for example).

You will get even better results by adding even more examples. And it’s important that your examples are as close as possible to your actual final request. For example, if you know you’re going to analyze entire paragraphs instead of mere sentences, it’s best to create examples with paragraphs too.

Here is the same job-title request through the NLP Cloud Python client, using GPT-J:

import nlpcloud

client = nlpcloud.Client("gpt-j", "<your API token>", gpu=True)
client.generation("""Extract job titles from the following sentences.

Sentence: John Doe has been working for Microsoft for 20 years as a Linux Engineer.
Job title: Linux Engineer
###
Sentence: John Doe has been working for Microsoft for 20 years and he loved it.
Job title: none
###
Sentence: Marc Simoncini | Director | Meetic
Job title: Director
###
Sentence: Franck Riboud was born on 7 November 1955 in Lyon. He is the son of Antoine Riboud, who transformed the former European glassmaker BSN Group into a leading player in the food industry. He is the CEO at Danone.
Job title: CEO
###
Sentence: Damien is the CTO of Platform.sh, he was previously the CTO of Commerce Guys, a leading ecommerce provider.
Job title:""",
top_p=0.1,
length_no_input=True,
remove_input=True,
end_sequence="###",
remove_end_sequence=True
)

The result will be: CTO

Let me give you a quick explanation about the text generation parameters I just used.

I set a very low top p value because I don’t want GPT-J to create too original results: I just want it to stick to what it saw in your request.

“length_no_input” means that the maximum length value should not take the input text into account.

“remove_input” means that the input text should be removed from the result.

“end_sequence” means that when the model meets this character, it should stop generating text. As in my few-shot examples I added “###” at the end of each answer, the model will automatically generate “###” after generating the response and it will stop there.

“remove_end_sequence” means that I want to remove “###” from the response.

Performance Considerations

Performing entity extraction with a GPT model gives a lot of freedom as any new entity can be extracted on the fly even if the model wasn’t trained for that!

However it comes at a cost: these large language models are huge and relatively slow.

For example, if you want to use GPT-J or GPT-NeoX it will require a huge GPU with a lot of VRAM like an NVIDIA RTX A6000 or A40. And there will be some latency (extracting an entity takes around 500ms). On the contrary, spaCy or NLTK will be much faster and less costly from an infrastructure standpoint.

Conclusion

In 2022, it is possible to perform advanced NER very easily without any annotation and training! It will greatly help companies deliver their entity extraction projects faster, and it also allows for more cutting edge applications based on natural language processing.

However large language models like GPT-3, GPT-J, and GPT-NeoX are costly, so you should not underestimate the infrastructure costs involved.

I hope this article will help you save time and money!

Top 9 Natural Language Processing Frameworks, Services And Actors In 2022

The natural language processing market is booming and many new tools have recently appeared in the ecosystem. Here are the libraries, frameworks, languages, services, and actors you should know about in order to integrate text understanding and text generation in your project in 2022.

Frameworks, Services, and Actors

  1. Python The best programming language for NLP
  2. Hugging Face Hub A central repository for all the models
  3. OpenAI The company behind GPT-3
  4. Deepspeed Parallelize your training and inference
  5. Big Science Hugging Face’s AI research group
  6. spaCy A fast and production-ready framework for NLP
  7. HF Transformers An advanced framework for NLP
  8. HF Tokenizers An advanced set of tokenizers for NLP
  9. NLTK A research and education framework for NLP

1. Python

Python has been the de facto standard language in data science for many years. If you are working on a natural language processing project, there will most likely be some Python code somewhere.

Python is a very expressive and simple high-level language that makes it perfectly suited for machine learning applications. But even more importantly, Python benefits from a comprehensive ecosystem of libraries and frameworks that make data scientists’ lives easier.

Whether you’re working on a research project or a production project, whether you’re training new models or using them for inference, you will most likely have to use Python. If you absolutely need to use another language, you might find nice libraries in other languages too but only for basic use cases (for more advanced use cases, the solution will be to adopt a microservices strategy and use a REST API).

2. Hugging Face Hub

Hugging Face Hub is a central repository that stores most of the open-source natural language processing models.

On Hugging Face, it is easy to discover new AI models but also upload and share yours. It is also a great place to browse and find datasets for your next project. Models and datasets can be easily downloaded and used through their Transformers framework (see below).

Hugging Face’s vision is to “democratize” natural language processing and become the “Github of machine learning”.

3. OpenAI

OpenAI is the company behind GPT-3, the most advanced language AI model ever created.

The first 2 versions of this model (GPT and GPT-2) were open-source, but OpenAI decided that GPT-3 would not be open-source anymore. If you want to use GPT-3, you need to subscribe to the OpenAI API. Only Microsoft has access to the source code of GPT-3 as they purchased an exclusive license.

The GPT models are text generation AI models that are very good at writing text like a human. It is actually quite hard for a human to detect whether a piece of text was written by a real person or by GPT-3…

It cost OpenAI millions of dollars in order to design and train this new AI. If you want to use it, you will have to go through a demanding validation process as OpenAI doesn’t allow all types of applications to use their model.

New open-source models are now being released in order to catch up with OpenAI like GPT-J and GPT-NeoX.

4. Deepspeed

Deepspeed is an open-source framework by Microsoft that focuses on model parallelization.

What does it mean exactly?

AI models are getting bigger and bigger (see GPT-3, GPT-J, GPT-NeoX 20B, T0, Fairseq 13B…). These huge models open the door to tons of new applications, but they are also very hard to run.

Training these models, and reliably running them in production for inference, can either be done through vertical scalability (using huge GPUs like NVIDIA A100 or Google TPUs) or horizontal scalability (using several small GPUs in parallel).

The 2nd approach is more and more popular as it is cheaper and it scales better. Nevertheless, performing distributed training and inference is far from easy, which is why Deepspeed really helps.

Deepspeed was originally targeted to training tasks, but it is now more and more used for inference as it is easy to use and integrates with Hugging Face Transformers (see below).

5. Big Science

Big Science is a collective of researchers and companies who work on big language models.

Their first workshop produced an AI model called T0 that performs very well at understanding human instructions.

They are now working on much bigger models: their goal is to create open-source multilingual AI models that are bigger and more advanced than GPT-3.

6. spaCy

spaCy is a Python natural language processing framework that is perfectly suited for production: it is both fast and easy to play with.

This is a framework maintained by a German AI company called Explosion AI.

spaCy is very good at Named Entity Recognition (also known as entity extraction), and in around 50 different languages. They provide pre-trained models and you can easily create your own models through annotated examples.

7. HF Transformers

The Transformers framework was released by Hugging Face a couple of years ago. Most of the advanced natural language processing models are now based on Transformers.

This is a Python module that is based on PyTorch, Tensorflow, and Jax, that can be used either for training or inference.

Hugging Face Transformers make it very easy to download and upload models to the Hugging Face Hub.

8. HF Tokenizers

The tokenizers library from Hugging Face is a set of advanced natural language processing tokenizers, used by transformer-based models.

Tokenization is about splitting an input text into small words or subwords that can then be encoded and processed by the AI model.

Tokenization might sound like a detail, but it is not. It is actually a critical part of natural language processing, and using the right tokenizer makes a huge difference in terms of quality of the results and performances.

9. NLTK

NLTK stands for Natural Language Toolkit. It is a Python framework that has been around for many years and that is great for research and education.

NLTK is not a production oriented framework, but it is perfect for data scientists trying to ramp up on natural language processing.

Conclusion

The natural language processing field has considerably evolved in 2021. Today, more and more companies want to use language AI models in production, and it is interesting to see that in 2022 the ecosystem has pretty much nothing to do with what it was 5 years ago.

Libraries and frameworks are getting more and more advanced, and the creation of large language models like GPT-3 raises new interesting challenges.

Can’t wait to see what 2023 will be like!

Multilingual Natural Language Processing: NLP in non-English languages

Performing natural language processing in non-English languages is a challenge. Today, it is possible to get great results with multilingual natural language processing. At last, anyone can perform natural language processing in French, Japanese, Spanish, Russian, Chinese, German… and much more.

Why Multilingual Natural Language Processing Is A Challenge

Almost 7000 different languages are spoken in the world today! Each language has its own rules and some languages can work very differently. For example French, Spanish and Italian are very similar, but they have nothing to do with Asian languages based on ideographs or symbols like Chinese and Japanese.

The consequence is that different techniques have to be used to create language models that are able to deal with all these languages.

To make it short, different languages might require different vector spaces, even if some pre-trained language embeddings already exist. This is an active research field.

So what are the solutions?

Training Specific Non-English Models

A first approach is to train a model for a specific language. For example, several new versions of BERT have been trained in various languages. German BERT, from Deepset AI, is a good example of a new version of BERT trained on the German language from scratch: see German BERT here.

The problem is that this technique doesn’t scale well. Training a new model takes time and costs a lot of money. Training several models is still affordable for small models like spaCy, and Explosion AI (the company behind spaCy) does a great job at maintaining several pre-trained models in many languages: see more here. But natural language processing models are getting bigger and bigger, and training these big models is very costly. For example, training the brand new GPT models (GPT-3, GPT-J and GPT-NeoX) took several weeks and cost millions of dollars. Training new versions of these models is not something everybody can do.

It also doesn’t scale well from an inference perspective. If a company needs to use natural language processing in production in several languages, it will have to maintain several models and provision several servers and GPUs. It can prove to be extremely costly. This is one of the reasons why, at NLP Cloud, I’m trying to avoid this strategy as much as possible.

Multilingual Models

A second approach is to leverage multilingual models.

These last years, new multilingual models have appeared and have proved to be very accurate. Sometimes even more accurate than specific non-English models. The most popular ones are mBERT, XLM, and XLM Roberta. XLM Roberta seems to be the most accurate multilingual model, and is performing very well on the XNLI evaluation dataset (a series of evaluations to assess the quality of multilingual models).

Some very good pre-trained models based on XLM Roberta are available. For example, for text classification in many languages, the best one is XLM Roberta Large XNLI.

For the moment there is no good multilingual model for text generation. For example GPT is excellent in English and not so bad in several non-English languages, but far from impressive. Big Science is currently working on very large multilingual text generation models. It seems promising! See more here.

Big Science just announced a multilingual 176 billion parameters transformers model.

Translation To The Rescue

The last strategy is to use translation. The idea is that you should translate your non-English content to English, send the English content to the model, and translate the result back to your original language.

This technique might sound like a hack, but it has advantages. Maintaining a translation workflow might be less expensive than training dedicated models, and all the languages in the world can be easily supported.

These last years, advanced translation models based on deep learning have been created. They are both fast and give very good results. For example, Helsinki NLP released a series of translation models based on deep learning.

Adding translation to your workflow will increase the overall response time though. So it might not be suited if you’re looking for very fast results.

Conclusion

Multilingual natural language processing is not a solved problem, but a lot of progress has been made these last years. It is now possible to perform natural language processing in non-English languages with very good results, thanks to specific models, multilingual models, and translation.

Deploying GPT-NeoX 20B In Production And a Focus On Deepspeed

Deploying GPT-NeoX 20B in production is a challenge and I learned it the hard way at NLP Cloud. In this article I’m telling you more about several tricks related to using GPT-NeoX 20B, and especially how to deal with Deepspeed in production.

GPT-NeoX 20B

GPT-NeoX 20B is the biggest open-source Natural Language Processing model as of this writing.

It was released by EleutherAI 2 weeks ago. It was trained on 20 billion parameters, after a 1 year hard work full of challenges. One of their main difficulties seemed to be the ability to set up a proper parallel architecture so that the model can be efficiently trained on multiple GPUs.

Their previous model, GPT-J, was trained on Google TPUs and was designed to be used on TPUs. GPT-NeoX 20B’s inner architecture is radically different and is made to be used on GPUs. The idea is that it should be the first of a series of even bigger models (the goal here is to catch up with GPT-3).

GPT-NeoX 20B is a text generation model, meaning that it can write text for you and actually achieve almost any Natural Language Processing use case with a great accuracy: blog post generation, chatbots, text classification, sentiment analysis, keywords extraction, code generation, entity extraction, intent classification, question answering, and more…

No doubt many researchers and companies will leverage this new model and get great results. But there is a challenge: how to deploy GPT-NeoX 20B?

Hardware Requirements

The first challenge that one faces when trying to deploy GPT-NeoX 20B in production, is the advanced hardware it requires.

It was still possible to deploy GPT-J on consumer hardware, even if it was very expensive. For example, you could deploy it on a very good CPU (even if the result was painfully slow) or on an advanced gaming GPU like the NVIDIA RTX 3090. But GPT-NeoX 20B is so big that it’s not possible anymore.

Basically GPT-NeoX requires at least 42GB of VRAM and 40 GB of disk space (and yes, this is the slim fp16 version). Few GPUs match these requirements. The main ones are the NVIDIA A100, A40, and RTX A6000.

Not only are these GPUs very expensive, but it’s also hard to get your hands on one of them these days because of the global semiconductor shortage.

The best solution here is to go for a multi-GPU architecture.

Multi-GPU With Deepspeed

If you can’t fit your model into one single GPU, you can try to split it into several GPUs.

It’s an interesting option for 2 reasons. First, scaling an infrastructure horizontally is often cheaper than scaling vertically. It’s true for servers and it’s true for GPUs too. Secondly, it’s easier to get your hands on several small GPUs like the NVIDIA Tesla T4 than bigger GPUs like the NVIDIA A40.

Unfortunately, splitting a machine learning model into several GPUs is a technical challenge. Hugging Face made a great article about model parallelism and the choices you have. Read it here. But luckily, EleutherAI designed GPT-NeoX 20B so that it is easily parallelized on several GPUs, whether it’s for training or inference.

The GPT-NeoX architecture is based on Deepspeed. Deepspeed is a framework from Microsoft that was originally designed to parallelize trainings among several GPUs, and it is more and more used for inference too. EleutherAI did all the hard work, so parallelizing GPT-NeoX is as simple as changing a number in a configuration file.

GPT-NeoX parallelism setting

However, deploying Deepspeed in production for online inference through an API is hard. Deepspeed was not designed to be easily integrated into web servers. At NLP Cloud, I learned it the hard way, and after some hard work I managed to get Deepspeed and GPT-NeoX to work behind the NLP Cloud API.

Usage Tricks

So let’s assume you managed to provision the proper hardware and correctly deploy GPT-NeoX 20B with Deepspeed. There are now a couple of caveats you should be aware of.

First, compared to GPT-J, the parameters (top k, top p, and temperature) don’t have the same effects on the model. So if you managed to find a good configuration for GPT-J, don’t take it for granted: you will have to make new tests with GPT-NeoX.

Last of all, even if the input size can go up to 2048 tokens, it will require more memory than the base 42GB mentioned above…

Batch Inference?

GPT models are quite slow, and GPT-NeoX 20B is no exception. So in order to improve the throughput of your application, you might want to work on a batch inference solution.

For the moment I haven’t come up with a good solution for that at NLP Cloud.

The GPT-NeoX code is made so that one can perform several inferences at the same time within one single request. But in my tests, the response time grew linearly with the number of inferences, which kind of defeats the purpose of batch inference…

Conclusion

GPT-NeoX 20B is definitely hard to deploy in production. The quality of text generation is amazing, but few will have the capacity to actually install this model.

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.