Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Training custom tokenizer

notebooks/training.livemd

Training custom tokenizer

Mix.install([
  {:tokenizers, "~> 0.4.0"},
  {:req, "~> 0.3.8"}
])

Intro

Let’s have a quick look at the 🤗 Tokenizers library features. The library provides an implementation of today’s most used tokenizers that is both easy to use and blazing fast.

Downloading the data

To illustrate how fast the 🤗 Tokenizers library is, let’s train a new tokenizer on wikitext-103 (516M of text) in just a few seconds. First things first, you will need to download this dataset and unzip it with:

wget https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip
unzip wikitext-103-raw-v1.zip

Alternatively you can run this code:

Req.get!("https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip").body
|> Enum.each(fn {filename, data} ->
  filename = to_string(filename)
  path = Path.join(__DIR__, filename)
  IO.puts("Writing #{filename} to path #{path}")

  :ok = File.mkdir_p!(Path.dirname(path))
  File.write!(path, data, [:write])
end)

Training the tokenizer from scratch

alias Tokenizers.Tokenizer
alias Tokenizers.Trainer
alias Tokenizers.PostProcessor
alias Tokenizers.PreTokenizer
alias Tokenizers.Model
alias Tokenizers.Encoding

In this tour, we will build and train a Byte-Pair Encoding (BPE) tokenizer. For more information about the different type of tokenizers, check out this guide in the 🤗 Transformers documentation. Here, training the tokenizer means it will learn merge rules by:

  • Start with all the characters present in the training corpus as tokens.
  • Identify the most common pair of tokens and merge it into one token.
  • Repeat until the vocabulary (e.g., the number of tokens) has reached the size we want.

The main API of the library is the class Tokenizer, here is how we instantiate one with a BPE model:

{:ok, model} = Model.BPE.init(%{}, [], unk_token: "[UNK]")
{:ok, tokenizer} = Tokenizer.init(model)

To train our tokenizer on the wikitext files, we will need to instantiate a trainer, in this case a BPE trainer:

{:ok, trainer} = Trainer.bpe(special_tokens: ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])

We can set the training arguments like vocab_size or min_frequency (here left at their default values of 30,000 and 0), but the most important part is to give the special_tokens we plan to use later on (they are not used at all during training) so that they get inserted in the vocabulary.

> The order in which you write the special tokens list matters: here "[UNK]" will get the ID 0, "[CLS]" will get the ID 1 and so forth.

We could train our tokenizer right now, but it wouldn’t be optimal. Without a pre-tokenizer that will split our inputs into words, we might get tokens that overlap several words: for instance we could get an “it is” token since those two words often appear next to each other. Using a pre-tokenizer will ensure no token is bigger than a word returned by the pre-tokenizer. Here we want to train a subword BPE tokenizer, and we will use the easiest pre-tokenizer possible by splitting on whitespace.

tokenizer = Tokenizer.set_pre_tokenizer(tokenizer, PreTokenizer.whitespace())

Now, we can just call the Tokenizer.train_from_files/3 function with the list of files we want to train on:

{:ok, tokenizer} =
  [
    "wikitext-103-raw/wiki.test.raw",
    "wikitext-103-raw/wiki.train.raw",
    "wikitext-103-raw/wiki.valid.raw"
  ]
  |> Enum.map(&Path.join(__DIR__, &1))
  |> then(&Tokenizer.train_from_files(tokenizer, &1, trainer: trainer))

This should only take a few seconds to train our tokenizer on the full wikitext dataset! To save the tokenizer in one file that contains all its configuration and vocabulary, just use the Tokenizer.save/2 function:

Tokenizer.save(tokenizer, Path.join(__DIR__, "tokenizer-wiki.json"))

and you can reload your tokenizer from that file with the Tokenizer.from_file/1 function:

{:ok, tokenizer} = Tokenizer.from_file(Path.join(__DIR__, "tokenizer-wiki.json"))

Using the tokenizer

Now that we have trained a tokenizer, we can use it on any text we want with the Tokenizer.encode/1 function:

{:ok, encoding} = Tokenizer.encode(tokenizer, "Hello, y'all! How are you 😁 ?")

This applied the full pipeline of the tokenizer on the text, returning an encoding. To learn more about this pipeline, and how to apply (or customize) parts of it, check out this page.

This encoding then has all the attributes you need for your deep learning model (or other). The tokens attribute contains the segmentation of your text in tokens:

Encoding.get_tokens(encoding)

Similarly, the ids attribute will contain the index of each of those tokens in the tokenizer’s vocabulary:

Encoding.get_ids(encoding)

An important feature of the 🤗 Tokenizers library is that it comes with full alignment tracking, meaning you can always get the part of your original sentence that corresponds to a given token. Those are stored in the offsets attribute of our Encoding object. For instance, let’s assume we would want to find back what caused the “[UNK]” token to appear, which is the token at index 9 in the list, we can just ask for the offset at the index:

{emoji_offset_start, emoji_offset_end} = Encoding.get_offsets(encoding) |> Enum.at(9)

and those are the indices that correspond to the emoji in the original sentence:

:binary.part(
  "Hello, y'all! How are you 😁 ?",
  emoji_offset_start,
  # Length
  emoji_offset_end - emoji_offset_start
)

Post-processing

We might want our tokenizer to automatically add special tokens, like [CLS] or [SEP]. To do this, we use a post-processor. Template post-processing is the most commonly used, you just have to specify a template for the processing of single sentences and pairs of sentences, along with the special tokens and their IDs.

When we built our tokenizer, we set [CLS] and [SEP] in positions 1 and 2 of our list of special tokens, so this should be their IDs. To double-check, we can use the Tokenizer.token_to_id/2 function:

Tokenizer.token_to_id(tokenizer, "[SEP]")

Here is how we can set the post-processing to give us the traditional BERT inputs:

tokenizer =
  Tokenizer.set_post_processor(
    tokenizer,
    PostProcessor.template(
      single: "[CLS] $A [SEP]",
      pair: "[CLS] $A [SEP] $B:1 [SEP]:1",
      special_tokens: [
        {"[CLS]", Tokenizer.token_to_id(tokenizer, "[CLS]")},
        {"[SEP]", Tokenizer.token_to_id(tokenizer, "[SEP]")}
      ]
    )
  )

Let’s go over this snippet of code in more details. First we specify the template for single sentences: those should have the form "[CLS] $A [SEP]" where $A represents our sentence.

Then, we specify the template for sentence pairs, which should have the form "[CLS] $A [SEP] $B [SEP]" where $A represents the first sentence and $B the second one. The :1 added in the template represent the type IDs we want for each part of our input: it defaults to 0 for everything (which is why we don’t have $A:0) and here we set it to 1 for the tokens of the second sentence and the last "[SEP]" token.

Lastly, we specify the special tokens we used and their IDs in our tokenizer’s vocabulary.

To check out this worked properly, let’s try to encode the same sentence as before:

{:ok, encoding} = Tokenizer.encode(tokenizer, "Hello, y'all! How are you 😁 ?")
Encoding.get_tokens(encoding)

To check the results on a pair of sentences, we just pass the two sentences to Tokenizer.encode/2:

{:ok, encoding} = Tokenizer.encode(tokenizer, {"Hello, y'all!", "How are you 😁 ?"})
Encoding.get_tokens(encoding)

You can then check the type IDs attributed to each token is correct with

Encoding.get_type_ids(encoding)

If you save your tokenizer with Tokenizer.save/2, the post-processor will be saved along.

Encoding multiple sentences in a batch

To get the full speed of the 🤗 Tokenizers library, it’s best to process your texts by batches by using the Tokenizer.encode_batch/2 function:

{:ok, encoding} = Tokenizer.encode_batch(tokenizer, ["Hello, y'all!", "How are you 😁 ?"])

The output is then a list of encodings like the ones we saw before. You can process together as many texts as you like, as long as it fits in memory.

To process a batch of sentence pairs, pass a list of tuples to the Tokenizer.encode_batch/2 function:

{:ok, encoding} =
  Tokenizer.encode_batch(tokenizer, [
    {"Hello, y'all!", "How are you 😁 ?"},
    {
      "Hello to you too!",
      "I'm fine, thank you!"
    }
  ])

When encoding multiple sentences, you can automatically pad the outputs to the longest sentence present by using Tokenizer.set_padding/2, with the pad_token and its ID (which we can double-check the id for the padding token with Tokenizer.token_to_id/2 like before):

tokenizer = Tokenizer.set_padding(tokenizer, pad_id: 3, pad_token: "[PAD]")

We can set the direction of the padding (defaults to the right) or a given length if we want to pad every sample to that specific number (here we leave it unset to pad to the size of the longest text).

{:ok, encoding} = Tokenizer.encode_batch(tokenizer, ["Hello, y'all!", "How are you 😁 ?"])

encoding
|> Enum.at(1)
|> Encoding.get_tokens()

In this case, the attention mask generated by the tokenizer takes the padding into account:

encoding
|> Enum.at(1)
|> Encoding.get_attention_mask()