AI Logic

Datasets and Benchmarks

Penn Treebank

Updated:

Structure and splits of the Penn Treebank. Left: the flow from American English text, annotated with POS tags and syntactic brackets to form the Penn Treebank, whose WSJ portion is preprocessed for language modeling and split by section into training, validation, and test sets. Right: one illustrative sentence shown as the original sentence, with POS tags, with syntactic brackets, and in the language modeling format

Overview

The Penn Treebank is a corpus (a collection of annotated text) of American English in which every word is tagged by hand with its part of speech, and sentence structure is marked with brackets. It was built by Marcus et al. at the University of Pennsylvania and published in Computational Linguistics in 1993. In its first three years (1989–1992), more than 4.5 million words were tagged for part of speech, and over half of them were annotated with skeletal sentence structure.

The goal was to provide a large annotated dataset for building and comparing statistical models of part-of-speech tagging and parsing. In particular, the portion consisting of Wall Street Journal (WSJ) articles served for many years as the standard data for parsing.

In deep learning, "PTB" usually refers to a version of the WSJ portion preprocessed for language modeling (distributed by Mikolov et al.). With about 930k training tokens and a 10k-word vocabulary, it is small, and it became the standard benchmark for comparing RNN and LSTM language models.

The "Penn Treebank" used in parsing (the original data with POS tags and brackets) and the "PTB" used in language modeling (preprocessed text with neither tags nor brackets) are completely different in content. When reading a paper, check which one is meant.

Contents: annotation and the language modeling version

The original Penn Treebank was annotated in two stages.

  1. Assign POS tags. An automatic POS tagger assigns tags, and humans correct them. The tagset has 36 POS tags and 12 punctuation/symbol tags, obtained by consolidating and reducing the fine-grained tags of the Brown Corpus (the leading English corpus before it) (e.g., NN singular noun, VBD past-tense verb, MD modal).
  2. Mark sentence structure with brackets. The tagged sentences are parsed automatically, and humans correct a simplified skeleton. Constituents are marked with brackets and labels, as in (NP the board) (noun phrase) and (VP will meet ...) (verb phrase).

The paper reports that correcting automatic output was faster than tagging from scratch (a median of 22 vs. 42 minutes per 1,000 words) and gave less inter-annotator disagreement (4.1% vs. 7.2% on average). As of November 1992, about 4.89 million tokens had been POS-tagged and about 2.88 million tokens had skeletal structure. Source texts included Dow Jones news, Department of Energy abstracts, Department of Agriculture bulletins, literary works, radio transcripts, and the Brown Corpus.

The WSJ portion consists of 2,499 WSJ articles from 1989 (about 1 million words), distributed in later releases (Treebank-2, Treebank-3) with more detailed structural annotation. The articles are divided into sections 00–24, and these numbers define the training and evaluation splits.

The language modeling version (Mikolov et al.'s preprocessing) strips the POS tags and brackets from the WSJ portion and normalizes the text as follows.

StepContent
CaseLowercase everything
NumbersReplace with N
PunctuationRemove most of it
VocabularyKeep the 10k most frequent words; replace the rest with <unk>
Sentence boundariesOne sentence per line. Each sentence end counts as <eos>
SplitSectionsTokens (including <eos>)
Train00–20about 930k
Validation21–22about 74k
Test23–24about 82k

About 4.8% of the tokens in the data are replaced by <unk>. A character-level version of the same text (with spaces replaced by _) is distributed alongside it.

Evaluation protocol

Language models are evaluated by word-level perplexity on the test set. Given the test token sequence w1,…,wNw_1, \dots, w_N (including <eos>), 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. The character-level version uses bits per character (BPC).

The notes in the distributed files state that the validation set is to be used only for tuning hyperparameters, not for training, and that perplexity is to be reported on the test set.

PTB perplexity is computed with the vocabulary fixed at 10k words and <unk> predicted as a single word. It cannot be compared directly with values on data that uses a different vocabulary or tokenization (text split by BPE, WikiText-103, etc.).

In parsing, models are trained on the WSJ portion and evaluated by F1, which counts how many brackets match the ground truth. For example, the parser of Kitaev and Klein (2018) reaches F1 93.55 on the WSJ test set without external data.

Usage and historical significance

The Penn Treebank became standard data in two fields.

  • Parsing and POS tagging: it became the foundation for training and comparing statistical parsers and taggers. It was already being used in probabilistic parsing research at the time of the paper.
  • Neural language models: Mikolov et al. evaluated RNN language models on PTB and showed lower perplexity than conventional n-gram models. Later papers on LSTM regularization (Variational Dropout, Zoneout, etc.) and architecture search (DARTS) compared results on PTB.

Test perplexity on word-level PTB has fallen as follows.

PaperModelTest perplexity
Mikolov et al. (2011)5-gram (modified Kneser-Ney smoothing)141
Mikolov et al. (2011)RNN (trained with backpropagation through time)123
Zaremba et al. (2014)Non-regularized LSTM114.5
Zaremba et al. (2014)Large LSTM regularized with Dropout78.4

Because the data is small, models train quickly on a single GPU, which made it well suited to comparing how to suppress overfitting with little data, as in RNN regularization.

Practical notes

License: the original Penn Treebank (Treebank-3) is distributed for a fee by the Linguistic Data Consortium (LDC), and using it requires agreeing to the LDC license. The copyright of the WSJ articles belongs to Dow Jones. The language modeling version is widely distributed from researchers' sites, but that does not remove the rights to the original text.

The language modeling PTB is data for research comparisons. Before using it as training data for a product or redistributing the text, check the LDC terms.

Unlike real text: it is lowercase only, numbers are N, punctuation is mostly gone, and the vocabulary is limited to 10k words. Merity et al. (2016) pointed out that these restrictions make PTB far from how language is actually used, and built WikiText, which keeps the original case, punctuation, and numbers.

Too small: with only about 930k training tokens, large models overfit quickly. It is not suited to comparing modern language models that assume large-scale pretraining.

Domain bias: the WSJ portion consists only of 1989 business news. Performance on PTB does not carry over to spoken language or text from other domains.

Overfitting to the validation set: many papers have tuned hyperparameters on the same validation set. When comparing small differences, check that results are reported over multiple random seeds and that the tuning effort is comparable.

Comparison with similar datasets

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

DatasetTextTraining tokensVocabularyCase, punctuation, numbers
PTB (language modeling)1989 WSJ articlesabout 930k10kNo (lowercase, N)
WikiText-2Good-quality Wikipedia articlesabout 2.09Mabout 33kYes
WikiText-103Good-quality Wikipedia articlesabout 103.23Mabout 268kYes

Rules of thumb for choosing:

  • To compare regularization of RNNs or small models under the same conditions as older papers, use PTB.
  • To compare models that use long context under conditions close to real text, use WikiText-103.
  • For parsing or POS tagging, use the original Penn Treebank from the LDC, not the language modeling version.

PyTorch example

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

'''
Load the language modeling PTB (ptb.train.txt, etc.) and train/evaluate an LSTM language model
The files are in data/ of Mikolov's simple-examples.tgz (one sentence per line, lowercase, numbers as N, out-of-vocabulary words as <unk>)
'''

def read_tokens(path):
  # Append <eos> to each line and concatenate into one token sequence (<eos> is also counted as a prediction target)
  tokens = []
  with open(path, encoding='utf-8') as f:
    for line in f:
      tokens += line.split() + ['<eos>']
  return tokens

train_tokens = read_tokens('data/ptb.train.txt')
valid_tokens = read_tokens('data/ptb.valid.txt')
test_tokens = read_tokens('data/ptb.test.txt')

# Build the vocabulary from the training data (exactly 10,000 words including <unk> and <eos>)
vocab = sorted(set(train_tokens))
stoi = {w: i for i, w in enumerate(vocab)}
print(len(train_tokens), len(vocab))  # 929589 10000

def to_ids(tokens):
  return torch.tensor([stoi[w] for w in tokens], dtype=torch.long)

def batchify(ids, batch_size):
  # Cut one long sequence into batch_size parallel sequences -> [length, batch_size]
  n = ids.size(0) // batch_size
  return ids[: n * batch_size].view(batch_size, n).t().contiguous()

train_data = batchify(to_ids(train_tokens), 20)
valid_data = batchify(to_ids(valid_tokens), 10)
test_data = batchify(to_ids(test_tokens), 10)


class LSTMLM(nn.Module):
  def __init__(self, vocab_size, dim=650, layers=2, dropout=0.5):
    super().__init__()
    self.embed = nn.Embedding(vocab_size, dim)
    self.lstm = nn.LSTM(dim, dim, layers, dropout=dropout)
    self.drop = nn.Dropout(dropout)                 # active only in model.train(); disabled by model.eval()
    self.out = nn.Linear(dim, vocab_size)

  def forward(self, x, state=None):
    h, state = self.lstm(self.drop(self.embed(x)), state)
    return self.out(self.drop(h)), state


def evaluate(model, data, bptt=35):
  # Perplexity over the whole test (or validation) set = exp(mean negative log-likelihood per token)
  model.eval()
  total_loss, total_tokens, state = 0.0, 0, None
  with torch.no_grad():
    for i in range(0, data.size(0) - 1, bptt):
      x = data[i : i + bptt]
      y = data[i + 1 : i + 1 + len(x)]
      x = x[: len(y)]
      logits, state = model(x, state)
      total_loss += nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), y.reshape(-1), reduction='sum').item()
      total_tokens += y.numel()
  return math.exp(total_loss / total_tokens)


model = LSTMLM(len(vocab))
# Training loop omitted (backpropagate over 35-token chunks; detach the hidden state and carry it to the next chunk)
# Choose hyperparameters by perplexity on valid_data, and evaluate on test_data only once at the end
# print('test perplexity', evaluate(model, test_data))

# Hugging Face's ptb_text_only (column 'sentence'; splits 'train', 'validation', 'test') is
# published as a loading script, so load_dataset may fail depending on the datasets version

FAQ

Q. Does the language modeling PTB contain POS or syntactic information?
A.

No. It is only the text of the WSJ portion, lowercased, with numbers replaced by N and out-of-vocabulary words by <unk>. To use POS tags or syntax, you need the original Penn Treebank from the LDC.

Q. Is `<eos>` counted when computing perplexity?
A.

Yes. By PTB convention, the sentence-final <eos> is treated as one of the words to predict, and the figure of about 82k test tokens includes <eos>. Counting differently changes the value, so match the convention of the papers you compare against.

Q. If a method lowers perplexity on PTB, does it also work for large language models?
A.

Not necessarily. PTB is small, with a 10k-word vocabulary and only about 930k training tokens, so techniques that suppress overfitting tend to work well on it. Confirm the effect on larger data such as WikiText-103.

References

  1. Marcus, M. P., Santorini, B., & Marcinkiewicz, M. A. (1993). Building a Large Annotated Corpus of English: The Penn Treebank. Computational Linguistics, 19(2), 313–330.
  2. Marcus, M. P., et al. (1999). Treebank-3 LDC99T42. Linguistic Data Consortium.
  3. Mikolov, T., Karafiát, M., Burget, L., Černocký, J., & Khudanpur, S. (2010). Recurrent neural network based language model. Interspeech 2010.
  4. Mikolov, T., Kombrink, S., Burget, L., Černocký, J., & Khudanpur, S. (2011). Extensions of Recurrent Neural Network Language Model. ICASSP 2011.
  5. Mikolov, T. simple-examples from the RNNLM Toolkit (distribution files of the language modeling PTB).
  6. Zaremba, W., Sutskever, I., & Vinyals, O. (2014). Recurrent Neural Network Regularization.
  7. Merity, S., Xiong, C., Bradbury, J., & Socher, R. (2016). Pointer Sentinel Mixture Models (introduces WikiText).
  8. Kitaev, N., & Klein, D. (2018). Constituency Parsing with a Self-Attentive Encoder. ACL 2018.