Instruction Tuning Explained: SFT, IFT & Alignment
Key Insights
- Instruction tuning trains a pretrained, next-token-predicting base model on instruction-response pairs, so it learns to answer requests instead of continuing text.
- Supervised fine-tuning (SFT) is training on any labelled input-output pairs, while instruction fine-tuning (IFT) is SFT on instruction data, which is why the terms overlap.
- Task diversity drives generalisation: Google’s FLAN, tuned on 62 instruction-phrased datasets, beat zero-shot GPT-3 175B on 20 of 25 evaluated datasets.
- Data quality beats volume: Meta’s LIMA, tuned on 1,000 curated examples, was preferred over a 65B Alpaca model trained on 52,000 examples.
- Chat templates and loss masking decide what the model learns, and only held-out evaluations, not a falling training loss, prove instruction following improved.
- Instruction tuning usually precedes preference alignment such as RLHF or DPO, but pipelines vary and neither stage guarantees factual accuracy.
Instruction tuning trains a pretrained language model on instruction-response examples so it answers user requests instead of merely continuing text. It is usually implemented through supervised fine-tuning (SFT).
The gap is easy to see. In Google’s FLAN study on instruction-tuned language models, an untuned base model asked to translate “The dog runs.” into French continued it as “The dog runs after the cat.”
This guide explains how SFT and instruction fine-tuning (IFT) relate, which datasets and chat templates are used, how training runs, how to evaluate results and where RLHF and DPO fit.
Your roadmap to becoming a Generative AI Engineer
See what you already know, what to learn next and how long the switch to a GenAI engineering role takes. Tap any step for what to study and build.
What's inside8 stages · 30 steps to job-ready
- Python & engineering foundations
- ML & deep learning essentials
- How LLMs work
- Prompting & building LLM apps
- RAG & model customisation
- Agents & tool use
- Production, evaluation & safety
- Portfolio & job readiness
Python & engineering foundations
What to study
- Core Python: data types, functions, classes, modules
- Virtual environments and package management (pip, uv)
- Writing clean, testable scripts
What to build
A command-line script that reads a CSV, cleans it and writes a summary report.
What to study
- SQL joins, aggregations and window functions
- pandas for cleaning and reshaping data
- Working with text data at scale
What to build
A notebook that cleans a messy text dataset and prepares it for a model.
What to study
- Git branching and pull requests
- How REST APIs work: HTTP methods, status codes, auth headers
- Reading and writing JSON
What to build
Call a public API from Python, handle errors and save the results as JSON.
What to study
- Vectors, matrices and dot products
- Probability and distributions
- Gradients and optimisation, intuitively
What to build
Implement cosine similarity and gradient descent from scratch in NumPy.
ML & deep learning essentials
What to study
- Supervised vs unsupervised learning
- Train/test splits, overfitting and evaluation metrics
- scikit-learn workflows
What to build
Train and evaluate a text classifier with scikit-learn.
What to study
- Tokenisation and text preprocessing
- Word embeddings and semantic similarity
- Sequence models (RNN, LSTM) and why transformers replaced them
What to build
Build a semantic search over 500 short texts using sentence embeddings.
What to study
- Layers, activations, loss functions and backpropagation
- Training loops, batching and GPUs
- PyTorch tensors and autograd
What to build
Train a fully connected network on a small dataset and plot its learning curve.
How LLMs work
What to study
- Self-attention and multi-head attention
- Encoder, decoder and encoder-decoder models
- Positional encoding and why scale matters
What to build
Walk through a minimal transformer implementation and explain each block in a short write-up.
What to study
- The Transformers library, model hub and datasets
- Running open-weights models locally
- Fine-tuning a pre-trained model for a task
What to build
Fine-tune a small pre-trained transformer for sentiment or topic classification.
What to study
- Closed vs open-weights model families
- Tokens, context windows, temperature and sampling
- Comparing models on cost, latency and quality
What to build
A comparison table of three models answering the same 20 prompts, with cost and latency.
What to study
- Quantisation, pruning and distillation
- When a small model beats a large one
- On-device and low-cost inference
What to build
Quantise an open model and compare its speed and quality against the original.
Prompting & building LLM apps
What to study
- System prompts, few-shot examples and chain-of-thought
- Prompt test sets and versioning
- Reducing hallucinations through prompt design
What to build
A prompt library with a 30-example test set and before/after scores.
What to study
- Calling LLM APIs: streaming, rate limits, keys
- Serving with FastAPI and simple UIs with Streamlit
- Caching and cost control
What to build
A small chat app with streaming responses, deployed for others to try.
What to study
- JSON schema outputs and validation
- Function / tool calling
- Retries and graceful failure
What to build
An invoice or resume parser that returns validated JSON.
What to study
- Chains, prompts and output parsers
- Document loaders and retrievers
- When a framework helps and when it gets in the way
What to build
Rebuild your chat app with LangChain and compare the code with your plain-API version.
RAG & model customisation
What to study
- Embedding models and similarity search
- Vector databases (e.g. pgvector, Pinecone, Weaviate)
- Chunking strategies and metadata filters
What to build
Index a document set in a vector database and query it with filters.
What to study
- Supervised fine-tuning vs prompting vs RAG
- LoRA and other parameter-efficient methods
- Preparing instruction datasets
What to build
LoRA fine-tune an open-weights model on a narrow task and compare it with prompting alone.
What to study
- Vision transformers and CLIP-style models
- Image captioning and visual question answering
- Combining text and image retrieval
What to build
An image search app that finds photos from a text description.
What to study
- The RAG pipeline end to end
- Re-ranking, hybrid search and citations
- Measuring retrieval quality
What to build
A document Q&A assistant that cites its sources, with a retrieval-quality report.
What to study
- Instruction tuning and reward models
- RLHF and DPO, conceptually and with TRL
- Where alignment fits in real products
What to build
Train a small reward model and run a preference-tuning loop on a toy task.
Agents & tool use
What to study
- ReAct, planning and reflection patterns
- Single-agent vs multi-agent setups
- Memory: short-term, long-term and retrieval
What to build
A research agent that searches, reads and summarises sources on a topic.
What to study
- Model Context Protocol (MCP) servers and clients
- Connecting agents to databases, CRMs and internal APIs
- Permissions and audit trails for tool calls
What to build
An MCP server that exposes two tools from a real API, used by your agent.
What to study
- Graphs, state and checkpoints
- Human-in-the-loop approvals
- Error handling in multi-step workflows
What to build
Rebuild your research agent as a LangGraph workflow with an approval step.
Production, evaluation & safety
What to study
- Docker images for AI apps
- CI/CD basics
- Secrets and environment configuration
What to build
Containerise your RAG assistant and deploy it with a CI pipeline.
What to study
- Building evaluation datasets
- LLM-as-judge and its limits
- Regression testing prompts and models
What to build
An eval harness that scores your assistant on 50 cases and runs on every change.
What to study
- Tracing LLM calls
- Tracking token cost and latency
- Dashboards and alerting
What to build
Add tracing and a cost dashboard to your deployed app.
What to study
- Managed model platforms on AWS, GCP and Azure
- Serverless deployment and autoscaling
- Data privacy and region choices
What to build
Deploy your app on one cloud using a managed model endpoint.
What to study
- Hallucination, bias and privacy risks
- Prompt injection and defences
- PII handling and content filtering
What to build
Add input and output guardrails to your assistant and document the risks you tested.
Portfolio & job readiness
What to study
- GenAI system design questions
- Explaining trade-offs: RAG vs fine-tuning, cost vs quality
- Coding rounds in Python
What to build
Mock-interview notes for three GenAI system design questions.
What to study
- Choosing a domain problem (healthcare, fintech, edtech)
- Writing clear READMEs and architecture notes
- Recording a short demo
What to build
A client-ready AI agent for one domain, with a public demo and write-up.
Fine-tuned text classifier
Adapting a pre-trained transformer to a real task.
Fine-tune a small pre-trained transformer on a labelled dataset, evaluate it properly and compare it with a classic ML baseline.
Structured data extractor
Turning messy documents into clean JSON.
Use an LLM API with schema-validated outputs to extract fields from invoices or resumes, with a prompt test set to track accuracy.
Document Q&A assistant
Retrieval-augmented answers with citations.
Index a document collection in a vector database and build an assistant that answers questions with cited sources and a retrieval-quality report.
LoRA fine-tune of an open model
Customising a model when prompting isn't enough.
Fine-tune an open-weights model with LoRA on a narrow task and document when it beats prompting and RAG, and when it doesn't.
Reward model & preference tuning
Teaching a model what good looks like.
Train a small reward model on preference data and run a preference-tuning loop, with a write-up of what changed.
Multimodal image search
Finding images from plain-language descriptions.
Embed images and text in a shared space and build a search app that retrieves photos from a description.
Tool-using research agent
An agent that plans, acts and asks for approval.
Build a LangGraph agent that searches, reads and summarises sources, calls tools through an MCP server and pauses for human approval.
Deployed GenAI service
From notebook to a monitored production API.
Containerise an LLM app, deploy it on a cloud platform with CI/CD, and add tracing plus a cost and latency dashboard.
Eval harness with guardrails
Proving your AI app works, and stays safe.
Create a 50-case evaluation set, automate scoring on every change, and add input and output guardrails against prompt injection and PII leaks.
Domain AI agent capstone
A client-ready agent for a real industry problem.
Pick a domain such as healthcare, fintech or edtech and ship an agent that combines retrieval, tools, evals and guardrails, with a public demo and write-up.
GenAI glossary 17 terms
Tap a term to see what it means. You will hear these in every GenAI interview.
- LLM
- Large language model: a neural network trained on huge amounts of text to predict and generate language.
- Transformer
- The neural network architecture behind modern LLMs, built around the attention mechanism.
- Token
- A chunk of text (often part of a word) that a model reads and writes. Pricing and limits are counted in tokens.
- Context window
- The maximum number of tokens a model can consider at once, including your prompt and its answer.
- Prompt engineering
- Designing instructions and examples so a model reliably produces the output you need.
- Embeddings
- Numeric vectors that capture meaning, so similar texts end up close together.
- Vector database
- A database built to store embeddings and find the most similar ones quickly.
- RAG
- Retrieval-augmented generation: fetching relevant documents and giving them to the model so answers are grounded.
- Fine-tuning
- Further training a pre-trained model on your own data to specialise it.
- LoRA
- Low-rank adaptation: a parameter-efficient fine-tuning method that trains small add-on weights instead of the whole model.
- Agent
- An LLM system that plans steps, calls tools and acts towards a goal, often over several turns.
- Tool calling
- Letting a model call functions or APIs, such as search or a database query, with structured arguments.
- MCP
- Model Context Protocol: an open standard for connecting AI applications to tools and data sources.
- Evals
- Systematic tests that measure how well an AI system performs on representative cases.
- Guardrails
- Checks on inputs and outputs that keep an AI system safe, on-topic and compliant.
- Hallucination
- When a model states something false or unsupported with confidence.
- Prompt injection
- An attack where malicious text tricks a model into ignoring its instructions.
Close your gaps with a structured programme
The Certificate Programme in Generative AI from CEP, IIT Delhi covers transformers, fine-tuning, RAG, agents and responsible AI through live weekend classes and hands-on projects.
What is Instruction Tuning, and Why is it Used?
Instruction tuning is a post-training process, meaning it happens after large-scale pretraining. It improves a model’s ability to follow natural-language instructions in question answering, summarisation, translation and conversation.
It mainly changes how a model responds rather than what it knows. The two questions below cover what changes inside the model and what that change delivers.
How does instruction tuning change a base model?
A base model is trained primarily to predict the next token in its training text. It learns to continue documents, so it treats a prompt as text to extend rather than a request to fulfil.
Instruction tuning trains the same model on examples that pair a task or prompt with a desired response. The aim is answers that match user intent and stronger instruction-following behaviour across tasks.
What is the main benefit of instruction tuning?
Diverse instruction examples can improve performance across many tasks, including some never seen during tuning. FLAN held out entire task clusters, such as natural language inference, and still reported large gains on them.
Its 137B instruction-tuned model beat zero-shot GPT-3 175B on 20 of 25 datasets. Scale mattered, though: tuning hurt unseen-task performance in models of 8B parameters and smaller.
Instruction tuning does not reliably add factual knowledge or guarantee correct answers. Accuracy still needs separate testing after training.
Supervised Fine-Tuning vs Instruction Fine-Tuning vs Pretraining
Pretraining teaches a model general language patterns through large-scale next-token prediction. Supervised fine-tuning (SFT) is the broader process of training on labelled input-output examples.
Instruction fine-tuning (IFT) specifically uses instruction-following examples. In LLM workflows, SFT and IFT frequently overlap, so the comparison below focuses on data and purpose.
How do pretraining, SFT and IFT differ?
The three stages differ more in their data and goals than in their mechanics. All three can use a token-prediction loss, but each learns from different examples.
Each stage also produces a different kind of model, which is why training order matters. The table compares them on four practical dimensions:
| Aspect | Pretraining | Supervised fine-tuning (SFT) | Instruction fine-tuning (IFT) |
|---|---|---|---|
| Main goal | Learn general patterns from data | Adapt a model using labelled examples | Improve instruction following |
| Training data | Large text corpora | Task-specific or general input-output pairs | Instructions with desired responses |
| Typical objective | Next-token prediction | Supervised prediction loss | Usually supervised next-token prediction |
| Outcome | Base model | Model adapted to a target task or behaviour | Model better suited to following user requests |
Is instruction tuning the same as SFT?
Often, in practice. The terms are used interchangeably when SFT runs on instruction-response datasets, which is the standard setup for chat assistants.
SFT can also cover supervised tasks that are not instruction following, such as mapping questions to SQL for one database. Whether a project counts as IFT depends on its data and goal.
Which Datasets and Formats are Used for Instruction Tuning?
Instruction tuning uses examples that pair an instruction with any needed context and a target response. Public datasets such as FLAN and Alpaca supply ready-made examples.
Chat templates then convert each conversation into the exact token format a model expects. Both the data and its formatting shape what the model learns.
What are FLAN and Alpaca instruction datasets?
FLAN and Alpaca are widely cited reference points, but they were built in very different ways. One reformats existing NLP datasets as instructions; the other generates new examples with a stronger model.
Their contrasting recipes show the two main ways teams source instruction data:
- FLAN: A Google family of instruction-tuning datasets and training approaches designed to improve generalisation across tasks. The original version rewrote 62 public NLP datasets as instructions, using ten templates per dataset.
- Alpaca: Stanford’s Alpaca instruction-following dataset holds 52,000 demonstrations generated with text-davinci-003 from 175 human-written seed tasks, using a modified Self-Instruct approach. Generating the data cost under $500.
Dataset size alone does not determine quality. Meta’s LIMA study on small-data alignment fine-tuned a 65B LLaMa model on only 1,000 carefully curated prompts and responses.
Human raters preferred its outputs to a 65B Alpaca reproduction trained on 52 times more data. Task diversity, response quality and relevance mattered more than row count.
How do chat templates structure training examples?
A chat template labels who said what before a conversation becomes tokens. It keeps training data in the same structure the model will see at inference, so training and serving formats match. Conceptually, one training example looks like this:
User: Explain photosynthesis in simple terms.
Assistant: Photosynthesis is the process by which plants use sunlight, water and carbon dioxide to make their own food and release oxygen.
Real models replace these plain labels with model-specific special tokens and role markers. Wrong or missing markers can sharply degrade a fine-tuned model, because it learned to rely on exact formatting.
Correct formatting tells the model which content belongs to the user and which is the target assistant response.
Why does response masking matter?
Masking decides which tokens count toward the training loss, the error signal the model learns from. It matters because a model learns to generate whatever the loss rewards.
In common causal language model SFT, where each token is predicted from the tokens before it, masking usually works like this:
- Loss is applied to target assistant tokens, while prompt tokens may be masked out.
- This trains the model to produce the desired response given the prompt, not to reproduce user text.
- The exact policy depends on the dataset and training setup; libraries usually expose it as completion-only or assistant-only loss settings.
How does the Instruction-Tuning Training Process Work?
The usual workflow selects a pretrained model, prepares instruction-response examples and applies the correct chat template. The model is then fine-tuned with a supervised loss.
Finally, its responses are evaluated before deployment. Data and formatting choices made early shape every later step, so they deserve as much care as training itself.
What are the main training steps?
The five steps run in a fixed order. A mistake made early, such as applying the wrong chat template, usually surfaces only later as weak responses. Treat each step as a checkpoint before moving on:
- Choose a base model: Select a model suited to the target task, context length and available hardware.
- Prepare the dataset: Clean examples, remove duplicates and check that every response is accurate and well formatted.
- Format conversations and define loss masking: Apply the model’s own chat template and decide which tokens contribute to the loss.
- Fine-tune the model: Update parameters with a supervised loss. LoRA (Low-Rank Adaptation) freezes base weights and trains small added matrices; on GPT-3 175B, it cut trainable parameters 10,000-fold and GPU memory threefold.
- Validate and save the best checkpoint: Compare checkpoints on held-out evaluations and keep the best-performing version.
What should engineers monitor during training?
Monitoring catches problems while they are still cheap to fix, before a full run’s compute is spent. Numeric signals show how optimisation is going, while sampled outputs show whether behaviour is actually improving.
Track both, with particular attention to these signals:
- Training and validation loss: The gap shows whether learning generalises beyond the training set.
- Overfitting: Validation loss rising while training loss keeps falling is a warning sign.
- Response quality: Sample outputs on fixed prompts to check tone, format and accuracy.
- Hardware use: GPU memory, throughput and utilisation reveal batch-size and efficiency limits.
A falling training loss alone does not prove better instruction following. LIMA’s authors found validation perplexity did not track generation quality, so they picked checkpoints using a 50-prompt development set.
How does Instruction Tuning Connect to Alignment?
Instruction tuning teaches a model to respond to instructions using supervised examples. Alignment methods such as RLHF and DPO can then optimise its behaviour using preference data.
The stages are related but not identical. Instruction tuning shows the model one good answer, while preference methods teach it to tell better answers from worse ones.
What happens after supervised fine-tuning?
Many pipelines next train on preferences: judgements of which of two responses is better, rather than a single target answer. This signal captures qualities such as helpfulness that one reference response cannot.
The two most common approaches use preferences differently:
- RLHF (reinforcement learning from human feedback): Common workflows collect preference comparisons, train a reward model, then optimise the model with reinforcement learning. In OpenAI’s InstructGPT paper on training with human feedback, this followed SFT, and outputs from the 1.3B model were preferred over those of 175B GPT-3.
- DPO (Direct Preference Optimization): DPO trains directly on preference pairs using a simple classification-style loss. It does not need standard RLHF’s separate reward-model-plus-RL pipeline.
The precise sequence varies by pipeline. Stages can be repeated, combined or skipped; LIMA reported strong results from SFT alone, with no reinforcement learning or preference modelling.
How do you Evaluate an Instruction-Tuned Model?
Evaluation checks whether tuning changed behaviour as intended. Use held-out prompts and representative tasks rather than training examples, which the model may have memorised.
Score each output on several dimensions, because a model can improve on one while slipping on another:
- Instruction following: Does the response do what was asked, including length or audience constraints?
- Task accuracy: Are answers correct against references or expert review?
- Response relevance: Does the output stay focused on the user’s intent?
- Format compliance: Does it honour requested structures such as JSON, lists or word limits?
- Robustness: Does quality hold when prompts are rephrased or contain typos?
- Safety: Where relevant, check refusals on harmful requests and over-refusal on harmless ones.
Always compare the tuned model with the base model on the same prompts. Without that baseline, you cannot tell whether training produced measurable improvement or merely changed style.
Conclusion
Instruction tuning adapts a pretrained model to follow instructions through supervised examples. Later alignment stages can then shape its behaviour further using preferences or reward signals.
The practical lesson is that SFT sets the baseline every later stage builds on. Data diversity, correct formatting and honest evaluation decide how strong that baseline is.
To practise this pipeline end to end, from SFT and instruction tuning to reward models and RLHF with TRL, explore the Varsity IIT Delhi Generative AI course.
Frequently Asked Questions About Instruction Tuning
Can instruction tuning be performed on a small dataset?
Yes. A small, high-quality dataset can improve a model for a focused task or behaviour, provided the examples are consistent and reflect real user requests.
In LIMA, adding just 30 dialogue examples raised the share of excellent multi-turn responses from 45.2% to 76.1%. Results still depend on task diversity, model capability and data quality.
Does instruction tuning change the model’s architecture?
Usually not. Standard instruction tuning updates existing weights and keeps the architecture intact. LoRA adds small trainable adapter matrices, but these can be merged into the base weights after training, so inference latency does not increase.
Can synthetic data be used for instruction tuning?
Yes. Another model can generate instructions and responses, as text-davinci-003 did for Alpaca. Check every batch for errors, repetition, bias and weak answers before training on it. Also confirm the generating model’s terms of use allow training on its outputs.
What is the difference between instruction tuning and prompt engineering?
Prompt engineering changes the input given to a model at inference time and leaves its weights untouched. Instruction tuning changes the model’s learned parameters through training on examples. Teams often prompt first and tune when prompts cannot deliver consistent behaviour.
Does instruction tuning improve factual accuracy?
It can improve performance on specific tasks, but it does not guarantee factual correctness. Tuned models can still hallucinate, and a confident, well-formatted answer can hide an error. Measure factual reliability separately with verified reference answers.
Can instruction tuning cause catastrophic forgetting?
Yes. Poor data choices or aggressive optimisation can erode capabilities the base model already had. Diverse data, conservative learning rates and evaluations on retained skills help reduce this risk. Re-running the base model’s key benchmarks after tuning shows whether anything was lost.
Is instruction tuning required before RLHF?
It is common in modern LLM pipelines, because preference training needs candidate responses worth comparing. InstructGPT, for example, applied RLHF to an SFT model. However, it is not an absolute requirement for every preference-optimisation setup.
What is the role of a tokenizer in instruction tuning?
The tokenizer converts text and special chat markers into the token IDs the model reads. Its vocabulary and template conventions must match the model and training data. Register any new role markers as special tokens so they are not split apart.
How much data is needed to instruction-tune an LLM?
There is no universal minimum; it depends on model size, task complexity, example quality and the behaviour change needed. In LIMA’s ablations, a 16-fold data increase without more prompt diversity left quality flat. Measure progress on held-out evaluations.
Can instruction tuning be combined with quantization or distillation?
Yes. Quantization reduces numerical precision to cut memory and serving costs, while distillation transfers behaviour from a teacher model to a smaller student. Both complement instruction tuning, but the combined workflow needs separate quality and efficiency checks.
Sources
Finetuned Language Models Are Zero-Shot Learners (Wei et al., ICLR 2022)
Alpaca: A Strong, Replicable Instruction-Following Model (Stanford CRFM, 2023)
LIMA: Less Is More for Alignment (Zhou et al., NeurIPS 2023)
Training Language Models to Follow Instructions with Human Feedback (Ouyang et al., NeurIPS 2022)
LoRA: Low-Rank Adaptation of Large Language Models (Hu et al., 2021)