Supervised fine-tuning (SFT)
Fine-tune an open model on examples of the exact outputs you want.
Use SFTRecipe when you have good examples of what the model should produce (code edits, structured JSON, SQL queries, or a specific style). Once it reliably follows your format, you can run Preference tuning (DPO) on top of the saved Artifact to improve it further.
What data you need#
- Minimum volume: 300–1,000 clean examples for focused tasks; 2,000+ for broader ones.
- Quality beats volume: don't train on raw, unfiltered logs. Score them with a
Judgeand keep only the high scorers, or filter on a score you already log such astests_passed. - Format: plain chat records, the same JSONL you'd send to OpenAI fine-tuning. The final assistant turn is what the model learns to write.
session_idis optional; add it when several records come from one conversation so they stay in the same split. Imported production logs work too (see Trajectories).
{
"messages": [
{
"role": "system",
"content": "Apply the edit snippet to the original file. Return only the merged file."
},
{ "role": "user", "content": "<original>...</original>\n<edit>...</edit>" },
{ "role": "assistant", "content": "export const retry = ..." }
]
}
Try it on a public dataset#
This runs as pasted. It imports 2,000 conversations from Hugging Face and trains with the defaults:
from grad import Grad
from grad.recipes import SFTRecipe
client = Grad()
chats = client.datasets.from_hf(
"HuggingFaceH4/ultrachat_200k",
split="train_sft",
messages="messages",
limit=2000,
)
run = client.runs.create(
dataset=chats,
name="ultrachat-sft",
recipe=SFTRecipe(model="qwen/qwen3-8b"),
).wait()
print(run.artifact.id)
To train on your own file instead, pass its path: client.datasets.push("my-sft", "train.jsonl") (or grad import ./train.jsonl --dataset my-sft). Add --dry-run to any grad train command to see the resolved defaults and a cost estimate first.
Train on your production logs#
Score your Dataset once with a Judge to keep only good examples, then train a LoRA adapter. The held-out eval split is grouped by session_id by default, so multi-turn conversations never leak into eval:
from grad import Grad, Judge
from grad.recipes import SFTRecipe
client = Grad()
dataset = client.datasets.get("diff-merge-prod") # pushed or imported earlier
# Score logs once with a Judge and keep only high-quality examples
judge = Judge(
name="clean_merge",
model="anthropic/claude-sonnet-5-5",
prompt="Did the assistant apply the edit accurately without breaking surrounding code?",
)
# Field filters run server-side, with no download
clean_dataset = dataset.score(judge).wait().filter(scores={"clean_merge": ">=0.8"})
sft = client.runs.create(
dataset=clean_dataset,
name="fast-diff-merge",
recipe=SFTRecipe(model="qwen/qwen3-8b"),
).wait(
on_metric=lambda m: print(f"step={m.step} loss={m.loss:.4f}"),
)
print(sft.artifact.id)
If your logs already include a deterministic score (like tests_passed from CI), skip dataset.score(judge) and filter directly: dataset.filter(scores={"tests_passed": "==1.0"}). A Python function works too (dataset.filter(lambda t: ...)); it runs on your machine once and saves the matching IDs as a view (see Score and filter datasets).
When to use SFT vs. DPO#
- Use SFT (
SFTRecipe) when you have verified examples of the exact outputs you want (or high-scoring production answers). - Follow with DPO (
DPORecipe) when the model already follows your format but keeps making specific mistakes you can contrast as(chosen, rejected)pairs. - Use distillation (
DistillRecipe) when you have prompts and a larger teacher model but no gold answers yet.
Parameters you might change#
adapter: LoRA (rank=32) by default. For large datasets (50,000+ records),adapters.LoRA(rank=64)or128can help.train_on: trains only the final assistant turn by default. Usetrain_on="all_assistant"for multi-turn agent traces.epochs: one pass by default. When a small dataset gives too few training steps, the dry run warns and suggests a smallerbatch_sizeor more epochs.
Every other setting has a default; see the training parameters reference. To see the exact tokens that get trained, run grad render <dataset> --model qwen/qwen3-8b (see chat templates).
Serve and call your model#
Download the trained Artifact and serve it on your own vLLM or SGLang server. The LoRA adapter loads onto the base model's Hugging Face weights (the default rank is 32, above vLLM's default --max-lora-rank of 16):
grad artifacts download fast-diff-merge@latest --output ./fast-diff-merge
vllm serve Qwen/Qwen3-8B \
--enable-lora \
--max-lora-rank 32 \
--lora-modules fast-diff-merge=./fast-diff-merge
Call it with any OpenAI-compatible client. For structured JSON, SQL, or code edits, check the output in a few lines of app code and retry on a larger model if the check fails:
from openai import OpenAI
oai = OpenAI(base_url="http://localhost:8000/v1", api_key="unused") # your vLLM server
messages = [
{"role": "system", "content": "Apply the edit snippet to the original file. Return only the merged file."},
{"role": "user", "content": "<original>export const retry = 1</original>\n<edit>export const retry = 3</edit>"},
]
def check_ts(code: str) -> bool:
# A cheap syntax check; use your real parser or CI here
return all(code.count(a) == code.count(b) for a, b in ("{}", "()", "[]"))
res = oai.chat.completions.create(model="fast-diff-merge", messages=messages)
code = res.choices[0].message.content
# Fall back in your own code if the fine-tuned model produces invalid syntax
if not check_ts(code):
res = oai.chat.completions.create(model="Qwen/Qwen3-8B", messages=messages) # or a larger model you serve
code = res.choices[0].message.content
See Deploying for SGLang and merged exports (adapters.LoRA(merge_on_export=True)).
Host it on Gradiated Cloud#
You'll publish it as a model version from the console or the Models API under your-org/fast-diff-merge, callable through the OpenAI SDK or Anthropic SDK with your GRADIATED_API_KEY:
import os
from openai import OpenAI
oai = OpenAI(base_url="https://api.gradiated.com/v1", api_key=os.environ["GRADIATED_API_KEY"])
res = oai.chat.completions.create(
model="your-org/fast-diff-merge",
messages=[{"role": "user", "content": "<original>export const retry = 1</original>\n<edit>export const retry = 3</edit>"}],
)
Want more control?#
Separate learning rates per layer (optim.ParamGroup) are coming soon with Custom loops.