LLM Evaluation and Model Selection: An Engineering Methodology

    Selecting a large language model for production is not simply a matter of choosing the model with the highest leaderboard score. This article presents an engineering-oriented methodology for model evaluation and selection: define task profiles from business requirements, build a four-dimensional metric system covering effectiveness, efficiency, cost, and stability, create a small high-fidelity evaluation set, run controlled concurrent tests, calculate weighted scores and cost per valid task, and support production decisions with tiered routing, shadow traffic, canary releases, version regression, and drift monitoring. It also highlights common pitfalls such as over-relying on public benchmarks, ignoring tokenizer differences, and treating nominal context length as effective context.

    LLM Evaluation and Model Selection: An Engineering Methodology

    1. Why “Which Models Are Best?” Is Hard to Answer in Engineering

    In engineering discussions, a common question is “Which models rank at the top?” From an engineering perspective, this question is under-defined: it does not specify task distribution, input format, output constraints, latency budget, or cost ceiling.

    The same model may perform well on long-document extraction but frequently break JSON formatting in tasks that require strict structured output. It may have low time-to-first-token in short question answering but degrade sharply in throughput under long-context workloads.

    More importantly, three real-world constraints matter:

    1. Public benchmarks may be contaminated or optimized for. Test questions from large-scale evaluation sets may already be present in training data in some form. A high score does not necessarily mean the model is usable on your private data.
    2. Leaderboard aggregation hides distribution differences. A composite score is a weighted result of several capabilities. The weights are determined by the benchmark owner, not by your business.
    3. Capability is only one part of engineering feasibility. Context length, concurrency limits, output-format stability, content-safety policies, and billing methods can all make the “strongest” model unusable in your system.

    Therefore, the better question is not “Who is first?” but rather: Among my defined task set and constraints, which model provides the lowest cost per valid task and the highest reliability?

    2. Step 1: Turn Business Requirements into a Task Profile

    Before starting model selection, break the invocation scenarios into enumerable task types. Common categories include:

    • Short Q&A and rewriting: short input, short output, latency-sensitive, usually not requiring high model capability.
    • Long-document understanding and extraction: long input, often at the scale of tens of thousands of tokens, with structured output; tests effective context utilization and instruction following.
    • Code generation and completion: requires strict syntactic correctness; compilation or unit tests can serve as objective criteria.
    • Mathematical and logical reasoning: requires multi-step reasoning, and errors cannot be easily corrected downstream.
    • Tool calling and multi-turn agents: requires stable parameter structures, predictable stop conditions, and the ability to retry from any step after failure.
    • Content safety and compliance review: has clear business thresholds for refusal rate and false-positive rate.

    For each task type, record three numbers: daily call volume, average input/output token length, and tolerable P95 latency. Once these numbers are fixed, the candidate model set often narrows to two or three options.

    3. Step 2: Build a Four-Dimensional Metric System

    3.1 Effectiveness

    Prefer metrics that can be judged automatically to reduce the noise and cost of human review:

    • Extraction tasks: field-level Exact Match and F1.
    • Generation tasks: semantic similarity to reference answers, human ratings on a five-point Likert scale, or pairwise preference win rate.
    • Code tasks: compile pass rate, unit test pass rate, and pass@k (the proportion of k candidates in which at least one passes).
    • Structured output: JSON parsing success rate and schema compliance rate. This is often overlooked, yet it is a decisive factor for downstream system stability.
    • Long-document scenarios: effective context utilization, meaning how answer accuracy changes with target information placement in a long input.

    3.2 Efficiency

    • TTFT (time to first token): directly affects interaction experience.
    • TPOT (time per output token): determines waiting time for long outputs.
    • End-to-end P50/P95/P99: use percentiles rather than averages; averages can hide the long tail.
    • Concurrent throughput: the number of tokens per second achievable under your quota, and the stable concurrency level before rate limiting is triggered.

    3.3 Cost

    Do not compare only by unit price. Use cost per valid task:

    1. Cost per valid task = (input tokens × input price + output tokens × output price) × (1 + retry amplification factor) / task success rate

    Two often-overlooked items matter here. First, different models use different tokenizers, so the same Chinese text may produce very different token counts, making “price per 1K tokens” unsuitable for direct cross-model comparison. Second, failed retries genuinely amplify cost, so the retry amplification factor should be measured in production, not estimated.

    3.4 Stability and Controllability

    This dimension includes output variance across repeated samples of the same input, format-following rate at low temperature, instruction forgetting in long conversations, parameter errors in tool calls, and whether content-safety policies falsely block normal business inputs.

    4. Step 3: Build a Small, High-Fidelity Evaluation Set

    Public benchmarks are useful for “eliminating obviously unqualified candidates,” but the final decision should rely on a self-built evaluation set. Recommended practices:

    • Scale: 200 to 500 samples are enough to produce a discriminating conclusion. With too few samples, the gap between two models may fall within the noise range.
    • Source: sample from real production traffic by task type while preserving the original input distribution, including length, domain, and noise level.
    • Annotation: each sample should include a determinable reference answer or validation rule. For subjective tasks, use double-blind double annotation and check annotation quality with an agreement metric such as the Kappa coefficient; disputed samples go to arbitration.
    • Isolation: keep the evaluation set separate from the prompt-tuning set to avoid overfitting to evaluation samples. Rotate 20% to 30% of samples every 1 to 2 months to prevent contamination.
    • Hard-case construction: actively add boundary samples such as long-distance references, nested negation, multi-entity ambiguity, extremely short vague questions, and format traps, such as requiring code blocks or tables in the output.

    An example format that is easy to version:

    1. {"id":"ext-0137","task":"long_doc_extraction","input_chars":48210,
    2. "prompt_version":"v3","expect":{"fields":["amount","due_date"],"json_schema":"invoice_v2"},
    3. "judge":"exact_match","weight":1.5}

    5. Step 4: Unify Execution Conditions

    The credibility of an evaluation depends on controlling variables. Items that must be fixed include: sampling parameters such as temperature, top_p, maximum output tokens, and whether thinking or reasoning mode is enabled; prompt and system-instruction versions; input concatenation order; whether caching is enabled; retry count; and timeout thresholds.

    A minimal concurrent evaluation skeleton:

    1. import asyncio, json, time
    2. from dataclasses import dataclass, field
    3. @dataclass
    4. class Case:
    5. cid: str
    6. task: str
    7. prompt: str
    8. judge: str
    9. weight: float = 1.0
    10. @dataclass
    11. class Result:
    12. cid: str
    13. task: str
    14. ok: bool
    15. ttft: float
    16. tokens_out: int
    17. raw: str = ""
    18. error: str = ""
    19. detail: dict = field(default_factory=dict)
    20. async def one_case(case: Case, call, sem: asyncio.Semaphore) -> Result:
    21. async with sem:
    22. t0 = time.perf_counter()
    23. try:
    24. resp = await call(case.prompt) # Unified model invocation
    25. ttft = resp["ttft"] # Measured via streaming interface
    26. text = resp["text"]
    27. ok, detail = judge(case, text) # Judging logic is decoupled from the model
    28. return Result(case.cid, case.task, ok, ttft, resp["tokens_out"],
    29. text, "", detail)
    30. except Exception as e:
    31. return Result(case.cid, case.task, False, 0, 0, "", str(e))
    32. async def run(cases, call, concurrency=8, retries=2):
    33. sem = asyncio.Semaphore(concurrency)
    34. out = []
    35. for c in cases:
    36. for attempt in range(retries + 1):
    37. r = await one_case(c, call, sem)
    38. if r.ok or attempt == retries:
    39. out.append(r)
    40. break
    41. await asyncio.sleep(0.5 * (2 ** attempt)) # Exponential backoff
    42. return aggregate(out)
    43. def aggregate(results):
    44. agg = {}
    45. for r in results:
    46. s = agg.setdefault(r.task, {"n": 0, "ok": 0, "ttft": [], "tokens": 0})
    47. s["n"] += 1
    48. s["ok"] += int(r.ok)
    49. s["ttft"].append(r.ttft)
    50. s["tokens"] += r.tokens_out
    51. for task, s in agg.items():
    52. s["acc"] = s["ok"] / s["n"]
    53. s["ttft_p95"] = sorted(s["ttft"])[int(0.95 * len(s["ttft"])) - 1]
    54. s["avg_out_tokens"] = s["tokens"] / s["n"]
    55. return agg

    The key design point is that judging logic is fully decoupled from model invocation. This allows the same judge to be reused across candidate models and makes it easier to upgrade the judging process into a rule engine or a second-pass validation model.

    6. Step 5: Weighted Scoring and Decision Making

    Normalize the four dimensions and apply weights based on business priorities, not leaderboard priorities:

    1. S = w_eff × norm(accuracy) + w_perf × norm(1/P95 latency) + w_cost × norm(1/cost per valid task) + w_stab × norm(format compliance rate)

    For normalization, it is recommended to use min-max scaling within the same candidate set to avoid the situation where one metric being zero makes the total score uninterpretable.

    Example (data are for demonstrating the calculation method only):

    Candidate Weighted effectiveness score P95 latency (ms) Relative cost per valid task Format compliance rate
    A 0.86 1200 1.0 99%
    B 0.88 2100 0.62 95%
    C 0.79 700 0.45 92%
    D 0.83 1500 0.80 99%

    If the business weights are effectiveness 0.4, latency 0.2, cost 0.25, and stability 0.15, the final ranking will be clearly different from any single leaderboard. This also shows that differences in ranking mainly come from weights, not from absolute capability.

    7. Advanced: From Single-Model Selection to Tiered Routing

    A better production solution is often not “choose one model,” but route requests by difficulty:

    1. def route(req):
    2. if req.task in ("rewrite", "classify") and len(req.input) < 2000:
    3. return small_model # Low-cost model handles high-volume simple requests
    4. if needs_strict_schema(req):
    5. return strong_model_with_validator # Strong model plus post-validation and auto-repair
    6. if hit_semantic_cache(req):
    7. return cache # Prefer semantic cache first
    8. return default_model

    Three engineering techniques can further reduce cost: semantic caching, which reuses results for high-frequency similar requests; cascaded validation, where a small model answers first and a larger model is used when confidence is low or validation fails; and moving deterministic logic, such as regular expressions, rule engines, and retrieval, out of model responsibilities.

    In practice, many problems that appear to be “model capability issues” are actually caused by unclear task boundaries.

    8. After Launch: Keep Evaluation Alive

    Offline evaluation answers “whom to choose,” while online systems answer “whether it got better.”

    • Shadow traffic: a new version processes real requests in a bypass mode without returning results to users. Compare output differences and failure rates to obtain conclusions from production distribution with zero user risk.
    • Canary and A/B testing: route traffic by user or request. Core metrics include success rate, P95 latency, structured-output compliance rate, human handoff rate, and user retry rate.
    • Version regression: server-side model upgrades are a typical uncontrolled external change. Keep a fixed regression set and run it automatically before and after upgrades to produce a difference report.
    • Drift monitoring: significant shifts in input-length distribution, task-type proportions, or failure-reason distribution should trigger evaluation-set supplementation and threshold review.
    • Observability: logging and alerting should connect “request ID → model version → prompt version → input/output summary → judging result.” Otherwise, production issues cannot be attributed.

    On a platform that provides unified model access, such as Baidu AI Cloud, this workflow can usually be implemented with general capabilities: a unified model-invocation interface to abstract provider differences, logging services to retain call chains, monitoring and alerting to track latency and failure rates, and quota management to control concurrency and cost.

    9. Typical Pitfalls to Avoid

    1. Inferring capability from parameter count. Parameter count only affects the upper bound of capability. Actual performance depends on data quality, post-training, and alignment strategies; models with similar parameter counts can differ greatly.
    2. Extrapolating from a single leaderboard result. A leaderboard is a slice of capability distribution. It has little reference value when it does not match your task distribution.
    3. Ignoring cost distortion caused by tokenizer differences. Always convert to “cost per valid task” before comparison.
    4. Treating nominal context length as effective context. Maximum context length and information recall from the middle of long documents are two different things.
    5. Underestimating output-format instability. A rare JSON parsing failure can break an entire data pipeline.
    6. Looking only at the model, not the system. Prompt quality, retrieval quality, post-processing, and validation logic often bring larger gains than switching models.

    10. Conclusion

    “Which models are strongest?” has no single answer. A more valuable question is: “Under my task distribution, latency budget, and cost constraints, how do I select and continuously maintain the right combination of models?”

    A practical path is: define the task profile → build a four-dimensional metric system → create a high-fidelity evaluation set → run controlled concurrent evaluations → perform weighted scoring and cost analysis → use tiered routing and online regression.

    Following this path turns model selection from subjective debate into a reproducible engineering decision. When models iterate, you only need to rerun the same process instead of restarting the discussion each time.