Skip to content

fix(feature-extraction): use last attended token for last_token/eos pooling - #1964

Open
definitelynotguru wants to merge 1 commit into
huggingface:mainfrom
definitelynotguru:fix/last-token-pooling
Open

definitelynotguru wants to merge 1 commit into
huggingface:mainfrom
definitelynotguru:fix/last-token-pooling

Conversation

@definitelynotguru

Copy link
Copy Markdown

Why

FeatureExtractionPipeline with pooling: 'last_token' or 'eos' always took result.slice(null, -1). In a right-padded batch, every shorter input therefore got the embedding of a padding token instead of its own last token. Batched embeddings from last-token models (e.g. Qwen3-Embedding) then differed from embedding the same texts one at a time. The reference Python implementation for these models uses the attention mask to find the last real token.

What changed

  • src/pipelines/feature-extraction.js: for last_token/eos, find the last attended position of each row from model_inputs.attention_mask and stack those token embeddings.
  • If no aligned 3D mask is available, or every row already ends on an attended token (unpadded, or left-padded), the old slice(null, -1) path is used. A fully masked row also keeps the old behaviour.
  • JSDoc for pooling notes that eos/last_token select the last attended token.
  • tests/pipelines/test_pipelines_feature_extraction.js: network-free regression for both aliases covering right-padded, unpadded and left-padded rows.

Scope

Only the last_token/eos pooling branch. mean, cls/first_token and none are unchanged.

Blast Radius

Output changes only for right-padded batches using last_token/eos, where the previous result was a padding-token embedding.

Verification

  • New regression before the fix: 2 failed (both aliases returned [90, 91] instead of [3, 4]); after: passes.
  • pnpm test: 30/30 suites passed (2249 passed, 54 skipped); structured-output 20/20.
  • pnpm build and docs-generate (toctree validation) pass; Prettier clean on changed files.

AI assistance was used to prepare this change; I reviewed the diff and test results.

This branch has not been deployed

No deployments
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.

1 participant