How to Download Open-Source LLM Weights and Deploy Them Locally: A Complete Guide
This guide walks developers and technical leads through the full process of running open-source large language models on their own servers. You will learn how to estimate storage and VRAM requirements, download model weights via Git LFS or a resumable Python script, verify file integrity with hash checks, choose an inference framework (Transformers, vLLM, SGLang, or TensorRT-LLM) based on your latency and throughput needs, launch an OpenAI-compatible API service, and prepare monitoring, rate limiting, and rollback strategies for production. All commands are examples and should be adapted to your model, GPU, and network environment.
This article is written for developers and technical leads who need to run open-source large language models on their own servers. After reading, you will be able to download weights and verify their integrity, pick an inference framework based on your VRAM budget, launch an OpenAI-compatible API service, and prepare monitoring and fallback strategies for going live. All commands are examples; adjust them to your model, GPU, and network environment.
1. Estimate Storage Space Before Downloading
You can roughly estimate the size of weight files with “parameter count × bytes per parameter.” At FP16 precision, each parameter takes 2 bytes, so a 7B-parameter model’s weights are about 14GB. Auxiliary files such as the tokenizer and configuration are usually small, but if a repository keeps multiple formats (for example, both .bin and .safetensors), the total size multiplies. Download only the format you actually need for inference, and reserve roughly 1.5x the disk space to accommodate temporary files during download.
Use an SSD for storage. A spinning hard drive becomes an obvious bottleneck when loading weights for the first time, and service cold-start time increases noticeably.
2. Downloading Weights with Git LFS
Most model hosting platforms use Git LFS to manage large files. With a normal clone, large files come down as pointer files of only a few hundred bytes; the real weights must be pulled separately via LFS. The commands below first fetch the repository structure, then pull only the files needed for inference:
sudo apt-get install -y git-lfsgit lfs install# Skip automatic download of large files; fetch the repo structure firstexport GIT_LFS_SKIP_SMUDGE=1git clone https://<platform-domain>/<org>/<model-repo>.git /data/models/llm-democd /data/models/llm-demo# Pull only safetensors weights, config files, and the tokenizergit lfs pull --include="*.safetensors,*.json,tokenizer*"
The placeholders in angle brackets must be replaced with the real address of your platform. For models that require authorization, use a personal access token and supply it through the Git credential helper or an environment variable. Do not write tokens directly into command-line history or script files.
3. On-Demand Download with Resume Using a Python Script
If the platform is compatible with the Hugging Face protocol, you can use the huggingface_hub library to download files by pattern, with parallel downloads and resumable transfers. If the download is interrupted, re-running the same script skips completed files and resumes incomplete ones from where they stopped.
import osfrom huggingface_hub import snapshot_downloadpath = snapshot_download(repo_id="<org>/<model-repo>",local_dir="/data/models/llm-demo",allow_patterns=["*.safetensors", "*.json", "tokenizer*"],max_workers=8,token=os.environ.get("HF_TOKEN"), # read the token from an environment variable)print("Download finished:", path)
Wrap the script in retry logic: wait with exponential backoff after failures (for example, 30s, 60s, 120s), and log the names of failed files to make network issues easier to diagnose.
4. Verifying File Integrity
Network interruptions or disk errors can corrupt weight files. Corrupted files sometimes still load and the service starts normally, but output quality degrades in ways that are time-consuming to debug. Always verify after downloading, following these three steps:
- Check the shard count. Open the index file (e.g., model.safetensors.index.json) and confirm that every shard it lists exists in the local directory.
- Check hashes. Run
git lfs ls-files -lto see the hash prefix of each large file, then compare it against the sha256 of the local file. - Check LFS objects. Run
git lfs fsckin the repository directory to verify that local objects are intact.
When computing sha256 for large files, read in chunks to avoid high memory usage:
import hashlibdef sha256_of(path, chunk_size=16 * 1024 * 1024):h = hashlib.sha256()with open(path, "rb") as f:for block in iter(lambda: f.read(chunk_size), b""):h.update(block)return h.hexdigest()print(sha256_of("/data/models/llm-demo/model-00001-of-00004.safetensors"))
For security, prefer the safetensors format. Files in .bin and .pt formats are based on pickle serialization and can execute arbitrary code when loaded. If a model requires trust_remote_code=True to load, review the Python files in the repository first and confirm they are safe before running.
5. Choosing an Inference Framework
The table below compares four common inference options. The conclusions are based on typical scenarios; actual performance depends on the model, hardware, and request load. Always benchmark with your own data before going live.
| Framework | Best for | Throughput and memory characteristics | Deployment complexity | Common issues |
|---|---|---|---|---|
| Transformers | Model debugging, small-scale experiments, pre-fine-tuning validation | Default generation does no continuous batching; throughput drops noticeably as concurrency rises | Low | Latency jitter under concurrency; high memory usage with long contexts |
| vLLM | General-purpose online serving with an OpenAI-compatible API | Uses PagedAttention to manage KV Cache; high throughput | Medium; CUDA version and driver must match | OOM at startup or runtime if memory utilization is set too high |
| SGLang | Multi-turn dialogue, structured output, workloads with many shared prefixes | Comparable to vLLM on most dialogue workloads; prefix cache is friendly to repeated prompts | Medium | Limited list of supported models; check in advance |
| TensorRT-LLM | Extreme latency/throughput requirements with a fixed model and hardware | Heavily optimized; typically the highest performance | High; requires building an inference engine first | The engine is bound to the GPU model and software version; changing the model requires a rebuild |
A practical decision order: use Transformers for debugging and validation. When you need to get a general-purpose online service up quickly, try vLLM first. If multi-turn dialogue or structured output dominates your traffic, compare measured results from SGLang. Only invest in TensorRT-LLM’s build and maintenance cost when the model and hardware are stable and you have hard performance targets.
6. Estimating Deployment Scale from Your VRAM Budget
VRAM used by weights equals parameter count times bytes per parameter. Quantization reduces bytes per parameter, but quantization scale parameters add a small overhead, so actual usage is slightly higher than the theoretical value:
| Parameters | FP16 (2 bytes) | INT8 (1 byte) | INT4 (~0.5 bytes) |
|---|---|---|---|
| 7B | ~14GB | ~7GB | ~4GB |
| 13B | ~26GB | ~13GB | ~7GB |
| 70B | ~140GB | ~70GB | ~35GB to 40GB |
KV Cache memory grows linearly with context length and concurrency. The formula is:
KV Cache bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
For an 8B-class model with 32 layers, 8 KV heads, head dimension 128, and FP16 precision: 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or about 128KB per token. A single 4K-context request uses about 512MB; serving 20 such requests concurrently requires about 10GB of KV Cache. At 128K context, a single request’s KV Cache reaches about 16GB—the most commonly underestimated cost in long-context deployments.
Total VRAM is estimated as: weights + KV Cache + framework and activation overhead. Framework overhead typically requires reserving 10% to 20% of total VRAM. Example: running the 7B FP16 model above on a 24GB GPU—weights take 14GB, leaving about 5GB after overhead, which holds roughly 5GB ÷ 128KB ≈ 40,000 tokens of KV Cache, enough for about 10 concurrent 4K-context requests. Switching to INT8 weights frees significantly more cache space, but you must validate output quality against a business-relevant evaluation set.
7. Launching an OpenAI-Compatible Service
The following uses vLLM as an example. Before installing, confirm that the CUDA version is compatible with your GPU driver, and refer to the official documentation for current versions:
pip install vllmexport API_KEY="<replace with a randomly generated key>"vllm serve /data/models/llm-demo \--tensor-parallel-size 2 \--max-model-len 8192 \--gpu-memory-utilization 0.85 \--host 0.0.0.0 --port 8000 \--api-key "$API_KEY"
Parameter notes: --tensor-parallel-size sets the number of GPUs used for tensor parallelism and must match your actual GPU count. --max-model-len limits the maximum context length per request and directly affects how much KV Cache is reserved. --gpu-memory-utilization controls the fraction of VRAM vLLM may use; setting it too high makes OOM likely under heavy load. --host 0.0.0.0 listens on all interfaces, so only expose this port on an internal network or behind a gateway.
After the service starts, run a smoke test with curl:
curl http://127.0.0.1:8000/v1/chat/completions \-H "Authorization: Bearer $API_KEY" \-H "Content-Type: application/json" \-d '{"model": "/data/models/llm-demo", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 64}'
If you choose SGLang instead, the launch command is:
python -m sglang.launch_server \--model-path /data/models/llm-demo \--tp 2 \--host 0.0.0.0 --port 30000
8. Common Errors and Troubleshooting
- CUDA out of memory: try, in order, lowering
--max-model-len, lowering--gpu-memory-utilization, increasing the number of tensor-parallel GPUs, or switching to quantized weights. - Weight loading fails with tensor shape mismatch: check the weight file sizes first. If a file is only a few hundred bytes, you have an LFS pointer file; run
git lfs pullto fetch the real content. - Very slow first startup: compiling kernels and capturing CUDA graphs takes time. A slow first launch is normal; subsequent launches are much faster.
- Garbled output or the model never stops: this usually means the chat template does not match the model. Check the chat_template setting in tokenizer_config.json and confirm your request format matches the format used during training.
9. Moving to the Cloud: Baidu AI Cloud as an Example
When a single machine cannot meet high-availability and elastic-scaling requirements, consider migrating to the cloud. The following uses Baidu AI Cloud as an example; the same approach applies to other cloud platforms or self-managed clusters.
Containerization and autoscaling. Package the inference engine as a Docker image and deploy it to a managed Kubernetes service such as Baidu AI Cloud’s CCE. Kubernetes’ default Horizontal Pod Autoscaler (HPA) only works with CPU and memory metrics and cannot directly sense GPU state. You therefore need a tool such as the Prometheus Adapter to expose VRAM utilization or request queue length as custom metrics and trigger scaling from those.
Storing and mounting model weights. In multi-node deployments, having every node pull tens of gigabytes of weights consumes significant bandwidth. Store the weights centrally in object storage (such as BOS) or high-performance file storage, and mount them at node startup. Cold-start time can be roughly estimated as: startup time ≈ weight size ÷ actual read bandwidth + load and warm-up time. For example, 14GB of weights at 500MB/s effective read bandwidth takes about 28 seconds just to read, and the total will be longer once loading and warm-up are included. Image caching, shared-storage bandwidth, and node readiness all affect this number, so measure it in your target environment before using it for capacity planning.
Alternatives. If your organization already runs a self-managed Kubernetes cluster, use NFS or Ceph for shared storage. If data compliance requirements are strict, use physical servers in your own data center with Docker Compose or systemd to manage the service. Weigh data compliance requirements, cost structure, and your team’s operational capacity when choosing.
10. Monitoring and Degradation Strategies Before Go-Live
Production environments require continuous observability of the inference service. The thresholds below are starting points only; adjust them to your business baseline:
| Metric | Example alert threshold | Notes |
|---|---|---|
| P99 time to first token (TTFT) | Above 2s for 5 minutes | Depends on input length; set per business scenario |
| 5xx error rate | Above 1% for 5 minutes | Indicates server-side errors; investigate with logs |
| GPU memory utilization | Above 90% for 10 minutes | Near the limit, OOM becomes likely |
| GPU temperature | Above the limit in the hardware spec sheet | High temperatures cause throttling and hurt latency |
| Request queue length | Above 2x the concurrency limit for 3 minutes | A growing queue indicates insufficient capacity |
When alerts fire, apply degradation strategies in this order. First, rate-limit by tenant or API key to protect core business traffic. Second, route very long-context requests to a separate resource pool, or return a queueing notice directly. Third, if a standby node exists, shift traffic to it. Failover requires that the standby node already has the same image version and weights prepared and has passed the same verification. Keep the previous image tag and weight directory for every release so you can roll back quickly if a switch fails.
11. How Next-Generation Models Affect Deployment
Longer context windows make KV Cache the dominant source of memory pressure; the estimation formula above applies directly. Multimodal models also introduce image or audio encoding steps, whose latency and memory usage need separate monitoring—you cannot rely on text-generation metrics alone. Low-bit quantization (such as INT4) can significantly reduce deployment cost, but the accuracy loss varies by model and task. Validate with an evaluation set relevant to your business; do not judge from theoretical numbers alone.
12. Summary
Local deployment of open-source LLMs breaks down into four stages. First, estimate storage and VRAM to determine hardware scale. Second, obtain weights via Git LFS or a resumable script, and verify hashes and shard completeness. Third, choose an inference framework based on latency, throughput, and maintenance cost, and benchmark with your own workload. Fourth, configure monitoring thresholds, rate limiting, and rollback plans before going live. Each stage has concrete checklist items; confirming them one by one significantly reduces rework after launch.
