How to Install and Deploy LLaMA 3 Into Production?

The LLaMA 3 generative AI model was released by Meta a couple of days ago, and it already shows impressive capabilities.

Learn how to install and deploy LLaMA 3 into production with this step-by-step guide. From hardware requirements to deployment and scaling, I cover everything you need to know for a smooth implementation.

Introduction to LLaMA 3

Meta has introduced initial versions of their Llama 3 open-source AI model, which can be utilized for text creation, programming, or chatbots. Furthermore, Meta announced its plans to incorporate LLaMA 3 into its primary social media applications. This move aims to compete with other AI assistants, such as OpenAI’s ChatGPT, Microsoft’s Copilot, and Google’s Gemini.

Similar to Llama 2, Llama 3 stands out as a freely accessible large language model with open weights, offered by a leading AI company (although it doesn’t qualify as “open source” in the conventional sense).

Currently, Llama 3 can be downloaded for free from Meta’s website in two different parameter sizes: 8 billion (8B) and 70 billion (70B). Users can sign up to access these versions. Llama 3 is offered in two variants: pre-trained, which is a basic model for next token prediction, and instruction-tuned, which is fine-tuned to adhere to user commands. Both versions have a context limit of 8,192 tokens.

In an interview with Dwarkesh Patel, Mark Zuckerberg, the CEO of Meta, mentioned that they trained two custom-built models using a 24,000-GPU cluster. The 70B model was trained with approximately 15 trillion tokens of data, and it never reached a point of saturation or a limit to its capabilities. Afterward, Meta decided to focus on training other models. The company also revealed that they are currently working on a 400B parameter version of Llama 3, which experts like Nvidia’s Jim Fan believe could perform similarly to GPT-4 Turbo, Claude 3 Opus, and Gemini Ultra on benchmarks like MMLU, GPQA, HumanEval, and MATH.

According to Meta, Llama 3 has been assessed using various benchmarks, including MMLU (undergraduate level knowledge), GSM-8K (grade-school math), HumanEval (coding), GPQA (graduate-level questions), and MATH (math word problems). These benchmarks demonstrate that the 8B model outperforms open-weights models such as Google’s Gemma 7B and Mistral 7B Instruct, and the 70B model is competitive against Gemini Pro 1.5 and Claude 3 Sonnet.

Meta reports that the Llama 3 model has been improved with the ability to comprehend coding, similar to Llama 2, and for the first time, it has been trained using both images and text. However, its current output is limited to text.

LLaMA 3 Benchmarks

LLaMA 3 Hardware Requirements And Selecting the Right Instances on AWS EC2

As many organizations use AWS for their production workloads, here is how to deploy LLaMA 3 on AWS EC2.

There are multiple obstacles when it comes to implementing LLMs, such as VRAM (GPU memory) consumption, inference speed, throughput, and disk space utilization. In this scenario, I need to make sure that I allocate a GPU instance on AWS EC2 with sufficient VRAM capacity to run the models.

LLaMA 3 8B requires around 16GB of disk space and 20GB of VRAM (GPU memory) in FP16. You could of course deploy LLaMA 3 on a CPU but the latency would be too high for a real-life production use case. As for LLaMA 3 70B, it requires around 140GB of disk space and 160GB of VRAM in FP16.

Getting your hands on 20GB of VRAM for LLaMA 3 8B is fairly easy. I recommend that you provision an NVIDIA A10 GPU: this GPU comes with 24GB of VRAM and it is a fast GPU based on the Ampere platform. On AWS EC2, you should select a G5 instance in order to provision an A10 GPU. A g5.xlarge will be enough.

Deploying the LLaMA 3 70B model is much more challenging though. No GPU has enough VRAM for this model so you will need to provision a multi-GPU instance. If you provision a g5.48xlarge instance on AWS you will get 192GB of VRAM (8 x A10 GPUs), which will be enough for LLaMA 3 70B.

In such a configuration, you can expect the following latencies (response times): 50 tokens generated in 1 second for LLaMA 3 8B, and 50 tokens generated in 5 seconds for LLaMA 3 70B.

In order to decrease the operating cost of these models and increase the latency, you can investigate quantization techniques but be aware that such optimizations can harm the accuracy of your model. Quantization is out of the scope of this article.

In order to provision such instances, log into your AWS EC2 console, and launch a new instance: select the NVIDIA deep learning AMI, on a g5.xlarge or g5.48xlarge instance. Do not forget to provision enough disk space too.

Deep Learning AMI on G5 instance on AWS

Production Inference With vLLM

vLLM is a library designed for rapid and easy LLM inference and deployment. Its efficiency is attributed to various sophisticated methods, including paged attention for optimal management of attention key and value memory, real-time processing of incoming queries in batches, and personalized CUDA kernels.

In addition, vLLM provides a high degree of adaptability by employing distributed computation (using tensor parallelism), real-time streaming, and compatibility with both NVIDIA and AMD graphics cards.

Specifically, vLLM will greatly aid in deploying LLaMA 3, so I can use AWS EC2 instances equipped with several compact NVIDIA A10 GPUs. This is advantageous over using a single large GPU, such as the NVIDIA A100 or H100. Furthermore, vLLM will significantly enhance the model’s efficiency through continuous batch inference.

Setting up vLLM is quite simple. Establish an SSH connection to the AWS instance you just created, and install vLLM using pip:

pip install vllm

Since I plan to perform distributed inference using vLLM on 8 x A10 GPUs, the installation of Ray is required as well:

pip install ray

In case you encounter compatibility problems while installing, it may be simpler for you to compile vLLM from the source or use their Docker image: have a look at the vLLM installation instructions.

Launch the Inference Server

Here is the Python inference script:

from vllm import LLM

# Use LLaMA 3 8B on 1 GPU
llm = LLM("meta-llama/Meta-Llama-3-8B-Instruct")

# Use LLaMA 3 70B on 8 GPUs
# llm = LLM("meta-llama/Meta-Llama-3-70B-Instruct", tensor_parallel_size=8)

print(llm.generate("What are the most popular quantization techniques for LLMs?"))

You can run the above script. If this is the first time you run this script, you will need to wait for the model to be downloaded and loaded on the GPU, then you will receive something like this:

The most popular quantization techniques for Large Language Models (LLMs) are:
1. Integer Quantization
2. Floating-Point Quantization
3. Mixed-Precision Training
4. Knowledge Distillation

It’s quite simple to understand. You simply need to adjust the tensor_parallel_size according to the number of GPUs that you possess.

The next step is an inference server capable of managing numerous requests and executing simultaneous inferences. To begin, start the server:

For LLaMA 3 8B:

python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-8B-Instruct

For LLaMA 3 70B:

python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-70B-Instruct
--tensor-parallel-size 8

It should take up to 1 minute for the model to load on the GPU. Then you can start a second terminal and start making some requests:

curl http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{
    "model": "meta-llama/Meta-Llama-3-8B-Instruct",
    "prompt": "What are the most popular quantization techniques for LLMs?"
}'

You now have a proper production ready inference server that can handle many parallel requests thanks to continuous batching. At some point, if the number of requests is too high, the GPU will be overloaded though. In that case you will need to replicate the model on several GPU instances and load balance your requests (but this is out of the scope of this article).

Conclusion

As you can see, deploying LLaMA 3 into production does not require any complex code thanks to inference servers like vLLM.

Provisioning the right hardware is challenging though. First because these GPUs are very costly, but also because of the current global GPU shortage. If this is your first time trying to provision a GPU server at AWS you might not have the permission to create a GPU server. In that case you will need to contact support and explain your use case. In this article I used AWS EC2 but other vendors are available of course (Azure, GCP, OVH, Scaleway…).

Empowering Social Listening with AI: The KWatch.io Story Powered by NLP Cloud

In today’s digital age, the power of social listening cannot be underestimated for businesses seeking to understand and engage with their audience in real-time. Through its integration with NLP Cloud, KWatch.io is now monitoring and analyzing online sentiment across various social media platforms. In this article, I will explore how KWatch.io leverages the cutting-edge AI capabilities of NLP Cloud to deliver advanced social listening services to its users. Learn more about KWatch.io on their website.

About Social Listening, KWatch.io and NLP Cloud

In the fast-paced digital landscape, understanding public sentiment towards brands, products, or topics as they unfold across social media has become indispensable. KWatch.io emerges as a beacon in this realm, harnessing the advanced capabilities of NLP Cloud to not only listen but understand the nuances of online conversations, without sacrificing data privacy.

This collaboration marks a significant leap in social listening technology, offering businesses and individuals insightful, real-time analysis powered by state-of-the-art artificial intelligence. As I look at this partnership between KWatch.io and NLP Cloud, this is the story of how artificial intelligence is reshaping the way organizations monitor, analyze, and respond to the global online dialogue.

Why Monitoring Social Media is Hard

In the realm of social listening and mention tracking, the primary challenges encompass not just the sheer volume of data traversing across social media platforms like Reddit, X (formerly Twitter), and Hacker News, but also the nuanced understanding required to accurately interpret the sentiment behind this data.

Given the dynamic nature of social media, real-time monitoring becomes a pivotal need, necessitating sophisticated solutions capable of parsing and analyzing data streams with minimal latency. Traditional models often struggle with the complexities of language—slang, irony, and cultural nuances can easily skew sentiment analysis. Furthermore, the demands of this task are not static; they evolve as the digital dialogue morphs, pushing existing systems to their limits. KWatch.io faced these multifaceted challenges head-on, seeking a robust, scalable solution capable of offering precision, adaptability, and comprehensive language support to meet the needs of their diverse clientele. Their endeavor wasn’t just about tracking mentions or keywords; it involved crafting a refined lens through which the vast and varied world of social media could be interpreted accurately and in real-time, making NLP Cloud’s advanced capabilities not just advantageous but essential.

KWatch.io Monitors and Analyzes Keywords on Reddit, X (Twitter), and Hacker News

At the heart of KWatch.io’s solution lies the integration with NLP Cloud, utilizing its comprehensive suite of AI APIs to address the nuanced demands of social listening and sentiment analysis across multiple languages and platforms like Reddit, X (Twitter), and Hacker News.

Set keywords in the KWatch.io dashboard

NLP Cloud’s APIs, particularly those focusing on sentiment analysis, entity recognition, language detection, and semantic similarity, serve as the foundational technology enabling KWatch.io to monitor, analyze, and interpret vast streams of social media data in real time. The integration was methodical, involving the deployment of custom models tailored to KWatch.io’s unique requirements for monitoring specific keywords and phrases amidst the noisy backdrop of social media chatter. By leveraging NLP Cloud’s scalable infrastructure, KWatch.io managed to significantly enhance its processing capacity, achieving more accurate sentiment analysis at a fraction of the time previously required. This capability is paramount, considering the diversity and volume of data encountered across platforms such as Reddit, X (formerly Twitter), and Hacker News.

An email alert from KWatch.io

NLP Cloud facilitated a seamless integration process, offering comprehensive documentation and support, allowing KWatch.io to fine-tune the performance and accuracy of its service. This collaboration not only addressed the immediate technical needs of KWatch.io but also established a robust framework for incorporating future NLP advancements and expanding service offerings. The technical synergy between KWatch.io’s platform and NLP Cloud’s APIs underscores a forward-thinking approach to solving the complex challenges inherent in social listening and sentiment analysis, setting a new benchmark for precision and scalability in the field.

Sentiment analysis of social media posts and comments in KWatch.io

Sentiment Analysis and Categorization with Chatdolphin

KWatch.io leverages the ChatDolphin LLM on NLP Cloud for both sentiment analysis and message categorization.

This AI model is both fast, accurate, and relatively cheap, which makes it a good candidate to analyze large volumes of data.

KWatch.io also integrated other NLP Cloud’s API endpoints like the language detection endpoint and the semantic similarity endpoint.

KWatch.io to Automatically Generate Replies on Social Media

Looking ahead, the partnership between NLP Cloud and KWatch.io is poised for continued close collaboration, driven by KWatch.io’s ambitious roadmap to enrich their product with a broader spectrum of AI features.

One of the most anticipated updates in the pipeline is the capability for KWatch.io to autonomously generate and post replies on social media platforms, leveraging AI algorithms. This development represents a significant step forward in automating interactive social media monitoring and engagement tasks. It underscores KWatch.io’s commitment to pushing the boundaries of what’s possible in social listening technology through AI. On the technical front, this involves sophisticated natural language understanding and generation models that can accurately interpret the context and sentiment of social media mentions, and craft responses that are coherent, contextually appropriate, and aligned with the user’s brand voice.

For NLP Cloud, this translates into challenges and opportunities to further optimize NLP Cloud’s infrastructure to support real-time processing at scale, enhance language models for greater accuracy and nuance in responses, and ensure seamless API integrations. As this feature evolves, both NLP Cloud and KWatch.io will be engaging deeply with technical challenges and opportunities, keeping the needs and expectations of the technically savvy audience at the forefront of development efforts.

Deploy LLaMA 2, Mistral, and Mixtral, on AWS EC2 with vLLM

In 2023, many advanced open-source LLMs have been released, but deploying these AI models into production is still a technical challenge. In this article I will show how to deploy these LLMs on AWS EC2: LLaMA 2 70B, Mistral 7B, and Mixtral 8x7B. I will use an advanced inference engine that supports batch inference in order to maximise the throughput: vLLM.

LLaMA 2, Mistral, and Mixtral

Meta has created and launched the Llama 2 series of large language models (LLMs), which includes a variety of generative text models that have been pre-trained and fine-tuned. These models vary in size, with parameters ranging between 7 billion and 70 billion.

Mistral AI, a startup co-founded by individuals with experience at Google’s DeepMind and Meta, made a significant entrance into the world of LLMs with Mistral 7B and then Mixtral 8x7B.

What makes Mistral 7B particularly impressive is its performance. In various tests, it has outperformed Llama2-13B, and even exceeded Llama1-34B in many metrics. This suggests that Mistral 7B provides similar or better capabilities with a significantly lower computational overhead. When it comes to coding tasks, Mistral 7B competes with CodeLlama 7B, and its compact size at 13.4 GB enables it to run on standard machines.

Mixtral 8x7B is an adaptable and swift model suitable for various applications. It operates at a speed that is six times faster and either meets or surpasses the performance of Llama 2 70B across all test metrics. This model supports multiple languages and possesses inherent coding capabilities. It can manage sequences up to 32k tokens in length.

All these models are open-source and you can deploy them on your own server if you manage to get access to the right hardware. Here is how to deploy them on AWS EC2 with vLLM.

Batch Inference And Multi GPU with vLLM

vLLM is a swift and user-friendly library tailored for efficient LLM inference and deployment. The performance of vLLM comes from several advanced techniques like paged attention for effective attention key and value memory management, batch processing of incoming queries in real-time, and customized CUDA kernels.

Moreover, vLLM offers good flexibility through distributed inference (via tensor parallelism), output streaming, and accommodation for both NVIDIA and AMD GPU architectures.

In particular, vLLM will be very helpful to deploy LLaMA 2, Mistral, and Mixtral, because it will allow me to deploy the models on AWS EC2 instances embedding several smaller GPUs (like the NVIDIA A10), instead of one single big GPU (like the NVIDIA A100 or H100). Also, vLLM will allow me to dramatically increase the throughput of the model thanks to batch inference.

Provision the Right Hardware on AWS EC2

Deploying LLMs is a challenge for many reasons: VRAM (GPU memory) usage, inference speed, throughput, disk space usage… Here I need to make sure that I will provision a GPU instance on AWS EC2 that has enough VRAM to run the models.

G5 instances are a good choice because they give you access to modern NVIDIA A10 GPUs, and can scale up to 192 GB of VRAM (see the g5.48xlarge instance), while remaining quite cost effective.

Mistral 7B is the easiest model to deploy as it requires around 14GB of VRAM. Then comes Mixtral 8x7B with 110GB and LLaMA 2 70B with 140GB. Here I only consider fp16, not fp32, and I am not applying any sort of quantization.

Consequently Mistral 7B can run on g5.xlarge instance but Mixtral 8x7B and LLaMA 2 70B require a g5.48xlarge instance, so I am going to provision a g5.48xlarge instance in this tutorial.

In order to provision such instances, log into your AWS EC2 console, and launch a new instance: select the NVIDIA deep learning AMI, on a g5.48xlarge instance. You will need at least 300GB of disk space.

Deep Learning AMI on a G5 instance on AWS

Install vLLM for Distributed Inference

Open an SSH connection to the newly created AWS instance, and install vLLM with pip:

pip install vllm

As I will use vLLM for distributed inference on 8 x A10 GPUs, I need to install Ray too:

pip install ray

In case of compatibility issues during the installation process, it might be easier for you to build vLLM from source or use their Docker image: see the installation documentation for more details.

Create the Inference Script

You can now create your first inference script. Create a Python file that contains the following:

from vllm import LLM

# Replace the model name with the one you want to use:
# Mixtral simple: mistralai/Mixtral-8x7B-v0.1
# Mixtral instruct: mistralai/Mixtral-8x7B-Instruct-v0.1
# Mistral 7B simple: mistralai/Mistral-7B-v0.1
# Mistral 7B instruct: mistralai/Mistral-7B-Instruct-v0.1
# LLaMA 2 70B: meta-llama/Llama-2-70b-hf
llm = LLM("mistralai/Mixtral-8x7B-Instruct-v0.1", tensor_parallel_size=8)

print(llm.generate("What is batch inference?"))

Now run your script with Python, which returns something like this:

Batch inference is the process of applying machine learning models to a batch of data inputs all at once, rather than processing each input individually in real-time. In batch inference, a large set of inputs is collected and then processed together as a group, or "batch," by the machine learning model.

Batch inference is often used in scenarios where real-time predictions are not required, and where there is a large volume of data that needs to be processed. It can be more efficient and cost-effective than real-time inference, as it allows for the efficient use of computing resources and can reduce the latency associated with processing individual inputs.

Batch inference is commonly used in applications such as image recognition, natural language processing, and predictive analytics. For example, a company might use batch inference to analyze customer data and generate insights about purchasing patterns, or to analyze sensor data from industrial equipment to identify potential maintenance issues.

In summary, batch inference is the process of applying machine learning models to a batch of data inputs all at once, as an alternative to real-time inference. It is commonly used in scenarios where real-time predictions are not required and where there is a large volume of data that needs to be processed efficiently.

As you can see this is a piece of cake. You have to adapt tensor_parallel_size depending on the number of underlying GPUs you have.

The above was a one-shot scenario. Now I want to start a proper inference server that can handle multiple requests and perform batch inference on the fly. First, start the server:

python -m vllm.entrypoints.openai.api_server \
--model mistralai/Mixtral-8x7B-Instruct-v0.1
--tensor-parallel-size 8

After some time, once the model is correctly loaded in VRAM, you can open a second shell window and make some requests:

curl http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{
    "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
    "prompt": "What is batch inference?"
}'

This will return the same result as before, but this time you can perform several requests at the same time.

Conclusion

Leveraging an advanced inference server like vLLM is beneficial if you want to maximize the utilization of your GPU and easily deploy your model on several GPUs in parallel.

As you can see, it is quite easy to deploy advanced open-source AI models like LLaMA 2, Mistral, and Mixtral, on your own server thanks to this technique.

In this tutorial I used AWS EC2 but I could have used other vendors of course. The main challenge will be the cost of the GPUs and also their availability.

Edge AI / On-Premise AI Models For Sensitive Applications

Many organizations want to integrate AI into their product or into their internal processes, but without sacrificing data privacy. For such organizations, the solution is to download and deploy AI models on their own servers instead of sending their data to the cloud. I am going to discuss this on-premise strategy in this article (also known as “edge AI”).

What Does On-Premise / Edge Computing Mean?

On-premise or edge computing refers to the practice of processing and storing data closer to its source, rather than sending it to a centralized cloud infrastructure. In this approach, computing resources are located near the systems sending the data.

In other words, on-premise and edge computing are trendy expressions that describe the fact that an application is deployed on your own servers rather than using an external cloud service like a SaaS API.

2 scenarios can be considered as on-premise: either you have your own machines hosted in your own facilities, or you leverage a cloud vendor like AWS, GCP, Azure… Strictly speaking the latter is less “on-premise” because you do not have control over the underlying server, but in general both can be considered as valid on-premise / edge solutions.

Why Is On-Premise AI / Edge AI Important?

On-premise or edge computing offers several advantages. Firstly, on-premise or edge computing dramatically enhances data privacy and security by keeping sensitive information closer to the source, reducing the risk of unauthorized access or data breaches during transportation to the cloud, and preventing cloud actors from leveraging your data for unwanted purposes. It also helps organizations comply with data regulations and laws that require local storage and processing.

Furthermore it reduces latency as data does not have to travel long distances to reach the cloud, allowing for faster processing and real-time analysis. Additionally, it minimizes dependence on network connectivity, ensuring operations can continue even when the internet is unreliable or disrupted.

AI is a very good on-premise candidate.

The first reason is that organizations tend to send extremely sensitive data to AI models. This is especially true in critical fields like medical applications, financial applications,… But not only.

The second reason is that AI actors on the market today tend to reuse customers’ data for their own business. OpenAI is a good example: for instance when organizations send data to ChatGPT, the data is scrutinized and OpenAI can reuse your data to train their own AI models. ChatGPT and GPT-4 privacy concerns are central questions that lead many organizations to focus on on-premise strategies.

How To Deploy AI Models On-Premise / At The Edge?

Deploying AI models on-premise involves setting up the infrastructure to host, manage, and serve the AI model within an organization’s own data center or managed infrastructure, rather than in the cloud.

Here are some common steps involved in the deployment of an AI model on-premise:

  • Select the right AI model for the task.
  • Evaluate hardware requirements such as CPU, GPU, and memory needs, based on the complexity and size of the AI model.
  • Set up the required deep learning frameworks (TensorFlow, PyTorch, etc.) and other libraries.
  • Convert the AI model to a format that is optimized for deployment (ONNX, TensorFlow Lite, OpenVINO, etc.), if not already in a deployable state.
  • Perform model quantization or pruning to optimize for inference speed and memory usage, if necessary.
  • Containerize the application and dependencies, which makes it easier to manage and scale.
  • Develop or adapt an inference application to handle incoming requests to the AI model. This service typically includes APIs that allow users to interact with the model to get predictions.

On-premise / Edge Computing VS Cloud Computing: Pros And Cons

On-premise or edge computing has limitations. The computing resources available at the edge are typically limited compared to cloud infrastructure, which may restrict the complexity of applications that can be deployed. Additionally, maintaining and managing distributed computing resources across multiple locations can be challenging, requiring additional investments in IT infrastructure and expertise.

In general, such a strategy is more costly than relying on a managed SaaS offering like OpenAI, Anthropic, NLP Cloud…

Last of all, data privacy is only guaranteed if the underlying on-premise infrastructure is correctly secured.

Conclusion

On-premise AI / edge AI is skyrocketing now that AI is gradually gaining traction among organizations.

Such a trend is understandable: AI is used in all sorts of critical applications that have strong privacy requirements and - by design - standard cloud actors cannot meet these requirements.

How To Develop A Token Streaming UI For Your LLM With Go, FastAPI And JS

Generative models sometimes take some time to return a result, so it is interesting to leverage token streaming in order to see the result appear on the fly in the UI. Here is how you can achieve such a text streaming frontend for your LLM with Go, FastAPI and Javascript.

What Is Token Streaming?

As a reminder, a token is a unique entity that can either be a small word, part of a word, or punctuation. On average, 1 token is made up of 4 characters, and 100 tokens are roughly equivalent to 75 words. Natural Language Processing models need to turn your text into tokens in order to process it.

When using a text generation AI model (also known as “generative” model), the response time can be quite high, depending on your hardware and the size of your model. For example, in case of a large language model (also known as “LLM”) like LLaMA 30B, deployed on an NVIDIA A100 GPU in fp16, the model generates 100 tokens in around 3 seconds. So if you expect your generative model to generate a large piece of text of hundreds or thousands of words, the latency will be high and you will need to wait maybe more than 10 seconds to get the full response.

Waiting for so long in order to get a response can be a problem from a user experience standpoint. The solution in that case is token streaming!

Token streaming is about generating every new token on the fly instead of waiting for the whole response to be ready. This is what you can see on the ChatGPT app, or on NLP Cloud’s ChatDolphin assistant for example. Words appear as soon as they are generated by the model.

Selecting An Inference Engine That Supports Token Streaming

The first step will be for you to leverage an inference engine that supports token streaming.

Here are some options you might want to consider:

Here is an example using the HuggingFace generate() method:

from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread

tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
inputs = tokenizer(["An increasing sequence: one,"], return_tensors="pt")
streamer = TextIteratorStreamer(tokenizer)

# Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
for new_text in streamer:
    print(new_text)

In this example, I generate an output with the GPT-2 model and I print each token in the console as soon as it arrives.

Streaming The Response With FastAPI

Now that you have chosen an inference engine, you will need to serve your model and return the streamed tokens.

Your model will most likely run in a Python environment so you will need a Python server in order to return the tokens and make them available through an HTTP API. FastAPI has become a de facto choice for such situations.

Here I use Uvicorn and FastAPI’s StreamingResponse in order to serve each token as soon as it is generated. Here is an example:

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread

model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")

app = FastAPI()

async def generate():
    inputs = tokenizer(["An increasing sequence: one,"], return_tensors="pt")
    streamer = TextIteratorStreamer(tokenizer)
    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()
    for new_text in streamer:
        yield new_text

@app.get("/")
async def main():
    return StreamingResponse(generate())

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

You can test your streaming server thanks to the following cURL command:

curl -N localhost:8000

You now have a working AI model that is properly returning streamed tokens.

I could directly read these streamed tokens from a client application in a browser. But I am not going to do that, for 2 reasons.

First, it is important to decouple the AI model from the rest of the stack because I do not want to restart the model every time I am going to make a small change to the API. Keep in mind that modern generative AI models are very heavy and often take several minutes to restart.

A second reason is that Python is not necessarily the best choice when it comes to building a high throughput concurrent application like I am going to do. This choice can be discussed of course and it might also be a matter of taste!

Forwarding Tokens Through A Go Gateway

As mentioned above, adding a gateway between your model and your final client is important, and Go is a good programming language for such an application. In production, you might also want to add a reverse proxy between the Go gateway and the final client, and a load balancer between your Go gateway and your AI model in order to spread the load on several replicas of your model. But it is out of the scope of this article!

The Go application will also be in charge of rendering the final HTML page.

This application makes a request to the FastAPI app, receives the streamed tokens from FastAPI, and forwards each token to the frontend using Server Sent Events (SSE). SSE is simpler than websockets because it is unidirectional. It is a good choice when you want to build an application that pushes information to a client, without listening to a potential client response.

Here is the Go code (the HTML/JS/CSS template will be shown in the next section):

package main

import (
    "bufio"
    "fmt"
    "html/template"
    "io"
    "log"
    "net/http"
    "strings"
)

var (
    templates      *template.Template
    streamedTextCh chan string
)

func init() {
    // Parse all templates in the templates folder.
    templates = template.Must(template.ParseGlob("templates/*.html"))

    streamedTextCh = make(chan string)
}

// generateText calls FastAPI and returns every token received on the fly through
// a dedicated channel (streamedTextCh).
// If the EOF character is received from FastAPI, it means that text generation is over.
func generateText(streamedTextCh chan<- string) {
    var buf io.Reader = nil

    req, err := http.NewRequest("GET", "http://127.0.0.1:8000", buf)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    reader := bufio.NewReader(resp.Body)

outerloop:
    for {
        chunk, err := reader.ReadBytes('\x00')
        if err != nil {
            if err == io.EOF {
                break outerloop
            }
            log.Println(err)
            break outerloop
        }

        output := string(chunk)

        streamedTextCh <- output
    }
}

// formatServerSentEvent creates a proper SSE compatible body.
// Server sent events need to follow a specific formatting that
// uses "event:" and "data:" prefixes.
func formatServerSentEvent(event, data string) (string, error) {
    sb := strings.Builder{}

    _, err := sb.WriteString(fmt.Sprintf("event: %s\n", event))
    if err != nil {
        return "", err
    }
    _, err = sb.WriteString(fmt.Sprintf("data: %v\n\n", data))
    if err != nil {
        return "", err
    }

    return sb.String(), nil
}

// generate is an infinite loop that waits for new tokens received 
// from the streamedTextCh. Once a new token is received,
// it is automatically pushed to the frontend as a server sent event. 
func generate(w http.ResponseWriter, r *http.Request) {
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "SSE not supported", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "text/event-stream")

    for text := range streamedTextCh {
        event, err := formatServerSentEvent("streamed-text", text)
        if err != nil {
            http.Error(w, "Cannot format SSE message", http.StatusInternalServerError)
            return
        }

        _, err = fmt.Fprint(w, event)
        if err != nil {
            http.Error(w, "Cannot format SSE message", http.StatusInternalServerError)
            return
        }

        flusher.Flush()
    }
}

// start starts an asynchronous request to the AI engine.
func start(w http.ResponseWriter, r *http.Request) {
    go generateText(streamedTextCh)
}

func home(w http.ResponseWriter, r *http.Request) {
    if err := templates.ExecuteTemplate(w, "home.html", nil); err != nil {
        log.Println(err.Error())
        http.Error(w, "", http.StatusInternalServerError)
        return
    }
}

func main() {
    http.HandleFunc("/generate", generate)
    http.HandleFunc("/start", start).Methods("POST")
    http.HandleFunc("/", home).Methods("GET")

    log.Fatal(http.ListenAndServe(":8000", r))
}

The “/home” page renders the HTML/CSS/JS page (shown later). The “/start” page receives a POST request from the JS application that triggers a request to the AI model. And the “/generate” page returns the result to the JS app through server sent events.

Once the start() function receives a POST request from the frontend, it automatically creates a goroutine that will make a request to the FastAPI app.

The generateText() function calls FastAPI and returns every token received on the fly through a dedicated channel (streamedTextCh). If the EOF character is received from FastAPI, it means that text generation is over.

The generate() function is an infinite loop that waits for new tokens received from the streamedTextCh channel. Once a new token is received, it is automatically pushed to the frontend as a server sent event. Server sent events need to follow a specific formatting that uses “event:” and “data:” prefixes, hence the formatServerSentEvent() function.

In order for SSE to be complete, you need a Javascript client that is able to listen to server sent events by subscribing to the “generate” page. See the next section to understand how to achieve that.

Receiving Tokens With Javascript In The Browser

You now need to create a “templates” directory and add a “home.html” file inside it.

Here is the content of “home.html”:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Our Streamed Tokens App</title>
</head>
<body>
    <div id="response-section"></div>    
    <form method="POST">
        <button onclick="start()">Start</button>
    </form>
</body>
<script>
    // Disable the default behavior of the HTML form.
    document.querySelector('form').addEventListener('submit', function(e) {
        e.preventDefault()
    })

    // Make a request to the /start to trigger the request to the AI model.
    async function start() {
        try {
            const response = await fetch("/start", {
            method: "POST",
            })
        } catch (error) {
            console.error("Error when starting process:", error)
        }
    }

    // Listen to SSE by subscribing to the /generate page, and
    // put the result in the #response-section div.
    const evtSource = new EventSource("generate")
    evtSource.addEventListener("streamed-text", (event) => {
        document.getElementById('response-section').innerHTML = event.data
    })
</script>
</html>

As you can see, listening to SSE in the browser is quite straightforward.

First you need to subscribe to the SSE endpoint (the “/generate” page). Then you need to add an event listener that will read the streamed tokens as soon as they are received.

Modern browsers automatically try to reconnect the event source in case of connection problems.

Conclusion

You now know how to create a modern generative AI application that dynamically streams text in the browser, à la ChatGPT!

As you noticed, such an application is not necessarily simple as several layers are involved. And of course the above code is oversimplified for the sake of the example.

The main challenge with token streaming is about handling network failures. Most of these failures will happen between the Go backend and the Javascript frontend. You will need to explore some more advanced reconnection strategies and make sure that errors are properly reported to the UI.

I hope that you found this tutorial useful!