A Comprehensive Guide to LLMs’ Inference and Serving

September 29, 2023

Large Language Models have become the talk of the town. Every day brings new progress and innovation. New versions of GPT are being released. Meta is in the limelight with Llama-2. Parallelly we have a large number of counterparts and variations getting launched, including in multiple languages. Foundational models can now handle text and images pretty easily.

Open source LLMs are democratizing AI and come with a lot of promise. We can count on them for their data privacy, transparency, customization capabilities, and their low cost. But the fundamental issue we are facing when it comes to LLMs is their huge size and thirst for computational power. Firms and individuals other than large enterprises may not be able to afford such large infrastructure for their AI models – but we may have some workarounds. With this constraint in mind, let’s explore some frameworks and methods for LLM serving and inference which can help us use them seamlessly.


To conduct the following experiments, first sign up on E2E Cloud. Once registered, you can go to ‘Compute’ tab on the left, and spin up a GPU compute resource.

Once you have launched the GPU node, you would be able to add your SSH keys, and get going. Follow the steps outlined below to test out the various approaches outlined.

Hugging Face Endpoints

This may be the simplest way to make use of LLMs. It becomes particularly useful when we are building simple systems or testing models. Hugging Face has made it straight-forward by providing necessary documentation for each model in its page. Short code snippets are enough to get the model running. Here is an example inference code snippet for Llama-2 chat model.


Install transformers and login to Hugging Face:

$ pip install transformers
$ huggingface-cli login

Import libraries, load and prompt the model.

from transformers import AutoTokenizer
import transformers
import torch

model = "meta-llama/Llama-2-7b-chat-hf"

tokenizer = AutoTokenizer.from_pretrained(model)
pipeline = transformers.pipeline(

sequences = pipeline(
    'Tell me which is the best large language model.\n',
for seq in sequences:
    print(f"Result: {seq['generated_text']}")

As simple as that!!


  • Best option for beginners and research purposes.
  • Detailed and good documentation
  • With its robust community support and widespread popularity, Hugging Face has become the go-to platform for machine learning developers and researchers.
  • Big companies support and use this platform to provide their models as open source.
  • It can be easily used with almost all other frameworks.


  • It does have paid services for using API endpoints by cloud. But usually, it involves downloading the model to the machine and using it. So, efficiency is compromised and it requires pretty decent machines to use.


vLLM is a fast and simple framework for LLM inference and serving. It provides high throughput serving and support for distributed inference. Offering seamless integration with Hugging Face models and OpenAI compatible API server. Outstanding features include Continuous Batching and Paged Attention. As their tagline says, it indeed is easy, fast and cheap LLM serving for everyone.


It can be deployed as an API service. Here is the FastAPI server code and client code from the official documentation. 

Install CUDA on the system if not installed already.

$ sudo apt install nvidia-cuda-toolkit

To start the server:

$ pip install vllm

$ python -m vllm.entrypoints.api_server

Query the hosted model using:

$ curl http://localhost:8000/generate \
    -d '{
        "prompt": "Joe Biden is the",
        "use_beam_search": true,
        "n": 4,
        "temperature": 0.2

We can use it for offline batched inference also. Here is an example for text completion:             

from vllm import LLM, SamplingParams
prompts = [
    "Joe Biden is the",
    "The best large language model is",

Define parameters, load model and prompt.

sampling_params = SamplingParams(temperature=0.7, top_p=0.95)
llm = LLM(model="meta-llama/Llama-2-13b-hf")
outputs = llm.generate(prompts, sampling_params)

# Print the outputs.
for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

For utilizing multiple GPUs we can deploy models to any cloud using SkyPilot.

$ pip install skypilot
$ sky check

A serving.yaml file is to be created as shown. Here we have requested A100 GPU for the Llama 13B model we want to deploy.

    accelerators: A100

    MODEL_NAME: decapoda-research/llama-13b-hf
    TOKENIZER: hf-internal-testing/llama-tokenizer

setup: |
    conda create -n vllm python=3.9 -y
    conda activate vllm
    git clone https://github.com/vllm-project/vllm.git
    cd vllm
    pip install .
    pip install gradio

run: |
    conda activate vllm
    echo 'Starting vllm api server...'
    python -u -m vllm.entrypoints.api_server \
                    --model $MODEL_NAME \
                    --tensor-parallel-size $SKYPILOT_NUM_GPUS_PER_NODE \
                    --tokenizer $TOKENIZER 2>&1 | tee api_server.log &
    echo 'Waiting for vllm api server to start...'
    while ! `cat api_server.log | grep -q 'Uvicorn running on'`; do sleep 1; done
    echo 'Starting gradio server...'
    python vllm/examples/gradio_webserver.py


  • If inference speed is your priority vLLM is the best option. Algorithms like paged attention accelerate inference like no other frameworks.
  • High Throughput serving 
  • It has integrations with Hugging Face Transformers and OpenAI API 
  • For better deployment and scaling using any cloud platform, it has native integration with SkyPilot framework.


  • Currently, it does not support quantization. So, it is not efficient in terms of memory usage.
  • Currently, it does not support LoRA, QLoRA or other adapters for LLMs.


OpenLLM is a platform for packaging LLMs into production. It allows seamless integration with leading services like BentoML, Hugging Face, LangChain. It allows deployment to cloud or on machines and supports docker containerization when used with platforms like BentoML. It works with state-of-the-art models like Falcon, Flan-T5, StarCoder and much more.


For quick inference through server install openllm library, 

$ pip install openllm

To start the server:

$ openllm start opt

Alternatively, to specify the model type, enter model-id and parameters: 

$ openllm start opt --model-id facebook/opt-2.7b
  --max-new-tokens 200 \
  --temperature 0.2 \
  --api-workers 1 \
  --workers-per-resource 2

Query the hosted model using curl or inbuilt python client.

import openllm
client = openllm.client.HTTPClient('http://localhost:3000')
client.query('Which is the best large language model?')

To get more control over the server, we can code one using BentoML service.

from __future__ import annotations

import bentoml
import openllm

# specify model name here
model = ""  

llm_runner = openllm.Runner(model)

# specify service name here
svc = bentoml.Service(name="", runners=[llm_runner])      

def download(_: bentoml.Context):

@svc.api(input=bentoml.io.Text(), output=bentoml.io.Text())
async def prompt(input_text: str) -> str:
    answer = await llm_runner.generate.async_run(input_text)
    return answer[0]["generated_text"]

To start the service run:

$ bentoml serve service:svc

If required we can containerize and deploy the LLM application also using BentoML.


  • It offers quantization techniques for LLMs with bitsandbytes and GPTQ.
  • There are options to modify the models. Experimental fine-tuning functionalities are available. It also supports plugins like adapters for LLMs.
  • Integration with BentoML and BentoCloud offers wonderful options for deployment and scaling. BentoML enables us to dockerize the application.
  • It has integrations with Hugging Face Agents framework and LangChain.


  • It does not support built-in distributed inference.

Ray Serve

Ray is a complete toolkit that includes libraries to make end-to-end ML pipelines. One of the libraries Ray Serve is a good scalable model serving tool. It can be used to build inference APIs. It supports complex deep learning models with TensorFlow or PyTorch and has special optimizations like response streaming, dynamic request batching and batched inference for LLMs. 


Here is a sample code snippet for serving a Llama 13B model.

import requests
from starlette.requests import Request
from typing import Dict
from ray import serve

from transformers import AutoModelForCausalLM

# Define a Ray Serve deployment for your Hugging Face Llama model.
class LlamaModelDeployment:
    def __init__(self, llama_model):
        self.llama_model = llama_model

    def __call__(self, request: Request) -> Dict:
        # Make a prediction with the Hugging Face Llama model.
        prediction = self.llama_model.generate(request.query_params["prompt"])

        return {"prediction": prediction}

# Load your Hugging Face Llama model.
llama_model = AutoModelForCausalLM.from_pretrained("decapoda-research/llama-13b-hf")

# Bind the deployment to the model.
app = LlamaModelDeployment.bind(llama_model=llama_model)

# Deploy the application.

For inference, query the /llamas endpoint using HTTP requests:

response = requests.get("http://localhost:8000/llamas?prompt=Which is the best large language model?")

# The response will contain a JSON object with the prediction.
prediction = response.json()["prediction"]


  • Dynamically scalable to many machines for adjusting required resources for the model.
  • It is optimized for LLMs with features like response streaming, dynamic request batching and multi-GPU serving for computation intensive LLMs.
  • It has got native integration for the LangChain.


  • It does not seem to be the best option for beginners as it comprises of all kinds of complicated functions for all types of ML models. 

More About E2E Cloud Platform

E2E Networks is a leading provider of advanced cloud GPUs in India, offering a high-value infrastructure cloud for building and launching machine learning applications. Our cloud platform supports a variety of workloads across various industry verticals, providing high-performance computing in the cloud. We offer a flagship machine learning platform called Tir, which is built on top of Jupyter Notebook. E2E Networks also provides reliable and cost-effective storage solutions, allowing businesses to store and access their data from anywhere. Our cloud platform is trusted by over 10,000 clients and is designed for numerous real-world use cases in domains ranging from Data Science, NLP, Computer Vision/Image Processing, HealthTech, ConsumerTech, and more.

Tir: E2E Cloud’s Flagship Machine Learning Platform Tir is built on top of Jupyter Notebook, an advanced web-based interactive development environment offered by E2E Cloud. It provides users with the latest features and functionalities, including JupyterLab, a cutting-edge interface for working with notebooks, code, and data. Tir allows easy integration with other E2E services to build and deploy a complete pipeline. There are interfaces to test and decide which model to use for your task.

E2E Cloud Models: E2E Networks offers a wide range of options for machine learning applications. There are deployment-ready models for tasks ranging from Data Science, NLP, Computer Vision/Image Processing, HealthTech, ConsumerTech, and more. Other models include embedding models that convert text to embeddings which are widely used for search engines, personalization and recommendation tasks.


  • Highly scalable infrastructure
  • Reliable for production-level purposes
  • We are now growing to an end-to-end platform for machine learning models.


The selection of the framework is indeed contingent on several factors, including the specific task you’re tackling, the Large Language Model you’re utilizing, and the expenses you’re prepared to bear. This is not an exhaustive list but these are some of the currently available frameworks you are expected to try first for LLM inference and serving. To sum up the whole thing:






Latest Blogs
This is a decorative image for: A Complete Guide To Customer Acquisition For Startups
October 18, 2022

A Complete Guide To Customer Acquisition For Startups

Any business is enlivened by its customers. Therefore, a strategy to constantly bring in new clients is an ongoing requirement. In this regard, having a proper customer acquisition strategy can be of great importance.

So, if you are just starting your business, or planning to expand it, read on to learn more about this concept.

The problem with customer acquisition

As an organization, when working in a diverse and competitive market like India, you need to have a well-defined customer acquisition strategy to attain success. However, this is where most startups struggle. Now, you may have a great product or service, but if you are not in the right place targeting the right demographic, you are not likely to get the results you want.

To resolve this, typically, companies invest, but if that is not channelized properly, it will be futile.

So, the best way out of this dilemma is to have a clear customer acquisition strategy in place.

How can you create the ideal customer acquisition strategy for your business?

  • Define what your goals are

You need to define your goals so that you can meet the revenue expectations you have for the current fiscal year. You need to find a value for the metrics –

  • MRR – Monthly recurring revenue, which tells you all the income that can be generated from all your income channels.
  • CLV – Customer lifetime value tells you how much a customer is willing to spend on your business during your mutual relationship duration.  
  • CAC – Customer acquisition costs, which tells how much your organization needs to spend to acquire customers constantly.
  • Churn rate – It tells you the rate at which customers stop doing business.

All these metrics tell you how well you will be able to grow your business and revenue.

  • Identify your ideal customers

You need to understand who your current customers are and who your target customers are. Once you are aware of your customer base, you can focus your energies in that direction and get the maximum sale of your products or services. You can also understand what your customers require through various analytics and markers and address them to leverage your products/services towards them.

  • Choose your channels for customer acquisition

How will you acquire customers who will eventually tell at what scale and at what rate you need to expand your business? You could market and sell your products on social media channels like Instagram, Facebook and YouTube, or invest in paid marketing like Google Ads. You need to develop a unique strategy for each of these channels. 

  • Communicate with your customers

If you know exactly what your customers have in mind, then you will be able to develop your customer strategy with a clear perspective in mind. You can do it through surveys or customer opinion forms, email contact forms, blog posts and social media posts. After that, you just need to measure the analytics, clearly understand the insights, and improve your strategy accordingly.

Combining these strategies with your long-term business plan will bring results. However, there will be challenges on the way, where you need to adapt as per the requirements to make the most of it. At the same time, introducing new technologies like AI and ML can also solve such issues easily. To learn more about the use of AI and ML and how they are transforming businesses, keep referring to the blog section of E2E Networks.

Reference Links




This is a decorative image for: Constructing 3D objects through Deep Learning
October 18, 2022

Image-based 3D Object Reconstruction State-of-the-Art and trends in the Deep Learning Era

3D reconstruction is one of the most complex issues of deep learning systems. There have been multiple types of research in this field, and almost everything has been tried on it — computer vision, computer graphics and machine learning, but to no avail. However, that has resulted in CNN or convolutional neural networks foraying into this field, which has yielded some success.

The Main Objective of the 3D Object Reconstruction

Developing this deep learning technology aims to infer the shape of 3D objects from 2D images. So, to conduct the experiment, you need the following:

  • Highly calibrated cameras that take a photograph of the image from various angles.
  • Large training datasets can predict the geometry of the object whose 3D image reconstruction needs to be done. These datasets can be collected from a database of images, or they can be collected and sampled from a video.

By using the apparatus and datasets, you will be able to proceed with the 3D reconstruction from 2D datasets.

State-of-the-art Technology Used by the Datasets for the Reconstruction of 3D Objects

The technology used for this purpose needs to stick to the following parameters:

  • Input

Training with the help of one or multiple RGB images, where the segmentation of the 3D ground truth needs to be done. It could be one image, multiple images or even a video stream.

The testing will also be done on the same parameters, which will also help to create a uniform, cluttered background, or both.

  • Output

The volumetric output will be done in both high and low resolution, and the surface output will be generated through parameterisation, template deformation and point cloud. Moreover, the direct and intermediate outputs will be calculated this way.

  • Network architecture used

The architecture used in training is 3D-VAE-GAN, which has an encoder and a decoder, with TL-Net and conditional GAN. At the same time, the testing architecture is 3D-VAE, which has an encoder and a decoder.

  • Training used

The degree of supervision used in 2D vs 3D supervision, weak supervision along with loss functions have to be included in this system. The training procedure is adversarial training with joint 2D and 3D embeddings. Also, the network architecture is extremely important for the speed and processing quality of the output images.

  • Practical applications and use cases

Volumetric representations and surface representations can do the reconstruction. Powerful computer systems need to be used for reconstruction.

Given below are some of the places where 3D Object Reconstruction Deep Learning Systems are used:

  • 3D reconstruction technology can be used in the Police Department for drawing the faces of criminals whose images have been procured from a crime site where their faces are not completely revealed.
  • It can be used for re-modelling ruins at ancient architectural sites. The rubble or the debris stubs of structures can be used to recreate the entire building structure and get an idea of how it looked in the past.
  • They can be used in plastic surgery where the organs, face, limbs or any other portion of the body has been damaged and needs to be rebuilt.
  • It can be used in airport security, where concealed shapes can be used for guessing whether a person is armed or is carrying explosives or not.
  • It can also help in completing DNA sequences.

So, if you are planning to implement this technology, then you can rent the required infrastructure from E2E Networks and avoid investing in it. And if you plan to learn more about such topics, then keep a tab on the blog section of the website

Reference Links



This is a decorative image for: Comprehensive Guide to Deep Q-Learning for Data Science Enthusiasts
October 18, 2022

A Comprehensive Guide To Deep Q-Learning For Data Science Enthusiasts

For all data science enthusiasts who would love to dig deep, we have composed a write-up about Q-Learning specifically for you all. Deep Q-Learning and Reinforcement learning (RL) are extremely popular these days. These two data science methodologies use Python libraries like TensorFlow 2 and openAI’s Gym environment.

So, read on to know more.

What is Deep Q-Learning?

Deep Q-Learning utilizes the principles of Q-learning, but instead of using the Q-table, it uses the neural network. The algorithm of deep Q-Learning uses the states as input and the optimal Q-value of every action possible as the output. The agent gathers and stores all the previous experiences in the memory of the trained tuple in the following order:

State> Next state> Action> Reward

The neural network training stability increases using a random batch of previous data by using the experience replay. Experience replay also means the previous experiences stocking, and the target network uses it for training and calculation of the Q-network and the predicted Q-Value. This neural network uses openAI Gym, which is provided by taxi-v3 environments.

Now, any understanding of Deep Q-Learning   is incomplete without talking about Reinforcement Learning.

What is Reinforcement Learning?

Reinforcement is a subsection of ML. This part of ML is related to the action in which an environmental agent participates in a reward-based system and uses Reinforcement Learning to maximize the rewards. Reinforcement Learning is a different technique from unsupervised learning or supervised learning because it does not require a supervised input/output pair. The number of corrections is also less, so it is a highly efficient technique.

Now, the understanding of reinforcement learning is incomplete without knowing about Markov Decision Process (MDP). MDP is involved with each state that has been presented in the results of the environment, derived from the state previously there. The information which composes both states is gathered and transferred to the decision process. The task of the chosen agent is to maximize the awards. The MDP optimizes the actions and helps construct the optimal policy.

For developing the MDP, you need to follow the Q-Learning Algorithm, which is an extremely important part of data science and machine learning.

What is Q-Learning Algorithm?

The process of Q-Learning is important for understanding the data from scratch. It involves defining the parameters, choosing the actions from the current state and also choosing the actions from the previous state and then developing a Q-table for maximizing the results or output rewards.

The 4 steps that are involved in Q-Learning:

  1. Initializing parameters – The RL (reinforcement learning) model learns the set of actions that the agent requires in the state, environment and time.
  2. Identifying current state – The model stores the prior records for optimal action definition for maximizing the results. For acting in the present state, the state needs to be identified and perform an action combination for it.
  3. Choosing the optimal action set and gaining the relevant experience – A Q-table is generated from the data with a set of specific states and actions, and the weight of this data is calculated for updating the Q-Table to the following step.
  4. Updating Q-table rewards and next state determination – After the relevant experience is gained and agents start getting environmental records. The reward amplitude helps to present the subsequent step.  

In case the Q-table size is huge, then the generation of the model is a time-consuming process. This situation requires Deep Q-learning.

Hopefully, this write-up has provided an outline of Deep Q-Learning and its related concepts. If you wish to learn more about such topics, then keep a tab on the blog section of the E2E Networks website.

Reference Links



This is a decorative image for: GAUDI: A Neural Architect for Immersive 3D Scene Generation
October 13, 2022

GAUDI: A Neural Architect for Immersive 3D Scene Generation

The evolution of artificial intelligence in the past decade has been staggering, and now the focus is shifting towards AI and ML systems to understand and generate 3D spaces. As a result, there has been extensive research on manipulating 3D generative models. In this regard, Apple’s AI and ML scientists have developed GAUDI, a method specifically for this job.

An introduction to GAUDI

The GAUDI 3D immersive technique founders named it after the famous architect Antoni Gaudi. This AI model takes the help of a camera pose decoder, which enables it to guess the possible camera angles of a scene. Hence, the decoder then makes it possible to predict the 3D canvas from almost every angle.

What does GAUDI do?

GAUDI can perform multiple functions –

  • The extensions of these generative models have a tremendous effect on ML and computer vision. Pragmatically, such models are highly useful. They are applied in model-based reinforcement learning and planning world models, SLAM is s, or 3D content creation.
  • Generative modelling for 3D objects has been used for generating scenes using graf, pigan, and gsn, which incorporate a GAN (Generative Adversarial Network). The generator codes radiance fields exclusively. Using the 3D space in the scene along with the camera pose generates the 3D image from that point. This point has a density scalar and RGB value for that specific point in 3D space. This can be done from a 2D camera view. It does this by imposing 3D datasets on those 2D shots. It isolates various objects and scenes and combines them to render a new scene altogether.
  • GAUDI also removes GANs pathologies like mode collapse and improved GAN.
  • GAUDI also uses this to train data on a canonical coordinate system. You can compare it by looking at the trajectory of the scenes.

How is GAUDI applied to the content?

The steps of application for GAUDI have been given below:

  • Each trajectory is created, which consists of a sequence of posed images (These images are from a 3D scene) encoded into a latent representation. This representation which has a radiance field or what we refer to as the 3D scene and the camera path is created in a disentangled way. The results are interpreted as free parameters. The problem is optimized by and formulation of a reconstruction objective.
  • This simple training process is then scaled to trajectories, thousands of them creating a large number of views. The model samples the radiance fields totally from the previous distribution that the model has learned.
  • The scenes are thus synthesized by interpolation within the hidden space.
  • The scaling of 3D scenes generates many scenes that contain thousands of images. During training, there is no issue related to canonical orientation or mode collapse.
  • A novel de-noising optimization technique is used to find hidden representations that collaborate in modelling the camera poses and the radiance field to create multiple datasets with state-of-the-art performance in generating 3D scenes by building a setup that uses images and text.

To conclude, GAUDI has more capabilities and can also be used for sampling various images and video datasets. Furthermore, this will make a foray into AR (augmented reality) and VR (virtual reality). With GAUDI in hand, the sky is only the limit in the field of media creation. So, if you enjoy reading about the latest development in the field of AI and ML, then keep a tab on the blog section of the E2E Networks website.

Reference Links




Build on the most powerful infrastructure cloud

A vector illustration of a tech city using latest cloud technologies & infrastructure