πŸ€– AI/ML

Token

Token

The basic unit in which a large language model (LLM) processes text. Split into words, subwords, or characters, and a key concept that determines context window size and API usage cost.

πŸ“– Detailed Explanation

A token is the basic processing unit that a language model uses to understand and generate text. In English, 1 token corresponds to roughly 4 characters or 0.75 words. Because Korean is a morpheme-based language, it uses more tokens than English for the same content. "μ•ˆλ…•ν•˜μ„Έμš”" is split into 2-3 tokens in GPT-4.

There are several algorithms for tokenization. BPE (Byte Pair Encoding) is used in the GPT family and repeatedly merges the most frequent pairs of characters. WordPiece is used in BERT and is similar to BPE, but decides merges based on probability. SentencePiece provides language-independent tokenization and is used in LLaMA and others.

Tokens are a key cost factor in using LLMs. OpenAI GPT-4 Turbo charges $10 per 1M input tokens and $30 per 1M output tokens. Therefore, reducing the number of tokens through prompt optimization can significantly cut costs. In addition, the context window (e.g., 128K tokens for GPT-4) refers to the maximum number of tokens that can be processed at one time.

Token efficiency varies by model and language. English text is more token-efficient than Korean, and code uses more tokens than natural language. Special tokens (e.g., [CLS], [SEP], <|endoftext|>) are used by the model to understand sentence structure. To determine the token count accurately, you should use an official tokenizer such as tiktoken (OpenAI).

πŸ’» Code Example

An example of checking the token count of a text with various tokenizers.

import tiktoken  # OpenAI ν† ν¬λ‚˜μ΄μ €
from transformers import AutoTokenizer  # Hugging Face

# =============================================
# 1. OpenAI tiktoken (GPT-4, GPT-3.5 용)
# =============================================
# pip install tiktoken

# GPT-4 ν† ν¬λ‚˜μ΄μ € λ‘œλ“œ
enc = tiktoken.encoding_for_model("gpt-4")

text_en = "Hello, how are you today?"
text_ko = "μ•ˆλ…•ν•˜μ„Έμš”, 였늘 기뢄이 μ–΄λ– μ„Έμš”?"
code = "def hello(): return 'world'"

# 토큰화
tokens_en = enc.encode(text_en)
tokens_ko = enc.encode(text_ko)
tokens_code = enc.encode(code)

print(f"μ˜μ–΄ ν…μŠ€νŠΈ: {len(tokens_en)} 토큰")
print(f"β†’ 토큰 ID: {tokens_en}")
print(f"β†’ 토큰: {[enc.decode([t]) for t in tokens_en]}")
print()
print(f"ν•œκ΅­μ–΄ ν…μŠ€νŠΈ: {len(tokens_ko)} 토큰")
print(f"β†’ 토큰: {[enc.decode([t]) for t in tokens_ko]}")
print()
print(f"μ½”λ“œ: {len(tokens_code)} 토큰")

# κ²°κ³Ό:
# μ˜μ–΄ ν…μŠ€νŠΈ: 7 토큰
# ν•œκ΅­μ–΄ ν…μŠ€νŠΈ: 14 토큰 (μ˜μ–΄λ³΄λ‹€ 2λ°° 많음)
# μ½”λ“œ: 9 토큰


# =============================================
# 2. Hugging Face Transformers
# =============================================
# pip install transformers

# LLaMA ν† ν¬λ‚˜μ΄μ € (SentencePiece 기반)
tokenizer_llama = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

# GPT-2 ν† ν¬λ‚˜μ΄μ € (BPE 기반)
tokenizer_gpt2 = AutoTokenizer.from_pretrained("gpt2")

# BERT ν† ν¬λ‚˜μ΄μ € (WordPiece 기반)
tokenizer_bert = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")

text = "인곡지λŠ₯이 세상을 λ°”κΎΈκ³  μžˆμŠ΅λ‹ˆλ‹€."

for name, tokenizer in [
    ("LLaMA", tokenizer_llama),
    ("GPT-2", tokenizer_gpt2),
    ("BERT", tokenizer_bert)
]:
    tokens = tokenizer.tokenize(text)
    print(f"{name}: {len(tokens)} 토큰 β†’ {tokens}")


# =============================================
# 3. 토큰 수 기반 λΉ„μš© 계산기
# =============================================
def estimate_cost(text: str, model: str = "gpt-4-turbo") -> dict:
    """OpenAI API λΉ„μš© μΆ”μ •"""
    enc = tiktoken.encoding_for_model(model)
    token_count = len(enc.encode(text))

    # 2025λ…„ 1μ›” κΈ°μ€€ 가격 ($ per 1M tokens)
    prices = {
        "gpt-4-turbo": {"input": 10.0, "output": 30.0},
        "gpt-4o": {"input": 5.0, "output": 15.0},
        "gpt-4o-mini": {"input": 0.15, "output": 0.60},
        "gpt-3.5-turbo": {"input": 0.50, "output": 1.50}
    }

    price = prices.get(model, prices["gpt-4-turbo"])
    input_cost = (token_count / 1_000_000) * price["input"]

    return {
        "model": model,
        "tokens": token_count,
        "input_cost_usd": round(input_cost, 6),
        "per_1k_tokens": round(price["input"] / 1000, 6)
    }

# μ‚¬μš© μ˜ˆμ‹œ
long_text = "λŒ€ν•œλ―Όκ΅­μ€ λ™μ•„μ‹œμ•„μ— μœ„μΉ˜ν•œ κ΅­κ°€λ‘œ..." * 100
result = estimate_cost(long_text, "gpt-4o-mini")
print(f"토큰 수: {result['tokens']}, μ˜ˆμƒ λΉ„μš©: ${result['input_cost_usd']}")

πŸ—£οΈ Say It Like This in Practice

"This prompt has over 8,000 tokens, so the context window is almost full"

β†’ Explains that the prompt is close to the model's maximum token limit

"Korean has low token efficiency, so it costs about twice as much as English"

β†’ Explains the cost increase caused by the tokenization characteristics of Korean

"Check the token count with tiktoken first, then send the request"

β†’ Recommends checking the token count in advance before an API call

⚠️ Common Mistakes & Cautions

Estimating token count from word count

Token != word. Long or rare words are split into multiple tokens. The exact token count must be verified with a tokenizer.

Confusing input/output token prices

In most APIs, output tokens cost 2-3 times more than input tokens. Set max_tokens appropriately to manage costs.

Exceeding the context window

An error occurs if the sum of input + output tokens exceeds the context window. You must reserve space for the output in advance.

Special characters and emoji

Emoji and special characters can take up more tokens than expected. In cost-sensitive services, reduce the use of special characters.

πŸ”— Related Terms

πŸ“š Learn More