SentencePiece Python API

SentencePiece Python API

SentencePiece Python 래퍼는 인코딩·디코딩·학습을 모두 지원해요. SentencePieceProcessor가 토크나이제이션의 주 인터페이스고, 폴리모픽 입력과 배치 처리를 지원해요.

출처: SentencePiece Python Wrapper

SentencePieceProcessor 클래스가 텍스트 토크나이제이션(인코딩)과 디토크나이제이션(디코딩)의 주요 인터페이스예요. 핵심 메서드는 두 가지예요.

  • sp.encode(...) — 입력 텍스트를 토큰 ID, 문자열 조각, 또는 NumPy 배열·Protobuf 메시지 같은 다른 형식으로 분할
  • sp.decode(...) — 토큰 ID나 문자열 조각으로부터 원본 텍스트 재구성

두 메서드 모두 폴리모픽 입력을 받고, 단일·배치 모드 모두 실행할 수 있어요. Protobuf 메시지로 인코딩하는 예시를 볼게요.

proto = sp.encode('This is a test', return_type='proto')
from google.protobuf import text_format
print(text_format.MessageToString(proto))

서브워드 정규화(Subword Regularization)를 위한 샘플링 인코딩도 가능해요.

for _ in range(3):
    print(sp.encode('This is a test', return_type=str, enable_sampling=True, alpha=0.1, nbest_size=-1))

enable_sampling=Truealpha, nbest_size 파라미터를 주면 같은 문장도 실행마다 다른 세그멘테이션을 만들어 내요.

주의할 점이 하나 있어요. 기존 SentencePiece 모델을 메모리에서 수정하는 것(토큰 추가·제거, 토큰 점수 편집)은 공식 지원되지 않아요. SentencePieceProcessor는 엄격히 읽기 전용 추론 엔진으로 설계됐다는 걸 기억해 두세요.

더 알아보기