LLM Engineering: Evaluating, Selecting, Deploying, and Governing Large Language Models

    Large language models are being released and upgraded at a rapid pace, but leaderboard scores alone are not enough for engineering teams. This article provides a practical framework organized around evaluation, model selection, deployment, and governance. It explains how to move beyond public benchmarks, build internal evaluation sets, compare latency, throughput, stability, and cost, optimize inference services, apply tiered routing and fallbacks, manage prompts and structured outputs, and run regression checks for model upgrades. The goal is to turn model capability into stable, controllable, and economical engineering systems.

    1. Iteration Logic: Understanding the Technical Changes Behind Model Updates

    Rapid model iteration has become the norm. Open models at the hundreds-of-billions-parameter scale are now approaching mainstream international performance in general reasoning, code generation, and mathematics, while some public benchmark results are close to top closed-source models. At the same time, flagship models from major international vendors continue to raise the performance ceiling.

    For developers and enterprise technical decision-makers, the important questions are not only which model scores higher, but also:

    1. How can different models be compared fairly?
    2. What technical changes in a new model are worth attention?
    3. How can a team evaluate a new model scientifically?
    4. How can improved model capability be turned into stable, controllable, and economical engineering delivery?

    This article follows a practical path: evaluation, model selection, deployment, and governance.

    1.1 Three Sources of Capability Improvements

    Over the past two years, major capability gains in large language models have come from three directions.

    • Architecture and data: Mixture-of-Experts, or MoE, architectures push total parameter counts toward the trillion-parameter scale while activating only a subset of experts for each token. When compute budgets are limited, this approach can expand model capacity and training data scale at the same time.
    • Post-training: Supervised fine-tuning, reinforcement learning from human feedback, and reinforcement learning based on verifiable rewards for reasoning tasks help models follow instructions more reliably, decompose problems more effectively, and perform more self-checking.
    • Inference-time compute: Models can be allowed to perform longer internal reasoning before answering, a strategy often described as test-time scaling. More inference compute can improve accuracy on difficult math, code, and logic problems. The tradeoff is longer response times and significantly higher token consumption.

    For engineering teams, these three points mean that a model is not simply “a stronger question-answering endpoint.” It is a compute component with adjustable capability boundaries and measurable resource consumption. The first step in model selection is to identify which of these capabilities your workload actually depends on.

    1.2 Engineering Challenges Caused by Frequent Iteration

    Frequent model updates create several engineering challenges:

    • Cognitive cost: Versions change quickly. Parameter settings, prompting techniques, and experience accumulated earlier may soon become obsolete.
    • Regression risk: New versions often change output style, default behavior, and tool-calling formats. Upgrading a model can therefore introduce behavioral drift.
    • Long context and deeper reasoning: Both raise the upper limit of task performance, but they also increase latency and cost per request.

    Teams therefore need a stable model access layer that treats model versions as replaceable configuration rather than scattering model-specific calling logic across business code.

    2. Capability Evaluation: From Public Leaderboards to Internal Evaluation Sets

    2.1 Three Limitations of Public Benchmarks

    Public benchmarks are useful, but they have three important limitations.

    • Ceiling effect: Many general-purpose benchmarks are already widely represented in training data. Scores for mainstream models cluster at a high level, reducing their ability to distinguish between models.
    • Data contamination: Evaluation questions and their variants may already appear in training corpora. A model may have “seen the question” rather than truly “solved the question.”
    • Task mismatch: Public benchmarks measure academic-style tasks, while real business workloads involve domain-specific terminology, formatting constraints, and workflow requirements.

    The conclusion is straightforward: public benchmarks are suitable for initial screening and broad comparison, but final selection should rely on your own evaluation set.

    2.2 Building an Internal Evaluation Set

    A practical internal evaluation set can be built through the following steps.

    1. Layered sourcing: Sample real production requests by scenario, such as question answering, summarization, information extraction, code generation, and multi-turn tasks. Add a small number of manually constructed edge cases.
    2. Anonymization and compliance: Remove or replace sensitive fields such as personal information and internal secrets, ensuring that evaluation data use complies with internal policies.
    3. Reference answers and scoring rules: For objective questions, define standard answers. For subjective questions, create detailed rubrics. Each case should list two to five judgeable scoring points.
    4. Double annotation: For subjective scoring, measure inter-annotator agreement, for example with Cohen’s Kappa. If agreement falls below 0.6, revise the rubric first rather than forcing an average score.

    2.3 Selecting Metrics

    A model evaluation framework should cover more than output quality alone.

    Dimension Core metrics Notes
    Effect Task success rate, key-point coverage, JSON validity Align with business acceptance criteria; avoid relying only on a vague sense of “better quality.”
    Latency Time to first token, or TTFT; time per output token, or TPOT; end-to-end latency Streaming interaction focuses on TTFT; batch tasks focus on end-to-end latency.
    Throughput Tokens generated per second, maximum concurrency Determines how much work can be served per unit of compute.
    Stability Timeout rate, failure rate, consistency across repeated calls Even with temperature set to 0, outputs may still vary, so multiple samples are needed.
    Cost Cost per 1,000 requests, average tokens consumed per task Distinguish input token pricing from output token pricing.

    2.4 Cautions When Using Model-as-a-Judge

    Using another strong model to score outputs can greatly improve the efficiency of subjective evaluation, but several biases need to be controlled.

    • Prefer longer answers.
    • Be affected by option order, also known as position bias.
    • Prefer outputs that resemble the judge model’s own style, also known as self-preference.

    Mitigation strategies include:

    • Shuffling candidate answers and swapping their positions in both directions.
    • Using multi-point coverage instead of a single overall score.
    • Periodically sampling outputs for manual review.

    When adding a new candidate model, re-evaluate all competing models on the same evaluation set. Only then are the results comparable.

    2.5 Evaluation Harness Skeleton

    The following example uses only the Python standard library and shows a basic evaluation workflow.

    1. # Python standard library only; this is a skeleton for an evaluation pipeline.
    2. import asyncio
    3. import time
    4. import statistics
    5. from collections import defaultdict
    6. # 1. Evaluation cases: each case can include a checking function.
    7. def exact_match(text: str, expect: str) -> float:
    8. return float(text.strip() == expect.strip())
    9. def json_valid(text: str, required_keys: list) -> float:
    10. import json
    11. try:
    12. obj = json.loads(text)
    13. except json.JSONDecodeError:
    14. return 0.0
    15. return float(isinstance(obj, dict) and all(k in obj for k in required_keys))
    16. cases = [
    17. {"id": "qa-001", "scene": "QA", "messages": [{"role": "user", "content": "..."}],
    18. "check": lambda out: exact_match(out, "Reference answer")},
    19. {"id": "ex-001", "scene": "Extraction",
    20. "messages": [{"role": "user", "content": "Extract the name and date from the text and output JSON"}],
    21. "check": lambda out: json_valid(out, ["name", "date"])},
    22. # Add more cases sampled from anonymized production logs.
    23. ]
    24. # 2. Model adapter: unified interface to hide differences between backends.
    25. async def call_model(messages: list, model: str, temperature: float = 0.2) -> str:
    26. # Replace this with a unified model service client in a real project.
    27. ...
    28. # 3. Concurrent execution and scoring.
    29. async def run_case(case: dict, model: str, semaphore) -> dict:
    30. async with semaphore:
    31. start = time.perf_counter()
    32. output = await call_model(case["messages"], model)
    33. elapsed_ms = (time.perf_counter() - start) * 1000
    34. return {**case, "model": model, "output": output,
    35. "elapsed_ms": elapsed_ms, "score": case["check"](output)}
    36. async def evaluate(model: str, concurrency: int = 16):
    37. semaphore = asyncio.Semaphore(concurrency) # Avoid overwhelming the inference service.
    38. tasks = [run_case(c, model, semaphore) for c in cases]
    39. return await asyncio.gather(*tasks)
    40. # 4. Summary: group scores by scene; examine latency percentiles.
    41. def summarize(results: list) -> dict:
    42. scenes, latencies = defaultdict(list), []
    43. for r in results:
    44. scenes[r["scene"]].append(r["score"])
    45. latencies.append(r["elapsed_ms"])
    46. latencies.sort()
    47. p95 = latencies[min(len(latencies) - 1, int(len(latencies) * 0.95))]
    48. return {
    49. "model": results[0]["model"],
    50. "case_count": len(results),
    51. "overall_score": round(statistics.mean(r["score"] for r in results), 4),
    52. "score_by_scene": {s: round(statistics.mean(v), 4) for s, v in scenes.items()},
    53. "latency_p95_ms": round(p95, 1),
    54. }
    55. if __name__ == "__main__":
    56. models = ["model-a", "model-b", "model-c"] # Candidate models come from configuration.
    57. for name in models:
    58. print(summarize(asyncio.run(evaluate(name))))

    Three details in this code are especially important.

    • Unified interface: An adapter layer hides differences between model services, keeping the evaluation framework decoupled from specific model backends.
    • Fixed parameters: All candidate models should use the same temperature, maximum output length, and system prompt for the same cases.
    • Statistical significance: If two models differ by only one or two percentage points in overall score, that difference alone should not drive a decision. Bootstrap sampling can be used to produce 95% confidence intervals. If the intervals overlap substantially, treat the difference as insignificant and make decisions based on engineering metrics such as latency and cost.

    3. Selection Dimensions: Five Questions Beyond Parameter Scale

    3.1 Does Task Capability Match the Workload?

    New models often shine in benchmarks related to math, code, and complex reasoning. Most business workloads, however, consist of tasks such as:

    • Classification and extraction;
    • Summarization;
    • Dialogue;
    • Long-document question answering;
    • Tool calling.

    Strong general capability does not automatically translate into business value. For example, extraction tasks care more about format stability and faithfulness, meaning the model should not invent information absent from the source. Code tasks care more about the pass rate on real engineering problems.

    3.2 Is Long Context Effectively Usable?

    A advertised context window length is not the same as effective use of long context. A common issue in the industry is “lost in the middle”: when critical information appears in the middle of a long document, model performance may decline noticeably.

    A practical test is to construct “needle in a haystack” style cases by inserting several facts into a long document, then measuring recall at different depth positions.

    3.3 Inference Performance and Resource Requirements

    Large-model inference involves two main stages:

    • Prefill stage, processing the input: Compute-intensive; mainly determines time to first token.
    • Decode stage, generating tokens one by one: Constrained by memory bandwidth; it repeatedly reads model weights and the KV cache.
    • Batching: Higher concurrency can amortize weight-reading costs and improve throughput, but per-request latency may increase.

    A simplified memory estimation is as follows:

    1. Weight memory ≈ parameters × bytes per parameter ÷ tensor parallelism
    2. KV cache ≈ 2 × layers × KV heads × head dimension × sequence length × concurrency × bytes per element

    The factor of 2 represents one copy each for Key and Value. KV cache grows linearly with context length and concurrency. In long-context serving, KV cache often becomes a memory bottleneck, requiring tradeoffs among context length, concurrency, and number of GPUs.

    For MoE models, total parameter count and activated parameter count differ significantly. Total parameters determine memory occupancy, while activated parameters determine compute per token. Both must be considered to estimate resource needs accurately.

    3.4 Controllability and Engineering Friendliness

    Important questions include:

    • Structured output: Can the model reliably follow a JSON schema or function-calling format?
    • Instruction following: Can it strictly obey constraints on length, tone, and output templates?
    • Parameter tunability: Are common parameters such as temperature and maximum output length available? Is there an option for reasoning intensity?
    • API consistency: Does the interface follow mainstream conventions? Can other models be switched with low cost through an adapter layer?

    3.5 Compliance and Sustainability

    For production systems, compliance and long-term sustainability matter.

    • License: For open-weight models, commercial terms, redistribution requirements, and derivative-model rules must be reviewed carefully. “Open source” does not mean “unconditional commercial use.”
    • Data processing: Clarify whether input data is used for training, how long logs are retained, and whether deployment options support keeping data within a specific region.
    • Roadmap: Version iteration frequency and deprecation policies directly affect upgrade cadence and regression cost.

    4. Inference Deployment: Turning Model Highlights into Service Capability

    4.1 Latency-Centered Capacity Planning

    Latency budgets for online services are usually derived from user experience. For example, in an intelligent question-answering scenario, if the overall response should complete within a few seconds, TTFT should generally be controlled within one second, and subsequent generation speed should be close to or faster than human reading speed.

    This requires determining, based on stress tests:

    • Maximum concurrency per replica;
    • Required tensor parallelism;
    • Target percentile for queue waiting time.

    4.2 Common Inference Optimization Techniques

    Technique Main benefit Cost and cautions
    Weight quantization, such as FP16 to INT8 or INT4 Reduces memory usage and improves bandwidth efficiency during decoding May introduce accuracy loss; regression testing on the internal evaluation set is required.
    KV cache quantization or sparsification Relieves memory pressure in long-context scenarios Long-range information recall may decrease; dedicated evaluation is needed.
    Continuous batching Significantly improves overall throughput Per-request latency may rise as batch size fluctuates.
    Prefix reuse or caching Avoids recomputing identical system prompts or long documents Depends on consistent request prefixes; prompt structure must be designed carefully.
    Speculative decoding with a draft model Reduces average generation latency Benefits are limited if the draft hit rate is low; implementation complexity increases.
    Tensor parallelism or expert parallelism Supports models that do not fit on a single GPU Introduces inter-GPU communication overhead; linear speedup is difficult to maintain.

    An often-overlooked principle is that optimization must be coupled with evaluation. Before deploying any quantization scheme, parallelism strategy, or caching strategy, treat it as a candidate configuration and run a quality regression on the internal evaluation set. Do not rely only on load-test metrics.

    4.3 Context Management

    • Prompt structure: Place stable instructions before dynamic content so that prefix caching can be reused.
    • History trimming: Trim conversation history by turn count or token budget. Summarize early but critical information when necessary.
    • Retrieval augmentation: When tasks depend on external knowledge, use retrieval results instead of stuffing an entire document into the context. This balances effectiveness and cost.

    5. Cost Control: Model Tiering and Multi-Level Fallback

    5.1 Tiered Routing

    Requests can be routed according to complexity:

    1. First, perform rule-based or lightweight classification.
    2. Send simple requests to smaller models.
    3. Escalate to larger models when confidence is insufficient or classification fails.
    4. Log all routing decisions so that thresholds can be reviewed and tuned later.
    1. async def resolve(user_input: str, fast_model: str, strong_model: str):
    2. messages = [{"role": "user", "content": user_input}]
    3. tier = classify_difficulty(user_input) # Returns "simple" or "hard"; thresholds are tuned with production data.
    4. if tier == "simple":
    5. answer = await call_model(messages, fast_model)
    6. if need_escalate(answer): # Escalate on refusal, empty output, or low confidence.
    7. answer = await call_model(messages, strong_model)
    8. else:
    9. answer = await call_model(messages, strong_model)
    10. return answer

    The classifier itself must be monitored continuously. Teams should sample and inspect two categories of cases: those judged as simple but later escalated, and those judged as simple but associated with user dissatisfaction. The routing threshold should be adjusted dynamically.

    5.2 Multi-Level Cascade

    For critical request paths, design a three-level structure:

    1. Primary model;
    2. Backup model;
    3. Fallback strategy.

    If the primary model times out or fails repeatedly, the system should switch automatically. The fallback strategy should return a clear message or route the request to human support. Retries should use exponential backoff with random jitter to avoid a retry storm immediately after a failure recovery.

    For services that support streaming output, prioritize streaming. In that case, TTFT is usually the primary user-experience metric.

    5.3 Separating Offline and Online Workloads

    • Offline tasks such as report generation, batch annotation, and data cleaning are suitable for throughput-oriented configurations. Batching can reduce the cost per token.
    • Real-time interactive requests should prioritize latency. If necessary, use a smaller model with stricter output constraints to maintain stable responses.

    6. System Governance: Prompt Management, Structured Output, and Observability

    6.1 Prompt Versioning

    System prompts, few-shot examples, and output templates should be placed under version control and linked to model versions. Every change should trigger an evaluation regression. This avoids the common problem where “changing one word changes behavior, but nobody knows why.”

    6.2 Dual Safeguards for Structured Output

    Constrained decoding can reduce format errors, but it cannot guarantee semantic correctness. Business systems still need:

    • Validation: Check outputs against a schema.
    • Repair: Re-request failed samples with error information attached.
    • Degradation: When failures continue, fall back to rule-based extraction or human handling.

    6.3 Observability

    Logs should record:

    • Request ID;
    • Model version;
    • Prompt version;
    • Input and output token counts;
    • Staged latency data;
    • Routing decisions.

    Metrics should include at least:

    • Success rate;
    • Latency percentiles by stage;
    • Token consumption per task;
    • Human takeover rate;
    • Explicit user feedback, such as thumbs-down rate.

    Cost budget alerts should also be configured to prevent abnormal traffic or prompt defects from causing a sudden increase in token consumption. Relevant data can be centrally collected and displayed using cloud logging services and monitoring/alerting capabilities, making problem diagnosis faster.

    6.4 Model Upgrade Regression Process

    1. Run full regression on the new evaluation set.
    2. Set no-degradation thresholds for key business metrics.
    3. Release gradually, starting with small traffic canaries and then increasing traffic step by step.
    4. Preserve a one-click rollback capability.

    7. Common Pitfalls and How to Avoid Them

    • Pitfall 1: Bigger is always better. Parameter count is only an upper bound on capacity. Task fit, output stability, and inference cost are equally important.
    • Pitfall 2: Leaderboard scores equal business performance. Public benchmark distributions differ from business distributions. Internal evaluation sets should be the final reference.
    • Pitfall 3: Upgrading is pure benefit. Upgrades require full regression, with special attention to format changes, refusal behavior, and style changes.
    • Pitfall 4: Long context can replace retrieval. Long context has diminishing marginal returns. Information utilization is unstable, and cost increases with length.
    • Pitfall 5: Calling models directly inside business code. Without an adapter layer, model lock-in and switching costs are amplified.

    These issues can be mitigated through three mechanisms:

    1. A unified model access layer;
    2. A continuous evaluation mechanism;
    3. A complete observability system.

    8. Conclusion

    Faster model iteration gives developers stronger capabilities, but it also raises engineering requirements. For very large language models, the real value is not a leaderboard ranking. The real value is whether a model can be evaluated reliably, deployed stably, cost-controlled effectively, and upgraded continuously.

    By using an internal evaluation set as the anchor, performance and cost constraints as boundaries, and tiered routing plus observability as safeguards, teams can stay in control even in a rapidly changing model ecosystem.

    In cloud environments, product categories such as model services, container services, object storage, logging services, and monitoring/alerting can serve as building blocks for this kind of technical stack. Baidu AI Cloud, for example, offers product categories in these areas that can be used as references. Teams should still choose the right combination based on their actual business requirements and convert model capability into measurable business value.