Step 4 of 5

Training Pipeline: Pretraining → SFT → Alignment

How a base model becomes an assistant, what LoRA and QLoRA change, and how to fine-tune on a free GPU without fooling yourself.

16 min read

A chat assistant starts life as something much less helpful: a base model that has read a large slice of the internet and can continue any text, but doesn't follow instructions, doesn't know it's an assistant, and will happily continue your question with three more questions. Getting from there to a useful model takes three stages.

  1. 01PretrainingTrillions of tokens → base model
  2. 02SFTInstruction → response pairs
  3. 03Preference alignmentRLHF, DPO, constitutional methods
  4. 04AssistantHelpful, follows instructions
The standard recipe. Each stage uses far less data than the one before it, and changes behavior more than knowledge.

Stage 1 - Pretraining#

The model learns next-token prediction on an enormous, deduplicated, filtered corpus: web pages, books, code, papers. This is where nearly all of a model's knowledge and capability comes from - and nearly all of the cost.

Two findings shape how labs size pretraining runs:

  • Scaling laws (OpenAI, 2020): loss falls as a smooth power law as you increase parameters, data, and compute. Performance is predictable before you spend the money.
  • Compute-optimal training (DeepMind's Chinchilla, 2022): many large models were undertrained. For a fixed compute budget, scale data alongside parameters - roughly 20 training tokens per parameter.

Model sizes span a wide range. Open-weight families typically ship at around 1B (on-device), 7-8B (a laptop or single GPU), ~70B (a server), and 400B+ (a cluster). Frontier labs generally don't publish parameter counts.

Stage 2 - Supervised fine-tuning (SFT)#

SFT trains the base model on curated examples of the behavior you want: an instruction and an ideal response, formatted with a chat template that marks system, user, and assistant turns. Tens of thousands of high-quality examples go a long way - quality and diversity matter far more than volume.

After SFT, the model follows instructions and answers in an assistant voice. It has learned a format and a style, not a new body of knowledge.

Base model
The raw model after pretraining - it can continue text but doesn't follow instructions or know it's an assistant.
SFT (Supervised Fine-Tuning)
Training on curated instruction → response pairs to teach the model to follow instructions in an assistant voice.
Chat template
A formatting convention that marks system, user, and assistant turns so the model knows which role is speaking.
Scaling laws
Empirical finding that loss falls as a smooth power law with more parameters, data, and compute - performance is predictable before training.

Stage 3 - Preference alignment#

Many good behaviors are easier to judge than to demonstrate: which of two answers is more helpful, more honest, less harmful? Alignment methods learn from those comparisons.

RLHF

InstructGPT

Collect human rankings of responses, train a reward model to predict them, then optimize the policy against that reward with reinforcement learning (classically PPO), with a penalty for drifting too far from the SFT model.

DPO

2023

Direct Preference Optimization skips the reward model and RL loop. It trains directly on (chosen, rejected) pairs with a simple classification-style loss. Simpler and more stable; widely used for open models.

Constitutional AI

Anthropic

Replace much of the human labeling with AI feedback guided by a written set of principles. The model critiques and revises its own outputs, and preferences come from a model judging against the constitution.

Full fine-tuning vs parameter-efficient methods#

When you fine-tune, you rarely retrain every weight. A 7B model in 16-bit precision is 14 GB of weights; full fine-tuning also needs gradients and optimizer state - easily 4-5× the model size in GPU memory.

LoRA (Low-Rank Adaptation) freezes the original weights and learns a small update for selected matrices, factored into two thin matrices:

W′=W+αr⋅BA\mathbf{W}' = \mathbf{W} + \frac{\alpha}{r} \cdot \mathbf{B}\mathbf{A}

W is frozen (d × k). Only A (r × k) and B (d × r) train, with rank r much smaller than d. For a 4096 × 4096 matrix, full update = 16.8M parameters; LoRA at r = 16 = 131k - under 1%.

SettingTypical valuesEffect
Rank r8-64 (up to 128)Capacity of the update. Higher = more expressive, more memory
Alpha αOften r or 2rScales the update's strength
Target modulesAttention (q, k, v, o) ± MLP projectionsIncluding MLP layers usually helps quality
Learning rate~1e-4 to 2e-4Higher than full fine-tuning because few params train

QLoRA goes further: load the frozen base model in 4-bit precision and train LoRA adapters on top. A 7-8B model then fits comfortably in a single 16 GB GPU, which is what makes free notebook GPUs viable.

LoRA
Low-Rank Adaptation - freezes original weights and trains two small matrices per layer, updating under 1% of parameters.
QLoRA
LoRA on a 4-bit quantized base model - fits a 7-8B model fine-tune on a single 16 GB consumer GPU.
RLHF
Reinforcement Learning from Human Feedback - trains a reward model on human preferences, then optimizes the policy against it.
DPO
Direct Preference Optimization - learns from chosen/rejected pairs without a separate reward model or RL loop. Simpler than RLHF.
Catastrophic forgetting
When fine-tuning on new data erodes capabilities the model learned during pretraining.

Fine-tuning on consumer hardware#

You can run a real fine-tuning experiment for free. A practical setup:

~4B

model size (e.g., Qwen3-4B)

4-bit

QLoRA base weights

T4 · 16 GB

free Kaggle/Colab GPU

Unsloth + TRL

fast LoRA + SFT trainer

The shape of the code (library APIs evolve, so check the current Unsloth notebook for exact arguments):

from unsloth import FastLanguageModel
from trl import SFTTrainer, SFTConfig

model, tokenizer = FastLanguageModel.from_pretrained(
    "unsloth/Qwen3-4B", max_seq_length=2048, load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(
    model, r=16, lora_alpha=16, lora_dropout=0,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
)
trainer = SFTTrainer(
    model=model, processing_class=tokenizer, train_dataset=dataset,
    args=SFTConfig(per_device_train_batch_size=2, gradient_accumulation_steps=4,
                   learning_rate=2e-4, max_steps=300, logging_steps=10,
                   output_dir="outputs"),
)
trainer.train()

Measure it properly#

The most common fine-tuning mistake isn't a bad hyperparameter - it's believing a result that isn't real. Design the experiment so it can fail:

An honest fine-tuning experiment

  1. 1Hold out data the model never trains on, from the same distribution.
  2. 2Measure style with held-out perplexity: does the model find your target text more predictable after training?
  3. 3Measure facts with a probe: ask specific questions whose answers appear only in the training data, and grade exact answers.
  4. 4Add a control run: train on shuffled or unrelated data with the same settings. If the control 'improves' too, your gain is an artifact.
  5. 5Compare against the base model with a good prompt - sometimes few-shot prompting gets you most of the way for free.
  6. 6Check for regressions on a small general benchmark to catch catastrophic forgetting.

Typical outcome: perplexity on the target style drops sharply (style learned), while the fact probe barely moves or produces confident wrong answers (facts not reliably learned). That's the style-vs-facts lesson, measured.

Papers behind this guide

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.