Train Your Own AI

Stop Wasting GPU Money: LoRA Hyperparameter Sweeps That Fit One Rental

FlopSource Research

You have rented a 4090-class GPU, you have a dataset, and one question stands between you and a good fine-tune: which learning rate, and which rank? Most people answer it the expensive way, running six settings as six full three-epoch trainings while five of them teach nothing a twenty-minute screening run could not have. This is the companion tutorial to Train Your Own AI, Episode 9: a hyperparameter sweep built as a screening round that costs less than one full run, followed by a single full run on the winner. No headline hourly GPU price is quoted here because rental prices move daily; check the directory for today's.

The three knobs that matter

A LoRA run has a dozen settings you could twiddle, and nine of them are a waste of your rental. Three knobs decide nearly everything:

Everything else stays locked during a sweep: batch size, the cosine schedule, warmup, and the seven target modules from Episode 1. And lora_alpha does not get swept either: set it equal to rank and leave it alone, because sweeping alpha separately is sweeping the same knob twice.

The sweep grid: six runs, one script

The grid is three learning rates times two ranks: six configurations, and six is the whole sweep. Rank 8 at the low and high rates, rank 16 at all three rates, and rank 32 at the middle rate. That covers the corners and the center without burning the rental on combinations nobody would pick.

One script runs all six: a loop over the config list, each pass building a fresh adapter with FastLanguageModel.get_peft_model, r and lora_alpha set from the config, same base model, same dataset, same chat template, same seed (3407), so the only thing changing between runs is the knob under test. Each run saves to its own folder, so nothing overwrites anything and every result stays comparable.

# One script, six configs. Same base, same data, same seed.
# Only the knob under test changes.
configs = [
    {"r": 8,  "lr": 5e-5},
    {"r": 8,  "lr": 2e-4},
    {"r": 16, "lr": 5e-5},
    {"r": 16, "lr": 1e-4},
    {"r": 16, "lr": 2e-4},
    {"r": 32, "lr": 1e-4},
]
for cfg in configs:
    model = FastLanguageModel.get_peft_model(
        model, r = cfg["r"], lora_alpha = cfg["r"],
        target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                          "gate_proj", "up_proj", "down_proj"],
        lora_dropout = 0, bias = "none",
        use_gradient_checkpointing = "unsloth",
        random_state = 3407,
    )
    # train, then score on the FROZEN held-out set (Ep 7)
    # judge = eval score per slice, never training loss

The crucial piece is the judge. You do not pick the winner by training loss. Training loss falls when a model memorizes, and a sweep judged on training loss picks the most overfit adapter in the room. The judge is the frozen held-out set from Episode 7: the same prompts, the same pass bar, scored per slice. Build the scoring into the loop, and the script prints a table at the end, one row per config, one score per slice, and the winner is obvious.

Screen cheap: one epoch on a quarter of the data

Six full trainings would still be expensive, so the screening round cheats in your favor. Each config trains for one epoch on a random 25% slice of the training data, then gets scored on the frozen held-out set. One epoch on a quarter of the data is roughly an eighth of a full three-epoch run, so all six screening runs together cost less than one full training.

That is the whole trick: you are not buying six adapters, you are buying six measurements. The ranking from a short screening run is not perfect, but it is reliable enough to kill the losers. The config whose loss explodes in the first hundred steps is dead whatever the dataset size. The config that barely moves the eval score after a full epoch on a quarter of the data will not wake up on the rest of it. Keep the top two, throw the rest away, and spend the real GPU time only where the evidence points. If two configs tie, pick the cheaper one: lower rank, lower rate, the adapter that trains faster and serves lighter.

One rule from Episode 8 still applies: the screening slice comes from training data only. The frozen held-out set never trains anything, it only judges.

Early stopping: let the trainer quit for you

Even the winning config should not run blind to the end. Wire early stopping into the trainer, so the run quits itself the moment the eval stops improving, instead of burning your rental on epochs that only memorize. In TRL, the SFTConfig carries the wiring: eval_strategy="steps" with eval_steps=50, so the trainer scores the held-out slice every fifty optimizer steps, and load_best_model_at_end=True, so the checkpoint you keep is the best one it saw, not the last one. Then add the transformers EarlyStoppingCallback with a patience of 2: two evals in a row with no improvement, and training stops, the best checkpoint is restored, and the GPU goes quiet.

from transformers import EarlyStoppingCallback
from trl import SFTTrainer, SFTConfig

args = SFTConfig(
    output_dir = "sweep/r16-lr1e-4",
    num_train_epochs = 3,              # ceiling, not a promise
    per_device_train_batch_size = 2,
    gradient_accumulation_steps = 4,
    learning_rate = 1e-4,
    lr_scheduler_type = "cosine",
    warmup_steps = 10,
    eval_strategy = "steps",           # score during training
    eval_steps = 50,
    load_best_model_at_end = True,     # keep the best, not the last
)
trainer = SFTTrainer(
    model = model,
    train_dataset = train_data,
    eval_dataset = heldout_slice,      # real eval set, never train loss
    args = args,
    callbacks = [EarlyStoppingCallback(early_stopping_patience = 2)],
)

This is the same mechanism Episode 7's harness was built to feed. A good config stops after two epochs instead of three, a bad config dies after one, and the savings land on every run you ever do after this episode. One warning: early stopping needs a real eval set to watch. If you point it at training loss, it will happily stop at the worst possible moment, because training loss keeps falling long after the model has stopped learning anything useful.

The cost math: price per experiment

Cost per experiment is just hours times the hourly rate of the box, and both numbers are yours to control. Hours come from the screening design: a one-epoch run on a quarter of the data is a fraction of a full run, and early stopping cuts the winner's run short too. The hourly rate comes from the directory, and it moves daily, which is why this tutorial quotes no price: check the directory for today's cheapest 4090-class box before you rent, because yesterday's bargain is today's overpay.

What you can budget in advance is the shape of the spend. Six screening runs at roughly an eighth of a full run each is three quarters of one full run, total. Then one full confirmation run on the winner, with early stopping, usually lands between one and two epochs of compute. The whole sweep, search and confirmation together, costs about 1.5 to 2 full trainings, and it hands you an adapter chosen by evidence instead of by guessing. Compare that with the naive version: six full trainings, six times the spend, five adapters you throw away. The sweep is not a luxury, it is the discount.

Read the results: what the sweep is telling you

When the table prints, read it like a diagnostic, not a leaderboard. Three patterns cover almost every sweep:

  1. High learning rate collapses: loss spikes early, the format slice craters, the model answers in fragments. That is not a close call; that rate is too hot for this task and this data. Cross it out.
  2. Rank 8 trails everywhere, even at the best rate: the adapter is too small to hold the behavior, and no learning rate fixes capacity. Rank 16 or 32 is the floor.
  3. The middle of the grid wins, and the neighbors are close: rank 16 at 1e-4 beats rank 16 at 5e-5 by a point or two, and rank 32 is no better than 16. The task is solved at rank 16, and the extra capacity buys nothing.

Take the winner, run the full confirmation training on the complete dataset with early stopping, and score it on the full frozen held-out set from Episode 7, per slice. If the confirmation matches the screening, ship it. If it does not, the screening slice was too small or too easy, and the fix is a bigger screening slice next time, not a bigger grid.

Recap

A sweep is a screening round, not six full trainings. Three knobs matter: learning rate at 5e-5, 1e-4, or 2e-4; rank at 8, 16, or 32; and epochs, 1-3, with more meaning memorization, not learning. Lock everything else, set alpha equal to rank, and run a grid of six configs in one script with the same seed, judged only by the frozen held-out set from Episode 7, never by training loss. Screen cheap: one epoch on a quarter of the data per config, keep the top two, and let early stopping with a patience of two quit the winner's run the moment the eval stops improving. The whole search costs about 1.5 to 2 full trainings instead of six, and the cost per experiment is hours times today's rate, so check the FlopSource directory before you rent, because prices move daily. That is the series so far: train in Episode 1, prove it in 7, fix it in 8, and now search it without burning the rental. Next up: serving your fine-tune as an API your app can call.

Find the cheapest GPU for your next run

Live pricing, hardware specs, and availability across 30 GPU clouds, neoclouds, and bare-metal providers.

Open the Directory