W10 · Transformers: Architecture and Applications
Fall 2026 (115-1) · National Taiwan University (GIND)
NTLDEV 7191 · Fri. 16:30–18:20 · GIND 204Last compiled: 2026-11-06 16:22:26 (Asia/Taipei)
One framework, two ways to turn text into research labels.
Vaswani et al. (2017) · Devlin et al. (2019) · Lab: Liao & Müller (2024), supplied Week 12 notebooks.
How does a Transformer turn a token sequence into contextual representations?
These representations can support a task classifier.
| Text we read | Transformer input |
|---|---|
| A word may be the unit of analysis. | A word may be split into several tokens. |
| A passage contains words and punctuation. | Special tokens mark boundaries or tasks. |
| We interpret the original text. | Token IDs index a model’s vocabulary. |
Token IDs → embedding lookup → input vectors.
Keep the tokenizer matched to the trained model.
My dog is cute. He likes playing.
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Token | [CLS] | my | dog | is | cute | . | he | likes | playing | . | [SEP] |
The bert-base-uncased tokenizer lowercases this input and adds [CLS] and [SEP].
Token vectors + position information → input to the encoder.
My dog is cute.
He likes playing.
Update dog using information from other input positions.
Weighted values → contextual representation.
BertViz · bert-base-uncased, layer 5 / head 5 (zero-based) · Vaswani et al. (2017), §3.2.
BERT can use every input position.
Learned matching scores set the mixing weights.
| Position | Approx. weight | What is being mixed |
|---|---|---|
| he | 0.69 | Information from the position at he |
| [SEP] | 0.26 | Information from this input’s final marker |
| Other 9 positions | 0.05 total | Information from the remaining positions |
Darker line → larger mixing weight.
These weights alone do not prove that he refers to dog.
BertViz · bert-base-uncased, layer 5 / head 5 (zero-based), updating dog · rounded weights from the same model run · Vaswani et al. (2017), §3.2.
One selected BERT head · update the representation at dog.
Attention weights → weighted sum of V → updated vector at dog.
BertViz neuron view · bert-base-uncased, layer 5 / head 5 (zero-based) · Vaswani et al. (2017), §3.2.
Start with token and position representations.
Each sublayer: LayerNorm(x + Sublayer(x))
The residual path adds the sublayer’s input back to its output.
Vaswani et al. (2017), §3.1, Figure 1 and §3.3. Normalization order varies across Transformer architectures.
The government announced a [MASK] policy.
Masked language modeling: predict selected hidden tokens from context.
The original text supplies the answers.
The model still needs a connection to our research labels.
Grimmer, Roberts & Stewart (2022), Text as Data, §8.5, p. 88 · BERT, §3.1. Masked-policy sentence: teaching example.
| Split | Purpose | Example decision |
|---|---|---|
| Training | Fit model parameters | Learn from human labels |
| Validation | Choose settings | Select a checkpoint or threshold |
| Test | Estimate performance after choices are fixed | Report held-out results |
Split by speaker, document or time when the research setting requires it.
| Case | Application | Journal |
|---|---|---|
| Case 1 · Liao & Tang | Legislative oversight and electoral reform | Electoral Studies |
| Case 2 · Schöll et al. | Citizen feedback and gender-issue attention | American Journal of Political Science |
| Case 3 · Bestvater & Monroe | Sentiment versus target-specific stance | Political Analysis |
Liao & Tang (2026), Electoral Studies 99:103026, §§4–5. Article. Original first-page excerpt.
Learn the label from legislation
7,216 human-labeled proposals and amendments → Chinese BERT
Check the new text genre
About 400 human-coded written questions · GTQ F1 .88
Turn question labels into a research outcome
63,748 questions · 402 district legislators · 1999–2019
GTQ percentage = 100 × targeted questions / all questions, within each legislator-year.
Liao & Tang (2026), §4.1 and footnote 9, pp. 4–5; §§5.1–5.2, pp. 6–7. Published classification and measurement design.
The initial GTQ share is lower after reform; the negative difference weakens over time.
Liao & Tang (2026), Figure 3, p. 7; Table 1, p. 6. Original figure; Model 4 fitted trends and 95% confidence intervals. Interpret with the time comparison and controls.
Schöll, Gallego & Le Mens (2024), AJPS 68(2):557–574, “Measuring Attention to Gender Issues” and Table 4. Article. Original first-page excerpt.
| Stage | What enters the research measure? |
|---|---|
| Human labels and BERT | About 20,000 tweets coded as gender issue / other |
| Validation | Precision .90 · recall .79 |
| Aggregation | Gender-related tweets / all tweets, for each politician-month |
BERT supplies the topic label; retweets supply the feedback measure.
Earlier relative feedback → Later issue-attention share
Schöll, Gallego & Le Mens (2024), “Measuring Attention to Gender Issues,” p. 562; research variables, pp. 564–565. Scores are reported for validation data; no separate untouched test set is established in the main-text description.
Both coefficients are positive: .11 for women and .07 for men.
Their response difference is not statistically clear.
Panel association; retweet feedback does not represent all voters’ preferences.
Schöll et al. (2024), Table 4, p. 567; interpretation, p. 568. Original table excerpt; logit coefficients, not percentage-point effects. SE clustered by politician.
Bestvater & Monroe (2023), Political Analysis 31(2):235–256, Table 2 and Figure 3. Article. Original first-page excerpt.
Target: approval of the 2017 Women’s March
Regress each approval measure on the author’s political ideology.
| Approval measure | Label source | Ideology slope | N |
|---|---|---|---|
| VADER | Sentiment dictionary + rules | −0.35 | 928 |
| BERT | Fine-tuned on human stance labels | −0.76 | 1,501 |
| Human coding | Manual approval / opposition labels | −1.87 | 1,501 |
A more negative slope means a sharper decline with conservatism.
Logit coefficients, not percentage-point changes. Estimation samples differ.
Bestvater & Monroe (2023), pp. 238–242; Table 2, p. 241. Article. Published observational results; human coding is the reference measure.
Bestvater & Monroe (2023), Table 2, p. 241; original Figure 3, p. 242 (CC BY 4.0). Article. Regression-estimated approval probabilities, not classifier confidence or causal effects.
Text + full hypothesis → Transformer NLI model → Relation scores
| Paired input | Teaching example |
|---|---|
| Text | “The council discussed the housing bill today.” |
| Hypothesis | “The council approved the housing bill today.” |
Natural language inference (NLI) predicts whether the text entails, contradicts or leaves the hypothesis unresolved.
The hypothesis is part of the input. The model still uses a Transformer.
Constructed teaching pair, not a model prediction. Bowman et al. (2015), §2.1 · Laurer et al. (2024).
Hypothesis: “The council approved the housing bill today.”
| Relation | Text | What follows? |
|---|---|---|
| Entailment | “Today, the council voted to approve the housing bill.” | The hypothesis is supported. |
| Contradiction | “The council did not approve the housing bill today.” | The text conflicts with the hypothesis. |
| Neutral | “The council discussed the housing bill today.” | Approval remains unresolved. |
NLI neutral means insufficient evidence about this hypothesis.
Constructed teaching examples, not model predictions. Relation definitions: Bowman et al. (2015), §2.1 and Figure 1.
| Candidate stance | Full hypothesis |
|---|---|
| Support | “The author supports this bill.” |
| Oppose | “The author opposes this bill.” |
Text + each hypothesis → Relation scores → Decision rule → Stance label
Define how to compare scores and handle uncertain cases.
Constructed stance hypotheses, not model predictions. Burnham (2025), §§3.2.1–3.2.3, pp. 619–620.
Same text: “I oppose Trump’s policies.”
Task-specific classifier
Input: the tweet.
Fine-tune on human stance labels for this task.
Predict a class from the trained label set.
Existing NLI classifier
Input: the tweet + a stance hypothesis.
Reuse a model trained on NLI relations.
Compare hypotheses to select a stance.
Both use Transformers. This NLI example skips target-task fitting; both approaches still need human validation.
Constructed tweet. Zero-shot route follows Burnham’s official NLI tutorial and its Hugging Face model.
Text: “I oppose Trump’s policies.”
Template: The author of this tweet {} Trump.
| Candidate text | Complete hypothesis |
|---|---|
supports |
The author of this tweet supports Trump. |
opposes |
The author of this tweet opposes Trump. |
does not express an opinion about |
The author of this tweet does not express an opinion about Trump. |
Compare the hypotheses, then check the text. “No opinion” is a stance candidate; NLI neutral is a relation.
Constructed tweet; no model prediction shown. Template and candidates from Burnham’s official NLI tutorial. Hugging Face model card.
Laurer et al. (2024), “Less Annotating, More Classifying,” Political Analysis 32:84–100. Eight tasks from five datasets; original first-page excerpt.
Text in the paper’s Figure 1: “Our armed forces keep us safe”
| Shown candidate hypothesis | Entailment score in Figure 1 |
|---|---|
| “The Military is good” | .83 |
| “The Military is bad” | .07 |
Selected label in the figure: Military: Positive
Compare the candidate hypotheses, then use the selected stance label.
Laurer et al. (2024), Figure 1, p. 89. Paper illustration of the NLI workflow, not a new classroom prediction or accuracy estimate.
| Comparison in the paper | Reported evidence |
|---|---|
| 100–2,500 target-task labels | BERT-NLI gains 10.7–18.3 macro-F1 points over TF-IDF classifiers, averaged across 8 tasks. |
| 500 labels for BERT-NLI vs. ~5,000 for classical methods | Similar average macro-F1; the larger samples are available for 4 datasets. |
These labeled-data gains include target-task fine-tuning.
Required annotation still depends on the task. Evaluate on held-out human labels.
Laurer et al. (2024), Figure 2, p. 93; Figure 3, p. 94; comparison and footnote 13, p. 95. Published results; no new model run.
Burnham (2025), “Stance detection: a practical guide to classifying political beliefs in text,” PSRM 13:611–628. Original first-page excerpt, CC BY 4.0; online publication in 2024.
862,923 COVID-19 tweets · 23,476 users
September 2020–February 2021
Tweet + topic-matched hypotheses → DeBERTaV3 NLI
Flag threat minimization when a matched threat-minimizing hypothesis is entailed.
Check 300 human-labeled tweets
| Hypothesis set | MCC | Accuracy |
|---|---|---|
| Set 1 | .67 | 87% |
| Set 2 | .74 | 90% |
The references came from the original training pool.
Burnham (2025), §§4.1–4.2, pp. 624–625. Published hypothesis checks; these are not new W10 predictions.
Tweet labels → User counts → Negative-binomial regression
Similar associations across label sets do not replace human validation.
Burnham (2025), Figure 3, p. 624 and §4.2, pp. 624–625. Original figure excerpt, CC BY 4.0; published observational associations, not new or causal W10 estimates.
| Design choice | Laurer · Political Analysis | Burnham · PSRM |
|---|---|---|
| Research output | Political text categories | COVID-19 threat-minimization labels |
| Target-task fine-tuning | Yes | No in this application |
| Human check | Held-out target-task labels | 300 tweets from the original training pool |
NLI does not automatically mean zero-shot.
Both applications require explicit category definitions and a validated decision rule.
Laurer et al. (2024), pp. 90–94 · Burnham (2025), §§4.1–4.2, pp. 624–625. These are different tasks, not a model ranking.
First: fine-tune policy classifiers. Then: reuse NLI for stance.
Policy labels → Fine-tuning → Evaluation → NLI stance exercise
Start with the supplied Flair and Transformers workflows. Finish with the NLI demonstration.
Open the notebooks/ folder with the data directory beside both files.
| Open | Main objects | Encoder in the original file |
|---|---|---|
| Flair notebook | Sentence → Corpus → TextClassifier |
Multilingual DistilUSE |
| Transformers notebook | Tokenizer → DistilBERT → Trainer |
English DistilBERT |
Same supplied data: 1,880 train · 627 validation · 627 test.
Read the text and label columns. Keep the existing split.
Different encoders and training recipes. Record both before comparing scores.
Liao & Müller (2024), supplied notebook files. Flair · Transformers · Data and labels · Before running.
1. Read and attach the supplied labels
Flair adds a label to each Sentence; Transformers maps class names to IDs.
2. Build the classifier and fit it on train
Flair uses ModelTrainer; Transformers uses Trainer. Validation guides model selection.
3. Evaluate after fixing the training procedure
Read the final test report and return to the full text of one error.
Only 44 of 627 test excerpts are labeled environmental policy.
Accuracy alone can hide a model that misses this class.
Read precision, recall and F1 by class.
Compare them with macro-F1 and accuracy where reported.
Explain one prediction with its full text.
Report the reference label, prediction and evidence for your interpretation.
Read the results and exit questions · Supplied split counts. Original notebook output cells are historical records.
1. Install once
Use the prepared environment. In a notebook, install with %pip, then restart the kernel.
2. Load the shared tools
DatasetDict loads data. Counter counts labels. classification_report reads performance by class.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Record the environment
Keep these package versions with your model settings and results.
2. Inspect the device
Choose CUDA, Apple MPS or CPU. Check the device reported by each training log.
Unified Lab guide. Code follows the supplied notebook workflows.
Preparation check: 27 November 2026.
1. Record the versions
These versions describe the prepared environment.
2. Read the device
This check reports CPU availability. Check the trainer log when training.
3. Keep the date with the output
This preparation check does not report a trained model’s performance.
Current preparation output, 27 November 2026: environment.txt. This is not the environment record of the original 2024 model run.
1. Load the existing split
Run from notebooks/. Keep train, validation and test in their supplied roles.
2. Read the stored mapping
0 means other policy. 1 means environmental policy. Preserve this order.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Inspect class balance
Split sizes: 1,880 / 627 / 627. Test has 44 environmental-policy texts.
2. Read before fitting
The first text discusses community policing and has reference label 0.
Unified Lab guide. Code follows the supplied notebook workflows.
Printed from the supplied data · 27 November 2026
| Split | Rows | Other policy (0) |
Environmental policy (1) |
|---|---|---|---|
| Train | 1,880 | 1,772 | 108 |
| Validation | 627 | 582 | 45 |
| Test | 627 | 583 | 44 |
0 → None Environment Policy
1 → Environment Policy
Only 44 of 627 test excerpts have the environmental-policy label.
Executed data printout · Supplied dataset counts; original Transformers notebook, zero-based cell 8 (mapping); Flair notebook, cells 12 and 19 (training and test labels).
1. Load the Flair interface
Sentence holds one text. Corpus holds the split. The classifier and trainer have separate jobs.
2. Configure the run
Set a seed and assign the device to Flair explicitly.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Attach the supplied label
Sentence stores text. add_label stores the gold value in the label layer.
2. Preserve each split
Convert train, validation and test separately, then inspect the first training example.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Keep the split together
Corpus holds train, dev and test. Their roles remain distinct.
2. Build classes from train
add_dev_test=False excludes held-out labels. The dictionary contains strings "0" and "1".
Unified Lab guide. Code follows the supplied notebook workflows.
1. Load the pretrained encoder
fine_tune=True allows encoder weights to change when training runs.
2. Add a classification head
Use the class dictionary and gold label layer. Each text receives one category.
Unified Lab guide. Code follows the supplied notebook workflows.
flair_trainer = ModelTrainer(
flair_classifier, corpus
)
flair_trainer.train(
"qta_flair_python_model",
shuffle=True,
patience=3,
learning_rate=0.02,
mini_batch_size=16,
max_epochs=3,
write_weights=True,
train_with_dev=False,
train_with_test=False,
monitor_test=False,
use_final_model_for_eval=False,
)1. Run the original training recipe
SGD, rate .02, three epochs. Dev selects the checkpoint. Test runs at the end.
2. Reload the selected model
best-model.pt contains the checkpoint selected using validation.
Unified Lab guide. Code follows the supplied notebook workflows.
| Epoch | Train loss | Dev loss | Dev micro-F1 |
|---|---|---|---|
| 1 | 0.2199 | 0.1576 | 0.9522 |
| 2 | 0.1360 | 0.1586 | 0.9522 |
| 3 | 0.0888 | 0.1616 | 0.9522 |
Values displayed to four decimal places.
Best checkpoint saved after epoch 1.
Historical training log: 19 April 2024 · CPU.
1. Read the training loss
Loss falls as the model fits the training data.
2. Check validation performance
Dev micro-F1 stays at 0.9522; dev loss rises slightly.
3. Identify the saved checkpoint
The log saves epoch 1. Later epochs do not improve the recorded selection score.
Historical output from the supplied 2024 Flair notebook, stored training log. These are original model records, not results from a new W10 training run.
1. Keep gold and predictions separate
Write predictions to predicted, then convert their strings back to category IDs.
2. Read the environmental-policy row
Compare precision, recall and F1. Use the shared class names and order.
Unified Lab guide. Code follows the supplied notebook workflows.
2024 notebook record · not a new run of revised code
| Class | Precision | Recall | F1 | Support |
|---|---|---|---|---|
Other policy (0) |
.9507 | .9914 | .9706 | 583 |
Environmental policy (1) |
.7368 | .3182 | .4444 | 44 |
Accuracy: .9442 · Macro-F1: .7075 · Test rows: 627
High accuracy can coexist with low environmental-policy recall.
Original Flair notebook, zero-based cell 19, final “Results / By class” output. Stored training recipe: rate .02, batch 16, three epochs.
1. Make the training components explicit
Load the tokenizer, model, settings and trainer. Set the seed before model creation.
2. Match tokenizer and checkpoint
Use distilbert-base-uncased for both the tokenizer and model.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Encode without replacing raw data
hf_data adds input IDs and attention masks. Padding gives 512 positions; truncation limits length.
2. Use the shared two-class mapping
Load the pretrained encoder with a new policy-classification head.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Define what evaluation reports
Choose the largest logit for each prediction. Macro-F1 weights the two classes equally.
Unified Lab guide. Code follows the supplied notebook workflows.
hf_args = TrainingArguments(
output_dir="./qta_hf_python_model",
num_train_epochs=3,
learning_rate=5e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="macro_f1",
greater_is_better=True,
save_total_limit=1,
report_to="none",
seed=42,
)1. Select using validation macro-F1
Evaluate and save each epoch. Reload the checkpoint with the highest validation macro-F1.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Configure first, then train
Train updates weights. Validation selects the checkpoint. The test split is absent.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Evaluate the fixed procedure
Predict test once the procedure is fixed. Read the same class report as for Flair.
Unified Lab guide. Code follows the supplied notebook workflows.
2024 notebook record · not a new run of revised code
| Stored test metric | Value |
|---|---|
| Accuracy | .9298245614 |
| Macro-F1 | .4818181818 |
| Macro-precision | .4649122807 |
| Macro-recall | .5000000000 |
| Test rows | 627 |
The stored cell reports macro averages, not a per-class report.
Original learning rate: 0.3. Revised code needs its own run and results.
Original Transformers notebook, zero-based cells 17, 19 and 25. Cells 33–34 use a different model path; the example is not validated by this test report.
1. Save both model and tokenizer
Store the selected checkpoint and its matching tokenizer together.
2. Reload from that path
The pipeline reads the saved model and tokenizer. device=-1 runs this demonstration on CPU.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Read the category and model score
Use policy text for this policy classifier. The score does not establish correctness.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Join by the unchanged test order
Keep full text, reference ID and both prediction IDs in one table.
2. Translate IDs into class names
Apply the same id2label mapping to the reference and both models.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Choose a text for inspection
Select a row where either model disagrees with the reference. If none do, use the first text.
2. Explain the evidence
Read the full text, reference, Flair prediction and Transformers prediction in that order.
Unified Lab guide. Code follows the supplied notebook workflows.
1. Load an NLI model
Its existing head predicts relations between two texts.
2. Reuse its weights
device=-1 selects CPU. There is no train() call.
NLI Lab guide · Adapted from Burnham’s official tutorial.
1. Define the target
The template names Trump. Candidate phrases specify the stance.
2. Read complete statements
The model pairs each statement with the same input text.
NLI Lab guide · Adapted from Burnham’s official tutorial.
1. Read texts A, B and C
These are constructed teaching inputs, not a research test set.
2. Compare candidate scores
False selects one stance. It normalizes across candidate hypotheses.
NLI Lab guide · Adapted from Burnham’s official tutorial.
A: I support Trump’s policies.
B: I oppose Trump’s policies.
C: The committee meets on Tuesday.
| Text | Support | Oppose | No opinion |
|---|---|---|---|
| A | 0.9918 | 0.0044 | 0.0038 |
| B | 0.0086 | 0.9843 | 0.0071 |
| C | 0.2063 | 0.1967 | 0.5970 |
Candidate scores with multi_label=False; short column names.
1. A ranks support first
Read the text and all three scores together.
2. B ranks opposition first
Check that the target matches the research definition.
3. C is less decisive
No opinion leads at .5970. Set review rules with validation data.
Actual CPU output and pinned revision · Constructed inputs; no fine-tuning, COVID-19 replication or accuracy estimate.
Architecture: Vaswani et al. (2017) · Devlin et al. (2019). Lab: Liao & Müller (2024), supplied Week 12 notebooks.