Skip to content

fix(python): keep encode options when pickling SentencePieceProcessor - #1349

Merged
taku910 merged 2 commits into
google:masterfrom
Kayvan-Zahiri:fix-pickle-keeps-options
Oct 17, 2026
Merged

taku910 merged 2 commits into
google:masterfrom
Kayvan-Zahiri:fix-pickle-keeps-options

Conversation

@Kayvan-Zahiri

Copy link
Copy Markdown
Contributor

SentencePieceProcessor.__setstate__ calls self.__init__() with no arguments, so pickling or copying a processor drops the options it was constructed with (out_type, add_bos, add_eos, reverse, emit_unk_piece, enable_sampling, nbest_size, alpha, num_threads):

sp = spm.SentencePieceProcessor(model_file=m, add_bos=True, add_eos=True, out_type=str)
sp.encode('hello world')                             # ['<s>', '▁he', 'll', 'o', '▁world', '</s>']
pickle.loads(pickle.dumps(sp)).encode('hello world')  # [39, 88, 21, 887]
copy.deepcopy(sp).encode('hello world')               # [39, 88, 21, 887]

This happens in practice with PyTorch DataLoader(num_workers>0) under the spawn start method (the default on macOS and Windows). Each worker gets an unpickled tokenizer, so it silently drops BOS/EOS or turns off subword-regularization sampling while the main process keeps them.

__getstate__ now stores the options next to the serialized model. __setstate__ restores them, and still accepts the old state (the bare serialized model), so pickles from earlier versions keep loading.

Tests: test_pickle_keeps_options (pickle and deepcopy) fails on main and passes here. test_unpickle_model_only_state covers the old pickle format. pytest test/sentencepiece_test.py: 49 passed, 4 skipped.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the __getstate__ and __setstate__ methods in SentencePieceProcessor to preserve processor options during pickling and deepcopying, while maintaining backward compatibility with older serialized models. It also adds corresponding unit tests. The review feedback highlights that hardcoding options and calling self.__init__() can lead to subclassing crashes and silent attribute loss. It suggests a more robust approach using self.__dict__ to automatically preserve subclass attributes and avoid maintenance overhead, along with adding a test case to verify subclass compatibility.

Comment thread python/src/sentencepiece/__init__.py Outdated
Comment on lines +699 to +715
_OPTIONS = ('_return_type', '_add_bos', '_add_eos', '_reverse', '_emit_unk_piece',
'_enable_sampling', '_nbest_size', '_alpha', '_num_threads')

def __setstate__(self, serialized_model_proto):
def __getstate__(self):
state = {name: getattr(self, name) for name in self._OPTIONS}
state['model_proto'] = self.serialized_model_proto()
return state

def __setstate__(self, state):
# Pickles written by older versions hold only the serialized model.
if not isinstance(state, dict):
state = {'model_proto': state}
self.__init__()
self.LoadFromSerializedProto(serialized_model_proto)
self.LoadFromSerializedProto(state['model_proto'])
for name in self._OPTIONS:
if name in state:
setattr(self, name, state[name])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Subclassing & Maintainability Issues with Hardcoded Options

There are two major issues with the current implementation of __getstate__ and __setstate__:

  1. Subclassing Crash: Calling self.__init__() in __setstate__ will fail with a TypeError if a subclass overrides __init__ with required arguments (e.g., def __init__(self, my_arg, **kwargs)). Bypassing this by calling SentencePieceProcessor.__init__(self) directly ensures the base class is always safely initialized.
  2. Silent Attribute Loss: If a subclass defines custom attributes, they will be silently discarded during pickling because of the hardcoded _OPTIONS list. Additionally, any new options added to SentencePieceProcessor in the future must be manually added to _OPTIONS, creating a maintenance burden.

Suggested Solution

Instead of maintaining a hardcoded list of options, we can copy self.__dict__ and remove the unpicklable _processor object. This automatically preserves all subclass attributes and configuration options, making the code completely future-proof.

Suggested change
_OPTIONS = ('_return_type', '_add_bos', '_add_eos', '_reverse', '_emit_unk_piece',
'_enable_sampling', '_nbest_size', '_alpha', '_num_threads')
def __setstate__(self, serialized_model_proto):
def __getstate__(self):
state = {name: getattr(self, name) for name in self._OPTIONS}
state['model_proto'] = self.serialized_model_proto()
return state
def __setstate__(self, state):
# Pickles written by older versions hold only the serialized model.
if not isinstance(state, dict):
state = {'model_proto': state}
self.__init__()
self.LoadFromSerializedProto(serialized_model_proto)
self.LoadFromSerializedProto(state['model_proto'])
for name in self._OPTIONS:
if name in state:
setattr(self, name, state[name])
def __getstate__(self):
state = self.__dict__.copy()
state.pop('_processor', None)
state['model_proto'] = self.serialized_model_proto()
return state
def __setstate__(self, state):
# Pickles written by older versions hold only the serialized model.
if not isinstance(state, dict):
state = {'model_proto': state}
SentencePieceProcessor.__init__(self)
self.LoadFromSerializedProto(state.pop('model_proto'))
self.__dict__.update(state)

Comment on lines +1147 to +1156
def test_pickle_keeps_options(self):
sp = spm.SentencePieceProcessor(
model_file=os.path.join(HERE, 'botchan_en_unigram_1000.model'),
add_bos=True,
add_eos=True,
out_type=str,
)
expected = sp.encode('hello world.')
self.assertEqual(pickle.loads(pickle.dumps(sp)).encode('hello world.'), expected)
self.assertEqual(copy.deepcopy(sp).encode('hello world.'), expected)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Add a test case to verify that subclassing SentencePieceProcessor works correctly with pickling and that custom attributes are preserved.

  def test_pickle_keeps_options(self):
    sp = spm.SentencePieceProcessor(
        model_file=os.path.join(HERE, 'botchan_en_unigram_1000.model'),
        add_bos=True,
        add_eos=True,
        out_type=str,
    )
    expected = sp.encode('hello world.')
    self.assertEqual(pickle.loads(pickle.dumps(sp)).encode('hello world.'), expected)
    self.assertEqual(copy.deepcopy(sp).encode('hello world.'), expected)

    # Test subclass pickling and custom attribute preservation
    class MyProcessor(spm.SentencePieceProcessor):
      def __init__(self, my_arg, **kwargs):
        super().__init__(**kwargs)
        self.my_arg = my_arg

    sub_sp = MyProcessor(
        my_arg='custom_value',
        model_file=os.path.join(HERE, 'botchan_en_unigram_1000.model'),
        add_bos=True,
        add_eos=True,
        out_type=str,
    )
    cloned = pickle.loads(pickle.dumps(sub_sp))
    self.assertEqual(cloned.encode('hello world.'), expected)
    self.assertEqual(cloned.my_arg, 'custom_value')

@taku910

taku910 commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator

Thank you for fixing this! Preserving the instance options during pickling/deepcopying is a great improvement for multi-process workflows like PyTorch DataLoader.

As gemini-code-assist pointed out, could we avoid hardcoding _OPTIONS and instead serialize self.dict directly? That will make it easier to maintain if new options are added to init in the future, and it will also work cleanly with subclasses.

Something like this (also copying state before pop so we don't mutate the input dict in-place):

    def __getstate__(self):
        state = self.__dict__.copy()
        state.pop('_processor', None)
        state['model_proto'] = self.serialized_model_proto()
        return state

    def __setstate__(self, state):
        # Pickles written by older versions hold only the serialized model.
        if not isinstance(state, dict):
            state = {'model_proto': state}
        else:
            state = state.copy()
        SentencePieceProcessor.__init__(self)
        self.LoadFromSerializedProto(state.pop('model_proto'))
        self.__dict__.update(state)

Please also add the subclass pickle test suggested in the review. Thanks!

@Kayvan-Zahiri

Copy link
Copy Markdown
Contributor Author

Thanks! Done in 52b1a47: pickling now copies __dict__ (minus _processor) and __setstate__ calls SentencePieceProcessor.__init__ directly, as you suggested. I added the subclass test too. One change from the bot's version: pickle can't find a class defined inside a test method, so the subclass lives at module level in the test file. The test suite passes (49 passed, 4 skipped), and the subclass case fails on the previous commit.

@taku910
taku910 merged commit d6b191e into google:master Oct 17, 2026
6 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.

2 participants