SentencePiece 빠른 시작

SentencePiece 빠른 시작

SentencePiece는 pip으로 설치하면 파이썬에서 바로 쓸 수 있어요. 모델을 학습하고, 텍스트를 토큰 id로 인코딩했다가 다시 문자열로 디코딩하는 전체 흐름을 볼게요.

출처: SentencePiece README

먼저 설치해요.

pip install sentencepiece

기본 예시를 볼게요. 모델을 학습하고, 텍스트를 토큰/ID로 인코딩했다가 원래 문자열로 디코딩하는 과정이에요.

import sentencepiece as spm

# No pre-tokenization or language-specific preprocessing required!
spm.SentencePieceTrainer.train(
    input='data/botchan.txt',
    model_prefix='m',
    vocab_size=1000
)

SentencePieceTrainer.train에 입력 파일과 모델 프리픽스, 어휘 크기만 넘기면 학습이 끝나요. 사전 토큰화나 언어별 전처리가 필요 없다는 점이 핵심이고요. 이렇게 학습하면 m.modelm.vocab 파일이 생겨요.

학습된 모델로 인코딩·디코딩을 할 수 있어요.

import sentencepiece as spm
sp = spm.SentencePieceProcessor(model_file='m.model')

text = "I saw a girl with a telescope."
pieces = sp.encode(text, out_type=str)
ids = sp.encode(text, out_type=int)
print(f"Pieces: {pieces}")

sp.encodeout_type=str이면 서브워드 조각(문자열)을, out_type=int면 어휘 ID(정수) 목록을 돌려줘요. 그리고 sp.decode(ids)로 ID를 다시 원래 문자열로 복원할 수 있어요.

SentencePiece의 학습은 raw 문장에서 바로 수행될 만큼 빨라서, 중국어·일본어처럼 단어 사이에 명시적 공백이 없는 언어의 토크나이저·디토크나이저를 만드는 데 특히 유용해요.

더 알아보기