Advanced objectives
Custom PyTorch losses and specialized training patterns built on Trainer and
losses.CustomLoss.
Start with the Recipe guides whenever a built-in recipe fits your task. Use the patterns on this page (together with Custom loops) when you need custom PyTorch loss math, async off-policy RL, specialized model heads, uncommon adapters, or closed-form solvers.
RL algorithm cookbook#
GRPORecipe picks the loss for you with loss="auto" (the default): losses.GRPO(clip_low=0.2, clip_high=0.28) when rollouts are on-policy, and the same clipped loss with mask_ratio=(0.5, 2.0) when you allow stale rollouts with max_staleness > 0. The mask drops tokens whose probability under the current weights has moved more than 2× from the sampler's, which is what keeps stale rollouts from destabilizing training. Every run records the loss auto resolved to and the rule version (auto@1) in its config, so a later change to the rule never silently changes a rerun. Pass loss= to a recipe, or to trainer.forward_backward(...) in a custom loop, to use any variant below. All of them share the same rollout_groups() and forward_backward(batch, loss=...) loop; only the AdvantageEstimator or the loss changes:
| Method | When to use it | How to run it |
|---|---|---|
| GRPO | Default synchronous RL against verifiable rubrics. | grad.with_advantages(groups, advantage=advantages.GroupStd()) + losses.GRPO(clip_low=0.2, clip_high=0.28) |
| Dr. GRPO | Remove std-division and length bias in reasoning RL. | grad.with_advantages(groups, advantage=advantages.GroupMean()) + constant-denominator CustomLoss |
| DAPO | Long reasoning or multi-turn coding where entropy collapses. | losses.GRPO(clip_low=0.2, clip_high=0.28) + skip_zero_var=True + length penalty in Rubric (the GRPO default already uses DAPO's higher upper clip) |
| Async GRPO | Rollout pools where container workers finish 1–4 weight versions behind the trainer. | losses.GRPO(clip_low=0.2, clip_high=0.28, mask_ratio=(0.5, 2.0)); chosen automatically when max_staleness > 0 |
| CISPO | Experiments only. Unclipped updates on clipped importance weights can be unstable on stale rollouts, so auto never picks it and runs.plan() warns when you combine it with max_staleness > 0. | losses.CISPO(clip_low=0.2, clip_high=0.28) |
| PPO + Critic | Dense per-token value baselines with GAE when group sampling is too expensive. | Attach heads={"v": heads.Linear(dim=1, token_level=True)} + PPOGAELoss(CustomLoss) |
| RLOO | Small group sizes (group_size=4) where std-normalization is noisy. | grad.with_advantages(groups, advantage=advantages.RLOO()) + losses.ImportanceSampling(kl_coef=0.02) |
| REINFORCE++ | Global batch stability with per-token KL shaping against a frozen reference. | Score ref.score_logprobs(trajs).aligned_logprobs, whiten active tokens, attach via with_targets() |
| GSPO | MoE models or long multi-turn trajectories where token-level importance ratios diverge. | Sequence-level geometric mean ratio via GSPOLoss(CustomLoss) |
The async tab is a complete loop. The other tabs define a loss class; use it by passing loss= in the GRPO loop from Custom loops, or GRPORecipe(loss=...).
The managed version is one argument: GRPORecipe(model="qwen/qwen3-8b", env=env, max_staleness=2) overlaps rollouts with training and switches to the masked loss on its own. Stale rollouts are kept rather than thrown away: discarding them biases training toward the problems that finish fastest, which are usually the easy ones. Metrics report staleness_mean and staleness_max per step. The hand-written version:
import itertools
from concurrent.futures import ThreadPoolExecutor
import grad
from grad import Grad, Rubric, Scorer, advantages, environments, losses, optim, validators
client = Grad()
tasks = client.datasets.from_hf(
"openai/gsm8k", subset="main", split="train", prompt="question", answer="answer"
)
# With no tools, environments.Tools is a single-turn prompt -> answer environment.
env = environments.Tools(
[], tasks=tasks, rubric=Rubric([Scorer("correct", fn=validators.NumericMatch(field="answer"))])
)
batches = list(itertools.islice(tasks.batches(32), 100))
with client.trainers.create(model="qwen/qwen3-8b") as trainer, \
ThreadPoolExecutor(max_workers=1) as pool:
# Overlap rollouts for step N+1 with training on step N; rollouts lag the weights by one step.
rollout = lambda b: env.rollout_groups(artifact=trainer.snapshot(), tasks=b, group_size=8)
next_rollouts = pool.submit(rollout, batches[0])
for step in range(len(batches)):
groups = next_rollouts.result()
if step + 1 < len(batches):
next_rollouts = pool.submit(rollout, batches[step + 1])
batch = grad.with_advantages(groups, advantage=advantages.GroupStd(), skip_zero_var=True)
fb = trainer.forward_backward(batch, loss=losses.GRPO(clip_low=0.2, clip_high=0.28, mask_ratio=(0.5, 2.0)))
trainer.optim_step(optim.AdamW(lr=5e-5))
print(f"step={step} kl_sample_train={fb.result().metrics['kl_sample_train']:.4f}")
Custom distillation divergences & SDFT#
Jensen-Shannon / Skew KL (gather_indices)#
Fetch top_k opaque TensorRefs from the teacher and pass gather_indices=t_refs to trainer.forward_backward(...). Only (T_resp, 32) student logprobs cross the wire, and out.teacher_topk_logprobs is automatically batch-fetched in a single RPC:
import torch
from grad import Grad, losses, optim
class JSDLoss(losses.CustomLoss):
outputs = ("topk_logprobs",)
def __init__(self, beta: float = 0.5):
self.beta = beta
def compute(self, records, out) -> torch.Tensor:
terms = []
for slp, tlp in zip(out.topk_logprobs, out.teacher_topk_logprobs):
pt, ps = torch.softmax(tlp, dim=-1), torch.softmax(slp, dim=-1)
m = self.beta * pt + (1.0 - self.beta) * ps
kl_t = (pt * (torch.log(pt + 1e-9) - torch.log(m + 1e-9))).sum(-1)
kl_s = (ps * (torch.log(ps + 1e-9) - torch.log(m + 1e-9))).sum(-1)
terms.append((self.beta * kl_t + (1.0 - self.beta) * kl_s).mean())
return torch.stack(terms).mean()
client = Grad()
teacher = client.models.get("qwen/qwen3-32b")
prompt_inputs = [
[{"role": "user", "content": "Explain what a race condition is in two sentences."}],
[{"role": "user", "content": "Write a SQL query that returns the 5 newest orders."}],
]
with client.trainers.create(model="qwen/qwen3-4b") as trainer:
for step in range(20):
# On-policy: the student samples, the teacher scores the student's own tokens.
rollouts = [g[0] for g in trainer.snapshot().sample(prompt_inputs, n=1, max_new_tokens=256)]
t_refs = teacher.score_logprobs(rollouts, top_k=32).topk_refs
batch = [r.with_targets(teacher_topk=ref) for r, ref in zip(rollouts, t_refs)]
fb = trainer.forward_backward(batch, loss=JSDLoss(beta=0.5), gather_indices=t_refs)
trainer.optim_step(optim.AdamW(lr=2e-4))
print(f"step={step} jsd={fb.result().loss:.4f}")
Self-Distillation Fine-Tuning (SDFT)#
In SDFT, the same base model acts as teacher when shown the question plus a golden demonstration in context, while the student sees only the question. That lets you teach new skills without the model forgetting what it already knows:
from grad import Grad, losses, optim
client = Grad()
teacher = client.models.get("qwen/qwen3-8b") # frozen base model, no extra deployment
demos = [
("How do I rotate an API key without downtime?",
"Create the new key, deploy it alongside the old one, switch traffic, then revoke the old key."),
]
question_inputs = [[{"role": "user", "content": q}] for q, _ in demos]
# The teacher sees the question plus a worked demonstration in context.
demo_prefixes = [
teacher.tokenize(messages=[{"role": "user", "content": f"{q}\n\nExample of a good answer: {demo}"}])
for q, demo in demos
]
with client.trainers.create(model=teacher) as trainer:
for step in range(50):
rollouts = [g[0] for g in trainer.snapshot().sample(question_inputs, n=1, max_new_tokens=512)]
t_refs = teacher.score_logprobs(
demo_prefixes,
response_tokens=[r.response_tokens for r in rollouts],
top_k=20,
).topk_refs
records = [r.with_targets(teacher_topk=ref) for r, ref in zip(rollouts, t_refs)]
trainer.forward_backward(records, loss=losses.TopKKLDistill(top_k=20))
trainer.optim_step(optim.AdamW(lr=1e-4)).result()
Custom reward models & step-level PRMs#
import torch
import torch.nn.functional as F
import grad
from grad import Grad, PreferencePair, heads, losses, optim
class BradleyTerryLoss(losses.CustomLoss):
outputs = ("heads",)
def compute(self, records, out) -> torch.Tensor:
terms = [
-F.logsigmoid(g["chosen"].heads["rm"][0] - g["rejected"].heads["rm"][0])
for g in grad.by_group(records, out)
]
return torch.stack(terms).mean()
client = Grad()
pairs = [
PreferencePair(
prompt=[{"role": "user", "content": "Count orders placed today."}],
chosen="SELECT count(*) FROM orders WHERE created_at >= current_date;",
rejected="SELECT * FROM orders;",
),
]
with client.trainers.create(
model="qwen/qwen3-8b",
heads={"rm": heads.Linear(dim=1)},
) as trainer:
for epoch in range(3):
fb = trainer.forward_backward(pairs, loss=BradleyTerryLoss())
trainer.optim_step(optim.AdamW(lr=1e-4))
print(f"bt_loss={fb.result().loss:.4f}")
rm_artifact = trainer.export(name="sql-verifier")
Multi-vector embeddings (ColBERT + Matryoshka) & cross-encoder rerankers#
import torch
import torch.nn.functional as F
import grad
from grad import losses
# Set pool=pooling.PerToken() on trainers.create() to receive per-token (L, D) embeddings.
class MatryoshkaColBERTLoss(losses.CustomLoss):
outputs = ("embeddings",)
def __init__(self, dims: tuple[int, ...] = (128, 256, 384)):
self.dims = dims
def compute(self, records, out) -> torch.Tensor:
terms = []
for g in grad.by_group(records, out):
q_tok, p_tok, n_tok = g["anchor"].embeddings, g["positive"].embeddings, g["negative"].embeddings
qm, pm, nm = q_tok.mean(0), p_tok.mean(0), n_tok.mean(0)
mrl = sum(
F.cross_entropy(
torch.stack([
F.normalize(qm[:d], dim=-1) @ F.normalize(pm[:d], dim=-1),
F.normalize(qm[:d], dim=-1) @ F.normalize(nm[:d], dim=-1),
]).unsqueeze(0) / 0.05,
torch.tensor([0]),
)
for d in self.dims
) / len(self.dims)
qc, pc, nc = F.normalize(q_tok, dim=-1), F.normalize(p_tok, dim=-1), F.normalize(n_tok, dim=-1)
colbert = F.cross_entropy(
torch.stack([(qc @ pc.T).max(-1).values.sum(), (qc @ nc.T).max(-1).values.sum()]).unsqueeze(0) / 0.1,
torch.tensor([0]),
)
terms.append(mrl + colbert)
return torch.stack(terms).mean()
Dynamic per-request choices (candidate_tokens)#
When your choice set varies per request (for example, ranking dynamic tools or zero-shot multiple-choice decisions with an LLM), score or fine-tune directly on those specific candidate_tokens without fetching full vocabulary logits:
import torch
from grad import Grad, Record, losses, optim
client = Grad()
base = client.models.get("qwen/qwen3-8b")
prompt_messages = [
{"role": "user", "content": "Which tool fits 'refund order 4417'? A) search_kb B) issue_refund C) escalate. Answer with one letter."},
]
choice_ids = [base.tokenize(c)[-1] for c in ["A", "B", "C"]]
scored = base.score_logprobs(
[base.tokenize(messages=prompt_messages)],
candidate_tokens=choice_ids,
)
probs = torch.softmax(torch.tensor([scored.candidate_logprobs[0][t] for t in choice_ids]), dim=-1)
class BrierLoss(losses.CustomLoss):
outputs = ("topk_logprobs",)
def compute(self, records, out) -> torch.Tensor:
terms = []
for lp, rec in zip(out.topk_logprobs, records):
p = torch.softmax(lp[-1], dim=-1)
target = torch.tensor(rec.metadata["target_probs"])
terms.append(((p - target) ** 2).sum())
return torch.stack(terms).mean()
decision_records = [
Record(messages=prompt_messages, metadata={"target_probs": [0.05, 0.9, 0.05]}),
]
with client.trainers.create(model="qwen/qwen3-8b") as trainer:
fb = trainer.forward_backward(decision_records, loss=BrierLoss(), gather_indices=choice_ids)
trainer.optim_step(optim.AdamW(lr=5e-5))
print(f"before={probs.tolist()} brier={fb.result().loss:.4f}")
Advanced adapters#
adapters.LoRA(rank=32) (the default) covers almost every task. Reach for these only when you have a specific reason:
| Class | What gets trained | When to use it |
|---|---|---|
adapters.DoRA(rank=32, alpha=32) | Weight-decomposed LoRA (magnitude + direction). | Small accuracy gains over LoRA at the same rank, at somewhat higher step cost. |
adapters.QLoRA(rank=32) | 4-bit NF4 quantized backbone + LoRA adapters. | Self-hosted training on GPUs too small for a 16-bit backbone. On Gradiated Cloud, plain LoRA is faster and costs the same per token. |
adapters.PrefixKV(num_tokens=256) | Backbone frozen; trains only prepended KV prefix tokens. | Compressing a large fixed document into a Cartridge. CartridgeRecipe sets this up for you. |
adapters.LoReFT(layers=[8, 16, 24], rank=4) | Backbone frozen; trains orthogonal low-rank residual-stream interventions. | Very small behavioural edits with a tiny parameter budget. |
adapters.Eagle3Draft(fusion_layers=[2, 18, 34]) | Frozen target trunk + multi-layer speculative draft fusion head. | Training a speculative-decoding draft head to make a deployed model faster. |
adapters.PartialUnfreeze(last_n_layers=1) | Top N transformer layers + ln_f + trainable heads. | Classifier or reward heads that need a little more capacity than FrozenHead(). |
Every adapter takes the same client.trainers.create(model=..., adapter=...) call and works with every loss on this page.
Advanced solvers#
Routers, linear probes, and representation steering vectors do not need SGD. Extract embeddings once with embed() and solve in a single trainer.fit_batch() call with a typed Solver. solvers.DualHeadKernelLBFGS fits a quality head and a cost head together, which is what RouterRecipe uses under the hood:
from grad import Grad, Record, adapters, pooling, solvers
client = Grad()
encoder = client.models.get("baai/bge-small-en-v1.5")
# One row per (request, candidate model): how well that model did on that request.
inputs = [
"Summarize this support ticket in one line.",
"Summarize this support ticket in one line.",
"Prove that the sum of two even numbers is even.",
"Prove that the sum of two even numbers is even.",
]
model_ids = ["qwen/qwen3-0.6b", "qwen/qwen3-32b", "qwen/qwen3-0.6b", "qwen/qwen3-32b"]
labels = [0.9, 0.95, 0.2, 0.9]
embeddings = encoder.embed(inputs, pool=pooling.Mean()).embeddings
embedding_records = [
Record(embedding=emb.tolist(), scalar=label, metadata={"action_id": model_id})
for emb, label, model_id in zip(embeddings, labels, model_ids)
]
with client.trainers.create(model=encoder, adapter=adapters.FrozenHead()) as trainer:
trainer.fit_batch(embedding_records, solver=solvers.DualHeadKernelLBFGS(l2=0.1))
router_artifact = trainer.export(name="support-router")