Chapter 11: NLP Fundamentals
Master the foundations of Natural Language Processing, from text preprocessing and tokenization to word embeddings that capture semantic meaning. Learn to build text classification systems and understand the transformer architecture that powers modern language models like BERT and GPT.
- Topics
- 4
- Demos
- 4
- Min read
- 34
Chapter Overview
Natural Language Processing (NLP) enables machines to understand, interpret, and generate human language. This field has undergone a dramatic transformation with the advent of deep learning, particularly the Transformer architecture introduced in 2017.
Traditional NLP relied heavily on hand-crafted features and rule-based systems. Modern NLP leverages neural networks that learn representations directly from raw text, capturing nuances of meaning, context, and linguistic structure that were previously impossible to encode manually.
The key insight driving modern NLP is that words and sentences can be represented as dense vectors (embeddings) in a continuous space where semantic relationships are preserved. Words with similar meanings cluster together, and analogies can be computed through vector arithmetic.
This chapter covers:
- Text Processing: Converting raw text into numerical form through tokenization, handling vocabulary, and special tokens
- Word Embeddings: Dense vector representations that capture semantic relationships between words
- Text Classification: Building models for sentiment analysis, spam detection, and topic categorization
- Transformers: The attention-based architecture behind BERT, GPT, and all modern language models
Chapter Roadmap
Click any topic to jump in
Text Processing
Tokenization, vocabulary building, and TF-IDF — converting raw text into numerical representations for models.
Word Embeddings
Dense vector representations that capture semantic meaning — Word2Vec, GloVe, and contextual embeddings from transformers.
Classification and generation
Text Classification
Bag of words to fine-tuned transformers — sentiment analysis, spam detection, and multi-label categorization.
Transformers
BERT, GPT, and T5 — pre-trained architectures that dominate modern NLP through self-supervised learning.
Topics
4 topics in this chapter
The previous chapter, CNNs and Sequence Models, ended with attention and the Transformer, which turn a sequence of vectors into a sequence of better vectors. Text, though, does not arrive as vectors. It arrives as a string of characters such as 'The movie wasn't great!', and a neural network can only multiply numbers. Somewhere between the raw string and the first layer, the text must be cut into units, and each unit must get an integer id. Which units should we choose? Whole words leave every rare or misspelled word unknown, while single characters make sequences very long and push the job of spelling onto the model.
This chapter, NLP Fundamentals, follows text from raw string to trained model. This topic covers the first step. It starts with tokenization, especially subword methods such as BPE and WordPiece. It then covers classic preprocessing such as lowercasing and stemming, and when modern models skip it. Next comes the vocabulary that maps tokens to ids and handles unknown tokens. The topic closes with special tokens such as [CLS], [SEP], and [PAD].
Definition
Tokenization is the deterministic mapping from a raw string to a sequence of tokens drawn from a fixed vocabulary , each replaced by its integer id in . Subword tokenizers such as BPE, WordPiece, and Unigram learn from a corpus, so frequent words remain single tokens and rare words split into known pieces.
In this topic
- 1Tokenization
- 2Text Preprocessing
- 3Vocabulary
- 4Special Tokens
Tokenization
Tokenization decides what a model sees as one symbol. Word-level tokenizers split on spaces and punctuation, which is intuitive but needs a huge vocabulary and still meets unseen words. Character-level tokenizers never meet an unknown symbol, but they make sequences several times longer. Subword methods sit between the two. Byte-Pair Encoding starts from characters and repeatedly merges the most frequent adjacent pair until the vocabulary reaches a target size, often 30,000 to 50,000. WordPiece, used by BERT, picks merges by likelihood gain and marks word-internal pieces with ##. Frequent words stay whole, and rare words break into known pieces. The pieces do not always match morphemes.
Byte-Pair Encoding starts with a character vocabulary and repeatedly merges the most frequent adjacent pair until the vocabulary reaches size . Each merge rescans the pair counts, so naive training costs for corpus size , though efficient implementations update counts incrementally. Applying the learned merges to a word of length costs at most . A 30,000 to 50,000 token vocabulary typically produces sequences several times shorter than character-level tokenization while still covering any input. Byte-level BPE, as in GPT-2, starts from the 256 byte values, so no string is ever out of vocabulary.
Tokenize 'unhappiness' using word-level vs BPE (subword). Which handles rare words better?
Text Preprocessing
Classic NLP pipelines normalize text before counting words: lowercasing, stripping punctuation, removing stopwords such as 'the', and reducing words to a base form. Stemming chops suffixes by rule, so Porter's stemmer maps 'running' to 'run' but may produce non-words such as 'studi'. Lemmatization uses a dictionary and part of speech, so it maps 'ran' to 'run'. For count-based models such as TF-IDF, this merges spellings of the same concept into one feature and shrinks a sparse vocabulary. For pretrained Transformers, it usually hurts: the model was trained on raw text, and case, punctuation, and 'not' all carry meaning it can use.
Stemming applies rule-based suffix stripping, such as Porter's algorithm with its five phases of rules, in per word, while lemmatization uses a dictionary and part-of-speech tags to find the base form. Both merge rows of the term-document matrix, which helps count-based models by pooling sparse counts. Modern subword tokenizers do not perform this normalization: bert-base-uncased keeps 'running' and 'ran' as separate whole tokens, and its WordPiece splits 'unhappiness' as un, ##ha, ##pp, ##iness, pieces that follow corpus statistics rather than morphemes. The network learns the shared meaning from context instead.
'Running' vs 'ran' — should we lemmatize for BERT? For TF-IDF?
Vocabulary
The vocabulary is the lookup table from token string to integer id, built once from the training corpus and then frozen. Every id indexes a row of the embedding matrix, so vocabulary size sets both the embedding parameter count and the size of the output softmax. Tokens absent from the table either map to a reserved [UNK] id, which discards their identity, or, with subword tokenizers, are split into smaller pieces that are present. Byte-level BPE, used by GPT-2, includes all 256 bytes, so no input is ever unknown. The trade-off: a bigger vocabulary gives shorter sequences but more parameters and rarer, less trained tokens.
A vocabulary of size maps tokens to integers in , enabling lookup via hash tables. The embedding matrix has parameters: for and , that is 38.4 million parameters before any Transformer layer. Zipf's law, word frequency for rank , means a small set of frequent words covers most running text, while a long tail of rare words, names, and typos never appears often enough to earn its own entry. Subword methods handle that tail by composing it from shared pieces.
Vocab: {'the':0, 'cat':1, 'sat':2, [UNK]:3}. Encode 'the dog sat'. What happens?
Special Tokens
Special tokens are reserved vocabulary entries that carry structure rather than text. In BERT, [CLS] is prepended to every input, and its final hidden state serves as the summary vector for classification. [SEP] ends a segment and separates sentence pairs, while segment ids of 0 and 1 tell the model which sentence each token belongs to. [PAD] fills shorter sequences so a batch forms a rectangle, and an attention mask of zeros stops real tokens from attending to padding. [MASK] replaces hidden words during masked language model pretraining. GPT-style models use different markers, such as an end-of-text token.
Special tokens partition the input for the model: [CLS] at position 0 aggregates sequence-level information via attention (its final hidden state serves as the sequence representation for classification), [SEP] signals segment boundaries, and [PAD] fills sequences to uniform length with attention mask values of 0. The attention mask prevents computation from wasting cycles on padding — masked positions contribute zero to the attention-weighted sum.
BERT input for sentiment classification of 'great movie'. How is it formatted?
Theory Exercise
Problem:
A corpus has 50,000 unique words. Word-level tokenization yields a vocabulary of 50,000 with frequent [UNK] tokens at test time. Why does a BPE vocabulary of only 32,000 subword tokens both shrink the embedding table AND eliminate out-of-vocabulary tokens?
Hints:
- Think about what BPE starts from before any merges
- Any word can be decomposed into smaller pieces
- Relate vocabulary size to the embedding matrix dimensions
Coding Exercise
Problem:
Compare how a word-level split and a pre-trained subword tokenizer (BERT's WordPiece) handle a rare/compound word. Show that the subword tokenizer avoids out-of-vocabulary tokens by decomposing the word into pieces.
Hints:
- Use AutoTokenizer.from_pretrained('bert-base-uncased') from the transformers library
- Call tokenizer.tokenize(text) to see the subword pieces (## marks a continuation piece)
- Compare the naive text.split() word list against the subword pieces
Related Problems on PixelBank
The previous topic, Text Processing, turned text into a sequence of integer ids. An id, though, says nothing about meaning. Id 2307 for 'great' is no closer to 'good' than to 'table', and a one-hot vector of length 30,000 puts every pair of words at the same distance. A model fed one-hot inputs must learn from scratch, separately for each word, that 'excellent' and 'great' behave alike. Can we give each word a short dense vector so that words used in similar ways land near each other?
The distributional hypothesis says yes: a word is characterized by the company it keeps. This topic starts with Word2Vec, which learns vectors by predicting nearby words and produces the famous king minus man plus woman result. GloVe reaches similar vectors by factorizing global co-occurrence counts. The embedding layer is the trainable lookup table every neural NLP model starts with. The topic closes with contextual embeddings from models such as BERT, which give the same word a different vector in each sentence.
Definition
A word embedding maps each vocabulary item to a dense vector , typically with between 100 and 1,024, stored as row of a matrix . Embeddings are learned so that geometric closeness, usually cosine similarity, reflects similarity of use. Contextual embeddings instead compute each token's vector from its whole sentence.
In this topic
- 1Word2Vec
- 2GloVe
- 3Embedding Layer
- 4Contextual Embeddings
Word2Vec
Word2Vec learns embeddings from a prediction task on raw text. Skip-gram takes each word and predicts the words within a small window around it; CBOW does the reverse, predicting the center word from the average of its neighbors. Instead of a full softmax over the vocabulary, negative sampling trains a logistic classifier to tell real word-context pairs from random ones, with noise words drawn in proportion to frequency to the 3/4 power. Words that appear in similar contexts receive similar gradients and end up with similar vectors, usually 100 to 300 dimensions. Each word gets exactly one vector, so all senses of an ambiguous word are blended.
Skip-gram Word2Vec maximizes with negative samples drawn from a noise distribution . The exponent flattens the frequency distribution so rare words get sampled more often. The resulting vectors encode linear relationships: because the training objective preserves co-occurrence ratios.
Word2Vec trained on text. vec('king') - vec('man') + vec('woman') ≈ ?
GloVe
GloVe, Global Vectors, starts from the corpus-wide co-occurrence matrix , where counts how often word appears near word . It then fits vectors so that the dot product of two word vectors plus two biases approximates , using weighted least squares. A weighting function caps very frequent pairs and gives zero weight to pairs that never co-occur, so only the nonzero entries are visited. The motivation is that ratios of co-occurrence probabilities carry meaning: 'ice' co-occurs with 'solid' far more than 'steam' does. GloVe and Word2Vec reach similar quality; Levy and Goldberg showed that skip-gram implicitly factorizes a shifted PMI matrix.
GloVe factorizes the log co-occurrence matrix: minimize where counts how often word appears near word , and is a weighting function that caps frequent pairs. This is a weighted least-squares problem on a sparse matrix, solvable in for iterations. Unlike Word2Vec's stochastic sampling, GloVe uses global statistics, which can be more data-efficient on smaller corpora.
How does GloVe differ from Word2Vec in training?
Embedding Layer
An embedding layer is a trainable matrix with one row per vocabulary entry and one column per dimension. The forward pass simply looks up row for token id , which is mathematically the same as multiplying a one-hot vector by but far cheaper. During backpropagation only the rows of tokens present in the batch receive gradient, so updates are sparse. The layer can start random and learn with the task, or start from pretrained vectors such as GloVe and then be fine-tuned or frozen. Its parameter count, vocabulary size times dimension, is often a large share of a small model.
An embedding layer is a lookup table that maps token ID to row . The forward pass is per token (array indexing). The gradient is nonzero only for tokens that appeared in the batch — this sparsity enables efficient updates. Initializing with pre-trained embeddings (GloVe, Word2Vec) and fine-tuning gives a warm start: the model begins with semantic structure rather than random vectors.
Vocab size 50K, embedding dim 256. How many parameters in the embedding layer?
Contextual Embeddings
Static embeddings give every occurrence of a word the same vector, so 'bank' in 'river bank' and 'bank account' are identical. Contextual embeddings come from a model that reads the whole sentence. ELMo used bidirectional LSTMs; BERT and GPT use Transformer layers, where self-attention mixes each token's vector with those of its neighbors at every layer. The output vector for a token is therefore a function of the entire input, so different senses land in different regions of the space. These vectors are not stored in a table: they are computed on the fly, which costs a forward pass but resolves ambiguity.
Static embeddings assign one vector per word type: regardless of context. Contextual embeddings from BERT compute at layer as a function of the entire input sequence, so 'river bank' and 'bank account' produce different vectors. The context is injected through self-attention: each token's representation is a weighted sum of all other tokens' representations, with weights learned to capture syntactic and semantic dependencies.
Word2Vec: 'bank' has one vector. BERT processes 'river bank' and 'bank robbery'. How many vectors for 'bank'?
Theory Exercise
Problem:
Word2Vec famously gives vec('king') - vec('man') + vec('woman') ≈ vec('queen'). Explain why a training objective that only predicts nearby context words ends up producing vectors whose DIFFERENCES encode relationships like gender or capital-city.
Hints:
- Words that share context words end up with similar vectors
- Think about what 'king' and 'queen' have in common in their contexts, and what differs
- The skip-gram objective is tied to co-occurrence statistics
Coding Exercise
Problem:
Train a small Word2Vec model with gensim on a toy corpus, then query the nearest neighbours of a word and inspect the learned vector dimensionality.
Hints:
- Use gensim.models.Word2Vec with a list of tokenized sentences
- Set vector_size (e.g. 50) and a small min_count so rare toy words survive
- model.wv.most_similar('word') returns the closest words by cosine similarity
Related Problems on PixelBank
The previous topic, Word Embeddings, gave every word, and with contextual models every token, a dense vector that captures meaning. Most real NLP work, though, asks a question about a whole text. Is this review positive? Is this email spam? Is this ticket about billing or a bug? Which of 20 topics does this article cover? A review may be 5 words or 500, and the classifier still has to produce one fixed-size answer. How do we turn a variable-length sequence of tokens into a single label, and how much does word order matter along the way?
Text classification answers this in several generations of models. This topic starts with bag of words, which ignores order, counts words into a sparse vector, and pairs well with TF-IDF weights and a linear classifier. Recurrent networks read the tokens in order and classify from a hidden state. Fine-tuning BERT adds a small head on top of a pretrained Transformer and is the strong default today. The topic closes with multi-label classification, where one text can carry several labels at once.
Definition
Text classification learns a function that assigns each document one of labels, or, in the multi-label case, a subset of them. The model first maps the variable-length token sequence to a fixed-size vector, by counting, recurrence, or pooled Transformer states, then applies a classifier trained with cross-entropy loss.
In this topic
- 1Bag of Words
- 2RNN/LSTM Classification
- 3Fine-tuning BERT
- 4Multi-label Classification
Bag of Words
Bag of words represents a document as a vector with one entry per vocabulary word, holding its count or presence; word order is discarded. TF-IDF reweights each count by the log of the number of documents divided by the number containing the word, so common words fade and distinctive ones stand out. The vectors are high-dimensional and over 99 percent zeros, stored sparsely, and a linear model such as logistic regression or a linear SVM on top is fast, strong, and interpretable. The weakness is order: 'dog bites man' and 'man bites dog' get identical vectors. Adding n-grams, adjacent word pairs, recovers some local order.
Bag of Words represents a document as where is the count (or binary presence) of word . This ignores word order: 'dog bites man' and 'man bites dog' have identical representations. TF-IDF refines this by weighting: , downweighting common words and highlighting distinctive ones. The document-term matrix is typically 99%+ sparse, enabling efficient storage with sparse matrices.
'not good' vs 'good' — what's the limitation of bag of words for sentiment?
RNN/LSTM Classification
A recurrent classifier embeds each token, runs an LSTM or GRU across the sequence, and feeds a summary vector to a softmax layer. The simplest summary is the final hidden state, which must compress the whole text; max pooling or attention over all hidden states usually works better on long inputs. A bidirectional LSTM runs a second LSTM from right to left and concatenates both directions, so every position sees its full context. Recurrent models capture order and negation that bag of words misses, but they process tokens one at a time, which limits parallelism, and they were largely replaced by Transformers after 2018.
For classification, the final hidden state (or concatenation of BiLSTM states ) is fed to a linear classifier: . The total compute is — linear in sequence length but with a large constant from the recurrent weight multiplications. Attention pooling over all hidden states often outperforms using only the final state.
BiLSTM for sentiment: 'The movie was not good but the acting saved it.' Which direction captures 'saved' affecting 'not good'?
Fine-tuning BERT
Fine-tuning BERT for classification adds one linear layer that maps the final [CLS] vector, 768 numbers in BERT-base, to class logits, then trains the whole network on labeled data with a small learning rate, typically 2e-5 to 5e-5 for 2 to 4 epochs. Pretraining already taught the network syntax and word meaning, so a few thousand labels often beat models trained from scratch on far more. With very little data or compute, a cheaper option is to freeze the encoder and train only the head, or the head plus the top layers. Too high a learning rate can erase pretrained knowledge, sometimes called catastrophic forgetting.
Fine-tuning BERT adds a classification head on the [CLS] token: where . The full model has about 110 million parameters, but the new head has only parameters for classes, 1,538 for binary sentiment. Because every other weight starts from a good pretrained solution, full fine-tuning with a small learning rate moves them only slightly, which is why it works even on datasets of a few thousand examples. Freezing the encoder, so that only parameters train, is the fallback for tiny datasets or tight compute.
BERT-base: 110M params. Your dataset: 5K samples. Fine-tune all layers or freeze some?
Multi-label Classification
In multi-label classification a text can carry any subset of labels: a film can be funny and romantic at once. Softmax is the wrong output, because it forces the probabilities to sum to 1, so raising one label lowers the others. Instead each label gets its own sigmoid, an independent yes or no probability, and the loss is binary cross-entropy summed over labels. At prediction time each label is thresholded separately, often at 0.5, though tuning one threshold per label on validation data usually raises F1, especially for rare labels. Evaluation uses micro- or macro-averaged F1 rather than plain accuracy.
Multi-label uses independent sigmoid outputs instead of softmax, with binary cross-entropy per label: . Since labels are independent, the output is (not a probability simplex). The expected number of positive labels can exceed 1. Threshold selection per label (not just 0.5) is often needed: optimize the threshold on validation F1 independently for each class.
Movie review can be 'funny', 'scary', and 'romantic' (all apply). Why sigmoid not softmax?
Theory Exercise
Problem:
A bag-of-words sentiment classifier represents 'not good' and 'good' almost identically and predicts both as positive. Explain the root cause, and describe two ways to give the model access to the negation without abandoning a linear classifier.
Hints:
- What information does a multiset of word counts discard?
- Could a feature represent a short sequence of words?
- Think about n-grams
Coding Exercise
Problem:
Build a classic TF-IDF + logistic regression sentiment classifier with scikit-learn, and show that adding bigram features (so negation like 'not good' is captured) improves accuracy over unigrams alone.
Hints:
- Use TfidfVectorizer; control n-grams with ngram_range=(1,1) vs (1,2)
- Chain the vectorizer and LogisticRegression in a Pipeline
- Use fetch_20newsgroups or a small custom labeled list, then compare test accuracy of both pipelines
Related Problems on PixelBank
The previous topic, Text Classification, ended with fine-tuning BERT, a pretrained Transformer, as the strong default. That raises a broader question. The Transformer architecture from the previous chapter is one building block, yet BERT, GPT, and T5 use it in visibly different ways, and each is good at different jobs. BERT is hard to use for writing text, GPT was long weaker at classification for its size, and T5 rewrites every task as text in, text out. What distinguishes them, and how should you choose one, and then adapt it to your task without retraining hundreds of millions of weights?
The answer lies in two choices: which tokens each position may attend to, and which objective the model is pretrained on. This topic starts with BERT, an encoder pretrained to fill in masked words using both directions. GPT is a decoder pretrained to predict the next token from the left only. T5 combines an encoder and a decoder and casts every task as text-to-text. The topic closes with fine-tuning strategies, from full fine-tuning to frozen backbones and LoRA.
Definition
A pretrained Transformer is a stack of self-attention layers trained on large unlabeled corpora with a self-supervised objective, then adapted to downstream tasks. Encoder-only models such as BERT use bidirectional attention and masked language modeling; decoder-only models such as GPT use causal attention and next-token prediction; encoder-decoder models such as T5 map an input sequence to an output sequence.
In this topic
- 1BERT (Bidirectional)
- 2GPT (Autoregressive)
- 3T5 (Encoder-Decoder)
- 4Fine-tuning Strategies
BERT (Bidirectional)
BERT is a stack of Transformer encoder layers; BERT-base has 12 layers, hidden size 768, 12 heads, and 110 million parameters. It is pretrained with masked language modeling: 15 percent of input tokens are selected, and of those 80 percent become [MASK], 10 percent a random token, and 10 percent stay unchanged; the model must recover the originals. Because attention is bidirectional, each prediction uses context on both sides. The original recipe also had next-sentence prediction, which RoBERTa later showed was unnecessary. BERT produces excellent representations for classification, tagging, and extractive question answering, but it has no natural left-to-right way to generate text.
BERT's masked language modeling objective randomly masks 15% of tokens and predicts them: . The bidirectional attention gives each masked token access to both left and right context, making prediction easier than left-to-right LM. BERT-base has layers, , heads, totaling 110M parameters. The [CLS] token's final representation is a 768-dimensional summary of the entire input.
BERT pretraining: 'The [MASK] sat on the mat.' What does BERT learn to predict?
GPT (Autoregressive)
GPT is a stack of Transformer decoder layers with a causal mask, so position attends only to positions up to . It is pretrained to predict the next token, which uses every position of every text as a training example with no labels needed. Generation is a loop: run the model, pick a token from the output distribution by greedy choice or sampling, append it, and repeat; a key-value cache avoids recomputing earlier positions. Scaling this recipe from GPT-2's 1.5 billion parameters to GPT-3's 175 billion produced few-shot learning from prompts alone. The cost is that every output token needs its own forward pass.
GPT's causal language modeling maximizes using a causal attention mask with for . Generation is sequential: each new token requires a forward pass. Without caching, step recomputes attention over all positions, work; a key-value cache stores past keys and values, so step costs for attention, at the price of memory that grows linearly with context. Kaplan et al. (2020) found that test loss falls as a power law in model size, , which motivated scaling GPT-2 to GPT-3.
GPT-3 prompt: 'The capital of France is'. How does GPT generate the answer?
T5 (Encoder-Decoder)
T5, the Text-to-Text Transfer Transformer, keeps the original encoder-decoder layout: an encoder reads the input bidirectionally, and a decoder generates the output causally while cross-attending to the encoder's states. Every task becomes text in and text out, marked by a prefix such as 'translate English to German:' or 'summarize:', and even labels are generated as words, so one model, one loss, and one decoding procedure cover translation, summarization, classification, and question answering. Pretraining uses span corruption: random spans are replaced by sentinel tokens and the decoder reproduces them. The cost is two stacks, and generating labels as text can occasionally produce invalid outputs.
T5 frames all tasks as text-to-text: input 'translate English to French: hello' outputs 'bonjour'. The encoder-decoder architecture uses cross-attention where decoder queries attend to encoder keys and values: . This separates understanding (encoder) from generation (decoder). With relative positional encodings instead of absolute sinusoids, T5 generalizes better to sequence lengths unseen during training.
How does T5 frame sentiment classification as text-to-text?
Fine-tuning Strategies
Adapting a pretrained Transformer ranges from cheap to expensive. Feature extraction freezes the backbone and trains only a new head. Full fine-tuning updates every weight; it is usually most accurate but stores a full model copy per task. Parameter-efficient methods train a tiny add-on. LoRA freezes each weight matrix and learns an update , where is and is with rank much smaller than ; starts at zero, so training begins from the original model. Adapters and prompt tuning are relatives. LoRA updates can be merged into after training, adding no inference latency.
LoRA reparameterizes a frozen weight as with , , and . Trainable parameters per matrix fall from to : for and , from 589,824 to 12,288, a 48x reduction. Initializing makes at the start, so training begins exactly at the pretrained model. Hu et al. (2021) report that ranks as low as 1 to 8 on the query and value projections match full fine-tuning on GPT-3, consistent with a low intrinsic rank of task adaptation.
BERT has 110M params. LoRA fine-tuning adds 0.3M params. How does it achieve similar performance?
Theory Exercise
Problem:
BERT (encoder-only, masked language modeling) excels at understanding tasks like classification, while GPT (decoder-only, next-token prediction) excels at generation. Explain how each model's attention mask and pre-training objective makes it suited to its strengths, and why BERT is awkward for free-form generation.
Hints:
- Compare bidirectional vs causal (left-to-right) attention
- What does each objective ask the model to predict?
- Generation requires producing one token at a time from left context only
Coding Exercise
Problem:
Use a pre-trained transformer from Hugging Face two ways: (1) run a zero-config sentiment pipeline, and (2) load BERT and inspect that the [CLS] token produces a 768-dimensional pooled representation used as the sequence summary for classification.
Hints:
- transformers.pipeline('sentiment-analysis') gives an end-to-end classifier
- AutoModel.from_pretrained('bert-base-uncased') returns hidden states; the first token (index 0) is [CLS]
- The last_hidden_state has shape (batch, seq_len, 768) for BERT-base