liveBook · Manning

GPT-2

As explained in Natural Language Processing in Action, Second Edition

GPT-2 is an autoregressive transformer language model developed by OpenAI and trained to generate text from preceding context.

GPT-2 is an autoregressive transformer language model from OpenAI. Given a prompt, it generates text one token at a time using a probability distribution conditioned on the preceding context. It offers a practical way to inspect how a generative language model turns a prompt into a continuation. section 10.2 section 10.2.1

To generate text, load the pretrained model and its matching tokenizer. The tokenizer encodes the prompt using GPT-2’s vocabulary; the model generates token IDs, which the tokenizer decodes into readable text. section 10.2.1

Listing 10.2 Loading the pretrained GPT-2 model from Hugging Face
>>> tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
>>> tokenizer.pad_token = tokenizer.eos_token                 #1
>>> vanilla_gpt2 = GPT2LMHeadModel.from_pretrained('gpt2')

Load the pretrained GPT-2 model and tokenizer with Hugging Face Transformers. section 10.2.1

Listing 10.3 Generating text with GPT-2
>>> def generate(prompt, model, tokenizer,
...        device=DEVICE, **kwargs):
>>>    encoded_prompt = tokenizer.encode(
...        prompt, return_tensors='pt')
>>>    encoded_prompt = encoded_prompt.to(device)
>>>    encoded_output = model.generate(
...        encoded_prompt, **kwargs)
>>>    encoded_output = encoded_output.squeeze()        #1
>>>    decoded_output = tokenizer.decode(encoded_output,
...        clean_up_tokenization_spaces=True,
...        skip_special_tokens=True)
>>>    return decoded_output

This helper encodes a prompt, calls the model’s generate method, and decodes the result. section 10.2.1

Inspecting a continuation

For the prompt “NLP is,” one pretrained GPT-2 continuation incorrectly describes NLP as a data structure and then repeats itself. A fluent continuation is not necessarily a correct or useful answer. section 10.2.1

A direct model call returns logits: scores for possible next tokens. Applying softmax converts the scores at the last prompt position into probabilities. For “NLP is a,” the example ranks “ new” above “ non.” Generation strategies can use these scores differently; nucleus sampling, for example, samples with a specified top-p setting rather than always taking the highest-ranked token. section 10.2.1

Listing 10.6 Finding the token with maximum probability
>>> encoded_prompt = tokenizer('NLP is a', return_tensors="pt")    #1
>>> encoded_prompt = encoded_prompt["input_ids"]
>>> encoded_prompt = encoded_prompt.to(DEVICE)
>>> output = vanilla_gpt2(input_ids=encoded_prompt)
>>> next_token_logits = output.logits[0, -1, :]
>>> next_token_probs = torch.softmax(next_token_logits, dim=-1)
>>> sorted_ids = torch.argsort(next_token_probs, dim=-1, descending=True)
>>> tokenizer.decode(sorted_ids[0])       #2
' new'
>>> tokenizer.decode(sorted_ids[1])    #3
' non'

Inspect the next-token scores, convert them to probabilities, and decode the highest-ranked token IDs. section 10.2.1

Fine-tuning adjusts generation patterns using a particular text corpus. One workflow filters a collection of manuscript lines to natural-language text, tokenizes each line as a separate training example, and reserves a subset for evaluation. A language-modeling data collator prepares batches, while Transformers’ Trainer handles training. Batch size should fit the available GPU memory. section 10.2.2

Listing 10.12 Fine-tuning GPT-2 with Hugging Face’s Trainer class
>>> from transformers import Trainer
>>> ft_model = GPT2LMHeadModel.from_pretrained("gpt2")    #1

>>> trainer = Trainer(
...        ft_model,
...        training_args,
...        data_collator=collator,           #2
...        train_dataset=train_dataset,    #3
...        eval_dataset=eval_dataset)
>>> trainer.train()

The Trainer combines a fresh pretrained GPT-2 model, training arguments, a data collator, and training and evaluation datasets. section 10.2.2

Comparing before and after fine-tuning

With the prompt “NLP is,” the fine-tuned model produces “NLP is not the only way to express ideas and understand ideas.” Comparing continuations from the original and fine-tuned models can reveal a change in generation style, but an individual output does not establish accuracy. section 10.2.2

GPT-2 is also an example of a causal model that could supply the generation side of a semantic-search question-answering pipeline. The demonstrated retrieval-and-generation pipeline instead uses FLAN-T5, not GPT-2, and instructs it to say when the retrieved sources do not answer a question. section 10.3.11

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Works through tokenization, logits, sampling, and a fine-tuning workflow using pretrained components.
Examples
Compares continuations for NLP and neural-network prompts before and after fine-tuning on manuscript sentences.
What it assumes
Assumes prior PyTorch training experience while introducing pretrained GPT-2 loading and generation.
What you can do after
Apply GPT-2 via Hugging Face Transformers to generate text, inspect next-token probabilities, and fine-tune on a text corpus.
How it connects
Connects GPT-2 with tokenization, nucleus sampling, fine-tuning, semantic search, and question answering.

Also explained in

Compare how 6 books explain GPT-2 →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.