01 · Memory and cost
VRAM, time, and cost
Two published planning tables, plus a time and cost line that uses a throughput you measure. Nothing here replaces a short dry run.
Commands you can paste, from a base model to your own fine-tune running on your machine.
Start at SFT and LoRA on a published instruct model.
Usual start SFT and LoRA on an instruct model. Pretraining from scratch is a later choice.
Twelve sections, plus a lab of interactive tools. Jump to a tool or a stage; the earlier ones still apply.
12
sections, in the order of a run
34
tools and repos with links
22
copy-paste recipes and commands
$0
to read this page. No account.
Lab
Most useful runs begin with supervised fine-tuning and a LoRA on a published instruct model, plus an eval you trust. Pretraining from scratch is a later choice: you need a new tokenizer, a language or domain that existing bases do not cover, and the compute to finish a full run.
Seven tools. Change a value, read what it does, copy a config. The twelve sections below stay as the written path.
01 · Memory and cost
Two published planning tables, plus a time and cost line that uses a throughput you measure. Nothing here replaces a short dry run.
02 · Before you train
Answer five questions. The recommendation updates as you go.
03 · The twelve stages
Pick a stage. Read when to do it, when to skip it, the inputs and outputs, the knobs, and a config you can copy.
04 · Reading a run
Schematic curves, not a real run. Switch a pattern to see what it means. On a fine pointer, hover a line for a short note.
05 · A full starting config
Pick a goal, a card, and a model class. You get a method, a starting config, and the commands to run and eval it.
06 · The string the model sees
Type a turn, pick a format. Train and serve in the same one. Mixing templates is a common silent failure.
07 · What goes wrong
Pick an answer. The note tells you why it is right or why it is not.
Training loss fell, but the model got worse on your private eval. What do you check first?
The run dies with an out-of-memory error on the first step. What do you change first?
You want the model to answer from a wiki that changes every week. Do you fine-tune on the wiki?
01 to 03 Start
Choose a checkpoint you are allowed to train and ship, then spend more time on the data than on the trainer.
Start from a published open-weight checkpoint unless you have a concrete reason to pretrain. The model card and the license are part of the choice: some cards restrict use, redistribution or the number of monthly active users. Read them before you train or ship.
Look at the official model hubs and pick a current release in a family you can live with:
-it) builds. Terms are on the official Gemma pages and the Hugging Face cards under google.For each candidate, write down: license, parameter count (and active experts, if MoE), context length, tokenizer, train vs instruct variant, and whether you can load it in the trainer you picked.
Data quality decides the run more often than the trainer does. A small, consistent set you have read will beat a large dump of mixed chat logs. Keep a held-out slice from the same distribution as the training set, and keep public eval sets out of training.
A practical cleaning stack for web-scale text is datatrove. NVIDIA’s NeMo Curator is the other common choice when you already sit in that stack. Install datatrove and start from its FineWeb example:
pip install datatrove
# The repo ships a full FineWeb-style pipeline you can adapt:
# https://github.com/huggingface/datatrove/blob/main/examples/fineweb.py
git clone --depth 1 https://github.com/huggingface/datatrove.git
cd datatrove
# Read examples/fineweb.py, then point the readers at your shards
# and keep the filter / minhash stages.
python examples/fineweb.py
Public corpora worth knowing (still read each card for license and how they were filtered):
Large web-scale pretraining corpus from Hugging Face, with a documented datatrove pipeline.
Education-filtered FineWeb slice. Near-dedup in the original run was per Common Crawl dump, not always cross-dump.
Ai2’s open pretraining corpus, built to go with the OLMo stack.
DataComp-LM baseline data, also the source of the CORE metric used in some pretrain speedruns.
A model never sees letters. It sees integer ids from a fixed vocabulary. If you start from a published base, keep that tokenizer. Changing it mid-stream silently breaks every pretrained embedding.
apply_chat_template). Train and serve with the same one.For a from-scratch vocab, Hugging Face tokenizers (Rust, with a Python API) and SentencePiece are the usual tools. tiktoken is the library for OpenAI-style BPE vocabularies you already have, not a trainer for a new one.
# Install: pip install sentencepiece
# Train a BPE model on a raw text file (one document per line is a common layout).
spm_train \
--input=data.txt \
--model_prefix=spm \
--vocab_size=32000 \
--model_type=bpe \
--character_coverage=0.9995 \
--byte_fallback=true
# Writes spm.model and spm.vocab
from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders, processors
tokenizer = Tokenizer(models.BPE(unk_token="<unk>"))
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
trainer = trainers.BpeTrainer(
vocab_size=32000,
special_tokens=["<unk>", "<s>", "</s>", "<pad>"],
)
tokenizer.train(["data.txt"], trainer)
tokenizer.decoder = decoders.ByteLevel()
tokenizer.post_processor = processors.ByteLevel(trim_offsets=True)
tokenizer.save("tokenizer.json")
04 to 06 Train
From-scratch pretraining is how you learn the stack. Fine-tuning a published base is how most products get trained.
Pretraining from scratch means a new tokenizer, a new set of weights, and enough tokens to make the compute worth it. Continued pretraining (CPT) starts from a published base, keeps its tokenizer, and keeps training on domain or language text with a lower learning rate.
nanochat is the current small stack for the whole path (tokenizer, pretrain, SFT, eval, a CLI). nanoGPT is earlier and now marked deprecated in its own README; keep it as a short pretrain loop to read, and use nanochat for a full run. The speedrun script is written for a single 8×H100 node and finishes in a couple of hours; read the script for the current flags before you spend the rental.
git clone https://github.com/karpathy/nanochat.git
cd nanochat
uv sync --extra gpu # CUDA (A100 / H100 / …)
# uv sync --extra cpu # CPU or Apple MPS, for tiny runs only
source .venv/bin/activate
# On a blank 8×H100 node this is the reference path:
# tokenizer, pretrain, eval, SFT, then you can chat.
bash runs/speedrun.sh
# When it finishes:
python -m scripts.chat_cli
OMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \
--depth=12 \
--run="d12" \
--model-tag="d12" \
--core-metric-every=999999 \
--sample-every=-1 \
--save-every=-1
For larger from-scratch or CPT jobs, look at Megatron-LM, torchtitan, LitGPT, and NVIDIA NeMo. In Axolotl, raw-text CPT is a completion dataset type, not a chat template.
# cpt.yml: keep the original tokenizer; lower the learning rate vs a from-scratch run
base_model: Qwen/Qwen3-0.6B
datasets:
- path: ./domain_text.jsonl # {"text": "..."} per line
type: completion
sequence_len: 4096
sample_packing: true
micro_batch_size: 1
gradient_accumulation_steps: 8
num_epochs: 1
learning_rate: 2.0e-5
lr_scheduler: cosine
warmup_ratio: 0.05
optimizer: adamw_torch_8bit
bf16: true
flash_attention: true
gradient_checkpointing: true
output_dir: ./outputs/cpt
# axolotl train cpt.yml
SFT teaches a model to produce a specific kind of answer, in a specific format. The usual unit is a conversation or an instruction-response pair. The common failure is training on the prompt tokens as well as the answer, or training with a different chat template than the one you serve.
tokenizer.apply_chat_template. In Axolotl, prefer type: chat_template for OpenAI-style message lists, and alpaca only when the file really is instruction / input / output.train_on_inputs: false in Axolotl; TRL’s SFT trainer does this for conversational data). If you train on the prompt, loss can fall while the model only learns to copy the question.TRL is the straight Hugging Face path. The official quick start fine-tunes a small Qwen on a conversational set:
pip install -U "trl[quantization]"
# sft_train.py
from trl import SFTTrainer
from datasets import load_dataset
trainer = SFTTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()
Axolotl is a YAML-first trainer used for a lot of open fine-tunes. Install a current PyTorch build that matches your CUDA, then:
pip3 install "axolotl[deepspeed]"
axolotl fetch examples
axolotl train examples/llama-3/lora-1b.yml
# my_sft.yml
base_model: Qwen/Qwen3-0.6B
load_in_4bit: true
adapter: qlora
lora_r: 16
lora_alpha: 16
lora_target_linear: true
datasets:
- path: ./my_data.jsonl
type: chat_template
# each line: {"messages":[{"role":"user","content":"..."},{"role":"assistant","content":"..."}]}
val_set_size: 0.05
sequence_len: 2048
sample_packing: true
train_on_inputs: false
micro_batch_size: 2
gradient_accumulation_steps: 4
num_epochs: 2
learning_rate: 2e-4
optimizer: adamw_bnb_8bit
lr_scheduler: cosine
warmup_ratio: 0.05
bf16: true
flash_attention: true
gradient_checkpointing: true
output_dir: ./outputs/sft
# axolotl train my_sft.yml
Other SFT entry points with official recipes: LLaMA-Factory (llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml), torchtune (tune run lora_finetune_single_device --config llama3_1/8B_lora_single_device; run tune ls for the current config names), LitGPT, and Unsloth in the next section.
LoRA freezes the base weights and trains a pair of thin matrices on chosen layers. You update a small fraction of the parameters. QLoRA does the same after loading the base in 4-bit, which cuts memory. Full fine-tuning of every weight is usually unnecessary; if LoRA cannot learn the task, full fine-tuning often will not either, and the first place to look is the data and the template.
r 16 to 64, lora_alpha equal to r or 2r, dropout 0, bias none, and target the attention and MLP projections (q,k,v,o,gate,up,down), not only q and v.Unsloth is the usual first trainer when you want a fast QLoRA loop on one GPU, including free Colab notebooks. PEFT is the adapter library those trainers sit on. bitsandbytes provides the 4-bit load.
pip install unsloth
# Or: uv pip install unsloth --torch-backend=auto
import torch
from unsloth import FastLanguageModel
from trl import SFTTrainer, SFTConfig
from datasets import load_dataset
max_seq_length = 2048
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/llama-3.1-8b-Instruct-bnb-4bit", # swap for the model you chose
max_seq_length=max_seq_length,
load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(
model,
r=16,
target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
lora_alpha=16,
lora_dropout=0,
bias="none",
use_gradient_checkpointing=True,
random_state=3407,
)
trainer = SFTTrainer(
model=model,
args=SFTConfig(output_dir="./output", max_length=max_seq_length),
train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()
# Merge to 16-bit, or export GGUF for llama.cpp / Ollama
model.save_pretrained_merged("merged_model", tokenizer, save_method="merged_16bit")
model.save_pretrained_gguf("gguf_model", tokenizer, quantization_method="q4_k_m")
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e .
llamafactory-cli version
llamafactory-cli train examples/train_lora/qwen3_lora_sft.yaml
pip install torchtune
# List the configs your install ships, names change:
tune ls
tune run lora_finetune_single_device --config llama3_1/8B_lora_single_device
07 to 08 Align
SFT gets the format right. Preference or reward training is for when you can say which answer is better, or when a scorer can grade it.
After SFT, you can push the model toward answers people (or a program) prefer. The three names you will see most:
prompt, chosen, rejected. The two completions must answer the same prompt. Conversational forms are fine if the trainer applies the chat template consistently.from trl import DPOTrainer
from datasets import load_dataset
# Each row needs a prompt plus chosen / rejected completions.
# Official example set: trl-lib/ultrafeedback_binarized
trainer = DPOTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
)
trainer.train()
pip install "trl[math_verify]"
# train_grpo.py
from datasets import load_dataset
from trl import GRPOTrainer
from trl.rewards import accuracy_reward
dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
trainer = GRPOTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
reward_funcs=accuracy_reward,
train_dataset=dataset,
)
trainer.train()
# Multi-GPU:
# torchrun --nproc_per_node 8 train_grpo.py
For larger RL jobs, OpenRLHF (pip install "openrlhf[vllm]") and veRL are the common dedicated stacks. Axolotl also exposes DPO and GRPO through YAML (rl: dpo or rl: grpo); for GRPO it recommends LoRA plus a vLLM sync rather than shipping full merged weights on every step. The Hugging Face alignment-handbook still has end-to-end recipes for the TRL trainers.
Distillation trains a smaller student to follow a larger teacher. The cheap form is to generate teacher answers and run SFT on them. The tighter form matches the teacher’s token distribution (knowledge distillation), often on sequences the student itself produces (on-policy distillation), so the student is not learning to imitate tokens it would never reach.
from trl import DistillationTrainer
from datasets import load_dataset
# Dataset needs a prompt column. Teacher and student should share a vocabulary.
trainer = DistillationTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
teacher_model="Qwen/Qwen2.5-1.5B-Instruct",
train_dataset=load_dataset("trl-lib/Capybara", split="train"),
)
trainer.train()
09 to 12 Ship
A falling loss is not a release. Measure the job, plan the box, then serve the same template you trained.
Evaluate the base model, the mid-run checkpoints, and the final merge on the same suite. Training loss is not a task score. If the suite leaked into the training data, the number is not a result.
--limit) to check the plumbing, then a full run overnight.lm-evaluation-harness is the standard CLI. LightEval is Hugging Face’s evaluation library and is handy if you already live in that stack. Many trainers also ship their own eval scripts (nanochat’s scripts.base_eval and scripts.chat_eval, torchtune eval recipes).
pip install "lm-eval[hf]"
# Quick plumbing check
lm-eval run \
--model hf \
--model_args pretrained=./merged_model \
--tasks hellaswag \
--limit 100
# List tasks, then run the ones you mean to report
lm-eval ls tasks
lm-eval ls tasks --pattern "mmlu*"
lm-eval run \
--model hf \
--model_args pretrained=./merged_model,dtype=bfloat16 \
--tasks hellaswag,gsm8k,ifeval \
--batch_size 8 \
--device cuda:0
pip install lighteval
lighteval accelerate "model_name=./merged_model" hellaswag
Plan memory and time before you rent a week of GPUs. Hourly prices move; look them up on the provider’s page the day you book. What you can compute ahead of time is the shape of the job.
micro_batch × gradient_accumulation × number of GPUs. Keep tokens per step in a range the recipe you copied was written for, rather than inventing a new one on a huge batch.A rough planning habit: write down model size, method (full / LoRA / QLoRA), sequence length, tokens in the dataset, epochs, and the GPU you will rent. From the trainer’s own memory notes or a 50-step dry run, read peak VRAM and tokens per second, then scale wall-clock to the full token count. Compare that hours figure against the provider’s current hourly rate yourself. Do not trust a screenshot of last year’s prices.
# PyTorch, after the trainer is constructed and one step has run:
import torch
print("allocated_gb", round(torch.cuda.max_memory_allocated() / 1024**3, 2))
print("reserved_gb", round(torch.cuda.max_memory_reserved() / 1024**3, 2))
# In Axolotl / TRL, set max_steps to a small number first and confirm
# the job fits before a long epoch.
You can train on a local card, on a rented GPU by the hour, or on a reserved cluster. For a first LoRA, a single 24 GB-class card (or a rented equivalent) is enough to learn the loop. Pretraining and large GRPO jobs want a multi-GPU node.
Common places people rent training GPUs, with their official pages. This is not a ranking, and it is not a price list.
GPU pods billed by the second, with secure and community clouds. Check the live pricing page.
Marketplace of host-set rates, including interruptible options. Read the current pricing guide before you bid.
On-demand GPU VMs, including the kind of 8×H100 node a full-path speedrun expects.
Serverless GPUs billed for active compute time. Useful for short, scripted jobs.
GPU cloud and fine-tune APIs. Confirm whether you need a raw box or a hosted fine-tune.
The major clouds’ GPU instance families (P/G, A3/A4, ND). Familiar IAM and networking, often a higher list price.
GPU cloud used for larger training jobs. Ask for current instance availability.
GPU cloud. Confirm regions and the GPU SKUs you need.
Serve the same tokenizer and chat template you trained. A correct merge with the wrong template looks like a failed train. Do not ship a mid-run checkpoint because the loss looked low.
pip install vllm
vllm serve ./merged_model --api-key local
# Or keep the adapter separate:
vllm serve <base-model> --enable-lora --lora-modules my-lora=./adapter
# Requests then use "model": "my-lora"
pip install sglang
python3 -m sglang.launch_server \
--model-path <base-model> \
--enable-lora \
--lora-paths my-lora=./adapter
# After you have a GGUF (Unsloth save_pretrained_gguf, or llama.cpp convert):
# llama.cpp
llama-server -m ./gguf_model/model-q4_k_m.gguf --port 8080
# With a LoRA GGUF:
# llama-server -m ./base.gguf --lora ./adapter.gguf
# Ollama, after a Modelfile that points at the GGUF:
ollama create my-sft -f Modelfile
ollama run my-sft
from openai import OpenAI
ai = OpenAI(base_url="http://localhost:8000/v1", api_key="local")
r = ai.chat.completions.create(
model="my-lora", # or the served model name
messages=[{"role": "user", "content": "Summarize this change in one paragraph."}],
)
print(r.choices[0].message.content)
Install links and source repos for the trainers, data tools, evals and servers used above. Open the repo or the docs and use the command on that page if a flag has moved.
Minimal stack: tokenizer, pretrain, SFT, eval and a CLI. The current successor to nanoGPT.
Short, readable pretrain loop. Its README now points you to nanochat for new work.
Fast LoRA / QLoRA / RL on one GPU, with merge and GGUF export. Docs at unsloth.ai.
YAML trainer for SFT, CPT, LoRA, QLoRA, DPO and GRPO. Docs at docs.axolotl.ai.
Hugging Face trainers: SFT, DPO, GRPO, distillation, and the rest of the post-training list.
PyTorch-native recipes and YAML configs for LoRA and full fine-tunes.
CLI and web UI over a large set of official example YAMLs.
Lightning’s from-scratch and fine-tune CLI, including a JSON data path.
The adapter library (LoRA and friends) that most of the trainers above sit on.
4-bit and 8-bit loaders used by QLoRA.
Model definitions, tokenizers, chat templates and the common load path.
The usual way to load Hub and local shards into a trainer.
FineWeb-style pipeline: filters, PII, exact dedup and MinHash near-dedup.
NVIDIA’s data-curation stack for large pretraining corpora.
Fast BPE / Unigram training and tokenization.
The other standard way to train a vocab from raw text.
OpenAI-style BPE: use it to speak an existing vocab, not to train a new one.
NVIDIA’s large-scale pretrain stack (tensor, pipeline and data parallel).
PyTorch’s pretraining platform for large dense and MoE runs.
ZeRO sharding and memory tricks used by Axolotl and many others.
Launch and device placement for Hugging Face trainers.
Fused attention kernels. Most trainers expose this as a flag.
RLHF / PPO / GRPO stack, often paired with a vLLM rollout.
Volcengine’s RL training library, used in a lot of recent GRPO work.
End-to-end recipes around TRL for SFT and preference training.
The standard CLI for public LLM benchmarks.
Hugging Face’s evaluation library.
High-throughput serving, including LoRA modules.
High-throughput serving with its own LoRA path.
Local GGUF inference and a server. Works on CPU and a lot of GPUs.
Simple local runner on top of llama.cpp-style weights.
Hugging Face’s production generation server.
NVIDIA’s optimized inference runtime.
Local training and inference on Apple silicon.
Short answers for the decisions that usually stall a first run.
Only when you need a new tokenizer or a base that existing releases cannot give you, and you can finish the run. For a product or a personal assistant, start with SFT and a LoRA on a published instruct model. Use nanochat if you want to learn the whole stack on a single node.
Start with LoRA or QLoRA. Full fine-tuning costs more memory and is rarely the first lever to pull. If the adapter cannot learn the task, inspect the data, the chat template and the eval before you train every weight.
There is no honest universal number. Start with a set you can read, in one template, with a held-out slice. Add more when the private eval stops moving. A few hundred clean, on-task examples will often beat a few hundred thousand mixed chat logs.
Usual causes: training on prompt tokens as well as answers; a different chat template at serve time; eval contamination; too many epochs on a small set; a learning rate that erased the base. Compare the served artifact to the untouched base on a fixed eval, and print a few decoded samples at the same settings.
For a first 7B to 8B QLoRA, a single 16 to 24 GB-class card is the usual starting band. Grow the box when the sequence length, the batch, or the model no longer fits. For from-scratch pretraining or large GRPO, rent a multi-GPU node and read the trainer’s own script (nanochat’s speedrun is written for 8×H100). Check today’s hourly rate yourself.
Not in one run, and not between train and serve. Pick the template that ships with the base (or a template you have fully applied to every example), and use it in the server too.
When the model already produces the format you want, and you can label a better answer or score one in code. DPO needs preference pairs. GRPO needs a reward function that is hard to game. Neither replaces a clean SFT set.
Pin the base revision, the trainer version, the dataset shard or commit, the random seed where the trainer allows it, and the decoding settings for eval. Save the YAML or the script next to the checkpoint. A merge without those notes is hard to defend.