A Guide to Using Axolotl on Linux: Fine-Tuning LLMs via YAML Configuration Files

Artificial Intelligence tutorial - IT technology blog
Artificial Intelligence tutorial - IT technology blog

Real-World Challenges: When Off-the-Shelf Models Don’t Understand Your Domain

Deploying open-source models like Llama 3, Mistral, or Qwen to on-premise infrastructure often introduces a familiar headache. The model is theoretically accurate but misuses your product-specific terminology. Worse still, it might generate invalid JSON outputs, breaking your automated CI/CD pipelines.

Prompt engineering and RAG only scratch the surface. When you need a model to follow internal scripting syntax with 100% precision or consistently adhere to a technical tone, fine-tuning becomes essential.

However, writing custom PyTorch or Hugging Face Transformers training scripts is tedious and time-consuming. You have to manually handle tokenization, integrate FlashAttention-2, calibrate gradient accumulation, and constantly battle CUDA OOM (Out of Memory) errors. Axolotl solves this elegantly by consolidating all the complex logic into a single YAML configuration file.

How Axolotl Works: The Declarative Configuration Mindset

If you are familiar with writing Kubernetes manifests or Ansible playbooks, Axolotl will feel right at home. Instead of writing hundreds of error-prone lines of Python code, you simply declare your parameters in a YAML file:

  • Model Management: Point directly to a repository on the Hugging Face Hub or a local file path.
  • Automated Dataset Processing: Automatically detects Alpaca, ShareGPT, and ChatML formats without requiring custom formatting scripts.
  • Maximum VRAM Efficiency: Built-in 4-bit/8-bit QLoRA support allows you to comfortably train 8B models on consumer 24GB GPUs like the RTX 3090, RTX 4090, or an AWS g5.xlarge (A10G) instance instead of renting expensive A100 clusters.
  • Speed Optimization: Leverages FlashAttention-2 and DeepSpeed ZeRO to push your GPU to its full potential.

Step-by-Step Guide: Fine-Tuning Llama 3 8B on Ubuntu

1. Setting Up the Environment

Your server needs to run Ubuntu 22.04 LTS with NVIDIA Drivers (version 535 or higher) and the NVIDIA Container Toolkit. To avoid CUDA library conflicts between host and container, the easiest approach is pulling the official Axolotl Docker image:

# Verify GPU detection on Linux
nvidia-smi

# Launch the pre-built Axolotl container with CUDA 12.1 and FlashAttention-2
docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 \
  -v $(pwd)/workspace:/workspace -it winglian/axolotl:main-latest bash

If you prefer running directly inside a virtualenv on bare metal:

git clone https://github.com/OpenAccess-AI-Collective/axolotl.git
cd axolotl
python3 -m venv venv
source venv/bin/activate
pip3 install packaging
pip3 install -e '.[flash-attn,deepspeed]'

2. Preparing the Training Dataset

Suppose you want to train the model to generate standardized CLI commands for your systems. Create /workspace/dataset.json using the standard Alpaca format:

[
  {
    "instruction": "Write a Linux command to check disk space in a human-readable format.",
    "input": "",
    "output": "Use the command: df -h"
  },
  {
    "instruction": "Restart the nginx service on Ubuntu systemd.",
    "input": "",
    "output": "Run the command: sudo systemctl restart nginx"
  }
]

3. Configuring the YAML File (config-qlora.yml)

This is the most critical step. The configuration below uses meta-llama/Meta-Llama-3-8B-Instruct as the base model and applies 4-bit QLoRA. Actual VRAM consumption sits comfortably at around 14.5 GB:

base_model: meta-llama/Meta-Llama-3-8B-Instruct
model_type: AutoModelForCausalLM
tokenizer_type: AutoTokenizer

load_in_8bit: false
load_in_4bit: true
strict: false

datasets:
  - path: /workspace/dataset.json
    type: alpaca

dataset_prepared_path: /workspace/prepared_data
val_set_size: 0.05
output_dir: /workspace/output_model

adapter: qlora
lora_r: 16
lora_alpha: 32
lora_dropout: 0.05
lora_target_modules:
  - q_proj
  - v_proj
  - k_proj
  - o_proj
  - gate_proj
  - down_proj
  - up_proj

sequence_len: 2048
sample_packing: true
pad_to_sequence_len: true

wandb_project:
wandb_entity:
wandb_watch:
wandb_name:

gradient_accumulation_steps: 4
micro_batch_size: 2
num_epochs: 3
optimizer: adamw_bnb_8bit
lr_scheduler: cosine
learning_rate: 0.0002

bf16: auto
fp16: false
tf32: false

flash_attention: true
warmup_steps: 10
evals_per_epoch: 1
saves_per_epoch: 1
debug:
weight_decay: 0.0
fsdp:
fsdp_config:
special_tokens:

4. Validating Data and Starting Training

Don’t jump straight into training. Use Axolotl’s preprocessing tool to tokenize and validate your dataset beforehand:

# Step 1: Validate syntax and build the token cache
python -m axolotl.cli.preprocess config-qlora.yml

# Step 2: Start training with GPU
accelerate launch -m axolotl.cli.train config-qlora.yml

The preprocessing step catches formatting issues early before burning through GPU compute. During training, the terminal displays real-time loss metrics and VRAM usage. Enabling sample_packing: true packs multiple short samples into a single 2048-token context window, accelerating training speeds 2x to 3x compared to standard padding.

5. Testing and Merging Weights

Once training completes, the LoRA adapter—weighing only a few dozen megabytes—will be saved in the output_model directory. You can test it immediately via the terminal:

python -m axolotl.cli.inference config-qlora.yml --lora_model_dir="/workspace/output_model"

To handle high-throughput production workloads using vLLM or TGI, you should merge the LoRA weights into the base model:

python -m axolotl.cli.merge_lora config-qlora.yml --lora_model_dir="/workspace/output_model"

This command exports a complete standalone model directory in safetensors format. You can then load it directly into vLLM to serve inference requests without worrying about tensor mismatches.

Conclusion: A Solid MLOps Foundation for Engineering Teams

Axolotl transforms LLM fine-tuning from an academic research task into a standardized infrastructure workflow. All parameters reside in a single YAML configuration file versioned cleanly with Git. This allows engineering teams to easily reproduce training runs, maintain full ownership of proprietary data, and keep GPU infrastructure costs under control.

Share: