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
2Attach LoRA adapters
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
5Save and push
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_lengthtomax_lengthand 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:
labelsequalinput_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 withadd_special_tokens=False(the template already added them), and callgenerate()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
2Instruction tuning
3Supervised fine-tuning on a narrow dataset
4Preference tuning
5Classic supervised tasks
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
2Scores
3Context
4Why √d_k
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
2BF16 ("brain float")
3FP16
4INT8 and 4-bit types
5A float's value
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_dtypewhen 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'sforwardthe 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
2The weights cooperate.
qkv_proj layers, millions of weights sit in a very narrow range, with a few outliers.3NF4 vs. FP4
4Double (nested) quantization
58-bit LLM.int8()
Going deeper5 points
- The compute dtype is separate from the storage dtype. 4-bit weights are dequantized to
bnb_4bit_compute_dtypefor each matrix multiply. For quality, FP32 beats BF16, which beats FP16. - What gets replaced. Only the Linear layers inside the decoder blocks become
Linear8bitLtorLinear4bit. For 8-bit, tied (shared) weights, the last layer and anything namedlm_headare skipped. Unless you passtorch_dtype, the layers that aren't quantized drop to FP16. - The
SCBcrash. If you write your ownllm_int8_skip_moduleslist, include a tied layer such aslm_head. Otherwise loading fails withAttributeError: 'Parameter' object has no attribute 'SCB'. - Quantization happens when the layer is moved to the GPU. If you load FP16 weights into a
Linear8bitLtorLinearNF4, 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
2The forward pass
3The scaling factor
4Starting point
peft/tuners/lora/layer.py in 0.17.0), so training starts exactly from the base model.5My adapter, counted
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 getValueError: Please specify target_modulesand list the big Linear layers yourself.- Typical settings: ranks of 8, 16 or 32. Add
fan_in_fan_out=Truefor models withConv1Dlayers. Keepbias="none", because training biases changes the base model's behaviour. - Training more than adapters:
modules_to_savemakes whole layers trainable, such as layer norms, or embeddings and the head when you add tokens. LoRA can also targetembed_tokensdirectly. - Managing adapters: one model can hold several adapters. You can load, add, delete, switch between them with
set_adapter(), turn them off temporarily withdisable_adapter(), merge withmerge_adapter(), or remove them all withunload().
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
<|user|> … <|end|>, then <|assistant|> … <|end|>, then <|endoftext|>.2The generation prompt
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
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
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()withpad_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
2DataCollatorForLanguageModeling
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
4Packing
packing_strategy="wrapped" reproduces the book's original behaviour.Going deeper3 points
- TRL has changed here.
DataCollatorForCompletionOnlyLMwas removed in trl 0.20. Its job is now done bycompletion_only_lossorassistant_only_lossinSFTConfig. The book keeps a copy incompatibility_functions.pyto show the masking.ConstantLengthDatasetwas replaced bypack_dataset(). - Packing in the collator.
DataCollatorWithFlattening, orpadding_free=Trueon the completion-only collator, packs a batch and restartsposition_idsat 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 setpacking=False, because trainer packing and a packing collator aren't used together by default. - Always check one batch. Decode
labels[labels >= 0]fromtrainer.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
2The batch
3Activations
4Gradients and optimizer state
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_lengthyour data needs. - Let the trainer apply LoRA. If you pass the base model plus
peft_config,SFTTrainercallsprepare_model_for_kbit_training()andget_peft_model()itself. - Sensible defaults. Use checkpointing with
use_reentrant=False, 2 accumulation steps, a minimum effective batch of 8, andauto_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
fp16orbf16, and only what the GPU supports. My saved arguments show both off. Since trl 0.20,bf16defaults 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 theoutput_dirname, 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
2Flash Attention 2 and PyTorch's SDPA
3SDPA
attn_implementation="sdpa".4Flash Attention 2
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
_AdamWwithbf16_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
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
: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.
AutoPeftModelForCausalLMreads the adapter config and loads the base model itself. Older versions neededPeftConfigplusPeftModelto get the embedding size right. - llama.cpp's REST API. POST a
promptandn_predictto/completion, and read thecontentfield 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
qkv_proj, o_proj, gate_up_proj, down_proj).2AttributeError: 'Parameter' object has no attribute 'SCB'
llm_int8_skip_modules list left out the tied lm_head. Add it.3The model never stops generating
4The chat template isn't applied
messages.5Adapters don't train
peft_config.6Flash Attention 2 errors on load or in training
7Exceptions from gradient checkpointing in newer PyTorch
gradient_checkpointing_kwargs={"use_reentrant": False}.8max_seq_length rejected
max_length.