To align tokens with the original text (e.g., for highlighting), use return_type='offset_mapping'.
Unicode Character Offsets
By default, offsets are Unicode character indices. You can slice the original string using these (start, end) tuples.
Raw Byte Offsets
To get byte-level offsets and pieces, use the return_bytes=True parameter (only valid when return_type='offset_mapping'). This is useful for binary protocols or bypassing Unicode overhead.
Byte Fallback Behavior
If byte_fallback=True is enabled in the model, unknown characters are decomposed into UTF-8 byte tokens. The first $N-1$ byte tokens are assigned a zero-width span (start, start), and the final token is assigned the full span of the character. This ensures slicing remains valid.
import sentencepiece as spm
sp = spm.SentencePieceProcessor(model_file='test/test_model.model')
text = "吾輩は猫である。"
# Encoding with Unicode offsets
enc_res = sp.encode(text, return_type='offset_mapping')
for piece, (start, end) in zip(enc_res['pieces'], enc_res['offsets']):
print(f"Piece: {piece} -> Surface: {text[start:end]}")
# Decoding with raw byte offsets
dec_res_bytes = sp.decode(enc_res['ids'], return_type='offset_mapping', return_bytes=True)
print(dec_res_bytes['text']) # Reconstructed text as bytes