Token
Token
The basic unit of text that an LLM processes. A word or subword. Determines the context window size.
Token
The basic unit of text that an LLM processes. A word or subword. Determines the context window size.
A token is the basic unit in which a large language model (LLM) processes text. The model splits text into pieces at the word, subword, or character level and processes them, and each of these pieces is a token. In English, on average 1 token corresponds to about 4 characters (0.75 words), while in Korean, because of morphological characteristics, 1-2 tokens per character are often used.
The history of tokenization goes hand in hand with the development of natural language processing. Early on, whitespace-based word splitting or character-level splitting was used, but with the emergence of BPE (Byte Pair Encoding) in 2016, subword tokenization became the standard. Since then, various tokenizers have been developed, such as WordPiece (BERT), SentencePiece (T5), and Tiktoken (GPT). In 2024-2025, Llama 3's 128K vocabulary and Claude's improved multilingual tokenization are drawing attention.
Tokenization has a direct impact on the performance and cost of LLMs. The larger the vocabulary size, the fewer tokens are needed to represent the same text, which is more efficient, but the embedding table size also grows. GPT-4 uses a vocabulary of about 100K, and Llama 3 improved multilingual efficiency with a 128K vocabulary. The number of tokens affects API cost (billed per input/output token), context window limits, and response speed.
In practice, tokens are central to prompt engineering and cost optimization. When processing long documents, you need to calculate the number of tokens in advance so as not to exceed the context window, and you need to establish a chunking strategy. In addition, you need to understand the roles of special tokens (BOS, EOS, PAD, etc.) to use the model correctly. OpenAI's tiktoken and Hugging Face's tokenizers library are widely used in practice.
Here are examples of using various tokenizers.
# OpenAI tiktoken 토크나이저
# pip install tiktoken
import tiktoken
# GPT-4 토크나이저 로드
enc = tiktoken.encoding_for_model("gpt-4")
# 텍스트 토큰화
text = "안녕하세요, 인공지능 토큰화를 알아봅시다!"
tokens = enc.encode(text)
print(f"원본 텍스트: {text}")
print(f"토큰 수: {len(tokens)}")
print(f"토큰 ID: {tokens}")
# 각 토큰을 텍스트로 디코딩
for token_id in tokens:
token_text = enc.decode([token_id])
print(f" {token_id} -> '{token_text}'")
# 토큰 수 미리 계산 (비용 예측용)
def estimate_tokens(text, model="gpt-4"):
enc = tiktoken.encoding_for_model(model)
return len(enc.encode(text))
long_text = "..." * 100
print(f"\n긴 텍스트 토큰 수: {estimate_tokens(long_text)}")
# 토큰 제한에 맞게 텍스트 자르기
def truncate_to_tokens(text, max_tokens, model="gpt-4"):
enc = tiktoken.encoding_for_model(model)
tokens = enc.encode(text)
if len(tokens) > max_tokens:
tokens = tokens[:max_tokens]
return enc.decode(tokens)
truncated = truncate_to_tokens(text, 10)
print(f"잘린 텍스트: {truncated}")
Here is an example of the Hugging Face Transformers tokenizer.
# Hugging Face 토크나이저
# pip install transformers
from transformers import AutoTokenizer
# 다양한 모델의 토크나이저
models = {
"GPT-2": "gpt2",
"BERT": "bert-base-uncased",
"Llama": "meta-llama/Llama-2-7b-hf",
"Korean": "beomi/kcbert-base"
}
text_en = "Hello, this is a tokenization example."
text_ko = "안녕하세요, 토큰화 예제입니다."
for name, model_id in models.items():
try:
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokens_en = tokenizer.encode(text_en)
tokens_ko = tokenizer.encode(text_ko)
print(f"\n{name} 모델:")
print(f" 영어 토큰 수: {len(tokens_en)}")
print(f" 한국어 토큰 수: {len(tokens_ko)}")
print(f" 어휘 크기: {tokenizer.vocab_size:,}")
except:
print(f"\n{name} 모델: 로드 실패 (인증 필요)")
# 특수 토큰 확인
tokenizer = AutoTokenizer.from_pretrained("gpt2")
print(f"\n특수 토큰:")
print(f" BOS (시작): {tokenizer.bos_token}")
print(f" EOS (종료): {tokenizer.eos_token}")
print(f" PAD (패딩): {tokenizer.pad_token}")
print(f" UNK (미지): {tokenizer.unk_token}")
# 배치 토큰화 (패딩 포함)
texts = ["짧은 문장", "이것은 조금 더 긴 문장입니다."]
encoded = tokenizer(texts, padding=True, return_tensors="pt")
print(f"\n배치 토큰화 결과:")
print(f" input_ids shape: {encoded['input_ids'].shape}")
These are the main LLM API token prices as of January 2025.
| Model | Input (1M tokens) | Output (1M tokens) | Context |
|---|---|---|---|
| GPT-4o | $2.50 | $10.00 | 128K |
| GPT-4o-mini | $0.15 | $0.60 | 128K |
| Claude 3.5 Sonnet | $3.00 | $15.00 | 200K |
| Gemini 1.5 Pro | $1.25 | $5.00 | 2M |
Token efficiency comparison by language (sentences with the same meaning):
| Language | GPT-4 Tokens | Llama 3 Tokens | Efficiency |
|---|---|---|---|
| English | ~15 | ~12 | Most efficient |
| Korean | ~35 | ~25 | 2-3x that of English |
| Japanese | ~40 | ~30 | 2-3x that of English |
| Chinese | ~25 | ~20 | 1.5-2x that of English |
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Tokens and words are different. "tokenization" is 1 word but can be 3 tokens, and the Korean "안녕하세요" is 1 word but is split into 3-5 tokens. Always check the actual token count with a tokenizer.
GPT, Claude, and Llama each use a different tokenizer. The same text has a different token count in each model, so you need to calculate using the tokenizer of the model you are using to be accurate.
Calculate the token count in advance with tiktoken (OpenAI) or the transformers library. Keep usage within 80% of the context window, and chunk long documents by semantic units before processing them.