How to Evaluate and Select Coding LLMs: A Practical Guide Beyond Leaderboard Scores
Public leaderboard scores are tempting but unreliable for selecting coding LLMs. This article explains why—data contamination, scaffolding effects, and distribution shift—and lays out a practical, reproducible methodology. It breaks "coding ability" into eight observable dimensions, shows how to build an internal evaluation set from real tickets using stratified sampling and version freezing, and combines automated metrics with blind human review backed by sound statistics (pass@k, first-pass yield, confidence intervals, and significance tests). It also provides a reusable Python evaluation skeleton and describes a tiered routing strategy that dispatches tasks to latency-optimized or flagship models for production use.
1. Why Leaderboard Scores Mislead Model Selection
Every time a new model launches, “Model X tops the benchmark” almost always becomes a hot topic in tech communities, and evaluation leaderboards and engineering benchmarks are often treated as procurement criteria. But taking public scores as a selection conclusion runs into at least three traps.
Data contamination: After repeated training, the questions and answers of public benchmarks may already have entered the training corpus. When a model answers correctly, it is hard to tell whether it can actually solve the problem or has simply memorized the answer.
Scaffolding effect: The same model can score very differently with a different prompt template, a different toolset, or depending on whether running tests is allowed. Leaderboards show the combined performance of “model + evaluation framework,” which is not the same as what your team will get after integration.
Distribution shift: Public benchmarks are mostly carefully constructed standalone problems, while what your team actually needs to solve is something like “add a feature to a repo with hundreds of thousands of lines of legacy code, following the existing conventions.” The task shape is different, so conclusions cannot be transferred directly.
More importantly, models each have their strengths: some excel at algorithm problems, some are good at retrieving and editing specific files in long context, some adapt better to the “read code → run tests → read errors → fix” loop, and some tend to drift off when there are many clues to follow.
For these reasons, public leaderboards are suitable for broad, coarse filtering but not for final decisions. Reliable selection is built on evaluation data that follows the same distribution as your own business. This is exactly what teams evaluating coding plan subscriptions should prioritize.
2. Breaking Down “Coding Ability” into Observable Dimensions
“Is its coding ability strong?” cannot be measured directly. What can be measured is its performance on specific tasks. It is recommended to break the evaluation into at least the following dimensions.
Requirement understanding and clarification: Facing vague, colloquial, or implicitly constrained requirements, can the model identify ambiguity and proactively ask clarifying questions instead of guessing and diving in? This determines the rework cost.
Single-file generation correctness: The correctness rate of implementing classic algorithm problems or utility functions. It measures fundamental coding skills and is also the easiest to inflate with training data, so it should only serve as a reference.
Cross-file engineering understanding: Can the model locate which files the change should land in, follow the project’s existing directory structure and naming conventions, and correctly connect the call chain? This ability is strongly correlated with long-context quality.
Long-context effectiveness: Among tens of thousands or even hundreds of thousands of tokens of repo content, can the model precisely locate the relevant code without being distracted by irrelevant content? Effectively using length and merely having a nominal length are two different things.
Tool use and execution loop: Can it correctly read and write files, run tests, parse errors, and iterate on fixes; can it stop at the right time and ask for human intervention?
Long-task stability and instruction following: Across dozens of multi-turn interactions, does the model stay focused on the original goal, or does it drift further with each change, forget early constraints, or expand the change scope on its own?
Code quality and maintainability: Naming, comments, error handling, edge-case coverage, and whether it introduces duplicate logic. These cannot be fully judged automatically and need human review as a backstop.
Cost and latency: Including the tokens consumed per completed task (including retries and tool calls), first-token latency, and generation throughput. For example, for “completing a piece of code,” different output lengths mean very different experiences for a latency-optimized model versus a flagship model.
3. Building Your Own Eval Set from Real Tickets
The core principles of a self-built eval set are: close to reality, diverse coverage, and frozen management.
Collection: Filter tasks from historical tickets, code review records, and defect tickets—for example, adding an interface, fixing a class of edge-case defects, adding tests to a legacy module, or completing a small refactor.
Stratified sampling: Stratify across four dimensions—language (covering at least the main tech stack), task type, number of files involved, and business module—to ensure the eval set is not biased toward some easy category.
Task card: Each task defines a clear input (a desensitized repo snapshot and requirement description) and output (the expected behavior change).
task_id: EVAL-0142language: pythonfiles_touched: 3 # files touched by the original changecategory: featureprompt: Add "settlement by billing period" to the order service...repo_snapshot: repo_0142.tar.gzscoring:hidden_tests: 12 # hidden tests: new cases + existing regression casesweights: {correctness: 0.7, maintainability: 0.3}forbidden: [network_access, install_packages] # restrict the runtime environment
Safe desensitization: Task cards go through manual review to ensure they contain no keys, customer data, or sensitive information directly tied to internal business.
Version freezing: Repo snapshots and scoring scripts are placed under unified version management. After the dataset is updated, re-run baselines for historical models so that cross-comparison is always done under the same ruler.
Leakage prevention: Benchmark data does not enter any model’s training or prompt cache. Evaluators are rotated periodically, and scoring scripts do not disclose their details to the party being tested.
Scale recommendation: 100–300 tasks are usually enough to support a meaningful selection review; for long-term tracking, you can continuously roll in additions.
4. Scoring: Automated Metrics as the Baseline, Human Review as the Gatekeeper
Automated metrics
- Hidden test pass rate: Original cases ensure no regression, and new cases verify whether the requirement is implemented.
- Static quality checks: Compilation or type checking, code style checks, and static security scans, to confirm whether the change introduces new warnings.
- Change size: Use diff line count and the number of changed files to measure whether the model is “restrained”; abnormally inflated changes are often a signal of over-modification.
- First-pass yield (FPY): The fraction of tasks that pass on the first try without human intervention, which directly reflects deliverability.
Human review
For dimensions that automated metrics cannot cover (whether requirement understanding is on point, whether the code style is consistent, and how maintainable it is), use blind review: reviewers do not know which model produced the result. Each item is scored from 1 to 5, plus a binary conclusion: “can it be merged directly?”
Statistical points
- Multiple sampling: Because generation is stochastic, repeat each task at least 3–5 times to avoid single-run results being dominated by chance.
- Confidence intervals: Compute pass@k (the probability of passing at least once across k samples), the mean, and the 95% confidence interval. When two models’ means differ by only one or two percentage points and their intervals overlap, it should not be treated as a significant difference.
- Significance testing: For mean-type metrics use a paired t-test; for pass-rate-type metrics use McNemar’s test.
- Distinguishing capability: pass@k reflects the potential to “get it right with a few more tries,” while FPY reflects the stability of “being reliable on the first try.” Teams pursuing delivery efficiency should value the latter more.
A simplified unified scoring formula:
Score = 0.5 × Hidden test pass rate+ 0.2 × First-pass yield+ 0.2 × Human review mean / 5+ 0.1 × Share of tasks with no new static-check warnings
The weights should be adjusted by the team according to business priorities and fixed before the evaluation begins, to prevent “fitting the results” after the fact.
5. Evaluation Skeleton: From Request to Results Table
Below is a reusable evaluation skeleton that runs tasks in batches through a unified inference interface, executes hidden tests in an isolated environment, and aggregates key metrics. In practice, you will need to replace it with your team’s own interface protocol and sandbox implementation.
import csvimport jsonimport osimport timefrom concurrent.futures import ThreadPoolExecutorfrom statistics import meanimport requestsAPI_BASE = os.environ["LLM_API_BASE"] # Unified inference gateway addressAPI_KEY = os.environ["LLM_API_KEY"]MODEL = os.environ["EVAL_MODEL"] # Identifier of the model under evaluationREPEAT = 3 # Repeat sampling count per taskdef call_model(prompt: str) -> tuple[str, int]:"""Call the unified inference API, return reply text and latency (ms)"""start = time.time()resp = requests.post(f"{API_BASE}/chat/completions",headers={"Authorization": f"Bearer {API_KEY}"},json={"model": MODEL,"messages": [{"role": "user", "content": prompt}],"temperature": 0.2},timeout=300,)resp.raise_for_status()return resp.json()["choices"][0]["message"]["content"], int((time.time() - start) * 1000)def run_task(task: dict) -> list[dict]:rows = []for _ in range(REPEAT):answer, latency = call_model(task["prompt"])patch = extract_patch(answer) # Extract code changes from the replypassed = run_hidden_tests(task["repo_snapshot"], patch) # Run in an isolated containerrows.append({"task_id": task["id"], "passed": passed, "latency_ms": latency})return rowsdef pass_at_k(rows: list[dict], k: int) -> float:"""Fraction of tasks passing at least once across k samples (k records per task)"""groups = {}for row in rows:groups.setdefault(row["task_id"], []).append(row["passed"])return mean(any(g[:k]) for g in groups.values())if __name__ == "__main__":tasks = [json.loads(line) for line in open("evalset/tasks.jsonl", encoding="utf-8")]with ThreadPoolExecutor(max_workers=8) as pool:results = [row for batch in pool.map(run_task, tasks) for row in batch]with open(f"result_{MODEL}.csv", "w", newline="", encoding="utf-8") as f:writer = csv.DictWriter(f, fieldnames=["task_id", "passed", "latency_ms"])writer.writeheader()writer.writerows(results)latencies = sorted(row["latency_ms"] for row in results)summary = {"model": MODEL,"sample_size": len(results),"pass_rate": round(mean(row["passed"] for row in results), 4),"pass@3": round(pass_at_k(results, 3), 4),"latency_p50_ms": latencies[len(latencies) // 2],"latency_p95_ms": latencies[int(len(latencies) * 0.95)],}print(json.dumps(summary, ensure_ascii=False, indent=2))
The whole flow can be organized into four steps:
- Unified call layer: Abstracts away the differences in interfaces and parameters across model services, so switching models later only requires changing environment variables.
- Sandbox execution layer: All model-generated code runs in isolated containers, with network access and dependency installation disabled, and with CPU, memory, and timeout limits set, to prevent infinite loops or malicious code from affecting the evaluation environment.
- Result storage layer: Details are written to object storage, making multi-person review and long-term trend analysis easier.
- Summary report: Outputs pass@k, first-pass yield, latency percentiles, and average token consumption per task, forming a comparison table that can be used directly for review.
6. From Selection to Production: Tiered Routing and Continuous Optimization
Evaluation is just the starting point. What is more worth investing in for production is a mechanism that dispatches a model per task.
- High-frequency light tasks: Scenarios such as inline completion, generating comments, and simple unit tests are extremely latency-sensitive. You can use the latency-optimized version of the same model family or a smaller-parameter model, combined with prompt caching to reduce overhead.
- Complex heavy tasks: Cross-module refactors, complex defect localization, and long-chain code generation go to the flagship model with stronger long-context ability and better multi-turn stability, and it is allowed to call tools and run tests.
- Routing criteria: Number of files involved, expected change size, historical success rate of similar tasks, and current system load. A simple example rule:
def route(task: dict) -> str:if task["latency_sensitive"] or task["files_touched"] <= 1:return "model_fast" # latency-optimized version / smaller modelif task["files_touched"] >= 5 or task["requires_test_loop"]:return "model_flagship" # flagship model, multi-turn tool calls allowedreturn "model_standard" # standard general-purpose version
Model performance changes with version iterations, so the routing table should also be reviewed and regression-tested like code. It is recommended to plug the evaluation pipeline into continuous integration, automatically re-run on each model version upgrade or eval set update, and track the following metrics on a dashboard:
- Success rate per scenario;
- Average number of interaction turns;
- Average latency;
- Cost per task.
Once a metric drops significantly, roll back or adjust the routing strategy promptly.
7. Cloud Support: Engineering the Eval Pipeline
A complete evaluation and inference pipeline can usually be built with general-purpose capabilities on a cloud platform:
- Object storage: Centrally store repo snapshots, eval sets, and result files;
- Message queue: Smooth out traffic spikes and asynchronously schedule large-scale evaluation tasks;
- Container platform: Host isolated sandboxes to ensure execution safety;
- Logging and monitoring/alerting: Retain call chains and alert promptly on anomalies in latency, failure rate, and other metrics.
On Baidu AI Cloud, these capabilities all have corresponding general-purpose product forms, and teams can combine them as needed based on their own tech stack.
8. Conclusion
Models iterate faster and faster, and the answer to “which model is the strongest” keeps changing, but the methodology of “how to scientifically measure models” remains valid over the long term. For teams preparing to purchase coding plan subscriptions, rather than chasing leaderboard rankings, it is better to accumulate an eval set and routing mechanism close to your own repo as early as possible. Only then can every model upgrade become a quantifiable, verifiable gain rather than a bet full of uncertainty.
