{"id":13423707,"url":"https://github.com/google/sentencepiece","last_synced_at":"2025-05-12T18:41:47.421Z","repository":{"id":37251545,"uuid":"84183882","full_name":"google/sentencepiece","owner":"google","description":"Unsupervised text tokenizer for Neural Network-based text generation.","archived":false,"fork":false,"pushed_at":"2025-04-01T15:36:50.000Z","size":25099,"stargazers_count":10835,"open_issues_count":59,"forks_count":1220,"subscribers_count":126,"default_branch":"master","last_synced_at":"2025-05-03T01:45:45.977Z","etag":null,"topics":["natural-language-processing","neural-machine-translation","word-segmentation"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/google.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-03-07T10:03:48.000Z","updated_at":"2025-05-02T07:04:40.000Z","dependencies_parsed_at":"2022-07-10T15:34:57.367Z","dependency_job_id":"1683cd09-98cf-4979-a219-5c707de90aca","html_url":"https://github.com/google/sentencepiece","commit_stats":{"total_commits":751,"total_committers":89,"mean_commits":8.438202247191011,"dds":0.2143808255659121,"last_synced_commit":"d8f741853847553169444afc12c00f4bbff3e9ce"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fsentencepiece","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fsentencepiece/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fsentencepiece/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fsentencepiece/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/google","download_url":"https://codeload.github.com/google/sentencepiece/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252526071,"owners_count":21762426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["natural-language-processing","neural-machine-translation","word-segmentation"],"created_at":"2024-07-31T00:00:40.995Z","updated_at":"2025-05-05T15:48:21.225Z","avatar_url":"https://github.com/google.png","language":"C++","readme":"# SentencePiece\n\n[![Build C++](https://github.com/google/sentencepiece/actions/workflows/cmake.yml/badge.svg)](https://github.com/google/sentencepiece/actions/workflows/cmake.yml)\n[![Build Wheels](https://github.com/google/sentencepiece/actions/workflows/wheel.yml/badge.svg)](https://github.com/google/sentencepiece/actions/workflows/wheel.yml)\n[![GitHub Issues](https://img.shields.io/github/issues/google/sentencepiece.svg)](https://github.com/google/sentencepiece/issues)\n[![PyPI version](https://badge.fury.io/py/sentencepiece.svg)](https://badge.fury.io/py/sentencepiece)\n[![PyPi downloads](https://img.shields.io/pypi/dm/sentencepiece?style=flat-square\u0026logo=pypi\u0026logoColor=white)](https://pypi.org/project/sentencepiece/)\n[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg)](CONTRIBUTING.md)\n[![License](https://img.shields.io/badge/License-Apache%202.0-brightgreen.svg)](https://opensource.org/licenses/Apache-2.0)\n[![SLSA 3](https://slsa.dev/images/gh-badge-level3.svg)](https://slsa.dev)\n\nSentencePiece is an unsupervised text tokenizer and detokenizer mainly for\nNeural Network-based text generation systems where the vocabulary size\nis predetermined prior to the neural model training. SentencePiece implements\n**subword units** (e.g., **byte-pair-encoding (BPE)** [[Sennrich et al.](https://www.aclweb.org/anthology/P16-1162)]) and\n**unigram language model** [[Kudo.](https://arxiv.org/abs/1804.10959)])\nwith the extension of direct training from raw sentences. SentencePiece allows us to make a purely end-to-end system that does not depend on language-specific pre/postprocessing.\n\n**This is not an official Google product.**\n\n## Technical highlights\n- **Purely data driven**: SentencePiece trains tokenization and detokenization\n  models from sentences. Pre-tokenization ([Moses tokenizer](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl)/[MeCab](http://taku910.github.io/mecab/)/[KyTea](http://www.phontron.com/kytea/)) is not always required.\n- **Language independent**: SentencePiece treats the sentences just as sequences of Unicode characters. There is no language-dependent logic.\n- **Multiple subword algorithms**: **BPE**  [[Sennrich et al.](https://www.aclweb.org/anthology/P16-1162)] and **unigram language model** [[Kudo.](https://arxiv.org/abs/1804.10959)] are supported.\n- **Subword regularization**: SentencePiece implements subword sampling for [subword regularization](https://arxiv.org/abs/1804.10959) and [BPE-dropout](https://arxiv.org/abs/1910.13267) which help to improve the robustness and accuracy of NMT models.\n- **Fast and lightweight**: Segmentation speed is around 50k sentences/sec, and memory footprint is around 6MB.\n- **Self-contained**: The same tokenization/detokenization is obtained as long as the same model file is used.\n- **Direct vocabulary id generation**: SentencePiece manages vocabulary to id mapping and can directly generate vocabulary id sequences from raw sentences.\n- **NFKC-based normalization**: SentencePiece performs NFKC-based text normalization.\n\nFor those unfamiliar with SentencePiece as a software/algorithm, one can read [a gentle introduction here](https://medium.com/@jacky2wong/understanding-sentencepiece-under-standing-sentence-piece-ac8da59f6b08).\n\n\n## Comparisons with other implementations\n|Feature|SentencePiece|[subword-nmt](https://github.com/rsennrich/subword-nmt)|[WordPiece](https://arxiv.org/pdf/1609.08144.pdf)|\n|:---|:---:|:---:|:---:|\n|Supported algorithm|BPE, unigram, char, word|BPE|BPE*|\n|OSS?|Yes|Yes|Google internal|\n|Subword regularization|[Yes](#subword-regularization-and-bpe-dropout)|No|No|\n|Python Library (pip)|[Yes](python/README.md)|No|N/A|\n|C++ Library|[Yes](doc/api.md)|No|N/A|\n|Pre-segmentation required?|[No](#whitespace-is-treated-as-a-basic-symbol)|Yes|Yes|\n|Customizable normalization (e.g., NFKC)|[Yes](doc/normalization.md)|No|N/A|\n|Direct id generation|[Yes](#end-to-end-example)|No|N/A|\n\nNote that BPE algorithm used in WordPiece is slightly different from the original BPE.\n\n## Overview\n### What is SentencePiece?\nSentencePiece is a re-implementation of **sub-word units**, an effective way to alleviate the open vocabulary\n  problems in neural machine translation. SentencePiece supports two segmentation algorithms, **byte-pair-encoding (BPE)** [[Sennrich et al.](http://www.aclweb.org/anthology/P16-1162)] and **unigram language model** [[Kudo.](https://arxiv.org/abs/1804.10959)]. Here are the high level differences from other implementations.\n\n#### The number of unique tokens is predetermined\nNeural Machine Translation models typically operate with a fixed\nvocabulary. Unlike most unsupervised word segmentation algorithms, which\nassume an infinite vocabulary, SentencePiece trains the segmentation model such\nthat the final vocabulary size is fixed, e.g., 8k, 16k, or 32k.\n\nNote that SentencePiece specifies the final vocabulary size for training, which is different from\n[subword-nmt](https://github.com/rsennrich/subword-nmt) that uses the number of merge operations.\nThe number of merge operations is a BPE-specific parameter and not applicable to other segmentation algorithms, including unigram, word and character.\n\n#### Trains from raw sentences\nPrevious sub-word implementations assume that the input sentences are pre-tokenized. This constraint was required for efficient training, but makes the preprocessing complicated as we have to run language dependent tokenizers in advance.\nThe implementation of SentencePiece is fast enough to train the model from raw sentences. This is useful for training the tokenizer and detokenizer for Chinese and Japanese where no explicit spaces exist between words.\n\n#### Whitespace is treated as a basic symbol\nThe first step of Natural Language processing is text tokenization. For\nexample, a standard English tokenizer would segment the text \"Hello world.\" into the\nfollowing three tokens.\n\n\u003e [Hello] [World] [.]\n\nOne observation is that the original input and tokenized sequence are **NOT\nreversibly convertible**. For instance, the information that is no space between\n“World” and “.” is dropped from the tokenized sequence, since e.g., `Tokenize(“World.”) == Tokenize(“World .”)`\n\nSentencePiece treats the input text just as a sequence of Unicode characters. Whitespace is also handled as a normal symbol. To handle the whitespace as a basic token explicitly, SentencePiece first escapes the whitespace with a meta symbol \"▁\" (U+2581) as follows.\n\n\u003e Hello▁World.\n\nThen, this text is segmented into small pieces, for example:\n\n\u003e [Hello] [▁Wor] [ld] [.]\n\nSince the whitespace is preserved in the segmented text, we can detokenize the text without any ambiguities.\n\n```\n  detokenized = ''.join(pieces).replace('▁', ' ')\n```\n\nThis feature makes it possible to perform detokenization without relying on language-specific resources.\n\nNote that we cannot apply the same lossless conversions when splitting the\nsentence with standard word segmenters, since they treat the whitespace as a\nspecial symbol. Tokenized sequences do not preserve the necessary information to restore the original sentence.\n\n* (en) Hello world.   → [Hello] [World] [.]   \\(A space between Hello and World\\)\n* (ja) こんにちは世界。  → [こんにちは] [世界] [。] \\(No space between こんにちは and 世界\\)\n\n#### Subword regularization and BPE-dropout\nSubword regularization [[Kudo.](https://arxiv.org/abs/1804.10959)] and BPE-dropout [Provilkov et al](https://arxiv.org/abs/1910.13267) are simple regularization methods\nthat virtually augment training data with on-the-fly subword sampling, which helps to improve the accuracy as well as robustness of NMT models.\n\nTo enable subword regularization, you would like to integrate SentencePiece library\n([C++](doc/api.md#sampling-subword-regularization)/[Python](python/README.md)) into the NMT system to sample one segmentation for each parameter update, which is different from the standard off-line data preparations. Here's the example of [Python library](python/README.md). You can find that 'New York' is segmented differently on each ``SampleEncode (C++)`` or ``encode with enable_sampling=True (Python)`` calls. The details of sampling parameters are found in [sentencepiece_processor.h](src/sentencepiece_processor.h).\n\n```\n\u003e\u003e\u003e import sentencepiece as spm\n\u003e\u003e\u003e s = spm.SentencePieceProcessor(model_file='spm.model')\n\u003e\u003e\u003e for n in range(5):\n...     s.encode('New York', out_type=str, enable_sampling=True, alpha=0.1, nbest_size=-1)\n...\n['▁', 'N', 'e', 'w', '▁York']\n['▁', 'New', '▁York']\n['▁', 'New', '▁Y', 'o', 'r', 'k']\n['▁', 'New', '▁York']\n['▁', 'New', '▁York']\n```\n\n## Installation\n\n### Python module\nSentencePiece provides Python wrapper that supports both SentencePiece training and segmentation.\nYou can install Python binary package of SentencePiece with.\n\n```\npip install sentencepiece\n```\n\nFor more detail, see [Python module](python/README.md)\n\n### Build and install SentencePiece command line tools from C++ source\nThe following tools and libraries are required to build SentencePiece:\n\n* [cmake](https://cmake.org/)\n* C++11 compiler\n* [gperftools](https://github.com/gperftools/gperftools) library (optional, 10-40% performance improvement can be obtained.)\n\nOn Ubuntu, the build tools can be installed with apt-get:\n```\n% sudo apt-get install cmake build-essential pkg-config libgoogle-perftools-dev\n```\n\nThen, you can build and install command line tools as follows.\n```\n% git clone https://github.com/google/sentencepiece.git \n% cd sentencepiece\n% mkdir build\n% cd build\n% cmake ..\n% make -j $(nproc)\n% sudo make install\n% sudo ldconfig -v\n```\nOn OSX/macOS, replace the last command with `sudo update_dyld_shared_cache`\n\n### Build and install using vcpkg\n\nYou can download and install sentencepiece using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:\n\n    git clone https://github.com/Microsoft/vcpkg.git\n    cd vcpkg\n    ./bootstrap-vcpkg.sh\n    ./vcpkg integrate install\n    ./vcpkg install sentencepiece\n\nThe sentencepiece port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.\n\n### Download and install SentencePiece from signed released wheels\n\nYou can download the wheel from the [GitHub releases page](https://github.com/google/sentencepiece/releases/latest).\nWe generate [SLSA3 signatures](slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator) during the release process. To verify a release binary:\n1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation).\n2. Download the provenance file `attestation.intoto.jsonl` from the [GitHub releases page](https://github.com/google/sentencepiece/releases/latest).\n3. Run the verifier:\n```shell\nslsa-verifier -artifact-path \u003cthe-wheel\u003e -provenance attestation.intoto.jsonl -source github.com/google/sentencepiece -tag \u003cthe-tag\u003e\n```\n\npip install wheel_file.whl\n\n## Usage instructions\n### Train SentencePiece Model\n```\n% spm_train --input=\u003cinput\u003e --model_prefix=\u003cmodel_name\u003e --vocab_size=8000 --character_coverage=1.0 --model_type=\u003ctype\u003e\n```\n* `--input`: one-sentence-per-line **raw** corpus file. No need to run\n  tokenizer, normalizer or preprocessor. By default, SentencePiece normalizes\n  the input with Unicode NFKC. You can pass a comma-separated list of files.\n* `--model_prefix`: output model name prefix. `\u003cmodel_name\u003e.model` and `\u003cmodel_name\u003e.vocab` are generated.\n* `--vocab_size`: vocabulary size, e.g., 8000, 16000, or 32000\n* `--character_coverage`: amount of characters covered by the model, good defaults are: `0.9995` for languages with rich character set like Japanese or Chinese and `1.0` for other languages with small character set.\n* `--model_type`: model type. Choose from `unigram` (default), `bpe`, `char`, or `word`. The input sentence must be pretokenized when using `word` type.\n\nUse `--help` flag to display all parameters for training, or see [here](doc/options.md) for an overview.\n\n### Encode raw text into sentence pieces/ids\n```\n% spm_encode --model=\u003cmodel_file\u003e --output_format=piece \u003c input \u003e output\n% spm_encode --model=\u003cmodel_file\u003e --output_format=id \u003c input \u003e output\n```\n\nUse `--extra_options` flag to insert the BOS/EOS markers or reverse the input sequence.\n```\n% spm_encode --extra_options=eos (add \u003c/s\u003e only)\n% spm_encode --extra_options=bos:eos (add \u003cs\u003e and \u003c/s\u003e)\n% spm_encode --extra_options=reverse:bos:eos (reverse input and add \u003cs\u003e and \u003c/s\u003e)\n```\n\nSentencePiece supports nbest segmentation and segmentation sampling with `--output_format=(nbest|sample)_(piece|id)` flags.\n```\n% spm_encode --model=\u003cmodel_file\u003e --output_format=sample_piece --nbest_size=-1 --alpha=0.5 \u003c input \u003e output\n% spm_encode --model=\u003cmodel_file\u003e --output_format=nbest_id --nbest_size=10 \u003c input \u003e output\n```\n\n### Decode sentence pieces/ids into raw text\n```\n% spm_decode --model=\u003cmodel_file\u003e --input_format=piece \u003c input \u003e output\n% spm_decode --model=\u003cmodel_file\u003e --input_format=id \u003c input \u003e output\n```\nUse `--extra_options` flag to decode the text in reverse order.\n```\n% spm_decode --extra_options=reverse \u003c input \u003e output\n```\n\n### End-to-End Example\n```\n% spm_train --input=data/botchan.txt --model_prefix=m --vocab_size=1000\nunigram_model_trainer.cc(494) LOG(INFO) Starts training with :\ninput: \"../data/botchan.txt\"\n... \u003csnip\u003e\nunigram_model_trainer.cc(529) LOG(INFO) EM sub_iter=1 size=1100 obj=10.4973 num_tokens=37630 num_tokens/piece=34.2091\ntrainer_interface.cc(272) LOG(INFO) Saving model: m.model\ntrainer_interface.cc(281) LOG(INFO) Saving vocabs: m.vocab\n\n% echo \"I saw a girl with a telescope.\" | spm_encode --model=m.model\n▁I ▁saw ▁a ▁girl ▁with ▁a ▁ te le s c o pe .\n\n% echo \"I saw a girl with a telescope.\" | spm_encode --model=m.model --output_format=id\n9 459 11 939 44 11 4 142 82 8 28 21 132 6\n\n% echo \"9 459 11 939 44 11 4 142 82 8 28 21 132 6\" | spm_decode --model=m.model --input_format=id\nI saw a girl with a telescope.\n```\nYou can find that the original input sentence is restored from the vocabulary id sequence.\n\n### Export vocabulary list\n```\n% spm_export_vocab --model=\u003cmodel_file\u003e --output=\u003coutput file\u003e\n```\n```\u003coutput file\u003e``` stores a list of vocabulary and emission log probabilities. The vocabulary id corresponds to the line number in this file.\n\n### Redefine special meta tokens\n  By default, SentencePiece uses Unknown (\u0026lt;unk\u0026gt;), BOS (\u0026lt;s\u0026gt;) and EOS (\u0026lt;/s\u0026gt;) tokens which have the ids of 0, 1, and 2 respectively. We can redefine this mapping in the training phase as follows.\n\n```\n% spm_train --bos_id=0 --eos_id=1 --unk_id=5 --input=... --model_prefix=... --character_coverage=...\n```\nWhen setting -1 id e.g., ```bos_id=-1```, this special token is disabled. Note that the unknown id cannot be disabled.  We can define an id for padding (\u0026lt;pad\u0026gt;) as ```--pad_id=3```.  \n\nIf you want to assign another special tokens, please see [Use custom symbols](doc/special_symbols.md).\n\n### Vocabulary restriction\n```spm_encode``` accepts a ```--vocabulary``` and a ```--vocabulary_threshold``` option so that ```spm_encode``` will only produce symbols which also appear in the vocabulary (with at least some frequency). The background of this feature is described in [subword-nmt page](https://github.com/rsennrich/subword-nmt#best-practice-advice-for-byte-pair-encoding-in-nmt).\n\nThe usage is basically the same as that of ```subword-nmt```. Assuming that L1 and L2 are the two languages (source/target languages), train the shared spm model, and get resulting vocabulary for each:\n\n```\n% cat {train_file}.L1 {train_file}.L2 | shuffle \u003e train\n% spm_train --input=train --model_prefix=spm --vocab_size=8000 --character_coverage=0.9995\n% spm_encode --model=spm.model --generate_vocabulary \u003c {train_file}.L1 \u003e {vocab_file}.L1\n% spm_encode --model=spm.model --generate_vocabulary \u003c {train_file}.L2 \u003e {vocab_file}.L2\n```\n\n```shuffle``` command is used just in case because ```spm_train``` loads the first 10M lines of corpus by default.\n\n\nThen segment train/test corpus with ```--vocabulary``` option\n```\n% spm_encode --model=spm.model --vocabulary={vocab_file}.L1 --vocabulary_threshold=50 \u003c {test_file}.L1 \u003e {test_file}.seg.L1\n% spm_encode --model=spm.model --vocabulary={vocab_file}.L2 --vocabulary_threshold=50 \u003c {test_file}.L2 \u003e {test_file}.seg.L2\n```\n\n## Advanced topics\n\n* [SentencePiece Experiments](doc/experiments.md)\n* [SentencePieceProcessor C++ API](doc/api.md)\n* [Use custom text normalization rules](doc/normalization.md)\n* [Use custom symbols](doc/special_symbols.md)\n* [Python Module](python/README.md)\n* [Segmentation and training algorithms in detail]\n\n","funding_links":[],"categories":["C++","A01_文本生成_文本对话","C++ (70)","Natural Language Processing","Implementations \u0026 How to reproduce paper's result","Text Processing and Tokenization","文本数据和NLP","🔹 **SentencePiece Implementations**","Libraries related to the Natural Language Processing","Implementations \u0026 How to reproduce paper's result?","Feature Extraction","Vorverarbeitungstools","Awesome Khmer Language","Frameworks and libraries"],"sub_categories":["其他_文本生成_文本对话","Conversation \u0026 Translation","Packet","Complex, performance-reproducable implementations","[Tools](#tools-1)","Natural Language Processing","Text/NLP","Tokenisierung","7. Misc",":snake: Python"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fsentencepiece","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogle%2Fsentencepiece","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fsentencepiece/lists"}