Repository navigation
AsyncGRPOTrainer with fast_inference: train and generate on one GPU with shared weights - #13292
Conversation
# Conflicts: # tests/test_async_grpo_patch.py
…eep LoRA-only training
… and tool-less templates TRL does not know)
…hat already exited
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| try: | ||
| row = next(iter(dataset)) | ||
| except Exception: | ||
| return False |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if kwargs.get("weight_transfer") is not None or kwargs.get("rollout_worker") is not None: | ||
| return False |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| for name in ("temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"): | ||
| if body.get(name) is not None: | ||
| params[name] = body[name] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…hema that maps the text to content
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…he self-test (stock TRL with unsloth imported)
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| except Exception as error: | ||
| logger.info( | ||
| f"Unsloth: could not check packed rows on `{type(backbone).__name__}`: {error}" | ||
| ) | ||
| return |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
|
||
| def _dataset_has_images(dataset): | ||
| try: | ||
| row = next(iter(dataset)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…thout iterating the dataset
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
TRL's
AsyncGRPOTrainer(TRL 1.14+) now runs with a model loaded withfast_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
AsyncGRPOTrainercarries Unsloth's vLLM engine, a small HTTP server starts on127.0.0.1inside the trainer process. It implements the endpoints TRL's rollout worker andVLLMClientuse (/v1/completionswith token ids,/v1/load_lora_adapter,/v1/unload_lora_adapter,/pause,/resume,/server_info,/health, ...).args.vllm_server_base_urlis pointed at it, and TRL's rollout process is unchanged.add_request/step); HTTP handlers only enqueue and wait.max_inflight_tasksdefaults to the engine'smax_num_seqswhen TRL's row-based default is left in place.trl-policy-vNadapter TRL saves is loaded through Unsloth'sload_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.UNSLOTH_VLLM_STANDBY) is woken once and kept awake, since async GRPO generates while it trains.target_parametersadapters; MoE expert LoRA is allowed through that check only when the in-process server is active.[4, B, T]position ids mRoPE models need), else a clear error.Results (B200, TRL 1.15.0, vLLM from the Unsloth stack)
tools=tools=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=andenvironment_factory=reaches the same tool-use reward range as stock TRL.TRL 1.13 and older have no PEFT support in
AsyncGRPOTrainerand are refused with a message. Not supported withfast_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 ownVLLMClient).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.