Evaluating Lightweight LLMs for Code Generation: Accuracy, Stability, and Cost Control

    A practical guide to evaluating lightweight large language models for code generation. Learn how to measure capability ceilings, pass-rate stability, and real token costs, and how to use tiered routing, prompt caching, and automated validation to keep production quality within budget.

    Why Lightweight Models Need Their Own Evaluation

    Lightweight models trade some capability for lower inference costs and faster response times. A common mistake during model selection is applying benchmark conclusions from flagship models directly to lightweight models, which often leads to unexpected gaps in production.

    The typical pattern is this: a lightweight model may match or even exceed its larger counterpart on some tasks, while its output quality drops noticeably on others. This variance comes from the combined effects of model capacity, training data distribution, and inference budget. Evaluation therefore needs to answer two questions: what can this model actually do, and can it do so consistently?

    The first can be called the capability ceiling; the second, the stability floor. Evaluations that only look at the ceiling tend to overvalue a model, because one impressive output says nothing about the average production experience.

    Breaking Down the Evaluation Dimensions

    Capability Ceiling vs. Stability Floor

    For the same batch of tasks, track two kinds of metrics separately:

    • Best single result: the best output across multiple samples, indicating whether the model has the potential to solve the problem.
    • Pass-rate distribution: call the model repeatedly with the same prompt and measure the proportion of outputs that pass validation, indicating whether results are reliable.

    If a model shows a high best single result but a low pass rate, it is suited for candidate generation, not for unattended automated pipelines.

    Code Correctness

    Code generation should be evaluated primarily through executable verification rather than subjective human scoring. Common approaches include unit tests, static analysis, and output format validation. For geometry, math, or graphics tasks, independently computed numerical results can serve as the ground truth.

    Cost and Latency

    Cost is determined by input tokens, output tokens, and cache hit rates. Latency affects interactive experience and batch throughput. Both should be compared alongside quality metrics in the same table—looking at any single dimension in isolation leads to wrong conclusions.

    Building a Reproducible Test Set

    Task Tiering

    Organize the test set into difficulty tiers, keeping a fixed number of problems per tier:

    1. Basic tier: function completion, string processing, simple data transformation.
    2. Reasoning tier: multi-step logic, edge-case handling, algorithm implementation.
    3. Construction tier: graphics generation tasks involving geometric constraints or spatial relationships.

    The purpose of tiering is to locate the model’s failure zone. If a model is stable on the basic tier but fluctuates on the construction tier, it can be assigned to everyday assistance scenarios, while complex tasks go to a larger model or human review.

    Example: Geometric Construction

    Geometric construction tasks are good for testing a model’s constraint understanding. For example, given three non-collinear points, ask the model to generate a graphics description that draws the circle passing through all three points. The correct approach is to construct the perpendicular bisectors of two sides; their intersection is the circle’s center. If the model merely states “the center is in the middle” without a verifiable construction process, it fails the test.

    The following script computes the circumcenter analytically and compares it against the model’s answer:

    1. import math
    2. def circumcenter(a, b, c):
    3. ax, ay = a
    4. bx, by = b
    5. cx, cy = c
    6. d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
    7. if abs(d) < 1e-12:
    8. raise ValueError("Points are collinear; no circumcircle exists")
    9. a2, b2, c2 = ax**2 + ay**2, bx**2 + by**2, cx**2 + cy**2
    10. ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d
    11. uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d
    12. return ux, uy
    13. def check_center(reported, points, tol=1e-3):
    14. ref = circumcenter(*points)
    15. return math.dist(reported, ref) <= tol

    This script only verifies whether the final result is correct. To check whether the construction steps are complete, you would also require the model to output the perpendicular bisector equations or the drawing sequence, then verify each item.

    Stability Testing with Repeated Sampling

    Stability must be measured through repeated calls. The following framework runs the same prompt multiple times and reports the pass rate:

    1. def run_trials(prompt, checker, call_model, n=10):
    2. results = []
    3. for _ in range(n):
    4. output = call_model(prompt)
    5. results.append(bool(checker(output)))
    6. return {
    7. "trials": n,
    8. "pass_rate": sum(results) / n,
    9. "first_attempt_pass": results[0],
    10. }

    Here call_model and checker are provided by the caller, representing the model interface and the validation logic respectively. Tasks with a pass rate below a set threshold should be logged separately as input for later routing decisions.

    Quantifying the Cost Structure

    A Cost Model

    The cost of a single call can be split into input, output, and cached portions. When the cache hit rate is high, input costs drop significantly. The following function estimates total daily cost; prices are per million tokens:

    1. def estimate_daily_cost(calls_per_day, in_tokens, out_tokens,
    2. cache_hit_ratio, price_in, price_in_cached, price_out):
    3. input_cost = in_tokens * (
    4. cache_hit_ratio * price_in_cached + (1 - cache_hit_ratio) * price_in
    5. )
    6. output_cost = out_tokens * price_out
    7. per_call = (input_cost + output_cost) / 1_000_000
    8. return per_call * calls_per_day

    The Impact of Cache Design

    Cache hits depend on whether the prompt prefix is stable. Placing system instructions, examples, and templates at the front of the prompt, and variable user input at the end, improves prefix reuse. Conversely, if every request starts with a timestamp or random identifier, the cache will almost never hit.

    Common Pitfalls in Budget Estimation

    Many teams only track output token prices and ignore the input overhead of long contexts. In code generation scenarios, each request often includes large code files, so input tokens frequently exceed output tokens. Estimates should be based on averages from real request logs, not idealized assumptions.

    Engineering Strategies for Production

    Tiered Routing

    Choosing a model based on task difficulty is an effective way to control costs:

    • Routine completions and format conversions go to the lightweight model.
    • Tasks with pass rates below the threshold are escalated to a larger model.
    • Tasks involving security, money, or production data must go through human review regardless of model size.

    Routing rules should be based on historical data from the test set, not intuition.

    Output Validation and Retry

    Every generated result should pass automated validation, such as compilation, unit tests, or schema checks. When validation fails, resubmit the request with the error message included. Set a cap on retries to keep costs under control.

    Monitoring Metrics

    Track the following metrics continuously in production:

    1. Validation pass rate, grouped by task type.
    2. Average input and output token counts.
    3. Cache hit rate.
    4. Percentage of requests escalated to a larger model.

    These metrics reveal whether model capability is drifting and help catch cost anomalies early.

    Common Pitfalls

    First, using a single result to represent overall performance. One successful output shows potential, not reliability.

    Second, comparing sticker prices instead of effective costs. If a model needs multiple retries to pass validation, its actual cost may exceed that of a nominally more expensive model.

    Third, letting the test set go stale. As the business evolves, old test sets no longer cover new scenarios, and evaluation conclusions gradually lose validity.

    Fourth, treating demos as evaluations. Carefully curated examples show the ceiling, not the distribution.

    Conclusion

    Evaluating lightweight models means measuring the capability ceiling, the stability floor, and total cost together. Teams should use tiered test sets, executable validation scripts, and repeated sampling to produce reproducible data. On that foundation, tiered routing, cache optimization, and output validation make it possible to keep production quality within budget. Model selection conclusions should be updated as test data changes, not fixed once and for all.