본문 바로가기
C.W.K.
Stream
Lesson 04 of 06 · published

토크나이저 깊이: BPE, WordPiece, SentencePiece

~32 min · transformers, tokenization

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

방식은 달라도 목적은 같아

tokenizer는 텍스트를 모델이 처리할 정수 ID로 나눠. 지금 자주 만나는 계열은 세 가지야.

  • Byte-Pair Encoding(BPE)은 자주 붙는 바이트나 문자 쌍을 합쳐. GPT·Llama·Qwen·Mistral 계열에서 널리 쓰이며 바이트 기반이라 다양한 Unicode 입력을 다룰 수 있어.
  • WordPiece는 가장 길게 맞는 조각부터 탐욕적으로 고르고 하위 단어를 ##로 표시해. BERT와 DistilBERT가 대표적이야.
  • SentencePiece는 공백까지 포함한 입력을 다루며 단어 경계를 로 나타내. T5·mBART·ALBERT·XLM-R에서 볼 수 있어.

실전에서는 네 가지 동작을 먼저 익혀

가능하면 Rust로 구현된 fast tokenizer를 써. 모델이 Python 구현만 제공하는 경우가 아니라면 기본값이며, 속도 차이가 열 배에 이를 수 있어.

  • tokenizer(text)input_idsattention_mask를 만들어.
  • encode()decode()는 텍스트와 ID 사이를 왕복해.
  • apply_chat_template(messages)는 설정에 든 Jinja 템플릿으로 대화 기록을 모델 형식에 맞춰.
  • 텍스트 목록을 tokenizer에 넘기면 배치로 처리할 수 있어.

Code

토크나이저 동작 inspect·python
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")

text = "Hugging Face is the GitHub of AI."
ids = tok.encode(text, add_special_tokens=False)
toks = tok.convert_ids_to_tokens(ids)

print("ids:  ", ids)
print("tokens:", toks)
print("vocab size:", tok.vocab_size)
print("model_max_length:", tok.model_max_length)
print("special tokens:", tok.special_tokens_map)
chat template 적용 (프롬프트 빌드 정공법)·python
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")

messages = [
    {"role": "system", "content": "You are a concise assistant."},
    {"role": "user", "content": "Explain Hugging Face in one sentence."},
]

prompt = tok.apply_chat_template(
    messages,
    tokenize=False,             # inspect 위해 string 반환
    add_generation_prompt=True, # assistant header 추가
)
print(prompt)

# 같은 콜, 모델용 토큰화:
input_ids = tok.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True)
print("shape:", input_ids.shape)

External links

Exercise

다른 모델 family 셋 골라 (Llama, Mistral, Qwen, T5, BERT). 각각 토크나이저 로드 후 같은 입력 string 에 비교: vocab size, 100단어 영문 단락의 토큰 수, special token, apply_chat_template 결과. 어느 family 가 토크나이저 family 공유, 어느 게 unique 한지 메모.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.