Local LLM Deployment Guide: Model Selection, Setup, and Troubleshooting
This guide covers deploying large language models on your own hardware. It explains how to estimate GPU memory for different model sizes, prepare the environment and verify downloaded weights, and set up four deployment options: Ollama, vLLM, a multi-GPU enterprise setup, and Huawei Ascend NPUs. It also describes how to run load tests, tune concurrency, and troubleshoot common problems.
Key Takeaways
Local deployment comes down to three things: matching the model version to available VRAM, keeping the service reachable only from the internal network by default, and using measured data to set concurrency parameters before going live. This guide first covers model selection and VRAM estimation, then walks through four deployment approaches, and finally explains how to run performance tests, tune the service, troubleshoot problems, and compare against cloud services. The commands assume a typical Linux server. Replace model names and paths with your actual values.
1. Model Selection and VRAM Planning
1.1 Estimating VRAM
Weight VRAM ≈ parameter count × bytes per parameter
FP16 uses 2 bytes per parameter, INT8 uses 1 byte, and INT4 uses about 0.5 bytes. For a 32B model, FP16 weights need about 64 GB of VRAM, while INT4 weights need roughly 16 GB to 18 GB.
This formula covers only the weights. At runtime, you also need memory for the KV Cache, which grows with context length and concurrency, plus overhead from the inference framework. Reserve at least 20% headroom above the estimated weight size.
The table below shows estimates. Before you choose a model, confirm the actual file size of the model, the output of your quantization tool, and the vendor’s specifications.
| Scenario | Model Size and Quantization | Recommended VRAM | Context Reference | Concurrency Reference | Notes |
|---|---|---|---|---|---|
| Entry-level trial | 7B to 8B, INT4 | 8 GB or more | About 4K | 1 to 2 | If VRAM is insufficient, CPU offloading works, but speed drops noticeably. |
| Personal development | About 14B, INT4 | 16 GB | 8K to 16K | 4 to 8 | Long contexts quickly consume KV Cache. |
| Professional workstation | About 32B, INT4 or INT8 | 24 GB (short context) or 48 GB | 16K to 32K | 10 to 30 | 24 GB leaves little headroom, so 48 GB is the preferred option. |
| Enterprise service | 70B class, INT8 or FP16 | Multiple 80 GB GPUs | 32K or more | 50 or more | Requires high-speed interconnect between GPUs. |
The concurrency values depend on input and output length. Treat them as a starting point, and validate them with the measurement method in Part 4.
70B-class models need careful calculation. INT8 weights are about 70 GB, which two 80 GB GPUs can hold, but the headroom is limited. FP16 weights are about 140 GB. Two 80 GB GPUs leave almost no room for the KV Cache, so use four or more GPUs.
1.2 Selection Criteria
First, does the task require high output quality and close adherence to complex instructions? If so, and the budget allows, choose a larger model.
Second, is the goal throughput per unit of cost, or running on a consumer GPU? For the latter, choose a smaller model and apply quantization.
1.3 Selection Checklist
- Confirmed the longest input and output lengths for the workload
- Confirmed that the model license permits the intended use
- Estimated weight VRAM with the formula and reserved at least 20% headroom
- Confirmed the VRAM capacity and number of GPUs on the target hardware
2. Base Environment and Model Weights
2.1 System and Drivers
Ubuntu 22.04 or an equivalent Linux distribution is recommended, with Python 3.10 or later. Check the GPU driver and CUDA version first, then install the inference framework. Inference frameworks have CUDA version requirements, so check the official version compatibility table before installing.
# Install Git and Git LFS. Model weights are usually stored as large files.sudo apt update && sudo apt install -y git git-lfsgit lfs install# Create an isolated virtual environment to avoid conflicts with system packagespython3 -m venv ~/llm-envsource ~/llm-env/bin/activatepip install --upgrade pip# Verify that the GPU and driver are workingnvidia-smi
Do not run the inference service as root. Create a dedicated account and restrict its access to the model directory:
sudo useradd -r -m -s /bin/bash llmsudo mkdir -p /opt/llm/modelssudo chown -R llm:llm /opt/llmsudo chmod 750 /opt/llm
Downloading and extracting models takes extra disk space. Keep at least twice the model size in free space:
df -h /opt
2.2 Downloading Models and Verifying Hashes
In some regions, ModelScope, a model hub operated in China, may offer faster downloads. The model ID below is only an example. Confirm the correct ID on the model page:
pip install modelscopemodelscope download --model Qwen/Qwen2.5-7B-Instruct --local_dir /opt/llm/models/Qwen2.5-7B-Instruct
To download from Hugging Face through a mirror, set the endpoint variable to a mirror address you trust. Mirrors are third-party services, so always verify file hashes after downloading:
export HF_ENDPOINT=<mirror-url>
After the download finishes, compute the hash and compare each value with the one published on the model page:
sha256sum /opt/llm/models/Qwen2.5-7B-Instruct/*.safetensors
Rerunning the download command usually resumes an interrupted download. Delete any file whose hash does not match, then download it again. Do not deploy files that fail verification.
3. Four Deployment Approaches
Approach 1 is for quick validation on a local machine. Approach 2 is for single-server production. Approach 3 is for multi-GPU enterprise deployment. Approach 4 uses Huawei Ascend NPUs as an example of deploying on Chinese-made AI accelerators.
Approach 1: Ollama for Quick Validation
Ollama requires few installation and model-pull steps, which makes it suitable for checking model behavior. The first download time depends on your network speed and the model size.
Checklist:
- The driver works, or CPU inference is confirmed
- There is enough disk space
- Port 11434 is free
# Install Ollama. Verify the script address on the official website before running it.curl -fsSL https://ollama.com/install.sh | sh# Pull and run the model. Use the actual tag from the model registry.ollama pull <model-tag>ollama run <model-tag># Call the REST APIcurl http://127.0.0.1:11434/api/generate \-d '{"model": "<model-tag>", "prompt": "Introduce yourself in one sentence.", "stream": false}'
Set concurrency parameters through a systemd override file:
sudo systemctl edit ollama
Add the following to the file that opens:
[Service]Environment="OLLAMA_NUM_PARALLEL=4"Environment="OLLAMA_MAX_LOADED_MODELS=1"
Save the file, then run sudo systemctl daemon-reload && sudo systemctl restart ollama.
OLLAMA_NUM_PARALLEL sets the number of parallel requests for a single model. Each additional parallel slot also increases VRAM usage, so do not raise this value on its own.
Run ollama ps to see how the model is split between GPU and CPU. A high CPU share means VRAM is insufficient. In that case, shorten the context, switch to a smaller model, or use a more heavily quantized version.
Security note: Ollama listens only on 127.0.0.1:11434 by default. Do not set OLLAMA_HOST to 0.0.0.0 and expose the port directly. To share the API with other services, forward it through a reverse proxy with authentication and TLS. An Nginx example follows:
server {listen 443 ssl;server_name llm.example.com;ssl_certificate /etc/nginx/certs/llm.crt;ssl_certificate_key /etc/nginx/certs/llm.key;location / {auth_basic "LLM API";auth_basic_user_file /etc/nginx/.llm_htpasswd;proxy_pass http://127.0.0.1:11434;proxy_buffering off;proxy_read_timeout 300s;}}
Generate the password file with sudo htpasswd -c /etc/nginx/.llm_htpasswd <username>. Install apache2-utils first.
Approach 2: vLLM for Single-Server Production
vLLM manages the KV Cache with PagedAttention and supports continuous batching, which gives higher throughput under concurrent load. It provides an OpenAI-compatible API, so most existing clients only need a new address and API key.
Checklist:
- The CUDA version matches the selected vLLM version, checked against the official compatibility table
- vLLM is installed in a dedicated virtual environment
- The service runs under the dedicated
llmuser - No other process uses VRAM on the target GPU (confirm with
nvidia-smi) - The API key is stored in a file with 600 permissions
source ~/llm-env/bin/activatepip install vllm
vLLM installs matching PyTorch and other dependencies. The package is large, so confirm you have enough disk space.
Generate a key and write it to a file. Do not put the key in scripts or command history:
sudo install -d -m 750 -o llm -g llm /etc/llmopenssl rand -hex 32 | sudo tee /etc/llm/vllm.key >/dev/nullsudo chown llm:llm /etc/llm/vllm.keysudo chmod 600 /etc/llm/vllm.key
Start the service. The parameters below are conservative starting points for a first deployment:
export VLLM_API_KEY=$(sudo cat /etc/llm/vllm.key)vllm serve /opt/llm/models/<model-name> \--served-model-name my-llm \--host 127.0.0.1 \--port 8000 \--tensor-parallel-size 1 \--max-model-len 16384 \--gpu-memory-utilization 0.85 \--max-num-seqs 64 \--enable-prefix-caching
What each parameter does:
--max-model-lensets the maximum context for a single request. A larger value reserves more KV Cache.--gpu-memory-utilizationsets the fraction of VRAM that vLLM can use. 0.90 is common on 80 GB cards. Start at 0.85 on 24 GB cards. Raise the value only after you confirm that no other process uses VRAM.--max-num-seqslimits the number of sequences processed at the same time. It directly sets the concurrency ceiling and the VRAM pressure.--enable-prefix-cachingreuses computed results for shared prefixes, such as the same system prompt. It helps only when requests actually share a prefix.--host 127.0.0.1allows local access only. For external access, place the service behind a reverse proxy.
Parameter names depend on the vLLM version. Check the output of vllm serve --help for your version, and recheck it after each upgrade.
Verify the service:
curl http://127.0.0.1:8000/v1/chat/completions \-H "Authorization: Bearer $VLLM_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "my-llm", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 64}'
Without a key, or with the wrong key, the API should return 401. This confirms that authentication is enforced.
For long-running deployments, manage the service with systemd so it restarts automatically after an unexpected exit. Example unit file:
[Unit]Description=vLLM OpenAI-compatible serverAfter=network-online.target[Service]User=llmWorkingDirectory=/opt/llmEnvironmentFile=/etc/llm/vllm.envExecStart=/home/llm/llm-env/bin/vllm serve /opt/llm/models/<model-name> --served-model-name my-llm --host 127.0.0.1 --port 8000 --max-model-len 16384 --gpu-memory-utilization 0.85 --max-num-seqs 64Restart=on-failureRestartSec=10[Install]WantedBy=multi-user.target
The file /etc/llm/vllm.env should contain VLLM_API_KEY=<key>, and its permissions should also be set to 600. The virtual environment path must match your actual path.
To run inference from a local Python script, use the offline API. This API bypasses HTTP authentication, so use it only in local scripts:
from vllm import LLM, SamplingParamsdef main():try:llm = LLM(model="/opt/llm/models/<model-name>",gpu_memory_utilization=0.85,max_model_len=16384,)except Exception as e:print(f"Failed to load the model: {e}")raise SystemExit(1)params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=256)prompts = ["Explain what KV Cache is in three sentences."]outputs = llm.generate(prompts, params)for out in outputs:print(out.outputs[0].text.strip())if __name__ == "__main__":main()
Approach 3: Multi-GPU Enterprise Deployment (70B Class)
70B-class models usually need several GPUs. vLLM splits the model across GPUs with tensor parallelism (--tensor-parallel-size). The speed of communication between GPUs directly affects latency.
Checklist:
- GPUs in the same machine have the same model and VRAM capacity
- The GPU interconnect (NVLink or PCIe) is confirmed with
nvidia-smi topo -m - The driver, CUDA, and NCCL versions match the selected vLLM version
- The power supply and cooling support all GPUs running at full load
- The tensor parallel size divides evenly into the number of attention heads, which is listed in
config.jsonin the model directory
# Check the GPU topology. Connections that start with NV indicate NVLink.nvidia-smi topo -m# Use only the first four GPUsexport CUDA_VISIBLE_DEVICES=0,1,2,3export VLLM_API_KEY=$(sudo cat /etc/llm/vllm.key)vllm serve /opt/llm/models/<70B-model> \--served-model-name my-llm-70b \--host 127.0.0.1 \--port 8000 \--tensor-parallel-size 4 \--max-model-len 32768 \--gpu-memory-utilization 0.88 \--max-num-seqs 32 \--enable-prefix-caching
Calculate VRAM based on the number of GPUs. An INT8 70B model has weights of about 70 GB. Spread across four 80 GB GPUs (320 GB combined), the remaining space is available for the KV Cache. FP16 70B weights are about 140 GB, which also requires four or more GPUs.
When you run a multi-GPU service in Docker, add --ipc=host or set a large enough --shm-size. If shared memory is insufficient, communication between processes fails. Common symptoms are errors or hangs during startup.
After startup, confirm that every GPU shows VRAM in use. If only one GPU is loaded, the tensor parallel configuration probably did not take effect. To investigate, set NCCL_DEBUG=INFO to view the communication logs.
Approach 4: Chinese-Made AI Accelerators (Huawei Ascend NPU as an Example)
The drivers, runtime, and inference frameworks for Chinese-made AI accelerators differ from the CUDA ecosystem. The parameters and version mappings in Approach 2 cannot be applied directly, so follow the vendor documentation. This section uses Huawei Ascend as an example. Other platforms, such as Cambricon and Hygon DCU, follow a similar approach.
Checklist:
- The vendor’s supported model list includes the target model
- The driver, firmware, and CANN toolkit are installed according to the vendor documentation, with matching versions
- The service account belongs to the user group the vendor requires (typically HwHiAiUser on Ascend, per the official instructions)
- The version requirements of the inference framework are confirmed, such as the Ascend adaptation of vLLM or the vendor’s inference engine
# Check NPU status, temperature, and memory usagenpu-smi info# Load the CANN environment variables. Adjust the path to your installation.source /usr/local/Ascend/ascend-toolkit/set_env.sh
The startup command and parameters for the inference service depend on the framework’s documentation. The interface can follow the OpenAI-compatible format from Approach 2, changing only the address, port, and model name. The VRAM estimation method described earlier also applies here. Use the output of npu-smi info to read actual usage.
4. Performance Testing, Concurrency Tuning, and Troubleshooting
4.1 Key Metrics
- Time to first token (TTFT): the time from sending a request to receiving the first token. It determines how quickly users perceive a response.
- Output throughput: the number of tokens generated per unit of time. It measures the overall capacity of the service.
- P95 latency: 95% of requests finish within this time. It reflects the slowest experiences better than the average does.
- Error rate: the share of requests that fail because of timeouts, insufficient VRAM, or service crashes.
- Peak VRAM: the highest usage on each GPU during the load test.
4.2 Test Method
Fix the input length, output length, and prompt set for the test, and send a few warm-up requests before the formal run. Increase concurrency in steps of 1, 4, 8, and 16. Run each level for several minutes and record the metrics above.
Monitor utilization and VRAM on the server at the same time:
# Print utilization and memory information every 5 secondsnvidia-smi dmon -s um -d 5
The script below tests each concurrency level. The prompt is fixed, and temperature is set to 0 to reduce variation in output length:
import osimport timefrom concurrent.futures import ThreadPoolExecutorimport requestsURL = "http://127.0.0.1:8000/v1/chat/completions"HEADERS = {"Authorization": f"Bearer {os.environ['VLLM_API_KEY']}"}PAYLOAD = {"model": "my-llm","messages": [{"role": "user", "content": "Write a product introduction of about 200 words."}],"max_tokens": 256,"temperature": 0,}def send_one(_):start = time.time()resp = requests.post(URL, headers=HEADERS, json=PAYLOAD, timeout=300)resp.raise_for_status()tokens = resp.json()["usage"]["completion_tokens"]return time.time() - start, tokensdef run(concurrency, total):wall_start = time.time()with ThreadPoolExecutor(max_workers=concurrency) as pool:results = list(pool.map(send_one, range(total)))wall = time.time() - wall_startlatencies = sorted(r[0] for r in results)p95 = latencies[max(int(len(latencies) * 0.95) - 1, 0)]total_tokens = sum(r[1] for r in results)print(f"concurrency={concurrency} requests={total} "f"throughput={total_tokens / wall:.1f} tokens/s P95={p95:.2f}s")if __name__ == "__main__":for c in (1, 4, 8, 16):run(concurrency=c, total=c * 4)
This script measures only throughput and P95. To measure an exact TTFT, switch to streaming output and record when the first chunk arrives. The vLLM repository also provides an official benchmark script. Its parameters change between versions, so check its help output before you use it.
4.3 Concurrency and VRAM Tuning
Tune in the following order:
- Use the longest combined input and output length of the workload to set
--max-model-len. An overly large context wastes KV Cache. - With the context length fixed, raise
--max-num-seqsstep by step. Find the point where P95 latency starts to rise sharply. Values below that point work as the concurrency ceiling. - Raise
--gpu-memory-utilizationonly after confirming that no other process uses VRAM. Leaving headroom reduces the risk of out-of-memory (OOM) errors. - After each change, rerun the benchmark and compare the results.
