Single-Forward Decision Making: Scoring Agent Options with Calibrated Probabilities

    This article explains how to treat agent action selection as a scoring problem instead of autoregressive text generation. It covers a formal task definition, a single-forward encoding and softmax scoring pipeline, probability calibration with ECE and temperature scaling, latency measurement and optimization, evaluation dimensions, deployment and monitoring practices, and common pitfalls.

    Why Agents Need to Decide, Not Write

    In many agent systems, the model’s job is not to produce long text. It is to choose one action from a finite set under a latency budget. A support bot may transfer to a human, send a template reply, or ask for more information. An operations agent may scale out, roll back, degrade, or keep watching. A game or simulation agent may pick a move or skill at every step.

    These tasks share three traits:

    1. High decision frequency. A session or workflow may require tens or hundreds of decisions, so per-call latency compounds.
    2. Limited output space. Candidates are an explicit set, from a handful to a few hundred.
    3. Need for usable confidence. Upstream logic often uses probability thresholds for human handoff, so calibration and ranking both matter.

    Autoregressive generation first emits an action name or ID, then parses it. Every token pays a full decode cost, latency grows with output length, parse failures require retries, and the same option can be phrased in many ways, splitting probability mass. When the task is “pick one,” that overhead is often unnecessary.

    A practical alternative is to score the candidate set. The model reads the current state and question, emits a probability for each option, and runs a single forward pass with no intermediate text.

    Formalizing the Decision Task

    Let the current state be (s) and the candidate set (A = {a_1, a_2, \dots, a_n}). The goal is to estimate (p(a_i \mid s)) with (\sum_i p(a_i \mid s) = 1).

    A simple request/response shape:

    1. from dataclasses import dataclass
    2. from typing import List
    3. @dataclass
    4. class DecisionRequest:
    5. state: str # textual or serialized state
    6. question: str # decision question
    7. options: List[str] # readable option descriptions
    8. @dataclass
    9. class DecisionResult:
    10. option_ids: List[str]
    11. probabilities: List[float]
    12. def best(self):
    13. idx = max(range(len(self.probabilities)), key=lambda i: self.probabilities[i])
    14. return self.option_ids[idx], self.probabilities[idx]

    Two constraints matter. Option text should be stable and unambiguous, or scores will drift across requests. Option order should not change results. Shuffle options during training and evaluation to avoid position bias.

    Single-Forward Scoring

    “Single-forward” means one forward pass produces scores for all options, then softmax yields probabilities. A typical split:

    1. State encoding. Encode state and question once.
    2. Option encoding. Encode each candidate; batch when the set is large.
    3. Scoring and normalization. Combine state and option vectors into a scalar, then softmax.

    Illustrative structure (names are not a specific API):

    1. import math
    2. def softmax(scores, temperature=1.0):
    3. scaled = [s / temperature for s in scores]
    4. m = max(scaled) # subtract max to avoid overflow
    5. exps = [math.exp(s - m) for s in scaled]
    6. total = sum(exps)
    7. return [e / total for e in exps]
    8. def decide(request, state_encoder, option_encoder, score_head):
    9. state_vec = state_encoder(request.state, request.question)
    10. scores = []
    11. for option in request.options:
    12. opt_vec = option_encoder(option)
    13. scores.append(score_head(state_vec, opt_vec))
    14. probs = softmax(scores)
    15. return DecisionResult(option_ids=list(range(len(request.options))),
    16. probabilities=probs)

    Benefits:

    • No parsing. Outputs are numbers; parse failures disappear.
    • Full distribution. All probabilities are available for ranking, thresholds, or margins.
    • Predictable latency. Cost tracks state length and option count, not generated length.

    Limits remain. Scoring cost grows with the number of options. At hundreds of candidates, use chunked scoring, coarse-to-fine ranking, or cached option encodings. Independent scores also cannot express hard dependencies such as “B only after A” unless those constraints are explicit in the state.

    Calibration: Making Scores Actionable

    Correct ranking does not imply reliable magnitudes. A predicted 0.9 may correspond to 0.6 accuracy. Using 0.9 as an auto-execute threshold then over-trusts the model.

    Expected Calibration Error (ECE) bins predicted probabilities, compares average confidence to accuracy in each bin, and takes a sample-weighted sum:

    1. def expected_calibration_error(confidences, correct_flags, n_bins=10):
    2. bins = [[] for _ in range(n_bins)]
    3. for conf, ok in zip(confidences, correct_flags):
    4. idx = min(int(conf * n_bins), n_bins - 1)
    5. bins[idx].append((conf, ok))
    6. total = len(confidences)
    7. ece = 0.0
    8. for bucket in bins:
    9. if not bucket:
    10. continue
    11. avg_conf = sum(c for c, _ in bucket) / len(bucket)
    12. avg_acc = sum(o for _, o in bucket) / len(bucket)
    13. ece += (len(bucket) / total) * abs(avg_acc - avg_conf)
    14. return ece

    Temperature scaling is a common fix. Fit a temperature on a validation set to minimize negative log-likelihood, then apply it at inference. Ranking is unchanged, so top-1 accuracy is preserved; only sharpness of the distribution changes.

    1. def fit_temperature(val_scores_list, val_labels, candidates=None):
    2. if candidates is None:
    3. candidates = [0.5 + 0.05 * i for i in range(60)]
    4. best_t, best_nll = 1.0, float("inf")
    5. for t in candidates:
    6. nll = 0.0
    7. for scores, label in zip(val_scores_list, val_labels):
    8. probs = softmax(scores, temperature=t)
    9. nll -= math.log(max(probs[label], 1e-12))
    10. if nll < best_nll:
    11. best_t, best_nll = t, nll
    12. return best_t

    Tie calibration to product thresholds. If auto-execute uses 0.8, measure accuracy and coverage at that threshold on the calibrated validation set before launch.

    Latency Measurement and Optimization

    Mean latency hides tails. Track medians (P50) and high percentiles (P95, P99). Warm up, keep input mix fixed, and exclude network jitter:

    1. import time
    2. def measure_latency(fn, inputs, warmup=10):
    3. for x in inputs[:warmup]:
    4. fn(x) # warmup so init cost is excluded
    5. samples = []
    6. for x in inputs:
    7. t0 = time.perf_counter()
    8. fn(x)
    9. samples.append((time.perf_counter() - t0) * 1000.0)
    10. samples.sort()
    11. n = len(samples)
    12. p50 = samples[n // 2]
    13. p95 = samples[min(n - 1, int(n * 0.95))]
    14. return p50, p95

    Common optimizations:

    • State cache. Reuse encodings for unchanged history in a session; encode only deltas.
    • Option encoding cache. Precompute vectors when the candidate set is stable.
    • Batching. Merge requests on the server for hardware utilization, with a wait budget so single-request latency does not spike.
    • Quantization. Lower precision on weights and activations to cut memory and compute; recheck calibration.
    • Option chunking. Coarse filter with rules or a small model, then score a shortlist.

    Interactive agents often target tens to hundreds of milliseconds per decision; offline jobs prioritize throughput. Measure on real traffic, not only lab traces.

    Evaluation and Model Choice

    Accuracy alone is not enough. Cover four axes:

    1. Ranking: top-1 accuracy, top-k recall, mean rank with many options.
    2. Calibration: ECE, reliability curves, accuracy vs. coverage at thresholds.
    3. Latency and throughput: P50/P95 and decisions per second per unit of compute.
    4. Scale: how metrics change as option count grows from 2 to hundreds.

    Evaluation sets should include hard cases: near-duplicate options, rare states, and adversarial phrasing. Public leaderboards are a reference only; task definitions and data often differ. Prefer internal datasets and the same hardware and request mix when comparing systems.

    Deployment and Monitoring

    Treat the decision module as a core service:

    • Service API. Stable request/response with request IDs, probability arrays, and model version for trace and replay.
    • Canary rollout. Run a new version on a small traffic share, compare decisions to the previous version, then expand.
    • Logs and audit. Record input summaries, probabilities, executed actions, and human corrections. Redact sensitive fields and follow retention policy.
    • Alerts. Watch latency percentiles, error rate, probability-distribution drift, and calibration. Alert on ECE shifts or unusual option mix.
    • Fast rollback. Keep the last stable model and config ready.

    Distribution drift is easy to miss. Inputs change, the model still looks confident, and accuracy falls. Recalculate calibration on recent labeled samples on a regular cadence.

    Common Pitfalls

    Higher probability is not automatically more reliable. Uncalibrated scores can be systematically high or low.

    Option order is not free. Models can be position-sensitive. Shuffle in train/eval and check stability.

    Average latency is not enough. Tails drive UX and timeouts; track P95 and P99.

    Leaderboard rank is not business impact. Internal metrics on your traffic should decide.

    Single-forward scoring is not universal. Multi-step reasoning, tool use, or long-horizon planning need richer state design or staged pipelines.

    Practical Sequence

    Define the decision problem and candidate-set size. Stand up scoring plus an evaluation set that covers ranking, calibration, and latency. Optimize with caching, batching, or quantization from measured bottlenecks. Ship with canaries and ongoing monitoring so online behavior stays aligned with offline metrics. Keep reproducible data and records at each step so the module stays maintainable.