Skip to content

Exclude padded token embeddings before CNN convolution - #4323

Merged
tomaarsen merged 2 commits into
huggingface:mainfrom
Afloat16:fix/cnn-mask-padding-before-convolution
Nov 5, 2026
Merged

tomaarsen merged 2 commits into
huggingface:mainfrom
Afloat16:fix/cnn-mask-padding-before-convolution

Conversation

@Afloat16

@Afloat16 Afloat16 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Problem

CNN applies its convolution to padded token embeddings even when an attention mask is supplied. Padding activations produced by an encoder need not be zero, so kernels crossing a sequence boundary mix padding into valid token outputs. The same sentence can receive different pooled embeddings depending on the amount of batch padding.

Change

Zero masked token embeddings before convolution. Use an out-of-place mask so the caller's input tensor remains unchanged. Inputs without an attention mask retain their existing behavior.

Validation

OMP_NUM_THREADS=1 python -m pytest tests/sentence_transformer/modules/test_cnn_padding.py tests/sentence_transformer/modules/test_cnn.py -q — 14 passed on CPU with PyTorch 2.15.0.

The new cases compare a cropped sentence with its left/right padded form through CNN and mean Pooling, using single and multiple kernels and both large finite and NaN padding values. They also check zero padding gradients, unchanged input tensors and the unmasked path. Against the original code, 10 new cases fail and three controls pass. Ruff and git diff --check pass.

@Afloat16
Afloat16 marked this pull request as ready for review November 4, 2026 16:22
@Afloat16

Afloat16 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

The workflows for the current head (a5236332be02) are waiting for approval and have not started. Could a maintainer approve Quality, Unit tests, and Minimum version tests for this fork PR so the changes can be checked?

@tomaarsen

Copy link
Copy Markdown
Member

Hello!

This fixes a reasonable padding issue when using a Transformer followed by a CNN, though that module is not normally used. I've simplified the mask expression and moved the tests into the existing CNN test file. All 14 tests pass, so this looks good to merge.

  • Tom Aarsen

@tomaarsen
tomaarsen merged commit 7da542f into huggingface:main Nov 5, 2026
12 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.

2 participants