Train the same GRPO loss-aggregation arms as LoRA adapters and at full weight, one durable action per arm, and check whether the two rankings agree.
Can a LoRA screen pick the right RL ablation?
An RL ablation table is expensive when every row is a full-weight run. A cheaper screen, such as LoRA arms on a small model, is only useful if it ranks the rows the same way the full-weight runs do. This tutorial runs that check for one ablation: how the GRPO policy loss is averaged over a batch.
token_meanpools every token in the batch, so long completions carry more of the gradient.sequence_meanweights every completion equally, whatever its length (original GRPO).prompt_meanweights every prompt group equally and pools tokens within a group (DAPO-style).
Mercor’s 397B SkyRL guide picked prompt_mean from 13 full-weight ablations on a 35B model, where trajectories ran from 2k to 128k tokens. This tutorial runs the same three choices on Qwen3-0.6B and GSM8K, once with LoRA and once at full weight, and reports whether the rankings match. It tests the method on a cheap proxy. A 0.6B model on single-turn math says nothing about long-horizon agentic RL.
Full code is available on GitHub.
The default screen runs 12 arms (3 aggregations, 2 modes, 2 seeds), each on one L4 GPU. Set SCREEN_GPU_TYPE to use another GPU type.
You need a Hugging Face token stored as a secret named HF_TOKEN.
Create it with flyte create secret HF_TOKEN --value <your token> (see Secrets).
Run it
git clone https://github.com/unionai/unionai-examples
cd unionai-examples/v2/tutorials/lora_ablation_screen
python lora_screen.pyAn arm is a row of the ablation table
Everything that defines an arm is a field on Arm, so the arm is its own cache key. LoRA and full weight differ only in mode and learning rate.
class Arm(BaseModel):
"""One row of the ablation table. Everything that defines the arm is here, so it's the cache key."""
loss_agg: str # token_mean | sequence_mean | prompt_mean
mode: str # lora | full
lr: float
seed: int = 0
@property
def name(self) -> str:
return f"{self.mode}-{self.loss_agg}-s{self.seed}"
class ScreenConfig(BaseModel):
base_model: str = "Qwen/Qwen3-0.6B"
steps: int = 20
prompts_per_step: int = 16
group_size: int = 8
max_tokens: int = 512
eval_questions: int = 300
lora_rank: int = 16
lora_alpha: int = 32
# Without these the model writes "#### 42" and keeps going until max_tokens, every completion has the same
# length, and the three aggregations become the same loss (an accidental A/A test; see the README).
stop: list[str] = ["\nProblem:", "Problem:", "\n\n\n"]
# LoRA wants roughly 10x the full-weight learning rate (Thinking Machines, "LoRA Without Regret").
DEFAULT_ARMS = [Arm(loss_agg=agg, mode=mode, lr=2e-5 if mode == "lora" else 2e-6, seed=seed)
for agg in ("token_mean", "sequence_mean", "prompt_mean") for mode in ("lora", "full")
for seed in (0, 1)]
LoRA arms use a learning rate 10 times the full-weight rate, following Thinking Machines’ “LoRA Without Regret.” LoRA targets every linear layer, attention and MLP.
The loss aggregations
The three arms differ only in the per-sequence weight applied to the policy-gradient term. Each weighting keeps the loss on the same scale, so the arms share a learning rate within a mode.
def sequence_weights(lengths: list[int], groups: list[int], loss_agg: str) -> list[float]:
"""Per-sequence weight w_i such that loss = -sum_i A_i * w_i * sum_t log p(t).
token_mean one pool of tokens: long completions dominate the gradient
sequence_mean every completion counts equally, whatever its length (original GRPO)
prompt_mean every prompt group counts equally; tokens are pooled within the group (DAPO-style)
"""
n_seq, n_tok = len(lengths), sum(lengths)
if loss_agg == "token_mean":
return [1.0 / n_tok] * n_seq
if loss_agg == "sequence_mean":
return [1.0 / (n_seq * max(L, 1)) for L in lengths]
if loss_agg == "prompt_mean":
group_tok: dict[int, int] = {}
for g, L in zip(groups, lengths):
group_tok[g] = group_tok.get(g, 0) + L
n_groups = len(group_tok)
return [1.0 / (n_groups * max(group_tok[g], 1)) for g in groups]
raise ValueError(loss_agg)
One arm, one durable action
train_arm runs a whole arm on one GPU: sample, score, take one GRPO step with the arm’s aggregation, repeat, then evaluate greedily on held-out questions.
@arm_env.task(cache="auto", retries=2, timeout=flyte.Timeout(max_runtime=timedelta(hours=3)))
async def train_arm(base: flyte.io.Dir, arm: Arm, cfg: ScreenConfig, train: list[QA], test: list[QA]) -> ArmResult:
import random
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
t_start = time.monotonic()
torch.manual_seed(arm.seed)
local_base = await base.download()
tok = AutoTokenizer.from_pretrained(local_base)
# fp32 master weights for full-weight RL (bf16 can't represent lr=2e-6 updates); bf16 base under LoRA.
model = AutoModelForCausalLM.from_pretrained(
local_base, torch_dtype=torch.float32 if arm.mode == "full" else torch.bfloat16).cuda()
if arm.mode == "lora":
from peft import LoraConfig, get_peft_model
model = get_peft_model(model, LoraConfig(
r=cfg.lora_rank, lora_alpha=cfg.lora_alpha, lora_dropout=0.0, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]))
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=arm.lr, betas=(0.9, 0.98),
weight_decay=0.0)
work = Path(tempfile.mkdtemp(prefix=f"{arm.name}-"))
policy_dir = work / "policy"
def export_policy() -> tuple[str, str | None]:
"""Write the current policy where the sampler can load it: an adapter, or a whole model."""
model.save_pretrained(policy_dir)
if arm.mode == "lora":
return local_base, str(policy_dir)
tok.save_pretrained(policy_dir)
return str(policy_dir), None
rng = random.Random(arm.seed)
history: list[StepLog] = []
for step in range(cfg.steps):
batch = rng.sample(train, cfg.prompts_per_step)
sampler_model, lora = export_policy()
out = await _sample(sampler_model, lora, [PROMPT.format(q=b.question) for b in batch], cfg.group_size, cfg,
1.0, arm.seed * 1000 + step, work)
seqs, groups, rewards = [], [], []
for g, (qa, grp) in enumerate(zip(batch, out["groups"])):
for s in grp["samples"]:
seqs.append((grp["prompt_ids"], s["ids"]))
groups.append(g)
rewards.append(reward(s["text"], qa.answer))
adv = advantages(rewards, groups)
lengths = [len(c) for _, c in seqs]
weights = sequence_weights(lengths, groups, arm.loss_agg)
t0 = time.monotonic()
model.train()
opt.zero_grad(set_to_none=True)
for (p_ids, c_ids), a, w in zip(seqs, adv, weights):
if a == 0.0 or not c_ids:
continue # no signal: the whole group scored the same
ids = torch.tensor([p_ids + c_ids], device="cuda")
with torch.autocast("cuda", dtype=torch.bfloat16):
logits = model(ids).logits[:, len(p_ids) - 1 : -1, :].float()
logp = torch.log_softmax(logits, -1).gather(-1, ids[:, len(p_ids):].unsqueeze(-1)).squeeze(-1)
(-a * w * logp.sum()).backward()
torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], 1.0)
opt.step()
history.append(StepLog(
step=step, mean_reward=round(statistics.fmean(rewards), 4), mean_len=round(statistics.fmean(lengths), 1),
len_cv=round(statistics.pstdev(lengths) / max(statistics.fmean(lengths), 1), 3),
engine_init_s=out["engine_init_s"], generate_s=out["generate_s"], train_s=round(time.monotonic() - t0, 1)))
print(json.dumps(history[-1].model_dump()), flush=True)
# held-out eval: greedy, one sample per question
sampler_model, lora = export_policy()
ev = await _sample(sampler_model, lora, [PROMPT.format(q=q.question) for q in test], 1, cfg, 0.0, 0, work)
correct = [reward(g["samples"][0]["text"], qa.answer) for qa, g in zip(test, ev["groups"])]
acc = statistics.fmean(correct)
policy_bytes = sum(f.stat().st_size for f in policy_dir.rglob("*.safetensors"))
return ArmResult(arm=arm, eval_acc=round(acc, 4), eval_se=round(math.sqrt(acc * (1 - acc) / len(correct)), 4),
history=history, seconds_total=round(time.monotonic() - t_start, 1), policy_bytes=policy_bytes)
Three details matter for a fair comparison:
- Token-in, token-out. vLLM returns the prompt and completion token IDs it sampled, and the trainer computes log-probabilities over exactly those IDs. Nothing is re-tokenized.
- vLLM runs in a subprocess. Each step starts vLLM, samples, and exits, so the sampler releases its GPU memory before training. A LoRA arm loads the base model plus the adapter. A full-weight arm loads the whole updated model. The report shows the per-step cost of each.
- fp32 master weights for full-weight arms. A full-weight update at a learning rate of
2e-6is too small to represent in bf16. LoRA arms keep the frozen base in bf16 and train fp32 adapters.
The task has cache="auto" and retries=2. A failed arm retries on its own without touching the other arms. A finished arm comes back from the cache when you rerun the screen.
The screen
screen fans out the arms in parallel, evaluates the base model once, and computes the ranking under each mode and Kendall’s τ between them.
@driver_env.task(report=True)
async def screen(arms: list[Arm] = DEFAULT_ARMS, cfg: ScreenConfig = ScreenConfig()) -> ScreenSummary:
(train, test), base = await asyncio.gather(load_gsm8k(n_test=cfg.eval_questions), prefetch(cfg.base_model))
base_acc_task = asyncio.create_task(eval_base(base, cfg, test))
outs = await asyncio.gather(*(train_arm(base, a, cfg, train, test) for a in arms), return_exceptions=True)
results = [o for o in outs if isinstance(o, ArmResult)] # a failed arm is a gap in the table, not a dead screen
def mean_acc(mode: str, agg: str) -> float:
accs = [r.eval_acc for r in results if r.arm.mode == mode and r.arm.loss_agg == agg]
return statistics.fmean(accs) if accs else float("nan")
aggs = sorted({r.arm.loss_agg for r in results})
ranking = {mode: sorted((a for a in aggs if not math.isnan(mean_acc(mode, a))), key=lambda a: -mean_acc(mode, a))
for mode in ("lora", "full")} # mean held-out accuracy over seeds, best first
common = [x for x in ranking["full"] if x in ranking["lora"]]
lora_order = [x for x in ranking["lora"] if x in common]
summary = ScreenSummary(
base_acc=await base_acc_task, results=results, ranking=ranking,
kendall_tau=round(kendall_tau(lora_order, common), 3),
same_winner=bool(common) and lora_order[0] == common[0],
)
await flyte.report.replace.aio(_report(summary), do_flush=True)
return summary
A failed arm leaves a gap in the table instead of failing the screen. Add an arm to the list and rerun, and only the new arm trains.
Results
Qwen3-0.6B on L4 GPUs, 20 GRPO steps of 16 prompts × 8 samples, greedy evaluation on 300 held-out GSM8K questions. The standard error is about 2.9 points per arm. The base model scores 37.7%.
| Aggregation | Full weight, seed 0 / 1 → mean | LoRA, seed 0 / 1 → mean |
|---|---|---|
prompt_mean |
61.7% / 59.0% → 60.3% | 45.3% / 56.0% → 50.7% |
token_mean |
54.3% / 58.3% → 56.3% | 49.3% / 51.0% → 50.2% |
sequence_mean |
52.3% / 56.7% → 54.5% | 49.3% / 53.7% → 51.5% |
- Full weight ranks
prompt_meanfirst. Both of its seeds beat every seed of the other two arms. - LoRA doesn’t pick the same winner. Its three arms are within 1.3 points of each other, and its two seeds of
prompt_meandiffer by 10.7 points. Kendall’s τ between the two rankings is −0.33. - LoRA arms learn less in the same step budget: 50.8% mean held-out accuracy against 57.0%. The LoRA learning rate isn’t tuned here.
Per arm, a full-weight step averages 18 seconds of engine start, 17 seconds of sampling, and 26 seconds of training, and writes 2.4 GB of policy. A LoRA step averages 19, 30, and 34 seconds and writes 40 MB. At this model size, LoRA saves memory and bytes moved, not wall-clock time.
Measure the noise floor first
If every completion reaches max_tokens, every sequence has the same length and the three aggregations compute the same loss. Without stop strings, Qwen3-0.6B writes the answer and keeps generating until the limit. A screen run that way is an A/A test. In one such run, full-weight arms with an identical loss still spread from 49.0% to 58.0% held-out accuracy. Run the screen with identical arms before you trust a ranking from it.
ScreenConfig.stop ends each completion after the answer. Because stop is a field on an input, changing it invalidates the cached arms. A change inside vllm_generate.py alone wouldn’t.
Related
- RL for LLMs with GRPO and LoRA builds a single-arm GRPO loop with a warm vLLM pool.
- Harness evals and trace audits for agentic RL covers the eval side of the same campaign.