Evaluating Open-Source LLMs: Specs, Performance, and Deployment Practices
This article provides a systematic framework for selecting open-source large language models. It covers model categories by parameter size and architecture, core evaluation dimensions including task quality, inference efficiency, resource consumption, stability, and licensing, along with reproducible benchmarking scripts and structured output validation approaches to guide real-world deployment decisions.
1. Why Model Selection Requires Systematic Evaluation
Open-source LLM specifications and architectures are evolving rapidly. Models with different parameter counts, inference structures, and licensing terms are available simultaneously, making it difficult to judge based solely on benchmark scores or release announcements. Leaderboard scores reflect performance on specific test sets that may not align with your business scenario’s input length, output format, latency requirements, or hardware constraints. Therefore, model selection requires comparing model capabilities, inference costs, and engineering constraints within a unified framework.
2. Model Categories by Specification
2.1 Small-Parameter Models
Small-parameter models typically range from hundreds of millions to several billion parameters. They are suitable for edge devices, low-VRAM GPUs, and latency-sensitive scenarios such as local structured information extraction, intent classification, request routing, and lightweight dialogue. These models have a lower ceiling on complex multi-step reasoning, but with clear prompt constraints and few-shot examples, they can reliably perform formatted output tasks. When deploying on mobile devices, you also need to consider the model package size and runtime memory peaks.
2.2 Medium-Sized Sparse Activation Models (MoE)
Sparse activation models (Mixture of Experts, or MoE) have a large total parameter count but only activate a subset of expert networks per token. This architecture introduces two key distinctions: VRAM usage is determined by total parameters, while per-step computation is determined by activated parameters. The common benefit is quality approaching that of similarly sized dense models with faster decoding speeds. The trade-offs are clear: deployment still requires accommodating all parameters, and the routing mechanism may cause uneven expert load distribution, affecting batch processing efficiency.
2.3 Large Dense Models
Dense models use all parameters in every computation step. The quality ceiling is typically higher, especially in long-chain reasoning, complex code generation, and cross-domain knowledge QA. The cost is slower decoding speed, and KV Cache consumes substantial VRAM as context grows, creating significant resource pressure in long-context scenarios. When selecting this type of model, you should separately verify output stability and watch for repetition, topic drift, or excessive reasoning.
3. Core Evaluation Dimensions
3.1 Task Quality
Aggregate benchmarks cannot replace business-specific testing. It is recommended to partition test sets by task type, covering instruction following, structured output, multi-turn dialogue, mathematical computation, code generation, and long-document QA. Prepare at least dozens of samples per task category and define human scoring rubrics in advance, such as answer correctness, format completeness, and clarity of reasoning steps. Scoring criteria must remain consistent across all candidate models; otherwise, comparison results are meaningless.
3.2 Inference Efficiency
Inference is divided into two phases that should be measured separately:
- Prefill phase: Processes the input prompt and determines time-to-first-token. Longer inputs lead to more noticeable latency.
- Decode phase: Generates output tokens one by one and determines the token output speed, directly affecting perceived fluency.
When measuring, you must fix context length, batch size, quantization method, maximum output length, and sampling temperature. If these parameters are not unified, data across models cannot be directly compared.
3.3 Resource Consumption
Resource evaluation consists of three parts: model weight footprint, KV Cache footprint, and peak VRAM or memory. KV Cache size relates to the number of layers, KV heads, head dimension, and context length. It can be estimated using the following formula:
KV Cache bytes ≈ 2 × num_layers × num_kv_heads × head_dim × context_length × bytes_per_element × batch_size
The coefficient 2 corresponds to the two caches for Key and Value. The longer the context and the higher the concurrency, the more likely KV Cache will exceed the weight footprint itself. Therefore, stress testing with realistic concurrency levels is necessary before deployment.
3.4 Stability and Hallucination
Stability focuses on output consistency when sampling the same prompt multiple times. It is recommended to sample each test case multiple times and track the following metrics:
- Output format compliance rate: the proportion of valid outputs out of total runs.
- Factual error rate: obtained through manual spot-checking or comparison with reference answers.
- Timeout ratio and abnormal termination ratio, especially when long reasoning modes are enabled.
For long reasoning modes, set a clear maximum output length to prevent the model from consuming excessive time and VRAM on invalid reasoning.
3.5 Licensing and Compliance
License terms determine whether a model can be used in commercial products, whether it can be modified and redistributed, and whether attribution or specific notices are required. Permissive open-source licenses generally allow commercial use, but you should still review the specific terms. Before deployment, legal or compliance personnel should confirm the terms, and the license text and version information should be included in the project’s dependency manifest.
4. Building a Reproducible Efficiency Benchmarking Script
The following script calls a local or remote inference service via HTTP and measures end-to-end latency and generation speed. The endpoint, API key, and model name are passed through environment variables to avoid hardcoding them.
import osimport jsonimport timeimport statisticsimport urllib.requestENDPOINT = os.environ["LLM_ENDPOINT"] # e.g., http://127.0.0.1:8000/v1/chat/completionsAPI_KEY = os.environ.get("LLM_API_KEY", "")MODEL = os.environ.get("LLM_MODEL", "local-model")def run_once(prompt: str, max_tokens: int = 256) -> dict:body = json.dumps({"model": MODEL,"messages": [{"role": "user", "content": prompt}],"max_tokens": max_tokens,"temperature": 0.0,}).encode("utf-8")req = urllib.request.Request(ENDPOINT,data=body,headers={"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}",},)start = time.perf_counter()with urllib.request.urlopen(req, timeout=300) as resp:data = json.loads(resp.read().decode("utf-8"))elapsed = time.perf_counter() - startusage = data.get("usage", {})completion_tokens = usage.get("completion_tokens", 0)text = data["choices"][0]["message"]["content"]return {"latency_s": elapsed,"completion_tokens": completion_tokens,"tokens_per_s": completion_tokens / elapsed if elapsed > 0 else 0.0,"output": text,}def benchmark(prompts, repeat: int = 3) -> dict:results = []for prompt in prompts:for _ in range(repeat):results.append(run_once(prompt))return {"samples": len(results),"median_latency_s": statistics.median(r["latency_s"] for r in results),"median_tokens_per_s": statistics.median(r["tokens_per_s"] for r in results),}if __name__ == "__main__":test_prompts = ["Explain what a sparse activation model is in three sentences.","Read the following order description and output the product name, quantity, and amount in JSON format.",]print(json.dumps(benchmark(test_prompts), ensure_ascii=False, indent=2))
Note that the speed measured here is end-to-end, including prefill time. To precisely separate the two phases, switch to streaming output and record the time-to-first-token and the interval between subsequent tokens separately. Additionally, each model should be warmed up with a few runs first to eliminate bias from weight loading and cache initialization.
5. Structured Output and Agent Workflow Validation
Structured output is the most common deployment scenario for small models. When evaluating, do not just check whether the output “looks like JSON”—use programmatic validation.
import jsonREQUIRED_FIELDS = {"name": (str,),"quantity": (int,),"amount": (int, float),}def validate_output(raw: str) -> tuple[bool, str]:try:obj = json.loads(raw)except json.JSONDecodeError as exc:return False, f"JSON parsing failed: {exc}"if not isinstance(obj, dict):return False, "Top-level structure is not an object"for key, types in REQUIRED_FIELDS.items():if key not in obj:return False, f"Missing field: {key}"if not isinstance(obj[key], types):return False, f"Field type error: {key}"return True, "ok"def pass_rate(outputs: list[str]) -> float:passed = sum(1 for o in outputs if validate_output(o)[0])return passed / len(outputs) if outputs else 0.0
The compliance rate is calculated as the number of validated samples divided by the total number of samples. Compliance rates should be tracked separately across different temperatures and prompt versions to avoid drawing conclusions based only on ideal conditions.
In lightweight agent scenarios, the model typically needs to call tools across multiple steps. When evaluating, consider the following:
- Whether the tool parameters at each step conform to the API definition—use the same programmatic validation approach described above to check parameter types and completeness.
