Evaluating Lightweight LLMs for Code Generation: Benchmarking and Model Selection Practices

    This article explains why lightweight large language models require dedicated evaluation for code generation tasks, outlines four key assessment dimensions including accuracy, output stability, latency, and cost, and provides a practical framework for designing reproducible test cases, modeling token costs, and implementing staged model selection. It also discusses engineering strategies such as structured outputs, automated retries, and multi-model fallback, along with monitoring practices for production deployment.

    Why Lightweight Models Need Separate Evaluation

    Large language model (LLM) products are typically categorized by parameter scale and positioning. High-end models excel at complex reasoning and long-horizon tasks, while lightweight models serve high-frequency invocation scenarios with lower latency and unit cost—such as code completion, log classification, text extraction, and front-end prototype generation.

    When selecting models, many teams directly reuse evaluation results from flagship models. This practice can lead to biased conclusions. Lightweight models often perform close to large models on simple tasks, but on tasks requiring multi-step reasoning, precise constraints, or long contexts, their error rates may increase noticeably. Therefore, evaluating lightweight models requires a dedicated test suite rather than relying solely on marketing metrics or single-pass impressions.

    Four Evaluation Dimensions

    Evaluation should cover the following four dimensions.

    1. Task accuracy: Whether the output satisfies the functional constraints in the requirement.
    2. Output stability: Whether the pass rate and result distribution are controllable across multiple calls with the same input.
    3. Response latency: Time to first token and total output time, with special attention to long-output scenarios.
    4. Invocation cost: Input and output token fees per task, as well as the impact of cache hits on overall cost.

    Stability is the most frequently overlooked dimension. A single demonstration may yield excellent results, but production environments depend on the lower bound—that is, the probability that the model still delivers a usable result in the worst case.

    Quantifying Stability

    Call the same prompt n times, record the number of passed runs, and compute the pass rate p. With small sample sizes, results are highly random. For example, when n = 10, the difference between 7 passes and 9 passes may not be statistically significant; more samples are needed before drawing conclusions.

    Designing Reproducible Test Cases

    Test cases should satisfy three conditions: clear requirements, automated judgment, and the ability to differentiate model capability levels.

    Example: Geometric Construction Tasks

    Geometric construction tasks simultaneously test spatial reasoning, step decomposition, and code implementation. For instance, ask the model to generate the construction process for drawing a regular heptagon using a marked ruler (Neusis construction), displayed as an animation, with GIF export support. This task introduces three main difficulties:

    • A regular heptagon cannot be constructed with only a compass and an unmarked straightedge; it requires a marked ruler. The model must understand this prerequisite.
    • The construction steps have sequential dependencies—the intersection point from one step becomes the input for the next.
    • The animation should retain only essential trajectory traces, which tests the model’s ability to manage drawing state.

    Instead of relying on subjective human scoring, the judgment should be broken into checkable sub-items, such as whether the page loads correctly, whether drawing elements are present, whether key point coordinates deviate from theoretical values within a threshold, and whether the exported file is valid.

    Test Execution Flow Example

    The following pseudocode expresses the core logic of the evaluation loop:

    1. Input: test case set cases, model call function call_model, repetition count n
    2. For each case in cases:
    3. results list = empty
    4. For i from 1 to n:
    5. record start time
    6. output = call_model(case.prompt)
    7. elapsed = end time - start time
    8. passed = execute case.checks(output) // per-item automated checks
    9. append (passed, elapsed, token usage) to results
    10. Compute pass rate, median latency, P90 latency, average token cost
    11. Output summary report

    The check function should be independent of the model’s output format. If the logic relies on whether the model includes explanatory text, the model could pass or fail merely by adding an extra paragraph, causing the results to lose validity.

    Cost Modeling

    The cost of a single task can be calculated as:

    Single-task cost = (input token count × input token price) + (output token count × output token price)

    Daily cost can be estimated by multiplying daily request volume by the average single-task cost.

    In scenarios such as AI-assisted coding and agentic workflows, each request carries a long system prompt and historical context, making input tokens dominate the total token usage. In such cases, cache hit rate becomes a key cost factor. If the prompt prefix remains stable, cached portions are typically billed at a lower rate than uncached portions. However, hit prices and cache expiration times vary across services; always rely on official billing documentation and actual invoices rather than rough estimates.

    A practical approach is to place stable system instructions at the beginning of the prompt and dynamic content at the end, thereby improving prefix reuse and cache efficiency.

    Model Selection and Engineering Deployment

    Layering by Task Complexity

    • High-frequency, low-complexity tasks (code completion, classification, format conversion): Prefer lightweight models; focus on latency and cost.
    • Medium-complexity tasks (single-file code generation, API documentation generation): Use lightweight models with automated validation and retry mechanisms.
    • High-complexity tasks (cross-module refactoring, multi-step reasoning): Use a higher-tier model and limit invocation frequency.

    Mitigating Output Variability

    1. Structured output: Require the model to return results in a fixed format for easier parsing and validation.
    2. Automated validation and retry: Set a maximum retry count for failed results, and store failure samples for analysis.
    3. Multi-model fallback: Switch to a backup model when the primary one fails. Different models may produce different output styles, so verify downstream parsing logic compatibility before switching.
    4. Reduce sampling randomness: Lower the sampling temperature for tasks with high determinism requirements. This reduces variability but does not eliminate it.

    Monitoring Metrics

    After deployment, continuously monitor pass rate, latency percentiles, daily cost, and retry rate. Trigger alerts when the pass rate declines persistently or costs exceed budget, rather than waiting for user feedback.

    Building an Evaluation Pipeline on Baidu AI Cloud

    On Baidu AI Cloud, you can combine general-purpose compute resources, object storage, message queues, and log services to assemble an evaluation pipeline. Test cases are stored in object storage, evaluation jobs are distributed to concurrent execution nodes via a message queue, results are written to a log service, and a monitoring and alerting module generates trend reports. This architecture is model-agnostic, so the same test suite can be used to compare different models side by side.

    Summary

    Lightweight models provide value in high-frequency scenarios through efficiency and cost savings, but their limitation lies in output variability. Evaluation should place pass rate, stability, latency, and cost in the same comparison table, and use real business cases instead of single demonstrations. Model selection should be layered according to task complexity, with validation and retry mechanisms built in to absorb output fluctuations.