NLP Implementation CrashCourse
NLP Implementation CrashCourse
Crash Course
From Black Boxes to Working Code
~ 1 Hour Read
Interview Prep Edition · Focus: How to USE the tools, not how they work inside
You are not being hired to invent new algorithms. You are being hired to take a PhD researcher's
ideas and turn them into running code. That is a completely different job. The PhD thinks in math and
theory — your job is to know which library does what, how to wire things together, and how to run
experiments without breaking things.
The one sentence to internalise: Modern NLP implementation is mostly knowing which
pretrained model to download, how to feed your data into it, and how to run a training loop. The
hard math is already done for you.
You already know embeddings — vectors that represent meaning. Everything in this document builds
on that. Keep coming back to: 'this is just transforming vectors' and you won't get lost.
Neural Networks
What they are from the outside — not how they work inside
Text, numbers, or Learned function (don't open Labels, scores, new text,
embeddings this box) vectors
Training Inference
Showing the model thousands of examples so Using a trained model to get predictions on
it learns the right weights new data
Slow. Needs a GPU. Done once (or few times). Fast. Can run on CPU. Done constantly in
production.
You write the training loop. You watch the loss You call model(input). You get output.
go down.
1. Pretrained Model
Someone at Google/Meta/Hugging Face already trained a massive model on billions of words. You
download this. You do NOT train from scratch — that would take weeks and cost thousands of
dollars.
The PhD has data specific to their domain — medical notes, legal documents, scientific papers,
tweets, etc. This data needs to be cleaned and formatted.
3. Fine-Tuning
You take the pretrained model and keep training it — but only on the PhD's small domain dataset.
The model already knows English; now it learns the PhD's specific task.
4. Evaluation
You measure how well the model performs. Different metrics depending on the task (accuracy, F1
score, BLEU score, perplexity). You report these numbers to the PhD.
5. Iteration
PhD looks at results, says 'try changing X'. You change X, re-run, report new numbers. This loop is
the bulk of the job.
Parameters / Weights The numbers inside the model that were learned during training. A
large model has billions of these. You never touch them directly.
Forward Pass Feeding input through the model to get an output. model(input) in
code. This is what happens during both training and inference.
Loss A single number measuring how wrong the model's prediction was.
Lower is better. During training, you want this to decrease over time.
Backpropagation The algorithm that figures out how to adjust the weights to reduce the
loss. You never write this yourself — PyTorch does it automatically
when you call [Link]().
Epoch One full pass through your entire training dataset. You typically train
for multiple epochs (e.g. 3–10).
Batch / Batch Size Instead of training on one example at a time, you process a batch (e.g.
32 examples) simultaneously. Faster and more stable.
Gradient The direction and amount to adjust each weight to reduce loss.
Backprop computes gradients. The optimizer uses them.
Optimizer The algorithm that actually updates the weights using gradients. Adam
is the most common one you'll use.
Learning Rate How big each weight update step is. Too big = unstable training. Too
small = too slow. A hyperparameter you set.
Overfitting When the model memorises training data but fails on new data. You fix
this with more data, dropout, or early stopping.
Checkpoint Saving the model weights to disk at a certain point so you can reload
them later without retraining.
GPU / CUDA Neural networks train ~100x faster on GPUs. CUDA is Nvidia's
software that PyTorch uses to run on GPU. [Link]('cuda') moves it
to GPU.
PyTorch
The framework — what you will actually write every day
PyTorch is the tool researchers use to build and run neural networks. Think of it as a very smart
version of NumPy that can automatically compute gradients (which is what you need for training).
Almost all cutting-edge NLP research code is written in PyTorch.
Your relationship with PyTorch: You will mostly use it to write training loops, move data between
CPU and GPU, save/load models, and call HuggingFace models (which are built on PyTorch). You
will rarely write a custom model from scratch.
import torch
# 1D tensor (a vector)
x = [Link]([1.0, 2.0, 3.0])
class MyDataset(Dataset):
def __init__(self, texts, labels):
[Link] = texts
[Link] = labels
3. The Training Loop — You Will Write This Over and Over
This is the most important thing to understand. Every training run is this loop. Once you know it, you
can train any model on any data.
Those five lines (zero_grad → forward → loss → backward → step) are the heartbeat of every
training run. Memorise them.
# Save
[Link](model.state_dict(), 'model_checkpoint.pt')
# Load
model.load_state_dict([Link]('model_checkpoint.pt'))
[Link]() # put in inference mode (disables dropout etc.)
state_dict() A dictionary of all the model's weights. What you save to disk and load
back. Think of it as a snapshot of everything the model learned.
[Link]() Puts the model in training mode. Activates things like dropout. Always
call before a training loop.
[Link]() Puts the model in inference mode. Disables dropout. Always call when
you just want predictions.
optimizer.zero_grad() Clears the gradients from the last step. If you forget this, gradients
accumulate and training breaks. First line of every training step.
[Link]() Uses the gradients to update the weights. Happens after backward().
.to(device) Moves a tensor or model to CPU or GPU. Both model AND data need
to be on the same device.
logits The raw, unnormalised output scores from the model before converting
to probabilities. Common in HuggingFace outputs.
argmax Picks the index of the highest value. Used to convert logits into a
predicted class label.
DataLoader Wraps a Dataset and handles batching, shuffling, and parallel loading.
You always use this during training.
AdamW The most common optimiser in NLP research. Use it unless the PhD
says otherwise. lr=2e-5 is a safe default for fine-tuning.
num_epochs How many times to loop through the full dataset. For fine-tuning
pretrained models, 3–5 epochs is typical.
HuggingFace Transformers
The App Store for NLP models — your most-used tool
HuggingFace is the single most important library in modern NLP. It gives you instant access to
thousands of pretrained models — BERT, GPT-2, RoBERTa, LLaMA, T5, and hundreds more — in
2-3 lines of code. You will use this library on almost every task the PhD gives you.
When the PhD says 'we need to fine-tune a model on our dataset', this entire chapter is how you
do it.
Tokenizer Converts raw text into numbers the model can read.
Text in → token IDs out. Every model has its own tokenizer. Always load the one that matches your
model.
Trainer HuggingFace's built-in training loop — wraps the PyTorch loop for you.
Optional but saves writing boilerplate. Used for fine-tuning. You give it a model, dataset, and training
arguments.
1. The Tokenizer
Raw text means nothing to a neural network. The tokenizer breaks text into tokens (sub-word pieces)
and maps each to an integer ID. It also creates the 'attention_mask' that tells the model which tokens
to pay attention to.
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# Single sentence
output = tokenizer('The river bank was muddy.')
# output = {'input_ids': [101, 1996, 2314, ...], 'attention_mask': [1, 1, 1, ...]}
# Assume you have a HuggingFace Dataset with 'text' and 'label' columns
tokenized_dataset = [Link](tokenize, batched=True)
# ■■ 5. Save ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■
model.save_pretrained('./my_finetuned_model')
tokenizer.save_pretrained('./my_finetuned_model')
# Sentiment analysis
# Text generation
gen = pipeline('text-generation', model='gpt2')
gen('The experiment showed that', max_length=50)
from_pretrained() Loads a model or tokenizer from HuggingFace Hub (or local path). The
standard way to get any model. Downloads weights automatically on
first call.
AutoModel / Auto* Smart loader classes that detect the model architecture and load the
right class. Use these instead of specific classes like BertModel.
input_ids The token IDs that come out of the tokenizer. What you feed into the
model. A tensor of integers.
attention_mask A tensor of 1s and 0s telling the model which tokens to pay attention to
(1) and which are padding (0).
logits Raw unnormalised scores output by the model. One score per class.
Apply softmax to get probabilities. Apply argmax to get the predicted
class.
last_hidden_state The embedding output from encoder models like BERT. Shape:
(batch, sequence_length, hidden_size). Use this when you need
sentence embeddings.
[CLS] token The first token in every BERT input. Its final embedding is commonly
used as a representation of the whole sentence for classification.
TrainingArguments Config object for Trainer. Where you set learning rate, epochs, batch
size, output directory, etc.
datasets library Companion library from HuggingFace for loading and processing
datasets efficiently. Works seamlessly with Transformers.
Hub / model card HuggingFace Hub is the model repository at [Link]. Each
model has a 'model card' page explaining what it does, what data it
was trained on, and how to use it.
save_pretrained() Saves model weights AND config to a folder. Use this instead of
[Link] when working with HuggingFace models.
When a PhD says 'I need you to implement X', this chapter tells you what X is, what goes in, what
comes out, and which model to reach for.
Named Entity Recognition (NER) Input text → each word labelled with its entity
type
Semantic Similarity / Search Two texts → similarity score (or embed many
texts and search by nearest vector)
Finding similar documents, duplicate detection, Model: AutoModel (get embeddings) Start with:
question-answer matching. You already know sentence-transformers/all-MiniLM-L6-v2
the embedding+matching idea — this is it in
production.
The model learns to find where in the paragraph Model: AutoModelForQuestionAnswering Start
the answer is. Output is a start and end position with: deepset/roberta-base-squad2
in the text.
Evaluation Metrics
How to measure if the model is actually working
After training, the PhD will ask: 'how did it do?' These are the numbers you report. Different tasks use
different metrics. Know these cold.
Classification Metrics
Precision Of all the times the model predicted class X, what % were actually
class X. Measures 'when it fires, is it right?'
Recall Of all actual class X examples, what % did the model find. Measures
'did it catch them all?'
F1 Score Harmonic mean of precision and recall. The single most common
metric in NLP research. Balances both concerns. Ranges 0–1, higher
is better.
Confusion Matrix A table showing predicted vs actual classes. Quickly reveals which
classes the model confuses. You'll produce these often.
BLEU Score Used for translation and summarisation. Measures overlap between
generated text and a human reference. 0–1, higher is better.
Cosine Similarity For embedding tasks. Measures angle between two vectors (0 to 1).
You already know this — it's the matching metric from your embedding
knowledge.
This is the map. Every implementation task the PhD gives you will fit somewhere in this workflow.
When you're lost, come back here.
Step 1 Understand the task What is the input? What is the output? What does 'correct'
look like? Ask the PhD if unclear. Do not start coding until you
can answer these.
Step 2 Get the data Raw data is almost never in the right format. You will write
code to load it, clean it, and convert it into a HuggingFace
Dataset or PyTorch Dataset. This often takes longer than the
model work.
Step 3 Pick a baseline Go to [Link] and search for models that do your
model task. Pick the smallest one that seems appropriate (e.g.
bert-base not bert-large). You can always upgrade later.
Step 4 Tokenize Load the tokenizer for your model. Write a tokenize() function
that takes your text and returns input_ids and attention_mask.
Apply it to your dataset.
Step 5 Set up training Define TrainingArguments (epochs, batch size, learning rate).
Create Trainer. Run [Link](). Watch the loss go down.
Step 6 Evaluate Run on the held-out test set. Compute metrics (F1, accuracy,
etc.). Report to PhD.
Step 7 Iterate PhD will almost certainly say 'try X'. X is usually: different
model, different hyperparameters, more data, different
preprocessing. Repeat steps 3–6.
Step 8 Save and document Save the final model with save_pretrained(). Write a short
README explaining what the model does, how it was trained,
and what metrics it achieved.
CUDA out of memory Your GPU doesn't have enough memory. Fix: reduce batch_size (try
halving it). Or use gradient_accumulation_steps in TrainingArguments
to simulate a larger batch.
Expected input of size X, Shape mismatch — usually your data isn't formatted correctly. Check
got Y your tokenizer output shapes with .shape.
Loss is NaN Training exploded. Usually caused by learning rate too high or a bug in
data loading. Try lowering lr by 10x.
Loss not decreasing Either learning rate too low, bug in training loop (did you call
optimizer.zero_grad()?), or the task is too hard for the model chosen.
RuntimeError: device Model is on GPU but data is on CPU (or vice versa). Add .to(device) to
mismatch both model and each batch.
Master Glossary
Every term you might hear in the interview
If the PhD uses a term you don't recognise, this is your reference. These are ordered from most to
least likely to come up.
Transformer The neural network architecture behind almost all modern NLP models
(BERT, GPT, T5, LLaMA). Uses 'attention' to relate words to each
other regardless of distance in a sentence. You don't need to know
how it works — just that every modern model is one.
GPT / GPT-2 / GPT-4 OpenAI's generative models. Read text left to right (decoder-only).
Great for text generation. GPT-4 is the large commercial one — in
research you'll more likely use smaller open variants.
LLaMA / Mistral / Falcon Open-source large language models. LLaMA is Meta's. Often used in
research as alternatives to GPT-4. You'll fine-tune these using the
same HuggingFace workflow.
Tokenization Converting raw text into tokens (sub-word pieces) and then integer
IDs. 'unhappiness' might become ['un', '##happiness'] or ['un',
'happiness'] depending on the tokenizer.
Attention / Self-Attention The mechanism that lets a transformer look at other words in the
sentence when processing each word. 'bank' in 'river bank' looks at
'river' to know what it means. You don't need to implement this — it's
built into every transformer model.
Pretrained / Foundation A model trained on massive amounts of general text data. Knows a lot
Model about language already. You build on top of these rather than starting
from scratch.
Transfer Learning The broader concept behind fine-tuning. Knowledge learned on one
task (general language) transfers to another (specific task). The
reason pretrained models are so powerful.
Zero-Shot / Few-Shot Zero-shot: using a model on a task it was never trained on, relying on
its general knowledge. Few-shot: giving the model 2-5 examples in the
prompt before asking it to do the task. Both are prompting techniques
for large models.
Prompt Engineering Carefully crafting the input text to get better outputs from a large
language model. Relevant if the PhD uses GPT-4 or similar in the
pipeline.
Dataset (HuggingFace) A library and format for handling NLP datasets. Loads from disk or
directly from Hub. Integrates directly with Trainer.
Batch Normalisation / Techniques that stabilise training by normalising activations. You won't
Layer Norm implement these — they're inside the model — but you may see them
mentioned.
Hyperparameter Any value you set before training that isn't learned from data: learning
rate, batch size, number of epochs, model size. Tuning these is a big
part of implementation work.
Reproducibility Making sure experiments can be recreated with the same results. Set
random seeds: torch.manual_seed(42). Log all hyperparameters. Save
your code and data versions.
A: BERT is an encoder — it reads the whole sentence bidirectionally and is great for understanding
tasks like classification and NER. GPT is a decoder — it reads left to right and is designed for
generation. BERT for understanding, GPT for generating.
Q: How would you handle a dataset that's too large to fit in memory?
A: Use HuggingFace Datasets with streaming mode, or DataLoader with multiple workers. Process in
batches rather than loading everything at once.
A: First check for bugs in the training loop — specifically whether zero_grad() is being called. Then try
adjusting the learning rate, usually lowering it. Also check the data pipeline to make sure labels are
correct.
A: Python with PyTorch and HuggingFace Transformers as the core stack. HuggingFace Datasets for
data loading, scikit-learn for metrics, and Weights & Biases or TensorBoard for tracking experiments.
A: I haven't worked with that specific technique yet, but given my ML background I'd get up to speed
quickly. Could you tell me more about how it fits into the project? — then it becomes a conversation,
not an exposure.