AI & Machine Learning Master Course — 128. Encoder and decoder model families
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 128: Encoder and decoder model families
Prerequisites: Lesson 127. Learning outcome: Match model architectures and training objectives to language tasks.
Choose an information pattern before a model name
Encoder-only, decoder-only, and encoder–decoder describe common transformer arrangements. Their most important distinction is what information each position can use and how outputs are trained. These are architectural families, not absolute restrictions on every possible downstream task.
An encoder commonly lets each valid input position attend to the full input. That is useful when a complete document is available for classification, token labeling, or representation learning. A causal decoder restricts each position to its prefix, making it suitable for autoregressive continuation. An encoder–decoder reads a source with an encoder and generates a target through a causal decoder that can cross-attend to the source.
Architecture and objective must be considered together. A bidirectional encoder is not automatically a sentence embedding model merely because it outputs vectors. A decoder is not automatically factual merely because it generates fluent text. Training data, objectives, adaptation, and evaluation determine useful behavior within the information pattern.
Encoder objectives hide targets deliberately
Masked-language objectives remove or alter selected input tokens and train a model to predict the hidden originals from available context. The surrounding sequence can include both left and right context because the task is reconstruction of deliberately withheld content, not ordinary left-to-right prediction.
If the target token were always visible unchanged at its own position, the model could exploit a trivial copy path. A masking or corruption protocol prevents that shortcut according to the chosen objective. BERT is a well-known encoder-based example, but exact objectives and corruption choices differ across models.
For document classification, an encoder representation can feed a supervised head. The downstream split still needs source independence, and token-level supervision needs correct padding and label alignment. Full input visibility is legitimate only when that full input is actually available at prediction time.
Decoder objectives shift inputs and targets
Autoregressive language modeling factors a sequence probability into conditional next-token probabilities. Training inputs are shifted relative to targets: a prefix ending at one position predicts the following token. A causal mask prevents access to future targets even when all training positions are processed in one matrix operation.
For the sequence [begin, red, box, end], inputs are [begin, red, box] and targets are [red, box, end]. Position one receives the prefix [begin, red] and predicts box. Supplying the unshifted target at the same input position without an appropriate objective would make the task incorrectly easy.
Teacher forcing uses the true preceding tokens during training. During generation, the model conditions on its own generated prefix. This difference can lead to error accumulation. A low teacher-forced loss therefore does not describe every aspect of free-running generation quality.
Encoder–decoder models separate source and target roles
In a translation-like task, the source document can be read fully while the target is generated causally. Decoder self-attention must not inspect future target tokens, but cross-attention can access the encoded source. Source visibility and target visibility are different masks with different purposes.
Text-to-text training can express many tasks as producing an output string from an input string. T5 is an example of an encoder–decoder research framework using this perspective. The representation still needs an explicit target format and evaluation protocol. Converting a classification label into text does not remove label ambiguity or make every answer format equally easy to score.
CPU lab: inspect visibility and next-token loss
This NumPy example constructs the shifted three-position decoder task and prints both a lower-triangular causal mask and an all-visible encoder mask. The target probabilities [0.5,0.25,0.8] are invented for arithmetic. They are not outputs of a trained language model.
Mean negative log-likelihood is −(log 0.5+log 0.25+log 0.8)/3≈0.767528 nats per target token. Exponentiating gives perplexity approximately 2.154435. This quantity summarizes assigned probability to the observed targets under the stated tokenization and weighting; it is not a count of factual errors.
The assertions verify the small visibility matrix and the probability calculation. The unique tokens in this fixture also make it easy to see that each target is absent from its allowed input prefix. In real text, a target token’s spelling may already occur earlier; causality concerns positions, not a ban on repeated token identities.
import numpy as np
sequence = ['<BOS>', 'red', 'box', '<EOS>']
inputs, targets = sequence[:-1], sequence[1:]
causal = np.tril(np.ones((len(inputs), len(inputs)), dtype=int))
bidirectional = np.ones_like(causal)
# Invented target probabilities, not outputs of a trained language model.
prob = np.array([.5, .25, .8])
nll = -np.log(prob).mean()
print('Decoder inputs:', inputs)
print('Next-token targets:', targets)
print('Causal visibility:', causal.tolist())
print('Encoder visibility:', bidirectional.tolist())
print('Mean NLL:', round(float(nll), 6))
print('Perplexity:', round(float(np.exp(nll)), 6))
assert all(t not in inputs[:i + 1] for i, t in enumerate(targets))
assert np.array_equal(causal, [[1, 0, 0], [1, 1, 0], [1, 1, 1]])
assert np.isclose(np.exp(nll), 10 ** (1 / 3))
Compare systems under compatible contracts
Perplexity depends on tokenization and the evaluated data. A model using shorter subword units can have a different per-token scale from a model using whole words. Do not rank models by incompatible perplexity numbers without an appropriate common unit and protocol.
For classification, use task metrics and resource costs. For generation, include correctness, format adherence, unsupported claims, and relevant human judgments. Keep prompt or adaptation choices on development examples. A larger architecture family does not exempt the system from those evaluation rules.
When reviewing code, ask three questions: what is visible, what is predicted, and which positions contribute to loss? Answering them often reveals leakage or alignment mistakes more quickly than memorizing model-brand categories. No pretrained model or framework is executed in this lesson.
Four practice questions with worked answers
Practice 1
Shift [begin, A, B, end] into decoder inputs and targets.
Answer: Inputs are [begin,A,B] and targets are [A,B,end]. Each input position predicts the following token while its attention is restricted to the available prefix.
Practice 2
A model assigns target probabilities 0.5 and 0.5. Find mean NLL and perplexity.
Answer: Mean NLL is −log(0.5)=log(2)≈0.693147 nats. Perplexity is exp(log(2))=2. The value depends on the defined token-level prediction task.
Practice 3
Can a translation decoder attend to the full source sentence while remaining causal over its target?
Answer: Yes. Source input is available before target generation. Causality restricts future target positions, while cross-attention can use all valid encoded source positions.
Practice 4
Why can a target token appear earlier in its own allowed prefix without leakage?
Answer: The earlier occurrence is a different position that was genuinely observed. Leakage means access to unavailable target-position information, not repeated spelling. Natural language routinely repeats words.
Five multiple-choice questions
Question 1
Which visibility pattern is typical of a bidirectional encoder?
- A. Every position can use only tokens strictly after it.
- B. Every position is isolated from all other input positions.
- C. Every valid input position can use the full input sequence.
Correct: C. Full input context is the common encoder pattern. Future-only and isolated processing are different information restrictions.
Question 2
What must causal next-token training align correctly?
- A. Shifted input–target positions and a prefix-respecting mask.
- B. Unshifted input–target positions with only padding masked.
- C. Identical input and target positions with unrestricted visibility.
Correct: A. The model predicts the next position from the available prefix. Unshifted target copying changes the intended task, even if padding is masked.
Question 3
What does teacher forcing supply during training?
- A. Future target tokens as unrestricted decoder inputs.
- B. The true preceding target tokens.
- C. The model’s own sampled tokens at every preceding position.
Correct: B. Teacher forcing conditions on the observed prefix. Free-running sampling and access to future targets are different procedures.
Question 4
What does the lab’s perplexity measure?
- A. Exponentiated average negative log-probability of the stated targets.
- B. The percentage of generated facts that are incorrect.
- C. The number of distinct vocabulary items that must appear in the output.
Correct: A. Perplexity is a probability-based sequence metric under a specified tokenization. It is not a factual-error rate or an output vocabulary constraint.
Question 5
Why are perplexities from different tokenizers not automatically comparable?
- A. All tokenizers assign identical sequence lengths to the same text.
- B. A lower vocabulary size guarantees a lower semantic error rate.
- C. The basic prediction units and per-token averaging can differ.
Correct: C. Different token units change the scale of the metric. Neither equal lengths nor a guaranteed semantic improvement follows from vocabulary size.
Common pitfalls
Avoid unshifted target leakage, confusing source attention with future-target access, comparing incompatible perplexities, and treating an architectural family as a guarantee of factuality. Inspect information visibility and loss positions explicitly.
Summary
Encoder, decoder, and encoder–decoder families provide different information patterns. Their objectives determine what is predicted, while masks and target alignment enforce the task. Evaluation must match both the architecture’s contract and the intended use.