Fix batch embedding averaging for batch_size > 1#3837
Closed
Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Closed
Fix batch embedding averaging for batch_size > 1#3837Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Chessing234 wants to merge 1 commit intolm-sys:mainfrom
Conversation
token_num was computed as a single scalar summing all tokens across the entire batch, then used to divide each per-sequence embedding. This caused incorrect averaging when batch_size > 1, as every sequence was divided by the total token count instead of its own. Change token_num to a per-sequence tensor via attention_mask.sum(dim=1, keepdim=True) so each sequence is divided by its own token count. Fixes lm-sys#3785 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Author
|
Closing in favor of #3839 (duplicate) |
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
model_worker.pywhenbatch_size > 1token_numwas computed as a single scalar (torch.sum(attention_mask).item()) summing tokens across the entire batch, causing each sequence's embedding to be divided by the total token count of all sequences instead of its ownattention_mask.sum(dim=1, keepdim=True)so each sequence is correctly normalized by its own token countFixes #3785
Test plan
ret["token_num"]still returns the correct total token count as a scalar🤖 Generated with Claude Code