Local LLM Inference and Database QA Evaluation: A Practical Guide
This guide explains how to evaluate local large language model inference and database question answering without collapsing model capability, serving performance, and delivery correctness into a single score. It covers separate Prefill and Decode metrics, first-token latency decomposition, queueing effects under concurrency, KV-cache and concurrency trade-offs, and a safer optimization sequence. For database QA, it examines strict versus relaxed pass rates, output-contract failures, business-scope errors, join and aggregation grain issues, period-over-period calculations, and automated result validation. It also discusses the cost of multi-step correction and a reproducible evaluation loop that separates model capability, inference system behavior, and delivery contracts so test results can support deployment decisions.
Evaluating whether a large language model is suitable for production requires answering at least three questions: Can response speed meet interaction requirements? Does the output match the business definition of a correct result? And how many resources are consumed to obtain a correct result?
These questions cannot be resolved by a single overall score. For example, under high concurrency, a first output that takes too long to arrive may be caused by request queueing rather than insufficient model compute. A database query may be logically close to correct but fail because the decimal precision or column name does not meet requirements; this does not necessarily mean the model completely lacks query capability.
A sound evaluation should therefore be divided into three layers:
- Model capability layer: Whether the model understands the task and can construct queries, correct errors, and explain results.
- Inference system layer: Whether input processing, output generation, batch scheduling, and cache management are efficient.
- Delivery contract layer: Whether returned results satisfy requirements for column names, order, types, precision, and business definitions.
The following analysis uses a set of existing test records as a case study. The values reflect performance under that specific test configuration only. They should not be treated as a general performance benchmark, nor should they be used to infer results on other hardware, models, or deployment environments.
1. Build Interpretable Local Inference Metrics
1.1 Input Processing and Output Generation Are Different Stages
LLM inference generally has two stages.
The first stage is input processing, where the prompt is computed and the state needed for subsequent generation is established. This is commonly called Prefill. The second stage is step-by-step output, where new tokens are generated continuously. This is commonly called Decode.
These two stages have different computational characteristics, and their speeds should not be conflated. Long-document question answering is mainly affected by input processing time; long-answer generation is more likely to be limited by step-by-step generation speed. A system may read input quickly but generate text slowly, or perform well on a single request while degrading noticeably when multiple requests compete for resources.
At minimum, record the following metrics together:
| Metric | What it measures | Main use |
|---|---|---|
| Input processing rate | Number of input tokens processed per unit time | Observe long-prompt handling capability |
| Output generation rate | Number of output tokens generated per unit time | Observe sustained generation speed |
| First-token latency | Time from request submission to first output | Measure interactive waiting experience |
| End-to-end latency | Time from submission to completion of all output | Measure total task duration |
| System total throughput | Requests or tokens completed per unit time | Measure overall service capacity |
| Queueing time | Time a request waits for execution | Identify scheduling and capacity bottlenecks |
In particular, “single-request rate” and “system total throughput” must be distinguished. When multiple requests share compute resources, the speed of each request may decrease while total system throughput may still increase. A drop in single-request speed alone cannot determine whether concurrent scheduling has actually reduced overall efficiency.
1.2 What Raw Performance Records Can Show
Existing records show a single-concurrency input processing peak of about 757.7 tokens/s. For input lengths ranging from about 2,000 to 32,000 tokens, recorded rates were about 629–758 tokens/s, with no obvious sustained degradation as length increased.
During step-by-step generation, single-concurrency speed was about 23.8–28.7 tokens/s. After concurrency increased, some test points fell to 8–18 tokens/s. When longer inputs and higher concurrency were combined, low values of 8–11 tokens/s were observed.
These data indicate that under this configuration, single-request operation was relatively stable, while concurrent load had a significant impact on interactive performance. However, they are not sufficient to explain all causes, because information is still missing on hardware configuration, repetition count, output-length distribution, cache state, and total system throughput.
An isolated long-input test point that showed a speed rebound should not be interpreted as “longer input is faster.” Batch composition, cache hits, runtime variation, and statistical methodology can all produce such an effect, and repeated experiments are needed to verify it.
2. First-Token Latency Degradation: How to Identify Queueing Effects
2.1 Decompose First-Token Latency
First-token latency can be approximated as:
First-token latency ≈ request admission overhead + queueing time + input processing time + first generation overhead.
In the test records, first-token latency for an input of about 32,000 tokens rose from about 51.5 seconds at single concurrency to about 186.4 seconds at six-way concurrency. This change is related not only to model computation speed but also to how many requests the service allows into the execution stage at once.
In that deployment, the maximum number of concurrently executing sequences was 2. When external concurrency exceeded this limit, excess requests had to wait for an available execution slot. Long-input requests also occupied compute resources for extended periods, making a backlog likely.
This configuration makes queueing a priority suspect. However, to confirm how much delay queueing contributed, it is still necessary to record when a request enters the queue, when input processing begins, and when output begins. Total waiting time alone cannot precisely separate each component of overhead.
2.2 Raising the Concurrency Limit Is Not a Cost-Free Optimization
Increasing the number of simultaneously executing requests may reduce some queueing wait, but it also increases runtime state and key-value cache resource requirements.
The key-value cache stores intermediate state needed for attention computation. Its usage generally grows with the number of active sequences and context length; the exact footprint also depends on model architecture, cache precision, and implementation.
In the original records, the GPU memory utilization setting was 0.91, and a warning indicated that cache space was close to its capacity boundary. Note that a GPU memory utilization configuration value is not the same as real-time memory occupancy. Whether resources are actually near their limit should be determined from runtime monitoring and cache usage.
Therefore, when adjusting the concurrency limit, monitor the following at the same time:
- Cache occupancy and available headroom;
- Request waiting time and completion time;
- Whether total system throughput increases;
- Whether cache eviction, request recomputation, or resource shortage occurs;
- Whether there is noticeable interference between long and short requests.
Increasing the token budget allowed per batch involves a similar trade-off. A budget that is too small may limit throughput, while one that is too large may let long-input tasks occupy more execution time and affect interactive request responsiveness. The optimization goal should be to meet business latency requirements while improving effective throughput, not simply to increase configuration values.
2.3 A More Reliable Optimization Path
Run experiments in the following order:
- Fix input length and output length, and establish a single-concurrency baseline.
- Increase concurrency step by step while collecting both single-request rate and total system throughput.
- Within available resources, adjust the number of simultaneously executing requests in small increments.
- Test mixed long- and short-input scenarios separately to observe whether long requests block short requests.
- If the inference engine supports chunked input processing, evaluate its impact on interactive latency and total throughput.
- Add business-side constraints for very long contexts, such as retrieval filtering, segmented processing, or context truncation.
These methods do not guarantee performance improvements in every environment, but they allow optimization conclusions to be based on observable data.
3. Database QA Evaluation: Why Pass Rates Need Layered Interpretation
3.1 A Low Strict Pass Rate Does Not Mean All Query Logic Is Wrong
The capability test contained 25 questions. Nine passed under strict judgment, for a pass rate of 36%. By difficulty, 8 basic questions passed, 1 simple question passed, and no medium or hard questions achieved a strict pass.
On the other hand, the test records show that all questions completed the tool-calling workflow, including generating queries, executing queries, viewing results, and submitting results. Some complex questions also generated multi-table joins, window functions, period-over-period comparisons, and cumulative share calculations.
This indicates that the model has some ability to construct queries and use execution feedback. However, completing the tool-calling loop only proves that the workflow ran; it does not prove that every query was semantically correct, nor does it guarantee that complex queries remain reliable under different data distributions.
The original records estimate that, after relaxing numeric comparison rules, the pass rate might reach 22/25, or about 88%. This estimate cannot replace a new evaluation result, and “allowing numeric error” and “ignoring format differences” are two different operations.
For example, a value that was not rounded as required may differ from a two-decimal result by more than one part in a million. To obtain a credible relaxed pass rate, the numeric normalization and comparison method must be specified, and each question must be rechecked.
3.2 Format Is Part of Delivery Correctness
If a question requires specified column names, a fixed number of decimal places, and a particular sort order, missing those constraints affects downstream program consumption of the result.
Therefore, “logically correct but format-noncompliant” is different from a calculation error, but it is still an engineering failure. A temporary analysis result intended for human reading may tolerate differences that a person can interpret. A result that feeds directly into a report or automated process must satisfy the data contract.
Split evaluation results into the following dimensions:
- Execution correctness: Whether the query runs successfully.
- Business correctness: Whether filters, grouping grain, and statistical definitions match the question.
- Calculation correctness: Whether joins, aggregations, ratios, and window calculations are correct.
- Output contract correctness: Whether column names, types, order, precision, and sorting comply.
- Final delivery correctness: Whether all required conditions are satisfied at the same time.
The strict pass rate should be retained, but it should be accompanied by an error classification report rather than replacing all analysis with a single number.
4. Structural Errors Deserve Priority over Surface Format Errors
4.1 Business Definition Deviations
In testing, there was a case where channel share was calculated using the wrong channel. Such errors often do not trigger query execution exceptions, and the result may look reasonable while answering a different question.
The solution is to clarify the following before writing the query:
- What is the statistical object?
- Which records are included in the numerator and denominator?
- What are the time range and channel range?
- Should refunds, canceled orders, or invalid records be excluded?
- Is the calculation grain order, customer, or product detail?
For share-based questions, check the denominator especially carefully. For example, “the share of a channel in total sales” and “the share of a product within a channel” both use division, but their business meanings are completely different.
4.2 Multi-Table Joins and Aggregation Grain
When discounts, order details, and multiple dimension tables are involved, check whether joins amplify the data.
If order-level amounts are joined directly to detail-level records and then summed, the same order amount may be counted repeatedly. A reliable approach is to define the grain of each intermediate result first, pre-aggregate where necessary, and check whether join keys are unique.
Three checks can be applied to intermediate results: whether row counts match expectations, whether key identifiers are duplicated, and whether amount totals show abnormal growth. The fact that the model generated a complex query structure does not mean these implicit constraints have been verified.
4.3 Period-over-Period Calculations and Empty Results
Period-over-period comparisons usually require a window function to obtain the previous period’s value and then calculate the rate of change. If records from the previous period are filtered out before the window calculation, the current period may have no comparison baseline.
The following illustrative query shows a common processing order:
WITH period_totals AS (SELECTperiod_key,SUM(amount) AS total_amountFROM transaction_recordsGROUP BY period_key),period_comparison AS (SELECTperiod_key,total_amount,LAG(total_amount) OVER (ORDER BY period_key) AS previous_amountFROM period_totals)SELECTperiod_key,ROUND((total_amount - previous_amount) * 100.0/ NULLIF(previous_amount, 0),2) AS growth_rateFROM period_comparisonWHERE period_key = :target_period;
This example assumes that period keys sort correctly and that adjacent records represent adjacent business periods. If a period is missing from the data, the preceding record is not necessarily the previous quarter or month; in that case, the time series must be filled in or the missing-period handling rule must be specified.
For cases with no previous period or a previous period of zero, the question and result contract should define whether to return null, a special marker, or another business definition. The model should not guess.
5. Turn Result Validation from Prompt Instruction into an Execution Process
Simply writing “pay attention to precision” in a prompt is usually not robust enough. A more reliable method is to turn constraints into a pre-execution checklist and validate results after execution.
Pre-execution checks should include:
- Whether the final output contains only the required columns;
- Whether column aliases match the requirements;
- Whether ratios need to be multiplied by 100;
- Whether two decimal places must be retained;
- Whether sorting is required and how ties should be handled;
- How nulls, zero denominators, and missing periods should be handled.
Post-execution checks should cover column structure, row count, data types, and key numeric ranges. For example, check whether percentages are out of bounds, whether totals are abnormally inflated by duplicate joins, and whether a query expected to return results instead returns an empty table.
Also distinguish numeric rounding from string formatting. ROUND(value, 2) usually expresses numeric rounding, but it does not necessarily guarantee a fixed two-decimal string for display. If the delivery requirement is a fixed text form, handle it explicitly in the result serialization layer rather than relying only on the query expression.
For constraints that can be automated, prefer deterministic validation programs. Models are suitable for interpreting questions and correcting queries, but column-name checks, decimal precision, and row-count checks do not need to be fully delegated to a probabilistic generation process.
6. Evaluation Cost: Focus on “Effective Completion,” Not a Single Call
The original records show that basic and simple questions took about two steps on average, while hard questions took about 6.1 steps on average. Some questions reached 14–17 steps and consumed about 55,000 tokens in total.
These data suggest that the cost of complex tasks comes not only from the final answer but also from repeated querying, reading results, analyzing errors, and re-execution. Even if final accuracy improves, too many retries may still fail to meet business latency requirements.
Record the total time, input and output tokens, query count, failure reason, and final pass status for each question, and calculate the “average cost per qualified result.”
For tasks where continuous correction is ineffective, set stopping conditions: reaching a maximum number of attempts, exhausting a resource budget, or terminating after the same error repeats multiple times. Returning a clear failure reason is usually more controllable than retrying indefinitely.
7. Build a Reproducible Evaluation and Optimization Loop
A practical evaluation process can be divided into four steps.
First, freeze the experimental conditions. Record hardware resources, inference configuration, context range, output length, request concurrency, and cache state. Warm up before formal testing, and distinguish cold-start results from steady-state results.
Second, run a performance matrix. Combine short, medium, and long inputs with different concurrency levels, repeat tests, and report median and high-percentile latency so that a single peak does not dominate the conclusion.
Third, build a capability error classification. Retain the strict pass rate while separately counting business-definition, query-structure, calculation-logic, and output-format errors. For scores under relaxed rules, explain the rule changes and recompute them; do not rely on visual estimates.
Fourth, optimize one variable at a time and retest. Adjust only one type of factor per iteration, such as scheduling configuration, output-constraint prompts, or result validation methods, then observe whether the benefit is stable and whether it introduces new resource risks.
Ultimately, the purpose of evaluation is not to label a model as “good” or “bad.” It is to identify the load under which the model can complete tasks reliably, which errors can be controlled through engineering measures, and what resource cost is required to meet business requirements. Only by analyzing model capability, the inference system, and delivery contracts separately can scattered test results be turned into actionable deployment decisions.
