Deploying 100B-Scale Open-Source LLMs: A Practical Guide to VRAM Planning, Long-Context Reasoning, and Long-Horizon Tasks
When selecting a large language model, calculating VRAM and cost requirements upfront prevents far more rework than comparing leaderboard scores. Using Qwen2.5-72B-Instruct (released September 2024) and DeepSeek-V3 (released December 2024) as examples, this guide explains how to deploy very large open-source models and how to put long-document understanding and long-horizon agent tasks into production. Model parameters, licenses, and hardware requirements should always be verified against the official model cards, as versions may change.
In model selection, calculating VRAM and cost requirements upfront prevents far more rework than comparing leaderboard scores. Using Qwen2.5-72B-Instruct (released September 2024) and DeepSeek-V3 (released December 2024) as examples, this guide explains how to deploy very large open-source models and how to put long-document understanding and long-horizon agent tasks into production. Model parameters, licenses, and hardware requirements should always be verified against the official model cards, as versions may change.
1. Estimate VRAM Before Choosing Hardware
The VRAM required by model weights can be approximated with this formula:
Weight VRAM ≈ parameter count × bytes per parameter × 1.2
Bytes per parameter: 2 for FP16/BF16, 1 for INT8, 0.5 for INT4. The 1.2 multiplier covers extra overhead such as quantization constants, unquantized layers (like the output layer), and activations.
For a 72B-parameter model:
| Precision | Theoretical weight size | Estimate with margin |
|---|---|---|
| FP16/BF16 | ~144 GB | ~173 GB |
| INT8 | ~72 GB | ~86 GB |
| INT4 | ~36 GB | ~43 GB |
Inference also requires the KV Cache, which can be estimated as:
KV Cache bytes = 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element
Qwen2.5-72B’s public configuration has 80 layers, 8 KV heads, and a head dimension of 128. In BF16, that works out to roughly 320 KB per token. With a 32K context and batch size of 1, the KV Cache occupies about 10 GiB. So an INT4-quantized model plus a 32K-context cache needs around 53 GiB in total, which fits on a single 80GB GPU. With FP16 weights, multi-GPU parallelism becomes mandatory.
2. Working Loading Code
The following code loads the model with 4-bit quantization and automatic multi-GPU device mapping, falling back to PyTorch’s built-in SDPA implementation when flash-attn is unavailable.
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfigMODEL_PATH = "/data/models/Qwen2.5-72B-Instruct" # Local directory with full weights# Example dependency versions: transformers>=4.45, bitsandbytes>=0.43, accelerate>=0.30# Optional: flash-attn>=2.5, must match your local CUDA version and GPU architecturebnb_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch.bfloat16,bnb_4bit_use_double_quant=True,)# Example configuration for two 48GB GPUs, with CPU as overflow fallbackMAX_MEMORY = {0: "40GiB", 1: "40GiB", "cpu": "64GiB"}def load_model():common = dict(quantization_config=bnb_config,device_map="auto",max_memory=MAX_MEMORY,torch_dtype=torch.bfloat16,)try:return AutoModelForCausalLM.from_pretrained(MODEL_PATH, attn_implementation="flash_attention_2", **common)except ImportError:# Fall back to SDPA if flash-attn is not installed or version-mismatchedreturn AutoModelForCausalLM.from_pretrained(MODEL_PATH, attn_implementation="sdpa", **common)tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)try:model = load_model()except torch.cuda.OutOfMemoryError:raise SystemExit("Out of VRAM: reduce concurrency or context length, or add more GPUs.")print("Model loaded. VRAM usage per GPU:")for i in range(torch.cuda.device_count()):print(f"GPU {i}: {torch.cuda.memory_allocated(i) / 1024**3:.1f} GiB")
A few points to note in this code:
trust_remote_codeis not enabled here. Only enable it for models from sources you fully trust, since it executes Python code from the model repository.- Falling back from flash-attn to SDPA is slightly slower but produces identical outputs, so it is safe to use.
- Quantization introduces precision loss. Before going live, compare FP16 and INT4 outputs on a fixed evaluation set rather than simply confirming the model loads successfully.
3. Long Context vs. RAG
Long context and retrieval-augmented generation (RAG) address the same class of problem, but they suit different scenarios.
| Dimension | Direct long-context input | RAG |
|---|---|---|
| Implementation complexity | Low; a single call suffices | High; requires chunking, vectorization, and retrieval |
| Latency and cost | Longer context means slower prefill and higher per-token billing | Only top-K chunks are sent, so cost stays stable |
| Information retrieval | Relies on the model locating information in long text; recall for mid-context content may degrade | Upper bound set by retrieval quality; results are traceable to source documents |
| Best suited for | Holistic understanding of a single document, such as reading an entire contract | Large-scale knowledge-base Q&A with frequently updated documents |
Start with long context to validate your prototype. If evaluation shows that mid-context information is frequently missed, then introduce RAG. Chunk size and the Top-K value must be tuned against your evaluation set; there is no universally optimal setting.
4. Long-Horizon Tasks: From One Sentence to an Analysis Report
A long-horizon task is one where the model autonomously decomposes a goal, calls tools, and proceeds based on the results. Take “analyze the last three months of sales data and identify the causes of the decline” as an example. A controllable execution flow typically looks like this:
- The model generates query statements, which are executed under a read-only database account after permission checks, returning the sales records.
- The model writes Python code for data cleaning and aggregation, executed inside a container or sandbox.
- The result of every tool call is fed back to the model, which decides the next step.
- Set a maximum number of steps (e.g., 10) and a maximum retry count per step (e.g., 2). Exceeding either limit halts execution and reports what has been completed to the user.
- Before producing the report, verify that key figures are consistent with the original query results.
The most common agent failure mode is infinite retrying after a tool call error, which spirals token costs and latency out of control. Step limits and retry limits must be enforced in code, not left to prompt instructions.
5. LoRA vs. Full Fine-Tuning
| Dimension | LoRA (low-rank adaptation) | Full fine-tuning |
|---|---|---|
| VRAM requirements | Trains only small low-rank matrices; far less VRAM than full fine-tuning | Requires gradients and optimizer states for all parameters; typically needs multiple GPUs |
| Data requirements | Works with smaller datasets, but sensitive to annotation quality | Needs more high-quality data; prone to overfitting when data is insufficient |
| Retention of general capabilities | Minimal change to existing abilities | Higher risk of catastrophic forgetting; general data must be mixed in |
| Best suited for | Adapting domain terminology, output formats, and tone | Substantially changing model behavior when compute is abundant |
Before fine-tuning, first verify with prompting or RAG that the need is real. Many scenarios can be solved by improving retrieval or prompts alone, with no model training required.
6. Selection and Evaluation Checklist
The evaluation framework should be established before model selection. The table below provides a ready-to-use structure; thresholds must be set by the business side based on fault tolerance.
| Metric | Measurement method | Example threshold | Tooling | Cost basis |
|---|---|---|---|---|
| Instruction-following accuracy | Build 200 constrained instructions and judge compliance one by one | ≥90% | Scripts plus manual review | Manual annotation hours |
| Long-context recall | Embed facts at 16K and 32K positions; measure QA hit rate | ≥85% at 32K | Custom scripts | GPU hours |
| Task planning success rate | Prepare 20 multi-step tasks; count end-to-end completions | ≥70% | Log replay | Average tokens per task |
| Inference latency | Fix input/output lengths; measure P50 and P95 | Per business SLA | vLLM or TGI benchmarking | GPU cost per hour |
| Cost per call | Input and output token counts × unit price | Below budget line | Billing logs | USD per thousand calls |
Manual sampling rates can be tiered by risk. For routine Q&A, sample 5% weekly; for high-risk scenarios involving contracts, finance, or medical content, the sampling rate should be no less than 20%.
7. Common Mistakes
- Deploying a quantized model directly without comparing it against the unquantized baseline.
- Estimating VRAM from weights alone while ignoring the KV Cache, causing out-of-memory errors under high concurrency.
- Assuming long context is fully utilized, while overlooking how recall varies with information position.
- Letting agents retry failed tool calls indefinitely, leading to runaway costs.
- Allowing model outputs to directly trigger database writes without permission checks and human confirmation.
8. Implementation Recommendations
- Use an evaluation set to determine the model and quantization precision first, then select hardware based on the VRAM estimate.
- For long-document scenarios, prototype with long context first; add RAG only when recall proves insufficient.
- Treat fine-tuning as the last resort. Consider LoRA only when neither prompting nor RAG can meet the requirement.
