Skip to content

Fix mean_pooling NaN for sequences with no attended tokens - #1959

Merged
xenova merged 1 commit into
huggingface:mainfrom
preetamggoudar:fix/mean-pooling-empty-mask
Nov 23, 2026
Merged

xenova merged 1 commit into
huggingface:mainfrom
preetamggoudar:fix/mean-pooling-empty-mask

Conversation

@preetamggoudar

Copy link
Copy Markdown
Contributor

Fixes #1891

Problem

mean_pooling divides by the raw attention-mask sum. When every token in a row is padding, that sum is 0, so a zero numerator produces NaN for every embedding dimension. The NaN then propagates through normalize() and any downstream similarity search.

Fix

Clamp the denominator to 1e-9 (via Math.max(count, 1e-9)), matching the reference sentence-transformers implementation:

torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)

An all-padding row now averages to 0 instead of NaN. Normal rows are unaffected.

Tests

Updated the existing regression test in tests/utils/tensor.test.js that previously documented the NaN behaviour to assert zeros instead.

  • 116/116 tests pass in tests/utils/tensor.test.js
  • Prettier check passes on both changed files

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@xenova xenova left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

@xenova
xenova merged commit 3de6bea into huggingface:main Nov 23, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: mean_pooling() returns NaN for a sequence whose attention mask selects no token

3 participants