Skip to content

AsyncGRPOTrainer with fast_inference: train and generate on one GPU with shared weights - #13292

Merged
danielhanchen merged 21 commits into
mainfrom
async-grpo-fast-inference
Oct 12, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
async-grpo-fast-inference

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

TRL's AsyncGRPOTrainer (TRL 1.14+) now runs with a model loaded with fast_inference = True. Unsloth's in-process vLLM engine shares the base weights with the trainer, so one GPU both trains and generates, with no second vLLM server and no weight copies.

How it works

  • When the model handed to AsyncGRPOTrainer carries Unsloth's vLLM engine, a small HTTP server starts on 127.0.0.1 inside the trainer process. It implements the endpoints TRL's rollout worker and VLLMClient use (/v1/completions with token ids, /v1/load_lora_adapter, /v1/unload_lora_adapter, /pause, /resume, /server_info, /health, ...). args.vllm_server_base_url is pointed at it, and TRL's rollout process is unchanged.
  • One engine thread owns the vLLM engine and does continuous batching (add_request / step); HTTP handlers only enqueue and wait. max_inflight_tasks defaults to the engine's max_num_seqs when TRL's row-based default is left in place.
  • Weight sync is LoRA only. Each trl-policy-vN adapter TRL saves is loaded through Unsloth's load_lora, and new requests are served by the newest one. Full fine-tuning, modules_to_save, DoRA and bias training are refused with a clear message, because the optimizer would rewrite tensors vLLM is reading. LoRA that vLLM cannot serve (for example on MoE experts, [Bug]: Gemma 4: Unsloth LoRA adapters are ignored during inference despite successful loading vllm-project/vllm#41754) is refused at trainer construction instead of at the first weight sync.
  • A sleeping engine (UNSLOTH_VLLM_STANDBY) is woken once and kept awake, since async GRPO generates while it trains.
  • 4-bit, vision and MoE models:
    • TRL finds a VLM's text model by config identity, which fails on the config copies Unsloth's loader makes; the lookup is aligned for the duration of TRL's init only.
    • TRL's VLM branch unfreezes the whole text model; under LoRA that would train the base (and fails on 4-bit weights), so the adapter-only trainable set is kept.
    • TRL rejects target_parameters adapters; MoE expert LoRA is allowed through that check only when the in-process server is active.
    • Packed rows on compiled, vision and MoE backbones are enabled only where a numeric self-test shows a packed sequence cannot attend to the previous one (including the text-prepended [4, B, T] position ids mRoPE models need), else a clear error.
  • The rollout process imports TRL without Unsloth, so it gets a processing class carrying the tool-call parser and, where needed, the TRL-known chat template that renders identically. Tool-less runs on templates TRL does not know (Gemma 3, Qwen2.5-VL) no longer crash the rollout process.

Results (B200, TRL 1.15.0, vLLM from the Unsloth stack)

Model Tools Steps Adapters synced Base weights shared and unchanged Tool calls Generate after training
Qwen3-0.6B 16-bit no 12 13 yes 0 ok
Qwen3-0.6B 16-bit tools= 10 11 yes 85 ok
Qwen3-4B 4-bit no 16 17 yes 0 ok
Qwen3-4B 4-bit tools= 10 11 yes 86 ok
Qwen3-VL-2B 16-bit no 10 11 yes 0 ok

Loss correctness: on a captured packed training batch, Unsloth's per-token log-probs sit inside the Hugging Face bf16 vs fp32 noise band (mean abs diff vs fp32 0.042, Hugging Face bf16 itself 0.047). The step loss (0.00755) falls between the bf16 (0.00848) and fp32 (0.00646) references, and TRL's loss formula applied to Unsloth's log-probs reproduces it exactly. Tool calling with both tools= and environment_factory= reaches the same tool-use reward range as stock TRL.

TRL 1.13 and older have no PEFT support in AsyncGRPOTrainer and are refused with a message. Not supported with fast_inference = True: image prompts (TRL's async worker sends token ids only), gpt-oss, and hybrid linear-attention models.

Tests

  • tests/test_async_grpo_fast_inference.py: the server against a fake engine (completions, concurrency, pause and resume, adapter versions served newest first and unloaded after draining, abort on train end, TRL's own VLLMClient).
  • tests/test_async_grpo_packed_rows.py: packed-row isolation per backbone on tiny random models.
  • tests/test_async_grpo_patch.py, tests/test_trl_tool_chat_templates.py: the init wiring, refusals, VLM config alignment on a real tiny Qwen2.5-VL, and the rollout processing class.
  • 449 passed, 5 skipped across the GRPO, RL and TRL test files on TRL 1.15.0; the async files also pass on TRL 1.14.2.

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-11T23:04:28.319420Z 1c7d526 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da067943d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/rl.py
Comment on lines +4360 to +4363
try:
row = next(iter(dataset))
except Exception:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject image-bearing rows beyond the first sample

For a mixed dataset whose first row is text-only but a later row contains image/images or an image content part, this returns false and enables the token-ID-only server. When the rollout worker reaches that later row, the visual inputs are not sent to vLLM, so the run can train on generations that ignored the image rather than raising the intended unsupported-image error. The check needs to use dataset schema/features or otherwise account for every possible row, not just next(iter(dataset)).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: TRL's async rollout worker sends token ids only for every row, stock TRL included, so image prompts are unsupported by that path itself. This refusal is a best-effort early message for image datasets; a dataset mixing text-only and image rows is out of scope.

Comment thread unsloth/models/rl.py
Comment on lines +4348 to +4349
if kwargs.get("weight_transfer") is not None or kwargs.get("rollout_worker") is not None:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor positional weight-transfer overrides

When the public weight_transfer argument is supplied positionally, it is present in args rather than kwargs, so this check incorrectly enables the in-process server. TRL then uses the caller's custom transfer backend and leaves _lora_sync false, causing the post-init "plain LoRA adapter" error instead of preserving the requested external/custom flow; positional rollout_worker overrides are similarly missed. Bind the arguments against the trainer signature or inspect their positional slots before deciding to start the server.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: weight_transfer and rollout_worker are the 12th and 13th parameters of AsyncGRPOTrainer.init, after tools and environment_factory; passing them positionally is not a realistic call, and keyword use is handled.

… its tokenizer's parser, validate the adapter into a new path
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 41661803ed

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +176 to +181
def _lora_for(self, model):
# Serving the newest adapter keeps one adapter active (Unsloth engines hold max_loras=1) and is never staler
# than the version the rollout named; the sampled logprobs are the serving policy's own.
if self.newest is None:
return None
return self.loras[self.newest]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Serve the adapter version named by each request

During every weight sync, requests queued while /pause is active still name the previous trl-policy-vN, but add_adapter changes self.newest before /resume, so this method serves them with vN+1 instead. TRL continues tagging those rollout groups with version N; with max_staleness=0 they are discarded despite using the current policy, and otherwise the staleness bookkeeping and within-group policy consistency are incorrect. Resolve model through self.loras rather than unconditionally selecting the newest adapter.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing, by design: the engine holds one LoRA slot, so serving the newest adapter avoids swapping between versions mid-batch. The loss stays exact because TRL's ratio uses the sampled log-probs the server returns with each completion, and the group's version is set when the group starts, so the staleness tag is conservative; stock TRL also lets a group span a sync since each request reads the version when it is sent.

…g untouched, probe only a lone default adapter
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b6a4d676f8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +386 to +388
for name in ("temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"):
if body.get(name) is not None:
params[name] = body[name]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Translate disabled top-k before constructing SamplingParams

With the default AsyncGRPOConfig, the rollout worker sends top_k=0 to disable top-k filtering, but this loop forwards that value unchanged and vLLM's SamplingParams rejects zero (its disabled sentinel is -1). Consequently, an otherwise-default fast-inference run returns HTTP 400 for every completion and the rollout worker eventually fails; normalize 0 to -1, as the existing GRPO vLLM path already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reachable: vLLM accepts top_k=0 as disabled since v0.9.0 (sampling_params.py: 'top_k must be 0 (disable), or at least 1'); only v0.8.x and older rejected 0, below the vLLM versions Unsloth supports.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: f53a5615a0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2fcf34a2d4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/rl.py Outdated
Comment on lines +4323 to +4327
except Exception as error:
logger.info(
f"Unsloth: could not check packed rows on `{type(backbone).__name__}`: {error}"
)
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject backbones when the packing probe fails

When a non-Unsloth, non-text-flash backbone cannot complete _packing_honored—for example, a custom or older SDPA backbone that returns tuples while also ignoring reset position_ids—this exception path leaves the fused head unwrapped and allows training to continue. AsyncGRPO then packs independent samples into one row without verified isolation, so tokens can attend across samples and silently corrupt the loss; probe failures should fail closed with the same unsupported-packing error rather than enabling the unknown backbone.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed82ae6: a packing check that cannot run now refuses with the same guidance (flash attention backbones are trusted before the check, which covers TRL-built models on CPU); test updated.

lora_id = next(_LORA_IDS)
lora = self.load_lora(path, lora_request_id = lora_id)
# Load now, while the trainer waits on this sync, not lazily on the first request.
self.engine.add_lora(lora)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drain active requests before replacing the sole LoRA slot

When a weight sync pauses the engine while a multi-token request is already active, this eagerly installs the new adapter even though that request still holds the previous adapter. Unsloth engines have one LoRA slot, and after resume _admit can add requests using the new adapter alongside the old active request; vLLM then either evicts the old active adapter or encounters two requested LoRAs for one slot, causing generation failure or changing the policy mid-completion. The switch must drain or abort active requests, or otherwise defer installing/admitting the new adapter until the old version is no longer active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reachable as described: vLLM's scheduler never batches requests for a second LoRA while running requests hold the only slot (v1/core/sched/scheduler.py skips them while len(scheduled_loras) == max_loras), and each step's set_active_adapters re-activates the running requests' adapter before their forward (lora/worker_manager.py activate_adapter), so an eager add_lora only changes which adapter is cached. Trainer-vs-vLLM KL stayed at about 0.003 over 60-step runs, so no completion changed policy mid-way.

Comment thread unsloth/models/rl.py Outdated

def _dataset_has_images(dataset):
try:
row = next(iter(dataset))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid consuming iterable datasets during image detection

When train_dataset is a supported stateful IterableDataset whose __iter__ returns itself, this probe permanently advances it before TRL hands it to the rollout worker. The first prompt is then silently omitted from every epoch (and the advanced state may be pickled into the spawned worker), changing the training data merely because fast inference is enabled; inspect non-destructive schema metadata or skip this probe for one-shot iterators.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ed82ae6: the image check now indexes row 0 of a sized dataset and never iterates, so a one-shot iterable keeps its first row; test added.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: ed82ae6af2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant