Chapter 7: Deep transfer learning for NLP with the transformer and GPT
This introduction contrasts transformer attention and scaling with earlier NLP architectures and summarizes GPT, BERT, and multilingual BERT.
After this chapter you will be able to
- Transformer attention and scaling. Explain how the transformer differs from earlier sequence models and why transformer-based models can scale effectively.
- GPT and BERT objectives. Distinguish GPT's causal modeling objective from BERT's training objectives and describe the kinds of tasks each is suited for.
- Multilingual BERT pretraining. Describe what mBERT is pretrained on and what kind of transfer learning it is suited for.
- Self attention and recurrence. Explain how self-attention relates parts of a sequence and why the transformer replaces recurrent components.
- Stacked architecture and positions. Describe the transformer's encoder and decoder stacks and the roles of embeddings and positional encodings.
- Encoder and decoder layers. Distinguish the encoder and decoder layers and describe what their attention mechanisms relate.
- Pretrained BERT input preparation. Describe how to prepare the example sentence for a pretrained model in the transformers library, including the tokenizer and vocabulary indices.
- BERT special and subword tokens. Explain the roles of BERT's example special tokens and describe the subword split shown in the sentence.
- Self-attention visualization workflow. Describe how the example uses visualization tools to inspect BERT self-attention and what caution the section gives about interpreting it.
- Contextual token dependencies. Explain how self-attention helps a transformer capture context by considering relationships between tokens in a sequence.
- Attention coefficient calculation. Trace how query and key vectors produce attention coefficients for a current token, including how the query, key, and value vectors are obtained.
- Parallel and vectorized computation. Explain why self-attention weight calculations can be parallelized and vectorized, unlike the sequential processing of a recurrent model.
- Multiple relationship representations. Describe how multihead attention extends self-attention to represent different kinds of relationships.
- Residual connections and normalization. Explain where residual connections and normalization occur in the transformer and what each contributes.
- Encoder-decoder attention inputs. Describe where keys, values, and queries in encoder-decoder attention come from and what tokens the resulting attention connects.
- Positional encoding of tokens. Explain why positional embeddings are added to token embeddings and how they represent position in the original transformer.
- Pretrained translation model selection. Describe how the example uses a pretrained MarianMT model and tokenizer for English-to-Twi translation, and how the model identifier can select another available language pair.
- Translation baseline and limitations. Explain why the English-to-Twi model is a useful but imperfect baseline, considering its training data and example translations.
- GPT semisupervised transfer learning. Explain how GPT combines language-model pretraining with fine-tuning, and describe the reported breadth of its improvements.
- Causal and masked objectives. Distinguish GPT’s causal modeling objective from BERT’s masked language modeling objective, and relate GPT to its preferred application.
- Decoder Stack and Masking. Explain how GPT’s decoder stack differs from BERT and how masked self-attention supports next-token prediction.
- Task Adaptation through Inputs. Explain how GPT can handle different tasks without changing its architecture, using textual entailment as an example.
- Transformers Pipeline API. Explain what a transformers pipeline provides and why it simplifies common inference tasks.
- Prompted GPT Text Generation. Describe how the section uses GPT-2 to continue a prompt and control the length of generated text.
- Generated Text Quality Limits. Explain the strengths and limitations observed in the creative and technical continuations.
- DialoGPT conversational adaptation. Explain how DialoGPT adapts GPT for conversation and what data was used to fine-tune it.
- Chatbot response generation loop. Trace how the example generates responses over successive conversational turns.
- Local context size trade-off. Explain the problem that can arise in longer chatbot conversations and the trade-off involved in limiting context.
What it builds on
- Bidirectional Encoder Representations from Transformers (BERT) (chapter 3) · Introduced BERT in the earlier benchmarking context.
- ELMo bidirectional language modeling (chapter 6) · Introduces bidirectional recurrent language modeling as another way to capture context.
Section by section
Introduction
This introduction contrasts transformer attention and scaling with earlier NLP architectures and summarizes GPT, BERT, and multilingual BERT.
- Transformer attention and scaling: Explain how the transformer differs from earlier sequence models and why transformer-based models can scale effectively.
Why it matters: This distinction sets up why transformers became a practical foundation for larger NLP models. - GPT and BERT objectives: Distinguish GPT's causal modeling objective from BERT's training objectives and describe the kinds of tasks each is suited for.
Why it matters: The models' training objectives help distinguish their representative applications. - Multilingual BERT pretraining: Describe what mBERT is pretrained on and what kind of transfer learning it is suited for.
Why it matters: This explains why a multilingual checkpoint is useful for transfer across languages.
Key terms: transformer, attention, recurrent, convolutional, parallel computing, GPT, causal modeling objective, BERT, masked modeling objective, next sentence prediction
7.1 The transformer
This section introduces the motivation and high-level structure of the transformer encoder-decoder architecture.
- Self attention and recurrence: Explain how self-attention relates parts of a sequence and why the transformer replaces recurrent components.
Why it matters: This explains the main departure from recurrent translation models. - Stacked architecture and positions: Describe the transformer's encoder and decoder stacks and the roles of embeddings and positional encodings.
Why it matters: This gives you a map of the transformer and explains how it retains information about order. - Encoder and decoder layers: Distinguish the encoder and decoder layers and describe what their attention mechanisms relate.
Why it matters: This distinguishes attention within a sequence from attention connecting the encoder and decoder.
Key terms: self-attention, recurrence, parallelization, encoder, decoder, embeddings, positional encodings, encoder-decoder attention, feedforward neural network, masked
7.1.1 An introduction to the transformers library and attention visualization
This section introduces pretrained BERT tokenization and uses attention visualization to explore its encoder layers.
- Pretrained BERT input preparation: Describe how to prepare the example sentence for a pretrained model in the transformers library, including the tokenizer and vocabulary indices.
Why it matters: This connects a sentence to the numeric inputs used by the pretrained model. - BERT special and subword tokens: Explain the roles of BERT's example special tokens and describe the subword split shown in the sentence.
Why it matters: These tokens help you interpret what the BERT tokenizer produces from a sentence. - Self-attention visualization workflow: Describe how the example uses visualization tools to inspect BERT self-attention and what caution the section gives about interpreting it.
Why it matters: Visual inspection provides an initial feel for attention while reminding you not to overinterpret every display. - BERT and transformer encoders: State the relationship the section draws between the BERT encoder and the original transformer encoder.
Why it matters: This explains why a BERT encoder is used to introduce transformer self-attention.
Key terms: transformers, tokenizer, vocabulary, indices, special tokens, [CLS], [SEP], subword, bertviz, self-attention
7.1.2 Self-attention
This section explains how transformer self-attention detects contextual relationships, computes attention weights in parallel, and extends to multiple attention heads.
- Contextual token dependencies: Explain how self-attention helps a transformer capture context by considering relationships between tokens in a sequence.
Why it matters: This explains what self-attention contributes to understanding a sentence in context. - Attention coefficient calculation: Trace how query and key vectors produce attention coefficients for a current token, including how the query, key, and value vectors are obtained.
Why it matters: This shows how the model turns token representations into attention weights. - Parallel and vectorized computation: Explain why self-attention weight calculations can be parallelized and vectorized, unlike the sequential processing of a recurrent model.
Why it matters: This is a key reason transformers can process long sequences more parallelizably than recurrent models. - Multiple relationship representations: Describe how multihead attention extends self-attention to represent different kinds of relationships.
Why it matters: Multiple attention heads provide a way to represent more than one kind of relationship in a sentence.
Key terms: self-attention, tokens, dependencies, context, query vector, key vector, value vector, input embedding, dot product, softmax
7.1.3 Residual connections, encoder-decoder attention, and positional encoding
This section briefly explains residual connections and normalization, encoder-decoder attention, and positional encoding in the transformer.
- Residual connections and normalization: Explain where residual connections and normalization occur in the transformer and what each contributes.
Why it matters: These features help explain how the transformer maintains workable gradients and feature scales. - Encoder-decoder attention inputs: Describe where keys, values, and queries in encoder-decoder attention come from and what tokens the resulting attention connects.
Why it matters: This explains how the decoder attends to the input sequence when producing output. - Positional encoding of tokens: Explain why positional embeddings are added to token embeddings and how they represent position in the original transformer.
Why it matters: Positional encoding supplies sequence-position information that the described self-attention operation otherwise lacks.
Key terms: residual connection, normalization layer, vanishing and/or exploding gradients, encoder-decoder attention, keys, values, queries, encoder stack, positional encoding, positional embeddings
7.1.4 Application of pretrained encoder-decoder to translation
This section uses a pretrained encoder-decoder model to translate English into Twi and examines its output and limitations as a low-resource translation baseline.
- Pretrained translation model selection: Describe how the example uses a pretrained MarianMT model and tokenizer for English-to-Twi translation, and how the model identifier can select another available language pair.
Why it matters: You can reuse an existing translation model without building an encoder-decoder from scratch. - Translation baseline and limitations: Explain why the English-to-Twi model is a useful but imperfect baseline, considering its training data and example translations.
Why it matters: A plausible translation is not necessarily correct, and biased training data constrain how confidently a baseline can be used. - Tokenizer output differences: Describe the visible translation output markers and why the section recommends checking tokenizer documentation.
Why it matters: Recognizing tokenizer-specific output helps you avoid treating formatting markers as ordinary translated words.
Key terms: MarianMTModel, encoder-decoder, Helsinki-NLP, tokenizer, JW300, parallel translated datasets, baseline, transfer learning, SentencePiece, WordPiece
7.2 The Generative Pretrained Transformer
This section introduces GPT’s semisupervised transfer-learning approach and contrasts its language-modeling objective with BERT’s.
- GPT semisupervised transfer learning: Explain how GPT combines language-model pretraining with fine-tuning, and describe the reported breadth of its improvements.
Why it matters: This is the transfer-learning setup that made GPT useful across language-understanding tasks. - Causal and masked objectives: Distinguish GPT’s causal modeling objective from BERT’s masked language modeling objective, and relate GPT to its preferred application.
Why it matters: The training objective helps distinguish GPT’s text-generation role from BERT’s approach.
Key terms: Generative Pretrained Transformer, semisupervised learning, unsupervised pretraining, self-supervised pretraining, supervised fine-tuning, causal modeling objective, CLM, masked language modeling, MLM, text generation
7.2.1 Architecture overview
This section explains GPT’s decoder-based architecture and how input transformations adapt it to different tasks.
- Decoder Stack and Masking: Explain how GPT’s decoder stack differs from BERT and how masked self-attention supports next-token prediction.
Why it matters: This explains why GPT is suited to generating text one token at a time. - Task Adaptation through Inputs: Explain how GPT can handle different tasks without changing its architecture, using textual entailment as an example.
Why it matters: Input transformations let one architecture address tasks beyond text generation. - Question Answering Input Transformation: Describe how the section transforms a multiple-choice question-answering task for GPT and selects an answer.
Why it matters: This example shows how task-specific input formatting enables answer selection with the same model.
Key terms: decoders, masked self-attention, encoder-decoder attention, causality, input transformation, textual entailment, premise, hypothesis, special delimiter token, question answering
7.2.2 Transformers pipelines introduction and application to text generation
This section introduces transformers pipelines and uses GPT-2 text generation to illustrate both the usefulness and limitations of generated continuations.
- Transformers Pipeline API: Explain what a transformers pipeline provides and why it simplifies common inference tasks.
Why it matters: Pipelines offer a simpler way to use pretrained models for common NLP tasks. - Prompted GPT Text Generation: Describe how the section uses GPT-2 to continue a prompt and control the length of generated text.
Why it matters: A prompt and length limit let you experiment with the kind and amount of text GPT-2 produces. - Generated Text Quality Limits: Explain the strengths and limitations observed in the creative and technical continuations.
Why it matters: Fluent output can help generate ideas, but it still needs scrutiny for coherence and factual accuracy.
Key terms: pipelines, pretrained models, inference, transformers, GPT-2, pipeline, primed, maximum of 100 tokens, max_length, semantic coherence
7.2.3 Application to chatbots
This section applies pretrained DialoGPT to chatbot conversations and discusses its model interface and context-length trade-offs.
- DialoGPT conversational adaptation: Explain how DialoGPT adapts GPT for conversation and what data was used to fine-tune it.
Why it matters: This explains why a GPT-based model can be used as a conversational chatbot. - Chatbot response generation loop: Trace how the example generates responses over successive conversational turns.
Why it matters: The loop shows how conversation history becomes the context for each chatbot response. - Pretrained model loading classes: Describe the GPT-specific and automatic classes available for loading DialoGPT and its tokenizer.
Why it matters: Automatic classes provide a more general way to load the model and tokenizer. - Language model head output: Describe how the LMHead transforms GPT output into next-token probabilities.
Why it matters: The language model head connects GPT's output to a prediction over possible next tokens. - Local context size trade-off: Explain the problem that can arise in longer chatbot conversations and the trade-off involved in limiting context.
Why it matters: Choosing how much history to retain balances response quality against access to earlier context.
Key terms: DialoGPT, GPT, special tokens, fine-tuning, tokenizer, chat history, conversational contribution, pretrained DialoGPT model, GPT2LMHeadModel, GPT2Tokenizer
7.3 Summary
Where this is used later
- Application to fill in the blanks and next-sentence prediction tasks (chapter 8) · Applies BERT to fill-in-the-blanks and next-sentence prediction tasks.
- Cross-lingual learning with multilingual BERT (mBERT) (chapter 8) · Explores cross-lingual learning with multilingual BERT.
- (chapter intro) (chapter 8) · The transformer architecture introduced in the previous chapter.
- Adapters (chapter 10) · The transformer architecture into which adapter layers are introduced.
- Transfer mBERT to monolingual Twi data with the pretrained tokenizer (chapter 8) · A pretrained tokenizer is used to prepare data for mBERT.
- Model architecture (chapter 8) · BERT's architecture is discussed after this introduction to its input tokens.
- Ethical and environmental considerations (chapter 11) · Attention visualization
- Bidirectional Encoder Representations from Transformers (BERT) (chapter 8) · Self-attention over tokens
Concepts explained in this chapter
- text generationText generation is the process of producing a sequence of text, often by predicting successive tokens.
- self-attentionSelf-attention is an attention mechanism that relates positions within a sequence to other positions in that sequence.
- GPT modelGPT is a family of autoregressive transformer language models developed by OpenAI.
- transformer architectureA transformer is a neural network architecture that models sequences using attention mechanisms rather than recurrent connections.
- causal language modelCausal language modeling trains a model to predict the next token from preceding tokens without access to future tokens.
- multi-head attentionMultihead attention is an attention mechanism that computes multiple representations of relationships within an input sequence.
- positional embeddingA method of representing sequence position by adding position-dependent information to token representations.
- machine translationMachine translation is the automatic translation of text or speech from one natural language to another.
- cross-lingual transfer learningA transfer-learning approach that applies knowledge learned from one language to a task involving another language.
- low-resource languageA low-resource language is a language for which relatively little data or other computational resources are available.
- next sentence predictionNext sentence prediction is a pretraining task that predicts whether one text segment follows another in the original text.
- decoderA decoder is a model component that generates an output sequence from an internal representation.
- encoderAn encoder is a model component that transforms an input sequence into an internal representation.
- tokenizationThe process of dividing text into units such as words, subwords, or characters.
- tokenizerA tokenizer is a software component that divides text into tokens and may convert them into model-ready representations.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
