Add offset tracking to Encoding#30
Conversation
|
Thanks for the PR! 🤗 Regarding implementation, it does seem to touch a lot of files (not necessarily a bad thing), but there are some points where it does certainly change API, e.g., |
|
Good point changing pre_tokenize_text's return type is a breaking change for anyone extending PreTokenizer, which I should have flagged upfront. Regarding the Rust implementation: not exactly. I looked at the Rust implementation NormalizedString tracks alignment internally and PreTokenizedString lets pre-tokenizers mutate in place, so offsets flow through without changing return types. Would you prefer I take that approach introducing something closer to NormalizedString to carry alignment internally or |
Hi @xenova |
Hi @nico-martin and @xenova,
Adds
offsets: [number, number][]to theEncodingobject returned bytokenizer.encode(). Each entry is a half-open character span[start, end]in the original (pre-normalization) input string. Special tokens injected by
post-processors (
[CLS],[SEP],</s>, etc.) receive the sentinel[0, 0].Adapted from huggingface/transformers.js#1702.
Changes:
(token, [start, end])tuples through thepipeline instead of bare strings
build_alignment_map(original, normalized)insrc/utils/core.tsmapspositions in the normalizer's output string back to the original input,
handling NFD expansion, NFC compression, and accent/diacritic stripping
offsets: Array<[number, number]>added to theEncodinginterface insrc/static/types.tsand re-exported fromtypes/index.d.tsTokenizer families with dedicated offset tests:
Known limitations:
ByteLevel.trim_offsetsis not yet implemented (marked@todo). Whentrim_offsets: trueis set in a config (RoBERTa, GPT-2 variants), theleading space before a word is currently absorbed into that token's span
start rather than being trimmed to the word boundary.
approximated.
build_alignment_mapcorrectly handles the common Unicodetransformations (NFC recomposition, whitespace normalisation) but may
diverge from the Rust reference implementation for rare character mappings
not expressible as standard Unicode normalization steps.