Skip to content
ImagineWorld

Running Continued Pretraining with Python and Unsloth

node_idnode-book_llm-systems-engineering_module-35-running-continued-pretraining-with-python-and-unsloth
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num35
chapter_titleRunning Continued Pretraining with Python and Unsloth
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Module 35 — Running Continued Pretraining with Python and Unsloth

Section titled “Module 35 — Running Continued Pretraining with Python and Unsloth”

Much like fine-tuning, continued pretraining can be run using Python and Unsloth. This module walks through each stage of such a run, from environment setup through model validation. The goal is to give you a pattern that can be copied and trusted, so that the transition from understanding continued pretraining to executing is clear. The techniques covered here build on the quantization and adapter methods established in earlier modules of this book, integrating them into a single coherent pipeline. Along the way, attention is paid to the hyperparameter and data choices that connect back to the forgetting and integration risks previously explored. By the end, you should understand how a compact script can drive a domain adaptation run on a mid-range GPU and produce a model ready for evaluation.

The first operational step in any continued pretraining run is establishing a reliable Python environment. Unsloth depends on specific versions of PyTorch and the Hugging Face Transformers library. It also requires the bitsandbytes quantization backend for 4-bit loading. Unsloth is designed to function as a drop-in replacement for standard Hugging Face training loops while offering substantial throughput improvements through kernel-level optimizations. These optimizations allow you to run continued pretraining workflows with roughly half the memory footprint of a standard Hugging Face plus Flash Attention 2 QLoRA baseline, which becomes particularly important when operating on a single consumer GPU. The installation sequence typically involves pip install unsloth along with its conditional dependencies, and careful attention to CUDA version matching remains an essential prerequisite.

Once the environment is ready, the base model is loaded using the FastLanguageModel class. This entry point handles the initialization of a quantized transformer in a memory-efficient form. The recommended pattern for 4-bit loading draws on the QLoRA paradigm (Module 28). A typical snippet follows this pattern:

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

After the base model is loaded, LoRA adapters are attached so that training updates only a small set of low-rank matrices while the base weights remain frozen. In Unsloth, the adapter configuration is applied through a dedicated helper:

model = FastLanguageModel.get_peft_model(
model,
r = 16,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
"embed_tokens", "lm_head"],
lora_alpha = 16,
lora_dropout = 0,
bias = "none",
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = True,
)

For continued pretraining specifically, Unsloth recommends including the input and output embedding layers among the LoRA targets, because continued pretraining benefits from allowing vocabulary representations to adjust slightly in response to domain-specific distribution. This design choice responds to findings that earlier LoRA configurations, which trained only attention projections, tended to underperform full fine-tuning on continued pretraining tasks. Rank-stabilized LoRA (the use_rslora flag) further improves training stability at higher adapter ranks, which becomes useful when the domain corpus differs substantially from the original pretraining distribution.

Preparing and Tokenizing a Domain Corpus for Training

Section titled “Preparing and Tokenizing a Domain Corpus for Training”

Once the model is ready, attention turns to the data pipeline, which for continued pretraining takes the form of raw text that will be fed into the same next-token prediction objective used during the original pretraining phase. The Hugging Face datasets library provides the standard interface for loading domain corpora, whether from local Parquet files or a remote repository. A single-column dataset with a text field is typically sufficient, though in practice many teams attach metadata columns for later filtering. The data loading pattern follows a simple form:

from datasets import load_dataset
dataset = load_dataset(
"json",
data_files = "domain_corpus.jsonl",
split = "train",
)

Tokenization then applies the model’s tokenizer to each document, followed by a decision about how sequences are packed into training examples (Module 19). A simple tokenization function for continued pretraining follows this pattern:

def tokenize(example):
return tokenizer(
example["text"],
truncation = True,
max_length = 2048,
)
tokenized_dataset = dataset.map(
tokenize,
batched = True,
remove_columns = ["text"],
)

Unsloth’s training harness can handle the packing step internally when the training arguments indicate it. For continued pretraining runs, practitioners often choose to interleave a small fraction of general-domain text with the domain corpus as a replay buffer (Module 32). This blending of new and old data is one of the simplest structural defenses against catastrophic forgetting, and it integrates naturally into the dataset construction step because the datasets library supports concatenation and interleaved sampling through standard methods.

Configuring and Launching the Training Run

Section titled “Configuring and Launching the Training Run”

With the model and data prepared, the next step is configuring the training loop. For continued pretraining specifically, Unsloth provides the UnslothTrainer class, which has become the preferred choice because it exposes configuration options that continued pretraining workflows depend on. The most important of these is a separate embedding_learning_rate parameter, which allows the embedding and output projection matrices to be updated at a different pace than the attention and feed-forward projections. The trainer is instantiated with a reference to the model, the tokenizer, the packed dataset, and an UnslothTrainingArguments object that specifies the optimization schedule. The hyperparameters in that configuration are where several of the risks addressed earlier become concrete engineering choices.

The learning rate deserves particular care. A continued pretraining run typically uses a learning rate that is lower than what was used in the original pretraining phase, because the model is already close to a useful optimum and large updates risk destabilizing its existing representations. A practical configuration begins with a small peak learning rate, a short linear warmup phase, and a cosine decay (Module 22) toward a lower floor:

from unsloth import UnslothTrainer, UnslothTrainingArguments
training_args = UnslothTrainingArguments(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 8,
warmup_steps = 50,
num_train_epochs = 1,
learning_rate = 5e-5,
embedding_learning_rate = 1e-5,
lr_scheduler_type = "cosine",
fp16 = not torch.cuda.is_bf16_supported(),
bf16 = torch.cuda.is_bf16_supported(),
logging_steps = 10,
optim = "adamw_8bit",
weight_decay = 0.01,
output_dir = "outputs",
)

The distinct embedding_learning_rate addresses a specific risk identified in the research on LoRA for continued pretraining. The embedding and output projection matrices benefit from a smaller learning rate than the attention and feed-forward projections, because they encode the token-level representation that generalizes across all downstream behavior. Using a single learning rate across every trainable parameter can cause the embedding space to drift too quickly, degrading the base model’s ability to handle tokens that appeared rarely in the domain corpus. The UnslothTrainer exposes this parameter directly, which is a primary reason it is chosen over more general-purpose trainers for continued pretraining work today.

The gradient accumulation setting multiplies the per-device batch by a fixed factor to approximate a larger effective batch without the memory cost of holding those examples in GPU memory simultaneously. The practical advice is to treat gradient accumulation as a memory management tool and to avoid using it as the default path to larger effective batch sizes when a single-device run is viable with a smaller batch. After instantiating the trainer, the run is launched with a single method call:

trainer = UnslothTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = tokenized_dataset,
dataset_text_field = "text",
max_seq_length = 2048,
dataset_num_proc = 2,
packing = True,
args = training_args,
)
trainer_stats = trainer.train()

Once training begins, you should watch the loss curve closely. A continued pretraining run should show a steady decline in loss across the first several hundred steps, with a plateau emerging as the model absorbs the domain distribution. A loss curve that drops sharply in the first few hundred steps and then fails to improve often indicates that the learning rate is too high and the model has overwritten useful representations before adapting to the new data. A loss curve that remains flat across many steps usually indicates that the learning rate is too low or that the data has low information density relative to what the model has already seen.

Saving, Merging, and Validating the Updated Model

Section titled “Saving, Merging, and Validating the Updated Model”

At the conclusion of the run, the LoRA adapter weights are saved separately from the base model. This separation is a practical convenience because the adapter weights for a LoRA configuration occupy a small fraction of the disk space required by a full model checkpoint, which makes iteration and version tracking cheaper. The save step uses the standard Hugging Face PEFT interface exposed through the Unsloth model wrapper:

model.save_pretrained("lora_adapter")
tokenizer.save_pretrained("lora_adapter")

For deployment, the adapter is typically merged back into the base model weights so that inference does not require holding both the base model and the adapter in memory simultaneously. The Hugging Face PEFT library exposes a merge_and_unload method that produces a single set of consolidated weights, which can then be saved in whichever precision the inference environment requires. Merging changes the forward pass from a two-branch computation, where the base weight multiplication is summed with the adapter multiplication, into a single matrix multiplication at each linear layer, which reduces inference latency and simplifies deployment.

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

For deployment into environments that require specific inference formats, Unsloth provides export helpers for GGUF and similar formats. These formats can be produced directly from the trainer through methods like save_pretrained_gguf, which handles the quantization and conversion in one step.

Validation is the final and most consequential stage of the workflow. The updated model should be evaluated both on a held-out portion of the domain corpus, which confirms that the continued pretraining has produced a perplexity improvement on in-domain text, and on a representative general capability benchmark, which confirms that the model has not meaningfully regressed on the behavior it already possessed. Domain-focused updates can degrade performance on general benchmarks if protective strategies like data replay are omitted (Shi et al., 2024). A minimal evaluation loop looks like this:

import torch
from torch.utils.data import DataLoader
def compute_perplexity(model, dataset, tokenizer):
model.eval()
total_loss = 0.0
total_tokens = 0
for batch in DataLoader(dataset, batch_size = 1):
with torch.no_grad():
outputs = model(
**batch,
labels = batch["input_ids"],
)
n = batch["input_ids"].numel()
total_loss += outputs.loss.item() * n
total_tokens += n
mean = total_loss / total_tokens
return torch.exp(torch.tensor(mean)).item()

Beyond perplexity, you should run the same downstream tasks the base model was known to handle well and compare the updated model’s scores against the base scores. A regression of more than a few percentage points on tasks the base model previously passed indicates that the continued pretraining has damaged general behavior and the configuration should be revisited. Common corrections include lowering the learning rate and increasing the replay fraction of general data. When the domain-specific gains materialize alongside preserved general behavior, the updated model can be promoted to downstream fine-tuning or alignment work with confidence that its foundation remains intact.

This book includes additional resources to support and continue your AI journey. Scan the QR code below (or go to ashford-publishing.com/materials) and enter the book code found at the back of this book.