""" Tokenizer BPE simples treinado do zero para dominio de atendimento/vendas PT-BR. """ import json import os import re from collections import Counter, defaultdict from pathlib import Path class BPETokenizer: """Byte Pair Encoding tokenizer construido do zero.""" SPECIAL_TOKENS = { "": 0, "": 1, "": 2, "": 3, "": 4, } def __init__(self, vocab_size: int = 4096): self.vocab_size = vocab_size self.token_to_id: dict[str, int] = {} self.id_to_token: dict[int, str] = {} self.merges: list[tuple[str, str]] = [] self._compiled_pattern = re.compile( r"""'s|'t|'re|'ve|'m|'ll|'d| ?\w+| ?\d+| ?[^\s\w]+|\s+""" ) def _pre_tokenize(self, text: str) -> list[str]: """Divide o texto em palavras brutas.""" text = text.lower().strip() return self._compiled_pattern.findall(text) def _get_pairs(self, word: tuple[str, ...]) -> set[tuple[str, str]]: """Retorna todos os pares adjacentes em uma palavra.""" pairs = set() for i in range(len(word) - 1): pairs.add((word[i], word[i + 1])) return pairs def train(self, texts: list[str], min_frequency: int = 2): """Treina o tokenizer BPE a partir de uma lista de textos.""" import time t0 = time.time() print("[Tokenizer] Treinando BPE...") # Conta frequencias de palavras (deduplica textos iguais cedo) word_freqs: dict[tuple[str, ...], int] = {} for text in texts: words = self._pre_tokenize(text) for w in words: chars = tuple(w) + ("",) word_freqs[chars] = word_freqs.get(chars, 0) + 1 print(f" Palavras unicas: {len(word_freqs)}") # Inicializa vocabulario com caracteres individuais vocab = set() for word in word_freqs: for ch in word: vocab.add(ch) # Adiciona tokens especiais self.token_to_id = dict(self.SPECIAL_TOKENS) idx = len(self.SPECIAL_TOKENS) for ch in sorted(vocab): if ch not in self.token_to_id: self.token_to_id[ch] = idx idx += 1 num_merges = self.vocab_size - len(self.token_to_id) self.merges = [] # Constroi contagem de pares inicial pair_freqs: dict[tuple[str, str], int] = {} # Mapeia par -> conjunto de palavras que contem esse par pair_to_words: dict[tuple[str, str], set] = defaultdict(set) for word, freq in word_freqs.items(): for i in range(len(word) - 1): pair = (word[i], word[i + 1]) pair_freqs[pair] = pair_freqs.get(pair, 0) + freq pair_to_words[pair].add(word) for step in range(num_merges): if not pair_freqs: break # Encontra melhor par best_pair = max(pair_freqs, key=pair_freqs.get) if pair_freqs[best_pair] < min_frequency: break pair = best_pair self.merges.append(pair) merged_token = pair[0] + pair[1] # Adiciona ao vocabulario if merged_token not in self.token_to_id: self.token_to_id[merged_token] = idx idx += 1 # Atualiza apenas as palavras que contem esse par affected_words = pair_to_words.pop(pair, set()) del pair_freqs[pair] for word in affected_words: freq = word_freqs.pop(word, 0) if freq == 0: continue # Remove contribuicoes dos pares antigos desta palavra for i in range(len(word) - 1): old_pair = (word[i], word[i + 1]) if old_pair in pair_freqs: pair_freqs[old_pair] -= freq if pair_freqs[old_pair] <= 0: del pair_freqs[old_pair] if old_pair in pair_to_words: pair_to_words[old_pair].discard(word) # Aplica merge new_word = [] i = 0 while i < len(word): if i < len(word) - 1 and word[i] == pair[0] and word[i + 1] == pair[1]: new_word.append(merged_token) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) # Adiciona nova palavra word_freqs[new_word] = word_freqs.get(new_word, 0) + freq # Adiciona contribuicoes dos novos pares for i in range(len(new_word) - 1): new_pair = (new_word[i], new_word[i + 1]) pair_freqs[new_pair] = pair_freqs.get(new_pair, 0) + freq pair_to_words[new_pair].add(new_word) if (step + 1) % 500 == 0: elapsed = time.time() - t0 print(f" Merge {step + 1}/{num_merges} | Vocab: {len(self.token_to_id)} | {elapsed:.1f}s") self.id_to_token = {v: k for k, v in self.token_to_id.items()} elapsed = time.time() - t0 print(f"[Tokenizer] Treinamento concluido! Vocab final: {len(self.token_to_id)} tokens ({elapsed:.1f}s)") def encode(self, text: str) -> list[int]: """Codifica texto em lista de IDs de tokens.""" tokens = [] words = self._pre_tokenize(text) for w in words: word = list(w) + [""] # Aplica merges for pair in self.merges: i = 0 while i < len(word) - 1: if word[i] == pair[0] and word[i + 1] == pair[1]: word = word[:i] + [pair[0] + pair[1]] + word[i + 2:] else: i += 1 for token in word: tokens.append(self.token_to_id.get(token, self.SPECIAL_TOKENS[""])) return tokens def decode(self, ids: list[int]) -> str: """Decodifica lista de IDs de volta para texto.""" tokens = [] for i in ids: token = self.id_to_token.get(i, "") if token in self.SPECIAL_TOKENS: continue tokens.append(token) text = "".join(tokens) text = text.replace("", " ") # Limpa espacos multiplos import re text = re.sub(r" +", " ", text).strip() return text def save(self, path: str): """Salva tokenizer em disco.""" os.makedirs(path, exist_ok=True) data = { "vocab_size": self.vocab_size, "token_to_id": self.token_to_id, "merges": [list(m) for m in self.merges], } with open(os.path.join(path, "tokenizer.json"), "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f"[Tokenizer] Salvo em {path}") def load(self, path: str): """Carrega tokenizer do disco.""" with open(os.path.join(path, "tokenizer.json"), "r", encoding="utf-8") as f: data = json.load(f) self.vocab_size = data["vocab_size"] self.token_to_id = data["token_to_id"] self.id_to_token = {int(v): k for k, v in self.token_to_id.items()} self.merges = [tuple(m) for m in data["merges"]] print(f"[Tokenizer] Carregado de {path} | Vocab: {len(self.token_to_id)}") def __len__(self): return len(self.token_to_id)