Repository navigation
fix(python): keep encode options when pickling SentencePieceProcessor - #1349
Conversation
There was a problem hiding this comment.
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.
| _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]) |
There was a problem hiding this comment.
Subclassing & Maintainability Issues with Hardcoded Options
There are two major issues with the current implementation of __getstate__ and __setstate__:
- Subclassing Crash: Calling
self.__init__()in__setstate__will fail with aTypeErrorif a subclass overrides__init__with required arguments (e.g.,def __init__(self, my_arg, **kwargs)). Bypassing this by callingSentencePieceProcessor.__init__(self)directly ensures the base class is always safely initialized. - Silent Attribute Loss: If a subclass defines custom attributes, they will be silently discarded during pickling because of the hardcoded
_OPTIONSlist. Additionally, any new options added toSentencePieceProcessorin 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.
| _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) |
| 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) |
There was a problem hiding this comment.
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')|
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): Please also add the subclass pickle test suggested in the review. Thanks! |
|
Thanks! Done in 52b1a47: pickling now copies |
SentencePieceProcessor.__setstate__callsself.__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):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_statecovers the old pickle format.pytest test/sentencepiece_test.py: 49 passed, 4 skipped.