Deployment and serving
local graph
Chapter 11 — Deployment and serving
Section titled “Chapter 11 — Deployment and serving”11 Deployment and serving
This chapter covers
- SLM serving and inference with vLLM
- SLM serving with FastAPI
- SLM deployment and serving on devices with MLC LLM
- Options for SLM deployment and inference on Android devices
It’s time to look at some of the most common environments and tools for deploying and serving small, customized language models. We won’t cover them all: the closer you get to local or edge deployments, the more hardware options and frameworks you’ll encounter. I’ve focused on the options that are currently most popular across operating systems and hardware combinations.
11.1 vLLM
Section titled “11.1 vLLM”vLLM is an open source library for LLM serving and inference (https://github.com/vllm-project/vllm). vLLM was introduced in the September 2023 paper “Efficient Memory Management for Large Language Model Serving with PagedAttention” (https://arxiv.org/abs/2309.06180). The paper introduces PagedAttention, an attention algorithm that improves memory management for LLMs by addressing issues of memory fragmentation and redundancy in the key-value (KV) cache. It does this by storing KV-cache blocks noncontiguously, which increases memory flexibility and reduces fragmentation—key to improving throughput and batch size in LLM serving systems. vLLM uses a centralized scheduler and KV-cache manager, similar to a virtual memory system, and emphasizes batching during autoregressive generation to optimize throughput. The paper critiques existing LLM serving systems for not meeting LLM-specific needs, and it highlights vLLM’s dynamic memory allocation and block management as key improvements for efficient memory use in complex applications. Overall, it is the first effort to focus on serving LLMs specifically, rather than ML models in general.
The paper notes several inefficiencies and challenges in how earlier systems managed memory:
-
Contiguous memory allocation—Most systems store a request’s KV cache in contiguous memory space. This can cause significant internal and external fragmentation. Internal fragmentation occurs when the actual request is shorter than its reserved maximum length, leaving unused space. External fragmentation occurs when different requests reserve different block sizes, leaving gaps that other requests can’t use.
-
Preallocation of memory—Existing systems preallocate memory for a request based on its maximum possible sequence length, regardless of the actual input or output length. This static allocation wastes memory because reserved space for future tokens and internal fragmentation goes unused until the request completes.
-
Inefficient memory sharing—Advanced decoding algorithms such as parallel sampling and beam search generate multiple outputs per request, but existing systems can’t share memory because each sequence’s KV cache is stored in its own contiguous space.
-
Scheduling and preemption—Existing systems struggle to schedule and preempt requests because input and output lengths vary. They must decide when to delete or swap some requests’ KV caches from GPU memory to make room for new requests or continued generation for existing prompts.
vLLM addresses the memory-management inefficiencies because it limits batch size and throughput in LLM serving systems.
This paper led to the open source vLLM project, released under the Apache 2.0 license. It’s a community-driven initiative with contributions from both academia and industry. Today, vLLM is a mature project with the following features and capabilities:
-
State-of-the-art serving throughput
-
Efficient management of attention key and value memory through PagedAttention
- Continuous batching of incoming requests
- Support for the most popular CPUs and GPUs (NVIDIA GPUs, AMD CPUs and GPUs, Intel CPUs, Gaudi accelerators and GPUs, PowerPC CPUs, TPU, and AWS Trainium and Inferentia Accelerators)
- Optimized CUDA kernels, including integration with FlashAttention and FlashInfer
- Fast model execution with CUDA/HIP graph
- Support for quantization (GPTQ, AWQ, INT4, INT8, and FP8)
- High throughput serving with various decoding algorithms
- Speculative decoding
- Chunked prefill
- Distributed inference (tensor and pipeline parallelism)
- Streaming outputs
- Prefix caching support
- Integration with Hugging Face models (Transformers, MoEs, embedding models, multimodal LLMs)
- Compatibility with the OpenAI API
- Multi-LoRA support
Let’s look at how we can use vLLM to serve SLMs.
11.1.1 Offline serving
Section titled “11.1.1 Offline serving”vLLM supports offline and online serving. We’ll first look at offline serving—it’s a good starting point for getting familiar with the library. A companion Colab notebook is provided.
In most cases, you can install vLLM as a Python library:
pip install vllmFor supported hardware architectures without a prebuilt wheel, you’ll need to build it from source. Check the official documentation before installing it in your environment.
In this first example, you’ll get familiar with the main vLLM API in a text-generation use case. We’ll then build on that with a chat use case and a quantized model. We’ll use hardware acceleration with an NVIDIA GPU.
First, we’ll download a pretrained model from the Hugging Face Hub (GPT-2 small in this example):
import torchfrom vllm import LLM
model_id = "openai-community/gpt2"device = "cuda" if torch.cuda.is_available() else "cpu"vllm_model = LLM(model_id, device=device)You’ll notice that the code for this part is cleaner than the equivalent based on Hugging Face’s Transformers API. The single line that creates the LLM class performs several actions (rather than just downloading the model checkpoints):
- It downloads the model configuration file.
- It analyzes the model configuration and prepares the model setup accordingly.
- It downloads the model’s tokenizer.
- It downloads the model’s checkpoints.
- It loads the checkpoints in the destination device (GPU memory in this example).
- It profiles the memory.
- It initializes the KV cache.
- It warms up the model.
The model is now ready for inference. Because we didn’t specify a task, vLLM defaulted to generate (it also supports classify, score, reward, and embed), so the selected GPT-2 model is ready to generate text. Provide a prompt, and start text completion with the generate method:
prompt = "Once upon a time in a land far away"output = vllm_model.generate(prompt)print(output[0].outputs[0].text)The generate method also accepts an argument that specifies the sampling strategy. vLLM provides SamplingParams, a class for configuring sampling configuration (temperature, top_p, top_k, and other options supported by libraries such as Hugging Face’s Transformers):
from vllm import SamplingParams
sampling_params = SamplingParams(temperature=0.1, top_p=0.95)output = vllm_model.generate(prompt, sampling_params)This is the simplest, most general way to use vLLM for inference with any of the supported models. You can see how clean the vLLM API is, which was a design goal for its authors and maintainers from the start.
Next, we’ll make things slightly more complex with a chat use case. We’ll switch to a different model—the instruction-tuned Microsoft Phi-3 Mini 4K Instruct model (https://huggingface.co/microsoft/Phi-3-mini-4k-instruct)—and set up a chat app, mostly reusing the code from the previous example. The setup code for chatting looks the same as for text generation:
import torchfrom vllm import LLM, SamplingParams
model_id = "microsoft/Phi-3-mini-4k-instruct"device = "cuda" if torch.cuda.is_available() else "cpu"llm = LLM(model=model_id, device=device, dtype=torch.half)sampling_params = SamplingParams(temperature=0.5)The only thing that changes is the method we call. Given a conversation prompt like the following
conversation = [ { "role": "system", "content": "You are a helpful assistant" }, { "role": "user", "content": "Hi" }, { "role": "assistant", "content": "Hi! How can I assist you today?" }, { "role": "user", "content": "Write an essay about the Monte Carlo Tree Search algorithm.", },]the method we’ll use is chat:
outputs = llm.chat(conversation, sampling_params=sampling_params, use_tqdm=False)The chat method works for both single and batch inference:
conversations = [conversation for _ in range(10)]
outputs = llm.chat(messages=conversations, sampling_params=sampling_params, use_tqdm=True)We can also provide an optional chat template. For example, to use the following Jinja template with the Phi-3 Mini 4K Instruct model, save it as phi-3.jinja:
{% if messages[0]['role'] == 'system' %} {% set offset = 1 %}{% else %} {% set offset = 0 %}{% endif %}
{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == offset) %} {% raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') %}{% endif %}
{{ '<|' + message['role'] + '|>' + '\n' + message['content'] | trim + '<|end|>' + '\n'}}
{% if add_generation_prompt %} { ' <|assistant|>\n' }{% endif %}Then pass the filename to the chat method via the chat_template argument:
with open('phi-3.jinja', "r") as f: chat_template = f.read()
outputs = llm.chat( conversations, sampling_params=sampling_params, use_tqdm=False, chat_template=chat_template,)As mentioned earlier in this section, vLLM supports inference for quantized LLMs, including those in GGUF format. Let’s see how to use a quantized model, using Microsoft’s Phi-3 Mini 4K Instruct as our example. For simplicity, we’ll use a version that’s already 4-bit quantized in GGUF format; the code that follows works for any LLM quantized the same way.
Microsoft provides a GGUF version of Phi-3 Mini 4K Instruct on the Hugging Face Hub. Log in with your Hugging Face credentials, and then specify the repository name and GGUF file to download. Use the same tokenizer as for the vanilla model:
from huggingface_hub import hf_hub_download
repo_id = "microsoft/Phi-3-mini-4k-instruct-gguf"filename = "Phi-3-mini-4k-instruct-q4.gguf"tokenizer = "microsoft/Phi-3-mini-4k-instruct"model = hf_hub_download(repo_id, filename=filename)After downloading the model checkpoints and tokenizer, provide a prompt (or batch of prompts), and create a SamplingParams object:
from vllm import LLM, SamplingParams
prompts = [ "How to explain Internet for a medieval knight?", "What's the future of AI?",]prompts = [[{"role": "user", "content": prompt}] for prompt in prompts]sampling_params = SamplingParams(temperature=0, max_tokens=128)Then create a vLLM LLM object using the downloaded model and tokenizer:
llm = LLM(model=model, tokenizer=tokenizer)We can now use the chat method as for any other vanilla model:
outputs = llm.chat(prompts, sampling_params)The output will look like this:
<|user|>\nHow to explain Internet for a medievalknight?<|end|>\n<|assistant|>\n', Generated text: ' Good morrow, nobleknight. I come before thee to share knowledge of a magical realm called theInternet, a place beyond our physical world, where information andknowledge flow like the rivers of our kingdom.\n\nImagine, if thou wilt, avast library, containing all the wisdom of the ages, from the time of thegreat empires to the present day. This library is not bound by walls orshelves, but exists in a realm beyond our senses, accessible to all whopossess the key to unlock its secrets.\n\nThe Internet is a network ofinvisible threads, connecting'
"<|user|>\nWhat's the future of AI?<|end|>\n<|assistant|>\n", Generatedtext: " The future of Artificial Intelligence (AI) is a topic of greatinterest and speculation among experts across various fields. While it'schallenging to predict with absolute certainty, several trends andpossibilities can be outlined based on current research, technologicaladvancements, and societal needs. Here are some key areas that are likelyto shape the future of AI:\n\n1. Advanced Machine Learning: AI willcontinue to evolve, with machine learning algorithms becoming moresophisticated, efficient, and capable of handling complex tasks. Thisincludes deep learning, reinforcement learning, and"11.1.2 Online serving
Section titled “11.1.2 Online serving”vLLM also provides an HTTP server compatible with the OpenAI API (https://github .com/openai/openai-python), the de facto standard for online LLM serving. After you install vLLM, you can start a server with the serve CLI command. In its simplest form, the command expects the following arguments:
- The ID of an LLM in the Hugging Face Hub
- The precision format for the model
- An authorization token to access the server’s API
The following example uses Microsoft’s Phi-3 Mini 4K Instruct model:
vllm serve microsoft/Phi-3-mini-4k-instruct --dtypefloat16 --api-key token-abc123After the server has ramped up, you can call it with an HTTP client built with OpenAI Python client API (as you would with any other framework that supports the library and format). The vLLM server supports the OpenAI API for completions, chat completions, and embeddings, and it provides further extensions for tokenizing, detokenizing, pooling, scoring, and reranking. The following example shows an HTTP client calling the vLLM completion API for the Phi-3 Mini 4K Instruct model:
from openai import OpenAI
client = OpenAI( base_url="http://localhost:8000/v1", api_key="token-abc123",)
completion = client.chat.completions.create( model="microsoft/Phi-3-mini-4k-instruct", messages=[ {"role": "user", "content": "Hello!"} ])The output looks like this:
ChatCompletionMessage(content=' Hello! How can I assist you today?',refusal=None, role='assistant', audio=None, function_call=None,tool_calls=[], reasoning_content=None)For a full list of OpenAI API configurations and options, see the OpenAI Python SDK documentation at https://github.com/openai/openai-python. You can serve vLLM offline or online using Docker containers and deploy it on Kubernetes, Nginx, or AWS.
Because of vLLM’s many implementation optimizations, SLM inference is very fast compared to other frameworks and runtimes. But once a model is deployed behind an HTTP endpoint, you should benchmark its real serving performance before opening access to client applications. The official vLLM GitHub repository provides several Python scripts to automate benchmarks for any model served through the framework’s API. The scripts are in the benchmarks folder, and they cover metrics such as latency and throughput. Two benchmarking datasets are also available on the Hugging Face Hub: ShareGPT (text only) and ShareGPT4V (multimodal).
To benchmark models served online, we first need to clone the vLLM GitHub repo and install its requirements. Then download the ShareGPT dataset in JSON format, such as by using wget:
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.jsonFinally, we can run the Python script to start benchmarking the served model (we’re still using Microsoft’s Phi-3 Mini 4K Instruct model, deployed on a vLLM server):
python ./vllm/benchmarks/benchmark_serving.py \--backend vllm \--model microsoft/Phi-3-mini-4k-instruct \--dataset-name sharegpt \--dataset-path /content/ShareGPT_V3_unfiltered_cleaned_split.json \--num-prompts 200 \--save-resultThis example passes several parameters to the script: the backend we’re using (vLLM), the model ID on the Hugging Face Hub, the dataset name and local path, the number of samples, and whether to save detailed benchmark results locally as JSON. When you run this benchmark against the model on a vLLM server in a free-tier Colab accelerated environment (with one NVIDIA T4 GPU available), you should see performance in the following ranges:
Traffic request rate: infBurstiness factor: 1.0 (Poisson process)Maximum request concurrency: None100% 200/200 [02:23<00:00, 1.39it/s]========== Serving Benchmark Result ==========Successful requests: 200Benchmark duration (s): 143.93Total input tokens: 49473Total generated tokens: 47232Request throughput (req/s): 1.39Output token throughput (tok/s): 328.17Total Token throughput (tok/s): 671.91----------Time to First Token----------Mean TTFT (ms): 38742.30Median TTFT (ms): 14503.04P99 TTFT (ms): 99097.12------Time per Output Token (excl. 1st token)------Mean TPOT (ms): 153.30Median TPOT (ms): 107.19P99 TPOT (ms): 1104.83--------Inter-token Latency--------Mean ITL (ms): 102.17Median ITL (ms): 72.11P99 ITL (ms): 532.52==============================The benchmark final report shows the number of successful requests, total duration, input and generated token counts, and request, output, and total token throughput. It also reports the mean, median, and 99th percentile for the time to first token, time per output token, and inter-token latency.
11.2 FastAPI
Section titled “11.2 FastAPI”FastAPI (https://fastapi.tiangolo.com/) is a modern, open source web framework building APIs with standard Python type hints. It aims to be performant, easy to learn and easy to learn. FastAPI is built on Starlette (https://www.starlette.io/) for the web layer and Pydantic (https://docs.pydantic.dev/latest/) for data modeling and validation. It uses Python’s async features for nonblocking operations and good performance under load, and its straightforward syntax helps developers get started quickly. FastAPI also generates live, interactive API documentation automatically, with either Swagger UI (https://swagger.io/) or ReDoc (https://github.com/Redocly/redoc) as the documentation interface (they offer different user experiences for exploring and testing the same REST API). This documentation is derived from your code and type hints, making the API easy to understand and test. FastAPI is well suited for data-driven APIs, microservices, and ML APIs.
Before we serve LLMs with this framework, let’s review the basic FastAPI syntax. After installing the library, we need to import the main requirement:
from fastapi import FastAPINext, we’ll create an instance of the FastAPI app:
app = FastAPI()Now we can start building routes. Routes define how incoming HTTP requests are handled. Each route is tied to a URL path and specifies the function that processes the request. For example, to accept HTTP GET requests, we’ll define a function and decorate it with the FastAPI get annotation:
@app.get("/")def read_root(): return {"Hello": "Friend"}To accept HTTP POST requests, we can define a custom function and decorate it with FastAPI’s post annotation:
from typing import Union
@app.post("/items/")async def create_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q}Now we can start the web server from the CLI:
fastapi <environment> <python_web_app_name>.pyHere <environment> can take the values dev (for development/testing) or run (for production). After the server starts, the implemented APIs are available at the hostname (default localhost) and port (default 8000) specified at the server’s startup. You can set the host and port with the —host and —port options of the fastapi command-line application.
Because this framework uses Swagger UI and ReDoc, it automatically generates online documentation for our custom API at the /docs GET endpoint (see figure 11.1).

[!visual-conversion] Figure 11.1 — Online documentation for our FastAPI web application’s custom API (p. 226)
Alternatively, you can use the /redoc GET route (see figure 11.2).
That’s it, regardless of the complexity or scope of your functions or API.
Now let’s see how to use FastAPI to serve LLMs. The server code is straightforward, since its structure is the same as any for other FastAPI app. What are specific to LLMs are the inference handling function and any supporting code for model initialization. The Hugging Face libraries we’ve used throughout this book integrate easily into FastAPI apps. As in the previous example, we’ll start by creating an instance of the FastAPI app class:
from fastapi import FastAPI
app = FastAPI()
[!visual-conversion] Figure 11.2 — Online ReDoc documentation for our sample FastAPI web application’s custom API (p. 227)
Next, we’ll create two classes—one for the model’s input and one for its output:
from pydantic import BaseModel
class InputData(BaseModel): prompt: strclass OutputData(BaseModel): response: strWe’ll initialize the model pipeline at application startup. Hugging Face pipelines are supported, and we can also use the Transformers auto classes. For example, for the GPT-2 small model for text generation, the syntax is as follows:
model = pipeline("text-generation", model="openai-community/gpt2")Finally, we need to create a route that uses the model to generate text based on a prompt through the request:
@app.post("/generate", response_model=OutputData)def generate(request: Request, input_data: InputData): prompt = input_data.prompt
response = model(prompt)[0]["generated_text"]
return OutputData(response=response)The preceding route returns the generated text in response to an HTTP POST request.
You can package FastAPI applications for serving LLMs in Docker containers and deploy them to container platforms such as Kubernetes or cloud services like AWS and Azure. For our simple GPT-2 text-generation app, the Dockerfile looks like this:
FROM python:3.10-slimWORKDIR /fastapi-demoCOPY requirements.txt .COPY ./src ./srcRUN pip install -r requirements.txtEXPOSE 8000CMD ["uvicorn", "src.main:main", "--host", "0.0.0.0", "--port", "8000"]In the preceding Dockerfile, we start from an official Python runtime image, set the root directory in the container, copy in the requirements file and source code, install dependencies, expose the listening port, and start the web server when the container starts.
11.2.1 Benchmarking various models
Section titled “11.2.1 Benchmarking various models”As mentioned earlier, FastAPI delivers strong performance. When serving LLMs with FastAPI, focus your benchmarking on model inference, since it has the biggest effect on overall performance.
For this subsection, a companion Colab notebook provides code to benchmark a model you’ll serve through a FastAPI route. The notebook doesn’t include the serving code because it requires tunneling, and Colab policies can change in ways that block tunneling techniques and third-party services. Still, you can use the notebook to benchmark different model versions, identify the fastest option, and choose a deployment candidate. Afterward, benchmark the FastAPI web application in a separate environment, as you would for any other web application.
This example uses the GPT-2 small model, but you can benchmark any GPT-2 size (including fine-tuned or PEFT variants) by swapping the model ID on the Hugging Face Hub. With minor changes to the auto classes and input preparation, the same approach works for other decoder-only architectures. GPT-2 small needs no hardware acceleration, but larger models or running all benchmarks at once will likely require a GPU.
Let’s download the model and tokenizer from the Hugging Face Hub:
from pathlib import Pathfrom transformers import GPT2Tokenizer, GPT2Modeldevice = "cpu"model_id = 'openai-community/gpt2'tokenizer = GPT2Tokenizer.from_pretrained(model_id)model = GPT2Model.from_pretrained(model_id)model.eval()model_path = Path("gpt2")model.save_pretrained(model_path)We’ll benchmark the vanilla FP32 model first. Now we’ll convert the checkpoints to ONNX using PyTorch’s native torch.onnx package:
import torchfrom transformers import BatchEncoding
input_ids: BatchEncoding = tokenizer( text, add_special_tokens=True, return_attention_mask=False, return_tensors="pt")for k, v in input_ids.items(): input_ids[k] = v.type(dtype=torch.int32)input_tensor = input_ids['input_ids']onnx_model_path = "gpt2_onnx.onnx"dynamic_axes = { 'input_ids': {0: 'batch_size', 1: 'sequence_length'}, 'logits': {0: 'batch_size', 1: 'sequence_length'},}torch.onnx.export( model, f=onnx_model_path, args=(input_tensor,), input_names=['input_ids'], output_names=['logits'], quantization=False, var_output_seq=True, do_constant_folding=True, opset_version=18, dynamic_axes=dynamic_axes)Next, we’ll optimize the ONNX model:
from onnxruntime.transformers.optimizer import optimize_model
optimized_onnx_path = "gpt2_optimized.onnx"optimized_model = optimize_model(input=onnx_model_path, model_type="gpt2", use_gpu=False)optimized_model.save_model_to_file(optimized_onnx_path)Finally, we’ll downsize the model to FP16:
from copy import deepcopy
optimized_fp16_model_path = "optimized_fp16.onnx"optimized_fp16_model = deepcopy(optimized_model)optimized_fp16_model.convert_float_to_float16()optimized_fp16_model.save_model_to_file(optimized_fp16_model_path)By applying techniques from earlier chapters, we now have four versions of the same model. We’ll benchmark them and choose one to serve through a FastAPI web app.
Let’s define a simple helper function we can reuse to benchmark any of these models:
import time
def benchmark_llm(f, name=""): for _ in range(10): f() seconds_per_iter = timeit.timeit(f, number=100) / 100 print( f"{name}:", f"{seconds_per_iter * 1000:.3f} ms", )This function expects two input values: a function f that runs inference for a given model and a benchmark name (useful for building reports and visualizations). After an initial warmup, it runs the model 100 times and returns the average latency.
Before running the benchmarks, we need to prepare the inputs expected by each model version, along with the inference function to pass to benchmark_llm. We will use the following test prompt:
text = "Today is Saturday and"This is the input for the vanilla PyTorch model:
inputs_base = tokenizer(text, return_tensors="pt").to(device)The benchmark execution is then quite straightforward:
benchmark_llm(lambda: model(**inputs_base), "PyTorch")The other three versions of the model are in ONNX format, so we need a bit of setup to prepare their input for ORT. First, we’ll encode the prompt:
import torch
encodings_dict = tokenizer.batch_encode_plus([text])
input_ids = torch.tensor(encodings_dict["input_ids"], dtype=torch.int32)
ort_inputs = { "input_ids": input_ids.cpu().numpy()}Finally, we’ll create inference sessions for the three ONNX models. They use the inputs prepared in the previous snippet and serve as Lambda functions for the benchmarks:
from onnxruntime import InferenceSession
providers=["CPUExecutionProvider"]# ONNX modelsess = InferenceSession(onnx_model_path, providers=providers)benchmark(lambda: sess.run(None, ort_inputs), "ONNX")
# Optimized ONNX modeloptimized_sess = InferenceSession(optimized_onnx_path, providers=providers)benchmark(lambda: optimized_sess.run(None, input_feed=ort_inputs), "ONNX optimized")
# Downsized ONNX modeloptimized_fp16_sess = InferenceSession( optimized_fp16_model_path, providers=providers)benchmark(lambda: optimized_fp16_sess.run(None, input_feed=ort_inputs), "ONNX optimized fp16")By running the benchmark multiple times for four versions of the model, each time using prompts of different lengths (1, 4, 64, 256, 512, and 1,024 tokens), we can observe the following average latency patterns:
====== Tokens 1 ======Pytorch (1 tokens): 69.091 msONNX (1 tokens): 36.075 msONNX optimized (1 tokens): 34.619 msONNX optimized fp16 (1 tokens): 88.717 ms====== Tokens 4 ======Pytorch (4 tokens): 80.526 msONNX (4 tokens): 38.535 msONNX optimized (4 tokens): 36.813 msONNX optimized fp16 (4 tokens): 149.577 ms====== Tokens 64 ======Pytorch (64 tokens): 281.216 msONNX (64 tokens): 217.580 msONNX optimized (64 tokens): 206.556 msONNX optimized fp16 (64 tokens): 369.766 ms====== Tokens 256 ======Pytorch (256 tokens): 977.689 msONNX (256 tokens): 768.100 msONNX optimized (256 tokens): 803.686 msONNX optimized fp16 (256 tokens): 1037.310 ms====== Tokens 512 ======Pytorch (512 tokens): 1948.008 msONNX (512 tokens): 1722.430 msONNX optimized (512 tokens): 1674.203 msONNX optimized fp16 (512 tokens): 2299.876 ms======Tokens 1024 ======Pytorch (1024 tokens): 3972.155 msONNX (1024 tokens): 4048.070 msONNX optimized (1024 tokens): 3973.077 msONNX optimized fp16 (1024 tokens): 5784.016 msUp to 512 tokens, the ONNX optimized model has the best average latency. At the 1,024 context length, the vanilla, ONNX converted, and ONNX optimized models converge . Using FP16 with the ONNX optimized model doesn’t improve performance; it degrades it. Overall, the ONNX optimized version is the best candidate.
11.2.2 Deploying the best-performing model with FastAPI
Section titled “11.2.2 Deploying the best-performing model with FastAPI”To deploy the selected model version behind a FastAPI route, we can follow the usual pattern for implementing routes in the framework. In addition, we need to implement a custom function to generate text with the ONNX-optimized GPT-2 small model:
import numpy as npimport torchfrom onnxruntime import InferenceSession
async def generate(prompt, max_length, device): pt_inputs_base = tokenizer(prompt, max_length=max_length, return_tensors="pt").to(device) pt_inputs = tokenizer(prompt, max_length=max_length, return_tensors="pt").to(device) ort_inputs = dict(tokenizer(prompt, max_length=max_length, return_tensors="np", return_attention_mask=False)) ort_inputs['input_ids'] = ort_inputs['input_ids'].astype(np.int32)
optimized_onnx_path = "gpt2_optimized.onnx" providers=["CPUExecutionProvider"] optimized_sess = InferenceSession(optimized_onnx_path, providers=providers) logits = optimized_sess.run(None, ort_inputs) np_logits = logits[0] output = torch.from_numpy(np_logits) predicted_ids = np.argmax(output[0], axis=-1)
return outputThe custom generate function takes as input the user prompt, maximum token count, and device to use (CPU in our example). In the body of the function, we prepare the input for the ONNX model, create an ORT inference session, run text generation, and decode the output to return the generated text in natural language. The generate function is declared async because, when the model is exposed through a web API, server performance can vary based on factors such as network speed and bandwidth or the output size (which affects LLM latency). Making the function calls asynchronous frees the CPU to do other work while inference completes.
On the web app’s side, we first need to create a class to handle the inputs for the generation . The GenerateRequest class extends Pydantic’s BaseModel class and defines two fields—the user prompt and the maximum length:
from pydantic import BaseModel
class GenerateRequest(BaseModel): prompt: str max_length: int = 64Next, we’ll create the FastAPI app and implement a route that generates a sentence from a prompt and maximum length:
from fastapi import FastAPI
app = FastAPI()
@app.post("/generate")async def generate_text(request: GenerateRequest): device = "cpu" generated_sentence = await generate(request.prompt, request.max_length, device)
return {"Generated sentence = ": generated_sentence}In this section, you’ve seen how to deploy an SLM behind FastAPI, which is a good fit for most local and cloud deployments. The next sections cover a different scenario: deploying and serving SLMs on the edge.
11.3 MLC LLM
Section titled “11.3 MLC LLM”So far in this chapter, we’ve explored two ways to deploy and serve SLMs behind traditional REST APIs. In this section and the next, we’ll move closer to the edge and look at options for on-device deployment and serving.
In this section, we’ll look at MLC LLM (https://github.com/mlc-ai/mlc-llm/tree/main), an open source ML compiler and high-performance deployment engine for LLMs. It compiles and runs code on the MLCEngine, a unified high-performance LLM inference engine across multiple platforms. MLCEngine also provides an OpenAI-compatible API via a REST server and through Python, JavaScript, iOS, and Android, all backed by the same engine and compiler. Figure 11.3 shows the end-to-end workflow for MLC LLM.
Figure 11.4 lists the supported operating systems, CPUs, and GPUs at the time of writing.
======Tokens 1024 ======Pytorch (1024 tokens): 3972.155 msONNX (1024 tokens): 4048.070 msONNX optimized (1024 tokens): 3973.077 msONNX optimized fp16 (1024 tokens): 5784.016 msUp to 512 tokens, the ONNX optimized model has the best average latency. At the 1,024 context length, the vanilla, ONNX converted, and ONNX optimized models converge . Using FP16 with the ONNX optimized model doesn’t improve performance; it degrades it. Overall, the ONNX optimized version is the best candidate.
11.2.2 Deploying the best-performing model with FastAPI
Section titled “11.2.2 Deploying the best-performing model with FastAPI”To deploy the selected model version behind a FastAPI route, we can follow the usual pattern for implementing routes in the framework. In addition, we need to implement a custom function to generate text with the ONNX-optimized GPT-2 small model:
import numpy as npimport torchfrom onnxruntime import InferenceSession
async def generate(prompt, max_length, device): pt_inputs_base = tokenizer(prompt, max_length=max_length, return_tensors="pt").to(device) pt_inputs = tokenizer(prompt, max_length=max_length, return_tensors="pt").to(device) ort_inputs = dict(tokenizer(prompt, max_length=max_length, return_tensors="np", return_attention_mask=False)) ort_inputs['input_ids'] = ort_inputs['input_ids'].astype(np.int32)
optimized_onnx_path = "gpt2_optimized.onnx" providers=["CPUExecutionProvider"] optimized_sess = InferenceSession(optimized_onnx_path, providers=providers) logits = optimized_sess.run(None, ort_inputs) np_logits = logits[0] output = torch.from_numpy(np_logits) predicted_ids = np.argmax(output[0], axis=-1)
return outputThe custom generate function takes as input the user prompt, maximum token count, and device to use (CPU in our example). In the body of the function, we prepare the input for the ONNX model, create an ORT inference session, run text generation, and decode the output to return the generated text in natural language. The generate function is declared async because, when the model is exposed through a web API, server performance can vary based on factors such as network speed and bandwidth or the output size (which affects LLM latency). Making the function calls asynchronous frees the GPU to do other work while inference completes.
On the web app’s side, we first need to create a class to handle the inputs for the generation. The GenerateRequest class extends Pydantic’s BaseModel class and defines two fields—the user prompt and the maximum length:
from pydantic import BaseModel
class GenerateRequest(BaseModel): prompt: str max_length: int = 64Next, we’ll create the FastAPI app and implement a route that generates a sentence from a prompt and maximum length:
from fastapi import FastAPI
app = FastAPI()
@app.post("/generate")async def generate_text(request: GenerateRequest): device = "cpu" generated_sentence = await generate(request.prompt, request.max_length, device)
return {"Generated sentence = ": generated_sentence}In this section, you’ve seen how to deploy an SLM behind FastAPI, which is a good fit for most local and cloud deployments. The next sections cover a different scenario: deploying and serving SLMs on the edge.
11.3 MLC LLM
Section titled “11.3 MLC LLM”So far in this chapter, we’ve explored two ways to deploy and serve SLMs behind traditional REST APIs. In this section and the next, we’ll move closer to the edge and look at options for on-device deployment and serving.
In this section, we’ll look at MLC LLM (https://github.com/mlc-ai/mlc-llm/tree/main), an open source ML compiler and high-performance deployment engine for LLMs. It compiles and runs code on the MLCEngine, a unified high-performance LLM inference engine across multiple platforms. MLCEngine also provides an OpenAI-compatible API via a REST server and through Python, JavaScript, iOS, and Android, all backed by the same engine and compiler. Figure 11.3 shows the end-to-end workflow for MLC LLM.
Figure 11.4 lists the supported operating systems, CPUs, and GPUs at the time of writing.
graph LR
A["1) Weight conversion"] --> B["2) Model compilation"] --> C["3) Platform native runners"]
[!visual-conversion] Figure 11.3 — The end-to-end workflow for MLC LLM, from model conversion to deployment on the supported platforms’ native runtimes (p. 236) | Platform | AMD GPU | NVIDIA GPU | Apple GPU | Intel GPU | | --- | --- | --- | --- | --- | | Linux / Win | Vulkan, ROCm | Vulkan, CUDA | N/A | Vulkan | | macOS | Metal (dGPU) | N/A | Metal | Metal (iGPU) | | Web browser | WebGPU and WASM | WebGPU and WASM | WebGPU and WASM | WebGPU and WASM | | iOS / iPadOS | Metal on Apple A-series GPU | Metal on Apple A-series GPU | Metal on Apple A-series GPU | Metal on Apple A-series GPU | | Android | OpenCL on Adreno GPU | | OpenCL on Mali GPU | |
[!visual-conversion] Figure 11.4 — Operating systems, CPUs, and GPUs supported by MLC LLM (p. 236)
Key strengths of the MLC LLM framework include cross-platform performance—especially on mobile and edge devices—universal deployment with a single engine, a familiar OpenAI-style API, and support for high concurrency, batching, and prompt caching.
Let’s get familiar with the MLC LLM API. A companion Colab notebook provides the code example for this section, and it uses an NVIDIA GPU for hardware acceleration. The steps in this example apply to any LLM hosted on the Hugging Face Hub (a requirement), and they show how to prepare the model for inference on Linux-based devices.
First, we need to install the library for Linux and the available CUDA drivers:
python -m pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu122 mlc-ai-nightly-cu122After verifying the installation, we can download the target model weights and configuration files from the Hugging Face Hub.
We need to install Git LFS (https://github.com/git-lfs/git-lfs), a Git extension for versioning large files. Then we can create the destination directory for the converted weights and configuration and clone the target model repo from the Hub (in this example, RedPajama INCITE Instruct 3B, trained by Together AI in collaboration with several open source communities):
!mkdir -p dist/models
!git lfs install!git clone https://huggingface.co/togethercomputer-/RedPajama-INCITE-Instruct-3B-v1To convert the model’s weights to MLC LLM format, we’ll use the mlc_llm_convert_weights command. It takes as input the path to the directory where the model weights have been cloned, the quantization type, the target device (an NVIDIA GPU in our case), and the output directory that will store the converted weights:
mlc_llm convert_weight ./RedPajama-INCITE-Instruct-3B-v1/ \--quantization q4f16_1 \--device cuda \-o dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLCOnce the conversion is completed, the next step is to generate the chat configuration for the selected model. This can be done using mlc_llm_gen_config, another command file provided by MLC LLM. It expects the path to the directory where you cloned the model weights (and configuration), the quantization type, the model chat template, and the output directory for the generated configuration (the same one used for the converted model weights):
mlc_llm gen_config ./RedPajama-INCITE-Instruct-3B-v1/ \--quantization q4f16_1 --conv-template redpajama_chat \-o dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC/After the previous two steps, the content of the RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC directory should look like this:
mlc-chat-config.json params_shard_1.bin params_shard_32.binparams_shard_45.bin ndarray-cache-b16.json params_shard_20.bin params_shard_33.binparams_shard_46.bin ndarray-cache.json params_shard_21.bin params_shard_34.binparams_shard_47.bin params_shard_22.bin params_shard_35.binparams_shard_0.bin params_shard_23.bin params_shard_36.binparams_shard_10.bin params_shard_48.binparams_shard_49.binparams_shard_11.bin params_shard_24.bin params_shard_37.binparams_shard_4.bin params_shard_25.bin params_shard_38.binparams_shard_12.bin params_shard_26.bin params_shard_39.binparams_shard_50.bin params_shard_13.bin params_shard_40.binparams_shard_5.bin params_shard_14.bin params_shard_41.binparams_shard_6.bin params_shard_15.bin params_shard_42.binparams_shard_7.bin params_shard_16.bin params_shard_43.binparams_shard_8.bin params_shard_17.bin params_shard_44.binparams_shard_9.bin params_shard_18.bin params_shard_45.binparams_shard_19.bin params_shard_20.bin params_shard_46.binparams_shard_21.bin params_shard_22.bin params_shard_47.binparams_shard_23.bin params_shard_24.bin params_shard_48.binparams_shard_25.bin params_shard_26.bin params_shard_49.binparams_shard_27.bin params_shard_28.bin params_shard_50.bintokenzier_config.jsonparams_shard_19.bin params_shard_31.bin params_shard_44.bintokenizer.jsonThe chat configuration file (mLC-chat-config.json), model weight metadata (ndarray-cache.json, ndarray-cache-b16.json), model shards, and tokenizer files (tokenizer.json, tokenizer_config.json) must be present for conversion and chat configuration to succeed.
We’re not done yet. At this stage, the model is prepared (and can optionally be uploaded to the Hugging Face Hub), but to run it on a target platform or device, we still need to compile the model library according to the specifications in the generated mLC-chat-config.json file. In our Colab notebook example, the target for inference is a Linux device. (See the official MLC LLM documentation for the steps to compile the model for other operating systems.)
Our next step is to create the destination directory for the compiled model:
mkdir ./dist/libs
Now we’ll compile the model with the mLC_llm_compile command. It takes as input the path to the directory containing the model chat configuration file, the target device type (NVIDIA GPU), and the output path and filename for the compiled model:
mLC_llm compile ./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC \ /mLC-chat-config.json \ —device cuda -o dist/libs \ /RedPajama-INCITE-Instruct-3B-v1-q4f16_1-cuda.so
Now that the model is ready, we can use the MLC LLM Python API to create an MLCEngine instance for OpenAI-compatible chat completions in Python with MLC LLM ported models. It takes the model configuration path and the compiled model path as input:
from mlc_llm import MLCEngine
engine = MLCEngine( model="./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC", model_lib="./dist/libs/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-cuda.so")You can chat with the model much like you do with the OpenAI API:
response = engine.chat.completions.create( messages=[{"role": "user", "content": "What is the meaning of life?"}], model="./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC", stream=False,)The MLCEngine class can also iterate over streaming responses:
for response in engine.chat.completions.create( messages=[{"role": "user", "content": "What's the meaning of life?"}], model="./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC", stream=False,): print(response)print("\n")The MLCEngine class handles only synchronous chat completions. For concurrent, asynchronous generation, use AsyncMLCEngine. If you’ve uploaded a converted, compiled model to the Hugging Face Hub, these engine classes can download it; just specify the model location in the following format:
HF://<model_id_in_the_hf_hub>
The chat-completion code for asynchronous generation via AsyncMLCEngine mirrors that of MLCEngine.
Besides using the Python API and CLI to run ported SLMs and the MLCEngine, you can also serve them through MLC LLM’s REST API. The server is available automatically after you install MLC LLM. For the ported model in this section’s example, we’ll start the server from the command line as follows:
mlc_llm serve MODEL --model-lib ./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLCWe’ll use the same command-line tool we used to convert and compile the model, but this time, we’ll specify a different action (serve) and provide the compiled model’s location with the --model-lib option. The other options for this command are as follows:
--additional-models—Serves multiple models.--speculative-mode—Specifies whether speculative decoding is enabled (and which type to use: small draft, eagle, or medusa) or disabled (default).
- —device—Specifies the device on which to run the model. By default, it’s set to auto, which lets MLC LLM detect available devices and choose the best one. To target a specific device, use device_name:device_id or device_name (in the latter case, the device ID defaults to 0).
- —mode—Specifies the engine mode. Use local (low request concurrency), interactive (up to one concurrent request), or server (many concurrent requests; this uses as much GPU as possible).
- —overrides—Specifies values for one or more engine configuration parameters, such as maximum GPU utilization, enabling tensor parallelism, and context-window size.
- —enable-tracing—Enables request logging.
- —host—Specifies a host name.
- —port—Changes the port the server listens on. Default is 8000.
- —allow-credentials—Indicates whether the server should allow credentials.
- —allowed-origins—Specifies the allowed origins.
- —allowed-methods—Restricts the allowed HTTP methods.
- —allowed-headers—Specifies the allowed headers.
NOTE Speculative decoding is an inference-time optimization that lets an LLM predict multiple future tokens in parallel instead of generating one at a time. It’s covered in chapter 12.
Once the server is running, you can access it at the hostname and port you specified at startup. The /docs endpoint lists all supported endpoints. A GET request to /v1/models returns the available models.
To interact with the server from any Python application (to run inference with a hosted model), implement a client as follows using the Requests package (https://github.com/psf/requests):
import requestsimport json
payload = { "model": "./dist/RedPajama-INCITE-Instruct-3B-v1-q4f16_1-MLC/", "messages": [{"role": "user", "content": "Write a poem about Python"}], "stream": True,}with requests.post("http://127.0.0.1:8080/v1/chat/completions", json=payload, stream=True) as r: for chunk in r.iter_content(chunk_size=None): chunk = chunk.decode("utf-8") if "[DONE]" in chunk[6:]: break response = json.loads(chunk[6:])content = response["choices"][0]["delta"].get("content", "")print(content, end="", flush=True)print("\n")MLC LLM applications for SLM serving can also be managed as Docker containers and deployed on devices that support containerization.
11.4 Deployment and inference on Android devices
Section titled “11.4 Deployment and inference on Android devices”There are several options for deploying private, offline SLMs on Android devices (https://www.android.com/intl/en_ie/). Many online examples use TensorFlow Lite or MediaPipe, which require developing SLMs in TensorFlow or converting PyTorch weights to TensorFlow via ONNX. This section focuses on PyTorch alternatives.
11.4.1 MLC LLM framework
Section titled “11.4.1 MLC LLM framework”One option for deploying to Android is to use the MLC LLM framework discussed in section 11.3. The MLC LLM documentation includes an end-to-end tutorial for building and deploying apps and SLMs on Android (https://llm.mlc.ai/docs/deploy/android.html). I won’t repeat the steps here because the linked page explains them well. Here’s a summary:
1 Install the prerequisites to build the model and app locally. 2 Build the runtime and the selected model libraries. This step is the same as for compiling and building a model for any other destination platform, as detailed in section 11.3. 3 Customize and build the template Android app available in the MLC LLM GitHub repository. 4 Bundle the app with the model weights. 5 Install the APK and weights on the target Android phone.
The MLC LLM documentation tutorial uses a Samsung S23 with a Snapdragon 8 Gen 2 chip, but the workflow is the same for other Android devices. Focus on the target device’s hardware specs, benchmark performance, and optimize the model as needed. This approach has the advantages of porting and serving an SLM through the MLC LLM framework, but it also requires installing many third-party, non-Python components (Android Studio, rustc, the Java Development Kit, the NDK, and more) in your development environment, in addition to model conversion and compilation. Let’s look at some other alternatives.
11.4.2 MLLM framework
Section titled “11.4.2 MLLM framework”Another potential open source option is mllm (https://ubiquitouslearning.github .io/mllm_website/), a lightweight, fast LLM engine for mobile and edge devices that supports text and multimodal inputs. It’s implemented in plain C++ with no dependencies and supports a range of mobile hardware and quantization strategies. At the time of writing, mllm runs on Android, Linux, and macOS on x86_64 and arm64. You
must build it from source. On Linux and macOS, you’ll need gcc 11.4+ and CMake 3.19+. On Android, you’ll need Android NDK toolchain 26+.
First, you’ll need to clone the official GitHub repo:
git clone https://github.com/UbiquitousLearning/mlmmlm can be built with one of the provided scripts. On Linux/macOS, use build.sh:
cd ./scripts && ./build.shSeveral text and multimodal models are available in mlm format on the Hugging Face Hub and can be used as soon as the library build completes. Models are provided in FP32 and INT4 (CPU-optimized); a few are also optimized for the Hexagon NPU in INT8. See the mlm GitHub repo for the latest list.
During the build, a dedicated bash script for running inference is created in the bin directory for each model. For example, to run Llama 2 7B, download the already converted model from the Hub:
!mkdir ../models && cd ../models!wget https://huggingface.co/mlmTeam/llama-2-7b-mlm/resolve/main/llama-2-7b-chat-q4_k.mllm?download=true -0 llama-2-7b-chat-q4_k.mllmThen run the following script to start a chat session:
cd ./bin./demo_llama -m ../models/llama-2-7b-chat-q4_k.mllm -v../vocab/llama2_vocab.mllmOn Android devices, you’ll need to use a different build script to build mlm, and you’ll need to specify the Android NDK path:
export ANDROID_NDK=/path/to/your/ndkcd ./scripts./build_android.shThen, after downloading one of the available converted models from the Hugging Face Hub, you can start a chat session using the script for that model. Here’s an example for the Llama 2 7B model:
cd ../script./run_llama.shIf the model you want to use isn’t yet available in mlm, or if it’s a custom model, the mlm repo includes a Python script, convert.py, that converts PyTorch or safetensors weights (single-file or sharded). You’ll find it in tools/converter. Before running it, set up a Python environment, and install the converter requirements:
cd ./tools/converterpip install -r ./requirements.txtYou can then use the script for a given model as follows for PyTorch-format che
python convert.py --input_model=<model_name>.pth--output_model=<model_name>.mlm --type=torchOr like this, for checkpoints in safetensors format:
python convert.py --input_model=<model_name>.safetensors--output_model=<model_name>.mlm --type=safetensorBecause device memory, storage, and computational resources are often limited, mlm supports INT4 quantization for mlm models, including custom models converted to the format this library requires. Only two quantization modes are supported: Q4_0 and Q4_K. After you build the mlm library, the quantize script is available in the bin directory:
cd ./bin./quantize <model_name>.mlm model_q4_0.mlm Q4_K11.4.3 Hugging Face Transformers
Section titled “11.4.3 Hugging Face Transformers”Another alternative, fully Python-based, is to deploy and run SLMs for on-device inference directly with the Hugging Face Transformers library. This method requires developer options to be enabled on the target device.
To check if developer options are enabled, open the device’s Settings section, and confirm that Developer Options appears in the list. If not, go to Settings > About phone > Software Information, find the phone’s Build Number, and tap it seven times.
Once that’s done, you’ll need to install the Termux app (https://termux.dev/en/) from the Google Play Store. Termux is an open source terminal emulator for Android that runs a Debian-based Linux environment. No rooting is required to install it or add packages through its package manager. Termux is essentially a portable Linux distribution, so you can also install compilers and interpreters for popular programming languages. This means you can install Python and create virtual environments to run your own SLMs.
After starting Termux, you can install Python from the command line. First, update the package list:
pkg update && pkg upgrade
Then proceed with the main installation:
pkg install python
After installation, install the Python package manager and a virtual environment manager:
pkg install python-pippip install virtualenvYou’ll need to create a virtual environment to isolate the dependencies for SLM deployment and inference. Choose a destination directory on the device, and create the environment as you would on a laptop or server:
python -m venv slm-envNow activate the virtual environment:
source slm-env/bin/activate
Finally, install the required PyTorch and Transformers packages (and any others needed to implement our Python inference script):
pip install torch transformersWe can now implement inference code for the selected model. The simple example that follows uses a bert-base-uncased model for a classification task, but you can use any model supported by the Transformers library:
import torchfrom transformers import BertTokenizer, BertForSequenceClassification
model_id = 'google-bert/bert-base-uncased'tokenizer = BertTokenizer.from_pretrained(model_id)model = BertForSequenceClassification.from_pretrained(model_id)
# Sample texttext = "That movie is a blockbuster"
# Tokenize the textinputs = tokenizer(text, return_tensors='pt')
# Perform classificationwith torch.no_grad(): outputs = model(**inputs)
# Get the predicted classpredicted_class = torch.argmax(outputs.logits)print(f"Predicted class: {predicted_class}")We’ll now save the script on the device and run it for inference like any other Python application. Assuming the script is named bert_classification.py, run it like this:
python bert_classification.pyThat’s it.
Running LLMs locally can be resource-intensive, so choose a model your Andro device can handle in terms of memory, CPU (or GPU), and storage. After benchmarking on-device performance, try the optimization techniques from earlier chapters (including quantization) to speed up inference while maintaining acceptable output quality.
That concludes our survey of options for deploying and serving SLMs. The frameworks we covered share two key traits: an easy-to-use API and strong, out-of-the-box performance. The next chapter continues with local SLM deployment and serving, focusing on user-friendly ways to build powerful SLM-based assistants on a laptop.
Summary
Section titled “Summary”-
vLLM uses PagedAttention to manage memory efficiently by storing key-value cache blocks noncontiguously, reducing fragmentation.
-
vLLM supports offline and online serving via OpenAI-compatible API endpoints for deploying language models.
-
vLLM supports quantized models, including GGUF, and can automatically download and run them.
-
vLLM provides an OpenAI-compatible REST API for serving models.
-
vLLM provides benchmark scripts to measure serving performance (throughput , latency, and time to first token).
-
FastAPI lets you build high-performance web APIs in Python, using type hints and generating documentation automatically.
-
FastAPI routes define URL endpoints that handle HTTP requests via decorated Python functions.
-
Pydantic BaseModel classes validate FastAPI request and response data.
-
FastAPI apps can integrate Hugging Face models and pipelines as machine learning inference endpoints.
-
MLC LLM compiles language models for cross-platform deployment with a unified engine and compiler.
-
mlc_llm convert_weight converts model weights to MLC format with the specified quantization settings.
-
mlc_llm gen_config generates chat configuration files for converted models, using the appropriate templates.
-
mlc_llm compile builds platform-specific model libraries for target devices and OSs.
-
The MLCEngine class provides an OpenAI-compatible chat-completions API for MLC LLM–converted models.
-
MLC LLM serves models via a REST API, supporting concurrent requests and hosting multiple models.
- Deploying on Android requires enabling developer options; you can use the MLC LLM framework or other approaches.
- The mllm framework provides a lightweight C++ inference engine for mobile devices with built-in quantization support.
- The Termux app lets you set up a Python environment on Android to run Transformers models directly.