Book notes

Fine-tuning LLMs on one GPU: my notes on Daniel Voigt Godoy's hands-on guide

I read A Hands-On Guide to Fine-Tuning LLMs with PyTorch and Hugging Face by Daniel Voigt Godoy page by page, from Chapter 0 to Appendix B, and worked through its notebooks as I went. The proof that I did the work is on the Hub: mkiadi2002/phi3-mini-yoda-adapter, a LoRA adapter that makes Microsoft's Phi-3 Mini 4K Instruct answer like Yoda.

These are my own notes, one section per idea: a scenario, a diagram I drew, and what to take away. The diagrams are mine. Where a figure from the book explains something better, I link it from the book's repository (MIT licence, © Daniel Voigt Godoy). The numbers about my adapter come from the files I published: its LoRA config, its saved training arguments and its file sizes. Everything else comes from the book's notebooks, and from the Hugging Face docs where I say so.

What I built: the whole recipe in five steps

Scenario. I wanted a 3.8-billion-parameter model to speak like Yoda, without a data-centre GPU. In full precision its weights alone are about 15 GB (3.8B × 4 bytes), before gradients, optimizer state or a single batch. Chapter 0 is the book's "shoot first, ask questions later" recipe, and I followed it end to end.

What the picture shows. Each step, with the settings my published adapter actually uses.

1Load a quantized base model
Phi-3 Mini 4K Instruct loaded in 4-bit NF4 with double quantization through BitsAndBytes. It takes a bit more than 2 GB of GPU memory.
2Attach LoRA adapters
rank 8, alpha 16, dropout 0.05, on the four big Linear layers of every block (qkv_proj, o_proj, gate_up_proj, down_proj). That makes 12.6M trainable parameters, 0.33% of the model.
3Format the dataset
dvgodoy/yoda_sentences has 720 English sentences with Yoda-speak translations. I turned each pair into a user/assistant conversation and let Phi-3's chat template wrap it in special tokens.
4Train with TRL's SFTTrainer
64-token packed sequences, learning rate 3e-4, 10 epochs, batch 16 with automatic halving on out-of-memory, gradient checkpointing and a paged 8-bit AdamW optimizer.
5Save and push
the result is a 50.4 MB adapter_model.safetensors plus tokenizer files. Anyone can load Phi-3 and put it on top.

The code. The configuration I trained with, as saved in my adapter's training arguments.

bnb_config = BitsAndBytesConfig(    load_in_4bit=True,    bnb_4bit_quant_type="nf4",            # 4-bit NormalFloat    bnb_4bit_use_double_quant=True,    bnb_4bit_compute_dtype=torch.float32,)model = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct",                                             device_map="cuda:0", quantization_config=bnb_config)model = prepare_model_for_kbit_training(model)model = get_peft_model(model, LoraConfig(    r=8, lora_alpha=16, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",    target_modules=["o_proj", "qkv_proj", "gate_up_proj", "down_proj"],   # Phi-3 needs these listed))sft_config = SFTConfig(    gradient_checkpointing=True, gradient_checkpointing_kwargs={"use_reentrant": False},    gradient_accumulation_steps=1, per_device_train_batch_size=16, auto_find_batch_size=True,    max_length=64, packing=True, packing_strategy="wrapped",               # short, packed sequences    num_train_epochs=10, learning_rate=3e-4, optim="paged_adamw_8bit",    logging_steps=10, output_dir="./phi3-mini-yoda-adapter", report_to="none",    bf16=torch.cuda.is_bf16_supported(including_emulation=False),)trainer = SFTTrainer(model=model, processing_class=tokenizer, args=sft_config, train_dataset=dataset)trainer.train()trainer.push_to_hub()
Going deeper4 points
  • The book pins library versions, and it matters. The October 2025 update pins transformers 4.56.1, peft 0.17.0, trl 0.23.1 and bitsandbytes 0.47.0. My model card shows TRL 0.23.1 and Transformers 4.56.1. TRL 0.20 renamed max_seq_length to max_length and changed how packing works. Until 0.23.1, training a model that already had adapters attached froze the adapters too.
  • The labels are the inputs. After building the trainer, pull one batch and check it: labels equal input_ids, so this is self-supervised training. The model shifts the labels by one position on its own.
  • Where to train. The book's Appendix A walks through renting a GPU pod on RunPod, and the FAQ covers Colab's free T4. One habit from Appendix A is worth keeping: stopping a pod is not the same as terminating it. A stopped pod stays on your list until you delete it.
  • How to query it. Build a message list with just the user turn, apply the chat template with add_generation_prompt=True, tokenize with add_special_tokens=False (the template already added them), and call generate() with the EOS token id. The book says the run fits a 6 GB GTX 1060 in about 35 minutes.

Why fine-tune at all, and when RAG is the better answer

Scenario. Before I trained anything, I had to answer the question everyone asks: why not just use RAG? The book's answer, from its FAQ and Chapter 1, is that they solve different problems.

What the picture shows. The kinds of fine-tuning, and where RAG fits instead.

1A pretrained base model
only continues text. You had to ask "The capital of Argentina is" instead of asking a question.
2Instruction tuning
was the original fine-tuning. It turns the next-token predictor into a chat model that answers questions and follows instructions.
3Supervised fine-tuning on a narrow dataset
is what the book teaches and what I did. It teaches a style, a format or a stable body of domain knowledge, for example an internal-docs chatbot or legal summaries.
4Preference tuning
(RLHF, DPO) is a different kind. It steers the model away from harmful or unwanted answers.
5Classic supervised tasks
such as classification are possible too. The book advises checking first whether a much smaller model already does the job.
Going deeper3 points
  • RAG is the generalist, fine-tuning is the specialist. RAG relies on a general model reading documents fetched at query time, so you can swap the documents at any time. A fine-tuned model is very good at one narrow task, which is why it can be much smaller.
  • Choose by how the knowledge behaves. Knowledge that changes often or is very broad belongs in RAG. Knowledge that is narrow and stable, or a style the model must always use, is a fine-tuning job. A Yoda voice is the second kind.
  • The difficulty is configuration, not maths. The book's point is that a naive training loop needs tens of gigabytes of GPU memory. A well-configured one gets a similar model in about a tenth of that. Chapters 2–5 are about that configuration.

Transformers and attention, the parts that matter for fine-tuning

Scenario. Every later chapter refers to "the big Linear layers" and "memory that grows with sequence length". Chapter 1 explains both with one formula.

What the picture shows. How one attention head turns token embeddings into context vectors.

1Three projections
each token's embedding goes through three Linear layers, giving a query, a key and a value.
2Scores
each query is compared with every key using a dot product, which measures how closely two vectors point the same way. The result is divided by √d_k and passed through a softmax. That gives an L × L table of attention weights.
3Context
the weights mix the value vectors into one context vector per token. The heads are then concatenated and projected back to the model's width.
4Why √d_k
For random 1024-dimensional vectors, the dot products have a standard deviation of about 32.6, close to √1024 = 32. Dividing by it keeps the softmax from saturating.
Going deeper3 points
  • Multi-head attention splits the width. d_k = d_model / n_heads. With 1024 and 16 heads, each head works in 64 dimensions.
  • Decoder-only models are stacks of the same block. Phi-3 has 32 of them, each with attention and an MLP. Their Linear layers hold almost all the parameters, which is why quantization (Chapter 2) and LoRA (Chapter 3) both target them.
  • Contextual embeddings. The same word gets a different vector depending on its neighbours. That is what attention adds on top of a fixed embedding table.

Data types: FP32, BF16, FP16 and what the bits mean

Scenario. The Chapter 2 notebook loads facebook/opt-350m twice, once without a dtype and once with one. The dtype stored on the Hub and the dtype in memory turn out to differ. It then casts very small and very large values to FP16, and they come back as zeros and infinities. Chapter 2 and Appendix B explain why.

What the picture shows. How each type spends its bits, and what that costs.

1FP32
1 sign bit, 8 exponent bits and 23 mantissa bits. This is full precision.
2BF16 ("brain float")
keeps FP32's 8 exponent bits, so it has the same range (up to about 3.4e38), but only 7 mantissa bits of precision.
3FP16
spends more bits on precision (10) and fewer on range (5). Its maximum is 65,504, and values below about 1e-8 underflow to zero.
4INT8 and 4-bit types
aren't floats at all. They are indexes into a small set of levels, which is what quantization relies on.
5A float's value
is (-1)^sign × 2^(exponent − bias) × (1 + fraction). For BF16 the bias is 127.
Going deeper4 points
  • Prefer BF16 to FP16 whenever the GPU supports it (torch.cuda.is_bf16_supported(including_emulation=False)). It is far less likely to overflow or underflow.
  • Always pass torch_dtype when loading. The dtype stored in the checkpoint and the dtype you get in memory can differ.
  • Mixed precision keeps FP32 master weights and runs the heavy maths in 16-bit inside torch.autocast. Accelerate wraps a model's forward the same way and converts the outputs back to FP32.
  • Integers in Appendix B: unsigned 8-bit values add up powers of two. Signed values use two's complement, where the left-most bit counts as −2⁷.

Quantization and BitsAndBytes

Scenario. My 3.8B model had to fit in a few gigabytes. Going from FP32 to 4-bit cuts the weights by roughly a factor of eight. The price is that the quantized layers can no longer be trained.

What the picture shows. How quantization works, and what BitsAndBytes does with it.

1Binning
split the range of the weights into 2^bits bins and store only each weight's bin index, plus the bin width and the first bin. To get a weight back, compute index × width + first bin. The book measures the error for 2, 4, 8 and 16 bits, and it shrinks as bits are added.
2The weights cooperate.
In Phi-3's qkv_proj layers, millions of weights sit in a very narrow range, with a few outliers.
3NF4 vs. FP4
both have 16 levels. Per the bitsandbytes docs, NF4 gives each level an equal share of a normal distribution, so its levels crowd near zero, where most weights are. The Transformers docs recommend NF4 for training.
4Double (nested) quantization
quantizes a second time and saves about 0.4 bits per parameter (Transformers bitsandbytes docs).
58-bit LLM.int8()
multiplies outlier features in 16-bit and everything else in 8-bit, then combines the two results.
Going deeper5 points
  • The compute dtype is separate from the storage dtype. 4-bit weights are dequantized to bnb_4bit_compute_dtype for each matrix multiply. For quality, FP32 beats BF16, which beats FP16.
  • What gets replaced. Only the Linear layers inside the decoder blocks become Linear8bitLt or Linear4bit. For 8-bit, tied (shared) weights, the last layer and anything named lm_head are skipped. Unless you pass torch_dtype, the layers that aren't quantized drop to FP16.
  • The SCB crash. If you write your own llm_int8_skip_modules list, include a tied layer such as lm_head. Otherwise loading fails with AttributeError: 'Parameter' object has no attribute 'SCB'.
  • Quantization happens when the layer is moved to the GPU. If you load FP16 weights into a Linear8bitLt or LinearNF4, they only get quantized on .to("cuda").
  • A quantized model can serve but not learn. Its quantized layers are frozen, which is exactly the problem LoRA solves.

LoRA and PEFT: train a thin detour, not the model

Scenario. After quantization, none of my 3.8B weights could be updated. LoRA added about 12.6M new ones that could be, and they ended up as the 50 MB file I published.

What the picture shows. The low-rank trick, and my adapter's real parameter count.

1The idea
keep W frozen and learn two thin matrices, A (r × in) and B (out × r). Their product B·A has the shape of W but rank r.
2The forward pass
the output is X·Wᵀ + (α / r)·(X·Aᵀ)·Bᵀ, so the layer runs two passes and adds them. With r = 8 on a 1024 × 1024 layer, that is 16,384 trainable weights instead of 1,048,576.
3The scaling factor
alpha is usually 2 × r, and α / r scales how much the detour contributes.
4Starting point
PEFT initialises B to zeros (I checked peft/tuners/lora/layer.py in 0.17.0), so training starts exactly from the base model.
5My adapter, counted
393,216 adapter weights per block × 32 blocks = 12,582,912. At 4 bytes each, that is 50.3 MB, which matches the 50.4 MB file on the Hub.
Going deeper5 points
  • prepare_model_for_kbit_training() comes first. It freezes every layer, casts the layers that aren't quantized to FP32 for numerical stability, and enables gradient checkpointing. That is why my model's footprint grew by about 30% before training.
  • target_modules: for well-known architectures PEFT picks targets itself (TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING). For newer ones such as Phi-3 at the time, you get ValueError: Please specify target_modules and list the big Linear layers yourself.
  • Typical settings: ranks of 8, 16 or 32. Add fan_in_fan_out=True for models with Conv1D layers. Keep bias="none", because training biases changes the base model's behaviour.
  • Training more than adapters: modules_to_save makes whole layers trainable, such as layer norms, or embeddings and the head when you add tokens. LoRA can also target embed_tokens directly.
  • Managing adapters: one model can hold several adapters. You can load, add, delete, switch between them with set_adapter(), turn them off temporarily with disable_adapter(), merge with merge_adapter(), or remove them all with unload().

Chat templates and the tokenizer

Scenario. In Phi-3, the PAD token is the same as the EOS token. Since a trl update, the collator masks padding in the labels, so it masks every EOS too. A model trained that way never learns where an answer ends and keeps generating. The book's one-line fix, which my training run used, is to make PAD the UNK token.

What the picture shows. One dataset row before and after the template, and the rules around it.

1The chat template
is a Jinja template stored in the tokenizer. It wraps every turn in special tokens. For Phi-3 that means <|user|> … <|end|>, then <|assistant|> … <|end|>, then <|endoftext|>.
2The generation prompt
at query time, add_generation_prompt=True ends the text with <|assistant|>. That token is the cue that it is the model's turn.
3Three ways to feed the trainer
a conversational dataset with a templated tokenizer, your own formatting_func, or a pre-formatted text column. Recent trl no longer applies the template to the prompt/completion format, so the book converts everything to conversational messages.
4Tokenizer rules
use EOS only to mark the end. Never leave PAD undefined, because libraries silently fall back to EOS. Pad generative models on the left, unless you pack.
Going deeper5 points
  • Spare rows in the embedding matrix. A tokenizer's vocabulary is usually shorter than the model's embedding layer, because embedding sizes are rounded to a multiple of a power of two. New tokens can use those spare rows without resizing.
  • Adding tokens. Strictly, the embeddings for new tokens should be trained. In practice the model may still learn to use frozen, random ones. If you must resize, call resize_token_embeddings() with pad_to_multiple_of.
  • Bring your own template. If a model has no template (OPT-350M), ChatML is a sensible default. TRL's setup_chat_format() sets PAD to EOS (fix that afterwards) and resizes the embeddings by default.
  • Make the response marker a single special token. A tokenizer that depends on context (Llama 2) splits "### Assistant:" differently in the middle of a sentence and on its own. The collator then can't find it, and masks everything.
  • Formatting functions must handle batches. The book tests them with dataset.map(..., batched=True). A function that only handles one row fails there.

Labels, collators and packing

Scenario. The Yoda sentences are short, so padding each one to 64 tokens would waste most of every row. Packing removes the padding. The next question is which tokens the loss is actually computed on.

What the picture shows. The same tokens seen by three collators, and padding compared with packing.

1DataCollatorWithPadding
only pads a batch. It adds no labels.
2DataCollatorForLanguageModeling
is SFTTrainer's default, and it needs mlm=False for causal models. It copies input_ids into labels without shifting them, because the model's forward() shifts them by one when it computes the cross-entropy.
3Completion-only training
replaces the prompt tokens' labels with -100, so only the answer counts in the loss. For a single turn, the response template is enough. For multi-turn chats, you also need the instruction template.
4Packing
joins all examples together and cuts the result into equal 64-token packs, so there is no padding at all. packing_strategy="wrapped" reproduces the book's original behaviour.
Going deeper3 points
  • TRL has changed here. DataCollatorForCompletionOnlyLM was removed in trl 0.20. Its job is now done by completion_only_loss or assistant_only_loss in SFTConfig. The book keeps a copy in compatibility_functions.py to show the masking. ConstantLengthDataset was replaced by pack_dataset().
  • Packing in the collator. DataCollatorWithFlattening, or padding_free=True on the completion-only collator, packs a batch and restarts position_ids at every example. With Flash Attention 2, models such as Llama, Phi, Mistral and Gemma use those boundaries. Without them, an example can attend to the one packed before it (IBM / Hugging Face write-up). In this case set packing=False, because trainer packing and a packing collator aren't used together by default.
  • Always check one batch. Decode labels[labels >= 0] from trainer.get_train_dataloader() before training. It's the fastest way to catch a template the collator can't find, or an EOS token that got masked.

Training memory and the SFTTrainer

Scenario. Chapter 5 starts from a practical problem: it is hard to predict when training will run out of memory. The model may fit, yet training still fails. The way out is to know which of the five memory terms is the large one.

What the picture shows. Total memory split into its parts, with the technique that targets each one.

1Model weights
shrink with quantization.
2The batch
shrinks with a smaller micro-batch. Gradient accumulation keeps the effective batch the same: effective batch = micro-batch × accumulation steps.
3Activations
shrink with gradient checkpointing, which recomputes them in the backward pass and trades compute for memory, and with Flash Attention or SDPA.
4Gradients and optimizer state
exist only for trainable weights, so LoRA reduces them most. Adam keeps two states per weight, and an 8-bit paged optimizer shrinks those further. With LoRA on, the book notes that the 8-bit optimizer helps only a little.
Going deeper6 points
  • The activation formula. Following Korthikanti et al. (arXiv 2205.05198), activations per block are 34·h·b·s + 5·n_heads·b·s² with eager attention. With Flash Attention the second term is zero. So the sequence length, through its square, is usually what causes out-of-memory, more often than model size. Choose the shortest max_length your data needs.
  • Let the trainer apply LoRA. If you pass the base model plus peft_config, SFTTrainer calls prepare_model_for_kbit_training() and get_peft_model() itself.
  • Sensible defaults. Use checkpointing with use_reentrant=False, 2 accumulation steps, a minimum effective batch of 8, and auto_find_batch_size=True (which halves the batch until it fits). Log, evaluate and save every N steps to TensorBoard.
  • Mixed precision. Set exactly one of fp16 or bf16, and only what the GPU supports. My saved arguments show both off. Since trl 0.20, bf16 defaults to on, so the book sets it explicitly.
  • The training loop under the hood. Each step does a forward pass, extracts the loss, runs backward through Accelerate (which also handles accumulation), steps the optimizer and zeroes the gradients.
  • Saving. save_model() writes the adapter. AutoPeftModelForCausalLM.from_pretrained(...).merge_and_unload() gives a full merged model. push_to_hub() publishes it under the output_dir name, which is where my repository's name comes from.

Eager attention, Flash Attention 2 and SDPA

Scenario. The book's ablation tables compare peak memory at 500 and 2,000 tokens. With eager attention, the longer sequence is where memory runs out. Changing only the attention implementation changes that.

What the picture shows. Why eager attention is expensive, and how to choose between the alternatives.

1Eager attention
builds the full L × L score matrix for every head and keeps it in GPU memory between steps. Memory grows with the square of the sequence length.
2Flash Attention 2 and PyTorch's SDPA
give the same result without keeping that matrix, so the s² term in the memory formula disappears.
3SDPA
is the easy default. Most Hugging Face models support it through attn_implementation="sdpa".
4Flash Attention 2
is a little faster, but it has requirements: the flash-attn package, NVCC, an Ampere, Ada or Hopper GPU, and 16-bit weights. If you load in FP32, training must use fp16 or bf16 mixed precision, or it fails at runtime.
Going deeper3 points
  • Full BF16 training can stall, because small updates round away to nothing. The book shows that an optimizer with stochastic rounding (torchao's _AdamW with bf16_stochastic_round=True) keeps the weights moving.
  • Benchmark one layer, not the model. The book times a single attention module on the GPU with CUDA events and reads its peak memory. It restarts the kernel between implementations to get a clean measurement.
  • Ablation tables. Peak memory for OPT-350M at 500 and 2,000 tokens, and for quantized OPT-350M and Falcon 7B, show which combination of techniques actually fits. They are worth reading before buying a GPU.

Deploying it locally: GGUF, Ollama and llama.cpp

Scenario. A model on the Hub is only half done. Chapter 6 runs it on an ordinary machine, without a GPU, behind a web UI and a REST API.

What the picture shows. Two paths from adapter to server.

1Merge, then convert
merge_and_unload() folds the adapter into the weights, so each layer does one matmul instead of two. The merged model is converted to a 16-bit GGUF file and then quantized to a type such as Q4_K_M. In the book's Unsloth run, the f16 model of 7,288 MB became 2,211 MB.
2Keep the adapter separate
convert_lora_to_gguf.py turns the adapter alone into a GGUF file (f32, f16, bf16, q8_0 or auto). Ollama then applies it on top of a stock phi3:mini.
3Four ways to convert a full model
llama.cpp's convert_hf_to_gguf.py, the "GGUF My Repo" Space on Hugging Face, Unsloth, or llama.cpp's Docker images with --convert and --quantize.
4Serving
Ollama reads a Modelfile. llama.cpp's server, from the :full or the smaller :server image, serves a web UI and a REST API.

The code. The Modelfile shape from the book, pointed at my adapter.

FROM phi3:miniADAPTER ./phi3-mini-yoda-adapter.ggufTEMPLATE "{{ if .System }}<|system|>{{ .System }}<|end|>{{ end }}{{ if .Prompt }}<|user|>{{ .Prompt }}<|end|>{{ end }}<|assistant|>{{ .Response }}<|end|>"PARAMETER stop <|end|>PARAMETER stop <|user|>PARAMETER stop <|assistant|>
Going deeper4 points
  • The Modelfile template must match training. Copy it from ollama show --modelfile phi3:mini, and keep <|end|> as a stop token, or the model keeps talking. Instructions include FROM, ADAPTER, TEMPLATE, PARAMETER, SYSTEM, LICENSE and MESSAGE.
  • Pin Ollama for adapters. The book's August 2025 update found that newer Ollama versions crashed on a Modelfile with an adapter, and that version 0.9.6 worked.
  • Load adapters the modern way. AutoPeftModelForCausalLM reads the adapter config and loads the base model itself. Older versions needed PeftConfig plus PeftModel to get the embedding size right.
  • llama.cpp's REST API. POST a prompt and n_predict to /completion, and read the content field of the response. The web UI exposes the sampling settings, such as temperature.

Common errors and their fixes

Scenario. The book has a whole troubleshooting chapter, and its notebooks warn about several breaking changes in the libraries. These are the errors they cover, with the fix for each.

Going deeper, by topic.

1ValueError: Please specify target_modules in peft_config
the installed PEFT doesn't know the architecture yet. List the quantized Linear layers yourself (for Phi-3: qkv_proj, o_proj, gate_up_proj, down_proj).
2AttributeError: 'Parameter' object has no attribute 'SCB'
a custom llm_int8_skip_modules list left out the tied lm_head. Add it.
3The model never stops generating
EOS is used as PAD, so it got masked in the labels. Set PAD to UNK, or to a new special token, and keep EOS unique. Right padding without packing does the same thing.
4The chat template isn't applied
recent trl ignores it for prompt/completion datasets. Convert them to conversational messages.
5Adapters don't train
trl before 0.23.1 froze adapters you had already attached. Upgrade, or pass the base model plus peft_config.
6Flash Attention 2 errors on load or in training
check that the weights are 16-bit, the GPU is Ampere or newer, and that you're using mixed precision if you loaded in FP32.
7Exceptions from gradient checkpointing in newer PyTorch
pass gradient_checkpointing_kwargs={"use_reentrant": False}.
8max_seq_length rejected
trl 0.20 renamed it to max_length.