Fine-tune and evaluate with tasks¶
Prepares data on a CPU, fine-tunes Qwen/Qwen2.5-0.5B on an H100, evaluates on a GPU, and reports on a CPU. The steps pass files to each other through the task bucket, and project code goes to the jobs with local_libs. Runs as plain Python or as a Prefect flow.
View example files ↗ · Related reference: Tasks →
flowchart LR
prepare["prepare<br>CPU"] -- "train.jsonl in /ns" --> finetune["finetune<br>H100"]
finetune -- "adapter in /ns" --> evaluate["evaluate<br>H100"]
prepare -- "heldout.jsonl in /ns" --> evaluate
evaluate --> report["report<br>CPU"]
What this example does¶
| File | What it holds |
|---|---|
pipeline.py |
The tasks, the pipeline and the command line. |
lib/data.py |
prepare_wikitext: writes the training and held-out lines as JSON Lines files. |
lib/evaluation.py |
evaluate_adapter: perplexity before and after fine-tuning, and a few continuations. |
| Step | Kind | Machine | What it does |
|---|---|---|---|
prepare |
function from lib |
the smallest CPU machine | Writes train.jsonl (2,000 lines of wikitext-2's train split) and heldout.jsonl (200 lines of its validation split) to $NS_OUTPUT_DIR, and returns their paths. |
finetune |
bash script | H100 | Runs axolotl train on train.jsonl, read from the bucket mount, then copies the adapter to the run's folder. |
evaluate |
function from lib |
H100 | Perplexity on heldout.jsonl with the adapter turned off and on, and three continuations from the fine-tuned model. |
report |
function | the smallest CPU machine | Prints the metrics and returns them with the model's path. |
Files through /ns. Every task's job mounts the task bucket at /ns, so a path one task returns is opened by the next as it is. prepare returns /ns/…/train.jsonl, and the fine-tune's Axolotl config points at that path.
Project code with local_libs. prepare and evaluate are functions from the package lib. local_libs=["lib"] sends the package to their jobs, and the jobs import the functions by name. lib imports datasets, torch and the rest inside its functions, so pipeline.py loads without them.
Requirements¶
- A Nebius profile that can create jobs: see Install and authenticate.
- H100 quota in the project's region.
- Object Storage credentials to read the results:
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY, or a profile in~/.aws/credentials. - For
--mode prefect-local:pip install "nebius-serverless[prefect]", andPREFECT_API_URLset to the Prefect server's API address.
Runtime and compute¶
| Jobs | 4: prepare and report on CPU, finetune and evaluate on an H100, on-demand: the task default |
| Image | docker.io/axolotlai/axolotl:main-20260309-py3.11-cu128-2.9.1 for the first three; python:3.12-slim-bookworm for report |
| Disk | 500Gi for the GPU jobs |
| Timeout | 30m prepare, 2h fine-tune, 1h evaluate, 10m report |
Run it¶
From this folder, so that import lib finds the package:
python pipeline.py # plain Python on this machine
python pipeline.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:
rows: 2000 train, 200 held out
perplexity: … before, … after
- '…'
model: tasks/finetune/<time>/files/model/ in the task bucket
The task bucket is ns-workspace-<project id>, so the model's S3 address is s3://ns-workspace-<project id>/ followed by that path.
How to adapt it¶
- Use your own data: change
prepare_wikitextinlib/data.pyto write your lines. The fine-tune and the evaluation read whatever files it returns. - Train longer: raise
max_stepsinCONFIG. - Add a step: write a function in
lib, wrap it in anns.Taskwithlocal_libs=["lib"], and pass it a path an earlier step returned.
Troubleshooting¶
- Axolotl fails writing
debug.log. Keepoutput_dir: /workspace/outputon the job's disk: Axolotl appends to its log, which the bucket mount doesn't support. ModuleNotFoundError: No module named 'lib'on this machine. Runpipeline.pyfrom its folder.
Source¶
"""Fine-tune, then evaluate: a pipeline of tasks on CPU and GPU machines.
Each step runs on the machine it needs, and the steps pass files to
each other through the task bucket, which every task's job mounts at
``/ns``:
1. ``prepare``: writes the training and held-out lines, on a CPU job.
2. ``finetune``: QLoRA on ``Qwen/Qwen2.5-0.5B`` with Axolotl, on an
H100 job. It reads the training file ``prepare`` wrote.
3. ``evaluate``: perplexity on the held-out lines, before and after
fine-tuning, on a GPU job.
4. ``report``: the metrics and the model's path, on a CPU job.
``prepare`` and ``evaluate`` are functions from the local package
``lib``, sent to their jobs with ``local_libs=["lib"]``. Run it from
this folder, so that ``import lib`` finds it::
python pipeline.py # plain Python on this machine
python pipeline.py --mode prefect-local # a Prefect flow on this machine
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
from lib.data import prepare_wikitext
from lib.evaluation import evaluate_adapter
import nebius_serverless as ns
from nebius_serverless.integrations.prefect import PrefectFlow
EXPERIMENT = "finetune-eval"
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, without its dataset: the pipeline adds the file
# that ``prepare`` wrote. The output stays on the job's own disk: Axolotl
# appends to a log file there, which the bucket mount doesn't support.
CONFIG = {
"base_model": BASE_MODEL,
"load_in_4bit": True,
"adapter": "qlora",
"sequence_len": 128,
"micro_batch_size": 1,
"gradient_accumulation_steps": 1,
"learning_rate": 2e-4,
"max_steps": 30,
"val_set_size": 0,
"logging_steps": 5,
"output_dir": "/workspace/output",
"lora_r": 8,
"lora_alpha": 16,
"lora_dropout": 0.05,
"lora_target_modules": [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
],
}
# A function from the package ``lib``, on the smallest CPU machine. The
# Axolotl image has the ``datasets`` library it uses.
prepare = ns.Task(
prepare_wikitext,
name="prepare-data",
image=IMAGE,
local_libs=["lib"],
timeout="30m",
)
# A bash script on an H100. The config arrives as JSON text, which
# Axolotl reads as YAML. Training writes to the job's disk, then the
# script copies the adapter to the run's folder in the bucket.
finetune = ns.Task(
name="finetune",
image=IMAGE,
gpu="h100",
disk="500Gi",
timeout="2h",
inputs=["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"
outputs[model]="$NS_OUTPUT_DIR/model"
""",
)
# A function from ``lib`` on an H100.
evaluate = ns.Task(
evaluate_adapter,
name="evaluate",
image=IMAGE,
local_libs=["lib"],
gpu="h100",
disk="500Gi",
timeout="1h",
)
def summarize(
data: dict[str, object], scores: dict[str, object]
) -> dict[str, object]:
"""Print the metrics; return them with the model's path."""
base = scores["perplexity_base"]
tuned = scores["perplexity_tuned"]
print(f"rows: {data['train_rows']} train, {data['heldout_rows']} held out")
print(f"perplexity: {base} before, {tuned} after")
for sample in scores["samples"]:
print(f"- {sample['text']!r}")
return {
"model": scores["model"],
"perplexity": {"base": base, "tuned": tuned},
"train_rows": data["train_rows"],
"heldout_rows": data["heldout_rows"],
"samples": scores["samples"],
}
# A self-contained function on a public image and the smallest CPU machine.
report = ns.Task(
summarize,
name="report",
image="python:3.12-slim-bookworm",
timeout="10m",
)
def pipeline() -> dict[str, object]:
"""Prepare, fine-tune, evaluate and report; return the report.
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.
"""
data = prepare.submit(train_rows=2000, heldout_rows=200).result()
# Axolotl reads the training file from the bucket mount, where
# ``prepare`` wrote it.
trained = finetune.submit(
config={
**CONFIG,
"datasets": [
{
"path": data["train"],
"ds_type": "json",
"type": "completion",
"field": "text",
}
],
}
)
# Starts when the fine-tune has ended, with its result in its place.
scores = evaluate.submit(
trained=trained, base_model=BASE_MODEL, heldout=data["heldout"]
)
return report(data=data, scores=scores)
def main() -> None:
parser = argparse.ArgumentParser(
description="Fine-tune, then evaluate, 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":
result = 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}")
result = run.result()
# The jobs see the task bucket at /ns. Without that prefix, the path
# is the model's folder in the bucket, ns-workspace-<project id>.
folder = str(result["model"]).removeprefix("/ns/")
print(f"model: {folder}/ in the task bucket")
if __name__ == "__main__":
main()
lib/data.py
"""Prepare the dataset: training and held-out lines as JSON Lines files."""
import json
import os
from pathlib import Path
def prepare_wikitext(
train_rows: int = 2000, heldout_rows: int = 200
) -> dict[str, object]:
"""Write wikitext-2 lines for training and for evaluation.
Runs in a CPU job. Writes ``train.jsonl`` (from the train split) and
``heldout.jsonl`` (from the validation split) to ``$NS_OUTPUT_DIR``,
and returns their paths. Every task's job mounts the bucket at the
same path, so the next tasks open these paths as they are.
"""
from datasets import load_dataset
folder = Path(os.environ["NS_OUTPUT_DIR"])
data = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1")
result: dict[str, object] = {}
for name, split, rows in (
("train", "train", train_rows),
("heldout", "validation", heldout_rows),
):
lines = [text for text in data[split]["text"] if text.strip()][:rows]
path = folder / f"{name}.jsonl"
# One write per file: the bucket mount takes whole files.
path.write_text(
"".join(json.dumps({"text": line}) + "\n" for line in lines)
)
result[name] = str(path)
result[f"{name}_rows"] = len(lines)
return result
lib/evaluation.py
"""Evaluate a trained adapter against its base model."""
import json
import math
from pathlib import Path
def evaluate_adapter(
trained: dict[str, str],
base_model: str,
heldout: str,
samples: int = 3,
) -> dict[str, object]:
"""Perplexity on the held-out lines, before and after fine-tuning.
Runs in a GPU job. ``trained`` is what the fine-tune returned, and
``heldout`` the file ``prepare_wikitext`` wrote. Also returns a few
continuations from the fine-tuned model, to read next to the numbers.
"""
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
texts = [
json.loads(line)["text"]
for line in Path(heldout).read_text().splitlines()
]
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()
def mean_loss() -> float:
loss_sum, tokens = 0.0, 0
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
return loss_sum / tokens
with torch.no_grad():
with model.disable_adapter():
base = mean_loss()
tuned = mean_loss()
continuations = []
for text in texts[:samples]:
prompt = " ".join(text.split()[:8])
ids = tokenizer(prompt, return_tensors="pt").input_ids.to("cuda")
out = model.generate(
input_ids=ids, max_new_tokens=30, do_sample=False
)
continuations.append(
{"prompt": prompt, "text": tokenizer.decode(out[0])}
)
return {
"model": trained["model"],
"run": trained["run"],
"perplexity_base": round(math.exp(base), 2),
"perplexity_tuned": round(math.exp(tuned), 2),
"samples": continuations,
}