Skip to content
ImagineWorld

Hands-On Fine-Tuning with Python and Unsloth

node_idnode-book_llm-systems-engineering_module-29-hands-on-fine-tuning-with-python-and-unsloth
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num29
chapter_titleHands-On Fine-Tuning with Python and Unsloth
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Module 29 — Hands-On Fine-Tuning with Python and Unsloth

Section titled “Module 29 — Hands-On Fine-Tuning with Python and Unsloth”

The preceding modules established the conceptual ground for parameter-efficient fine-tuning and the mechanics that govern a supervised training loop. This module translates that material into a concrete workflow that you can execute on a single consumer GPU. The library of choice is Unsloth, which pairs hand-tuned CUDA kernels with the Hugging Face ecosystem to reduce the memory footprint of LoRA-based training while preserving numerical fidelity (Han & Han, 2024). Here, you follow a complete run from dependency installation through adapter persistence, pausing at each stage to interpret what the code is actually doing to the model. The examples target a 8B-parameter base model loaded in 4-bit precision, a configuration that fits comfortably within 16GB of VRAM and reflects the most common hardware profile for individual developers. The aim is a working artifact: a saved LoRA adapter whose behavior reflects the instructional objective defined by the dataset.

A reliable fine-tuning run begins with a predictable environment. Unsloth depends on a specific combination of PyTorch, CUDA, and the bitsandbytes quantization library, and mismatched versions are the most common source of failure during the first forward pass. You should verify that the installed CUDA toolkit aligns with the PyTorch build before installing Unsloth itself, because the library compiles Triton kernels against the active CUDA runtime at import time. A typical install into a fresh Python 3.11 environment looks like the following:

Terminal window
pip install torch==2.4.0 --index-url https://download.pytorch.org/whl/cu121
pip install "unsloth[cu121-torch240] @ git+https://github.com/unslothai/unsloth.git"
pip install trl peft accelerate bitsandbytes datasets

Once the environment is prepared, you should confirm GPU availability before loading any model weights. A short diagnostic prevents the more painful scenario in which a multi-gigabyte checkpoint begins downloading only to fail when a kernel cannot be dispatched. The snippet below reports visible devices and the available memory headroom.

import torch
assert torch.cuda.is_available(), "CUDA device not detected"
device = torch.cuda.current_device()
props = torch.cuda.get_device_properties(device)
print(f"GPU: {props.name}")
print(f"Total VRAM: {props.total_memory / 1e9:.2f} GB")
print(f"Free VRAM: {torch.cuda.mem_get_info()[0] / 1e9:.2f} GB")

With the hardware confirmed, the base model can be loaded through Unsloth’s FastLanguageModel interface, which wraps the standard Transformers loading path with kernel substitutions that accelerate both attention and the MLP projections. Loading a 4-bit quantized model requires only a handful of arguments. The max_seq_length parameter governs the maximum token count the rotary positional embeddings will accommodate, and setting it explicitly prevents unexpected truncation later in the pipeline.

from unsloth import FastLanguageModel
max_seq_length = 2048
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B",
max_seq_length = max_seq_length,
dtype = None,
load_in_4bit = True,
)

The dtype = None argument allows Unsloth to auto-detect the most suitable compute precision for the detected GPU, typically bfloat16 on Ampere hardware and newer. At this point the model is ready for adaptation, although no parameters have yet been made trainable.

Attaching LoRA Adapters and Configuring Rank

Section titled “Attaching LoRA Adapters and Configuring Rank”

Attaching LoRA (Module 28) in Unsloth is handled through the get_peft_model call, which patches the targeted modules in place.

from unsloth import FastLanguageModel
max_seq_length = 2048
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B",
max_seq_length = max_seq_length,
dtype = None,
load_in_4bit = True,
)

For a first run, a uniform rank remains the sensible default because it isolates the effect of the rank choice itself from any secondary allocation heuristic.

The lora_alpha parameter scales the adapter’s contribution during the forward pass. A common convention sets α\alpha equal to rr, which produces a scaling factor of 1 and leaves the effective learning rate of the adapter aligned with the optimizer’s base learning rate. The target_modules list determines which linear projections receive adapters. Covering both the attention projections and the feedforward projections has been shown to outperform attention-only adaptation on instruction-following benchmarks, because the feedforward pathway carries a large share of the task-specific representation capacity (Biderman et al., 2024a). The use_gradient_checkpointing flag activates Unsloth’s custom recomputation strategy, which saves activations selectively and reduces peak memory use during the backward pass by roughly 30 percent relative to the default Transformers implementation.

After the adapter is attached, you should verify that the trainable parameter count matches expectations. A mismatch here typically indicates that the target module names do not correspond to the architecture of the loaded base model, which varies across model families.

trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"Trainable: {trainable:,} ({100 * trainable / total:.3f}% of total)")

For an 8B-parameter base model with rank 16 adapters attached to the seven projections listed above, the trainable parameter count lands near 42 million, or roughly half a percent of the total. This ratio is consistent with the efficiency profile reported in most applications of Unsloth.

Formatting the Dataset and Configuring the Trainer

Section titled “Formatting the Dataset and Configuring the Trainer”

The Hugging Face datasets library provides a consistent interface for loading both public instruction corpora and local files. The example below uses the Alpaca-cleaned dataset, a widely studied instruction-following corpus, though the same pattern applies to a JSONL file on disk.

from datasets import load_dataset
dataset = load_dataset("yahma/alpaca-cleaned", split = "train")

Each example must then be rendered into a single text string that the tokenizer can process. The prompt template defines the boundary between the instruction portion and the response portion, and it must be applied consistently across training and inference so that the model sees the same structural cues in both settings. A common template follows the Alpaca convention, which separates the instruction, the optional input, and the response with labeled headings.

alpaca_template = """Below is an instruction that describes a
task, paired with an input that provides further context.
Write a response that appropriately completes the request.
### Instruction:
{instruction}
### Input:
{input}
### Response:
{response}"""
EOS_TOKEN = tokenizer.eos_token
def format_example(example):
text = alpaca_template.format(
instruction = example["instruction"],
input = example.get("input", ""),
response = example["output"],
) + EOS_TOKEN
return {"text": text}
dataset = dataset.map(format_example)

Appending the end-of-sequence token to every formatted example is essential, because without it the model has no signal that a response has concluded, and generated completions tend to continue indefinitely during inference. The map operation produces a text column that the trainer can consume directly.

Configuration of the trainer itself is handled through the SFTTrainer class from the trl library, which extends the standard Trainer with features specific to supervised fine-tuning. The TrainingArguments object governs optimization behavior, and a small set of arguments carries most of the weight.

from trl import SFTTrainer, SFTConfig
training_args = SFTConfig(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 10,
max_steps = 200,
learning_rate = 2e-4,
logging_steps = 10,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "cosine",
seed = 3407,
output_dir = "outputs",
dataset_text_field = "text",
max_seq_length = max_seq_length,
)
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
args = training_args,
)

The effective batch size is the product of per_device_train_batch_size and gradient_accumulation_steps, which here yields an effective batch of 8. Gradient accumulation allows you to train at larger effective batch sizes without exceeding available memory, because the accumulated gradients occupy no more space than a single micro-batch backward pass. The learning rate of 2e-4 is a common choice for LoRA fine-tuning, which tolerates learning rates roughly ten times higher than full fine-tuning because only a small fraction of parameters is being updated. The 8-bit AdamW optimizer from the bitsandbytes library reduces optimizer state memory by roughly 75 percent relative to the standard 32-bit implementation, which frees VRAM for larger sequence lengths or batch sizes (Dettmers et al., 2022).

A production configuration typically replaces max_steps with num_train_epochs once the training corpus size is known, because step-based budgeting is primarily useful during early experimentation when you want to observe loss behavior without committing to a full pass over the data. A response-only loss mask, configured through the DataCollatorForCompletionOnlyLM helper, restricts the loss computation to tokens in the response portion of each example. This prevents the model from being penalized for failing to predict the fixed instruction text, which it has no reason to memorize and which would otherwise dominate the gradient signal.

Training is launched with a single call:

trainer_stats = trainer.train()

Loss values reported at each logging interval should decline smoothly from an initial value near the base model’s cross-entropy on the instruction format. A loss curve that plateaus within the first few logging steps usually indicates a learning rate that is too low or a rank that is too small for the target behavior. A loss curve that oscillates violently suggests the opposite problem: a learning rate that is too high for the chosen rank and alpha configuration. Practitioners who encounter either pattern should adjust one variable at a time, because the interaction between rank, alpha, and learning rate is multiplicative and difficult to diagnose when several are changed simultaneously.

Saving, Merging, and Validating the Fine-Tuned Model

Section titled “Saving, Merging, and Validating the Fine-Tuned Model”

Once training concludes, the adapter weights must be persisted before the Python session terminates. Unsloth provides two saving pathways. The first writes only the LoRA adapter weights, which produces a small artifact on the order of tens of megabytes that can be loaded on top of the original base model at inference time. The second merges the adapter into the base weights and saves a full model checkpoint, which is larger but eliminates the need to apply the adapter dynamically during inference.

model.save_pretrained("lora_model")
tokenizer.save_pretrained("lora_model")

The adapter-only save is appropriate during iterative development, because it allows you to maintain many adapters against a single base model without duplicating the base weights on disk. When the adapter is ready for deployment, merging produces a single self-contained checkpoint that inference frameworks can load directly. Merging requires the base model to be loaded in a precision compatible with the merge operation, typically 16-bit, because merging into a 4-bit quantized base is a lossy operation.

merged_model = model.merge_and_unload()
merged_model.save_pretrained("merged_model", safe_serialization = True)
tokenizer.save_pretrained("merged_model")

The safe_serialization flag writes the weights in the safetensors format, which provides integrity guarantees and faster load times compared with the legacy PyTorch pickle format. Unsloth also supports direct export to GGUF, a quantized format consumed by llama.cpp and related inference runtimes, through the save_pretrained_gguf method. This pathway is useful when the target deployment environment is a CPU-only machine or an edge device without CUDA support.

Before handing the model off to a formal evaluation pipeline, you should perform a quick generation test to confirm that the trained behavior is present. This validation step catches the most common failure modes.

FastLanguageModel.for_inference(model)
prompt = alpaca_template.format(
instruction = "Explain what a Kalman filter does in two sentences.",
input = "",
response = "",
)
inputs = tokenizer(prompt, return_tensors = "pt").to("cuda")
outputs = model.generate(
**inputs,
max_new_tokens = 128,
temperature = 0.7,
do_sample = True,
)
print(tokenizer.decode(outputs[0], skip_special_tokens = True))

The for_inference call switches Unsloth’s internal kernels into a generation-optimized mode that disables gradient tracking and enables fused attention paths, which reduces per-token latency by roughly a factor of 2 during interactive use. The prompt is rendered with an empty response field so that the model is placed exactly at the position from which it learned to generate during training. A coherent and on-topic completion indicates that the adapter has absorbed the instructional format. An incoherent completion, or one that repeats the instruction, usually indicates that the end-of-sequence token was omitted from the training examples or that the response-only loss mask was misconfigured.

The purpose of this validation is to confirm that the training pipeline produced a functioning artifact before scarce evaluation compute is allocated to it. Practitioners who treat this step as optional frequently discover subtle pipeline bugs only after investing substantial effort in downstream evaluation, at which point the cost of diagnosis is considerably higher. A successful generation test closes the hands-on fine-tuning loop and produces an adapter ready for the evaluation stage.