Weighted mean pooling changes with left padding

Author: AHMETHAKANBEZIR1Created Oct 1, 2026Updated Oct 1, 2026

Bug

Weighted mean pooling uses positions in the padded batch tensor rather than positions relative to each sequence's first real token. Adding left padding therefore changes the pooled embedding and its gradients, although the real token embeddings are identical. It also disagrees with the flattened pooling path, whose positions are sequence-relative.

Minimal reproduction

python
import torch
from sentence_transformers.sentence_transformer.modules import Pooling

pooling = Pooling(embedding_dimension=1, pooling_mode="weightedmean")
single = pooling({
    "token_embeddings": torch.tensor([[[1.], [3.]]]),
    "attention_mask": torch.tensor([[1, 1]]),
})["sentence_embedding"]
left_padded = pooling({
    "token_embeddings": torch.tensor([[[99.], [1.], [3.]]]),
    "attention_mask": torch.tensor([[0, 1, 1]]),
})["sentence_embedding"]
print(single)       # 2.3333: (1*1 + 2*3) / (1+2)
print(left_padded)  # 2.2000: (2*1 + 3*3) / (2+3)
torch.testing.assert_close(left_padded, single)  # fails

Reproduced on clean main 4a3b5cd6ec718e421f57e824a41ed3fd99595df6, Windows CPU, Python 3.14.6 / Torch 2.13.0 / Transformers 5.14.1. This is a direct pooling reproduction: it does not assume a transformer itself produces padding-invariant hidden states.

Proposed focused fix and validation

Subtract each sequence's leading-padding count from its position weights. Read the original attention mask so excluding a prompt keeps the remaining tokens' original sequence positions. Retain missing/stale mask fallback and output dtype; leave other pooling modes and the flattened implementation unchanged.

34 independent value/gradient cases cover left/right padding, flattened inputs with/without seq_idx, prompt inclusion/exclusion, float32/64/16/bfloat16 and missing/stale masks. Clean base gives 8 failures and 26 passing controls; the fix passes all34. The complete Pooling test module passes 109 tests, 6 CUDA-only skips, both on Torch 2.13 / Transformers 5.14 and Torch 2.10 / Transformers 5.0. Full pre-commit passes. Current issues/PRs were checked for an existing weightedmean left-padding fix; none was found.

Prepared and validated autonomously with OpenAI Codex assistance at the account owner's request; no human code review has occurred yet. The PR will disclose this assistance and record Codex as a commit co-author.

Source: huggingface/sentence-transformers