Skip to content

Don't align wordpieces to the previous token via the preceding space - #429

Merged
honnibal merged 2 commits into
masterfrom
fix/offset-alignment-whitespace
Oct 29, 2026
Merged

honnibal merged 2 commits into
masterfrom
fix/offset-alignment-whitespace

Conversation

@honnibal

Copy link
Copy Markdown
Member

Fixes explosion/spaCy#13730 (the DeBERTa duplicate alignments). Supersedes #426.

Problem

get_span2wp_from_offset_mapping mapped the character after each spaCy token (its trailing space) to that token. With fast tokenizers whose offsets include the preceding space (SentencePiece models like DeBERTa-v3), every wordpiece was therefore also aligned to the previous token, e.g. ▁is (10, 13) aligned to both Copenhagen and is. When pooling, nearly every token got its neighbour's wordpiece mixed in.

Fix

Simply dropping the +1 (as in #426) leaves whitespace-only wordpieces such as GPT-2's Ġ unaligned, which breaks the existing invariant in test_model_wrapper.py that all non-special fast-tokenizer wordpieces are aligned. Instead, trailing whitespace is mapped separately and only used as a fallback for wordpieces that don't overlap any token characters.

Genuine many-to-many overlaps are unchanged, e.g. ▁world covering both a spaCy whitespace token ' ' and world.

Tests

  • Added DeBERTa-style and GPT-2-style cases to test_offset_alignment (the DeBERTa cases fail on master), plus a length check on the result.
  • Full suite passes locally (84 passed).
  • Checked against real microsoft/deberta-v3-xsmall, roberta-base, tiny-random-gpt2 and bert-base-uncased offsets: no spurious duplicates, no unaligned wordpieces. RoBERTa/BERT alignments are unchanged.

The RoBERTa fast/slow differences also reported in spaCy#13730 are not addressed here.

Thanks to @mayuriphad for the diagnosis in #426.

With fast tokenizers whose offsets include the preceding space (e.g.
sentencepiece models like DeBERTa-v3), each wordpiece was also aligned to
the previous spaCy token, because the character after each token was mapped
to that token. Map trailing whitespace separately and only use it as a
fallback for wordpieces that don't overlap any token characters, so
whitespace-only wordpieces (e.g. GPT-2 "Ġ") are still aligned.

Fixes explosion/spaCy#13730. Supersedes #426.

Co-authored-by: Mayuri <mayuriphad656@gmail.com>
@honnibal
honnibal merged commit db0d994 into master Oct 29, 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.

Inconsistent Token Alignment Between Fast and Slow Tokenizers in spacy-transformers

1 participant