Repository navigation
Releases
Releases · google/sentencepiece
v0.2.3
Release Notes v0.2.3
This release introduces SentencePiece Lite, a zero-dependency C++20 runtime, new vocabulary-selection algorithms for training (Auto-character Coverage and Sparse L1 Unigram pruning), a Bazel (Bzlmod) build, a large number of security and robustness fixes found by OSS-Fuzz and community reports, and a cleanup of long-deprecated APIs and flags.
1. SentencePiece Lite (New Zero-Dependency Runtime)
- New
lite/runtime: A compact (~45 KB stripped, < 2k LOC) C++20 tokenizer engine that runs directly on memory-mapped FlatBuffers model binaries (.spm.fb) with no runtime dependency on Protobuf or Abseil (#1330, Commita2cb4d8). See lite/README.md.
2. Training: New Vocabulary Selection Algorithms
- Auto-character Coverage (
--auto_character_coverage): NewTrainerSpec.auto_character_coverageoption for both BPE and Unigram that globally optimizes the allocation between single characters and multi-character subwords within the vocabulary budget, while keeping lossless round-trip via byte fallback (Commitse23ece8,df18339,d34a6ce). See doc/auto_character_coverage.md. - Sparse L1 Unigram pruning (
--use_sparse_pruning): Optional L1-regularized EM vocabulary selection with Post-Lasso debiased refit for the Unigram model, replacing the discrete heuristic pruning (#1295, Commitfd53b5c). Required when--auto_character_coverageis used with Unigram. See doc/sparse_l1_unigram.md. PruneUnreachableSentencePieces: Remove pieces that can never appear in a Viterbi path during Unigram training, and fix the discrete pruning loop order (Commitsb292ce5,59c3b80).- Custom pretokenizer callback: Trainer now accepts a
std::function<std::vector<std::string>(absl::string_view)>pretokenizer, exposed to Python via thepretokenizer=training argument;pretokenization_delimiterand callback are mutually exclusive (#1287, Commitd1b6696). unk_id = -1withbyte_fallback: Training with--unk_id=-1is now allowed when--byte_fallback=true; null-byte pieces are treated as UNUSED when byte fallback is enabled (fixes #1308, Commitc2fbf86).spm_evalmetrics: Added Bytes/Tok, Model PPL, Empirical PPL, and Coverage metrics (Commit01305c9).
3. Python Wrapper
- Pickling:
SentencePieceProcessornow preserves encode options and the full instance dict (including subclasses) when pickled (#1349, Commits4e66c53,52b1a47). - Normalizer fixes:
- Decode / Encode edge cases:
- Buffer protocol & integer inputs: Accept 8/16/32/64-bit signed/unsigned integer buffers with saturation clamping and zero-copy lifetime safety; accept general sequences (including tuples) in decode APIs (Commit
b3717da). - Free-threaded Python: Fix a pretokenizer callback race on free-threaded builds (
cp314t) and GIL-safety issues in_TrainFromMap(Commitsca0f388,ee1d3dd). Free-threaded wheels are now tested on 3.14t / 3.15t. - Python version support: Requires Python >= 3.10; added Python 3.15 classifier and
cibuildwheel4.3.1 (Commitsfa40c16,ab49d75). - AIX: Fixed the Python build on AIX (#1359).
4. Performance Optimizations
- BPE training: Replaced the per-symbol position
btree_setwith a vector and parallelized initial indexing; removed the 65,535-character sentence length limit by replacing 16-bit packed positions with aPositionstruct (Commitsa44ce92,b3717da). - Sentence preprocessing: Parallelized
TrainerInterface::LoadSentencesandSplitSentencesByWhitespace, withRunBatch-based dynamic load balancing for normalization (Commitsa44ce92,d1b6696). - Decode: Avoid intermediate allocations and skip redundant
StrReplaceAllinDecode()(Commita44ce92). - Unigram: Avoid unnecessary allocations in
Lattice::NBest/Lattice::Sample, heap-free score precomputation inBoundedPriorityQueue::Gc, and deduplicated corpus byte counting (Commitee1d3dd). - ParallelEncode / Normalizer: Skip unused
SentencePieceTextallocations inParallelEncodeoverloads and skip alignment bookkeeping when not requested (Commitee1d3dd).
5. Security & Hardening
- OSS-Fuzz findings: Bounded hypothesis allocations, agenda shrink rounds, and periodic timeout checks in
unigram::Lattice::NBestto fix timeouts/OOM; added piece-ID bounds checks inIdToPiece,GetScore,IsControl,IsUnknown,IsUnused,IsByte(fixes #1342, #1344, #1347, Commit2e432ca). - Lattice bounds: Reject invalid positions/lengths in
Lattice::Insert, verify EOS/begin nodes before Viterbi backtrace, and guard against nullprevpointers and cycles (Commitfa40c16). - Empty-piece guards: Guard empty pieces in
PrefixMatcher::PrefixMatchand UnigramPieceToId(#1326, #1325). - Charsmap validation: Validate leaf node offsets and safely slice values in
DecompileCharsMap; fixBuilder::BuildNFC_CFMapand regeneratenfc_cf.tsv(#1329, #1327). - Trainer guards:
RET_CHECKon zero character/word counts, clamp thread pool size to 1024, fix swap-and-pop bug when removing empty normalized sentences, and fix NaN in Gumbel sampling / thread-local RNG re-seeding (Commitsb3717da,70ed5fc,a44ce92). - Lite hardening: Alignment and bounds checks on FlatBuffers models, direct-mapping validation, and endian-swap overflow protection (Commit
b3717da). - General input validation: Additional edge-case hardening across C++, Lite, and Python (Commit
5d21631).
6. Normalization
nmt_nfkc: Normalize U+061C (ARABIC LETTER MARK) to space (#1331).
7. Deprecations & Removals
- Removed deprecated C++ / Python APIs (#1286, Commit
442a7d7):*AsSerializedProto/*AsImmutableProtovariants,ImmutableSentencePieceText,ImmutableNBestSentencePieceText.SampleEncodeAndScore*,CalculateEntropy.SetVocabulary/ResetVocabulary/LoadVocabulary.- Python:
OverrideNormalizerSpec,__getstate_for_pickle__.
- Deprecated
TrainerSpecfields (now marked[deprecated = true]and removed fromspm_trainCLI flags):accept_language,self_test_sample_size,mining_sentence_size,training_sentence_size,train_extremely_large_corpus,enable_differential_privacy,differential_privacy_noise_level,differential_privacy_clipping_threshold(Commitsd29cf00,470b7d5). - Removed
SelfTestDatafromsentencepiece_model.proto(Commit470b7d5). - Removed
contrib/nlcodecfast BPE trainer and other dead code / unused build dependencies (Commitsb6910fd,c91fbef).
8. Build System & Packaging
- Bazel (Bzlmod) support: New
MODULE.bazel/BUILD.bazelcovering the runtime, trainer, CLI binaries, shared libraries, and test suites;darts-clone,libsais, andabseil-cppare taken from the Bazel Central Registry (#1310, #1311, #1312, #1313, closes #1280). - C++20 baseline: Raised the required C++ standard to C++20 across CMake, Bazel, and the Python extension, including MSVC (#1316, Commit
c0232a9). - Dependency upgrades: Protobuf v36.2, Abseil 20260817.0, FlatBuffers 25.12.19, GoogleTest 1.18.0, Google Benchmark 1.10.0; removed legacy
protobuf-liteandbuiltin_pb(#1296, Commit443fedc). - GoogleTest migration: Replaced the custom
testharnesswith GoogleTest / GoogleMock via CMakeFetchContent(Commits87ab362,c5ae4a9). - CMake modernization: Modernized configuration and target export,
protoccross-compilation support (`CMAKE_CROSSCOMPILIN...
v0.2.2
Release Notes v0.2.2
This release contains major updates, including the migration of the Python wrapper to pybind11, native NumPy support, enhanced offset mapping, performance optimizations, security hardening, and internal code modernization.
1. Python Wrapper (pybind11 Migration & Features)
- SWIG to pybind11 Migration: Fully migrated the Python wrapper from SWIG to pybind11, enabling better performance, safer memory management, and cleaner code integration (#1266, Commit
528dc9e). - Native NumPy Support:
- direct encode/decoder from/to numpy object
- Enhanced Offset Mapping:
- Type Stubs (PEP 561): Added inline type stubs (
.pyifiles) and packaged PEP 561 marker to provide auto-completion and static type safety in IDEs (#1258, Commit8b7f97b). - Parallel Encoding API: Introduced
parallel_encodeandThreadPoolAPIs, allowing Python users to tokenize single large documents across multiple CPU cores in parallel (#1254, Commit3c37c39). - Direct Proto Loading: Added support for loading processors and normalizers directly from in-memory Proto instances (Commit
12788ba). - Concurrency Enhancements: Added GIL release during C++ execution to improve multi-threaded Python performance (#1251, Commit
0a044ae). - BOS/EOS Behavior Hardening: Aligned BOS/EOS adding behavior with C++ constraints, raising explicit
ValueErrorinstead of silent failures or crashes (Commit780618a).
2. Performance Optimizations
- BPE Training Optimization: Ported O(log n) lazy priority queue update optimization to BPE trainer to speed up training (Commit
8db9878). - Encode/Decode Optimizations: Decoding/Encoding optimization for integer/string input case by skipping
SentencePieceTextconversion, resulting in ~2x speedup (Commit4b9231b). - Unigram Pruning: Improved unigram pruning using token-normalized frequency calculations (#1135, Commit
1cd0c59).
3. Security & Hardening
- Trie Validation at Load: Added verification of
darts-clonetrie offsets when loading models to prevent segfaults on corrupted or malicious model files (#1224, Commit6b2f05d). - Bounds Checking in Maps: Added bounds checks to piece accessors and validated value offsets in
DecompileCharsMap(#1265, Commit82b7c6d). - Crash Prevention: Replaced internal
CHECKmacros withDCHECKor returned errors to prevent host application crashes on invalid inputs (Commit66b2587). - Null Character Disallowment: Explicitly disallow vocabulary pieces containing null characters (Commit
eb3ba49). - NBest Timeout: Implemented a global timeout for NBest A* search to prevent hangs on pathological inputs (Commit
ba57749).
4. C++ API & Internals Modernization
- Abseil Migration: Extensively migrated from custom utilities to Abseil primitives ([#1270]
- Normalizer Maps: Supported loading normalizer from raw maps in C++ (#1273, Commit
e476e5e).
5. Build & Packaging
- Deprecate Win32 Wheels: Stopped support and distribution of 32-bit Windows wheels (win32) (Commit
24fd00c). - Modernized Python builds: Switched from calling
setup.pydirectly to the standardpypa/buildPEP 517 frontend (#1167, Commitf300c7d). - PEP 639 License: Added PEP 639 license metadata to
pyproject.toml(#1173).
6. Documentation
- API Cheat Sheet: Added comparison tables, zero-copy, and sampling comparison guides.
- Refactored Options: Fully reorganized
options.mdandspecial_symbols.mdwith verified code examples.
v0.2.1
Major changes
- [Python] Supported wheels and builds for Python 3.13 and 3.14(rc1) #1134, #1127, #1121, #1111, #1110, #1104, #1103, #1099, #1091
- [Python] Added an experimental support for free-threading. #1134, #1127, #1110 https://github.com/google/sentencepiece/tree/master/python#free-threading-support
- [Python] Updated the supported Python version to 3.9 or later.
New features
- [ALL]: Added new build mode to prevent the precompiled normalization rules being embedded in *.so and *.a. (
-DSPM_DISABLE_EMBEDDED_DATA=ON). This reduces the runtime size by approximately 1-2 MB. This mode is enabled to build python wheels. The rules are loaded as the data package.
Bug fixes & minor changes
- [ALL]: Security fix to address a heap overflow issue that could occur when using a model containing an invalid precompiled normalization model.
- [Python]: Deprecates the wheel package for Linux i686.
- [Python]: Supported wheel for Windows Arm64. #1114
- [Python]: Fixed the crash issue on batch decoding #1051
- [ALL]: Updated the Unicode normalization rule with the latest ICU/Unicode rules.
- [ALL]: Unused code and build mode cleanup.
v0.2.0
Major changes
N/A
New features
- [ALL] Added SentencePieceNormalizer class in C++/Python. It supports almost the equivalent feature of spm_normalize. Python Sample C++ Sample
- [ALL] Added SentencePieceProcessor::Normalize method in C++/Python Python Sample
C++ Sample - [ALL] Added functionality to override the normalization spec before the processing. Python Sample
Bug fixes & minor changes
- Introduce better support of using external abseil and protobuf #869
- Build universal binary in OSX release package #892
- Add the set_min_log_level function to python to change the loglevel from the python wrapper. #893
- Uses the logsumexp techniques in marginal probabilities of n-best tokenization to avoid underflow.
- Support Python 3.12 #932
- Improves the thread utilization in batch encoding/decoding.
- Fix nasty bug in BPE position encoding.
- Fix bugs in the handling of duplicated bigrams
v0.1.99
Major changes
N/A
New features
N/A
Bug fixes & minor changes
v0.1.98
Major changes
- Python 3.11 support (wheel packages for python 3.11 are available)
- Includes the entire full sources in the source python package to reduce the pip install troubles.
- Improves the algorithm to initialize unigram seed vocabulary. Coverage is improved.
New features
- [ALL] Added the feature to train the model with pre-tokenization boundary constraints. (
--pretokenization_delimiter) flag
Bug fixes & minor changes
- [ALL] Makes the error message more descriptive.
- [ALL] Fixes the crash error when std::random_device failed
- [ALL] Fixes the build error on Raspberry pi around atomic operation
- [ALL] Fixes the minor bugs in nbest enumeration
- [ALL] Fixes the build error when using the external protobuf library.
- [ALL] Fixes the build error on a big-endian machine.
- [Windows] Use /MD build flag instead of /MT.
v0.1.97
Major changes
- Migrated the C++ version from C++11 to C++17.
- Migrated the CI environment from Travis-CI to Github actions
- Started using cibuildtool to build pypi wheel packages
New features
- [ALL] Support differential privacy while training. https://aclanthology.org/2022.findings-acl.171.pdf
- [ALL] Introduced APIs that return the struct of ImmutableSentencePieceText, which encodes string-token, id, and utf-8 byte offsets at once. New API is available both from C++ and Python.
- [ALL] Allow tab ‘\t’ to be included in user defined symbols.
- [ALL] Added NFKD normalization rule. NFKD rule is provided as a TSV file.
- [ALL] Added option to emit unknown symbol instead of raw symbol.
- [Python]: Batch encode/decode requests are performed in native multi-threads.
- [Python]: Supports to pass a custom log stream during training.
- [Python]: Adds module-level version variable:
spm.__version__ - [Python]: Creates wheel package of Mac universal binary.
Bug fixes & minor changes
- Uses the efficient encoding algorithm by default. Removed the functionality to switch the Viterbi tokenization algorithm.
- Make the output of Encode and 1-best from NBestEncode same.
- Use std::string_view as much as possible.
- [Python] Removed pip package for ppc64le and s390x architecture as cibuiltool doesn’t support them.
v0.1.96
Updates
- Improves the performance of unigram training
- Updated the nfkc normalization with the latest ICU module.
- Stop handling zero-width-joiner string as whitespace.
New features
- added new sampling algorithm without replacement.
- added API for new sampling and perplexity calculation.
- added
allow_whitespace_only_piecesmode.
v0.1.95
v0.1.94
Updates
- added SetRandomGeneratorSeed function to set the seed value for random generator. This can allow to make reproducible sampling.
- Validate the range of the vocab id in Python module.
- Change the directory arrangement of python module.
- Added protobuf python module.
Bug fixes
- Support to build python wheel from source package.