sentencepiece
하는 일
이 스킬은 언어별 규칙 없이 작동하는 토크나이저 SentencePiece를 설명합니다. 여러 언어를 다뤄야 하는 모델이나 재현 가능한 어휘가 필요한 개발자를 위한 스킬입니다.
사용하는 경우
- ✓여러 언어를 다뤄야 하는 모델을 만들 때.
- ✓텍스트에 중국어, 일본어 또는 한국어 문자가 포함되어 있을 때.
- ✓별도의 사전 분할 단계 없이 원시 텍스트로 토크나이저를 학습하고 싶은 경우.
스킬 링크
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/02-tokenization/sentencepiece/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“여러 언어, 특히 일본어가 포함된 제 텍스트에서 잘 작동하는 토크나이저를 학습해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
이 스킬은 텍스트를 원시 문자로 보고, BPE 또는 Unigram으로 어휘를 학습하고, 작은 모델 파일을 저장합니다. 명령줄과 Python 두 방식으로 학습하는 방법을 보여 줍니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
SentencePiece - Language-Independent Tokenization
Unsupervised tokenizer that works on raw text without language-specific preprocessing.
When to use SentencePiece
Use SentencePiece when:
- Building multilingual models (no language-specific rules)
- Working with CJK languages (Chinese, Japanese, Korean)
- Need reproducible tokenization (deterministic vocabulary)
- Want to train on raw text (no pre-tokenization needed)
- Require lightweight deployment (6MB memory, 50k sentences/sec)
Performance:
- Speed: 50,000 sentences/sec
- Memory: ~6MB for loaded model
- Languages: All (language-independent)
Use alternatives instead:
- HuggingFace Tokenizers: Faster training, more flexibility
- tiktoken: OpenAI models (GPT-3.5/4)
- BERT WordPiece: English-centric tasks
Quick start
Installation
# Python
pip install sentencepiece
# C++ (requires CMake)
git clone https://github.com/google/sentencepiece.git
cd sentencepiece
mkdir build && cd build
cmake .. && make -j $(nproc)
sudo make install
Train model
# Command-line (BPE with 8000 vocab)
spm_train --input=data.txt --model_prefix=m --vocab_size=8000 --model_type=bpe
# Python API
import sentencepiece as spm
spm.SentencePieceTrainer.train(
input='data.txt',
model_prefix='m',
vocab_size=8000,
model_type='bpe'
)
Training time: ~1-2 minutes for 100MB corpus
Encode and decode
import sentencepiece as spm
# Load model
sp = spm.SentencePieceProcessor(model_file='m.model')
# Encode to pieces
pieces = sp.encode('This is a test', out_type=str)
print(pieces) # ['▁This', '▁is', '▁a', '▁test']
# Encode to IDs
ids = sp.encode('This is a test', out_type=int)
print(ids) # [284, 47, 11, 1243]
# Decode
text = sp.decode(ids)
print(text) # "This is a test"
Language-independent design
Whitespace as symbol (▁)
text = "Hello world"
pieces = sp.encode(text, out_type=str)
print(pieces) # ['▁Hello', '▁world']
# Decode preserves spaces
decoded = sp.decode_pieces(pieces)
print(decoded) # "Hello world"
Key principle: Treat text as raw Unicode, whitespace = ▁ (meta symbol)
Tokenization algorithms
BPE (Byte-Pair Encoding)
spm.SentencePieceTrainer.train(
input='data.txt',
model_prefix='bpe_model',
vocab_size=16000,
model_type='bpe'
)
Used by: mBART
Unigram (default)
spm.SentencePieceTrainer.train(
input='data.txt',
model_prefix='unigram_model',
vocab_size=8000,
model_type='unigram'
)
Used by: T5, ALBERT, XLNet
Training configuration
Essential parameters
spm.SentencePieceTrainer.train(
input='corpus.txt',
model_prefix='m',
vocab_size=32000,
model_type='unigram',
character_coverage=0.9995, # 1.0 for CJK
user_defined_symbols=['[SEP]', '[CLS]'],
unk_piece='<unk>',
num_threads=16
)
Character coverage
| Language Type | Coverage | Rationale |
|---|---|---|
| English | 0.9995 | Most common chars |
| CJK (Chinese) | 1.0 | All characters needed |
| Multilingual | 0.9995 | Balance |
Encoding options
Subword regularization
# Sample different tokenizations
for _ in range(3):
pieces = sp.encode('tokenization', out_type=str, enable_sampling=True, alpha=0.1)
print(pieces)
# Output (different each time):
# ['▁token', 'ization']
# ['▁tok', 'en', 'ization']
Use case: Data augmentation for robustness.
Common patterns
T5-style training
spm.SentencePieceTrainer.train(
input='c4_corpus.txt',
model_prefix='t5',
vocab_size=32000,
model_type='unigram',
user_defined_symbols=[f'<extra_id_{i}>' for i in range(100)],
unk_id=2,
eos_id=1,
pad_id=0
)
Integration with transformers
from transformers import T5Tokenizer
# T5 uses SentencePiece internally
tokenizer = T5Tokenizer.from_pretrained('t5-base')
inputs = tokenizer('translate English to French: Hello', return_tensors='pt')
Performance benchmarks
Training speed
| Corpus | BPE (16k) | Unigram (8k) |
|---|---|---|
| 100 MB | 1-2 min | 3-4 min |
| 1 GB | 10-15 min | 30-40 min |
Tokenization speed
- SentencePiece: 50,000 sentences/sec
- HF Tokenizers: 200,000 sentences/sec (4× faster)
Supported models
T5 family: t5-base, t5-large (32k vocab, Unigram)
ALBERT
자주 묻는 질문
얼마나 빠른가요?
초당 약 50,000개의 문장을 처리한다고 이 스킬은 말합니다.
어떤 모델이 이를 사용하나요?
T5, ALBERT, XLNet, mBART를 언급합니다.
학습에 얼마나 걸리나요?
보통 1분에서 2분 정도 걸린다고 이 스킬은 말합니다.
상세 정보
작성자의 원본 설명
Language-independent tokenizer treating text as raw Unicode. Supports BPE and Unigram algorithms. Fast (50k sentences/sec), lightweight (6MB memory), deterministic vocabulary. Used by T5, ALBERT, XLNet, mBART. Train on raw text without pre-tokenization. Use when you need multilingual support, CJK languages, or reproducible tokenization.
인기도
- GitHub 스타
- 14k
- 순위
- #11183
- 라이선스
- MIT
- 업데이트
- 2026. 10. 10.
댓글
- …
이 저장소의 다른 스킬
autoresearch
14k에이전트가 문헌 검토부터 실험과 글쓰기까지 AI 연구 프로젝트 전체를 진행하도록 안내합니다. 테스트와 검토를 반복하는 주기를 따릅니다.
prompt-guard
14k에이전트가 Meta의 작은 분류기로, AI 앱에 도달하기 전에 텍스트에서 프롬프트 인젝션과 탈옥 시도를 검사하도록 돕습니다.
pytorch-fsdp2
14k에이전트가 PyTorch FSDP2를 학습 스크립트에 추가해, 큰 모델을 여러 GPU에 나누고 올바르게 저장하도록 보여 줍니다.
ml-training-recipes
14k에이전트에게 모델 선택, 옵티마이저, 학습률, 손실 급등 해결 등 신경망 학습의 검증된 방법을 알려 줍니다.