Self-Hosting Large Language Models: Five Steps to Cost It Out Before Going Live
Many teams are moving from cloud-based LLM APIs to self-hosting open-weight models for better data control and predictable costs. But the real costs show up in GPU memory planning, inference deployment, fine-tuning, and ongoing operations. This article walks through five practical steps before going live: estimating GPU memory, deploying inference, domain fine-tuning, choosing a deployment location, and running a go-live checklist—with concrete guidelines you can apply directly.
From API Calls to Owning Model Weights
Enterprises have mostly used large language models through cloud-based APIs. This approach is quick to start, but it has three recurring problems: sensitive data must leave the corporate network; under high concurrency, network latency and per-call fees grow with usage; and black-box interfaces give you no way to modify the model’s internal computation.
Recently, teams have released complete model weight files. Developers can download open weights to local machines or private clouds, run inference on their own hardware, fine-tune on domain data, and tune inference-service parameters. In short, the shift is from a “pay-per-call service” to a “model asset you control.”
But getting the weights is only the starting point. The real costs of self-hosting appear in GPU memory planning, inference deployment, version management, and day-to-day operations. This article covers five steps and what to calculate at each one: memory estimation, inference deployment, domain fine-tuning, deployment location, and a go-live checklist. Each step comes with directly actionable criteria.
Step 1: Estimate GPU Memory Before Choosing Hardware
The memory used by model weights can be estimated with a simple formula:
Weight memory ≈ parameter count × bytes per parameter
FP16 uses 2 bytes per parameter, INT8 uses 1 byte, and INT4 uses 0.5 bytes. For a 10B-parameter model, FP16 weights require roughly 20GB.
The table below covers weights only, in GB (1GB = 10^9 bytes). If you convert to GiB (1GiB = 2^30 bytes), the figures are about 93% of the values shown.
| Model Size | FP16 Weights | INT8 Weights | INT4 Weights |
|---|---|---|---|
| 7B | ~14GB | ~7GB | ~3.5GB |
| 13B | ~26GB | ~13GB | ~6.5GB |
| 70B | ~140GB | ~70GB | ~35GB |
Note that these values are not your production memory requirement. You also need to add three components:
- KV cache: the model stores intermediate results for every generated token; its size scales with batch size and context length. With long contexts and high concurrency, it often takes more memory than the weights themselves.
- Activation memory: temporary data produced during forward passes.
- Framework and driver overhead.
Before going live, run load tests with realistic request lengths and concurrency levels, use the measured peak memory as your baseline, and leave headroom.
When memory falls short, multi-GPU parallelism is the common solution. Tensor parallelism splits each layer’s weights across GPUs and requires inter-GPU communication on every forward pass; it suits scenarios with high interconnect bandwidth within a single server. Pipeline parallelism splits the model by layers into stages, with lower communication volume but pipeline bubbles; it suits multi-machine deployments.
For a 70B model with FP16 weights (~140GB total), tensor parallelism across four 80GB GPUs puts roughly 35GB of weights on each card, leaving room for KV cache and activations. With only two cards, the weights nearly fill the memory, leaving almost nothing for the KV cache. The tensor parallel size must also evenly divide the model’s number of attention heads—check the model’s configuration file for exact requirements.
Step 2: Loading and Inference Deployment
The code below is illustrative only and cannot run as-is. Framework names and interfaces are placeholders.
# Pseudocode: local LLM loading and inference flow (illustrative, not runnable)import deep_learning_framework as dlconfig = dl.ModelConfig(pretrained_weights_path="./local_model_weights/", # directory must contain full config files and weight shardsdtype="float16",tensor_parallel_size=4, # must match the number of available GPUs and evenly divide the attention head count)tokenizer = dl.AutoTokenizer.from_pretrained(config)model = dl.AutoModelForCausalLM.from_pretrained(config)inputs = tokenizer("Explain the core principles of vector databases", return_tensors="pt")outputs = model.generate(**inputs, max_new_tokens=500) # cap the generated lengthprint(tokenizer.decode(outputs[0]))
To turn the pseudocode into a working service, follow these steps:
- Choose an inference framework, read its official documentation, and find the actual interfaces for model loading, tokenization, and generation.
- Replace the package names, class names, and parameter names in the sample code with the framework’s real ones. Parameter names vary considerably across frameworks—don’t rely on memory.
- Run the full pipeline with a small model first to confirm normal output, then switch to your target model.
- Record the framework version, CUDA version, and launch command in your deployment documentation.
To get multi-GPU setups working, you also need:
- Environment dependencies: pin the versions of Python, the CUDA driver, and the inference framework, and isolate them in a virtual environment or container. Version drift is a common cause of failed deployments.
- Parallel launch: multi-GPU scenarios typically run through a launcher provided by the framework rather than executing a single script directly. Consult your framework’s documentation for the exact command.
- Memory verification: before starting, use
nvidia-smito confirm available memory on each GPU and that the tensor parallel size matches the number of available cards.
When you hit out-of-memory (OOM) errors, troubleshoot in this order:
- Reduce the maximum sequence length or the maximum tokens generated per request.
- Lower the maximum batch size or limit concurrent requests.
- Switch to INT8 or INT4 quantized weights, and use an evaluation set to confirm the quality drop is acceptable.
- Check whether other processes are sharing the same GPU.
- Check KV-cache-related settings, such as whether paged management is enabled.
PagedAttention reduces memory fragmentation in the KV cache. Continuous batching lets requests join or leave the batch during generation, improving GPU utilization. The actual gains from both depend on your request length distribution and concurrency patterns—validate with real traffic.
Step 3: Domain Fine-Tuning and Data Engineering
Base models are trained on general-purpose corpora. Their understanding of terminology and conventions in vertical domains—medical imaging reports, legal contracts, industrial code—can be off. Fine-tuning narrows that gap.
Full fine-tuning updates all parameters and demands substantial memory and storage. Parameter-efficient fine-tuning (PEFT) is the more common choice. With LoRA, for example, base weights are frozen and low-rank matrices are trained in parallel branches at designated layers. The resulting delta files are small and easy to store and swap.
A common starting configuration looks like this; confirm the module names against your model’s architecture:
lora:r: 16 # rank; common starting points are between 8 and 16lora_alpha: 32 # typically 2x rlora_dropout: 0.05target_modules: [q_proj, k_proj, v_proj, o_proj] # attention layers to inject into; replace based on model architecture
How much memory LoRA saves has no single answer. The savings depend on:
- LoRA rank: higher rank means more trainable parameters.
- Batch size and sequence length: both determine activation memory usage.
- Optimizer and precision settings.
- Gradient checkpointing: trades longer training time for lower memory usage.
- The range of targeted layers.
Run a short test of both full fine-tuning and LoRA on the same machine, record peak memory and runtime, then decide which approach to use.
Data quality usually matters more than training tricks. Enterprises can curate internal Q&A pairs and high-quality business logs into instruction datasets. During curation, keep these points in mind:
- Deduplicate, and remove or anonymize samples containing personal information.
- Keep input and output formats consistent.
- Split training, validation, and test sets by task, and ensure test data never leaks into training data.
- Measure results with fixed evaluation metrics—never rely on training loss alone.
Define evaluation metrics in advance. A workable approach:
| Metric | Definition | Suggested Test Set Size |
|---|---|---|
| Task accuracy | Percentage of samples where model output matches the reference answer, with matching rules documented in the evaluation doc | At least 300 samples |
| Human scoring | Average of scores (1–5) from two reviewers; a third reviewer breaks ties when scores differ by more than 1 point | At least 100 samples |
After training, you can merge the LoRA delta into the base weights or keep it as a standalone adapter. Merging simplifies inference but eliminates the ability to quickly switch between adapters. Either way, practice version management: record the base model version, data version, hyperparameters, and evaluation results. When quality regresses, the team can quickly roll back to the last stable version.
Step 4: Choosing Where to Deploy
Deployment location determines latency, cost, data compliance, and operational burden. Three common options:
| Dimension | Cloud API | Enterprise Private Cloud | On-Device (Local Hardware) |
|---|---|---|---|
| Data compliance | Data leaves the network; dependent on provider agreements | Data stays in an environment you control | Data stays on the device; strongest compliance |
| Latency | Network-dependent and variable | Low, controllable intranet latency | No network latency, but limited by device compute |
| Bandwidth | Public bandwidth consumed per call | Minimal impact with sufficient intranet bandwidth | No bandwidth needed |
| Cost structure | Pay per call; cheap at low volume | Fixed hardware and operations investment; lower unit cost at high volume | High device procurement cost; limited model size |
| Model capability ceiling | Access to the latest, largest models | Limited by GPUs purchased | Usually limited to small or quantized models |
| Ops skill required | Low | High; requires dedicated GPU cluster maintenance | Medium; requires device distribution and update management |
Work through these questions when deciding:
- Is business data forbidden from leaving the corporate network? If so, rule out cloud APIs.
- Is daily call volume stable and substantial? If so, a private cloud usually has a lower unit cost—compare total monthly cost against API fees.
- Is there dedicated staff for GPU cluster monitoring, incident handling, and driver upgrades? If not, the hidden costs of self-hosting will be high.
- Does the use case require offline operation or strict first-token latency? If so, on-device or an intranet private cloud fits better.
- Does the task require the full capability of a large model? If so, small models on-device may fall short.
Most enterprises end up with hybrid deployments: sensitive workloads on a private cloud, general Q&A and low-sensitivity tasks on cloud APIs.
Step 5: The Go-Live Checklist
Confirm each item below before going live, and keep verifiable records for every one.
- Capacity load testing: stress test with realistic request lengths and concurrency; record peak memory, first-token latency, and throughput. Leave headroom in production capacity; the margin depends on your traffic variability.
- Version locking: record the file hash of model weights, inference framework version, CUDA version, and container image tag. Any change requires re-running load tests.
- Monitoring and alerting: monitor memory usage, KV cache usage, batch size, queued requests, first-token latency, and error rate. Set thresholds for each metric and notify on-call staff when thresholds are exceeded.
- Canary rollout: start with 5% of traffic, expand to 20% after observation, then go fully live. Check quality and latency metrics at every stage.
- Rollback plan: retain the previous stable version’s weights, images, and configuration. Document rollback triggers and procedures, and rehearse the rollback once.
- Access auditing: restrict read/write permissions on model files, enable authentication on inference endpoints, log the user, timestamp, and request size for every call, and anonymize sensitive content in logs.
- Cost accounting: calculate monthly cost using the template below and compare it against your cloud API bill.
| Cost Item | Calculation | Example (for illustration; replace prices with actual quotes) |
|---|---|---|
| GPU cost | GPU count × hourly rate per GPU × monthly running hours | 4 GPUs × $2.8/hour × 720 hours = ~$8,060 |
| Power and data center | Total power draw × electricity price × running hours | Based on actual facility rates |
| Operations staff | Headcount × monthly labor cost | Based on actual team cost |
| Storage and backup | Number of model versions × size per version × storage price | Based on actual storage rates |
| Redundancy and peaks | Extra GPUs reserved for peak traffic and failures | Determined by peak traffic and availability targets |
Once you have the monthly cost, compare it against API fees for the same period to find the call-volume threshold where self-hosting becomes cheaper. If your projected volume stays below that threshold long-term, cloud APIs are usually the more economical choice.
