How to Objectively Evaluate Locally Deployed Open-Source Large Language Models
Evaluating locally deployed open-source large language models (LLMs) requires more than just looking at download counts and leaderboard rankings. This article provides a systematic approach to assessing LLMs based on their architecture, hardware compatibility, and performance on specific business tasks. It covers how to interpret basic model specifications, view public benchmarks critically, build a customized evaluation framework, assess deployment costs, and test effective context lengths to make informed model selection decisions.
1. Why Systematic Evaluation of Open-Source Models is Necessary
Open-source large language models are updated rapidly, and each release triggers extensive discussion. Download counts, leaderboard rankings, and community popularity can indicate the level of attention, but they do not directly prove whether a model is reliable for specific tasks.
When evaluating a model, you should first answer three questions: What are the boundaries of the model’s capabilities? How well does it perform on your own hardware? How does it behave on your own business data? Only by addressing these three questions individually can you build a solid foundation for your model selection.
2. Understand the Basic Specifications of the Model First
2.1 Architecture Type
The architecture dictates the computation method during inference.
- Dense Models: All parameters participate in the calculation when generating each token. The structure is straightforward, the deployment path is mature, and they generally run more stably under the same VRAM constraints.
- Mixture of Experts (MoE) Models: Only a portion of the parameters is activated during each inference. The computation volume for a single inference is lower, but the weights of all experts still need to be loaded into memory, meaning the overall resource consumption is not necessarily lower.
When selecting a model, consider the architecture alongside your actual hardware, rather than just looking at the total parameter count.
2.2 Parameter Scale and VRAM Requirements
The parameter scale directly affects VRAM usage. When stored in 16-bit floating-point format, every billion parameters occupy approximately 2 GB of VRAM. Quantization can reduce the storage bits per parameter to 8 or 4, decreasing the footprint accordingly.
The actual usage also includes the key-value cache, runtime overhead, and batch processing buffers. The longer the context, the larger the key-value cache. Therefore, a certain margin should be reserved when estimating, and the model should be actually loaded on the target device at least once.
2.3 Licensing
Open source does not mean unconditional commercial use. Licenses typically specify attribution requirements, redistribution conditions, scope of use, and patent terms. Before going live, the person in charge must read each clause and, if necessary, have the legal department confirm it.
2.4 Multimodal Capabilities
The ability to understand images or videos does not mean the model can generate them. When evaluating, these two types of capabilities should be tested separately.
- Understanding tasks: Image question answering, screenshot-to-code, document layout recognition, and object localization and bounding in images.
- Generation tasks: Image generation, video generation. These capabilities require specialized models and are usually not possessed by text models.
In agent workflows, understanding capabilities are often more valuable than generation capabilities because they can read UI screenshots, tables, and documents, and then pass them to subsequent steps for processing.
2.5 Context Length
The native context length of a model is the working range validated during training. Some methods can extend the context to longer lengths by adjusting positional encoding, but this extension is an extrapolation. The performance after extrapolation will degrade as the length increases, and the rate of degradation varies across different tasks.
Therefore, the nominal maximum length should only serve as an upper-bound reference; the actual usable length must be determined through testing. Section 6 will provide a testing method for this.
3. How to View Leaderboards and Vendor Self-Test Scores
Public information has reference value, but its nature needs to be distinguished.
- Leaderboards and download counts: These reflect popularity and rankings on specific test sets. Some test set questions may overlap with training data, and the rankings may not transfer to other tasks.
- Vendor-published evaluation scores: These are usually completed by the vendors themselves, and the settings are often the most favorable to them. Sampling temperature, prompt templates, whether Chain of Thought is used, and the test script version can all significantly affect the results.
- Community feedback: This comes from the personal experiences of a small number of users, the sample size is small, and it is easily influenced by specific use cases.
When using this information, it is recommended to treat them as clues. When comparing two models, try to keep the following conditions consistent: quantization method, sampling parameters, prompts, context length, and scoring criteria. Directly comparing scores with different conditions usually leads to unreliable conclusions.
4. Establish Your Own Evaluation Framework
4.1 Define Task Categories
Select task categories based on business requirements. Common ones include:
- Code generation and bug fixing
- Long document QA and information extraction
- Structured output, such as returning JSON in a fixed format
- Instruction following, such as restricting word count or prohibiting certain words
- Image understanding, such as reading fields from a screenshot
- Tool calling, such as selecting the correct function based on a description and filling in the parameters
Each task category only needs to cover the parts most relevant to your business; there is no need to pursue comprehensiveness.
4.2 Prepare Samples and Scoring Rules
Prepare 20 to 50 samples for each task category, including both common and edge cases. Samples should be kept securely to prevent them from being included in training data, which would cause them to lose their reference value.
Choose the scoring method based on the nature of the task:
- Tasks that can be automatically scored, such as unit test pass rates, JSON parsing success rates, and key field matching, should prioritize automated scoring.
- Subjective tasks, such as text summarization and answer quality, should be independently scored by two or more reviewers, and the scoring criteria should be recorded.
4.3 Write the Invocation Script
The following example uses the standard library to send requests to a local inference service, recording latency and output length. The service interface is assumed to be compatible with common chat formats, and the actual address and model name need to be modified according to your deployment environment.
import jsonimport timeimport urllib.requestENDPOINT = "http://localhost:8000/v1/chat/completions"MODEL_NAME = "local-candidate-model"def run_case(prompt: str, max_tokens: int = 1024) -> dict:"""Sends a request and returns the output text, elapsed time, and number of output tokens."""payload = {"model": MODEL_NAME,"messages": [{"role": "user", "content": prompt}],"temperature": 0,"max_tokens": max_tokens,}request = urllib.request.Request(ENDPOINT,data=json.dumps(payload).encode("utf-8"),headers={"Content-Type": "application/json"},method="POST",)start = time.perf_counter()with urllib.request.urlopen(request, timeout=300) as response:body = json.loads(response.read().decode("utf-8"))elapsed = time.perf_counter() - starttext = body["choices"][0]["message"]["content"]usage = body.get("usage", {})return {"text": text,"latency_s": round(elapsed, 3),"completion_tokens": usage.get("completion_tokens"),}def run_suite(cases: list[dict]) -> list[dict]:"""Executes samples in batches. Each sample contains an id, prompt, and check function."""results = []for case in cases:output = run_case(case["prompt"])passed = case["check"](output["text"])results.append({"id": case["id"], "passed": passed, **output})return resultsdef pass_rate(results: list[dict]) -> float:return sum(r["passed"] for r in results) / len(results)
The check function should be written for the specific task. For example, for structured output tasks, you can try parsing the JSON and validating the fields; for code tasks, you can pass the generated code to a unit test for execution.
4.4 Control Variables and Repeat Tests
The same set of samples should use the same running parameters across different models. Because sampling involves randomness, key conclusions need to be averaged over multiple runs, and failed samples should be retained for individual failure analysis. Failure reasons usually fall into three categories: understanding errors, formatting errors, and knowledge deficits. The approaches to fixing these three types of problems are different, and they need to be tracked separately.
5. Deployment Cost Assessment
Whether a model can run on a device is only the first step. The actual runtime performance must also be evaluated.
| Metric | Meaning | Reason for Focus |
|---|---|---|
| Time to First Token | Time from request submission to outputting the first token | Determines interactive response speed |
| Generation Speed | Number of output tokens per second | Determines time consumption for long text output |
| Peak Memory | Maximum memory usage during model loading and inference | Determines whether it can run on the target device |
| Concurrent Throughput | Total output speed when multiple requests are executed simultaneously | Determines the number of users the service can support |
Quantization can significantly reduce memory usage, but it will bring a certain loss in quality. It is recommended to run the evaluation once before and after quantization to compare the gap between the two sets of results. If the decline in a certain task category exceeds the acceptable range for your business, you should switch to a higher-precision version or replace it with another candidate model.
6. Practical Testing Method for Context Length
The nominal context length is not equal to the effective length. A common practice is the “needle in a haystack” test: insert a clear fact at a random position in an irrelevant text, then ask a question to check whether the model can retrieve this information. Gradually increase the total length and change the insertion position, recording the inflection point where the accuracy starts to drop significantly.
The following function is used to construct the test text:
def build_haystack(filler: str, needle: str, total_chars: int, depth: float) -> str:"""Constructs the test text. depth ranges from 0 to 1, representing the relative position of the needle in the text."""repeated = filler * (total_chars // len(filler) + 1)body = repeated[:total_chars]pos = int(total_chars * depth)return body[:pos] + "\n" + needle + "\n" + body[pos:]
During testing, multiple sets of samples can be generated based on combinations of length and depth to plot an accuracy heatmap. Lengths beyond the inflection point are not suitable for production tasks that rely on precise retrieval. Long document QA can also be tested using the same approach, replacing the information to be searched with paragraphs from real documents.
7. Model Selection Decision Recommendations
A complete selection process can be advanced according to the following steps:
- Clarify the business scenarios and acceptance metrics, such as the required code pass rate and the maximum acceptable response time per request.
- Complete deployment on the target hardware, recording VRAM, memory, and inference speed.
- Compare two to three candidate models using a private evaluation set with fixed running parameters.
- Combine license terms, version maintenance frequency,
