M1: Why Fine-Tune M2: Dataset Prep M3: LoRA M4: RLHF M5: Evaluation M6: Deployment Capstone
Intermediate Read time: 15 min Module 6 of 6

Deploying Your Fine-Tuned Model

You've trained the model. It passes evaluation. Now it needs to serve real users in under 500 milliseconds. This module takes you from a folder of model weights to a live API endpoint — and covers the quantization step that makes it fast enough to deploy affordably.

Module 6 of 6 — Fine-Tuning LLMs

By the end of this module, you will be able to merge LoRA adapter weights into the base model, apply GPTQ or GGUF quantization for inference speed, and serve the model via a FastAPI endpoint or Hugging Face Inference Endpoint.

Step 1: Merge the LoRA Adapter

After LoRA fine-tuning, you have two separate sets of weights: the frozen base model and the trained adapter (matrices A and B). Before serving, merge them. The merged model has the same architecture as the original — no adapter overhead at inference time.

from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

# Load the base model
base_model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-hf",
    torch_dtype="float16",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

# Load LoRA adapter on top of base model
model = PeftModel.from_pretrained(base_model, "./lora-adapter-output")

# Merge: fold adapter weights into the base model
merged_model = model.merge_and_unload()

# Save the merged model — same architecture as base, adapter incorporated
merged_model.save_pretrained("./merged-model")
tokenizer.save_pretrained("./merged-model")

print("Merged model saved. No adapter needed at inference time.")

Step 2: Quantize for Inference Speed

The merged model is in 16-bit float precision. For deployment, you often want to reduce this further. Two formats dominate:

GPTQ (GPU-optimized)

GPTQ (Frantar et al., arXiv:2210.17323) quantizes the model to 4-bit integers using a calibration dataset. The result is a model that runs about 3-4x faster on GPU at roughly the same quality as the 16-bit version. Use GPTQ when you're serving from a GPU server.

GGUF / llama.cpp (CPU and consumer hardware)

GGUF is a file format used by llama.cpp that supports 4-bit and 8-bit quantization optimized for CPU inference. If your deployment target is a laptop, an edge device, or a server without a GPU, GGUF lets you run a 7B model in about 4 GB of RAM at roughly 10-20 tokens per second on a modern CPU.

Deployment pipeline: merge LoRA, quantize, serve via API LoRA adapter + base model Merge merge_and_unload() single model file Quantize GPTQ / GGUF 4-bit int Serve FastAPI / HF Endpoint directional illustration
Key concept

Quantization converts 16-bit float weights to 4-bit integers. This cuts model size by 75% and speeds up inference substantially. On most tasks, the quality loss is negligible because model weights follow a near-normal distribution that maps well to low-bit integer ranges.

Step 3: Serve via FastAPI

A FastAPI server wraps your model in an HTTP endpoint that accepts a prompt and returns a generated response. This is the simplest way to expose a fine-tuned model to an application.

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import torch

app = FastAPI()

# Load at startup — not per request
tokenizer = AutoTokenizer.from_pretrained("./merged-model")
model = AutoModelForCausalLM.from_pretrained(
    "./merged-model",
    torch_dtype=torch.float16,
    device_map="auto"
)
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)

class Request(BaseModel):
    prompt: str
    max_new_tokens: int = 256
    temperature: float = 0.1

class Response(BaseModel):
    generated_text: str
    tokens_used: int

@app.post("/generate", response_model=Response)
async def generate(req: Request):
    outputs = generator(
        req.prompt,
        max_new_tokens=req.max_new_tokens,
        temperature=req.temperature,
        do_sample=req.temperature > 0,
        return_full_text=False
    )
    text = outputs[0]["generated_text"]
    return Response(
        generated_text=text,
        tokens_used=len(tokenizer.encode(req.prompt + text))
    )

# Run: uvicorn serve:app --host 0.0.0.0 --port 8000

Hugging Face Inference Endpoints: The Managed Option

If you don't want to manage infrastructure, Hugging Face Inference Endpoints lets you deploy any model from the Hugging Face Hub with a few clicks. You push your merged model to the Hub, create an endpoint, and get a URL you can call like any API. Pricing is per-second of compute used, so you only pay when your endpoint handles requests.

For a pilot deployment, this is often the right choice: no DevOps, no GPU management, and you can shut it down when not in use.

Cost context Chen, Zaharia, and Zou (arXiv:2310.11409) showed in the FrugalGPT paper that routing to specialized, smaller fine-tuned models can significantly reduce inference cost compared to routing all requests to large general-purpose models, while maintaining or improving quality on in-domain tasks. This is the economic case for deploying your own fine-tuned model rather than always calling a large API.
Deployment Config Planner Interactive

Describe your deployment scenario and see the recommended configuration.

500
500ms
7B
Try this — no setup required Open a Hugging Face account (free) and browse the model hub for a small open-source model relevant to your domain (search for "7b" + your domain). Click "Deploy" and note the options available. Read the pricing for Inference Endpoints. Calculate: at 500 requests per day, each generating 200 tokens at the cheapest GPU tier, what would a pilot deployment cost per month? This exercise makes deployment feel concrete and within reach.

Knowledge check

Q1: After merging a LoRA adapter, the merged model is larger than the original base model. True or false?

A) True — the adapter adds parameters
B) False — merging folds the adapter into the existing weights, keeping model size identical

Q2: You need to deploy a 7B fine-tuned model on a server with only a CPU (no GPU). Which quantization format is most appropriate?

A) GPTQ — it's the standard quantization format
B) GGUF with llama.cpp — optimized specifically for CPU inference
C) Keep it in 16-bit float — quantization is always lossy
Why shouldn't you load the model inside the FastAPI request handler? Think first. +
Loading a 7B model takes 10–30 seconds and requires allocating several GB of GPU memory. If you load inside the request handler, every request triggers this overhead. Users wait 30 seconds for a response. You also risk running out of memory if concurrent requests each try to load the model simultaneously. Load once at startup, keep it in memory, and reuse it across all requests. That's why the code example loads the model outside the endpoint function.

Before you go

Reflect: For your use case, which matters more: the lowest possible latency, or the lowest possible cost per 1,000 requests? That question determines whether to use a GPU endpoint or a quantized CPU deployment.

Share this insight
"Fine-tuning a 7B model, quantizing it to 4-bit, and serving it on your own infrastructure costs a fraction of routing every request to a large commercial API. The FrugalGPT research showed this is also the quality-optimal path for specialized tasks."

You might also like

Ready to deploy your first fine-tuned model? Let's design the architecture together.

Book a free 30-min call with Arjun

References

  1. Frantar, E. et al. (2022). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. arXiv:2210.17323.
  2. Chen, L., Zaharia, M., Zou, J. (2023). FrugalGPT. arXiv:2310.11409.
  3. Gerganov, G. (2023). llama.cpp. GitHub. github.com/ggerganov/llama.cpp.
  4. Dettmers, T. et al. (2022). LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale. arXiv:2208.07339.
  5. Mangrulkar, S. et al. (2022). PEFT: State-of-the-Art Parameter-Efficient Fine-Tuning. Hugging Face GitHub.
  6. Rao, A., Jaggi, A., Naidu, S. (2025). MEDFIT-LLM. IEEE RMKMATE 2025. DOI:10.1109/RMKMATE64574.2025.11042816.
← Module 5: Evaluation Capstone →
Was this helpful?