Self-Host or Call an API? A Practical Guide to Deploying Open-Weight LLMs Locally

    Open-weight large language models give teams full control over data, costs, and serving infrastructure—but they also bring responsibility for hardware sizing, quantization, fine-tuning, security, and compliance. This guide compares open-weight deployment with API-based access, explains how to estimate GPU memory for model weights and KV cache, covers inference service architecture and rate limiting, and provides a practical pre-launch checklist for licensing, access control, logging, and operations.

    1. What Open Weights Mean—and Their Limits

    There are two main ways to use large language models. The first is calling an API, where the model parameters stay with the service provider and you only send inputs and receive outputs. The second is obtaining the model weight files—the complete set of parameters produced after training—and loading and running them on your own hardware. The latter is commonly known as open weights.

    The key differences between the two approaches:

    Dimension API Access Local Open-Weight Deployment
    Data flow Inputs and outputs pass through the provider’s network Data can stay entirely within your local environment
    Cost structure Pay per call, low upfront investment Higher fixed costs for hardware, power, and operations staff
    Latency and concurrency Subject to provider quotas and queuing You control batching and the number of GPUs
    Model updates Upgrades handled centrally by the provider You must evaluate and roll out new versions yourself
    Compliance responsibility Largely covered by the provider’s agreements Access control, logging, and license verification fall on you

    Obtaining weight files does not mean unlimited usage rights. License agreements typically define commercial-use scope, redistribution conditions, attribution requirements, and usage restrictions. Review every clause before going live, and consult legal counsel when necessary.

    2. Is Self-Hosting Right for Your Team?

    Self-hosting is a good fit for teams that meet most of these conditions:

    • Business data has strict residency requirements and cannot—or should not—be sent to external networks;
    • Workloads are relatively stable, so GPU utilization can stay high over the long term;
    • Someone can own driver, framework, monitoring, and incident handling;
    • You need to fine-tune on business data and keep full control over the fine-tuned model.

    If your requirements are still exploratory, traffic fluctuates heavily, or your team lacks operations expertise, API access is usually the better choice. The two approaches can also coexist: route sensitive data to a local model and general tasks to an external API.

    3. Resource Estimation Before Deployment

    The first step in deployment is estimating hardware requirements. GPU memory usage consists of three main parts: model weights, activation values during inference, and the KV cache that stores historical token states. Weights are the easiest to compute—multiply the parameter count by the bytes per parameter.

    The following example shows the weight memory for the same parameter count at different precisions. The parameter count is hypothetical and for illustration only.

    1. def weight_memory_gb(num_params_billion: float, bytes_per_param: float) -> float:
    2. """Estimate GPU memory used by model weights alone, excluding KV cache and runtime overhead."""
    3. total_bytes = num_params_billion * 1e9 * bytes_per_param
    4. return total_bytes / (1024 ** 3)
    5. PRECISIONS = {
    6. "FP16/BF16": 2.0,
    7. "INT8": 1.0,
    8. "INT4": 0.5,
    9. }
    10. for label, bpp in PRECISIONS.items():
    11. print(f"{label:>10}: ~{weight_memory_gb(70, bpp):6.1f} GB")

    The results are roughly 130 GB, 65 GB, and 33 GB. These numbers cover weights only, not total memory.

    KV cache size scales with context length and the number of concurrent requests. For a standard multi-head attention architecture, the KV cache per token is approximately: 2 × number of layers × number of KV heads × head dimension × bytes per element. As concurrency or context length grows, this overhead can exceed the weights themselves.

    The following example uses a hypothetical 70B model with 80 layers, 8 KV heads, head dimension of 128, FP16 KV cache, a context length of 8192, and 16 concurrent requests.

    1. def kv_cache_gb(layers: int, kv_heads: int, head_dim: int,
    2. bytes_per_elem: float, context_len: int, concurrency: int) -> float:
    3. """Estimate total KV cache usage in GB."""
    4. per_token_bytes = 2 * layers * kv_heads * head_dim * bytes_per_elem
    5. total_bytes = per_token_bytes * context_len * concurrency
    6. return total_bytes / (1024 ** 3)
    7. kv = kv_cache_gb(layers=80, kv_heads=8, head_dim=128,
    8. bytes_per_elem=2, context_len=8192, concurrency=16)
    9. print(f"KV cache ~{kv:.1f} GB") # ~40.0 GB

    Under these assumptions, weights take about 130 GB and KV cache about 40 GB—and you still need room for activations and runtime overhead. Capacity planning must account for all of these. Actual layer counts, KV head counts, and attention architectures should be confirmed against the official model card.

    4. Designing the Inference Service

    Once the model is loaded onto GPUs, you need a serving layer to handle request intake, queuing, scheduling, and response delivery. A production-ready inference service typically includes the following elements.

    1. Model parallelism strategy: If the model fits on a single GPU, deploy it directly. If not, split layers across multiple GPUs—this is tensor parallelism. Cross-GPU communication adds latency, so more GPUs is not always better; measure communication overhead on your target hardware first.
    2. Request scheduling: Dynamic batching combines multiple requests into one computation to improve hardware utilization. Continuous batching allows new requests to join while existing ones are still running, reducing queue wait times.
    3. API specification: Expose a standard JSON request format with streaming responses, so existing clients and gateways can integrate directly.
    4. Containerization and release: Package the runtime environment as an image with pinned versions for model files, frameworks, and dependencies. Use gradual rollouts so you can quickly roll back to the previous version if problems arise.
    5. Health checks and monitoring: Expose liveness and readiness probes, and continuously collect first-token latency, tokens generated per second, GPU memory usage, and error rates. Set alert thresholds based on your service-level objectives—for example, trigger an alert when first-token latency exceeds its target by a defined margin.

    The API specification should define fields, error codes, and timeout policies. Here is a sample request:

    1. {
    2. "model": "local-llm-v1",
    3. "messages": [
    4. {"role": "user", "content": "Summarize the payment terms of this contract."}
    5. ],
    6. "max_tokens": 512,
    7. "stream": true,
    8. "timeout_ms": 30000
    9. }

    The server should return a consistent error structure and distinguish these cases: 400 for invalid request parameters, 401 for authentication failure, 429 for rate limiting, 504 for inference timeout, and 503 for service unavailability. Clients may retry 429 and 503 with exponential backoff, but should not retry 400 or 401.

    Rate limiting is a fundamental tool for protecting service stability. The following token bucket implementation is a good starting point for gateway-side rate limiting.

    1. import threading
    2. import time
    3. class TokenBucket:
    4. def __init__(self, rate: float, capacity: int):
    5. self.rate = rate # tokens added per second
    6. self.capacity = capacity # maximum bucket capacity
    7. self.tokens = float(capacity) # current token count, starts full
    8. self.updated_at = time.monotonic() # last refill timestamp
    9. self._lock = threading.Lock()
    10. def _refill(self, now: float) -> None:
    11. elapsed = now - self.updated_at
    12. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    13. self.updated_at = now
    14. def allow(self, cost: float = 1.0) -> bool:
    15. with self._lock:
    16. self._refill(time.monotonic())
    17. if self.tokens >= cost:
    18. self.tokens -= cost
    19. return True
    20. return False
    21. if __name__ == "__main__":
    22. bucket = TokenBucket(rate=2.0, capacity=5)
    23. print([bucket.allow() for _ in range(7)]) # first 5 pass, last 2 are rejected
    24. time.sleep(1.0)
    25. print(bucket.allow()) # ~2 tokens refilled after 1 second, returns True

    This implementation counts within a single process. When running multiple replicas, move the token state to a shared store such as Redis—otherwise each replica counts independently and the effective limit is multiplied.

    5. Quantization

    Quantization reduces memory usage by lowering parameter precision. Common approaches include FP8, INT8, and INT4 quantization, with formats such as GPTQ, AWQ, and GGUF. Whether a quantized model runs on your target hardware depends on the inference framework’s support for that format and its kernels.

    Quantization results vary by model and task—you should not judge it by memory savings alone. Follow these steps:

    • Prepare an evaluation set that reflects your business, covering major task types and edge cases;
    • Evaluate both the original-precision and quantized models, comparing accuracy, refusal rates, and format adherence;
    • Measure first-token latency and throughput on the target hardware to confirm that quantization actually delivers gains;
    • Record the quantization method, calibration data source, and framework version for reproducibility.

    If key task metrics degrade significantly after quantization, switch to a higher precision or quantize only some layers.

    6. Fine-Tuning

    Fine-tuning adapts a model to domain-specific terminology and output formats. Common approaches include full-parameter fine-tuning and Low-Rank Adaptation (LoRA). LoRA trains only a small set of additional parameters, requires less GPU memory, and suits resource-constrained teams.

    Before fine-tuning, confirm the following:

    • Training data sources are properly licensed and contain no personal information collected without consent;
    • Data has been anonymized, with cleaning rules documented;
    • Training and evaluation sets are strictly separated, with no evaluation data leaking into training;
    • Whether the fine-tuned model counts as a derivative work under the base model’s license, and whether commercial use is permitted;
    • Base model versions and training configurations are retained so results can be reproduced.

    Fine-tuned models should go through the same full evaluation as base models, benchmarked side by side against the base model. If fine-tuning yields no quantifiable improvement, it should not go live.

    7. Security, Compliance, and Launch Checklist

    After local deployment, your team owns access control, logging, and data protection. Verify each item before launch.

    Licensing and provenance

    • Commercial scope, redistribution terms, attribution requirements, and usage restrictions have been reviewed;
    • The original license text and model card are archived, with versions recorded;
    • SHA256 hashes of model files have been verified against the official published values;
    • License terms for derivative models have been confirmed, with legal review where necessary.

    Access and networking

    • The inference endpoint is restricted to the internal network or accessed via a gateway, never exposed directly to the public internet;
    • Each caller uses a separate API key or service identity, with revocation support;
    • Keys and credentials are stored in environment variables or a secrets management service, never in code or images;
    • Rate limits, timeouts, and quotas are configured per caller.

    Data and logging

    • Data residency scope is defined, and storage locations verified for compliance;
    • Request and response logs are redacted by default; personal information and secrets never appear in logs;
    • Log retention periods are set, with automatic deletion on expiry;
    • Sensitive content in inputs and outputs is filtered or audited.

    Release and operations

    • Images, model files, and dependencies are all version-pinned;
    • Gradual rollout and rollback procedures have been rehearsed;
    • Liveness and readiness probes plus core monitoring metrics are wired into alerting;
    • A troubleshooting runbook exists, documenting common errors and their resolutions.

    After completing the checklist, run the service in a test environment for a period of time—observing latency, GPU memory, and error rates—before gradually shifting production traffic over.