From Sequence Constraints to Token-Level Estimation: Practices in Generation Length Control

    This article explores practical approaches to controlling text generation length in large language models. It explains why traditional length constraints often fail and introduces a method that models remaining length as a value function for token-level estimation. By detailing the construction of training data, integration into the decoding process, and comprehensive evaluation strategies, the article provides developers with an actionable roadmap for implementing budget-aware generation systems that balance output quality, token limits, and computational costs.

    1. Why Generation Length Must Be an Explicit Model State

    In autoregressive language models, text is not generated all at once but progressively expanded by continuously predicting the next token. Each additional token typically requires new decoding computation and reading or updating the key-value (KV) cache in the attention mechanism. Therefore, output length is not just the text volume the user sees, but also a critical variable in computational resource consumption.

    However, the relationship between length and cost is not a simple, fixed linear one. Actual overhead is also influenced by input context length, batching methods, cache management, model architecture, and inference hardware. Nevertheless, when other conditions are similar, controlling the number of output tokens remains a vital means to reduce inference overhead and improve tail latency.

    For tasks requiring multi-step reasoning, length is closely tied to quality. If the budget is too small, the model may fail to complete necessary analysis, verification, and conclusion organization. If the budget is too large, it does not guarantee a better answer and might instead introduce redundant derivation, topic drift, or ineffective self-correction.

    Thus, the true goal of length control is not “write as little as possible,” but rather:

    Within a given budget, allocate necessary computation and expression to the most valuable steps, and complete the answer as naturally as possible.

    This requires the system to not only know the total budget but also judge during generation: how far the current path is from a normal conclusion, whether the remaining budget is sufficient, and when to compress the expression or enter the wrapping-up phase.

    2. Why Traditional Length Control Often Fails

    1. Prompt Constraints Lack Enforcement Guarantees

    “Please keep it under a certain word count” is a semantic instruction. The model can understand it but may not execute it stably. Especially in complex reasoning, response structure, explanation depth, and formatting requirements may compete with length constraints.

    Furthermore, word count and token count are not equivalent. Tokenization varies across languages, punctuation, numbers, and code snippets. Control oriented toward computational budgets should be based on actual token statistics, while control oriented toward user reading experience may require auxiliary metrics like character or paragraph count.

    2. Maximum Output Length Only Ensures the Limit is Not Exceeded

    Setting a generation cap can prevent continued output, but this method does not guarantee content completeness. The model might be truncated mid-formula, inside a code block, or right before the final conclusion.

    Therefore, two goals should be distinguished:

    • Hard budget constraint: The generation process must not exceed the specified token count.
    • Natural completion within budget: The model can arrange content in advance and finish the task before the limit is reached.

    The former can be achieved through external control, while the latter requires the model to possess budget awareness or be actively guided by the decoding strategy.

    3. One-Time Length Prediction Lacks Dynamic Feedback

    Predicting total length before generation begins can assist routing and resource planning, but the subsequent generation path is uncertain. The model might choose a more complex derivation or discover a concise solution early on.

    If prediction occurs only once, the system cannot correct its judgment in time. In contrast, updating the remaining length estimate token by token allows the control strategy to follow changes in the actual generation path.

    4. Sequence-Level Rewards Struggle to Provide Fine-Grained Direction

    Applying penalties to overly long answers during training can alter overall output tendencies, but it does not necessarily tell the model “at which step to reduce expansion.” The same total length loss might correspond to completely different issues: verbosity in the first half, repetitive verification, delayed conclusions, or excessive formatting overhead.

    The value of token-level modeling lies in transforming these issues into observable, updatable states during the decoding process.

    3. Modeling Remaining Length as a Value Function

    In reinforcement learning, the value function is used to estimate how much cumulative reward can be obtained from the current state onwards. For text generation, the current context and generated prefix can be viewed as the state, and the next token as the action.

    If a fixed negative reward is received for every non-terminating token generated, then the future cumulative reward is linked to the remaining generation length.

    Suppose (L) billable tokens are still needed from the current prefix to the end, the reward for each token is (-1), and the discount factor is (0<\gamma<1). The return for a specific continuation path is:

    [
    G(L)=-\sum_{k=0}^{L-1}\gamma^k
    =-\frac{1-\gamma^L}{1-\gamma}
    ]

    The counting convention here must remain consistent: whether the end-of-sequence token counts toward the length, and whether structural tokens are billed, should be explicitly defined during training and evaluation.

    This mapping has two important properties:

    First, it is bounded. As length increases, the return approaches (-1/(1-\gamma)), preventing the target value from increasing infinitely.

    Second, it maintains a monotonic relationship with the length of a deterministic path. The larger the remaining length, the more negative the return; when the remaining length is zero, the return is zero.

    Therefore, the model can learn a value estimator to predict the future negative return corresponding to the current prefix. It does not necessarily output “how many tokens are left” directly; it can also output a proxy signal monotonically associated with length.

    Important Note: Discounted Value Does Not Equal Average Remaining Length

    The actual generation process is stochastic, so the model usually learns:

    [
    V(s)=\mathbb{E}[G(L)\mid s]
    ]

    This quantity depends on the distribution of remaining lengths, not just the average length. Because the discount transformation is nonlinear, you cannot simply invert the predicted value and claim to have obtained the accurate expected remaining length.

    More rigorous approaches include:

    • Using the value output as a relative length signal;
    • Establishing a calibration relationship between value and actual length using validation data;
    • Predicting direct length targets or remaining length distributions simultaneously;
    • Using different calibration strategies for different length intervals.

    When the discount factor approaches 1, the cumulative return in short-to-medium length intervals is closer to the negative length, but overly long paths may still enter a numerical saturation zone. The choice of the discount factor thus needs to be considered alongside the task’s length range.

    4. How to Construct Token-Level Training Data

    Token-level length learning does not necessarily require manual segment-by-segment annotation. As long as the complete generation trajectory is obtained and the termination position is clear, supervision targets can be constructed for multiple prefixes within the trajectory.

    Suppose a continuation contains (T) billable tokens. For the prefix after generating the (t)-th token, the remaining length can be defined as:

    [
    L_t=T-t
    ]

    Calculating the corresponding discounted return based on (L_t) yields the training sample.

    However, there is an easily overlooked issue here: a trajectory provides the length of one actual continuation, not the average length of all possible continuations for that prefix. If you want the model to estimate the expected return under a specific generation strategy, you need to cover enough continuation paths.

    1. Data Should Cover Tasks and Length Distributions

    The training set should not only contain short Q&A but also cover different scenarios like explanations, reasoning, code generation, and structured outputs. Different tasks have different ending patterns, and the judgment of remaining length varies accordingly.

    Additionally, avoid letting extremely short samples dominate the majority of training weights; otherwise, the model may perform well on common short answers but struggle to judge when long reasoning finishes.

    2. Termination Methods Must Be Distinguished

    Normal completion, reaching maximum length, and abnormal interruption should not be treated as the same endpoint.

    If a trajectory is forcibly truncated by the upper limit, the truncation point does not represent the model’s natural completion. Directly using it as a supervision signal for “remaining length is zero” will introduce bias. Such samples can be individually marked, filtered, or handled using training methods capable of processing censored data.

    3. Multiple Samplings to Observe Path Differences

    Generating multiple continuations for the same question allows observing length differences across paths. The same prefix might have both a short solution and a long one, so learning a single deterministic number may not be sufficient to support reliable control.

    In budget-sensitive scenarios, predicting length intervals or quantiles is often more practical than single-point prediction. For example, the system can decide whether to wrap up early based on a more conservative upper-quantile estimate.

    4. Current Policy Determines Value Meaning

    The value function is not a static attribute detached from the generation policy. Once the sampling temperature, termination rules, or length guidance methods change, the remaining length distribution also shifts.

    Especially when the length controller begins to influence the generation path, the estimator originally trained on uncontrolled trajectories may exhibit bias. Therefore, it is necessary to re-evaluate on controlled generation data and supplement training or calibration when needed.

    5. How to Integrate Length Estimation into the Decoding Process

    Having a remaining length estimate does not mean precise control is achieved. A complete system also needs to transform the estimation signal into action selection.

    Assume the target budget is (B), and (t) tokens have been generated; the remaining budget is:

    [
    R_t=B-t
    ]

    The system can compare (R_t) with the calibrated remaining length prediction and adjust the generation strategy accordingly.

    1. When Budget is Sufficient, Retain Normal Generation Path

    If the predicted remaining length is significantly smaller than the available budget, strong intervention is usually unnecessary. Excessively pursuing perfect length adherence might cause content to be unnecessarily expanded or compressed.

    2. When Budget is Tight, Gradually Enter Wrap-Up Mode

    When the estimated length required to complete the task approaches the remaining budget, the model can be guided to:

    • Reduce repetitive explanations;
    • Merge similar arguments;
    • Stop adding non-essential branches;
    • Prioritize core results;
    • Retain necessary verification and formatting closure.

    This control should be gradually strengthened rather than suddenly demanding an end at the last few tokens.

    3. Candidate Re-scoring is a Feasible Approach

    For several candidate tokens or short continuation branches, you can simultaneously examine the language model probability, task relevance, and length budget deviation before selecting the more suitable path.

    However, it must be emphasized: this is a general control design idea and does not imply that any specific method has adopted the exact same implementation. Candidate evaluation also introduces additional computation, which must be weighed alongside the benefits of reduced output.

    4. Hard Limits Remain the Last Line of Defense

    Length value estimation is essentially a statistical prediction and cannot guarantee absolute non-exceedance. Actual deployment should still retain a hard budget and reserve space for necessary concluding content.

    For structured outputs, length control should also be combined with format states, such as whether a code block is closed or an object structure is complete. Relying solely on a value signal indicating “it’s about to end” cannot guarantee valid syntax.

    6. How to Evaluate “Precision” and “Effectiveness”

    Length control cannot only look at whether the final answer is close to the target token count. A model can reach the target length through meaningless padding or become shorter by deleting critical steps, but neither behavior represents a capability improvement.

    It is recommended to establish at least the following evaluation dimensions.

    1. Length Error and Budget Violation

    Calculate absolute error, relative error, over-budget ratio, and hit rate within the allowable error margin. Different budget tiers should be reported separately to avoid overall averages masking issues in long-output scenarios.

    Furthermore, budget tasks and exact-length tasks should be evaluated separately: the former requires not exceeding the limit, while the latter requires approaching the specified length. The optimal behaviors for both are not the same.

    2. Completeness and Correctness

    Check whether the answer provides a clear conclusion, whether necessary conditions are omitted, whether the reasoning is self-consistent, and whether the structured content is parsable.

    For tasks that indeed require longer derivations, a too-short budget may cause all methods to degrade significantly. In such cases, the failure should be attributed to insufficient budget rather than simply viewed as controller failure.

    3. Quality Comparison Under the Same Budget

    Fair comparisons should fix the task set, inputs, token budget, number of samples, stopping rules, and scoring methods.

    If a method uses an additional value model, multi-branch sampling, or candidate re-scoring, its added computation should also be factored into the end-to-end cost. The same output token count does not equal the same inference overhead.

    4. Prediction Calibration and Operating Costs

    Separately check the relationship between predicted remaining length and actual length, and analyze it in buckets by task type and generation phase. Simultaneously record end-to-end latency, decoding throughput, extra memory footprint, and resource consumption per successful task.

    Unverified performance figures should not be directly taken as technical conclusions. Claims that a smaller model outperforms a larger one must also be limited to specific tasks, budgets, and evaluation settings, and cannot be generalized as an overall capability advantage.

    7. How to Validate Scaling

    Token-level value learning can be scaled in three directions: model capacity, training data volume, and number of continuation samples. However, the bottlenecks for improvement differ in each direction.

    Increasing model capacity may enhance the understanding of task structure and termination positions; increasing data volume mainly improves task coverage and generalization; increasing sample count helps observe the length distribution of different paths for the same question.

    However, continuous decline in training loss does not necessarily mean continuous improvement in budget control. Value regression error, length hit rate, task accuracy, and actual cost may exhibit different trends.

    Reasonable experiments should isolate other variables to observe changes in a single dimension and report error margins. Not observing saturation within a limited experimental interval does not imply that infinite scaling will continue to yield benefits.

    8. Developer Implementation Roadmap

    For existing inference systems, length-aware capabilities can be introduced in the following order:

    1. Unify the token counting methodology, clearly defining how internal reasoning, user-visible output, and structural markers count toward the budget.
    2. Establish a baseline, recording quality, length, and cost under prompt constraints and hard truncation.
    3. Collect complete generation trajectories, distinguishing between natural completion and forced interruption.
    4. Train a remaining length predictor; verify prediction effectiveness first, then introduce closed-loop control.
    5. Gradually wrap up when the budget is tight, retaining hard limits and format validation as safety boundaries.
    6. Continuously monitor changes in task distribution and decoding strategies to prevent the estimator from losing calibration.

    Ultimately, the core significance of token-level length modeling is transforming generation length from a post-hoc statistical value into an observable state during decoding. It provides a finer-grained basis for budget allocation, but a truly usable solution still needs to place value learning, dynamic control, task quality, and system cost within the same evaluation framework. Only by completing tasks stably within a limited budget can length control be translated into actual engineering benefits.