Deploying Local LLMs: From VRAM Selection to a Working Chat Interface

    This guide walks through the complete process of deploying an open-source large language model on your own hardware, covering VRAM estimation, model quantization and format selection, building a CUDA-accelerated llama.cpp inference server, building a FastAPI backend with a Gradio chat UI, and securing the service from public exposure. It includes concrete command examples, a VRAM reference table, and a troubleshooting checklist for common deployment issues.

    1. VRAM and Environment Checks

    Before deployment, verify that your GPU can fit the model. The VRAM consumed by model weights can be estimated with a simple formula: multiply the parameter count by the number of bytes per parameter. Under FP16 precision, each parameter takes 2 bytes, so a 7B model requires about 14GB of weights, a 13B model about 26GB, and a 70B model about 140GB.

    Quantization can dramatically reduce this number. Q4_K_M is a common 4-bit quantization format used by llama.cpp, averaging about 4.8 bits per weight (roughly 0.6 bytes). A 7B model quantized this way takes about 4.2GB of weights; the actual GGUF file is closer to 4.5GB because a few layers retain higher precision, plus quantization scaling parameters and file metadata are included. Use the actual file size for capacity planning.

    Weights are only part of the story. During inference you also need KV Cache, which stores the processed context so the model can generate subsequent tokens. The KV Cache size grows with context length and concurrent requests. For example, Llama 2 7B without grouped-query attention uses about 512KB per token in FP16, so a context of 4096 tokens requires roughly 2GB.

    The numbers in the table below assume three conditions: a single user (batch size = 1), context length 4096, and the entire model loaded on the GPU (no CPU offload). They also reserve 1–2GB for the operating system and desktop environment. Adjustments are needed if these conditions change; the table is only a starting point.

    Model Size Precision Approx. Weights VRAM Recommended GPU VRAM
    7B Q4_K_M ~4.5GB 8GB or more
    13B Q4_K_M ~8GB 12GB or more
    32B Q4_K_M ~20GB 24GB or more, tight margin
    70B Q4_K_M ~42GB 48GB or multi-GPU
    7B FP16 ~14GB 20GB or more

    For the 7B FP16 case, 20GB VRAM is recommended. 16GB is only suitable when the context is very short, concurrency is single, and you accept the GPU running near its limit.

    System Selection

    Linux distributions like Ubuntu 22.04 or 24.04 have the most complete CUDA support, making them ideal for long-running services. The commands in this article assume Linux with an NVIDIA GPU. macOS with Apple Silicon uses Metal acceleration, which llama.cpp also supports, but command-line arguments and paths need to be adjusted. Windows users should be aware that when VRAM runs out, NVIDIA’s default “CUDA system memory fallback” strategy moves some data into system RAM; the service continues running but speed drops significantly.

    Environment Checklist

    Run each of the following checks and proceed only if all pass.

    1. Driver and CUDA version: Run nvidia-smi and note the Driver Version and CUDA Version shown at the top right.
    2. Compiler toolchain: Run nvcc --version. To compile llama.cpp with CUDA support, you need a CUDA Toolkit whose version is compatible with your driver.
    3. Free VRAM: Run nvidia-smi --query-gpu=name,memory.total,memory.used --format=csv. Close other VRAM-hogging programs; used memory should be near zero.
    4. System memory: Run free -h. At least 16GB of RAM is recommended; more is needed for 70B models or heavy CPU offloading.
    5. Disk space: Run df -h ~. Leave at least 1.5× the model file size free for downloads, checksums, and compiled artifacts.
    6. Model directory permissions: Run mkdir -p ~/llm/models ~/llm/logs and ensure both directories belong to your user. Run services as a normal user, not root.
    7. Port availability: Run ss -ltn | grep -E ':(8080|8000|7860)\b'. The three ports used in this article should produce no output.

    2. Model Formats and Quantization Choices

    Open-source models come in several common formats; choosing the wrong one will prevent loading.

    Format Typical Source Typical Inference Engine Quantization Method Common Errors
    GGUF llama.cpp ecosystem, e.g., quantized repos on Hugging Face llama.cpp, Ollama, LM Studio Built-in quantization types (Q4_K_M, Q5_K_M, Q8_0, etc.) Interrupted download causing truncated file; outdated llama.cpp; missing shard files
    GPTQ Hugging Face AutoGPTQ, Transformers, vLLM Post-training quantization, often 4-bit Missing quantize_config.json; CUDA operator library not installed
    SafeTensors Hugging Face Transformers, vLLM Not quantized; stores FP16 or BF16 raw weights Insufficient VRAM; weights not compatible with config.json

    This article uses the GGUF format. Selection rules:

    • For single-user chat with llama.cpp, choose GGUF.
    • For high-concurrency multi-user services, consider vLLM with GPTQ, AWQ, or SafeTensors.
    • Recommended quantization: Q4_K_M; it balances size and quality. Q3 and lower quantizations show noticeable quality loss on code and math tasks, so they are not recommended for regular conversation.

    GGUF models may be published in shards, with filenames like model-00001-of-00002.gguf. To load, place all shards in the same directory and specify the first shard. After downloading, verify file integrity using the SHA256 value provided on the source page:

    1. sha256sum ~/llm/models/model-q4_k_m.gguf

    If the checksum does not match, download again.

    3. llama.cpp Inference Server

    Installation and Version Recording

    llama.cpp must be compiled from source to enable CUDA acceleration.

    1. git clone https://github.com/ggml-org/llama.cpp ~/llm/llama.cpp
    2. cd ~/llm/llama.cpp
    3. git checkout <selected release tag>
    4. cmake -B build -DGGML_CUDA=ON
    5. cmake --build build --config Release -j

    Replace <selected release tag> with the latest stable tag from the Releases page. Record the version number for future debugging:

    1. git describe --tags > ~/llm/llama-version.txt

    After compilation, the server binary is at build/bin/llama-server. Run ./build/bin/llama-server --version to confirm the version.

    Launch Parameters

    The following command starts an inference server with a 7B model:

    1. export LLM_API_KEY="$(openssl rand -hex 32)"
    2. ./build/bin/llama-server \
    3. -m ~/llm/models/model-q4_k_m.gguf \
    4. --host 127.0.0.1 \
    5. --port 8080 \
    6. -c 4096 \
    7. -np 1 \
    8. -ngl 99 \
    9. --api-key "$LLM_API_KEY"

    Parameter meanings:

    • -m: Path to the model file.
    • --host 127.0.0.1: Accept connections only from the local machine. This is the first line of defense against public exposure; do not change it to 0.0.0.0.
    • --port 8080: Service port.
    • -c 4096: Context length. This is the total context shared by all concurrent slots, and it directly determines KV Cache size.
    • -np 1: Number of concurrent slots. -np divides -c equally among slots, so to ensure each request still gets a 4096-token context, set -c to 4096 × -np. A larger context increases VRAM usage.
    • -ngl 99: Number of layers to place on the GPU. 99 means all layers run on the GPU; the value is automatically capped at the model’s actual layer count. If VRAM is tight, reduce this number to offload some layers to the CPU, which will run but with noticeably slower generation.
    • --api-key: Requires requests to carry an Authorization: Bearer header, acting as a second layer of access control.

    LLM_API_KEY is stored only in the environment variable of the current terminal; it must be re-exported after a reboot. The FastAPI backend will later use the same value.

    Verifying the Service

    In the startup log, look for offloaded N/N layers to GPU with the two numbers equal, meaning all layers are on the GPU. Then open another terminal and run:

    1. curl http://127.0.0.1:8080/health

    A response of {"status":"ok"} means the service is ready. Send a test chat request:

    1. curl http://127.0.0.1:8080/v1/chat/completions \
    2. -H "Content-Type: application/json" \
    3. -H "Authorization: Bearer $LLM_API_KEY" \
    4. -d '{"messages":[{"role":"user","content":"Introduce yourself in one sentence"}],"max_tokens":64}'

    If the returned JSON contains content in choices[0].message.content, the inference pipeline works.

    4. FastAPI Backend and Gradio Interface

    The backend receives front-end requests, adds the API key, forwards them to llama-server, and performs basic input validation. The front-end talks only to the backend, never directly to the inference server.

    Installing Dependencies

    Requires Python 3.10 or newer.

    1. mkdir -p ~/llm/app && cd ~/llm/app
    2. python3 -m venv .venv
    3. source .venv/bin/activate
    4. pip install "fastapi>=0.115,<0.116" "uvicorn>=0.32,<0.33" "httpx>=0.27,<0.28" "gradio>=5,<6"
    5. pip freeze > requirements.lock.txt

    requirements.lock.txt records the actually installed versions. When migrating to another machine, use it to reinstall.

    FastAPI Backend

    Write the following code to ~/llm/app/backend.py:

    1. import os
    2. import httpx
    3. from fastapi import FastAPI, HTTPException
    4. from pydantic import BaseModel, Field
    5. LLM_URL = os.getenv("LLM_URL", "http://127.0.0.1:8080")
    6. LLM_API_KEY = os.getenv("LLM_API_KEY", "")
    7. app = FastAPI(title="local-chat-backend")
    8. class Message(BaseModel):
    9. role: str = Field(pattern="^(system|user|assistant)$")
    10. content: str = Field(max_length=8000)
    11. class ChatRequest(BaseModel):
    12. messages: list[Message] = Field(min_length=1, max_length=50)
    13. max_tokens: int = Field(default=512, ge=1, le=1024)
    14. temperature: float = Field(default=0.7, ge=0.0, le=2.0)
    15. @app.get("/api/health")
    16. async def health():
    17. return {"status": "ok"}
    18. @app.post("/api/chat")
    19. async def chat(req: ChatRequest):
    20. headers = {}
    21. if LLM_API_KEY:
    22. headers["Authorization"] = f"Bearer {LLM_API_KEY}"
    23. payload = {
    24. "messages": [m.model_dump() for m in req.messages],
    25. "max_tokens": req.max_tokens,
    26. "temperature": req.temperature,
    27. "stream": False,
    28. }
    29. try:
    30. async with httpx.AsyncClient(timeout=120) as client:
    31. resp = await client.post(
    32. f"{LLM_URL}/v1/chat/completions", json=payload, headers=headers
    33. )
    34. resp.raise_for_status()
    35. except httpx.HTTPError:
    36. raise HTTPException(status_code=502, detail="Inference service unavailable")
    37. data = resp.json()
    38. return {"reply": data["choices"][0]["message"]["content"]}

    The limits in the code (number of messages, single-message length, max_tokens cap) prevent a single request from exhausting VRAM and threads. LLM_API_KEY is read from an environment variable, not hardcoded.

    Start the backend:

    1. source ~/llm/app/.venv/bin/activate
    2. cd ~/llm/app
    3. uvicorn backend:app --host 127.0.0.1 --port 8000

    Verify:

    1. curl http://127.0.0.1:8000/api/health
    2. curl -X POST http://127.0.0.1:8000/api/chat \
    3. -H "Content-Type: application/json" \
    4. -d '{"messages":[{"role":"user","content":"Hello"}]}'

    The second command should return JSON containing a reply field, confirming the backend can call the inference server.

    Gradio Chat Interface

    Write the following code to ~/llm/app/frontend.py:

    1. import os
    2. import httpx
    3. import gradio as gr
    4. BACKEND_URL = os.getenv("BACKEND_URL", "http://127.0.0.1:8000")
    5. def respond(message, history):
    6. messages = [{"role": m["role"], "content": m["content"]} for m in history]
    7. messages.append({"role": "user", "content": message})
    8. try:
    9. resp = httpx.post(
    10. f"{BACKEND_URL}/api/chat", json={"messages": messages}, timeout=120
    11. )
    12. resp.raise_for_status()
    13. return resp.json()["reply"]
    14. except httpx.HTTPError:
    15. return "Backend call failed. Please check the backend and inference service status and logs."
    16. demo = gr.ChatInterface(fn=respond, type="messages", title="Local Chat")
    17. if __name__ == "__main__":
    18. demo.launch(server_name="127.0.0.1", server_port=7860)

    Setting server_name to 127.0.0.1 ensures the interface is visible only on the local machine. type="messages" passes history as a list of dictionaries with role and content, matching the backend’s data structure.

    Start the interface:

    1. source ~/llm/app/.venv/bin/activate
    2. cd ~/llm/app
    3. python frontend.py

    Open http://127.0.0.1:7860 in your browser and send a message. If the interface returns a proper response, the three-layer chain is fully working.

    5. Avoiding Public Exposure and Access Control

    Once a local LLM service is exposed to the public internet, anyone can consume your GPU, read conversation content, or use it to access other resources on the machine. All of the following measures must be applied.

    Bind Address

    All three services bind to 127.0.0.1, accepting only local connections. Check the listening state:

    1. ss -ltnp | grep -E ':(8080|8000|7860)\b'

    Each line should show a local address of 127.0.0.1:port. If you see 0.0.0.0:port or *:port, the service is exposed on all interfaces. Stop it and fix the launch parameters immediately.

    Firewall

    Use ufw to restrict incoming connections. Allow SSH first, otherwise you will lose remote access:

    1. sudo ufw allow OpenSSH
    2. sudo ufw default deny incoming
    3. sudo ufw default allow outgoing
    4. sudo ufw enable
    5. sudo ufw status verbose

    Note: Docker-published ports bypass ufw rules. If you run the services described here in a container, do not use port mappings like -p 8080:8080 unless you have verified the network access scope.

    Remote Access

    When you need to access from another device, prefer an SSH tunnel over opening a port:

    1. ssh -L 7860:127.0.0.1:7860 username@server-address

    After establishing the tunnel, open http://127.0.0.1:7860 in your local browser. The tunnel only forwards data between the local port and the service; it does not change the service’s binding address.

    Reverse Proxy

    If you truly need to expose the service through a domain name, place a reverse proxy (e.g., Caddy or Nginx) in front and satisfy all of the following conditions:

    • Enable TLS with a certificate from a recognized CA such as Let’s Encrypt.
    • Add authentication, e.g., HTTP Basic Auth or single sign-on.
    • Proxy only the front-end port 7860 or backend port 8000; do not proxy llama-server’s port 8080.
    • Keep the backend’s LLM_API_KEY enabled; do not disable it because a reverse proxy exists.

    6. Verification and Troubleshooting

    Verification Checklist

    • curl http://127.0.0.1:8080/health returns ok.
    • A /v1/chat/completions request with an Authorization header returns text content.
    • curl http://127.0.0.1:8000/api/health returns ok.
    • A browser visit to http://127.0.0.1:7860 completes one full conversation.
    • ss -ltnp shows all three ports bound to 127.0.0.1.
    • Direct access from another device to the server’s IP on the corresponding ports fails.

    Log Locations

    By default, llama-server and FastAPI write logs to the terminal. For long-running operation, redirect output to log files:

    1. ./build/bin/llama-server ... > ~/llm/logs/llama.log 2>&1 &
    2. uvicorn backend:app --host 127.0.0.1 --port 8000 > ~/llm/logs/backend.log 2>&1 &

    If you manage the services with systemd, view logs with `