Bridge to LLMs
Deep Learning for Natural Language Processing
Natural Language Processing (NLP) turns text or speech into useful predictions and generated language. This lesson follows a message from raw characters to tokens, IDs, embeddings and contextual representations; shows how output design changes across NLP tasks; calculates embedding similarity and classification loss; and explains how to fine-tune and evaluate pretrained models without silently leaking text or changing their expected preprocessing.
Why Language Is Difficult for a Neural Network
A photograph arrives as numbers arranged in a grid. A sentence arrives as symbols whose meaning depends on order, surrounding words, speaker, domain and sometimes information outside the sentence. “The service is sick” may be praise in slang or a fault report in engineering. “That was not bad” cannot be classified by counting the word bad.
Deep NLP systems learn representations from data so that useful language patterns can support classification, extraction, retrieval, translation or generation. They do not receive strings directly: the first job is a consistent conversion from text to integer IDs.
A deep NLP system turns language into task-specific predictions
Every arrow is a testable part of the data path.
Raw language
“Pump A is not safe.”
Tokenizer
[Pump] [A] [is] [not] [safe] [.]
Token IDs
[731, 42, 19, 87, 905, 7]
Embeddings + model
contextual vectors
Task head
unsafe: 0.94
Tokenization Decides the Units the Model Reads
A token is one unit produced by a tokenizer. It may be a whole word, part of a word, a character or a byte-level unit. The tokenizer owns a vocabulary that maps each recognized token to an integer ID. Special tokens can mark padding, unknown pieces, sequence boundaries or task-specific roles.
One string can be divided at different levels
The pieces below are illustrative; a real pretrained tokenizer has its own learned vocabulary and boundary markers.
Word tokens
retraining
one known word—or unknown
Subword tokens
re · train · ing
reuse learned pieces
Character tokens
r · e · t · r · a · i · n · i · n · g
small vocabulary, long sequence
Token IDs are identifiers, not quantities. ID 900 is not “larger in meaning” than ID 12. The numbers [731,42,19,87,905,7] in the opening diagram are illustrative IDs; a real tokenizer returns its own fixed mapping. A model uses each ID only as a row address in an embedding table. When using pretrained weights, use the matching tokenizer: vocabulary, special IDs, casing rules and segmentation are part of the learned system.
Do not clean text automatically
Lowercasing, deleting punctuation, removing stop words or stemming can destroy signals and disagree with a pretrained tokenizer. Preserve raw text by default, normalize only for a justified reason, and test the effect on real examples such as negation, emojis, codes and names.
An Embedding Turns an ID Into a Learnable Vector
A vocabulary of 50,000 tokens could represent each token with a 50,000-position one-hot vector, but that vector is mostly zeros and says nothing about related usage. An embedding table stores a shorter dense vector in each vocabulary row. If a developer chooses width 128, the table shape is [50,000,128]; an input with 8 messages and 20 tokens becomes [8,20,128]. The vocabulary size comes from the tokenizer, width is a model-design choice, and the table values are initialized then learned.
Cosine similarity compares vector direction
cos(a,b) = (a · b) / (‖a‖ ‖b‖)
Use manually chosen two-dimensional vectors a=[1,1] and b=[0.8,0.6] so every operation is visible. Real embedding vectors are model-produced and usually much wider.
Multiply and add
a·b = 1×0.8 + 1×0.6
= 1.4
Measure each length
‖a‖=√2≈1.414
‖b‖=√(0.64+0.36)=1
Divide out length
cos(a,b)=1.4/(1.414×1)
≈ 0.990
Why divide? The dot product grows with vector length as well as alignment. Dividing by both lengths isolates direction, so large-magnitude vectors do not appear similar merely because they are large. A value near 1 means similar direction; 0 means perpendicular; −1 means opposite direction.
The same spelling can need different contextual representations
“Deposit cash at the bank.”
“Sit on the river bank.”
Define the Prediction Unit Before Choosing a Model
“Analyze support messages” is not yet a machine-learning task. Do you need one intent per message, one entity tag per token, a similarity score between tickets, or a generated reply? This decision controls the annotation format and the representation passed to the final task head.
| Task | Prediction unit | Model output | Example |
|---|---|---|---|
| Text classification | whole document | one or more labels | complaint → billing |
| Token classification | each token | tag per token | Priya → PERSON |
| Extractive QA | question + passage | start/end span | answer words in passage |
| Semantic similarity | text pair | score or class | duplicate ticket: 0.91 |
| Generation | prompt/source | new token sequence | report → summary |
One Text-Classification Prediction With Numbers
Assume a contextual encoder has read “the motor is overheating.” The developer defined three labels—normal, warning and critical—so the final linear layer must output three numbers. For a transparent example, use model-produced raw scores called logits: normal=0.2, warning=1.1, critical=2.0. These logits are illustrative outputs, not probabilities or developer-set thresholds.
pi = ezᵢ / Σjezⱼ
zᵢ is one logit and pᵢ is its softmax probability. Exponentiation makes every score positive and accentuates differences; dividing by their sum normalizes the results to 1. Subtracting the largest logit first is a numerically safer but mathematically equivalent implementation.
1. Exponentiate
e⁰·²=1.221
e¹·¹=3.004
e²=7.389
2. Normalize
sum=11.614
p≈[0.105, 0.259, 0.636]
3. Compare with label
true class=critical
loss=−ln(0.636)
≈ 0.453
Interpretation: critical is the most likely class, but 0.636 is not certainty. The true label comes from the dataset; cross-entropy uses its probability and training changes the model weights to lower this loss over many examples. Calibration must be evaluated separately.
Static Embeddings, Recurrent Models and Transformers
| Approach | Representation | Good starting situation | Limitation |
|---|---|---|---|
| TF-IDF + linear model | Sparse word/subword counts | Fast, interpretable baseline on labelled text | Weak handling of order and contextual meaning |
| Static embedding + CNN/RNN | One learned/pretrained vector per token type | Compact custom baseline with moderate data | Same base vector for every occurrence |
| LSTM/GRU | Context evolves sequentially | Streaming or smaller sequence models | Sequential training; long context remains difficult |
| Pretrained Transformer encoder | Contextual vector per occurrence | Classification, retrieval or extraction with transfer learning | Context length, compute and domain mismatch |
| Pretrained generative model | Autoregressive or encoder–decoder tokens | Generation and instruction-based tasks | Hallucination, cost, decoding and safety concerns |
Always establish a simple baseline. A fine-tuned Transformer is not automatically better than TF-IDF for short, domain-specific categories, especially when latency, interpretability or training data is constrained.
Fine-Tuning Reuses Language Representations
Pretraining learns broad patterns from a large text objective. Fine-tuning continues training on a smaller labelled task. A sequence-classification model usually adds a randomly initialized classification head on top of a pretrained encoder; the tokenizer and encoder start with learned knowledge rather than random weights.
1. Match
Choose a checkpoint and its exact tokenizer for language, domain, licence and maximum length.
2. Adapt
Tokenize examples, dynamically pad batches, add the correct task head and fine-tune with a small learning rate.
3. Validate
Measure task metrics, subgroup errors, calibration, latency, memory and behavior on shifted/real text.
Tokenize and Inspect Before You Train
This compact example prepares two messages for a pretrained sequence classifier. Dynamic padding makes each batch only as long as its longest member. Truncation prevents inputs from exceeding the model limit—but any discarded text is lost, so inspect truncation rates.
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint,
num_labels=3,
)
texts = [
"Pump A is not safe to restart.",
"Routine inspection completed successfully.",
]
batch = tokenizer(
texts,
padding=True, # pad to longest item in this batch
truncation=True, # enforce the model input limit
return_tensors="pt",
)
print(tokenizer.convert_ids_to_tokens(batch["input_ids"][0]))
print(batch["attention_mask"]) # 1=real token, 0=padding here
with torch.no_grad():
logits = model(**batch).logits
probabilities = logits.softmax(dim=-1)
print(probabilities)Which values are choices?
The checkpoint name selects a pretrained vocabulary, tokenizer rules, encoder width and learned weights. num_labels=3 comes from this task's label set. The two strings are data. Padding and truncation are preprocessing choices that must match the deployment policy.
What happens inside?
The tokenizer returns integer input_ids and an attention_mask. model(**batch) looks up embeddings, builds contextual states and applies the three-output classifier head. no_grad avoids storing training gradients; softmax(dim=-1) normalizes across the three labels for each message.
The classifier head above is untrained for your three labels until fine-tuned. Random head probabilities are not useful predictions. Pin a reviewed model revision in production and record tokenizer/model versions together.
Build an Evaluation Split That Matches Reality
Split by the unit that can repeat—not just by rows
Leaky row split
Ticket 104 sentence A → train
Ticket 104 sentence B → test
Near-duplicate context crosses the boundary.
Grouped split
All of Ticket 104 → one split
New tickets → held out
Evaluation better matches deployment.
| Task | Useful metrics | What an average can hide |
|---|---|---|
| Imbalanced classification | Per-class precision, recall, F1; confusion matrix | Rare but costly class failure |
| Entity extraction | Span/entity-level precision, recall, F1 | Partial boundaries and entity types |
| Retrieval/similarity | Recall@k, MRR, task-specific thresholds | Poor performance on hard negatives |
| Generation | Task metrics plus human/factual evaluation | Fluent but unsupported or unsafe output |
| Production classifier | Calibration, abstention coverage, drift slices | Confidence that does not match correctness |
A Practical NLP Debugging Path
1. Inspect raw examples
Find empty text, encoding damage, label errors, duplicates and sensitive information.
2. Inspect tokens and masks
Check special tokens, fragmentation, truncation, padding IDs and attention-mask polarity.
3. Overfit a tiny clean set
If the model cannot memorize it, verify head size, loss, labels, gradients and parameter updates.
4. Compare a simple baseline
TF-IDF or a compact model can reveal whether the neural pipeline adds value.
5. Slice errors
Break metrics down by label, language, length, domain, negation and important user groups.
6. Test realistic shift
Use later time periods, new users/templates and adversarially simple wording changes.
Limitations Are Part of the Model Design
Language datasets reproduce errors, stereotypes and exclusions in their sources. Tokenizers can handle languages and domain terminology unevenly. Context windows truncate information; generated text can be unsupported; labels can encode subjective policy rather than objective truth. Larger models also increase latency, cost and deployment complexity.
For high-impact systems, document intended use, excluded use, subgroup performance, privacy handling, human escalation and monitoring. A confident language output is still a statistical model result, not proof of correctness.
From Text to a Reliable NLP System
- Define the prediction unit, deployment boundary and consequences of mistakes.
- Create representative labels and leakage-resistant splits before model tuning.
- Use the tokenizer paired with the pretrained checkpoint; inspect actual tokens, masks and truncation.
- Convert token IDs into embeddings and contextual representations, then attach the task-appropriate head.
- Compare a simple baseline with pretrained and custom neural options under the same evaluation.
- Analyze per-class and subgroup errors, not only one overall score.
- Measure latency, memory, calibration, drift, privacy and human-review needs before deployment.