Hugging Face Transformers
3.15.2kata 2 de 3

Tokenization — Text to Token IDs

AutoTokenizer, BPE, WordPiece, max_length

Un tokenizer convierte texto en una secuencia de IDs numéricos que el modelo entiende. Proceso: (1) Preprocesamiento (minúscula, remover puntuación, etc.), (2) Segmentación (split en tokens/subwords), (3) Mapeo a IDs (token → número en vocabulario). Diferentes modelos usan diferentes vocabularios y estrategias: WordPiece (BERT), BPE (GPT-2), SentencePiece (T5). Usar el tokenizer equivocado produce resultados sin sentido.

AutoTokenizer.from_pretrained() descarga el tokenizer correcto automáticamente. Ejemplos: 'unbelievable' se tokeniza como ['un', 'believe', 'able'] en BERT (WordPiece), pero como ['un', 'be', 'lie', 'va', 'ble'] en GPT-2 (BPE). Parámetros críticos: truncation=True (discartar tokens después de max_length), padding='max_length' (rellenar con tokens especiales para tamaño uniforme), return_tensors='pt' (retornar PyTorch tensors).

Sin truncation y padding, el tokenizer retorna listas de longitud variable (ragged tensors). Algunos modelos no pueden manejar esto. Con padding='max_length', todas las secuencias tienen la misma longitud, rellenadas con token especial [PAD]. attention_mask se genera automáticamente: 1 para tokens reales, 0 para padding.

max_length típico es 128 para clasificación, 512 para preguntas/respuestas. Secuencias más largas se truncan a max_length. Para documentos muy largos, divide en chunks y procesa por separado, luego agrega resultados.

structure.txt
# Tokenization: text to token IDs
from transformers import AutoTokenizer
import torch

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')

# Single text
text = 'Hello, my dog is cute'
tokens = tokenizer(text, truncation=True, max_length=128, padding='max_length', return_tensors='pt')

# tokens['input_ids']: shape (1, 128) = [101, 7592, 1010, 2026, 3899, 2003, 6521, 102, 0, 0, ...]
# tokens['attention_mask']: shape (1, 128) = [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, ...]
# 101 = [CLS], 102 = [SEP], 0 = [PAD]

# Batch tokenization
texts = ['Hello world', 'How are you', 'I am fine']
batch_tokens = tokenizer(texts, truncation=True, max_length=128,
                         padding='max_length', return_tensors='pt')
# batch_tokens['input_ids']: shape (3, 128)

# Decode: reverse process (IDs back to text)
decoded = tokenizer.decode(tokens['input_ids'][0])
# Output: '[CLS] hello, my dog is cute [SEP] [PAD] [PAD] ...'

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Tokenization without truncation text = 'a' * 1000 # 1000 caracteres = ~250 tokens tokens = tokenizer(text) # No truncation=True print(len(tokens['input_ids'])) # How long?

  2. 02

    # Padding without max_length texts = ['hi', 'hello world', 'what is your name'] tokens = tokenizer(texts, padding=True, return_tensors='pt') print(tokens['input_ids'].shape) # What's the shape?

  3. 03

    # Token IDs decoded input_ids = [[101, 7592, 1010, 2026, 3899, 2003, 6521, 102]] decoded = tokenizer.decode(input_ids[0]) print(decoded) # What does it say?