[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,96 +2,153 @@
|
||||
id: wiki-2026-0508-tokenization-subword-processing
|
||||
title: "Tokenization & Subword Processing"
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-TKNP-001]
|
||||
aliases: [Tokenization, BPE, WordPiece, SentencePiece, Tiktoken]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [auto-reinforced, tokenization, bpe, wordpiece, subword-tokenizer, nlp-preprocessing]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [nlp, tokenization, llm, bpe]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-04
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python / Rust
|
||||
framework: tokenizers / tiktoken / sentencepiece
|
||||
---
|
||||
|
||||
# [[Tokenization & Subword Processing|Tokenization & Subword Processing]]
|
||||
# Tokenization & Subword Processing
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "언어의 원자화: 인간의 문장을 모델이 이해할 수 있는 숫자 조각(Token)으로 분해하는 과정이며, 이 분해 방식의 효율성이 모델의 지능, 속도, 그리고 운영 비용을 결정짓는 AI의 첫 번째 관문."
|
||||
## 매 한 줄
|
||||
> **"매 text → discrete unit ID sequence"**. Tokenization 매 LLM input/output pipeline 의 entry/exit point. 매 word-level (OOV 폭발) → character-level (long sequence) → subword (BPE, WordPiece, SentencePiece, Unigram) 의 evolution. 매 modern LLM (GPT, Claude, Llama) 모두 BPE-variant + 100k-256k vocab.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
토큰화(Tokenization)는 텍스트를 모델이 처리할 수 있는 최소 단위인 토큰으로 나누는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **주요 방식**:
|
||||
* **BPE (Byte-Pair Encoding)**: 가장 빈번하게 등장하는 문자 쌍을 반복적으로 병합하여 토큰 사전을 구축합니다. (GPT, Llama 등 표준)
|
||||
* **WordPiece**: BPE와 유사하나, 병합 시 언어 모델의 우도(Likelihood) 증가량을 기준으로 선택합니다. (BERT 계열)
|
||||
* **SentencePiece**: 사전 훈련 없이 텍스트 전반을 바이트 스트림으로 처리하여 다국어 및 미등록어(OOV) 대응에 강점이 있습니다.
|
||||
2. **의미적 단위**:
|
||||
* 현대 토크나이저는 단어 전체가 아닌 '하위 단어(Subword)' 단위를 사용합니다. 이를 통해 "unhappiness"를 "un", "happi", "ness"로 나누어 각 부분의 의미를 조합할 수 있게 합니다.
|
||||
3. **토큰 사전 크기 (Vocab Size)**:
|
||||
* 사전이 너무 작으면 문장이 너무 많은 토큰으로 쪼개져 연산 효율이 떨어지고, 너무 크면 모델의 파라미터가 낭비됩니다. 보통 32k ~ 128k 사이에서 결정됩니다.
|
||||
### 매 algorithms
|
||||
- **BPE (Byte-Pair Encoding)** — 매 most common pair 의 iteratively merge. 매 GPT-2/3/4, Claude, Llama 모두 byte-level BPE.
|
||||
- **WordPiece** — 매 BERT 가 사용. 매 BPE-like but uses log-likelihood for merge.
|
||||
- **SentencePiece (Unigram)** — 매 language-agnostic, no pre-tokenization. 매 T5, mBART, multilingual.
|
||||
- **Tiktoken** — 매 OpenAI 의 fast Rust BPE impl.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **다국어 불균형**: 영어는 단어당 토큰 수가 적지만, 한국어나 다른 언어는 동일한 의미라도 훨씬 많은 토큰으로 쪼개져 비용이 비싸고 성능이 저하될 수 있습니다.
|
||||
* **비결정론적 이슈**: 토크나이저의 사소한 차이가 모델의 산술 연산 능력이나 특수 문자 처리 능력에 큰 영향을 미칠 수 있습니다.
|
||||
### 매 byte-level BPE
|
||||
- 매 raw UTF-8 byte 의 starting alphabet — 매 256 base tokens.
|
||||
- 매 OOV 매 impossible (모든 byte 의 representable).
|
||||
- 매 Korean / CJK 매 multi-byte → multi-token (매 3-4 bytes per char).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
* **상위 개념**: [[Natural Language Processing (NLP)|NLP]], [[Transformer Architecture|Transformer Architecture]]
|
||||
* **하위 시스템**: [[Tokenization Economics|Tokenization Economics]]
|
||||
* **연관 물리 제약**: [[Context Window & Long-Context LLMs|Context Window]], [[KV Cache|KV Cache]]
|
||||
### 매 modern vocab sizes (2026)
|
||||
- GPT-4 / Claude 3.x: ~100k.
|
||||
- GPT-4o: ~200k (cl100k → o200k).
|
||||
- Llama 3: 128k.
|
||||
- Gemini: ~256k.
|
||||
- 매 larger vocab → fewer tokens per text → cheaper, but larger embedding table.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-04*
|
||||
### 매 응용
|
||||
1. LLM input encoding / output decoding.
|
||||
2. Cost / context-budget estimation (매 token = $).
|
||||
3. Multilingual fairness (매 vocab choice 매 non-English speakers 의 hit hard).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### tiktoken (OpenAI)
|
||||
```python
|
||||
import tiktoken
|
||||
enc = tiktoken.encoding_for_model("gpt-4o")
|
||||
ids = enc.encode("Hello, 안녕하세요!")
|
||||
print(ids, len(ids)) # token IDs + count
|
||||
print(enc.decode(ids)) # roundtrip
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Hugging Face tokenizers (BPE)
|
||||
```python
|
||||
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
tok = Tokenizer(models.BPE())
|
||||
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
|
||||
trainer = trainers.BpeTrainer(vocab_size=32000, special_tokens=["<pad>", "<eos>"])
|
||||
tok.train(["corpus.txt"], trainer)
|
||||
tok.save("tokenizer.json")
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### SentencePiece (Unigram)
|
||||
```python
|
||||
import sentencepiece as spm
|
||||
spm.SentencePieceTrainer.train(
|
||||
input="corpus.txt",
|
||||
model_prefix="sp",
|
||||
vocab_size=32000,
|
||||
model_type="unigram",
|
||||
character_coverage=0.9995, # 매 multilingual 의 essential
|
||||
)
|
||||
sp = spm.SentencePieceProcessor(model_file="sp.model")
|
||||
print(sp.encode("hello", out_type=str))
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Anthropic (Claude) token counting
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
client = Anthropic()
|
||||
count = client.messages.count_tokens(
|
||||
model="claude-opus-4-7",
|
||||
messages=[{"role": "user", "content": text}],
|
||||
)
|
||||
print(count.input_tokens)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Special-token handling
|
||||
```python
|
||||
from transformers import AutoTokenizer
|
||||
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
||||
ids = tok.apply_chat_template(
|
||||
[{"role": "user", "content": "hi"}],
|
||||
tokenize=True, add_generation_prompt=True,
|
||||
)
|
||||
# 매 chat template 의 special token 의 자동 insert
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Custom merge inspection
|
||||
```python
|
||||
# 매 어떤 token 으로 split 되는지 의 inspect
|
||||
text = "안녕하세요"
|
||||
ids = enc.encode(text)
|
||||
for i in ids:
|
||||
print(i, repr(enc.decode([i])))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Use existing LLM | Match its tokenizer (tiktoken/HF) |
|
||||
| Train new LLM (English) | Byte-level BPE, 32k-128k vocab |
|
||||
| Multilingual model | SentencePiece Unigram, high coverage |
|
||||
| Code model | Larger vocab (200k+), code-heavy corpus |
|
||||
| Korean / CJK heavy | Larger vocab + ensure char coverage |
|
||||
| Domain-specific (medical) | Extend vocab with domain merges |
|
||||
|
||||
**기본값**: 매 byte-level BPE 32k-128k for English/code, SentencePiece Unigram for multilingual.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[NLP-Foundations]] · [[LLM-Foundations]]
|
||||
- 변형: [[BPE]] · [[WordPiece]] · [[SentencePiece]] · [[Unigram-LM]]
|
||||
- 응용: [[LLM-Inference]] · [[Token-Cost-Optimization]]
|
||||
- Adjacent: [[Embeddings]] · [[Context-Window]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 token cost estimation, custom tokenizer training, multilingual fairness audit, prompt length debug.
|
||||
**언제 X**: 매 trivial LLM API 사용 — 매 implicit, no explicit work needed.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Wrong tokenizer mismatch**: 매 model 과 tokenizer 매 must match — 매 mix 시 garbage output.
|
||||
- **Korean = 1 token assumption**: 매 byte-level BPE 매 한국어 1 char ≈ 2-3 tokens.
|
||||
- **No EOS handling**: 매 generation stop token 의 forget — 매 endless output.
|
||||
- **Whitespace prefix issue**: 매 ` hello` vs `hello` 의 different token — 매 leading-space sensitivity.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Sennrich et al. 2016 BPE, Kudo SentencePiece 2018, OpenAI tiktoken, HF tokenizers).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — BPE/SP/tiktoken modern coverage |
|
||||
|
||||
Reference in New Issue
Block a user