The problem
Renting a GPU by the hour makes every mistake in a LoRA run visible on the invoice. A 7B model needs a card with plenty of memory, the meter runs while the dataset is still being cleaned, and if the instance is reclaimed at hour five with no usable checkpoint, you pay again for hours one to five. The three failure modes I wanted to reproduce are wasted tokens from careless data, lost progress from fragile checkpoints, and a run that nobody capped.
What I could and could not reproduce
This sandbox has no GPU, so I did not fine-tune a 7B model. What I did: prepared a real instruction dataset with the 7B model's tokenizer, computed the LoRA parameter counts for a 7B architecture without loading its weights, and ran a real LoRA training with checkpointing, a hard kill, a resume and a budget guard on a 0.5B model of the same family, on CPU. The mechanics carry over. The speed and price numbers do not.
The environment
First I recorded what this machine is, because the numbers later only mean something relative to this hardware and software. Nothing beyond what these commands print is claimed about the machine, its location or its provider, and I did not look anything else up.
uname -a
Linux vm 6.18.44-fc-v880 #1 SMP PREEMPT_DYNAMIC @0 x86_64 x86_64 x86_64 GNU/Linux
cat /etc/os-release | head -2
PRETTY_NAME="Ubuntu 24.04.5 LTS"
NAME="Ubuntu"
nproc
4
nvidia-smi
-bash: nvidia-smi: command not found
So this is a clean Ubuntu 24.04 container with four CPU cores, about 16 GB of RAM (from free -m, not shown) and no GPU. Everything below that I call measured was measured here, and any number I derived from arithmetic rather than a run is labelled as derived.
Root cause
The expense is tokens times seconds per token times price per hour, and each factor has a way of silently growing. Duplicate and over-long examples inflate the token count. Training state that exists only on the instance makes any interruption cost everything since the last save. A training loop with no wall-clock limit keeps billing long after the loss curve has flattened.
Why LoRA changes the checkpoint question
LoRA freezes the base weights and trains small low-rank matrices, so what you must preserve is small. The catch is that the Hugging Face Trainer by default also writes optimizer, scheduler and random-number state next to the adapter so that a resume is exact. Those files are larger than the adapter, and they are the part people forget to sync off the machine.
Source of truth
I relied on the references below plus measurements in this sandbox. Anything else in this article is something I measured myself and label as such. Each bullet says what the source confirms, and the two license queries after the list are commands I ran against the Hugging Face API.
- The PEFT LoRA developer guide confirms that PEFT's default LoRA targets only the query and value layers of each attention block, and that you can widen the target set to all linear layers.
- The Transformers Trainer documentation describes
save_steps,save_total_limitandresume_from_checkpoint, and states thatsave_only_modeldrops optimizer, scheduler and RNG state and so prevents resuming from that checkpoint. - The cards for Qwen/Qwen2.5-7B and databricks-dolly-15k carry the licenses, queried below.
curl -s https://huggingface.co/api/datasets/databricks/databricks-dolly-15k | python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('cardData',{}).get('license'))"
cc-by-sa-3.0
curl -s https://huggingface.co/api/models/Qwen/Qwen2.5-7B | python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('cardData',{}).get('license'), d.get('gated'))"
apache-2.0 False
Approaches compared
Data preparation
You can train on the raw dump, or spend CPU time (cheap) before spending GPU time (expensive): normalize, de-duplicate on the prompt, drop examples above a token limit, and hold out a validation split. Raw is faster to start, but you pay for every wasted token at the GPU rate.
Checkpointing
There are three options. Save only the adapter, which is tiny but cannot restore the optimizer and so changes the training dynamics after a restart. Save the full Trainer state every N steps, which resumes exactly. Or save nothing and rely on a short run. For rented or preemptible machines the second is the sensible default, provided the files leave the box.
Cost control
You can eyeball the cost, extrapolate from a short measured pilot, or enforce a limit in code. These are not exclusive: a pilot gives you a number before you commit, and a wall-clock guard in the training loop makes that number binding.
Why this fix
I combined the careful option in each category: clean the data on the CPU and count tokens with the real tokenizer, write full Trainer checkpoints every few steps with a small save_total_limit, and add a callback that stops training and saves when a wall-clock budget is exceeded. Cost is estimated from measured tokens per second, not from a spec sheet.
The reason is asymmetry. Each of these steps costs minutes of CPU time or a few lines of code, while each failure it prevents costs paid GPU hours. The estimator below is a method demonstration, not a price forecast, because the throughput I measured is a CPU number.
Step by step
Install the stack
mkdir -p /work && cd /work && python3 -m venv venv && . venv/bin/activate && pip install -q torch --index-url https://download.pytorch.org/whl/cpu 2>&1 | tail -3; pip install -q transformers peft datasets accelerate 2>&1 | tail -3; pip list 2>/dev/null | grep -Ei '^(torch|transformers|peft|datasets|accelerate) '
accelerate 1.16.0
datasets 5.2.0
peft 0.22.0
torch 2.15.0+cpu
transformers 5.24.1
Size the 7B run without downloading it
I built the Qwen2.5-7B architecture on the meta device, which allocates no weight memory, wrapped it with PEFT LoRA on all seven projection types and counted parameters. The script prints weights at 2 bytes per parameter and the adapter plus gradients plus two Adam moments at 16 bytes per trainable parameter. This is arithmetic on parameter counts and excludes activations, which I did not measure. I show rank 16 only. The frozen weights dominate memory; the adapter is small, which is what makes frequent saves cheap.
cd /work && . venv/bin/activate && python count7b.py 2>&1 | grep -v Warning | tail -20
base params: 7615616512
r=16: trainable=40370176 (0.530% of base) adapter fp32 file ~154 MiB, bf16 ~77 MiB
weights bf16 14.2 GiB; adapter fp32 + grads + Adam m,v = 0.60 GiB
Prepare the data on the CPU
The script (my own, not reproduced here) loads databricks-dolly-15k, drops empty rows and duplicate prompts (instruction plus context, case-folded), renders each pair with the Qwen2.5 chat template, counts tokens with the 7B model's tokenizer, drops anything above 512 tokens, then shuffles with a fixed seed and splits off 500 validation rows.
cd /work && . venv/bin/activate && python prep.py 2>&1 | grep -v -i warn | tail -20; ls -la /work/*.jsonl; head -c 600 /work/data_train.jsonl
raw rows: 15011
kept: 13852 dropped: {'over_512_tokens': 959, 'duplicate_prompt': 200}
train 13352 rows 2008351 tokens, median 115 p95 384 max 512
Of 15,011 raw rows, 200 were duplicate prompts and 959 exceeded 512 tokens, so 1,159 rows were removed before any GPU would have seen them. The training split is 2,008,351 tokens per epoch, the number every later cost estimate multiplies.
Train with LoRA and frequent checkpoints
Training uses Qwen2.5-0.5B on CPU in fp32, because a 7B model is out of reach for this machine. My script applies LoRA with rank 16 and alpha 32 to all seven projection types, computes loss on assistant tokens only, uses batch size 4 and a learning rate of 2e-4, and sets save_steps=10 with save_total_limit=2. I started a 40-step run in the background; PEFT reported the trainable share below.
cd /work && . venv/bin/activate && rm -rf run1 && (nohup python train.py run1 40 > run1.log 2>&1 &) ; sleep 90; grep -v -i warn run1.log | tail -15; ls run1 2>&1
trainable params: 8,798,208 || all params: 502,830,976 || trainable%: 1.7497
What a checkpoint contains
Once the run had finished, I listed the two largest files of the last checkpoint. Their sizes decide what you must copy off a rented machine after each save, and how long that copy takes on a slow or metered link.
cd /work && ls -la run1/checkpoint-40 | grep -E 'adapter_model|optimizer'
-rw------- 1 root root 35237104 Nov 26 10:39 adapter_model.safetensors
-rw-r--r-- 1 root root 70658835 Nov 26 10:39 optimizer.pt
The optimizer file is about twice the size of the adapter. That matches Adam keeping two fp32 moments of four bytes for every trainable parameter, which I checked with a one-line calculation: two moments times four bytes times the 8,798,208 trainable parameters.
cd /work && . venv/bin/activate && python3 -c "print(2*4*8798208)"
70385664
By the same arithmetic, the rank-16 adapter on the 7B model would come with an optimizer file near 308 MiB. That is derived, not measured. These checkpoints also contain no tokenizer files, because I did not hand the Trainer a tokenizer, so save it once yourself.
Kill the process, then resume
To imitate a reclaimed instance I sent SIGKILL while the run was between checkpoints, which leaves the process no chance to save. I used a hard kill rather than a polite signal because a reclaimed instance rarely waits. Then I listed what survived and the last three loss lines.
cd /work && pkill -9 -f 'train.py run1'; sleep 1; pgrep -f 'train.py run1' || echo killed; ls run1; tr '\r' '\n' < run1.log | grep -o "{'loss'[^}]*}" | tail -3
killed
checkpoint-10
checkpoint-20
{'loss': '1.077', 'grad_norm': '5.074', 'learning_rate': '0.0001293', 'epoch': '0.19'}
{'loss': '2.579', 'grad_norm': '21.51', 'learning_rate': '0.0001211', 'epoch': '0.2'}
{'loss': '1.867', 'grad_norm': '2.429', 'learning_rate': '0.0001127', 'epoch': '0.21'}
The process had reached step 21, so the work after checkpoint-20 was lost: one step here, up to nine with a save interval of ten. I restarted the same script with a resume argument, which calls the Trainer with resume_from_checkpoint enabled.
cd /work && . venv/bin/activate && nohup python train.py run1 40 resume > run1_resume.log 2>&1 & sleep 150; cd /work; tr '\r' '\n' < run1_resume.log | grep -v -i warn | grep -E "loss|Resum|resum|trainable" | head; ls run1
trainable params: 8,798,208 || all params: 502,830,976 || trainable%: 1.7497
{'loss': '1.867', 'grad_norm': '2.429', 'learning_rate': '0.0001127', 'epoch': '0.21'}
checkpoint-20
checkpoint-30
The first logged line after the resume is identical to the line the killed process logged for step 21: same loss, same gradient norm, same learning rate. That is evidence that the resume restored the optimizer, scheduler and data order, not just the weights. The run then finished at step 40, and its 20 resumed steps took 211.5 seconds:
{'train_runtime': '211.5', 'train_samples_per_second': '0.378', 'train_steps_per_second': '0.095', 'train_loss': '2.201', 'epoch': '0.4'}
Check that the adapter actually helps
A saved adapter that does nothing is still a charge on the invoice, so I computed the mean loss on the assistant tokens of the first 64 held-out rows, for the bare base model and then with each saved adapter applied on top.
cd /work && . venv/bin/activate && python evalloss.py run1/checkpoint-30 run1/checkpoint-40 2>&1 | grep 'val loss'
base val loss: 2.5019
run1/checkpoint-30 val loss: 2.249
run1/checkpoint-40 val loss: 2.2471
Validation loss fell from 2.5019 to 2.2471 after 160 training examples. This is a small sample, a single seed and a tiny model, so read it only as proof that the checkpoint loads and moves the loss in the right direction, not as a quality result.
Put a hard budget in the training loop
I copied the training script and added a callback that, once the wall-clock budget set through an environment variable is exceeded, requests a save and stops training after the current step. Here are the lines I added, printed from the file.
cd /work && sed -n '28,34p' train_budget.py
class Budget(TrainerCallback):
def __init__(self, seconds): self.t0 = time.time(); self.s = seconds
def on_step_end(self, args, state, control, **kw):
if time.time() - self.t0 > self.s:
print(f"BUDGET HIT at step {state.global_step}: saving and stopping", flush=True)
control.should_save = True; control.should_training_stop = True
return control
I ran it on a fresh 40-step run with a 45-second budget; the sed at the end strips the progress-bar prefix. An earlier identical attempt stopped at step 6 and this one at step 5, so the stopping step varies with timing.
cd /work && . venv/bin/activate && rm -rf run2 && BUDGET_SECONDS=45 python train_budget.py run2 40 2>&1 | tr '\r' '\n' | grep -E 'BUDGET|train_runtime' | sed 's/.*it]//'; ls run2
BUDGET HIT at step 5: saving and stopping
{'train_runtime': '49.37', 'train_samples_per_second': '0.405', 'train_steps_per_second': '0.101', 'train_loss': '2.863', 'epoch': '0.05'}
checkpoint-5
The check runs at the end of a step, so the run overshoots the budget by up to one step: 49.4 seconds of reported runtime against 45 here. On a GPU a step is much shorter, so the overshoot shrinks, but leave a margin anyway.
Turn a measurement into a cost estimate
The estimator multiplies the real token count by epochs, divides by throughput and multiplies by an hourly price. I derived throughput from the resumed run: the mean token count of the 400 training rows I used, times the measured samples per second. It ignores padding, so it is rough.
cd /work && . venv/bin/activate && python3 -c "import json;r=[json.loads(l) for l in open('data_train.jsonl')][:400];print(sum(x['n_tokens'] for x in r)/400)"
158.485
cd /work && . venv/bin/activate && python3 -c "print(round(0.378*158.485,1))"
59.9
cd /work && . venv/bin/activate && python estimate.py 59.9 1.00 3
train tokens/epoch: 2008351 epochs: 3.0 measured tok/s: 59.9
estimated wall time: 27.94 h estimated cost at 1.0/h: 27.94
with 20% headroom for eval, checkpoints and restarts: 33.53
The price of 1.00 per hour is a placeholder I typed in, not a quote from any provider, and 59.9 tokens per second is what this four-core CPU did with a 0.5B model. Both are meaningless for a 7B model on a GPU. The method transfers: run a short pilot on the real hardware and feed in the real price.
Limits and alternatives
What worked
- Cleaning removed 1,159 of 15,011 rows and gave a measured token count.
- A hard kill cost only the steps since the last checkpoint, and the resume reproduced the interrupted step exactly.
- The wall-clock callback stopped the run and left a checkpoint.
What I did not verify
I never ran a 7B model, so I have no GPU throughput, no activation memory and no real price. QLoRA, bf16 mixed precision, gradient checkpointing, multi-GPU setups and syncing checkpoints to remote storage were not tested. Treat the 0.5B run as a test of the mechanics only.
When to choose another method
If a run takes minutes, skip the machinery and save at the end. If your instance may be preempted, sync each checkpoint directory off the box as soon as it appears. If memory, not time, is the limit, look at quantized base weights and gradient checkpointing, which I did not measure.