# Fine-tune a small model

Fine-tuning teaches an existing model your own examples. Here you train a small **LoRA adapter**: a few megabytes of extra weights on top of a 0.5-billion-parameter model. The example data is tiny so the run takes minutes. It shows the whole workflow; replace the examples with your own data for real work.

## 1. Deploy the Fine-tuning starter

1. Open **Deploy**. This template needs 24 GB of GPU memory, so pick a GPU with **VRAM** of 24 GB or more. Sort by **Price, low to high** to find the cheapest one. Select **Continue**.
2. Above the template cards, select the **Training** filter. Select the **Fine-tuning starter** card, then **Continue**.
3. Name the server `finetune-test`, keep the disk size (the template suggests 150 GB) and optionally select an SSH key.
4. Check **Per hour** on the review step and select **Start my server**.

The template starts JupyterLab with PyTorch, `transformers`, `peft` and `datasets`. The first start installs these tools, so JupyterLab can take several minutes to answer after the status shows **Running**. Later starts are quick.

## 2. Open JupyterLab and check the tools

Open the server, select the **Connect** tab and **Open Jupyter**. Under **Notebook** select **Python 3 (ipykernel)** and run:

```python
import torch, transformers, peft
print(torch.cuda.get_device_name(0), transformers.__version__, peft.__version__)
```

If an import fails, run `!ls /workspace/.finetune-deps`. That file appears when the installation has finished. If it is missing, wait a few minutes and try again.

## 3. Train

Paste this into a new cell and run it. It downloads the model (about 1 GB), adds a LoRA adapter and trains for three passes over four examples.

```python
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer

name = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name).to("cuda")
model = get_peft_model(
    model,
    LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM"),
)
model.print_trainable_parameters()

pairs = [
    ("How do I stop paying for compute?", "Stop the server."),
    ("How do I stop all charges?", "Destroy the server."),
    ("Is the disk billed while stopped?", "Yes, until you destroy the server."),
    ("Where do I see the price?", "On the review step before you request a server."),
]
texts = [f"Question: {q}\nAnswer: {a}{tok.eos_token}" for q, a in pairs]

opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=2e-4)
model.train()
for epoch in range(3):
    for text in texts:
        batch = tok(text, return_tensors="pt").to("cuda")
        loss = model(**batch, labels=batch["input_ids"]).loss
        loss.backward()
        opt.step()
        opt.zero_grad()
    print(f"pass {epoch + 1}: loss {loss.item():.3f}")

model.save_pretrained("/workspace/lora-out")
```

You should see the number of trainable parameters (a small fraction of one percent) and one `loss` line per pass. The loss usually falls from pass to pass; your exact numbers will differ. The adapter is saved on the server's disk.

## 4. Try the result

```python
model.eval()
ids = tok("Question: How do I stop all charges?\nAnswer:", return_tensors="pt").to("cuda")
out = model.generate(**ids, max_new_tokens=20, do_sample=False)
print(tok.decode(out[0], skip_special_tokens=True))
!ls -lh /workspace/lora-out
```

The listing shows `adapter_config.json` and `adapter_model.safetensors`. To use the adapter later, load the base model and add it with `PeftModel.from_pretrained(base_model, "/workspace/lora-out")`.

## 5. Keep the adapter

Open the `lora-out` folder in the file browser, right-click each file and choose **Download**. Or copy the folder from your own computer, with `PORT` and `HOST` from the **Connect** tab:

```bash
scp -P PORT -r root@HOST:/workspace/lora-out ./
```

This needs an SSH key on the server. See [Moving files](/docs/moving-files).

## Costs and limits

A 24 GB GPU costs more than the small ones. The price on the card in **Deploy** is the live price, per hour, billed by the second. This run needs only a few minutes of GPU time, so stop the server as soon as you are done. A bigger model needs more memory; see the [GPU memory guide](/docs/gpu-memory-guide). If training stops with an out-of-memory error, see [Troubleshooting](/docs/troubleshooting).

## When you are done: stop or delete

- **Stop** ends the compute charge and keeps the disk, with the model download and your adapter. The disk is still charged.
- **Destroy** ends every charge and deletes the disk. Download the adapter first. See [Start, stop and restart](/docs/start-stop-restart).

## Next

- [Serve a model as an API](/docs/tutorial-model-api)
- [Save money](/docs/tutorial-save-money)
