liveBook · Manning

Token

As explained in Deep Learning with R, Third Edition

A token is a discrete unit of text processed by a language model, such as a word, subword, character, or punctuation symbol.

A token is a small unit produced by splitting text for processing. Depending on the tokenizer, it can be a character, a word, punctuation, or a subword. Tokens can be mapped to numeric indices so text can be represented as sequences for a model. section 14.2 section 14.2.2

Splitting a sentence

A word-level split of “The quick brown fox jumped over the dog.” yields “The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “dog”, and “.” as separate tokens. A character-level split instead starts with “T”, “h”, “e”, and a space. section 14.2

split_words <- function(text) {
  text |>
    str_split(boundary("word", skip_word_none = FALSE)) |>
    unlist() |>
    str_subset("\\S")
}

This R function splits at word boundaries, preserves punctuation, and removes whitespace from the result. section 14.2

A tokenizer typically standardizes text, splits it, and looks up each token in a vocabulary. Lowercasing is one standardization choice. An index of 0 can mark a token missing from the vocabulary; detokenization can display it as “[UNK]”. section 14.2.1

Listing 14.1 A basic character-level tokenizer
new_char_tokenizer <- function(vocabulary, nomatch = "[UNK]") {
  self <- new.env(parent = emptyenv())
  attr(self, "class") <- "CharTokenizer"

  self$vocabulary <- vocabulary
  self$nomatch <- nomatch

  self$standardize <- function(strings) {
    str_to_lower(strings)
  }

  self$split <- function(strings) {
    split_chars(strings)
  }

  self$index <- function(tokens) {
    match(tokens, self$vocabulary, nomatch = 0L)
  }

  self$tokenize <- function(strings) {  #1
    strings |>
      self$standardize() |>
      self$split() |>
      self$index()
  }

  self$detokenize <- function(indices) { #2
    indices[indices == 0] <- NA
    matches <- self$vocabulary[indices]
    matches[is.na(matches)] <- self$nomatch
    matches
  }

  self
}

This character tokenizer combines lowercasing, splitting, indexing, and detokenization. section 14.2.1

The choice of token unit affects vocabulary size and sequence length:

  • Characters need a relatively small vocabulary but produce long sequences. In Moby Dick, 89 vocabulary terms cover the characters. section 14.2.1
  • Words produce shorter sequences but can require a large vocabulary. A 2,000-term vocabulary leaves some words unknown; indexing every word in Moby Dick would require about 17,000 terms. section 14.2.1
  • Subwords can combine common character sequences while retaining smaller pieces for less common words. section 14.2.2

Byte-pair encoding builds subword tokens by starting with characters and repeatedly merging frequent adjacent pairs. For example, “o” and “w” can merge into “ow”, which can then participate in a later merge. The ordered merge rules are used to tokenize new text. section 14.2.2

str(vocabulary)

chr [1:2000] " " "e" "t" "a" "o" "n" "s" "i" "h" "r" "l" "d" "u" "m" ...

tail(vocabulary)

[1] "ience"  "infer"  "ise,"   "island" "ivid"   "lau"

tokenized <- sub_word_tokenizer$tokenize(string)
str(tokenized)

int [1:27] 15 129 1 220 1 236 1110 158 25 1 ...

tokenized |> sub_word_tokenizer$detokenize() |> str_flatten("_")

[1] "c_all_ _me_ _ish_ma_el_._ _some_ _years_ _ago_--_never_ _mind_ _how_ _long_ _precise_ly_."

A subword tokenizer splits a Moby Dick passage into a mixture of whole words and smaller pieces, including “ish”, “ma”, and “el”. section 14.2.2

In a language model, tokens are also the units predicted during generation: each selected token becomes part of the input for the next step. Sampling strategies can select the most likely token or sample from a set of candidates. section 15.6 section 16.6

How Deep Learning with R, Third Edition covers it

How deep it goes
Builds character, word, and byte-pair tokenizers, including vocabulary construction, indexing, and unknown-token handling.
Examples
Compares character, word, and subword tokenization using Moby Dick passages and a small fox sentence dataset.
What you can do after
Build character, word, and byte-pair tokenizers from scratch in R and inspect vocabulary indices and unknown tokens.
How it connects
Connects tokenization with vocabularies, embeddings, attention, and language modeling.

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 R, Third Edition. The section links point to the parts of the book it draws on.