liveBook · Manning

Token

As explained in Deep Learning with Python, Third Edition

A discrete unit in a text sequence, such as a word or subword, that serves as the basic item attended over by the model.

A token is one unit in a text sequence. Before text can become numeric model input, it must be split into units such as characters or words. The choice changes the sequence the model receives. section 14.2

def split_words(text):
    return re.findall(r"[\w]+|[.,!?;]", text)

This regex-based splitter returns words and selected punctuation marks as separate tokens. section 14.2

Splitting produces strings, not yet numeric inputs. A vocabulary maps each token to an integer index. An unknown-token entry can supply an index when a string is absent from the vocabulary. section 14.2

vocabulary = {
    "[UNK]": 0,
    "the": 1,
    "quick": 2,
    "brown": 3,
    "fox": 4,
    "jumped": 5,
    "over": 6,
    "dog": 7,
    ".": 8,
}
words = split_words("The quick brown fox jumped over the lazy dog.")
indices = [vocabulary.get(word, 0) for word in words]

The lookup maps known words to indices and falls back to [UNK] for missing entries. Here, both capitalized “The” and “lazy” take that fallback. section 14.2

A token in context

In “The train left the station on time,” the meaning of “station” depends on nearby words. Self-attention lets its representation draw on “train” and other tokens in the sequence, including itself. section 15.3.2

Tokens need not be whole words: pretrained Transformer models also embed subwords. A useful distinction is that tokenization decides the sequence units, while embeddings and self-attention determine how those units are represented and related. section 14.2 section 15.5

How Deep Learning with Python, Third Edition covers it

How deep it goes
Works through regex splitting and vocabulary lookup, then explains token-level self-attention; mentions subwords without specifying a subword tokenizer.
Examples
Uses a fox-and-dog sentence for splitting and indexing, and a train-station ambiguity for contextual attention.
What it assumes
Starts from raw strings and teaches splitting and indexing directly, using Python regex and dictionary lookups.
What you can do after
Apply it via Python regex and vocabulary lookups to split and index text, then understand what self-attention operates over.
How it connects
Connects self-attention in Transformer encoders with the token embeddings used by Word2Vec and pretrained Transformers.

Also explained in

Compare how 31 books explain token →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.