LLM Adaptation: Choosing the Right Training Approach
Fine-tuning open-weight models used to mean writing custom PyTorch training loops from scratch. You had to wire up Hugging Face Accelerate, debug DeepSpeed ZeRO-3 JSON files, and pray your gradient accumulation logic did not silently overflow memory. While that bare-metal approach works, it wastes engineering cycles on plumbing instead of dataset curation and model evaluation.
When adapting a foundation model like Qwen2.5, you will generally choose between three core strategies:
- Full Fine-Tuning: Updates every parameter in the architecture. This yields peak performance for heavy domain shifts, but the hardware barrier is steep. A 7B parameter model in FP16 demands 14 GB just to store the weights. Once you factor in AdamW optimizer states (8 to 16 bytes per parameter), gradients, and activations, your memory footprint balloons past 120 GB. You will need a multi-GPU cluster—typically two to four A100 or H100 80GB cards—just to get started.
- LoRA and QLoRA: LoRA (Low-Rank Adaptation) freezes base weights and trains lightweight rank decomposition matrices across targeted layers like
q_projandv_proj. QLoRA takes this further by quantizing base weights down to 4-bit NormalFloat (NF4). That drops the base model memory for Qwen2.5-7B from 14 GB down to roughly 4.8 GB. With activation checkpointing enabled, an entire fine-tuning run fits into 12 GB to 16 GB of VRAM. A single consumer-grade RTX 3090 or RTX 4090 handles it with room to spare. - Direct Preference Optimization (DPO): Takes your supervised fine-tuned checkpoint and steers its behavior using pairs of chosen and rejected responses. Older RLHF pipelines required training a separate, notoriously finicky reward model before running PPO. DPO bypasses that instability entirely. It optimizes policy behavior directly using a closed-form implicit reward function embedded in a standard binary cross-entropy loss.
For 90% of internal enterprise tasks, starting with LoRA SFT and following up with light DPO delivers the best accuracy per dollar.
LLaMA-Factory: Strengths and Real-World Trade-offs
LLaMA-Factory has become a go-to framework for rapid iteration. It bundles Hugging Face PEFT, DeepSpeed, BitsAndBytes, and FlashAttention-2 behind both a robust CLI and a browser-based dashboard called LLaMA Board. Still, every abstraction layer carries tradeoffs.
Where It Excels
- Multi-Stage Support: Move from continuous pre-training to SFT, reward modeling, and DPO without rewriting scripts.
- Frictionless Dataset Registration: Map custom JSON datasets into training runs by adding a single five-line block to a manifest file.
- Built-in Live Telemetry: Track real-time training loss, gradient norms, learning rate schedules, and VRAM utilization directly inside a Gradio UI.
- One-Step Weight Merging: Merge your trained LoRA adapter weights directly back into base FP16 tensors. You get clean Hugging Face checkpoints ready for vLLM or Ollama deployment immediately.
Practical Limitations
- Deeper Debugging Hurdles: If you need custom loss functions, non-standard masking, or specialized attention variants, debugging the abstraction layers inside LLaMA-Factory takes longer than inspecting raw PyTorch.
- UI Resource Overhead: The Gradio server and internal metrics loggers hold an extra 500 MB to 1 GB of system RAM and minor GPU overhead. On tight 16 GB cards, drop to headless CLI execution to avoid out-of-memory crashes.
Hardware and Environment Prerequisites
We will target Qwen2.5-7B-Instruct, a model that punches well above its weight class in structured JSON generation, coding, and multi-turn reasoning.
Here is the minimum and recommended hardware profile for this run:
- OS: Ubuntu 22.04 LTS or 24.04 LTS (x86_64)
- GPU: 1x NVIDIA RTX 3090 or RTX 4090 (24 GB VRAM) for 16-bit LoRA; an RTX 4080 (16 GB) or RTX 3060 (12 GB) works if running 4-bit QLoRA. For data centers, an A10G (24 GB), L4 (24 GB), or A100 (40/80 GB) is ideal.
- Host RAM: 32 GB minimum. Tokenizing and caching a 50,000-sample dataset will easily eat 18 GB of system memory.
- Disk: 120 GB of NVMe SSD storage. The base 7B model takes ~15 GB, datasets take 2 to 5 GB, and full training checkpoints consume 15 GB apiece.
- Driver & Tooling: NVIDIA Driver version 535 or higher with CUDA 12.1 or 12.4.
Step-by-Step Implementation
Follow these steps to configure your environment, prepare your data, and launch training on an Ubuntu server.
Step 1: System Dependencies and PyTorch Setup
Always isolate machine learning dependencies inside a dedicated virtual environment. System-level pip installs will eventually break system tools.
# Install fundamental build tools and git-lfs
sudo apt update && sudo apt install -y git git-lfs python3-venv python3-pip build-essential
# Initialize virtual environment
python3 -m venv ~/llama-env
source ~/llama-env/bin/activate
# Install PyTorch with CUDA 12.1 wheels
pip install --upgrade pip setuptools wheel
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
# Sanity check CUDA detection
python3 -c "import torch; print(f'CUDA: {torch.cuda.is_available()} | GPU: {torch.cuda.get_device_name(0)} | VRAM: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.1f} GB')"
Step 2: Install LLaMA-Factory and FlashAttention-2
Clone the repository and install the framework with acceleration packages. FlashAttention-2 cuts attention memory complexity from quadratic $O(N^2)$ to linear $O(N)$, which speeds up 2048-token sequences by 25% to 35% on Ampere and Ada architectures.
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
# Install core framework with DeepSpeed and 4-bit quantization support
pip install -e ".[metrics,deepspeed,bitsandbytes]"
# Install FlashAttention-2 (requires ninja for parallel compilation)
pip install ninja packaging
pip install flash-attn --no-build-isolation
Step 3: Prepare and Register Datasets
LLaMA-Factory catalogs all data sources in data/dataset_info.json. You need two datasets: one for teaching domain style (SFT) and one for teaching trade-offs (DPO).
Create your SFT dataset at data/custom_sft.json:
[
{
"instruction": "You are a site reliability engineer. Diagnose this container failure.",
"input": "Kubernetes pod status shows OOMKilled with exit code 137.",
"output": "Exit code 137 means the Linux kernel sent a SIGKILL (128 + 9) because the container exceeded its cgroup memory limit. Check limits via `kubectl describe pod <pod-name>` and review host kernel events with `dmesg -T | grep -E -i 'oom[- ]killer'`."
}
]
Next, build a pairwise comparison dataset at data/custom_dpo.json for preference tuning:
[
{
"conversations": [
{
"from": "human",
"value": "How do I inspect open TCP listening sockets on Ubuntu 22.04?"
}
],
"chosen": {
"from": "gpt",
"value": "Run `ss -tulpn`. The flags break down as: `-t` (TCP), `-u` (UDP), `-l` (listening sockets), `-p` (show process PID), and `-n` (numeric ports without DNS lookups). Avoid deprecated tools like `netstat`."
},
"rejected": {
"from": "gpt",
"value": "You can install netstat or grep around the /proc directory to see what processes are running."
}
}
]
Open data/dataset_info.json and register both files:
{
"custom_sft": {
"file_name": "custom_sft.json"
},
"custom_dpo": {
"file_name": "custom_dpo.json",
"ranking": true
}
}
Step 4: Launch LLaMA Board
On remote instances, bind the server to 0.0.0.0 and tunnel the connection over SSH. Never expose raw port 7860 directly to the public internet.
# Run on remote instance
llamafactory-cli webui --port 7860 --host 0.0.0.0
Open an encrypted tunnel from your local laptop terminal:
ssh -N -L 7860:127.0.0.1:7860 user@your-server-ip
Navigate to http://localhost:7860 in your local browser to access the control panel.
Step 5: Execute Supervised Fine-Tuning (LoRA SFT)
In the WebUI Train tab, apply these specific hyperparameters for your base SFT run:
- Model name:
Qwen2.5-7B-Instruct - Model path:
Qwen/Qwen2.5-7B-Instruct(or your local directory) - Stage:
Supervised Fine-Tuning - Finetuning method:
lora - Dataset: Select
custom_sft - Learning rate:
5e-5with acosinedecay scheduler and 10% warmup steps - Batch size & Gradient accumulation: Set batch size to
2and gradient accumulation steps to8(effective batch size of 16) - Cutoff length:
2048tokens - LoRA configuration: Set rank ($r$) to
16, alpha to32, dropout to0.05, and target modules toall - Compute precision:
bf16(Ampere or newer) orfp16(Turing/T4)
Hit Preview Command to verify the flags, then click Start. On an RTX 4090, training throughput usually settles around 12 to 18 tokens per second per GPU. Monitor the loss plot in the UI; it should smoothly fall from ~2.4 down to 0.8–1.1 over 3 epochs.
Step 6: Run DPO Preference Alignment
With the SFT adapter saved, treat it as the reference checkpoint and align model outputs with human preferences:
- Stage: Switch to
Direct Preference Optimization (DPO) - Checkpoint dir: Select your SFT folder (e.g.,
saves/Qwen2.5-7B-Instruct/lora/sft) - Dataset: Select
custom_dpo - Learning rate: Drop this to
5e-6(an order of magnitude lower than SFT prevents catastrophic forgetting) - DPO Beta: Set to
0.1. This controls KL penalty strength against the reference model. Higher values force the model to stick closer to original behaviors.
Click Start. LLaMA-Factory computes margin log-ratios between your chosen and rejected answers, steadily nudging probability mass away from poor answers.
Step 7: Merge Adapters and Export
Running inference with dynamic LoRA adapters adds unnecessary latency. Merge the adapter weights into the base foundation tensors before deploying to production:
llamafactory-cli export \
--model_name_or_path Qwen/Qwen2.5-7B-Instruct \
--adapter_name_or_path saves/Qwen2.5-7B-Instruct/lora/dpo \
--template qwen \
--finetuning_type lora \
--export_dir exports/Qwen2.5-7B-Production \
--export_size 2 \
--export_device cpu
The resulting exports/Qwen2.5-7B-Production folder is an unquantized FP16 Hugging Face model directory. You can load it straight into high-performance inference engines like vLLM with vllm serve exports/Qwen2.5-7B-Production --port 8000 or convert it to GGUF format for edge execution in Ollama.

