weightedmean pooling produces NaNs for 512-token float16 inputs
Description
On current main 4a3b5cd, weightedmean pooling returns NaNs for a completely finite, ordinary 512-token float16 input, on both padded and flattened encoder-output paths.
import torch
from sentence_transformers.sentence_transformer.modules import Pooling
pool = Pooling(3, pooling_mode='weightedmean')
features = {
'token_embeddings': torch.ones(1, 512, 3, dtype=torch.float16),
'attention_mask': torch.ones(1, 512, dtype=torch.long),
}
print(pool(features)['sentence_embedding']) # [[nan, nan, nan]], expected [[1,1,1]]
# Setting cu_seq_lens_q=torch.tensor([0,512],dtype=torch.int32)
# on a fresh features dict reproduces the same error in the flattened path.The positional weights sum to 512*513/2=131328, beyond float16's finite range. Both numerator and denominator overflow. Individual weighted products can overflow even for shorter sequences when the final mean is representable. Excluding a prompt that consumes the complete sequence also returns NaN in float16 because the 1e-9 denominator guard underflows to zero.
A focused fix performs weighted products and reductions in float32 for float16/bfloat16 inputs, then restores the output dtype. Existing external token_weights_sum dtype promotion is preserved, consistent with the downstream Dense-head dtype requirement addressed in #3751. Other pooling modes and float32/float64 arithmetic are unchanged.
Reproduced on CPU with PyTorch 2.10 and 2.13. Final regression matrix: 40 cases, pristine base 12 failures/28 passing controls; fixed full pooling file 115 passed/6 existing CUDA-only skips in both environments. Padded/flattened, value/gradient, input immutability, normalizer promotion, and empty prompt checked. Eight padded torch.compile(backend='eager',fullgraph=True) value/gradient cases passed per environment. Live FlashAttention/GPU execution has not been tested.
AI assistance: prepared and validated autonomously with OpenAI Codex on behalf of AHMETHAKANBEZIR1; no independent human review has occurred yet. A focused PR will follow.
Source: huggingface/sentence-transformers