Text Generation
PyTorch
English
poetry
custom-architecture
from-scratch
rope
swiglu
poemformer / tokenizer.py
rororova's picture
Upload 7 files
9ed8088 verified
Raw History Blame Contribute Delete
5.37 kB
"""
PoemTokenizer β€” sentencepiece BPE wrapper that also produces the
structural inputs PoemFormer expects: line_ids, stanza_ids, line_pos.
Usage
-----
tok = PoemTokenizer()
tok.train(texts, vocab_size=8000, model_prefix="poem_tok")
enc = tok.encode("Shall I compare thee to a summer's day?\nThou art more lovely")
# enc.input_ids, enc.line_ids, enc.stanza_ids, enc.line_pos
"""
from __future__ import annotations
import os
import io
from dataclasses import dataclass
from typing import List, Optional
import sentencepiece as spm
import torch
@dataclass
class PoemEncoding:
input_ids: torch.Tensor # (T,)
line_ids: torch.Tensor # (T,)
stanza_ids: torch.Tensor # (T,)
line_pos: torch.Tensor # (T,) β€” position within current line
def to(self, device):
return PoemEncoding(
self.input_ids.to(device),
self.line_ids.to(device),
self.stanza_ids.to(device),
self.line_pos.to(device),
)
class PoemTokenizer:
NEWLINE_PIECE = "▁\n" # sentencepiece encodes \n with leading ▁
def __init__(self, model_path: Optional[str] = None):
self.sp: Optional[spm.SentencePieceProcessor] = None
self._newline_id: Optional[int] = None
if model_path and os.path.exists(model_path):
self.load(model_path)
# ── Training ─────────────────────────────────────────────────────────────
def train(
self,
texts: List[str],
vocab_size: int = 8_000,
model_prefix: str = "poem_tok",
character_coverage: float = 0.9995,
) -> None:
"""Train BPE tokenizer on a list of poem strings."""
corpus = io.StringIO("\n\n".join(texts))
spm.SentencePieceTrainer.train(
sentence_iterator=iter(corpus.getvalue().splitlines()),
model_prefix=model_prefix,
vocab_size=vocab_size,
model_type="bpe",
character_coverage=character_coverage,
pad_id=0, unk_id=1, bos_id=2, eos_id=3,
user_defined_symbols=["\n"], # keep newline as atomic token
)
self.load(f"{model_prefix}.model")
def load(self, model_path: str) -> None:
self.sp = spm.SentencePieceProcessor()
self.sp.Load(model_path)
# Find the id for the newline token
self._newline_id = self.sp.PieceToId("\n")
if self._newline_id == self.sp.unk_id():
# Fallback: look for the piece that decodes to \n
for i in range(self.sp.GetPieceSize()):
if self.sp.IdToPiece(i) in ("\n", "▁\n", "<0x0A>"):
self._newline_id = i
break
# ── Encoding ─────────────────────────────────────────────────────────────
def encode(
self,
text: str,
max_length: Optional[int] = None,
add_bos: bool = True,
add_eos: bool = True,
) -> PoemEncoding:
assert self.sp is not None, "call train() or load() first"
ids = self.sp.EncodeAsIds(text)
if add_bos:
ids = [self.sp.bos_id()] + ids
if add_eos:
ids = ids + [self.sp.eos_id()]
if max_length:
ids = ids[:max_length]
T = len(ids)
line_ids = [0] * T
stanza_ids = [0] * T
line_pos = [0] * T
cur_line = 0
cur_stanza = 0
cur_lp = 0
prev_was_nl = False
for i, tok in enumerate(ids):
line_ids[i] = min(cur_line, 63) # clamp to max_lines
stanza_ids[i] = min(cur_stanza, 15) # clamp to max_stanzas
line_pos[i] = min(cur_lp, 23) # clamp to max_line_len
if tok == self._newline_id:
if prev_was_nl:
# Double newline β†’ stanza break
cur_stanza += 1
cur_line += 1
cur_lp = 0
prev_was_nl = True
else:
cur_lp += 1
prev_was_nl = False
return PoemEncoding(
input_ids = torch.tensor(ids, dtype=torch.long),
line_ids = torch.tensor(line_ids, dtype=torch.long),
stanza_ids = torch.tensor(stanza_ids, dtype=torch.long),
line_pos = torch.tensor(line_pos, dtype=torch.long),
)
def decode(self, ids: List[int]) -> str:
assert self.sp is not None
return self.sp.DecodeIds(ids)
# ── Properties ───────────────────────────────────────────────────────────
@property
def vocab_size(self) -> int:
assert self.sp is not None
return self.sp.GetPieceSize()
@property
def pad_id(self) -> int:
return self.sp.pad_id()
@property
def bos_id(self) -> int:
return self.sp.bos_id()
@property
def eos_id(self) -> int:
return self.sp.eos_id()
@property
def newline_id(self) -> int:
return self._newline_id