Module contents
Lesson 1 of 24Review 60 min

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 x1,…,xTx_1,\ldots,x_T; what each xtx_t 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 rr. The first Zipf and Heaps regularity is approximately f(r)∝r−αf(r)\propto r^{-\alpha} over a range of ranks. A descending line on logarithmic axes suggests a scaling relationship; its slope is −α-\alpha if the fit is appropriate. But chosen range, tokenization, ties and words appearing once change the graph. A linear log-log fit and high R2R^2 do not prove a power law or identify its cause, as Clauset and colleagues caution.

InteractiveWord frequencies in four sources

Part one, chapter I of Don Quixote, Gutenberg 2000 edition. Tokens beginning with a letter are counted after NFC normalization and lowercasing; punctuation and digits do not count as words.

17171120Rank (log scale)Frequency (log scale)
  • Observed frequencies
  • Adjustable line

The line is a visual guide, not a statistical estimate. Ties and the many types occurring once form steps. The monkey curve comes from the explicit generator in the local cell: its shape alone does not demonstrate language or semantics.

Corpus
1.00
Words1878
Types717
Types with frequency 1508
Line slope−1.00
Compare real or generated frequencies with a line of adjustable slope; both scales are logarithmic.

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 NN is the number of tokens and V(N)V(N) the distinct types observed in that prefix, sometimes V(N)≈KNβV(N)\approx K N^\beta. The slope on a log-log graph estimates β\beta 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 α\alpha and β\beta 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, V(N)V(N) 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 cc whose component cic_i counts token ii. 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.

InteractiveWhat the bag cannot see
Order of A
elperromordióalhombre
Order of B
elhombremordióalperro

The representations match. Equality is checked at each coordinate, including zeroes.

CoordinateSentence ASentence B
al11
el11
hombre11
mordió11
perro11

Text is NFC normalized and lowercased; letters, numbers and underscores form words, each non-whitespace punctuation mark is another token and spaces are discarded. This rule differs from the cell and surprisal figure: decimal digits and underscores are retained here and apostrophes split. Bigrams are ordered consecutive pairs, without start or end markers. Each bar uses the largest count in this comparison as its scale.

In this pair there are 5 distinct tokens and up to 25 possible bigrams with that vocabulary. The table shows only coordinates observed in either sentence; zeroes observed in neither do not change equality. Matching vectors do not imply matching text or meaning.

Representation
Count A5
Count B5
Observed coordinates5
Equal vectors?Yes
Compare counts and order using words and bigrams calculated from sentences you enter.

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 VV units allows up to V2V^2 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 TT, autoregressive factorization is the chain rule, not an independence assumption:

p(x1:T)=p(x1)∏t=2Tp(xt∣x<t).p(x_{1:T})=p(x_1)\prod_{t=2}^{T}p(x_t\mid x_{<t}).

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 p(<eos>∣x1:T)p(\texttt{<eos>}\mid x_{1:T}) to its token factors. Here xtx_t 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 ε>0\varepsilon>0 exists such that, for every possible prefix, p(<eos>∣prefijo)≥εp(\texttt{<eos>}\mid\text{prefijo})\ge\varepsilon (where “prefijo” means prefix). After nn continuation decisions, the probability of continuing is at most (1−ε)n(1-\varepsilon)^n, which tends to zero. The condition is sufficient, not necessary.

InteractiveThe sentence as a product of conditionals

A separate bigram model for each unit is built from the training excerpt in this lesson’s cell: En un lugar de la Mancha, de cuyo nombre no quiero acordarme. The corpus is too small to evaluate a language model. The cell supplies the text and normalization; the bigram and its smoothing are defined here.

Each bar represents −log₂ p(token | previous). For a pair, p = (pair count + 1) / (context count + 14); the denominator includes known tokens, UNK and EOS, but not BOS or PAD. Smoothing adds one to each possible output. BOS is used first and EOS is scored at the end.

Scroll through the table to see all events, including EOS.

Observed tokenContext → modelSurprisal and probability
hechas · OOV<bos> → <unk>3.907 bits · (0+1)/(1+14)
,<unk> → ,3.807 bits · (0+1)/(0+14)
pues · OOV, → <unk>3.907 bits · (0+1)/(1+14)
,<unk> → ,3.807 bits · (0+1)/(0+14)
estas · OOV, → <unk>3.907 bits · (0+1)/(1+14)
prevenciones · OOV<unk> → <unk>3.807 bits · (0+1)/(0+14)
,<unk> → ,3.807 bits · (0+1)/(0+14)
no, → no3.907 bits · (0+1)/(1+14)
quiso · OOVno → <unk>3.907 bits · (0+1)/(1+14)
aguardar · OOV<unk> → <unk>3.807 bits · (0+1)/(0+14)
más · OOV<unk> → <unk>3.807 bits · (0+1)/(0+14)
tiempo · OOV<unk> → <unk>3.807 bits · (0+1)/(0+14)
<eos><unk> → <eos>3.807 bits · (0+1)/(0+14)

Input is NFC normalized and lowercased, as in the cell. Word mode retains letters, non-decimal Unicode numbers and internal apostrophes, separates punctuation and discards spaces, decimal digits and underscores. Character mode retains each code point in the normalized text. ␠ indicates a space and ↵ a line break.

Unseen tokens share UNK and the next context is also UNK: their original identity is lost. Therefore bits cannot be attributed to the exact text when OOV occurs. Words and punctuation also discard information, so their total is not comparable without encoding what was omitted. For characters, bits per code point are shown only when there are no OOVs and the text is not empty; cost includes EOS and corresponds to normalized text, not necessarily the original.

Bigram unit
Scored events, including EOS13
Unknown tokens8
Total bits49.993
Bits per event3.846
Bits per normalized code pointNot comparable
Change text and unit to examine probabilities from an explicit smoothed bigram; UNK does not recover lost text.

The surprisal of an observed token is −log⁡2p(xt∣x<t)-\log_2 p(x_t\mid x_{<t}) 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 C>0C>0 code points, T>0T>0 scored tokens and natural log-probability ℓ\ell, the units are

bits/token⁡=−ℓTln⁡2,bpc⁡=−ℓCln⁡2,PPL⁡token=exp⁡ ⁣(−ℓT)=2bits/token⁡.\operatorname{bits/token}=\frac{-\ell}{T\ln 2},\qquad \operatorname{bpc}=\frac{-\ell}{C\ln 2},\qquad \operatorname{PPL}_{\mathrm{token}}=\exp\!\left(\frac{-\ell}{T}\right)=2^{\operatorname{bits/token}}.

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.

InteractiveShapes of sequence problems

Speech recognition

Your choiceUnanswered
ResultChoose a shape
Match inputs, outputs and supervision locations with each task.

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.

[ ]Vocabularies and countsBrowser
"""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 α≈0,718\alpha\approx 0{,}718 and β≈0,870\beta\approx 0{,}870 (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.

[ ]Four corpora and reproducible countsLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericA common unit
A model assigns the complete representation of a normalized 40-code-point sentence a natural log-probability of −52 nats. How many bits per code point is that?
NumericChange the denominator
The same representation has eight scored words and total log-probability −52 nats; EOS is not scored in this exercise. What is its perplexity per word?
NumericThe price of collapsing words
3% of test tokens are unknown. At those positions one model assigns <unk> probability 0.5 and another 0.01; on all remaining positions they assign the same observed probabilities. How many bits per token does the first save on that test?
QuizIs it the same data?
One model discards spaces and replaces unseen words with <unk>; another scores every character of the original text. Both divide total surprisal by the original number of characters. What can you conclude?
CodeEncode and recognize what was lost
Implement encode(text, vocab) and decode(ids, vocab). vocab assigns distinct integer indices to the four markers <unk>, <bos>, <eos>, <pad> and individual characters. Encode must add BOS and EOS and replace unknown characters with UNK. Decode skips BOS, EOS and PAD, returns replacement character � for each UNK and rejects indices absent from vocab with ValueError. Do not normalize or change case. Round trips are required only for text whose characters are in the vocabulary.
def encode(text, vocab):
  pass

def decode(ids, vocab):
  pass
Shift+Enter to run
ProofFactorize and terminate
Prove: Prove the product rule for a finite sequence and justify a sufficient condition for an autoregressive generator to terminate almost surely.
0
Consider normalized conditionals at every prefix and a positive lower bound ε for EOS probability at every possible prefix.

Step 1 of 3. What results from repeatedly applying the product rule on positive-probability prefixes?

QuizWhere the loss lives
You want to classify reviews, tag words and transcribe speech. Which description respects their usual alignments?
Key idea
A modeled sequence is a specific representation of data. Order, discarded information, scored events and termination criterion determine what its probability means.