End-to-end RL for several skills at once: concurrent GRPO runs share warm GPUs and one copy of the base model, checkpoint every iteration, autoscale, pause for a review, and serve each approved model.

Concurrent RL runs on a shared base model

Code available on GitHub.

Say you have one base model and several things you want it to get better at: one team wants reliable JSON extraction, another wants arithmetic reasoning. Each is a separate reinforcement learning (RL) run with its own reward. If every run is its own job, every run loads the same base model onto its own GPUs, and each GPU sits idle whenever its run is between steps. The runs also need someone to look at the result before a model ships, and every approved model needs an endpoint.

This tutorial runs that whole lifecycle on Union.ai for two skills at once:

  • Concurrent runs on shared GPUs. Both RL runs are in progress at the same time and call into the same warm GPU replicas. The base model is loaded once; each run trains its own LoRA adapter on top.
  • Distributed and autoscaled. Generation, scoring, and training run in separate containers sized for the work. The rollout pool grows from one GPU replica to two when generation calls queue up, and shrinks when they are idle.
  • Resilient. Each run checkpoints every iteration and resumes there after a preemption. A crashed engine or a failed step is retried on the shared replicas without corrupting the other run’s state.
  • A review for each run. After its final eval, each run pauses until a person approves or rejects that skill’s model. Nothing is published without an approval.
  • Serving for each model. Every approved model is published as an artifact and served by its own autoscaling vLLM app, next to the base model and a side-by-side chat.

The example uses Qwen/Qwen2.5-1.5B-Instruct on L4 GPUs. You do not need a Hugging Face token or a dataset. If RL for LLMs is new to you, RL for LLMs with GRPO and LoRA covers a single run in more detail.

The ideas, in plain terms

Policy. The thing being trained. Here it is the language model.

Rollout. One answer the policy produced for one problem. The loop samples several answers per problem so it can compare them.

Reward. A number that says how good an answer was. Where that number comes from is the main choice you make:

Where the reward comes from Use it when
RLVR (RL with verifiable rewards) A program checks the answer: does the expression equal the target, does the JSON match Correctness can be checked by code. This tutorial does this
RLHF (RL from human feedback) People rate or rank answers, usually through a reward model trained on those ratings Quality is a matter of preference: tone, helpfulness, style
Judge model Another LLM grades the answer against a rubric Checking needs reading comprehension and you have no human labels

Only the reward changes between these. Change the reward shows the one function to replace.

GRPO. The update rule. For each problem, compare every sampled answer with the other answers to the same problem. Answers that scored above their group’s average become more likely, and answers below it become less likely:

advantage_i = (reward_i - mean(group rewards)) / (std(group rewards) + eps)
loss        = -mean( advantage_i * average log-probability of answer_i's tokens )

There is no critic network to train. The full GRPO algorithm also clips the update and adds a KL penalty. This tutorial leaves both out and takes one small gradient step per iteration.

LoRA. Instead of changing all 1.5 billion weights, training adds a pair of small matrices next to each layer and trains only those. The base weights stay frozen. An adapter is tens of megabytes where the base model is gigabytes. This is what lets several runs share one base model: the large frozen part is identical for all of them, and only the small adapter differs.

The two skills

Both are defined in tasks.py, which is pure Python with no ML dependencies.

Skill What the base model gets wrong Reward
countdown: combine the given numbers with + − × ÷ to hit a target, using each number once guesses, reuses numbers, makes arithmetic mistakes 0 unless it reasons in <think> first; +0.1 for a valid expression; +1.0 if it is correct
json: turn a messy support email into a strict 8-field JSON record wraps the JSON in markdown, picks the cc’d person’s email, skips normalization rules +0.2 bare JSON, +0.2 exact keys, +0.6 × fraction of fields correct

Problems are generated, so there is an unlimited supply for training, plus a fixed held-out set of 100 that training never sees. The reward is a checker, not an answer key for the model to copy:

tasks.py
def score(task: str, completion: str, answer: str) -> tuple[float, bool, bool]:
    """Returns (reward, formatted, correct). Reward is in [0, 1.1] for countdown and [0, 1] for json."""
    truth = json.loads(answer)
    if task == "countdown":
        formatted, correct = check_countdown(completion, truth["numbers"], truth["target"])
        # No reasoning, no reward. Without this gate the first run learned to drop <think> and guess:
        # format went to 100%, but the search that solves the harder puzzles disappeared.
        formatted = formatted and _has_reasoning(completion)
        return 0.1 * formatted + 1.0 * (correct and formatted), formatted, correct
    g = grade_json(completion, truth)
    reward = 0.2 * g["strict"] + 0.2 * g["keys_ok"] + 0.6 * g["frac"]
    return reward, g["strict"] and g["keys_ok"], g["strict"] and not g["wrong"]

Partial credit matters. A reward that is 0 for everything except a perfect answer gives the model nothing to climb at the start, when almost every answer is wrong.

How the work is laid out

Each kind of work gets its own task environment: a container image plus the hardware it needs.

Environment Hardware Reusable Tasks
rl-demo-rollout 1 × L4 yes, 1 to 2 replicas generate, evaluate
rl-demo-reward 1 CPU yes score_chunk
rl-demo-train 1 × L4 yes, 1 replica init_adapter, train_step, merge_adapter
rl-demo-driver 1 CPU no train_rl, the loop and the review

A reusable environment keeps its containers alive between task calls. The Python process, and anything it has loaded into GPU memory, is still there for the next call. For an RL loop that is the difference between loading a model once and loading it hundreds of times.

Reusable environments are also shared across runs: runs that use an environment with the same name and version call into the same replicas. When the countdown run and the JSON run are both active, they call into the same replicas:

            flowchart LR
    subgraph RUNS["two runs, one per skill"]
      D1["train_rl · countdown<br/>CPU driver"]
      D2["train_rl · json<br/>CPU driver"]
    end

    subgraph ROLL["rl-demo-rollout · reusable · L4 · 1 to 2 replicas"]
      V["vLLM engine<br/>base weights loaded once<br/>LoRA attached per request"]
    end

    subgraph TRAIN["rl-demo-train · reusable · L4"]
      T["base weights loaded once<br/>adapter + optimizer: countdown<br/>adapter + optimizer: json"]
    end

    R["rl-demo-reward · reusable · CPU"]
    H{{"review<br/>one per run"}}
    A[("model artifacts")]
    S["vLLM apps<br/>one per approved model<br/>0 to 2 replicas"]

    D1 -- "generate / evaluate" --> V
    D2 -- "generate / evaluate" --> V
    D1 -- "score_chunk" --> R
    D2 -- "score_chunk" --> R
    D1 -- "train_step" --> T
    D2 -- "train_step" --> T
    D1 --> H
    D2 --> H
    H -- "approved" --> A
    A --> S
        

While one run is in its gradient step, the other is generating, so both GPUs stay busy. The second run never waits for a model load.

Run it

You need a Union.ai deployment with L4 capacity and a Flyte config pointing at it (flyte create config).

git clone https://github.com/unionai/unionai-examples
cd unionai-examples/v2/tutorials/rl_multi_lora
uv sync

# 1. Train both skills: two runs in progress at once, sharing the same warm replicas.
#    The first time, this also copies the base model into your object store.
uv run python train.py --task all

# 2. Each run pauses for review after its final eval. Approve it on the run page, or:
uv run python review.py <run-name> --approve     # or --reject

# 3. Serve the base model, every approved model, and the side-by-side chat.
uv run python serve.py                           # or: uv run python serve.py --tasks json

train.py prints a URL per run. Open one to watch its report update after every iteration.

Walkthrough of train.py

1. Environments

One image is used everywhere. It starts from the vLLM plugin’s serving image, so training and serving run the same vLLM, and adds peft for LoRA:

train.py
# Built on the vLLM plugin's serving image, so rollouts here and serving in serve.py run the same vLLM
# (and share its layers in the build cache). It already carries vLLM's own torch/transformers pins and
# the prebuilt flashinfer kernels; training only adds peft and the reusable-container bridge.
image = DEFAULT_VLLM_IMAGE.clone(name="rl-demo-train").with_pip_packages(
    "peft>=0.21",
    "accelerate>=1.0",
    "unionai-reuse>=0.1.3",
    "async-lru>=2.0.0",
)

# 24Gi, not 32Gi: a g6.2xlarge (1x L4) has ~29Gi allocatable, and anything larger spills over to the
# 4x L4 g6.12xlarge, which is often out of capacity.
L4 = flyte.Resources(cpu=4, memory="24Gi", gpu=flyte.GPU("L4", 1), shm="auto")

The rollout environment is reusable and autoscales between one and two replicas:

train.py
# The reusable environments below keep ReusePolicy's default scope="global": every run of this file lands
# on the same warm replicas, so concurrent countdown and JSON runs share one copy of the base weights.
# Nothing in a replica may therefore assume it serves a single run; state is keyed by skill / adapter path.

# Rollouts and eval: warm vLLM with per-request LoRA. concurrency=1 because one in-process engine is not
# safe to drive from several coroutines; the driver parallelizes across replicas instead.
rollout_env = flyte.TaskEnvironment(
    name="rl-demo-rollout",
    image=image,
    resources=L4,
    reusable=flyte.ReusePolicy(replicas=(1, ROLLOUT_CHUNKS), concurrency=1, idle_ttl=600, scaledown_ttl=300),
)

The trainer is one reusable GPU replica. concurrency is the number of skills, so one step per run can be in flight:

train.py
# Trainer: one warm GPU replica that keeps the base model resident, plus a LoRA adapter and optimizer per
# skill. concurrency=2 lets one step per skill be in flight: the GPU part of a step is serialized by
# _TRAINER_LOCK (the active adapter is a switch on the shared model, and two backward passes don't fit
# on an L4), while input download and adapter upload overlap with the other skill's GPU work.
train_env = flyte.TaskEnvironment(
    name="rl-demo-train",
    image=image,
    resources=L4,
    reusable=flyte.ReusePolicy(replicas=1, concurrency=len(tasks.TASKS), idle_ttl=600, scaledown_ttl=300),
)

The driver is an ordinary container. depends_on tells Flyte to deploy the other environments with it:

train.py
driver_env = flyte.TaskEnvironment(
    name="rl-demo-driver",
    image=image,
    resources=flyte.Resources(cpu=1, memory="2Gi"),
    depends_on=[rollout_env, reward_env, train_env],
)

2. Rollouts: one warm vLLM engine, a LoRA per request

The engine is built once per replica and cached. Every later call, from either run, finds the base model already on the GPU:

train.py
@alru_cache(maxsize=1)
async def _load_engine(base_uri: str) -> Any:
    """Build the vLLM engine once per warm replica; the frozen base stays resident on the GPU."""
    from vllm import LLM

    local_base = await _local_dir(base_uri)
    logger.info("Building warm vLLM engine from %s", local_base)
    return LLM(
        model=local_base,
        enable_lora=True,
        max_lora_rank=LORA_RANK,
        max_loras=1,
        gpu_memory_utilization=0.85,
        max_model_len=2048,
        enable_prefix_caching=True,  # every prompt in a task shares the long system prompt
    )

The adapter is not baked into the engine. Each request names the adapter to apply, so one engine can generate with countdown’s adapter in one batch and JSON’s in the next:

train.py
async def _lora_request(adapter: flyte.io.Dir | None, version: int) -> Any:
    if adapter is None:
        return None
    import zlib

    from vllm.lora.request import LoRARequest

    # vLLM caches adapters by lora_int_id, so it must be >= 1 and unique per adapter *across runs*: the
    # engine is shared, and every run has its own v1, v2, ... Hash the remote path, not the version.
    # vLLM stores the id in an int32 array, so fold the hash into [1, 2**31 - 1].
    lora_id = zlib.crc32(adapter.path.encode()) % (2**31 - 1) + 1
    return LoRARequest(f"policy-v{version}-{lora_id:08x}", lora_id, await _local_dir(adapter.path))

vLLM remembers adapters by an integer id. Because the engine is shared, the id has to be unique across runs, so it is derived from the adapter’s storage path. A version counter would collide: every run has its own v1, v2, and so on. The id also has to fit in a signed 32-bit integer.

generate renders the prompts with the model’s chat template, samples GROUP_SIZE answers for each, and returns the text together with the exact token ids that were sampled:

train.py
@rollout_env.task(retries=2)  # a retry after an engine crash gets a freshly built engine
async def generate(
    base: flyte.io.Dir,
    task: str,
    questions: list[str],
    answers: list[str],
    adapter: flyte.io.Dir,
    version: int,
    first_group: int,
    max_new_tokens: int,
) -> list[Rollout]:
    """Sample GROUP_SIZE completions for each question in one vLLM batch, using the current adapter."""
    from vllm import SamplingParams

    engine = await _load_engine(base.path)
    tokenizer = engine.get_tokenizer()
    prompts = [_render(tokenizer, task, q) for q in questions]
    sampling = SamplingParams(n=GROUP_SIZE, temperature=SAMPLING_TEMPERATURE, top_p=1.0, max_tokens=max_new_tokens)
    lora = await _lora_request(adapter, version)
    outputs = await _generate(engine, prompts, sampling, lora)
    return [
        Rollout(
            group_id=first_group + i,
            question=q,
            answer=a,
            completion=o.text,
            completion_ids=list(o.token_ids),
        )
        for i, (q, a, out) in enumerate(zip(questions, answers, outputs))
        for o in out.outputs
    ]

evaluate uses the same engine with greedy decoding on the 100 held-out problems. It runs once before training with no adapter and once after with the final adapter:

train.py
@rollout_env.task
async def evaluate(
    base: flyte.io.Dir,
    task: str,
    max_new_tokens: int,
    adapter: flyte.io.Dir | None = None,
    version: int = 0,
    sample_index: int = -1,
) -> EvalResult:
    """Greedy accuracy on the fixed held-out set (base model when ``adapter`` is None).

    The sample shown in the report is ``sample_index`` if given, otherwise the first problem the model
    got wrong — so the base eval picks a failure and the final eval shows the same problem again.
    """
    from vllm import SamplingParams

    engine = await _load_engine(base.path)
    tokenizer = engine.get_tokenizer()
    problems = tasks.eval_set(task, EVAL_SIZE)
    prompts = [_render(tokenizer, task, q) for q, _ in problems]
    sampling = SamplingParams(n=1, temperature=0.0, max_tokens=max_new_tokens)
    lora = await _lora_request(adapter, version)
    outputs = await _generate(engine, prompts, sampling, lora)
    completions = [out.outputs[0].text for out in outputs]
    graded = [tasks.score(task, c, a) for c, (_, a) in zip(completions, problems)]

    if sample_index < 0:
        sample_index = next((i for i, (_, _, ok) in enumerate(graded) if not ok), 0)
    n = len(problems)
    result = EvalResult(
        accuracy=sum(ok for _, _, ok in graded) / n,
        format_rate=sum(fmt for _, fmt, _ in graded) / n,
        num_problems=n,
        sample_index=sample_index,
        sample_question=problems[sample_index][0],
        sample_completion=completions[sample_index],
        sample_correct=graded[sample_index][2],
    )
    logger.info(
        "eval %s (adapter=%s): accuracy %.1f%%",
        task,
        "none" if adapter is None else f"v{version}",
        100 * result.accuracy,
    )
    return result

3. Reward

Scoring takes microseconds of Python, so it runs in a small CPU container instead of on a GPU:

train.py
@reward_env.task
async def score_chunk(task: str, rollouts: list[Rollout]) -> list[float]:
    """Score one generate() chunk; runs while the other chunk is still generating."""
    return [tasks.score(task, r.completion, r.answer)[0] for r in rollouts]

4. Trainer: one base model, one adapter per skill

The trainer keeps its state in a module-level dictionary, which survives between calls because the container is reusable. The base model is loaded once. Each skill gets a named LoRA adapter on that base, with its own optimizer:

train.py
# In-memory trainer state for this warm replica, shared by every run that lands on it:
#   base, model, tokenizer - one frozen base on the GPU
#   policies[skill]        - that skill's LoRA adapter (a named PEFT adapter on the shared base), its
#                            AdamW state, and the remote path the in-memory weights correspond to
# A step whose input adapter matches the recorded path skips the reload and keeps Adam's moments.
_TRAINER: dict[str, Any] = {}
# Held while _TRAINER is being (re)loaded and for the GPU part of a step.
_TRAINER_LOCK = asyncio.Lock()

async def _trainer(base: flyte.io.Dir, task: str, adapter: flyte.io.Dir) -> tuple[dict[str, Any], dict[str, Any]]:
    """Return ``(shared state, this skill's policy)`` with the skill's adapter active and trainable."""
    import torch
    from peft import PeftModel
    from transformers import AutoModelForCausalLM, AutoTokenizer

    st = _TRAINER
    if st.get("base") != base.path:
        logger.info("Loading base model %s", base.path)
        st.clear()
        torch.cuda.empty_cache()
        local_base = await _local_dir(base.path)
        st.update(
            base=base.path,
            model=AutoModelForCausalLM.from_pretrained(local_base, dtype=torch.bfloat16).to("cuda"),
            tokenizer=AutoTokenizer.from_pretrained(local_base),
            policies={},
        )

    policy = st["policies"].get(task)
    if policy is not None and policy["adapter"] == adapter.path:
        st["model"].set_adapter(task)  # another skill's step may have run in between
        return st, policy

    logger.info("Loading %s adapter %s", task, adapter.path)
    st["policies"].pop(task, None)
    local_adapter = await adapter.download()
    model = st["model"]
    if not isinstance(model, PeftModel):  # first adapter on this replica: wrap the base
        model = st["model"] = PeftModel.from_pretrained(model, local_adapter, adapter_name=task, is_trainable=True)
    else:
        if task in model.peft_config:  # stale weights from an earlier run of the same skill
            model.delete_adapter(task)
        model.load_adapter(local_adapter, adapter_name=task, is_trainable=True)
    model.set_adapter(task)  # activates this adapter and freezes every other one
    model.train()
    params = [p for p in model.parameters() if p.requires_grad]
    if not params:
        raise RuntimeError(f"adapter {task!r} has no trainable parameters")
    policy = st["policies"][task] = {
        "adapter": adapter.path,
        "params": params,
        "optimizer": torch.optim.AdamW(params, lr=LEARNING_RATE, weight_decay=0.0),
    }
    return st, policy

Each call checks whether the adapter it was handed is the one already in memory for that skill. If it is, the only work is switching the active adapter. Otherwise it loads that one adapter and leaves the base model and the other skill alone.

The group-relative advantage is a few lines:

train.py
def _group_normalized_advantages(rollouts: list[Rollout], rewards: list[float]) -> list[float]:
    """GRPO advantage: within each prompt group, ``(r - mean) / (std + eps)``."""
    import statistics
    from collections import defaultdict

    by_group: dict[int, list[int]] = defaultdict(list)
    for i, r in enumerate(rollouts):
        by_group[r.group_id].append(i)

    advantages = [0.0] * len(rollouts)
    for idxs in by_group.values():
        group_rewards = [rewards[i] for i in idxs]
        mean = statistics.fmean(group_rewards)
        std = statistics.pstdev(group_rewards) if len(group_rewards) > 1 else 0.0
        for i in idxs:
            advantages[i] = (rewards[i] - mean) / (std + 1e-4)
    return advantages

The GPU part of a step computes the loss on the sampled tokens, takes one optimizer step, and saves the adapter:

train.py
def _grpo_step(
    st: dict[str, Any], policy: dict[str, Any], task: str, rollouts: list[Rollout], rewards: list[float], version: int
) -> tuple[pathlib.Path, pathlib.Path, float, int]:
    """The blocking GPU part of a step: backward passes, optimizer step, adapter saved to local disk.

    Returns ``(tmp_dir, adapter_dir, mean_loss, contributing)``. Call with ``_TRAINER_LOCK`` held.
    """
    import torch
    import torch.nn.functional as F

    model, tokenizer, optimizer = st["model"], st["tokenizer"], policy["optimizer"]

    advantages = _group_normalized_advantages(rollouts, rewards)
    items = [(r, adv) for r, adv in zip(rollouts, advantages) if adv != 0.0 and r.completion_ids]
    prompt_ids = {
        q: tokenizer(_render(tokenizer, task, q), add_special_tokens=False).input_ids
        for q in {r.question for r, _ in items}
    }

    optimizer.zero_grad()
    total_loss = 0.0
    for start in range(0, len(items), MICRO_BATCH):
        batch = items[start : start + MICRO_BATCH]
        seqs = [prompt_ids[r.question] + r.completion_ids for r, _ in batch]
        width = max(len(s) for s in seqs)
        input_ids = torch.full((len(seqs), width), tokenizer.pad_token_id, dtype=torch.long)
        attention = torch.zeros((len(seqs), width), dtype=torch.long)
        loss_mask = torch.zeros((len(seqs), width), dtype=torch.float32)
        for row, ((r, _), seq) in enumerate(zip(batch, seqs)):
            input_ids[row, : len(seq)] = torch.tensor(seq)
            attention[row, : len(seq)] = 1
            loss_mask[row, len(prompt_ids[r.question]) : len(seq)] = 1.0  # completion tokens only
        input_ids, attention, loss_mask = input_ids.cuda(), attention.cuda(), loss_mask.cuda()

        logits = model(input_ids=input_ids, attention_mask=attention).logits[:, :-1].float()
        token_logp = -F.cross_entropy(logits.transpose(1, 2), input_ids[:, 1:], reduction="none")
        mask = loss_mask[:, 1:]
        seq_logp = (token_logp * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
        adv = torch.tensor([a for _, a in batch], device=seq_logp.device)
        # Mean over every contributing sequence in the step, so the step size doesn't scale with batch.
        loss = -(adv * seq_logp).sum() / len(items)
        loss.backward()
        total_loss += float(loss.item())

    if items:
        torch.nn.utils.clip_grad_norm_(policy["params"], 1.0)
        optimizer.step()
    logger.info("GRPO step v%d: %d/%d rollouts contributed, loss %.4f", version, len(items), len(rollouts), total_loss)

    out_dir = pathlib.Path(tempfile.mkdtemp(prefix=f"adapter-{task}-v{version}-"))
    model.save_pretrained(str(out_dir), selected_adapters=[task])
    # PEFT writes a named (non-"default") adapter into a subdirectory named after it.
    saved = out_dir / task if (out_dir / task / "adapter_config.json").exists() else out_dir
    return out_dir, saved, total_loss, len(items)

train_step wraps it. The lock makes the GPU work take turns, because the active adapter is a single switch on the shared model. Downloading inputs and uploading the new adapter happen outside the lock, so they overlap with the other run’s GPU work:

train.py
@train_env.task(retries=2)  # a retry reloads the adapter it was given (see below)
async def train_step(
    base: flyte.io.Dir,
    task: str,
    rollouts: list[Rollout],
    rewards: list[float],
    adapter: flyte.io.Dir,
    version: int,
) -> tuple[flyte.io.Dir, float, int]:
    """One GRPO policy-gradient step; returns ``(new_adapter, mean_loss, contributing)``."""
    async with _TRAINER_LOCK:
        st, policy = await _trainer(base, task, adapter)
        # From here the in-memory weights match no published adapter until the upload below finishes;
        # if this step fails midway, the retry reloads from ``adapter`` instead of training on top.
        policy["adapter"] = None
        # Off the event loop, so the replica keeps heartbeating and the other skill's I/O keeps moving.
        out_dir, saved, mean_loss, contributing = await asyncio.to_thread(
            _grpo_step, st, policy, task, rollouts, rewards, version
        )
    try:
        new_adapter = await flyte.io.Dir.from_local(str(saved))
    finally:
        shutil.rmtree(out_dir, ignore_errors=True)  # don't fill the long-lived replica's disk
    policy["adapter"] = new_adapter.path  # the next step resumes from memory instead of reloading
    return new_adapter, mean_loss, contributing

The new adapter goes back to the driver as a flyte.io.Dir. Flyte uploads it to object storage and hands the next generate call a reference, so there is no shared filesystem to set up.

5. Driver: the loop

The driver is a for loop that calls the other tasks. It evaluates the base model, runs the iterations, evaluates again, waits for the review, and publishes the approved model:

train.py
@driver_env.task(report=True, produces_artifacts=True)
async def train_rl(base: flyte.io.Dir, skill: str = "countdown", num_iterations: int = 0) -> flyte.io.Dir:
    """Eval the base, run the GRPO loop, eval again, wait for a review, and publish the merged model.

    ``skill`` is one of ``tasks.TASKS`` (not named ``task``: that would clash with ``flyte.run``'s first
    parameter). Loop state is checkpointed every iteration, so a preempted driver resumes mid-run.
    """
    task = skill
    if task not in tasks.TASKS:
        raise ValueError(f"task must be one of {tasks.TASKS}, got {task!r}")
    cfg = TASK_CONFIG[task]
    num_iterations = num_iterations or cfg.iterations

    ctx = flyte.ctx()
    cp = ctx.checkpoint if ctx is not None else None
    start_iter = 0
    adapter: flyte.io.Dir | None = None
    adapter_version = 0
    history: list[IterationMetrics] = []
    base_eval: EvalResult | None = None

    if cp is not None:
        prev = await cp.load()
        if prev is not None:
            state = json.loads(prev.read_text())
            start_iter = state["iteration"] + 1
            adapter_version = state["adapter_version"]
            adapter = flyte.io.Dir.from_existing_remote(state["adapter_path"])
            history = [IterationMetrics(**row) for row in state["history"]]
            base_eval = EvalResult(**state["base_eval"])
            logger.info("Resumed at iteration %d (adapter v%d)", start_iter, adapter_version)

    # Act 1: how bad is the base model?
    if base_eval is None:
        with flyte.group("eval-base"):
            base_eval = await evaluate(base, task, cfg.max_new_tokens)
    await _publish_report(history, task, num_iterations, "running", base_eval)

    if adapter is None:
        adapter = await init_adapter(base)

    # Act 2: RL.
    for it in range(start_iter, num_iterations):
        with flyte.group(f"iter-{it}"):
            problems = tasks.train_batch(task, it, PROMPTS_PER_ITER)
            per_chunk = -(-len(problems) // ROLLOUT_CHUNKS)
            gen_futs = [
                asyncio.create_task(
                    generate(
                        base,
                        task,
                        [q for q, _ in problems[s : s + per_chunk]],
                        [a for _, a in problems[s : s + per_chunk]],
                        adapter,
                        adapter_version,
                        first_group=s,
                        max_new_tokens=cfg.max_new_tokens,
                    )
                )
                for s in range(0, len(problems), per_chunk)
            ]
            # Score each chunk as soon as it lands, overlapping reward with the other chunk's generation.
            rollouts: list[Rollout] = []
            score_futs: list[asyncio.Task[list[float]]] = []
            for fut in asyncio.as_completed(gen_futs):
                chunk = await fut
                rollouts.extend(chunk)
                score_futs.append(asyncio.create_task(score_chunk(task, chunk)))
            rewards = [r for chunk_rewards in await asyncio.gather(*score_futs) for r in chunk_rewards]

            adapter, mean_loss, contributing = await train_step(
                base, task, rollouts, rewards, adapter, adapter_version + 1
            )
            adapter_version += 1

            graded = [tasks.score(task, r.completion, r.answer) for r in rollouts]
            n = len(rollouts)
            best = max(range(n), key=lambda i: rewards[i])
            history.append(
                IterationMetrics(
                    iteration=it,
                    adapter_version=adapter_version,
                    num_rollouts=n,
                    mean_reward=sum(rewards) / n,
                    max_reward=max(rewards),
                    accuracy=sum(ok for _, _, ok in graded) / n,
                    format_rate=sum(fmt for _, fmt, _ in graded) / n,
                    mean_loss=mean_loss,
                    contributing=contributing,
                    sample_question=rollouts[best].question,
                    sample_completion=rollouts[best].completion,
                    sample_reward=rewards[best],
                )
            )
            logger.info(
                "iter %d: mean reward %.3f, accuracy %.1f%%", it, history[-1].mean_reward, 100 * history[-1].accuracy
            )
            await _publish_report(history, task, num_iterations, "running", base_eval)

            if cp is not None:
                state = {
                    "iteration": it,
                    "adapter_version": adapter_version,
                    "adapter_path": adapter.path,
                    "history": [vars(m) for m in history],
                    "base_eval": vars(base_eval),
                }
                await cp.save(json.dumps(state).encode())

    # Act 3: same held-out problems, trained model.
    with flyte.group("eval-final"):
        final_eval = await evaluate(
            base, task, cfg.max_new_tokens, adapter, adapter_version, sample_index=base_eval.sample_index
        )

    # Act 4: a person decides whether this skill's model ships. The GPUs are not held while the run waits:
    # the warm replicas keep serving the other runs, and scale down once every run is idle.
    await _publish_report(history, task, num_iterations, "review", base_eval, final_eval)
    if not await _review(task, base_eval, final_eval):
        await _publish_report(history, task, num_iterations, "rejected", base_eval, final_eval)
        raise RuntimeError(f"The {task} model was rejected in review; nothing was published.")

    # Approved: merge the adapter into the base weights and publish the model artifact.
    model = await merge_adapter(base, adapter)
    await _publish_report(history, task, num_iterations, "complete", base_eval, final_eval)
    return await _as_model_artifact(model, task, base_eval.accuracy, final_eval.accuracy)

Things to notice:

  • Calling a task is an await. await generate(...) runs on a rollout replica and returns the result. asyncio.create_task runs two chunks in parallel, which is what makes the rollout pool scale to its second replica.
  • Scoring overlaps generation. Each chunk is scored as soon as it arrives, while the other chunk is still generating.
  • Checkpoints. After every iteration the driver saves where it is and where the latest adapter lives. See What happens when something fails.
  • Report. report=True gives the task a live HTML page. report_helpers.py draws the reward curve and the before and after cards with no extra dependencies.
  • Groups. flyte.group("iter-3") folds each iteration’s tasks together in the run view.

6. Review the result

When the final eval is done, the run pauses on a condition. A condition is an action that waits for a value from outside the run, here a yes or no from a reviewer. The prompt is Markdown, so the reviewer sees the accuracy before and after and the same held-out problem answered by both models:

train.py
async def _review(task: str, base_eval: EvalResult, final_eval: EvalResult) -> bool:
    """Pause this run until a person approves or rejects the trained model. Returns True to publish."""
    approval = await flyte.new_condition.aio(
        f"approve-{task}",
        prompt=(
            f"## Publish the `{task}` model?\n\n"
            f"| | Held-out accuracy ({final_eval.num_problems} problems) |\n|---|---|\n"
            f"| Base model | {base_eval.accuracy:.0%} |\n"
            f"| After RL | {final_eval.accuracy:.0%} |\n\n"
            f"The same held-out problem, before and after:\n\n"
            f"```\n{final_eval.sample_question}\n```\n\n"
            f"Base model ({'correct' if base_eval.sample_correct else 'wrong'}):\n\n"
            f"```\n{base_eval.sample_completion[:1500]}\n```\n\n"
            f"After RL ({'correct' if final_eval.sample_correct else 'wrong'}):\n\n"
            f"```\n{final_eval.sample_completion[:1500]}\n```\n\n"
            f"Approve to merge the adapter and publish `{MODEL_ARTIFACTS[task]}`. "
            "The reward curves are in this run's report."
        ),
        prompt_type="markdown",
        data_type=bool,
        timeout=REVIEW_TIMEOUT,
    )
    approved = await approval.wait.aio()
    logger.info("review %s: %s", task, "approved" if approved else "rejected")
    return approved

Each run creates its own condition, named after its skill (approve-json, approve-countdown), so the two runs are reviewed separately. A reviewer can approve the JSON model the moment it finishes while the countdown run is still training.

While a run waits, it holds only its 1-CPU driver. The shared GPU replicas keep serving the other run, and once no run is using them they scale down on their own.

If the reviewer rejects the model, the run fails with a message and publishes nothing. If nobody answers within REVIEW_TIMEOUT (24 hours), wait raises flyte.errors.ConditionTimedoutError and the run also ends without publishing.

To review, open the run in the Union.ai UI and answer the condition there, or use review.py, which finds the pending condition on a run and signals it with flyte.remote:

review.py
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("run_name")
    decision = parser.add_mutually_exclusive_group(required=True)
    decision.add_argument("--approve", action="store_true")
    decision.add_argument("--reject", action="store_true")
    args = parser.parse_args()

    flyte.init_from_config(root_dir=pathlib.Path(__file__).parent)
    pending = [c for c in flyte.remote.Condition.listall(run_name=args.run_name) if c.name.startswith("approve-")]
    if not pending:
        raise SystemExit(f"Run {args.run_name} has no review waiting. Is it still training?")
    for condition in pending:
        condition.signal(args.approve)
        print(f"{condition.name}: {'approved' if args.approve else 'rejected'}")

See External conditions for the CLI and the other payload types.

7. Publish the model

An approved adapter is merged into the base weights, which produces an ordinary checkpoint that any server can load with no adapter handling:

train.py
@train_env.task
async def merge_adapter(base: flyte.io.Dir, adapter: flyte.io.Dir) -> flyte.io.Dir:
    """Merge the LoRA into the base: a plain HF checkpoint that vLLM can stream with no adapter overhead."""
    import torch
    from peft import PeftModel
    from transformers import AutoModelForCausalLM, AutoTokenizer

    local_base = await _local_dir(base.path)
    model = AutoModelForCausalLM.from_pretrained(local_base, dtype=torch.bfloat16)  # CPU is plenty
    merged = PeftModel.from_pretrained(model, await adapter.download()).merge_and_unload()
    out_dir = tempfile.mkdtemp(prefix="merged-")
    merged.save_pretrained(out_dir, safe_serialization=True)  # weights + config + generation_config
    AutoTokenizer.from_pretrained(local_base).save_pretrained(out_dir)  # chat template included
    return await flyte.io.Dir.from_local(out_dir)

The driver returns it wrapped as a model artifact, with a model card holding the accuracy numbers:

train.py
async def _as_model_artifact(model: flyte.io.Dir, task: str, base_accuracy: float, final_accuracy: float) -> Any:
    """Wrap a merged model Dir so the run publishes it as ``MODEL_ARTIFACTS[task]``, with a model card.

    The task returning it must be declared with ``produces_artifacts=True``; without that flag the backend
    ignores the metadata and silently records no artifact.
    """
    from flyte import artifacts

    summary = (
        f"# {MODEL_ARTIFACTS[task]}\n\n"
        f"`{BASE_MODEL_REPO}` trained with GRPO + LoRA (rank {LORA_RANK}) on the `{task}` task, "
        f"adapter merged into the base weights.\n\n"
        f"| | Held-out accuracy ({EVAL_SIZE} problems) |\n|---|---|\n"
        f"| Base model | {base_accuracy:.0%} |\n| After RL | {final_accuracy:.0%} |\n\n"
        f"System prompt used in training:\n\n```\n{tasks.SYSTEM_PROMPTS[task]}\n```\n"
    )
    card = None
    try:
        card = await artifacts.Card.create_from.aio(content=summary, format="md", card_type="model")
    except Exception as e:  # noqa: BLE001 - the artifact is still useful without its card
        logger.warning("Could not upload model card: %s", e)

    metadata = artifacts.Metadata.create_model_metadata(
        name=MODEL_ARTIFACTS[task],
        description=f"{BASE_MODEL_REPO} RL-trained on {task}: {base_accuracy:.0%} -> {final_accuracy:.0%}",
        card=card,
        framework="huggingface",
        model_type="qwen2",
        architecture="Qwen2ForCausalLM",
        task="text-generation",
        attrs={
            "base_model": BASE_MODEL_REPO,
            "rl_task": task,
            "base_accuracy": f"{base_accuracy:.4f}",
            "final_accuracy": f"{final_accuracy:.4f}",
        },
    )
    return artifacts.new(model, metadata)

The task must be declared with produces_artifacts=True. Without it the run succeeds and no artifact is recorded.

8. Launch one run per skill

train.py
def _base_model() -> Any:
    """The prefetched base model artifact; prefetch it on first use."""
    import flyte.prefetch
    import flyte.remote

    existing = next(iter(flyte.remote.Artifact.listall(name=BASE_ARTIFACT, limit=1)), None)
    if existing is not None:
        return existing
    run = flyte.prefetch.hf_model(repo=BASE_MODEL_REPO, hf_token_key=None)  # public repo, no HF token
    print(f"Prefetching {BASE_MODEL_REPO}: {run.url}")
    run.wait()
    return flyte.remote.Artifact.get(BASE_ARTIFACT)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        "--task",
        choices=(*tasks.TASKS, "all"),
        default="countdown",
        help="skill to train; 'all' launches one run per skill, sharing the same warm GPU replicas",
    )
    parser.add_argument("--iterations", type=int, default=0, help="GRPO iterations (default: per-task)")
    args = parser.parse_args()

    flyte.init_from_config(root_dir=pathlib.Path(__file__).parent)
    base_model = _base_model()
    for skill in tasks.TASKS if args.task == "all" else (args.task,):
        run = flyte.run(train_rl, base=base_model, skill=skill, num_iterations=args.iterations)
        print(f"{skill}: {run.url}")
        print(f"  when it pauses for review: approve in the UI, or python review.py {run.name} --approve")

--task all submits one run per skill without waiting between them. Each run has its own driver, report, checkpoint, review, and artifact. They share the rollout, reward, and trainer replicas.

What happens when something fails

A long RL run sees failures, and on shared replicas a failure must not take the other run down with it. The example handles each case in a specific place:

What fails What happens
The driver’s container is preempted The platform reschedules the driver, without using the task’s retries. The new attempt loads the last checkpoint and continues from the next iteration with the same adapter, history, and base eval. Problems are generated from the iteration number, so the resumed run sees the same problems it would have. See Durable training
The vLLM engine process crashes generate clears the cached engine before it raises, and its retries=2 runs the call again on a freshly built engine instead of handing the dead one to the other run
A train_step fails halfway through The step marks the in-memory adapter as unpublished before it starts, so its retry (retries=2) reloads the adapter it was given instead of training on top of half-updated weights
A replica is lost The next call lands on another replica, which loads the base model and the adapter from object storage. Nothing is stored only on a replica’s disk

Distributed and autoscaled

Nothing in the loop says how many machines it runs on. That is set by the environments:

  • Rollouts scale between one and two GPU replicas (replicas=(1, ROLLOUT_CHUNKS)). Each iteration splits its problems into two generate calls that run in parallel, so a single run already scales the pool to its second replica, and with two runs active, calls queue for the two replicas. When the runs go quiet, idle replicas shut down after scaledown_ttl, and the whole pool after idle_ttl.
  • Scoring runs on one CPU replica that takes eight calls at a time.
  • Training is one GPU replica that holds both skills. The runs take turns on the GPU, which is the point: one L4 holds the base model once instead of once per run.
  • Serving scales per model, from zero replicas when nobody is using a model to two under load.

To train more skills at once, raise the rollout pool’s maximum replicas. For bigger models, change the L4 resources to a larger GPU. The driver code does not change in either case.

Serve and compare

serve.py deploys one vLLM app per model. Each is bound to an artifact by name, and the weights stream from object storage straight into GPU memory:

serve.py
base_worker = VLLMAppEnvironment(
    name="rl-demo-base",
    model_id="base",
    model_path=flyte.app.ArtifactValue(name=BASE_ARTIFACT, type="directory"),
    image=DEFAULT_VLLM_IMAGE,
    # bf16 needs compute capability >= 8.0; L4 is the cheapest GPU that qualifies, and a 1.5B model
    # leaves most of its 24GB for KV cache.
    resources=flyte.Resources(cpu="4", memory="16Gi", gpu="L4:1", disk="20Gi"),
    stream_model=True,
    extra_args=["--max-model-len", "4096", "--enable-prefix-caching", "--gpu-memory-utilization", "0.90"],
    scaling=MODEL_SCALING,
    requires_auth=True,
)

rl_workers = {
    task: base_worker.clone_with(
        name=f"rl-demo-rl-{task}",
        model_id=f"rl-{task}",
        model_path=flyte.app.ArtifactValue(name=MODEL_ARTIFACTS[task], type="directory"),
    )
    for task in tasks.TASKS
}

A model that was rejected in review has no artifact, so serve only the approved ones with python serve.py --tasks json.

Every model app autoscales on the number of requests in flight and scales to zero when idle:

serve.py
# Each model: no replicas while idle, a second replica when one is handling more than 16 requests at once,
# and back to zero 10 minutes after the last request.
MODEL_SCALING = flyte.app.Scaling(
    replicas=(0, 2),
    metric=flyte.app.Scaling.Concurrency(16),
    scaledown_after=timedelta(minutes=10),
)

The first request to a model that has scaled to zero waits for a replica to start. For a live demo, set MODEL_SCALING to Scaling(replicas=(1, 1)) beforehand and put it back afterward.

The chat app (chat_ui.py) sends the same prompt to two models and grades both answers with the same checker used in training, so you see a pass or fail badge next to each.

What to expect

Both runs were launched together with python train.py --task all on a Union.ai cluster with L4 GPUs. Accuracy is greedy decoding on the 100 held-out problems. Run time covers training only, not the time a run waits for its review.

Skill Iterations Base model After RL Run time
json 30 5% 92% 31 min
countdown 60 6% 26% 48 min

The same skills trained one at a time ended at 94% and 25% to 29%, so sharing the replicas did not cost accuracy. Your numbers differ by a few points from run to run.

JSON extraction is mostly a formatting and attention problem, and the model learns it almost completely. Countdown needs search and arithmetic, which a 1.5B model improves at more slowly. More iterations or a larger base model move it further.

Make it yours

Add a third skill

A skill is a problem generator, a system prompt, and a reward. To add one:

  1. In tasks.py, add its name to TASKS, its system prompt to SYSTEM_PROMPTS, a branch in make_problem that returns (user_message, answer_json), and a branch in score that returns (reward, formatted, correct).
  2. In train.py, add an entry to TASK_CONFIG with the iteration count and the maximum answer length.
  3. For the chat UI, add a branch in tasks.verdict and a few entries in tasks.PRESETS.

python train.py --task all then starts three runs, each with its own review. The trainer’s concurrency, the artifact names, and the serving apps follow tasks.TASKS, so nothing else changes. Check the base model’s accuracy on the first report card before a long run: if the base already scores above about 30%, make the problems harder.

Change the reward: RLVR, RLHF, or a judge

score_chunk is the only place the loop learns what “good” means. Keep its signature, a list of rollouts in and a list of numbers out, and change what is inside.

For RLHF with a reward model trained on human preferences, give the reward its own GPU environment and keep the model warm the same way the rollout engine is. This sketch shows the shape and is not part of the tested example:

reward_env = flyte.TaskEnvironment(
    name="rl-demo-reward",
    image=image,
    resources=L4,
    reusable=flyte.ReusePolicy(replicas=1, concurrency=1, idle_ttl=600),
)


@alru_cache(maxsize=1)
async def _load_reward_model(uri: str) -> Any: ...  # load your preference model once per warm replica


@reward_env.task
async def score_chunk(task: str, rollouts: list[Rollout]) -> list[float]:
    model = await _load_reward_model(REWARD_MODEL_URI)
    return model.score([(r.question, r.completion) for r in rollouts])

For a judge model, score_chunk calls a served LLM with a rubric and parses a score from the reply. For direct human ratings, the task reads the ratings your labeling tool stored for those rollouts. In every case the driver, the trainer, and the rollout engine stay as they are.

Whatever the source, scale rewards to a small range and give partial credit where you can. GRPO only looks at differences within a group, so a group where every answer gets the same reward teaches nothing.

Change the review

The review is a bool condition, but a condition can also return an int, float, or str. A str condition could collect the reviewer’s notes and put them in the model card. A float condition could ask for a minimum accuracy and publish only above it. To skip human review for a skill, replace the _review call with a check on final_eval.accuracy.

Knobs

Setting Where Effect
PROMPTS_PER_ITER, GROUP_SIZE train.py Rollouts per iteration. More is a steadier gradient and a slower iteration
LEARNING_RATE train.py Raise it if the reward curve is flat. Lower it if the curve climbs and then collapses
LORA_RANK train.py Adapter capacity. Also sets max_lora_rank for the vLLM engine
rollout_env replicas train.py Raise the maximum if rollouts from several runs queue up
MICRO_BATCH train.py Sequences per backward pass. Lower it if the trainer runs out of GPU memory
REVIEW_TIMEOUT train.py How long a finished run waits for a reviewer
MODEL_SCALING serve.py Replicas per served model and when to add one
Environment name train.py Give a run its own replicas by giving its reusable environments a distinct name

Isolating runs

Sharing replicas is what makes several runs cheap, and it means the code inside a replica cannot assume it serves one run. This example keys all cached state by skill or by adapter path for that reason. If you would rather give each run private replicas, for example to compare two learning rates for the same skill at the same time, give each run’s reusable environments a distinct name. Reusable containers are shared by environment name and version, whatever the ReusePolicy scope. Two concurrent runs of the same skill on shared replicas would otherwise take turns evicting each other’s adapter from the trainer.

Troubleshooting

Symptom Cause
The run shows as running but nothing is happening It is waiting for its review. Approve or reject it on the run page or with review.py
review.py says the run has no review waiting The run has not reached its final eval yet
The run finishes and no model artifact appears The model was rejected or the review timed out, or the task is missing produces_artifacts=True
serve.py fails to find an artifact That skill’s model was not approved. Pass only approved skills with --tasks
EngineDeadError from generate The vLLM engine process crashed. Its own traceback is earlier in the same log. The replica drops the dead engine and the next call rebuilds it
OverflowError: ... out of bounds for int32 in the engine log A lora_int_id larger than 2³¹ − 1
GPU tasks wait for resources for a long time No L4 node is available. The memory request is 24Gi so the task fits a single-L4 node
Reward stays near zero The reward has no partial credit, or the problems are too hard for the base model to ever get right
Format rate reaches 100% and accuracy falls The model found a shortcut in the reward. The countdown reward requires reasoning in <think> for this reason

Files

File Role
tasks.py Problem generators, system prompts, rewards, held-out eval set, chat presets
train.py Environments, rollouts, reward, trainer, driver loop, review, artifact publishing
review.py Approve or reject a run’s review from the terminal
serve.py One autoscaling vLLM app per model bound to its artifact, plus the chat app
chat_ui.py Side-by-side Gradio chat with pass or fail grading
report_helpers.py The live training report