Skip to content

Fine-tuning sweep with tasks

Fine-tunes Qwen/Qwen2.5-0.5B with three Axolotl configs at once, measures each adapter's perplexity, and picks the best. Every step is an ns.Task, and the pipeline runs as plain Python or as a Prefect flow.

View example files ↗ · Related reference: Tasks →

flowchart LR
    t1["train lr-2e-4-r8<br>H100"] --> e1["evaluate<br>H100"]
    t2["train lr-1e-4-r16<br>H100"] --> e2["evaluate<br>H100"]
    t3["train lr-5e-5-r16<br>H100"] --> e3["evaluate<br>H100"]
    e1 & e2 & e3 --> pick["pick<br>CPU"]

What this example does

sweep.py holds the tasks, the pipeline and the command line. It is the Jobs version of the sweep as tasks, with an evaluation and a pick added:

Step Kind Machine What it does
train bash script H100, one per config Runs axolotl train with one config, then copies the adapter to the run's folder. Returns its name and the adapter's path.
evaluate function H100, one per adapter The adapter's perplexity on 200 lines of wikitext-2's validation split. Starts as soon as its training has ended.
pick function the smallest CPU machine Prints every run's perplexity and returns the best run with its config.

The configs are data in the script: BASE_CONFIG, and the learning rate and LoRA rank of each run in SWEEP. Each one reaches its job as an argument, so nothing is uploaded by hand. A path one task returns is opened by the next as it is: every task's job mounts the task bucket at /ns.

Requirements

  • A Nebius profile that can create jobs: see Install and authenticate.
  • Spot quota for three H100 jobs at the same time.
  • Object Storage credentials to read the results: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or a profile in ~/.aws/credentials.
  • For --mode prefect-local: pip install "nebius-serverless[prefect]", and PREFECT_API_URL set to the Prefect server's API address.

Runtime and compute

Jobs 3 training, 3 evaluation, 1 pick
Machine gpu="h100" for training and evaluation, on-demand: the task default. The pick runs on CPU
Image docker.io/axolotlai/axolotl:main-20260309-py3.11-cu128-2.9.1; the pick uses python:3.12-slim-bookworm
Disk 500Gi for the GPU jobs
Timeout 2h per training job, 1h per evaluation

Run it

From this folder:

python sweep.py                        # plain Python on this machine
python sweep.py --mode prefect-local   # a Prefect flow on this machine

Expected output

Each task prints its job id and states as it runs. At the end, the perplexity of each run, best first, then:

best: lr-1e-4-r16, perplexity …
config: {'name': 'lr-1e-4-r16', 'learning_rate': 0.0001, 'lora_r': 16}
adapter: tasks/axolotl-train/<time>/files/model/ in the task bucket

The task bucket is ns-workspace-<project id>, so the adapter's S3 address is s3://ns-workspace-<project id>/ followed by that path. In Prefect mode the link to the flow run comes first, and the runs' folders are under flows/axolotl-sweep/.

How to adapt it

  • Add a run: add an entry to SWEEP. Each entry is one training job and one evaluation job.
  • Change what every run shares in BASE_CONFIG, such as max_steps or the dataset.
  • Use another base model: change BASE_MODEL. The evaluation loads the same model under the adapter.

Troubleshooting

  • Axolotl fails writing debug.log. Keep output_dir: /workspace/output on the job's disk: Axolotl appends to its log, which the bucket mount doesn't support. train copies the output to the bucket when training ends.
  • A run waits in PROVISIONING. The project may not have capacity or quota for three H100s at once.

Source

sweep.py
"""A fine-tuning sweep as a pipeline of tasks: train, evaluate, pick.

The Axolotl fine-tune of ``examples/training/axolotl-sweep``, as tasks
instead of jobs, with an evaluation step and a pick at the end:

1. ``train``: a bash script that runs ``axolotl train`` with one config.
   One H100 job per config, all at the same time.
2. ``evaluate``: the perplexity of one trained adapter on wikitext-2's
   validation split, on a GPU job. Each one starts as soon as its
   training run has ended.
3. ``pick``: the config with the lowest perplexity, on a CPU job.

Run it from this folder::

    python sweep.py                        # plain Python on this machine
    python sweep.py --mode prefect-local   # a Prefect flow on this machine

It prints the best config and its adapter's folder in the task bucket.
Reading results needs Object Storage credentials: ``AWS_ACCESS_KEY_ID`` and
``AWS_SECRET_ACCESS_KEY``, or a profile in ``~/.aws/credentials``.
``prefect-local`` also needs ``pip install "nebius-serverless[prefect]"``
and ``PREFECT_API_URL``.
"""

import argparse
import os

import nebius_serverless as ns
from nebius_serverless.integrations.prefect import PrefectFlow

EXPERIMENT = "axolotl-sweep"
IMAGE = "docker.io/axolotlai/axolotl:main-20260309-py3.11-cu128-2.9.1"
BASE_MODEL = "Qwen/Qwen2.5-0.5B"
MODES = ("local", "prefect-local")

# The API address of the Prefect server, read from the environment so
# that no server address is kept in this file.
PREFECT_API_URL = os.environ.get("PREFECT_API_URL")

# The Axolotl config every run shares: QLoRA on 2,000 wikitext-2 lines
# for 30 steps. The output stays on the job's own disk: Axolotl appends
# to a log file there, which the bucket mount doesn't support. ``train``
# copies it to the run's folder when training ends.
BASE_CONFIG = {
    "base_model": BASE_MODEL,
    "load_in_4bit": True,
    "adapter": "qlora",
    "datasets": [
        {
            "path": "Salesforce/wikitext",
            "name": "wikitext-2-raw-v1",
            "split": "train[:2000]",
            "type": "completion",
            "field": "text",
        }
    ],
    "sequence_len": 128,
    "micro_batch_size": 1,
    "gradient_accumulation_steps": 1,
    "max_steps": 30,
    "val_set_size": 0,
    "logging_steps": 5,
    "output_dir": "/workspace/output",
    "lora_dropout": 0.05,
    "lora_target_modules": [
        "q_proj",
        "k_proj",
        "v_proj",
        "o_proj",
        "gate_proj",
        "up_proj",
        "down_proj",
    ],
}

# What each run changes. One H100 job per entry; ``lora_alpha`` is
# twice ``lora_r`` in each.
SWEEP = [
    {"name": "lr-2e-4-r8", "learning_rate": 2e-4, "lora_r": 8},
    {"name": "lr-1e-4-r16", "learning_rate": 1e-4, "lora_r": 16},
    {"name": "lr-5e-5-r16", "learning_rate": 5e-5, "lora_r": 16},
]

# A bash script. The config arrives as JSON text in ``inputs[config]``;
# JSON is also YAML, so Axolotl reads it as is. What the script sets in
# ``outputs`` comes back as a dict of strings.
train = ns.Task(
    name="axolotl-train",
    image=IMAGE,
    gpu="h100",
    disk="500Gi",
    timeout="2h",
    inputs=["name", "config"],
    command="""
    printf '%s\\n' "${inputs[config]}" > /workspace/config.yaml
    axolotl train /workspace/config.yaml
    mkdir -p "$NS_OUTPUT_DIR/model"
    cp -r /workspace/output/. "$NS_OUTPUT_DIR/model"
    cp /workspace/config.yaml "$NS_OUTPUT_DIR/config.yaml"
    outputs[name]="${inputs[name]}"
    outputs[model]="$NS_OUTPUT_DIR/model"
    """,
)


def perplexity(
    trained: dict[str, str], base_model: str, rows: int = 200
) -> dict[str, object]:
    """Perplexity of one adapter on wikitext-2's validation split.

    Runs in the job, so it imports there. ``trained`` is what ``train``
    returned. Lower is better.
    """
    import math

    import torch
    from datasets import load_dataset
    from peft import PeftModel
    from transformers import AutoModelForCausalLM, AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(base_model)
    model = AutoModelForCausalLM.from_pretrained(
        base_model, torch_dtype=torch.bfloat16
    ).to("cuda")
    model = PeftModel.from_pretrained(model, trained["model"]).eval()
    split = load_dataset(
        "Salesforce/wikitext", "wikitext-2-raw-v1", split="validation"
    )
    texts = [text for text in split["text"] if text.strip()][:rows]
    loss_sum, tokens = 0.0, 0
    with torch.no_grad():
        for text in texts:
            ids = tokenizer(
                text, return_tensors="pt", truncation=True, max_length=128
            ).input_ids.to("cuda")
            if ids.shape[1] < 2:
                continue
            loss = model(input_ids=ids, labels=ids).loss.item()
            loss_sum += loss * (ids.shape[1] - 1)
            tokens += ids.shape[1] - 1
    mean = loss_sum / tokens
    return {
        **trained,
        "eval_loss": round(mean, 4),
        "perplexity": round(math.exp(mean), 2),
    }


# On an H100.
evaluate = ns.Task(
    perplexity,
    name="evaluate",
    image=IMAGE,
    gpu="h100",
    disk="500Gi",
    timeout="1h",
)


def pick_best(
    scores: list[dict[str, object]], sweep: list[dict[str, object]]
) -> dict[str, object]:
    """Print each run's perplexity; return the best run and its config."""
    for score in sorted(scores, key=lambda score: score["perplexity"]):
        print(f"{score['name']}: perplexity {score['perplexity']}")
    best = min(scores, key=lambda score: score["perplexity"])
    config = next(run for run in sweep if run["name"] == best["name"])
    return {**best, "config": config}


# A self-contained function on a public image and the smallest CPU machine.
pick = ns.Task(
    pick_best,
    name="pick-best",
    image="python:3.12-slim-bookworm",
    timeout="10m",
)


def pipeline() -> dict[str, object]:
    """Train each config, evaluate each adapter, and return the best.

    With Prefect, this function's source is what runs as the flow. From
    outside its body it uses only tasks and constants with JSON values.
    """
    # One H100 job per config, all at the same time.
    training = [
        train.submit(
            name=run["name"],
            config={
                **BASE_CONFIG,
                "learning_rate": run["learning_rate"],
                "lora_r": run["lora_r"],
                "lora_alpha": 2 * run["lora_r"],
            },
        )
        for run in SWEEP
    ]

    # Each evaluation starts as soon as its training run has ended.
    scores = [
        evaluate.submit(trained=run, base_model=BASE_MODEL)
        for run in training
    ]

    return pick(scores=scores, sweep=SWEEP)


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Run the Axolotl sweep as a pipeline of tasks."
    )
    parser.add_argument(
        "--mode",
        choices=MODES,
        default="local",
        help=(
            "local: plain Python here; prefect-local: a Prefect flow "
            "here (default: %(default)s)"
        ),
    )
    mode = parser.parse_args().mode

    if mode == "local":
        best = pipeline()
    else:
        flow = PrefectFlow(
            pipeline,
            flow_name=EXPERIMENT,
            api_url=PREFECT_API_URL,
            remote_job=False,
        )
        run = flow.submit()
        if run.flow_run_url:
            print(f"Prefect: {run.flow_run_url}")
        best = run.result()

    # The jobs see the task bucket at /ns. Without that prefix, the path
    # is the adapter's folder in the bucket, ns-workspace-<project id>.
    folder = str(best["model"]).removeprefix("/ns/")
    print(f"best: {best['name']}, perplexity {best['perplexity']}")
    print(f"config: {best['config']}")
    print(f"adapter: {folder}/ in the task bucket")


if __name__ == "__main__":
    main()