Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix encode() with an empty batch and out_type='offset_mapping'
The default return_bytes expression short-circuits to the input list itself
rather than to False, so an empty batch passes [] into the bool parameter of
_EncodeAsOffsetMappingBatch and pybind11 raises TypeError.

Every other return_type gives [] for an empty batch.
  • Loading branch information
Kayvan-Zahiri committed Sep 2, 2026
commit 63b19653991be6e8372b4e9edcecfccdb747e9dc
4 changes: 3 additions & 1 deletion python/src/sentencepiece/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,9 @@ def Encode(self,
elif return_type == 'offset_mapping':
if return_bytes is None:
# Default to matching input type
return_bytes_val = isinstance(input, bytes) or (isinstance(input, list) and input and isinstance(input[0], bytes))
return_bytes_val = isinstance(input, bytes) or bool(
isinstance(input, list) and input and isinstance(input[0], bytes)
)
else:
return_bytes_val = return_bytes
args.append(return_bytes_val)
Expand Down
9 changes: 9 additions & 0 deletions python/test/sentencepiece_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1288,6 +1288,15 @@ def test_trainer_with_normalizer(self):
add_dummy_prefix=True,
)

def test_offset_mapping_empty_batch(self):
sp = spm.SentencePieceProcessor()
sp.Load(os.path.join(data_dir, 'botchan_en_bpe_1000.model'))
# Every other return_type gives [] for an empty batch. offset_mapping used to
# leak the empty list into a bool parameter and raise TypeError.
self.assertEqual(sp.encode([], return_type='offset_mapping'), [])
self.assertEqual(sp.encode([], return_type=int), [])
self.assertEqual(sp.encode([], return_type=str), [])

def test_offset_mapping(self):
sp = self.sp_

Expand Down
Loading