Models
Fine-tune a model with Hugging Face
Decide when fine-tuning is worth it, prepare a dataset, train a LoRA adapter with TRL and PEFT, and serve it next to your AILabStore models.
9 min read · Updated November 1, 2026
Fine-tuning adapts a model with published weights to your task, style or domain. With Hugging Face's TRL and PEFT libraries, you can train a LoRA adapter for a 7B to 8B model on a single GPU in an hour or two. This guide walks through the full process and shows how to serve the result alongside the models you already use through AILabStore.
When should you fine-tune?
Try these first, in order. They are faster and cheaper:
- Better prompts with clear instructions and a few examples.
- RAG, when the model lacks knowledge rather than skill.
- A stronger model, by switching the
modelstring.
Fine-tune when you need:
- A consistent output format or tone across thousands of requests.
- Lower cost or latency, by teaching a small model to do what a large model does.
- Behaviour that is hard to describe in a prompt, learned from hundreds of examples.
- To run fully on your own infrastructure.
What you need
- A GPU with 24 GB of memory or more. A managed JupyterLab instance with a GPU (Enterprise) works well.
- A Hugging Face account and access token, and acceptance of the model licence for gated models such as Llama.
- 200 to 5,000 high-quality examples.
pip install -U transformers datasets peft trl accelerate bitsandbytes
huggingface-cli login
1. Prepare your dataset
TRL expects conversations in the chat "messages" format. Save one JSON object per line:
{"messages": [{"role": "system", "content": "You write product descriptions for an outdoor gear store."}, {"role": "user", "content": "Item: 2-person tent, 1.9 kg, 3-season"}, {"role": "assistant", "content": "Light enough for long trails and roomy enough for two..."}]}
Generate training data with a strong model
A practical shortcut is to have a frontier model produce high-quality examples, then review them. This is called distillation:
import os, json
from openai import OpenAI
client = OpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])
SYSTEM = "You write product descriptions for an outdoor gear store. 60-80 words, warm, concrete."
with open("items.txt") as f, open("train.jsonl", "w") as out:
for item in f:
r = client.chat.completions.create(
model="anthropic/claude-opus-5.5",
messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": item.strip()}],
)
out.write(json.dumps({"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": item.strip()},
{"role": "assistant", "content": r.choices[0].message.content},
]}) + "\n")
Check the provider's terms for any restrictions on using outputs to train other models, and review a sample by hand. Quality matters far more than quantity.
Hold back 10% of examples as an evaluation set.
2. Load the base model in 4-bit
QLoRA loads the base model in 4-bit precision to save memory and trains small adapter matrices on top:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
BASE = "meta-llama/Llama-3.1-8B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(
BASE,
quantization_config=BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
),
device_map="auto",
)
Other good base models include Qwen, Mistral, Gemma and Phi. See the Hugging Face directory for links.
3. Train with TRL and PEFT
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})
peft_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules="all-linear",
task_type="CAUSAL_LM",
)
args = SFTConfig(
output_dir="gear-writer-lora",
num_train_epochs=2,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.03,
logging_steps=10,
eval_strategy="steps",
eval_steps=50,
bf16=True,
)
trainer = SFTTrainer(
model=model,
args=args,
train_dataset=data["train"],
eval_dataset=data["eval"],
peft_config=peft_config,
processing_class=tokenizer,
)
trainer.train()
trainer.save_model("gear-writer-lora")
Watch the evaluation loss. If it starts rising while training loss keeps falling, you are overfitting: reduce epochs or add data.
For faster training on a single GPU, Unsloth offers optimised kernels; for config-driven multi-GPU runs, Axolotl is a popular choice. Both appear in our Libraries directory.
4. Evaluate against the base model
Compare outputs on your held-out set. A quick approach is to use a strong model as a judge:
JUDGE = """Compare two product descriptions for the same item.
Criteria: accuracy to the specs, 60-80 words, warm and concrete tone.
Reply with "A", "B" or "tie"."""
def judge(item, a, b):
r = client.chat.completions.create(
model="anthropic/claude-sonnet-5.5",
temperature=0,
messages=[{"role": "system", "content": JUDGE},
{"role": "user", "content": f"Item: {item}\n\nA:\n{a}\n\nB:\n{b}"}],
)
return r.choices[0].message.content.strip()
Randomise which output is A and B to avoid position bias, and spot-check verdicts yourself.
5. Share and serve the model
Push the adapter to the Hub (private by default is a good choice):
trainer.model.push_to_hub("your-org/gear-writer-lora", private=True)
tokenizer.push_to_hub("your-org/gear-writer-lora", private=True)
To serve it, Enterprise customers can deploy a managed vLLM instance on a dedicated GPU by choosing Request deployment for vLLM in Portal → Managed tools, pointing it at the base model with your LoRA adapter enabled. vLLM exposes an OpenAI-compatible endpoint, so your application code stays the same; only the base URL and model name change for that route:
tuned = OpenAI(base_url=os.environ["VLLM_ENDPOINT"], api_key=os.environ["VLLM_TOKEN"])
r = tuned.chat.completions.create(
model="gear-writer-lora",
messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": "Item: down sleeping bag, -5°C"}],
)
Keep your AILabStore models as a fallback for requests the fine-tuned model was not trained for.
Tips
- Start with a small LoRA rank (8 to 16) and two epochs.
- Keep the same system prompt in training and production.
- Version datasets and adapters together, and track runs with managed MLflow.
- Re-evaluate whenever you change the base model.