Enterprise Deployment of Open-Source LLMs: VRAM, Quantization, and RAG Implementation
Enterprises replacing or supplementing external LLM APIs with open-source models need to answer four questions: Is the hardware sufficient? Can the model run locally? Can a general-purpose model handle the business need? How can enterprise knowledge be supplied to the model? This article walks through each question with checkable formulas, Python code, and acceptance criteria for VRAM estimation, INT8/INT4 quantization and 4-bit loading, LoRA fine-tuning, and permission-aware RAG. It also covers license, privacy, and common deployment failures. This article is not legal advice; license and compliance conclusions must be confirmed by legal or compliance personnel.
1. Estimate VRAM Before Choosing Hardware
VRAM is the first obstacle to local deployment. Model weights are stored at a specific precision: FP16 uses 2 bytes per parameter, INT8 uses 1 byte, and INT4 uses roughly 0.5 byte.
| Parameter count | FP16 | INT8 | INT4 |
|---|---|---|---|
| 10B | About 20 GB | About 10 GB | About 5–6 GB |
| 70B | About 140 GB | About 70 GB | About 35–40 GB |
The table above covers weights only. Actual VRAM usage has four components:
Total VRAM ≈ weights + framework/CUDA overhead + activations + KV cache
Framework overhead varies by environment and should be measured on the target machine. As a practical margin, reserve 10% to 20% of total VRAM.
KV Cache is the easiest component to underestimate in long-context or high-concurrency scenarios:
KV Cache bytes = 2 × layers × KV heads × head dimension × context length × concurrency × bytes per element
The coefficient 2 accounts for the separate K and V caches. With 80 layers, 8 KV heads, 128 head dimension, and FP16 (2 bytes per element):
- Single request, 4K context: 2 × 80 × 8 × 128 × 4096 × 1 × 2 ≈ 1.34 GB
- Single request, 128K context: about 32 times larger, ≈ 42.9 GB
- 8 concurrent requests, 4K context: ≈ 10.7 GB
The layer count and head count above are assumptions. Replace them with values from the model’s config.json.
For MoE models, consider two things separately. All expert weights must stay resident in VRAM, so VRAM is estimated from total parameter count. At inference, only a subset of experts is activated, so compute and latency depend mainly on activated parameters.
For example, a 70B model in INT4 uses about 35–40 GB for weights. With 8 concurrent requests and 4K context, add about 10.7 GB for KV Cache and 10%–20% headroom. Total demand is roughly 50–60 GB. A single 80 GB GPU can carry this workload, but it still needs to be measured on the actual machine.
2. Choose Quantization Precision and Load a 4-bit Model
The trade-off between INT8 and INT4 is as follows. INT8 uses about half the VRAM of FP16 and usually has smaller accuracy loss, making it suitable for precision-sensitive tasks such as contract clause extraction. INT4, especially NF4, uses the least VRAM and is useful for high-concurrency or memory-constrained Q&A scenarios, but complex reasoning and code generation are more likely to degrade. The final decision should be based on local evaluation.
Environment requirements:
- Python 3.10 or newer, an NVIDIA GPU, and a matching driver and CUDA version.
torch,transformers,accelerate, andbitsandbytesversions must be compatible with each other. Pin them in a virtual environment and record them inrequirements.txt.bitsandbytesis sensitive to CUDA versions and operating systems. Check the official documentation for supported platform combinations.
Loading code:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfigMODEL_ID = "your-org/your-open-model" # Replace with the model ID from the model cardREVISION = "main" # Pin to a specific commit in productionbnb_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch.bfloat16,bnb_4bit_use_double_quant=True,)tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)model = AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=REVISION,quantization_config=bnb_config,device_map="auto",torch_dtype=torch.bfloat16,)model.eval()messages = [{"role": "user", "content": "Explain RAG in two sentences."}]input_ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device) # If this returns a dict, use input_ids = inputs["input_ids"]with torch.no_grad():output_ids = model.generate(input_ids, max_new_tokens=256, do_sample=False)answer = tokenizer.decode(output_ids[0][input_ids.shape[-1]:], skip_special_tokens=True)print(answer)
Key parameter notes:
nf4is a commonly used 4-bit quantization type.- Double quantization saves additional VRAM by quantizing the constants used during quantization.
compute_dtypedetermines the precision used during computation.device_map="auto"assigns layers automatically. If VRAM is insufficient, some layers may be placed on CPU, which slows inference significantly. Confirm VRAM capacity first.
Keep trust_remote_code at its default value of False. If a model requires it, review the remote code first and pin it to a specific commit.
Quantization acceptance method: prepare 200 to 500 business samples. Test them in FP16 or INT8, if FP16 cannot fit, and again under the target quantization precision. Record accuracy, citation correctness, and output format compliance. A suggested threshold is no more than 2 percentage points below the baseline; the exact threshold depends on business risk. If accuracy is insufficient, fall back to INT8, use a larger GPU, or use a smaller model.
3. Use LoRA for Domain Adaptation
LoRA is useful when the model is unstable with domain terminology, output formats, or industry-specific wording. If the problem is simply that the model lacks enterprise knowledge, prefer RAG before fine-tuning. Test prompts first. If prompt engineering already meets the target, fine-tuning is unnecessary.
Data preparation:
- Use JSONL format, with one
messagessample or instruction-output sample per line. - Remove duplicate samples, delete personal information such as phone numbers and ID numbers, and do not mix expired documents into the dataset.
- Split data into 90% training, 5% validation, and 5% test. The test set must never be used for training.
- Start with a few hundred samples to verify the workflow, then expand data only after confirming measurable improvement.
LoRA configuration:
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_trainingmodel = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)lora_config = LoraConfig(r=16,lora_alpha=32,lora_dropout=0.05,bias="none",task_type="CAUSAL_LM",target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],)model = get_peft_model(model, lora_config)model.print_trainable_parameters()
The names in target_modules vary by model architecture. Use model.named_modules() to confirm them.
Starting training parameters:
| Parameter | Starting value | Notes |
|---|---|---|
| learning_rate | 1e-4 to 2e-4 | Higher values can cause oscillation |
| num_train_epochs | 1 to 3 | Stop when validation loss rises |
| per_device_train_batch_size | 1 to 4 | Reduce if VRAM is insufficient |
| gradient_accumulation_steps | 4 to 16 | Increases effective batch size |
| max_seq_length | Based on data distribution | Measure the sequence length distribution first |
In QLoRA, the base model is loaded in 4-bit and LoRA parameters account for only a small fraction of memory. Training memory is dominated by base weights, activations, and sequence length. Gradient checkpointing reduces activation memory at the cost of slower training.
Save only the adapter directory:
model.save_pretrained("./lora_adapter")
At inference time, load the base model and attach the adapter. Back up the previous adapter before overwriting it. Compare the fine-tuned model against the base model on the test set: format compliance rate, terminology accuracy, and human scoring.
4. Build RAG for Knowledge-Base Q&A
A complete RAG pipeline has five steps:
- Document parsing: convert PDF, Word, and Markdown files to plain text while preserving heading levels and page numbers.
- Chunking: split by heading or paragraph into chunks of roughly 300–800 characters, with 50–100 characters of overlap. These are starting recommendations and should be calibrated with retrieval metrics.
- Embedding: use a locally deployed embedding model to vectorize chunks and write them into a vector store. Store metadata with each chunk, including source file, version, and permission group.
- Retrieval: fetch the top k results; start with k between 5 and 10. A reranker can optionally improve ranking quality.
- Generation: place retrieved results into the prompt, require the model to answer only from the materials, and cite source numbers. If the materials are insufficient, the model should answer that no relevant information was found.
Below is a minimal example that does not depend on an external vector database:
import numpy as npfrom sentence_transformers import SentenceTransformerembedder = SentenceTransformer("/path/to/local/embedding-model") # Replace with local model pathdef build_index(chunks):return np.asarray(embedder.encode(chunks, normalize_embeddings=True))def retrieve(query, chunks, index, metas, user_groups, k=5):# Permission filtering happens before scoring; unauthorized documents never enter later stages.allowed = [i for i, m in enumerate(metas) if m["group"] in user_groups]if not allowed:return []q = embedder.encode([query], normalize_embeddings=True)[0]scores = index[allowed] @ qtop = np.argsort(-scores)[:k]return [(chunks[allowed[i]], metas[allowed[i]], float(scores[i])) for i in top]def build_prompt(question, hits):context = "\n".join(f"[{i + 1}] ({m['source']}) {text}" for i, (text, m, _) in enumerate(hits))return ("Answer only from the materials below. Mark each conclusion with a source number. ""If the materials are insufficient, answer: No relevant information was found in the provided materials.\n"f"Materials:\n{context}\nQuestion: {question}")
Permission control must happen before retrieval. If filtering is done only after retrieval, sensitive chunks may still enter the prompt and logs.
RAG acceptance metrics:
| Metric | How to measure | Target |
|---|---|---|
| Retrieval recall@k | Annotate the chunk that contains the standard answer, then measure how often it appears in the top k results | Set by business |
| Citation hit rate | Sample answers and check whether cited source numbers actually support the stated conclusion | Set by business |
| Answer accuracy | Human sampling, scored by whether the answer is correct | Set by business |
| Hallucination rate | Sample answers and measure the proportion of conclusions with no basis in retrieved materials | Set by business |
| Time to first token | Measure from request submission to first output token, report P50 and P95 | Set by business |
| Throughput | Measure generated tokens per second at a defined concurrency level | Set by business |
5. License, Privacy, and Troubleshooting
License review must be item by item. Model weights, inference code, training data, embedding models, and dependency libraries may each be under a different license. Read the model card and the LICENSE files in each repository. Permissive licenses such as MIT address copyright authorization only; they do not cover patents, trademarks, or compliance risks from model output. If fine-tuning data contains third-party copyrighted content, responsibility still rests with the user. Put license review into the project initiation process and have legal or compliance personnel confirm before entering production.
Privacy controls:
- Store sensitive documents only locally or in controlled environments. Do not send them to unapproved external endpoints.
- Do not log original text. Log sanitized questions and citation IDs only.
- Restrict access to vector stores and adapter files, and encrypt them at rest.
Troubleshooting checklist:
| Symptom | Common cause | Fix |
|---|---|---|
| CUDA out of memory | Context too long, concurrency too high, or batch size too large | Reduce context, lower max_new_tokens and concurrency, reduce batch size, enable gradient checkpointing |
bitsandbytes errors |
Version and CUDA mismatch, or unsupported platform | Check the compatibility matrix and rebuild the virtual environment if necessary |
| Some layers offloaded to CPU, very slow | Insufficient VRAM with device_map="auto" |
Confirm VRAM headroom, use a larger GPU, or use lower precision |
| No chat template found | Model repository does not provide one | Construct the prompt format manually according to the model card |
| Repeated or garbled output | Wrong eos/pad token settings or poor sampling parameters | Check tokenizer eos and pad settings, then adjust generation parameters |
| Empty retrieval results | Permission filter too strict, or chunking and embedding are inconsistent | Check user permission groups and metadata, and confirm that query and index use the same embedding model |
| Worse after fine-tuning | Learning rate too high or noisy training data | Lower the learning rate, inspect cleaning results, and use early stopping on validation loss |
Data loss risk mainly comes from overwriting files and accidental deletion. Back up datasets before training. Keep previous versions before overwriting adapters or vector stores. Before deleting directories or overwriting files, confirm the path first.
If the steps above are completed and VRAM estimates, quantization acceptance, fine-tuning comparison, and RAG metrics all meet business requirements, the system can enter a pilot phase. During the pilot, record every human review result as the basis for later adjustments.
