Choosing an Open-Source LLM: Balancing Parameters, Context Length, and Cost
This guide explains how to choose an open-source large language model based on hardware limits, long-context memory costs, multimodal approaches, evaluation on your own business data, and cost per successful task. It includes a formula for estimating KV cache size, a model selection function, and a launch checklist.
1. Check Whether the Hardware Can Hold the Model
Parameter count sets the upper limit of a model’s capacity, but it is not the same as the amount of computation performed for each inference. In a mixture-of-experts (MoE) architecture, each token’s forward pass activates only part of the expert subnetworks. As a result, the total parameter count can be very large while the number of parameters active per call stays relatively low. When selecting a model, evaluate these two figures separately.
This architecture brings two types of cost.
- Storage cost: all parameters must reside in GPU memory or system memory. For FP16 weights, each parameter takes 2 bytes, so the weights of a 1-trillion-parameter model require about 2 TB.
- Compute cost: inference speed depends mainly on the number of active parameters, the batching strategy, and communication overhead between GPUs.
Deploying very large models usually requires multi-GPU or multi-node parallelism. Common combinations include tensor parallelism, expert parallelism, and pipeline parallelism. Before selecting a model, confirm two things: whether your hardware budget can hold all the weights, and whether the communication overhead of the parallelism scheme is acceptable.
2. Estimating the Memory Cost of Long Context
A context window of one million tokens can hold large document sets or codebases, but it is not free. Standard self-attention has computational complexity that scales with the square of the sequence length. Doubling the sequence length roughly quadruples the attention computation. During inference, the model also stores a KV cache, and the cache size grows linearly with context length.
The KV cache size can be estimated with this formula:
KV cache bytes = 2 × layers × KV heads × head dimension × context length × bytes per element × concurrent requests
The factor of 2 accounts for the separate K and V caches. Here is an example with assumed parameters: 80 layers, 8 KV heads, a head dimension of 128, FP16 at 2 bytes per element, a context of 131,072 tokens, and a single request. Each token takes 2 × 80 × 8 × 128 × 2 = 327,680 bytes, about 320 KB. Multiplied by 131,072 tokens, the total is about 43 GB. The cache alone approaches the memory capacity of a 48 GB GPU, and this figure excludes the model weights. For long context, memory is often the bottleneck rather than compute.
Engineering teams commonly use three strategies to reduce the cost of long context.
- Retrieval-augmented generation: first use vector or keyword search to filter relevant passages, and include only the necessary content in the context.
- Hierarchical summarization: split long documents into segments, summarize each one, then summarize the summaries level by level to shorten the input for each request.
- Prefix caching: reuse the KV cache for fixed system prompts or document prefixes to avoid repeated computation.
The right strategy depends on the task. Tasks that require exact quotes from the source suit retrieval-augmented generation. Tasks that need a global understanding, such as cross-file code review, fit long context better, but they accept higher latency and cost.
3. Native Multimodality Versus an Add-On Pipeline
Native visual understanding means the model learns joint representations of images and text during training. An add-on approach first converts images to text with a separate OCR or image captioning module, then passes the text to a language model. The two approaches differ in three main ways.
- Fine-grained information: add-on pipelines can lose details such as axis ticks in charts, merged cells in tables, and small text in screenshots.
- Pipeline complexity: an add-on pipeline requires maintaining several modules, and errors from each module accumulate through the chain.
- Evaluation: measure image recognition accuracy, the accuracy of reasoning that combines image and text, and end-to-end latency separately. Checking only whether the final answer reads well cannot show which stage failed.
4. Choosing an Open-Source LLM: Evaluate with Your Own Business Data
Composite indexes, code arena leaderboards, and individual benchmarks reflect performance only on specific task distributions. Selecting a model by copying rankings directly can lead to poor decisions. A more reliable approach follows these steps.
- Sample 200 to 500 items from real business workloads, covering both high-frequency scenarios and edge cases.
- Define an automatically checkable scoring rule for each item, such as regex matching, unit test pass rate, or structured field comparison.
- Use the same prompt, sampling parameters, and output length limit for all candidate models, and record accuracy, latency, and cost.
- Sample unstable items multiple times and observe the variance in results. High variance means the model’s behavior is unpredictable for that item, so it needs extra constraints before launch.
The following function filters candidates by constraints first, then compares cost.
from dataclasses import dataclass@dataclassclass EvalResult:model: straccuracy: float # Accuracy on the business evaluation set, from 0 to 1p95_latency_s: float # End-to-end 95th percentile latency, in secondscost_per_task: float # Average cost per successful task, in USDdef pick_model(results: list[EvalResult],max_latency_s: float,min_accuracy: float) -> EvalResult | None:"""Among candidates that meet the accuracy and latency constraints,select the model with the lowest cost per task."""feasible = [r for r in resultsif r.accuracy >= min_accuracy and r.p95_latency_s <= max_latency_s]if not feasible:return Nonereturn min(feasible, key=lambda r: r.cost_per_task)results = [EvalResult("model-a", 0.92, 3.1, 0.012),EvalResult("model-b", 0.88, 1.8, 0.005),EvalResult("model-c", 0.95, 6.5, 0.020),]best = pick_model(results, max_latency_s=4.0, min_accuracy=0.90)print(best.model) # prints model-a
Filtering by constraints before comparing cost prevents choosing a cheap model that fails the quality bar. In this example, model-b has the lowest unit price but only 0.88 accuracy, so it is eliminated. model-c has the highest accuracy, but its P95 latency exceeds 4 seconds, so it is also eliminated. model-a meets both constraints and has the lowest cost among the remaining candidates, so it is selected.
5. Calculating Cost: Include Failures and Retries in Cost per Task
LLM services usually bill per million tokens, with separate prices for input and output. Output tokens generally cost more, so the cost of tasks that generate long text grows faster. The cost of a single request is calculated as:
Request cost = input tokens ÷ 1,000,000 × input price + output tokens ÷ 1,000,000 × output price
def request_cost(input_tokens: int, output_tokens: int,price_in_per_m: float, price_out_per_m: float) -> float:"""Return the cost of a single request. Prices are in USD per million tokens."""return (input_tokens / 1_000_000) * price_in_per_m \+ (output_tokens / 1_000_000) * price_out_per_m# 3,000 input tokens, 800 output tokens, $2 per million input tokens, $8 per million output tokensprint(round(request_cost(3000, 800, 2.0, 8.0), 4)) # prints 0.0124
Cost per task is not the same as cost per request. Keep three points in mind.
- Failures and retries: failed and retried requests consume billable tokens too. Cost per task equals total spend divided by the number of successful tasks: cost_per_task = total spend ÷ successful tasks.
- Cache hits: some services offer a lower price for prefix input that hits the cache. When calculating cost, split input into cache-hit and cache-miss portions and apply the matching price to each.
- Output length: limiting the maximum output length controls cost and reduces latency.
Tiered routing can also reduce cost. Send simple requests to a smaller model and escalate complex requests to a larger model. Routing rules can be based on task type, input length, or historical accuracy. Whether or not routing is used, validate with the same evaluation set to confirm that overall accuracy does not drop noticeably.
6. Launch Checklist
- Confirm that the hardware budget can hold the model weights, and calculate the KV cache size at your target context length.
- Build an evaluation set with at least 200 business samples, and record accuracy, P95 latency, and cost per task.
- Filter candidates by constraints first, then compare cost.
- Keep monitoring cost and accuracy after launch.
