Train your own model

Commands you can paste, from a base model to your own fine-tune running on your machine.

steps
12
tools
34
recipes
22
to read
$0

Contents in working order

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.

Start at fine-tuning, then widen the stack

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.

Work through the path

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

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.

Time and cost, from a dry run

02 · Before you train

Prompt, retrieval, or a fine-tune

Answer five questions. The recommendation updates as you go.

Where does the knowledge live?
Does a careful prompt already pass a held-out set?
What are you trying to change?
Do you already have a clean task set you can inspect?
How often do the facts change?

03 · The twelve stages

Step explorer

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

Loss-curve explorer

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.

Healthyschematic

  • Training loss. Falls when the model fits the batch.
  • Validation loss. Should stay down if the model is generalizing.

05 · A full starting config

Recipe builder

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

Chat-template previewer

Type a turn, pick a format. Train and serve in the same one. Mixing templates is a common silent failure.

Rendered template

      

07 · What goes wrong

Three failure cases

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

Base, data and tokenizers

Choose a checkpoint you are allowed to train and ship, then spend more time on the data than on the trainer.

01Pick a base model

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.

  • Use an instruct or chat checkpoint when you will fine-tune on conversations. It already knows a chat template, so you need less data to get a usable assistant.
  • Use a base (completion) checkpoint for continued pretraining on raw text, or when you want to impose a new template from a clean start.
  • Pick a size you can both train and serve on the hardware you have. Get the data format and the eval loop working on a small model, then move up.
  • Match context length, architecture (dense or mixture-of-experts) and modalities to the job. An MoE can be lighter at inference than its total parameter count suggests, but the training setup is pickier.
  • Pin the revision you evaluate (a commit hash or a dated repo). “Latest” is not a reproducible base.
  • If a trainer publishes 4-bit convenience weights (for QLoRA), those are still bound by the original license and should be treated as a packing of the same model.

Look at the official model hubs and pick a current release in a family you can live with:

  • Qwen. strong general and multilingual dense and MoE lines, including recent Qwen3.5 and Qwen3.8 releases. Check each card for the license on that size.
  • Gemma. Google’s Gemma 4 line, including instruct (-it) builds. Terms are on the official Gemma pages and the Hugging Face cards under google.
  • Llama. Meta’s Llama releases. The community license is not a blanket public-domain grant; read it for your distribution plans.
  • OLMo. Ai2’s OLMo 3 line, useful when you want more of the stack (data, code, checkpoints) in the open. Cards live under allenai.
  • gpt-oss. OpenAI’s open-weight gpt-oss checkpoints, including tool-use oriented builds. Fine-tuning notebooks exist in Unsloth and Axolotl.
  • Mistral. Mistral and Ministral releases. Confirm the license on the specific card.

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.

02Data: collect, clean and dedupe

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.

  • Collect only text you have the right to use. Scraped sites, books, tickets and private chats each have a license or a terms-of-service problem. Record the source of every shard.
  • For pretraining or continued pretraining, start from a maintained corpus rather than raw crawls when you can: FineWeb and FineWeb-Edu, Dolma, and DCLM are built for this and already have quality filters and dedup stages.
  • Run a pipeline, in order: language identification, quality and boilerplate filters, PII redaction, exact document dedup, then near-dedup (MinHash or similar). Then decontaminate against the evals you will report.
  • Near-dedup matters. Exact string matches miss paraphrases and repeated news wires. MinHash over shingles (as in the FineWeb / datatrove pipeline) is the usual next step. Decide whether you dedup within a dump or across dumps.
  • For supervised fine-tuning, put every example in one format (chat messages or a single instruction scheme), drop empty or truncated answers, and fix obvious label noise by hand on a sample. Mix sources only after you have normalized the template.
  • Do not train on your test. If a public benchmark string appears in the corpus, remove it or you will be measuring memorization.

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:

install + FineWeb-style pipeline
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):

03Tokenizers

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.

  • Reuse the base model’s tokenizer for continued pretraining, SFT, LoRA, preference training and serving. Load it from the same repo as the weights, including special tokens and the chat template.
  • Train a new tokenizer only when you pretrain from scratch, or when the existing vocab is a poor fit (a new script, a language that tokenizes into huge sequences, a domain with a private symbol set).
  • Measure compression on your data (bytes per token, or characters per token). A tokenizer that explodes sequence length will waste context and compute.
  • After you train a vocab, freeze it. Adding tokens later means resizing embeddings and, for a pretrained model, training those new rows with care.
  • Chat models depend on special tokens and a template (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.

SentencePiece BPE, from scratch
# 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
Hugging Face tokenizers, BPE
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

Pretrain, SFT and adapters

From-scratch pretraining is how you learn the stack. Fine-tuning a published base is how most products get trained.

04Pretraining and continued pretraining

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.

  • Train from scratch when you need a new vocab or a base that existing releases cannot give you. Use a small, readable stack first so you can see every stage.
  • For CPT, keep the original tokenizer and special tokens. Mix in some general text if the domain data is narrow, or the model forgets ordinary language. Use a learning rate well below a from-scratch run, and a warmup.
  • Plan tokens against parameters. Training compute for a dense Transformer is often estimated as about 6ND floating-point operations (two per parameter per token in the forward pass, four in the backward pass), where N is parameters and D is tokens. How many tokens per parameter is a research choice; do not treat one blog ratio as a law. Watch validation loss, not only training loss.
  • Checkpoint often, evaluate on a held-out shard, and keep the data pipeline deterministic enough to replay.

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.

nanochat: install and speedrun
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
nanochat: a short depth-12 experiment
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.

Axolotl continued pretraining (completion)
# 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

05Supervised fine-tuning

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.

  • Put data in the model’s native chat template. In Transformers that means 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.
  • Mask the loss on system and user tokens. Train on assistant tokens only (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.
  • For multi-turn chats, keep the full history in the window and mask every non-assistant turn.
  • Pack short examples into the sequence length when the trainer supports it, so you do not waste padding. Check that packing does not leak tokens across examples.
  • One to three epochs is the usual range on a clean set. Stop when the held-out loss or your task eval stops improving. A perfect training loss is often memorization.
  • Start from an instruct model when your data is conversational. A base model can be SFT’d, but it will need more examples and a carefully applied template.

TRL is the straight Hugging Face path. The official quick start fine-tunes a small Qwen on a conversational set:

TRL SFTTrainer
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:

Axolotl install and first LoRA SFT
pip3 install "axolotl[deepspeed]"
axolotl fetch examples
axolotl train examples/llama-3/lora-1b.yml
Axolotl: your own chat data
# 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.

06LoRA and QLoRA

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.

  • Start with QLoRA if memory is tight, or with 16-bit LoRA if you have the VRAM. Train and serve in the same precision when you can.
  • A working starting point: rank 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.
  • Learning rates in published recipes typically sit around 1e-4 to 3e-4 for LoRA and QLoRA, and about an order of magnitude lower for a full fine-tune. Lower the rate as the model gets larger.
  • Enable gradient checkpointing. Use a packed sequence length you can hold. 2048 is a sane test length even when the base supports more.
  • When you are done, either merge the adapter into the base for a single set of weights, or serve the adapter on top of the base (vLLM, SGLang, and llama.cpp can all do this). Keep the tokenizer and the chat template next to the adapter.
  • Practical memory bands for planning, which move with context length and batch: LoRA on a 7B to 8B often fits in 16 to 24 GB; a 13B to 14B in 24 to 40 GB; 30B to 70B QLoRA often wants 40 to 80 GB. Treat those as planning bands, then measure on your box.

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.

Unsloth Core + QLoRA SFT
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")
LLaMA-Factory LoRA SFT
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
torchtune LoRA, single device
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

Preferences, rewards and distillation

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.

07DPO, RLHF and GRPO

After SFT, you can push the model toward answers people (or a program) prefer. The three names you will see most:

RLHF / PPO
Train a reward model on preference pairs, then optimize the policy with PPO (or a close cousin) against that reward, with a KL penalty so the model does not drift too far from the SFT reference.
DPO
Skip the reward model. Train directly on pairs of chosen and rejected completions for the same prompt, relative to a frozen reference model. This is the usual first preference method because the data and the trainer are simpler.
GRPO
Group Relative Policy Optimization. Sample a group of completions for each prompt, score them with a reward function (often a unit test, a math checker, or a rubric), and update the policy using the group’s relative scores. No separate value model. This is the method used in a lot of recent reasoning and “the model can check its work” runs.
  • Do SFT first, unless you already have a model that can produce the format you want to score. Preference training will not invent a capability that never appears in the samples.
  • DPO data is prompt, chosen, rejected. The two completions must answer the same prompt. Conversational forms are fine if the trainer applies the chat template consistently.
  • GRPO needs a reward you can compute in code. A brittle regex or a noisy learned reward will be gamed. Start with something checkable: unit tests, a verifier, exact match on a held-out set.
  • Keep a reference model (or a LoRA you can disable) so the policy cannot collapse. Watch reward, KL, and a task eval that is not the reward itself.
  • Other trainers in the same family you will see in configs: ORPO, KTO, IPO, and GSPO. Use them when the docs of your stack recommend them for your data shape, not because of the acronym.
TRL DPO
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()
TRL GRPO with a math accuracy reward
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.

08Distillation

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.

  • Teacher and student need a compatible tokenizer, or you have to map ids. Same-family pairs (a 7B and a 0.5B from one lab) are the easy case.
  • On-policy distillation: the student generates, the teacher scores those tokens, the student is trained to match the teacher’s distribution. This is what TRL’s Distillation trainer is built for.
  • A distilled model is a new model. Evaluate it on your task, not only against the teacher’s training loss. If you need a tiny draft model for speculative decoding, train it on the same distribution the large model will see in production.
TRL DistillationTrainer
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

Evals, compute, cloud and serving

A falling loss is not a release. Measure the job, plan the box, then serve the same template you trained.

09Evals

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.

  • Build a private eval that looks like production: a few hundred examples you will not train on, scored the way a user would judge them (exact match, a rubric, a unit test, a human pass). This is the number you trust.
  • Add public suites that match the skill you claim: general knowledge, math, code, instruction following, multilingual, or a domain set. Common benchmark tasks include MMLU-style sets, GSM8K, HumanEval / similar code tests, IFEval, and conversation judgments. Only run what you will read.
  • Keep decoding settings fixed (temperature, top-p, max tokens, the chat template). A change in the template can move a score more than a week of training.
  • Compare against the untouched base, not only against last week’s adapter. If the new model is better on your task and worse on everything else, say so.
  • For a first pass, run a slice (--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).

lm-evaluation-harness
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
LightEval, Accelerate backend
pip install lighteval
lighteval accelerate "model_name=./merged_model" hellaswag

10Compute and cost planning

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.

  • A dense training step is often estimated at about 6ND FLOPs, with N the trainable (or full) parameter count and D the tokens in the run. That gives you a way to compare two recipes. It does not give you a bill.
  • Memory is usually the constraint, not raw FLOPs. Full fine-tuning stores weights, activations, gradients and optimizer states (Adam keeps two moments per parameter). LoRA shrinks the optimizer to the adapters. QLoRA also stores the base in 4-bit. Context length and batch size then dominate activations.
  • Turn on gradient checkpointing (more compute, less activation memory), sequence packing, FlashAttention or the vendor equivalent, and, if the trainer supports it, activation offloading or optimizer 8-bit states.
  • Effective batch size is 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.
  • Multi-GPU: start with DDP when the model fits on one GPU. Move to FSDP or DeepSpeed ZeRO when it does not. CPT and large SFT almost always need one of those.
  • Budget for failed runs, evals, and the export step. Save checkpoints to object storage on a schedule. Spot or interruptible instances are cheaper and will vanish; a run that cannot resume is more expensive than a reserved box.

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.

Dry-run a few steps and read VRAM
# 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.

11Cloud GPU options

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.

  • Compare on-demand, interruptible or spot, and reserved or committed rates on the day you start. Interruptible boxes need checkpointing that resumes.
  • Check the CUDA and driver image, CPU RAM, local disk (datasets and checkpoints are large), and network egress. A cheap GPU with a tiny disk will stall mid-epoch.
  • Prefer a provider that can snapshot the image or attach object storage. Copy the final merge off the box before you terminate it.
  • Some platforms are raw VMs (you install CUDA, PyTorch, the trainer). Others are serverless functions that bill for active GPU time. The second group is handy for short jobs and painful for multi-day pretrains unless you have designed for it.

Common places people rent training GPUs, with their official pages. This is not a ranking, and it is not a price list.

12Serving

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.

  • Merge the LoRA into the base when you want a single set of weights, or load the adapter at serve time if you will swap adapters. Export GGUF when the target is llama.cpp or Ollama; keep a 16-bit or bfloat16 merge when the target is vLLM or SGLang, then let that stack quantize if it should.
  • High-throughput API: vLLM or SGLang. Local or CPU / Apple: llama.cpp, Ollama, or MLX. NVIDIA production stacks also include TensorRT-LLM and Hugging Face TGI. Pick one, measure tokens per second and memory on your hardware.
  • Match quantization to the train when you can. If you trained in 4-bit and will serve in 4-bit, you avoid a precision surprise. Still run the eval on the served artifact, not only on the training dtype.
  • Expose an OpenAI-compatible endpoint if your apps already speak that API. Keep a system prompt and tool schema identical to training.
vLLM, merged model or a LoRA
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"
SGLang, with a LoRA
pip install sglang
python3 -m sglang.launch_server \
  --model-path <base-model> \
  --enable-lora \
  --lora-paths my-lora=./adapter
llama.cpp server and Ollama
# 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
OpenAI-compatible client against a local server
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)

Tools and repos

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.

nanochat

Minimal stack: tokenizer, pretrain, SFT, eval and a CLI. The current successor to nanoGPT.

GitHub

nanoGPT

Short, readable pretrain loop. Its README now points you to nanochat for new work.

GitHub

Unsloth

Fast LoRA / QLoRA / RL on one GPU, with merge and GGUF export. Docs at unsloth.ai.

GitHub

Axolotl

YAML trainer for SFT, CPT, LoRA, QLoRA, DPO and GRPO. Docs at docs.axolotl.ai.

GitHub

TRL

Hugging Face trainers: SFT, DPO, GRPO, distillation, and the rest of the post-training list.

GitHub

torchtune

PyTorch-native recipes and YAML configs for LoRA and full fine-tunes.

GitHub

LLaMA-Factory

CLI and web UI over a large set of official example YAMLs.

GitHub

LitGPT

Lightning’s from-scratch and fine-tune CLI, including a JSON data path.

GitHub

PEFT

The adapter library (LoRA and friends) that most of the trainers above sit on.

GitHub

bitsandbytes

4-bit and 8-bit loaders used by QLoRA.

GitHub

Transformers

Model definitions, tokenizers, chat templates and the common load path.

GitHub

Datasets

The usual way to load Hub and local shards into a trainer.

GitHub

datatrove

FineWeb-style pipeline: filters, PII, exact dedup and MinHash near-dedup.

GitHub

NeMo Curator

NVIDIA’s data-curation stack for large pretraining corpora.

GitHub

tokenizers

Fast BPE / Unigram training and tokenization.

GitHub

SentencePiece

The other standard way to train a vocab from raw text.

GitHub

tiktoken

OpenAI-style BPE: use it to speak an existing vocab, not to train a new one.

GitHub

Megatron-LM

NVIDIA’s large-scale pretrain stack (tensor, pipeline and data parallel).

GitHub

torchtitan

PyTorch’s pretraining platform for large dense and MoE runs.

GitHub

DeepSpeed

ZeRO sharding and memory tricks used by Axolotl and many others.

GitHub

Accelerate

Launch and device placement for Hugging Face trainers.

GitHub

FlashAttention

Fused attention kernels. Most trainers expose this as a flag.

GitHub

OpenRLHF

RLHF / PPO / GRPO stack, often paired with a vLLM rollout.

GitHub

veRL

Volcengine’s RL training library, used in a lot of recent GRPO work.

GitHub

alignment-handbook

End-to-end recipes around TRL for SFT and preference training.

GitHub

lm-evaluation-harness

The standard CLI for public LLM benchmarks.

GitHub

LightEval

Hugging Face’s evaluation library.

GitHub

vLLM

High-throughput serving, including LoRA modules.

GitHub

SGLang

High-throughput serving with its own LoRA path.

GitHub

llama.cpp

Local GGUF inference and a server. Works on CPU and a lot of GPUs.

GitHub

Ollama

Simple local runner on top of llama.cpp-style weights.

GitHub

TGI

Hugging Face’s production generation server.

GitHub

TensorRT-LLM

NVIDIA’s optimized inference runtime.

GitHub

MLX LM

Local training and inference on Apple silicon.

GitHub

Questions about the path

Short answers for the decisions that usually stall a first run.

Should I pretrain from scratch?

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.

LoRA or a full fine-tune?

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.

How much SFT data do I need?

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.

The loss fell and the model got worse. What broke?

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.

Which GPU should I rent?

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.

Can I mix chat templates?

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 do I add DPO or GRPO?

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.

How do I keep a run reproducible?

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.