AI Logic

Datasets and Benchmarks

WikiText-103

Updated:

How WikiText-103 was built and preprocessed. Left: the flow from English Wikipedia, selecting good-quality articles, extracting the text, tokenizing, and building the vocabulary to form WikiText-103, split by article into training, validation, and test sets. Right: one illustrative sentence shown in its original form and in the WikiText-103 form, and the evaluation rules

Overview

WikiText-103 is about 100 million tokens of text for language modeling, extracted from 28,000 good-quality articles of English Wikipedia. Merity et al. released it in 2016, together with the smaller WikiText-2, in their paper on the pointer sentinel method for language models. It is the standard benchmark for comparing word-level language models by perplexity, used especially to compare how well models use long context.

It was motivated by the limits of the language modeling version of Penn Treebank (PTB), the previous standard. The paper raises the following issues with PTB.

  • Unlike real text: everything is lowercase, there is no punctuation, and the vocabulary is limited to 10k words
  • No rare words: because the vocabulary is cut at 10k words, it cannot measure the ability to predict rare words such as names
  • Other large datasets have restrictions too: their licenses are strict, or their sentences are shuffled so long context cannot be learned

WikiText keeps case, punctuation, and numbers, and contains whole articles in order. Its training set is about 110 times larger than PTB's.

WikiText-2 and WikiText-103 share the same 60 articles each for validation and test; they differ only in the amount of training data and the vocabulary. WikiText-2 has a small training set of about 2.09M tokens and is used for quick experiments.

Contents: construction, splits, and format

WikiText was built in the following steps.

  1. Select articles. Only articles meeting the "Good" and "Featured" criteria set by Wikipedia editors were selected. These are articles that humans reviewed and judged to be well written, factually accurate, neutral, and stable. There are 23,805 Good and 4,790 Featured articles.
  2. Extract the text. The article text is extracted with the Wikipedia API, and sections consisting mainly of lists are removed. Macros such as unit conversions and dates are processed, and stray text leaked from HTML, such as edit buttons, is removed. Math and LaTeX code are replaced with <formula>.
  3. Tokenize. The text is normalized and split with the Moses tokenizer (a tool commonly used in machine translation that splits English text into words and symbols). Separators inside numbers are also split, so 8,600 becomes 8 @,@ 600.
  4. Build the vocabulary. Words appearing fewer than 3 times are discarded to form the vocabulary, and out-of-vocabulary words are replaced with <unk>.
SplitArticlesTokens
Train28,475103,227,021
Validation60217,646
Test60245,569

The vocabulary has 267,735 words, and 0.4% of tokens are replaced by <unk> (4.8% for PTB). Token counts include newlines. The split is by article, so no article is divided between the training and test sets.

The files are text with tokens separated by spaces, in the same format as the language modeling version of PTB, so that existing language modeling code can be used as is. WikiText-103 comes in two versions.

VersionContentSuited for
Standard (wikitext-103-v1)Out-of-vocabulary words replaced with <unk>Word-level language models
Raw (wikitext-103-raw-v1)Tokens before replacement with <unk>Character-level and subword-level language models

Evaluation protocol

Evaluation uses word-level perplexity on the test set. Given the test token sequence w1,…,wNw_1, \dots, w_N, it is computed from the model's probabilities as

PPL=exp⁡(−1N∑t=1Nlog⁡p(wt∣w1,…,wt−1))\mathrm{PPL} = \exp\left( -\frac{1}{N} \sum_{t=1}^{N} \log p(w_t \mid w_1, \dots, w_{t-1}) \right)

It represents roughly how many words, on average, the model is choosing among for the next word; lower is better. It equals the mean cross-entropy used in training passed through exp⁡\exp. NN is the number of tokens in the standard version (tokens for <unk> and newlines each count as one).

Because whole articles appear in order, the test set can be evaluated while carrying over earlier text as context, rather than being cut into short segments. Models that can use longer context achieve lower perplexity by using names and terms that appeared earlier in the article as clues.

Perplexity depends on what counts as one unit. For models that predict subwords such as BPE or bytes, the log-likelihood over the whole text must be summed and renormalized by the number of WikiText-103 words before taking exp⁡\exp; otherwise it cannot be compared with word-level values. It also cannot be compared directly with PTB perplexity (10k vocabulary).

Usage and historical significance

WikiText-103 spread as the word-level language modeling benchmark that replaced PTB. Its large training set and article-level long context make it well suited to comparing models that handle long-range dependencies. The Transformer-XL paper, which proposed Transformer-XL relative positional encoding, also uses WikiText-103 as its main evaluation, calling it "the largest word-level language modeling benchmark with long-term dependency."

Test perplexity has fallen from LSTM to Transformer-based models. The following values are summarized in Table 1 of the Transformer-XL paper (Dai et al. 2019).

ModelParametersTest perplexity
LSTM (Grave et al. 2016)−48.7
LSTM + neural cache (Grave et al. 2016)−40.8
GCNN-14 (Dauphin et al. 2016)−37.2
QRNN (Merity et al. 2018)151M33.0
Adaptive Input (Baevski & Auli 2018)247M20.5
Transformer-XL Large (Dai et al. 2019)257M18.3

The GPT-2 paper (Radford et al. 2019) reports that even a model not trained on WikiText-103 at all (trained on web text) reached a test perplexity of 17.48 with the largest 1.5B-parameter model (37.50 with the smallest 117M model). However, this value was obtained after applying invertible detokenizers that undo tokenization artifacts (symbols such as @-@ and detached punctuation) as much as possible, and the paper notes that these detokenizers alone lowered perplexity by 2.5 to 5.

In this way, WikiText-103 has been used both for "comparing models trained on that data" and for "zero-shot language prediction ability of models pretrained on large data."

Practical notes

License: WikiText is built from Wikipedia text, so it is released under the Creative Commons Attribution-ShareAlike (CC BY-SA) terms.

CC BY-SA requires attribution and release under the same license when redistributing the text or publishing modified versions. The Hugging Face dataset card lists both CC BY-SA 3.0 (and GFDL) and CC BY-SA 4.0 as licenses. Before using it in a product or in data you publish, check it together with the original Wikipedia terms of use.

A test article also appears in the training set: the GPT-2 paper found that one of the 60 test articles of WikiText-103 also appears in the training set, and pointed out at least 1.6% overlap. Counting 8-word sequences, 9.09% of the test set overlapped with the training set. Most of the overlap consists of set phrases, but there are also long matching passages.

Overlap with pretraining data: models pretrained on text that includes Wikipedia may have seen the WikiText-103 test articles during training. For zero-shot evaluation, check for overlap with the pretraining data, and discount the results accordingly when interpreting them.

Tokenization artifacts: @,@, @-@, and detached punctuation (1915 .) are forms that do not occur in the original text. The raw version has the same tokenization applied. When evaluating a model trained on natural text, perplexity comes out higher to the extent that the model is unfamiliar with these forms.

Domain bias: only good-quality encyclopedia articles are included. WikiText-103 scores alone do not reveal language prediction ability on conversation or text from other domains.

Comparison with similar datasets

The datasets commonly used for word-level language modeling compare as follows.

DatasetTextTraining tokensVocabularyUnknown-word (<unk>) rateCase, punctuation, numbers
PTB (language modeling)1989 WSJ articlesabout 930k10k4.8%No (lowercase, numbers as N)
WikiText-2600 good-quality Wikipedia articlesabout 2.09M33,2782.6%Yes
WikiText-10328,475 good-quality Wikipedia articlesabout 103.23M267,7350.4%Yes

(Figures are from Table 1 of the WikiText paper.)

A larger word-level benchmark is One Billion Word, about 10 times the size of WikiText-103. However, its sentences are shuffled, so long context can be neither learned nor evaluated.

Rules of thumb for choosing:

  • To compare small techniques such as regularization under the same conditions as older RNN papers, use PTB or WikiText-2.
  • To compare models that use long context or larger word-level language models, use WikiText-103.
  • To compare sentence-level prediction ability on much more data, One Billion Word has been used.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

"""
Load WikiText-103 and compute the test perplexity of a language model
Load it with Hugging Face datasets (pip install datasets).
  'wikitext-103-v1'     : out-of-vocabulary words replaced with <unk> (for word-level language models)
  'wikitext-103-raw-v1' : before replacement with <unk> (for subword/character level)
"""
from datasets import load_dataset

ds = load_dataset('Salesforce/wikitext', 'wikitext-103-v1')
print(ds)  # train / validation / test. Each line of the original file is one record (empty lines too)


def read_tokens(split):
  # Split each line on whitespace, append <eos>, and concatenate into one token sequence (newlines are also counted as prediction targets)
  tokens = []
  for line in ds[split]['text']:
    if line.strip() == '':
      continue                 # skip empty lines (paragraph breaks); match the counting to the papers you compare against
    tokens += line.split() + ['<eos>']
  return tokens


train_tokens = read_tokens('train')
test_tokens = read_tokens('test')
vocab = sorted(set(train_tokens))           # build the vocabulary from the training data (includes <unk>)
stoi = {w: i for i, w in enumerate(vocab)}
test_ids = torch.tensor([stoi[w] for w in test_tokens])
print(len(train_tokens), len(vocab))


def evaluate(model, ids, bptt=256):
  """Perplexity over the whole test set. Carries over the hidden state from the previous segment to use the article context"""
  model.eval()                               # disable Dropout
  total_nll, state = 0.0, None
  with torch.no_grad():
    for i in range(0, ids.size(0) - 1, bptt):
      x = ids[i : i + bptt].unsqueeze(1)                 # [length, 1]
      y = ids[i + 1 : i + 1 + x.size(0)].unsqueeze(1)
      x = x[: y.size(0)]
      logits, state = model(x, state)                    # [length, 1, vocab]
      total_nll += nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1), reduction='sum').item()
  return math.exp(total_nll / (ids.size(0) - 1))         # exp of the mean negative log-likelihood per word (token)


# To compare a subword model (GPT-2, etc.) with word-level values,
# sum the negative log-likelihood over subwords, divide by the number of WikiText-103 words, then take exp:
#   ppl_word = math.exp(total_nll_over_subwords / num_words)

FAQ

Q. What is the difference between WikiText-103 and WikiText-2?
A.

The validation and test sets are the same 60 articles each; they differ in the amount of training data (28,475 vs. 600 articles) and the vocabulary (267,735 vs. 33,278 words). Because the vocabularies differ, perplexities cannot be compared directly even on the same test set.

Q. Should I use the raw version or the standard version?
A.

To compare a word-level language model with papers, use the standard version with <unk> replacement. For models that predict subwords such as BPE or characters, use the raw version. Both have the same tokenization applied (@,@, etc.).

Q. Can GPT-2's WikiText-103 perplexity be compared with models trained on WikiText-103?
A.

Not as is. GPT-2's value was obtained after applying detokenizers that undo tokenization artifacts and renormalizing by the number of words, and its pretraining data may contain text similar to the test articles. When comparing, align the evaluation conditions and treat it as a reference value.

References

  1. Merity, S., Xiong, C., Bradbury, J., & Socher, R. (2016). Pointer Sentinel Mixture Models. arXiv:1609.07843.
  2. Salesforce/wikitext (Hugging Face dataset card).
  3. Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V., & Salakhutdinov, R. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. ACL 2019.
  4. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.