Fix off-by-one in completion_tokens count in generate_stream#3843
Open
Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Open
Fix off-by-one in completion_tokens count in generate_stream#3843Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Conversation
The loop `for i in range(max_new_tokens)` appends a token before yielding, but reports `completion_tokens: i` instead of `i + 1`. Since i is 0-indexed and the token is already appended, this undercounts by 1 on every streaming chunk and on the final response. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
In
generate_stream(), the loopfor i in range(max_new_tokens)generates a token and appends it tooutput_idsbefore yielding. However, the usage dict reportscompletion_tokens: iinstead ofi + 1. Sinceiis 0-indexed and the token is already appended by the time the yield executes, this undercounts by exactly 1 on every streaming chunk and on the final response.Example: After the first token is generated (
i=0), the response reportscompletion_tokens: 0instead of1. After N tokens, it reportsN-1instead ofN.Fix: Use
i + 1forcompletion_tokensandtotal_tokensin both the streaming yield (line 282-283) and the final yield (line 303-304).Reference: The vLLM worker (
vllm_worker.py) correctly useslen(output.token_ids)for the same field, confirming the intended semantics.Test plan
completion_tokensmatches the actual number of tokens in the responsetotal_tokens = prompt_tokens + completion_tokensholds🤖 Generated with Claude Code