Wandering Giants Compute · Learn
Tutorial

How to Fine-Tune Llama on a Cloud GPU

The short answer

Rent a GPU with enough VRAM (24 GB for Llama 3.1 8B with QLoRA, 80 GB for Llama 3.3 70B with QLoRA), install transformers, TRL, PEFT and bitsandbytes, load the model in 4-bit, attach LoRA adapters, train with SFTTrainer on chat-formatted JSONL, then merge or serve the adapter with vLLM.

Llama 3.1 8B QLoRA VRAM
≈ 6–12 GB (fits a 24 GB RTX 4090)
Llama 3.3 70B QLoRA VRAM
≈ 42–55 GB (fits one 80 GB A100 or H100)
Full fine-tune memory
≈ 16–20 bytes per parameter before activations
Typical LoRA settings
r 16, alpha 32, learning rate 2e-4, all linear layers
Tools used
transformers, TRL SFTTrainer, PEFT, bitsandbytes, vLLM
8B QLoRA on 20M tokens
≈ 1.4 GPU-hours on H100 PCIe (compute estimate)

Fine-tuning Llama on a rented GPU is mostly a memory problem and a data problem; the code is short. This tutorial takes you from an empty cloud machine to a trained, merged and served Llama model using QLoRA with Hugging Face TRL and PEFT, with the VRAM sums and cost estimates you need to pick the right card first. It assumes Python familiarity, not deep ML experience. For the wider picture of what training is and when you need it, start with the GPU model training guide.

What do you need before you start?

You need four things: a GPU with enough VRAM, a Hugging Face account with access to the Llama model you want, a dataset in chat format, and about an hour of setup and test time.

  • A GPU machine with root access. You will install Python packages and run long jobs, so you want SSH and a real Linux box, not a notebook that times out.
  • Llama access. Meta's models on Hugging Face are gated. Open the model card, for example meta-llama/Llama-3.1-8B-Instruct, accept the licence, and create a read token in your Hugging Face settings.
  • Data. A few hundred to tens of thousands of examples of the behaviour you want. Quality beats quantity: 1,000 clean, consistent conversations usually beat 50,000 scraped ones.
  • A plan for evaluation. Hold back 5–10% of examples, and write down 20 prompts you will check by hand before and after.

Which GPU do you need to fine-tune Llama?

The GPU is set by model size and method. QLoRA stores the frozen base model in 4-bit (about 0.5–0.6 bytes per parameter) and trains small adapters; 16-bit LoRA stores the base at 2 bytes per parameter; full fine-tuning with Adam needs 16–20 bytes per parameter before activations.

ModelMethodWeightsRough total with activationsSmallest card that fits
Llama 3.2 3BLoRA (BF16)3 × 2 = 6 GB10–14 GBRTX 4090 (24 GB)
Llama 3.1 8BQLoRA (4-bit)8 × 0.55 ≈ 4.4 GB8–14 GBRTX 4090 (24 GB)
Llama 3.1 8BLoRA (BF16)8 × 2 = 16 GB20–30 GBL40S (48 GB)
Llama 3.1 8BFull (Adam, mixed precision)8 × 16–20 = 128–160 GB150–190 GBB200 (180 GB) tight, or 4–8 GPUs with FSDP
Llama 3.3 70BQLoRA (4-bit)70 × 0.55 ≈ 39 GB45–60 GBA100 80GB or H100 (80 GB)
Llama 3.3 70BLoRA (BF16)70 × 2 = 140 GB150–175 GBH200 (141 GB) too tight; B200 or 2–4 GPUs

The "rough total" column adds LoRA parameters, their Adam state, CUDA context and activations at 2,048 tokens with gradient checkpointing on. It is a rule-of-thumb range, not a measurement. Longer sequences and bigger batches push it up. The full breakdown is in how much VRAM you need to fine-tune an LLM.

Practical picks:

  • Llama 3.1 8B, first project: an RTX 4090 at $1.59/hr or an L40S at $1.89/hr. The L40S's 48 GB lets you use 16-bit LoRA and longer sequences.
  • Llama 3.3 70B: one A100 80GB at $3.79/hr or one H100 at $4.99/hr. The H100 has more than twice the A100's dense BF16 compute, so it finishes sooner.
  • Several runs in parallel (hyperparameter sweeps): a machine with 2, 4 or 8 of the same card, one run per GPU.

Step 1: Launch the machine and check the GPU

On Wandering Giants Compute pick a GPU, choose Root, and launch. You get Ubuntu with CUDA and PyTorch already installed, plus SSH and Jupyter. Billing runs by the minute from launch until you stop, so do your data preparation locally first if you can.

SSH in and confirm the card is visible:

bash
nvidia-smi
python3 -c "import torch; print(torch.__version__, torch.cuda.is_available(), torch.cuda.get_device_name(0))"
df -h /    # check you have disk for the model: 8B is ~16 GB, 70B is ~140 GB in BF16

Start a tmux session so training survives a dropped SSH connection:

bash
tmux new -s train

Step 2: Install the training stack

Use a virtual environment so you do not fight the system Python. The version floors below are the ones this code was written against; newer minor versions should work, but TRL renames arguments between releases, so pin what works once you have it.

bash
python3 -m venv ~/ft && source ~/ft/bin/activate
pip install -U pip
pip install -U "torch>=2.4" "transformers>=4.51" "trl>=0.20" "peft>=0.15" \
  "bitsandbytes>=0.45" accelerate datasets
hf auth login        # older huggingface_hub versions: huggingface-cli login

Step 3: Prepare your data in chat format

TRL's SFTTrainer understands a "conversational" dataset: each row has a messages list of role and content pairs. It applies the model's own chat template, so Llama's special tokens are handled for you.

json
{"messages": [{"role": "system", "content": "You are a support agent for Acme Rail. Answer in two sentences."}, {"role": "user", "content": "Can I change my ticket after the train leaves?"}, {"role": "assistant", "content": "No, changes must be made before departure. After that you can request a partial refund from the app within 28 days."}]}

Save one object per line as train.jsonl and eval.jsonl. To test the pipeline before you use your own data, the public trl-lib/Capybara dataset is already in this format.

Count your tokens before you train; it sets your run time and cost:

python
from datasets import load_dataset
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
ds = load_dataset("json", data_files="train.jsonl", split="train")
n = sum(len(tok.apply_chat_template(r["messages"], tokenize=True)) for r in ds)
print(f"{len(ds)} examples, {n:,} tokens per epoch")

Step 4: Train Llama 3.1 8B with QLoRA

This script loads the base model in 4-bit NF4, attaches LoRA adapters to every linear layer, and trains with gradient checkpointing. It is the standard QLoRA recipe from the TRL documentation and the original QLoRA paper.

python
# train_qlora.py
import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

model_id = "meta-llama/Llama-3.1-8B-Instruct"

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    quantization_config=bnb,
    torch_dtype=torch.bfloat16,
    device_map={"": 0},
    attn_implementation="sdpa",
)

data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})

peft_config = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    target_modules="all-linear",
    task_type="CAUSAL_LM",
)

args = SFTConfig(
    output_dir="llama31-8b-qlora",
    num_train_epochs=2,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,      # effective batch 16
    gradient_checkpointing=True,
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    warmup_ratio=0.03,
    bf16=True,
    max_length=2048,
    logging_steps=10,
    eval_strategy="steps",
    eval_steps=100,
    save_steps=100,
    save_total_limit=3,
    report_to="none",
)

trainer = SFTTrainer(
    model=model,
    args=args,
    train_dataset=data["train"],
    eval_dataset=data["eval"],
    processing_class=tokenizer,
    peft_config=peft_config,
)
trainer.train()
trainer.save_model("llama31-8b-qlora/final")

Run it inside tmux, and watch memory in a second pane:

bash
python train_qlora.py 2>&1 | tee train.log
watch -n 2 nvidia-smi

What the settings mean, in one line each:

  • r=16, lora_alpha=32: adapter rank and scale. Rank 8–64 covers almost every task; raise it if the model underfits a large, varied dataset.
  • learning_rate=2e-4: normal for LoRA, about 10× higher than full fine-tuning.
  • gradient_checkpointing=True: recomputes activations in the backward pass, trading roughly 20–30% speed for a large memory saving.
  • max_length=2048: examples longer than this are truncated. Set it from your token count, not by habit.

If you hit out-of-memory, halve per_device_train_batch_size and double gradient_accumulation_steps; the effective batch stays the same. On older TRL releases, max_length was called max_seq_length and processing_class was tokenizer.

Step 5: Scale the same script to Llama 3.3 70B

Change model_id to meta-llama/Llama-3.3-70B-Instruct, drop per_device_train_batch_size to 1 or 2, and raise gradient_accumulation_steps to keep the effective batch near 16. On one 80 GB card the 4-bit weights take about 39 GB (70 × 0.55), which leaves room for adapters and activations at 2,048 tokens. Download alone is about 140 GB of BF16 safetensors, so make sure the disk is big enough before you start.

If you want 16-bit LoRA on 70B, or a full fine-tune of a smaller model, you need more memory than one card has. That means sharding across several GPUs in one machine with FSDP or DeepSpeed, which is covered in single vs multi-GPU training.

Faster alternatives: Unsloth and Axolotl

You do not have to write the training loop yourself. Two open-source tools wrap the same libraries.

Unsloth patches the model with hand-written kernels and usually trains LoRA and QLoRA noticeably faster on one GPU with less memory, per its own published figures. The code looks almost the same:

python
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
    max_seq_length=2048,
    load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(
    model, r=16, lora_alpha=16, lora_dropout=0,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    use_gradient_checkpointing="unsloth",
)
# then build SFTTrainer exactly as above, without peft_config

Import Unsloth before transformers and TRL. Check the Unsloth docs for the current multi-GPU position; it has historically been strongest on single-GPU runs.

Axolotl drives everything from one YAML file, which is easier to version and repeat:

yaml
# llama-qlora.yml
base_model: meta-llama/Llama-3.1-8B-Instruct
load_in_4bit: true
adapter: qlora
lora_r: 16
lora_alpha: 32
lora_dropout: 0.05
lora_target_linear: true

datasets:
  - path: train.jsonl
    type: chat_template
    field_messages: messages
val_set_size: 0.05
output_dir: ./outputs/llama-qlora

sequence_len: 2048
sample_packing: true
micro_batch_size: 4
gradient_accumulation_steps: 4
num_epochs: 2
learning_rate: 0.0002
lr_scheduler: cosine
warmup_ratio: 0.03
optimizer: paged_adamw_8bit
bf16: auto
gradient_checkpointing: true
flash_attention: true
bash
pip install axolotl            # see docs.axolotl.ai for the CUDA-specific install
axolotl train llama-qlora.yml  # older releases: accelerate launch -m axolotl.cli.train llama-qlora.yml

sample_packing fills each 2,048-token slot with several short examples, which can cut run time sharply on chat data where most examples are short. Flash Attention needs the flash-attn package built for your CUDA version; set flash_attention: false if you have not installed it.

How long and how much will it cost?

A useful compute estimate is: training FLOPs ≈ 6 × parameters × training tokens, divided by the GPU's dense BF16 throughput times a utilisation factor. We use NVIDIA's published dense BF16 figures (RTX 4090 ≈ 165 TFLOPS, L40S ≈ 362, A100 312, H100 PCIe ≈ 756) and assume 25% utilisation for QLoRA. Treat the result as a floor and budget 1.5–2× for data loading, evaluation, checkpoints and the restart you did not plan.

Worked example: 10,000 conversations averaging 1,000 tokens, 2 epochs = 20 million training tokens.

Model and methodGPUEstimated GPU-hoursPrice per GPU-hourCost
Llama 3.1 8B QLoRARTX 40906.5$1.59/hr$10.34
Llama 3.1 8B QLoRAL40S3.0$1.89/hr$5.67
Llama 3.1 8B QLoRAH1001.4$4.99/hr$6.99
Llama 3.3 70B QLoRAA100 80GB29.9$3.79/hr$113.32
Llama 3.3 70B QLoRAH10012.4$4.99/hr$61.88

Estimates, prices as of November 2026. The arithmetic for the 8B H100 row: 6 × 8×10⁹ × 2×10⁷ = 9.6×10¹⁷ FLOPs; 756×10¹² × 0.25 = 1.89×10¹⁴ FLOP/s; 9.6×10¹⁷ ÷ 1.89×10¹⁴ ≈ 5,080 s ≈ 1.4 hours. For a 70B model the fastest card is usually also the cheapest per run, because a 2–2.5× speed advantage outweighs a smaller price gap. For more scenarios see what it costs to fine-tune an LLM.

Step 6: Evaluate, merge and serve the model

Training loss going down only tells you the model is memorising your format. Before you ship, run your 20 hand-picked prompts through the base model and the fine-tune side by side, and check the held-out eval loss did not rise in the last third of training (a sign of overfitting; use an earlier checkpoint if it did).

To produce a standalone model, load the adapter on a 16-bit base and merge. Merge onto the BF16 base, not the 4-bit one, so you do not bake in quantisation error.

python
# merge.py
import torch
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer

model = AutoPeftModelForCausalLM.from_pretrained(
    "llama31-8b-qlora/final", torch_dtype=torch.bfloat16, device_map="auto"
)
merged = model.merge_and_unload()
merged.save_pretrained("llama31-8b-merged", safe_serialization=True)
AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct").save_pretrained("llama31-8b-merged")

Then serve it with vLLM as an OpenAI-compatible API:

bash
pip install vllm
vllm serve ./llama31-8b-merged --max-model-len 8192
# or keep the base and hot-load the adapter:
vllm serve meta-llama/Llama-3.1-8B-Instruct --enable-lora \
  --lora-modules acme=./llama31-8b-qlora/final --max-lora-rank 16

Serving the adapter separately lets one base model carry several fine-tunes. For a fuller serving walkthrough, see running Llama on a cloud GPU.

Common mistakes that waste GPU hours

Most failed Llama fine-tunes fail for boring reasons. Check these before you launch a long run.

  1. Wrong chat template. Training a base model on raw text and then prompting it like an instruct model, or vice versa. Start from the -Instruct model and let SFTTrainer apply its template.
  2. No pilot run. Run 50 steps with max_steps=50 first. It catches out-of-memory, tokenisation and path errors in minutes, not hours.
  3. Too many epochs. Small datasets overfit after 2–3 epochs. Watch eval loss.
  4. Leaving the machine on. Copy checkpoints off the box (to object storage or your laptop with rsync), then stop it. On our billing, a stopped machine pays only for disk, about 3¢ an hour per 50 GB.
  5. Training when retrieval would do. If the goal is answering from your documents, retrieval-augmented generation is usually cheaper and easier to update. Fine-tune for format, tone and task behaviour.

When renting from Wandering Giants fits

Wandering Giants Compute suits this job when you want one machine with 1, 2, 4 or 8 of the same GPU, full root access, and per-minute billing that stops itself when your prepaid credit runs out. That covers almost every LoRA and QLoRA job on Llama models up to 70B, and full fine-tunes of smaller models across up to eight cards. Prices show in your own currency, with UK VAT included for UK customers.

It does not fit if you need a multi-node cluster with InfiniBand for full fine-tuning or pre-training at 70B scale and above; we do not offer one. Providers such as Lambda (1-Click Clusters), CoreWeave and Nebius sell multi-node capacity, and that is the honest place to go for it. For a side-by-side of where to rent for this kind of work, see the best GPU clouds for fine-tuning.

Frequently asked questions

Can I fine-tune Llama 3.1 8B on a 24 GB GPU?

Yes. With QLoRA the 4-bit weights take about 5 GB, and adapters, optimiser state and activations with gradient checkpointing bring a 2,048-token run to roughly 8–14 GB. An RTX 4090 handles it comfortably; plain 16-bit LoRA also fits at shorter sequence lengths.

What GPU do I need to fine-tune Llama 3.3 70B?

For QLoRA, one 80 GB card such as an A100 80GB or H100 is enough: the 4-bit weights are about 35–42 GB and the rest fits in the remaining headroom at moderate sequence lengths. Full fine-tuning of 70B needs over a terabyte of GPU memory, which means a multi-node cluster.

How long does it take to fine-tune Llama 8B?

On 20 million training tokens, a compute estimate is about 1.4 hours on one H100 PCIe and about 6.5 hours on an RTX 4090 with QLoRA. Real runs are often slower because of data loading, evaluation and short sequences, so budget 1.5–2× the estimate.

Should I use QLoRA or LoRA for Llama?

Use QLoRA when memory is the constraint, for example 70B on one card or 8B on a 24 GB GPU with long sequences. Use 16-bit LoRA when the model fits, because it trains faster per step and avoids quantisation error in the base weights.

Do I need to merge the LoRA adapter after training?

No. vLLM can serve the base model with your adapter loaded through --enable-lora, which lets you keep several adapters on one base. Merging produces a single standalone model, which is simpler to ship and slightly faster to serve.

Do I need permission to download Llama?

Yes. Meta's Llama models on Hugging Face are gated: you accept the licence on the model page, then log in on the GPU machine with a Hugging Face access token before downloading.

Wandering Giants Compute

Rent the GPU for this, by the minute.

Launch a Root machine with CUDA and PyTorch ready, fine-tune Llama by the minute, and stop paying the moment training ends.

Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.

Keep reading

About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.

Last reviewed 25 November 2026.