Review: sequences as data and the autoregressive factorization
Study sequences, tokenization, word frequencies, autoregressive probabilities and sequence task shapes.
After this lesson you can
- Tokenize text into words or characters and build a vocabulary from training data.
- Interpret Zipf and Heaps patterns and the limitations of bag-of-words.
- Factor sequence probabilities and distinguish perplexity units.
- Compare sequence tasks and their supervision and alignment.
Before you start
Order changes the question
“The dog bit the man” and “the man bit the dog” contain the same words with the same counts, but describe different situations. Their difference is order. The same applies to a line of code, a price series or a recording: permuting elements can change the program, trajectory or sound. A sequence is an ordered list ; what each represents and the information available at each step depend on the task.
Working with text requires a preliminary choice: converting the string into units the model can index. In this lesson we use words and characters, build vocabularies and establish the probability rule connecting the module. Subwords are studied later; there is no need to attribute a universal solution to them before defining what information each representation retains.
From string to tokens
Word or character tokenization transforms text into a sequence of units. A simple word tokenizer can separate letters, numbers and punctuation with regular expressions; another can traverse the string character by character, including spaces and line breaks. No regular expression is a universal definition of a word. Explain whether you separate apostrophes, hyphens and punctuation and what you do with spaces: if discarded, joining tokens will not necessarily reconstruct the original string. Jurafsky and Martin present these choices as part of the representation, not an inconsequential detail.
What you call a character also matters. In Python, iterating a string traverses Unicode code points, not necessarily visible graphemes or UTF-8 bytes. “á” can be represented by one code point or “a” followed by a combining accent. NFC can convert both sequences to a common canonical form, but does not make every visually similar string equivalent. Lowercasing also discards information. Apply the same normalization in training and evaluation and distinguish reconstructing normalized text from recovering the original. Normalization and segmentation are defined in Python’s Unicode documentation and Unicode UAX 29.
A vocabulary with special tokens assigns an index to each admitted unit. It is common to reserve <unk> for unknown units, <bos> for the beginning, <eos> for the end and <pad> to pad examples of different lengths. These are distinct roles: <pad> is not sequence text and is usually excluded from loss; <eos> represents a decision to stop. Identifiers must be distinct and literal text must not be confused with markers.
Build the vocabulary only from training data. If you remove words below a frequency threshold, measure the out-of-vocabulary word rate on new data as unknown occurrences divided by word occurrences, stating whether punctuation is included and excluding markers. With zero words the ratio is undefined. An unknown character replaced by <unk> is not magically recovered: if two different characters share that index, they produce the same encoding. To guarantee reversibility, restrict the alphabet to known characters or add an unambiguous escape, such as a byte representation. Bytes also require specifying the encoding.
Frequencies with a long tail
A bag of counts can provide a first look at the whole dataset. Order words from most to least frequent and call their rank . The first Zipf and Heaps regularity is approximately over a range of ranks. A descending line on logarithmic axes suggests a scaling relationship; its slope is if the fit is appropriate. But chosen range, tokenization, ties and words appearing once change the graph. A linear log-log fit and high do not prove a power law or identify its cause, as Clauset and colleagues caution.
Comparison with random text is a cautionary test. Li showed that a source writing random letters and spaces can produce a Zipf-like rank-frequency distribution. This does not mean language is random or the processes share semantics; it means that graph alone does not establish semantics. Code and logs also depend on their generation and tokenization rules. Experimental figures must come from the texts or reproducible generator.
The second regularity describes the appearance of types while traversing text: if is the number of tokens and the distinct types observed in that prefix, sometimes . The slope on a log-log graph estimates for the chosen interval. Prefixes of the same text are nested and are not independent observations. Heaps’ Law and Heaps functions distinguishes growth within a work from comparison across works and shows deviations from a simple power. Do not force an exact relationship between and for every finite sample.
The long tail explains a practical difficulty: many types have few examples and some may appear in test but not train. The empirical frequency of an unseen event is zero, though that does not prove it impossible. Nor does it follow that new types will always appear: with a finite vocabulary, is bounded. The next lessons study how to reserve probability for rarely observed events.
The bag that loses order
A bag of words transforms a sequence into a vector whose component counts token . The sum is order-independent, so any permutation produces the same vector. No function of that vector can distinguish the two opening sentences on its own: both enter with the same representation.
Ordered bigrams count consecutive pairs and distinguish those sentences. They recover local information but do not necessarily determine the entire sequence: “a b a c a” and “a c a b a” each contain bigrams a b, b a, a c and c a once. If start and end markers are included, both examples still begin and end with a. A vocabulary of units allows up to distinct pairs before restrictions, although a sparse matrix stores only observed ones. More context increases discriminating ability and also worsens count sparsity.
A sequence as a product
For fixed length , autoregressive factorization is the chain rule, not an independence assumption:
Each conditional may depend on the entire prefix. The equality is exact for any joint distribution: it follows by repeatedly applying the product rule. On zero-probability prefixes, conditionals are not determined by the usual ratio; they can be defined arbitrarily as normalized distributions without changing the joint. Models differ in how they approximate factors and which context they use, not in the mathematical identity.
To model a variable-length string and its termination, add the factor to its token factors. Here are content tokens, <eos> stops generation when emitted and <bos> and <pad> are not possible content outputs. Including <eos> in the alphabet does not guarantee termination: total mass on finite strings is one if and only if the probability of continuing without stopping tends to zero. A sufficient condition is that some exists such that, for every possible prefix, (where “prefijo” means prefix). After continuation decisions, the probability of continuing is at most , which tends to zero. The condition is sufficient, not necessary.
The surprisal of an observed token is bits. Whole-sequence surprisal is the sum of its factors, including <eos> when the protocol scores it. Zero probability gives infinite surprisal. Cross-entropy averages that loss over selected events, and token perplexity is the exponential of mean loss expressed in nats.
For text with code points, scored tokens and natural log-probability , the units are
Word and character perplexity have different denominators and cannot be directly compared. Dividing by the same number of characters or bytes can provide a common unit only if models score a reversible representation of the same text, with the same normalization and compatible space and ending conventions. If a word model discards spaces or maps multiple distinct words to <unk>, it scores another representation: dividing its loss by original characters does not add missing bits. Two valid models also need not assign the same probability to text. When multiple token sequences decode to the same string, string probability requires summing their probabilities; scoring only the canonical tokenization does not always yield that sum. See Should you marginalize over possible tokenizations?.
Choosing input, output and alignment
The taxonomy of sequence tasks asks what objects you observe and where supervision lies. Classifying review sentiment transforms a sequence into one label. Part-of-speech tagging usually assigns a label to each input token, with a given alignment. Generating an image-conditioned description produces a sequence from a non-sequential input; generating music can depend on previous notes and an initial condition.
Translation and speech recognition transform one sequence into another and can have different lengths. In speech we do not know beforehand which acoustic frame corresponds to each symbol. CTC addresses this by summing probabilities over compatible monotonic alignments instead of assuming one observed label per frame; it is not the only possible architecture or loss. Hannun’s CTC explanation shows why alignment matters.
Input and output shape guide architecture but do not determine it alone. You can turn an aligned task into a global prediction, add context or choose a structured loss; each decision changes what is learned and how it is evaluated.
From raw text to indices
The example works offline with two short excerpts, one from chapter I and one from chapter II of part one of Don Quixote, Project Gutenberg edition 2000, prepared by an anonymous volunteer and Joaquín Cuenca Abela. The book is identified as public domain in the United States; check Project Gutenberg terms and applicable law before redistributing it. The excerpts only check the pipeline: they are not complete chapters and their fits do not justify conclusions about Zipf or Heaps.
To analyze full chapters in the browser, obtain the edition from its source and copy part one’s chapter I into TRAIN and chapter II into TEST, retaining Python triple quotes. The cell builds vocabulary only from TRAIN and counts unknown words in TEST; it needs no report files. The next local cell reproduces the figure with complete chapters and records provenance, boundaries and hashes.
"""Palabras, caracteres, OOV, Zipf y Heaps en Pyodide.
Fragmentos breves, no capítulos completos: Miguel de Cervantes, Don Quijote,
primera parte, capítulos I y II, edición Project Gutenberg 2000, preparada por
un voluntario anónimo y Joaquín Cuenca Abela:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha indica dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html
y la ley local antes de redistribuir. Esta muestra no estima leyes generales.
Para el análisis completo sustituye TRAIN y TEST por los capítulos I y II.
"""
import re
import unicodedata
from collections import Counter
import numpy as np
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SPECIALS = ('<unk>', '<bos>', '<eos>', '<pad>')
PATTERN = re.compile(r"[^\W\d_]+(?:['’][^\W\d_]+)*|[^\w\s]", re.UNICODE)
def normalize(text):
return unicodedata.normalize('NFC', text).lower()
def tokenize(text):
# Letras con apóstrofo interno o signo; no conserva espacios ni números.
return PATTERN.findall(normalize(text))
def is_word(token):
return bool(token) and token[0].isalpha()
class Vocabulary:
def __init__(self, tokens, min_frequency=1):
if min_frequency < 1:
raise ValueError('La frecuencia mínima debe ser positiva')
counts = Counter(tokens)
if set(counts) & set(SPECIALS):
raise ValueError('Colisión con un token especial')
ordered = sorted((t for t, n in counts.items() if n >= min_frequency),
key=lambda t: (-counts[t], t))
self.tokens = list(SPECIALS) + ordered
self.ids = {token: i for i, token in enumerate(self.tokens)}
def encode(self, tokens, boundaries=False):
ids = [self.ids.get(token, self.ids['<unk>']) for token in tokens]
return [self.ids['<bos>'], *ids, self.ids['<eos>']] if boundaries else ids
def decode(self, ids, remove_boundaries=False):
result = []
for i in ids:
if not isinstance(i, int) or i < 0 or i >= len(self.tokens):
raise ValueError('Identificador fuera del vocabulario')
token = self.tokens[i]
if remove_boundaries and token in ('<bos>', '<eos>'):
continue
result.append(token)
return result
def encode_bytes(text):
# IDs 0..3 reservados; un byte usa un ID entre 4 y 259.
return [b + 4 for b in normalize(text).encode('utf-8')]
def decode_bytes(ids):
if any(not isinstance(i, int) or not 4 <= i < 260 for i in ids):
raise ValueError('Se esperaba un identificador de byte')
return bytes(i - 4 for i in ids).decode('utf-8', errors='strict')
def fit_loglog(xs, ys):
x, y = np.asarray(xs, dtype=float), np.asarray(ys, dtype=float)
if len(x) < 2 or np.any(x <= 0) or np.any(y <= 0) or np.unique(x).size < 2:
return None
slope, intercept = np.polyfit(np.log(x), np.log(y), 1)
residuals = np.log(y) - (intercept + slope * np.log(x))
return {'slope': float(slope), 'intercept': float(intercept), 'log_residuals': residuals.tolist()}
def experiment(train, test):
train, test = normalize(train), normalize(test)
train_tokens, test_tokens = tokenize(train), tokenize(test)
vocab = Vocabulary(train_tokens)
ids = vocab.encode(train_tokens, boundaries=True)
assert vocab.decode(ids, remove_boundaries=True) == train_tokens
test_words = [t for t in test_tokens if is_word(t)]
unknown = [t for t in test_words if t not in vocab.ids]
print('Tokens train:', train_tokens)
print('Vocabulario:', list(enumerate(vocab.tokens)))
print('Palabras test, desconocidas y tasa:', len(test_words), len(unknown),
len(unknown) / len(test_words) if test_words else 'indefinida')
print('OOV:', unknown)
chars = Vocabulary(list(train))
assert ''.join(chars.decode(chars.encode(list(train)))) == train
assert decode_bytes(encode_bytes(test)) == test
print('Caracteres test desconocidos:', sum(c not in chars.ids for c in test))
print('Bytes: ida y vuelta exacta del texto normalizado')
words = [t for t in train_tokens if is_word(t)]
frequencies = sorted(Counter(words).values(), reverse=True)
ranks = list(range(1, len(frequencies) + 1))
seen, sizes = set(), []
for word in words:
seen.add(word)
sizes.append(len(seen))
prefixes = sorted(set(int(x) for x in np.linspace(1, len(words), min(10, len(words))))) if words else []
print('Zipf, pares y ajuste:', list(zip(ranks, frequencies)), fit_loglog(ranks, frequencies))
print('Heaps, pares y ajuste:', [(n, sizes[n - 1]) for n in prefixes],
fit_loglog(prefixes, [sizes[n - 1] for n in prefixes]))
print('Ajustes descriptivos; la muestra corta no prueba una ley de potencia.')
experiment(TRAIN, TEST)Characters are reconstructed exactly only when they belong to the known vocabulary; <unk> does not preserve identity. The byte alternative recovers the normalized UTF-8-encoded string, but lowercase normalization alone does not recover the original. Words omit spaces and numbers, and punctuation is tokenized separately; OOV rate counts words only.
The module starts with n-grams and smoothing, moves through distributed representations and recurrent networks, and reaches encoders, decoders and attention. This lesson’s conditionals will recur; what changes is how they are represented and calculated.
The figure uses aggregates obtained with this local program. It downloads Gutenberg text and the CPython 3.13.0 file, generates two controls with their seeds and saves counts and hashes. It also calculates descriptive Zipf and Heaps slopes for chapter I using all observed ranks and selected prefixes respectively. The reproduced run yields and (0.718 and 0.870). Changing those intervals can greatly change exponents and the fit does not prove a power law. Chapter I has 1,878 words, 717 types and 508 frequency-one types; in chapter II, 768 of 2,206 words do not appear in the first chapter’s vocabulary. These values depend on boundaries, edition and tokenization included below. The downloaded book’s SHA-256 was 392270e534c66988d6e949ba0f9a64117969fde0f2aebbc6efef3314e23e4385, and the Python file’s was 9d2fb944932526a29c70b83238fadc6a5a05c86910623776820e61a5e1deb69c.
"""Genera datos agregados reproducibles para los interactivos de m17-l01.
Ejecutar localmente: descarga Gutenberg y CPython si no se indican archivos ya
obtenidos mediante --book y --python-source. Usa --no-download para impedir
las descargas. Consulta las condiciones antes de redistribuir datos.
"""
import argparse
import hashlib
import json
import math
import os
import random
import re
import unicodedata
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
BOOK_URL = 'https://www.gutenberg.org/files/2000/2000-0.txt'
CODE_URL = 'https://raw.githubusercontent.com/python/cpython/v3.13.0/Lib/collections/__init__.py'
PART = 'Primera parte del ingenioso hidalgo don Quijote de la Mancha'
HEADINGS = (
'Capítulo primero. Que trata de la condición y ejercicio del famoso hidalgo\ndon Quijote de la Mancha',
'Capítulo II. Que trata de la primera salida que de su tierra hizo el\ningenioso don Quijote',
'Capítulo III. Donde se cuenta la graciosa manera que tuvo don Quijote en\narmarse caballero',
'Capítulo IV. De lo que le sucedió a nuestro caballero cuando salió de la\nventa',
)
TOKEN_PATTERN = r"[^\W\d_]+(?:['’][^\W\d_]+)*|[^\w\s]"
PATTERN = re.compile(TOKEN_PATTERN, re.UNICODE)
def read_source(path, url, download):
if path:
return Path(path).read_bytes()
if not download:
raise ValueError('Indica los archivos locales necesarios o elimina --no-download')
request = urllib.request.Request(url, headers={'User-Agent': 'OryonLearn/1.0 (educational research)'})
with urllib.request.urlopen(request, timeout=30) as response:
content = response.read(8_000_001)
if len(content) > 8_000_000:
raise ValueError('Fuente demasiado grande')
return content
def decode(content):
return content.decode('utf-8-sig').replace('\r\n', '\n').replace('\r', '\n')
def extract_chapters(text):
# Buscar desde la aparición de primera parte que precede al encabezado I,
# evitando la tabla de contenido y la segunda parte.
candidates = []
for part in (match.start() for match in re.finditer(re.escape(PART), text)):
start = text.find(HEADINGS[0], part)
if start != -1:
candidates.append((part, start))
if not candidates:
raise ValueError('No se encontró la primera parte y su capítulo I')
part, first = min(candidates, key=lambda pair: pair[1] - pair[0])
positions = [first]
for heading in HEADINGS[1:]:
pos = text.find(heading, positions[-1] + 1)
if pos < 0:
raise ValueError('No se encontró encabezado: ' + heading)
positions.append(pos)
region = text[first:positions[-1] + len(HEADINGS[-1])]
if any(region.count(heading) != 1 for heading in HEADINGS):
raise ValueError('Encabezados ambiguos en el tramo seleccionado')
chapters = [text[positions[i] + len(HEADINGS[i]):positions[i + 1]].strip() for i in range(3)]
if any(len(chapter) < 1000 for chapter in chapters):
raise ValueError('Capítulo inesperadamente corto')
return chapters, {'part_offset': part, 'headings_offsets': positions,
'offset_units': 'puntos de código tras decodificar y unificar saltos'}
def normalize(text):
return unicodedata.normalize('NFC', text).lower()
def tokenize(text):
return PATTERN.findall(normalize(text))
def counts_for(tokens):
words = [token for token in tokens if token and token[0].isalpha()]
counts = Counter(words)
ordered = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
prefixes = sorted({max(1, round(len(words) ** (i / 31))) for i in range(32)}) if words else []
prefix_set = set(prefixes)
seen = set()
heaps = []
for i, word in enumerate(words, 1):
seen.add(word)
if i in prefix_set:
heaps.append([i, len(seen)])
return {'tokens': len(words), 'types': len(counts), 'hapax': sum(n == 1 for n in counts.values()),
'rank_frequency': [[rank, n] for rank, (_, n) in enumerate(ordered, 1)],
'heaps': heaps}
def loglog_slope(pairs):
# Mínimos cuadrados ordinarios sobre logaritmos naturales. Las pendientes
# son descriptivas, no inferencias con observaciones independientes.
points = [(math.log(x), math.log(y)) for x, y in pairs if x > 0 and y > 0]
if len(points) < 2:
return None
mean_x = sum(x for x, _ in points) / len(points)
mean_y = sum(y for _, y in points) / len(points)
denominator = sum((x - mean_x) ** 2 for x, _ in points)
if denominator == 0:
return None
return sum((x - mean_x) * (y - mean_y) for x, y in points) / denominator
def bigrams(tokens):
# Los marcadores son objetos estructurales que no pueden aparecer como
# token léxico: se codifican como claves JSON de cadenas diferenciadas.
counts = defaultdict(Counter)
last = '<bos>'
for token in tokens:
if token in ('<bos>', '<eos>', '<unk>', '<pad>'):
raise ValueError('Colisión con token especial')
counts[last][token] += 1
last = token
counts[last]['<eos>'] += 1
return {ctx: dict(sorted(successors.items())) for ctx, successors in sorted(counts.items())}
def monkey(seed=1701, length=100_000):
rng = random.Random(seed)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return ''.join(' ' if rng.random() < .18 else rng.choice(alphabet) for _ in range(length)) + ' '
def synthetic_logs(seed=1702, lines=2000):
rng = random.Random(seed)
levels = ('info', 'info', 'info', 'warn', 'error')
paths = ('health', 'health', 'search', 'login')
statuses = ('200', '200', '200', '404', '500')
return '\n'.join(f'{rng.choice(levels)} request {rng.choice(paths)} status {rng.choice(statuses)}'
for _ in range(lines))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--book')
parser.add_argument('--python-source')
parser.add_argument('--no-download', action='store_false', dest='download', default=True)
parser.add_argument('--output', default=os.environ.get('ORYON_CORPUS_OUTPUT', 'm17-l01-corpus.json'))
# En una celda interactiva no hay argumentos de línea de comandos propios:
# sys.argv pertenece al proceso anfitrión. Como script se validan los
# argumentos de verdad, sin descartar opciones desconocidas silenciosamente.
args = parser.parse_args(None if '__file__' in globals() else [])
book_bytes = read_source(args.book, BOOK_URL, args.download)
code_bytes = read_source(args.python_source, CODE_URL, args.download)
book, code = decode(book_bytes), decode(code_bytes)
(train, test, validation), positions = extract_chapters(book)
train_tokens, test_tokens = tokenize(train), tokenize(test)
vocabulary = set(train_tokens)
test_words = [token for token in test_tokens if token and token[0].isalpha()]
unknown = sum(token not in vocabulary for token in test_words)
sources = {'quijote': train, 'python': code, 'mono': monkey(), 'logs': synthetic_logs()}
stats = {key: counts_for(tokenize(value)) for key, value in sources.items()}
# El vocabulario de caracteres con <unk> no preserva caracteres fuera de
# train; se prohíbe por ello anunciar BPC comparable de texto arbitrario.
char_counts = bigrams(list(normalize(train)))
word_counts = bigrams(train_tokens)
payload = {'book_url': BOOK_URL, 'book_sha256': hashlib.sha256(book_bytes).hexdigest(),
'book_bytes': len(book_bytes), 'code_url': CODE_URL,
'code_sha256': hashlib.sha256(code_bytes).hexdigest(), 'code_bytes': len(code_bytes),
'split': {'train': 'primera parte, capítulo I', 'test': 'primera parte, capítulo II',
'validation': 'primera parte, capítulo III', **positions},
'transform': {'normalization': 'NFC y lower', 'regex': TOKEN_PATTERN,
'word_definition': 'token cuya primera letra es alfabética',
'ignored': 'espacios, dígitos y guion bajo; puntuación se tokeniza separada'},
'synthetic': {'mono': {'seed': 1701, 'length_before_final_delimiter': 100_000, 'space_probability': .18,
'alphabet': 'abcdefghijklmnopqrstuvwxyz'},
'logs': {'seed': 1702, 'lines': 2000,
'grammar': 'nivel request ruta status código; elecciones independientes'}},
'stats': stats, 'test_oov': {'unknown': unknown, 'word_tokens': len(test_words),
'rate': unknown / len(test_words) if test_words else None},
'models': {'word_bigram_counts': word_counts, 'char_bigram_counts': char_counts,
'smoothing': 'sin aplicar; el consumidor debe declarar suavizado y vocabulario'},
'chapter_sha256_utf8': {'train': hashlib.sha256(train.encode('utf-8')).hexdigest(),
'test': hashlib.sha256(test.encode('utf-8')).hexdigest(),
'validation': hashlib.sha256(validation.encode('utf-8')).hexdigest()}}
Path(args.output).write_text(json.dumps(payload, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Salida:', args.output, 'OOV:', payload['test_oov'])
print('Hash Gutenberg:', payload['book_sha256'], 'hash CPython:', payload['code_sha256'])
for name, data in stats.items():
print(name, 'tokens:', data['tokens'], 'tipos:', data['types'], 'hapax:', data['hapax'])
zipf_slope = loglog_slope(stats['quijote']['rank_frequency'])
heaps_slope = loglog_slope(stats['quijote']['heaps'])
print('Quijote, pendiente Zipf y exponente alfa:', zipf_slope,
-zipf_slope if zipf_slope is not None else None)
print('Quijote, pendiente Heaps y exponente beta:', heaps_slope)
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
def encode(text, vocab):
pass
def decode(ids, vocab):
passStep 1 of 3. What results from repeatedly applying the product rule on positive-probability prefixes?