SentencePieceNormalizer: add_dummy_prefix / escape_whitespaces / remove_extra_whitespaces in a loaded spec/model are silently overwritten

Author: taku910Created Sep 26, 2026Updated Sep 26, 2026
Labelsbugv0.2.3

Description

SentencePieceNormalizer.__init__ always calls _SetProtoField() for add_dummy_prefix, escape_whitespaces and remove_extra_whitespaces after loading. It uses the keyword argument values, which default to False.

So when loading with model_file=, model_proto= or normalizer_spec=, those three flags stored in the model/spec are discarded. The normalizer then behaves differently from the original.

Reproduction

python
import sentencepiece as spm

n = spm.SentencePieceNormalizer(rule_name='nmt_nfkc',
                                add_dummy_prefix=True,
                                remove_extra_whitespaces=True)
spec = n.serialized_normalizer_spec()
print(repr(n.normalize('  ABC  d')))   # ' ABC d'

m = spm.SentencePieceNormalizer(normalizer_spec=spec)
print(repr(m.normalize('  ABC  d')))   # '  ABC  d'  <- flags lost

The same code path runs for model_file= / model_proto=. For a model trained with the default settings (all three flags true), the flags stored in the model are forced to false on load.

Expected behavior

Loading from a serialized spec or model should reproduce the stored normalization behavior. The explicit keyword arguments should override it only when the caller actually passes them.

Cause

python/src/sentencepiece/__init__.py:

python
self._normalizer._SetProtoField('add_dummy_prefix', add_dummy_prefix)
self._normalizer._SetProtoField('escape_whitespaces', escape_whitespaces)
self._normalizer._SetProtoField('remove_extra_whitespaces', remove_extra_whitespaces)

These lines run unconditionally, whichever loading path was used.

Proposed fix

  • Change the defaults of the three keyword arguments to None.
  • model_file / model_proto / normalizer_spec: call _SetProtoField only when the value is not None, so the stored values are kept.
  • rule_name / rule_tsv / norm_map: treat None as False. This keeps the current behavior. Note that the NormalizerSpec proto defaults are true, so a plain "skip if None" would change the output of these paths.
  • Add tests:
    • round-trip through serialized_normalizer_spec()
    • model_file= keeps the flags stored in the model

Compatibility note

This changes the output for anyone who uses model_file= / model_proto= today and depends on the flags being forced to false. It should be mentioned in the release notes.

Related

Found while reviewing #1333, which fixes the missing LoadFromSerializedNormalizerSpec binding (normalizer_spec= did not work at all before that PR).