Skip to content

feat(sglang): enable NeMo-Gym async-GRPO rollouts on the SGLang backend - #3127

Open
Kh4L wants to merge 28 commits into
NVIDIA-NeMo:mainfrom
Kh4L:sglang-gym-enablement
Open

Kh4L wants to merge 28 commits into
NVIDIA-NeMo:mainfrom
Kh4L:sglang-gym-enablement

Conversation

@Kh4L

@Kh4L Kh4L commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

What

Enable NeMo-Gym rollouts in async GRPO with the SGLang generation backend.

  • Make the generation handle safe to serialize into the trajectory collector without transferring ownership of the driver's engines, router or health monitor.
  • Expose the stable router endpoint and normalize Gym URLs through the shared actor factory, for both single and sharded Gym deployments.
  • Select SGLang's async rollout and refit paths and resolve context limits from the active backend.
  • Make memory-saver tag transitions idempotent and reconcile replacement engines before refit.

Main refresh

Earlier refresh 5e193cd591fc1145d882b56e2559c0f346f125b8 merges main efc309512601fef2a219c47240651ec130f2709b.

The resolution preserves both the SGLang URL-normalization regression and main's new Environment Server routing/cleanup tests. All 96 upstream Gym definitions and all 101 upstream helper-test definitions remain present. The intended SGLang backend selection, runtime dispatch and lifecycle changes are retained alongside the Environment Server implementation.

#3613 is merged and supplies rollout fault tolerance. #3063 remains an independent truncation change; #3614/#3615 are a separate quantization stack.

Validation

  • 294 normal-import CPU tests pass: 246 Gym helper, task-input and shard cases, plus 48 focused SGLang fault-tolerance, memory-lifecycle and serialization cases. Three optional Gym-package cases are excluded from the local CPU run.
  • The factory regression covers every backend argument with both single and sharded deployments, including caller-config preservation.
  • Repository-pinned Ruff 0.9.9 lint/import sorting and formatting, syntax and feature diff checks pass across all 19 Python feature files.
  • Source comparison verifies that the new Environment Server helpers and tests survive the merge.

These are supplementary macOS CPU checks with project conftest/config disabled. Native engine/Ray integration tests need the Linux/CUDA environment; they are not claimed as passed here. Full project CI was requested for that revision.

Matched sync and async Gym benchmark on GB200

Qwen3-0.6B on Workplace Assistant completed 20 GRPO steps in each mode, with four prompts and two completions per prompt (160 samples per run). Both runs used seed 42, temperature 1, top-p 1, a 768-token output cap, two TP1 SGLang engines and two Megatron training GPUs (global batch 8, microbatch 1). The recipe files differ only in grpo.async_grpo.enabled. Async used a maximum trajectory age of one step and drained outstanding rollouts before refit.

Measured across 20 steps Sync Async
Total tokens 48,202 48,251
Sum of training-step times 74.15 s 36.90 s
Total tokens / total step time, four GPUs 650 tokens/s 1,308 tokens/s
Median step time 2.60 s 1.32 s
Mean reward 0.15 0.15
Steps with nonzero gradient norm 0/20 0/20

Async processed 2.01× as many tokens per timed training second on this workload. The async refit interval, including draining the collector and updating weights, totaled 6.04 s across 20 steps (16.4% of step time, median 0.123 s). Sync has no asynchronous collector to drain. Its weight-transfer timer alone had a median of 0.118 s.

The measurements come from separate jobs, each on four GB200s. Step timers exclude job startup and the async collector starts before step 1. Both modes produced identical rewards within every prompt group, so all advantages, losses and gradient norms were zero. These runs exercise rollout, replay, training and refit. Learning quality needs a workload with within-group reward variation.

xychart-beta
    title "Mean rollout reward in both modes (identical at all 20 steps)"
    x-axis "GRPO step" 1 --> 20
    y-axis "Reward" 0 --> 0.5
    line [0, 0, 0.25, 0, 0.25, 0.25, 0.25, 0.5, 0, 0, 0, 0.25, 0.5, 0, 0, 0, 0.25, 0, 0.25, 0.25]
Loading
xychart-beta
    title "Throughput by step (lower curve sync, upper curve async)"
    x-axis "GRPO step" 1 --> 20
    y-axis "Total tokens per second" 0 --> 2000
    line [104, 675, 794, 969, 942, 1040, 964, 941, 968, 905, 865, 914, 898, 784, 1010, 877, 1067, 829, 982, 954]
    line [287, 1869, 999, 1940, 1608, 1836, 1365, 1877, 1295, 1920, 1299, 1844, 1784, 1034, 1856, 1863, 1785, 1876, 1829, 1870]
Loading

The benchmark ran NeMo-RL 442c0d6bc56b6aeabb56300b2e798739f3faaf32 with Gym 666aee20392b58b580e241fa830c5de167546b9d and Qwen3-0.6B snapshot c1899de289a04d12100db370d81485cdf75e47ca. Only three test files changed between the tested source and PR head 993247154261b74477c50097270a4ff66b77e866. The bare-metal async collector and replay buffer used the Megatron-capable Python environment to deserialize tensors. Sync job 9194076 and async job 9206913.

Earlier integration evidence

HSG job 6595733 completed 0:0 on two nodes / eight GB200 GPUs: Qwen2.5-Math-1.5B, four-GPU Megatron training, four TP1 SGLang engines and stateful multi-turn Gym async GRPO.

The validated stacked source was #3063 60140cd23496d80c3ae04cd3a5fc276c38d44a60, containing #3127 0ce9be27fb8528e54b9a968530503cba7336653e. It used SGLang 0.5.17.dev30+g3003d70f6 and Gym 022a07a2ef1f1bd65ee0e9b06fe1fc9a3613cb55. The strict validator passed three optimizer steps, four refits and 24 trainable four-turn trajectories, with nonzero reward variance and gradients on optimizing steps and clean teardown.

This historical run predates the current main refresh; it does not validate the current head or current Gym adapter.

Related: NVIDIA-NeMo/Gym#1787, #3063.

@copy-pr-bot

copy-pr-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 8388bdf

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from 8388bdf to ea9f964 Compare August 27, 2026 07:37
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@copy-pr-bot

copy-pr-bot Bot commented Aug 27, 2026

Copy link
Copy Markdown

/ok to test

@Kh4L, there was an error processing your request: E1

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/1/

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ea9f964

@Kh4L Kh4L added the CI:L1 Run doctests, unit tests, and functional tests label Aug 27, 2026
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ea9f964

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from ea9f964 to d870793 Compare August 27, 2026 11:17
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@copy-pr-bot

copy-pr-bot Bot commented Aug 27, 2026

Copy link
Copy Markdown

/ok to test

@Kh4L, there was an error processing your request: E1

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/1/

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from d870793 to 7283095 Compare August 27, 2026 12:01
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 7283095

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test bdea1e5

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from bdea1e5 to 0acca43 Compare August 27, 2026 14:46
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@copy-pr-bot

copy-pr-bot Bot commented Aug 27, 2026

Copy link
Copy Markdown

/ok to test

@Kh4L, there was an error processing your request: E1

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/1/

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0acca43

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from 0acca43 to 0ce9be2 Compare August 27, 2026 14:55
@copy-pr-bot

copy-pr-bot Bot commented Aug 27, 2026

Copy link
Copy Markdown

/ok to test 0ce9be27f9710d693760651f2b7eb8c5f03401a2

@Kh4L, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 0ce9be2

@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Exact stacked hardware validation passed.

  • HSG job 6595733: COMPLETED 0:0, 2 nodes / 8 GB200 GPUs
  • Exact source: feat(nemo-gym): opt-in truncation of non-contiguous rollout episodes #3063 60140cd23496d80c3ae04cd3a5fc276c38d44a60, containing this head 0ce9be27fb8528e54b9a968530503cba7336653e
  • Qwen2.5-Math-1.5B: 4-GPU Megatron training + four TP1 SGLang rollout engines
  • 3/3 optimizer steps, 4/4 refits, 24/24 trainable four-turn Gym trajectories
  • Reward variance and nonzero gradients on optimizing steps; clean teardown
  • SGLang 0.5.17.dev30+g3003d70f6; decode CUDA graphs enabled, prefill capture disabled

The PR body now contains the final validation details.

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from 0ce9be2 to d1b086b Compare August 27, 2026 16:45
@Kh4L

Kh4L commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d1b086b

@Kh4L

Kh4L commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Current head d1b086b6836e0b67cf54bef6b4a320cc9e000545 is a patch-equivalent restack. Its only content delta from HSG-validated 0ce9be27fb8528e54b9a968530503cba7336653e is the five inherited SGLang unit-test fixture declarations; job 6595733 still covers the runtime tree. Fresh CI is triggered on the exact head.

@Kh4L
Kh4L force-pushed the sglang-gym-enablement branch from d1b086b to 17075a1 Compare August 28, 2026 01:22
@Kh4L

Kh4L commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 17075a1

@fujial-code

Copy link
Copy Markdown
Contributor

/ok to test 06cea75

@fujial-code

fujial-code commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

CI follow-up: e221442 fixes the failure in L0_Unit_Tests_Sglang by obtaining SGLangGenerationWorker.ray_metadata.modified_class before constructing the worker in both context-length tests, matching the existing test_config.py pattern. The previous code attempted object.new on Ray’s ActorClass wrapper.

Local validation: 7 isolated pytest cases passed with the locked Ray 2.58.0 and the actual decorated worker class extracted from source (six corrected cases plus reproduction of the old constructor failure). This is not a full-import or GPU test run. Ruff lint/format, syntax checks on all 21 changed Python files, and git diff --check passed.

Main advanced 13 commits, exceeding the CI freshness limit of 10; 06cea75 merges main 8294dd2 without conflicts. Reviewed the overlapping Gym sampling, rollout and setup changes.

Current-head CI: lint and branch freshness checks passed. The test workflow is waiting for the test environment approval: https://github.com/NVIDIA-NeMo/RL/actions/runs/44229461168 . GitHub reports current_user_can_approve=false for the current account; an authorized automation or rl_maintainers reviewer must approve this deployment before tests can run. Release validation is still in progress: https://github.com/NVIDIA-NeMo/RL/actions/runs/44229461726 . This is not an all-green result.

The old-head patch coverage failure (64.49%, target 80%) remains pending verification after the SGLang lane completes successfully; no threshold, CI label, or tests were weakened. C5 still awaits matched sync/async hardware measurements; no benchmark jobs were submitted.

@yuki-97 yuki-97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for bringing NeMo-Gym async GRPO to SGLang; it fills a real gap in backend support.

Great to see the 2-node GB200 multi-turn Gym run posted in the description: it shows the intended setup clearly.

Scope: partial review at 06cea75. Every changed file has been reviewed except nemo_rl/algorithms/grpo.py, nemo_rl/models/generation/sglang/sglang_generation.py and nemo_rl/models/generation/sglang/sglang_worker.py, which have only had a first pass, so more comments may follow on those three. The comments below can be addressed and answered in the meantime.

Checked:

  • Serializing the handle into the collector — __getstate__ / _owns_runtime follows the existing VllmGeneration.__getstate__ and MegatronGeneration._owns_policy pattern, and the collector's copy needs none of the state it drops
  • Memory-tag tracking — no path changes engine memory outside _offloaded_memory_tags; resuming a resident tag does raise KeyError at the pinned SGLang, so sending only the transitions that change state is right
  • Max sequence length — choosing the backend first fixes SGLang reading an inherited vllm_cfg.max_model_len, and the one production caller of _postprocess_single_nemo_gym_group was updated

Remaining comments are on:

  • in_flight_weight_updates being silently ignored for SGLang, and the async GRPO docs that describe it
  • the SGLang router URL without /v1, and unreached fallbacks in the max sequence length resolver
  • CI coverage for async GRPO on SGLang, a nightly with curves, and whether NVIDIA-NeMo/Gym#1787 is required

nit

  • duplicated max sequence length resolvers and their naming
  • where to keep dedicated SGLang engines resident after validation and checkpointing
  • the hand-written sglang_cfg check in the NeMo Gym setup
  • a long comment in __init__

Generated by Claude Code (#4999 version)

"Async GRPO requires Megatron, or an async vLLM or TRT-LLM "
"Async GRPO requires Megatron, SGLang, or an async vLLM or TRT-LLM "
"generation engine. Set "
"policy.generation.use_async_rollouts=true (SGLang), "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No CI job runs async_grpo_train with SGLang.

grpo_sglang_async.sh is sync GRPO with async rollouts on colocated engines, and the async SGLang unit tests in test_grpo.py run against MagicMock(spec=SGLangGeneration) engines.

Suggest fix: replace grpo_sglang_async.sh with an async GRPO run that mirrors grpo_async_gym.sh on SGLang without Gym: policy.generation.colocated.enabled=false, grpo.async_grpo.enabled=true, loss_fn.use_importance_sampling_correction=true, and grpo.val_period below grpo.max_num_steps. Its existing run_test fast entry in L1_Functional_Tests_SGLang.sh:38 then covers it.

Comment on lines +140 to +143
# SGLang's memory-saver endpoints are not idempotent: resuming a tag
# that is already resident raises ``KeyError``. Async disaggregated
# rollout keeps engines resident between refits, so remember the
# driver-issued phase and only send transitions that change it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: this 4-line comment inside __init__ can be 2 lines, per comments-docstrings-and-docs.md (no 3+ line comment blocks inside function bodies).

Suggest fix:

Suggested change
# SGLang's memory-saver endpoints are not idempotent: resuming a tag
# that is already resident raises ``KeyError``. Async disaggregated
# rollout keeps engines resident between refits, so remember the
# driver-issued phase and only send transitions that change it.
# SGLang raises KeyError when resuming an already-resident tag, so track
# the released tags and only send transitions that change them.

Comment thread nemo_rl/experience/rollouts.py Outdated
)


def _resolve_generation_context_limit(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: _resolve_generation_context_limit duplicates _generation_max_seq_len in single_controller_utils/setup.py:850-865.

The two disagree when sglang_cfg.context_length is null: that one returns None, this one uses the limit reported by the engines.

Its docstring (rollouts.py:2714) and error message (rollouts.py:2743) also say "context limit" and "for NeMo-Gym", but the value is the backend's max sequence length and nothing in the lookup is Gym-specific.

Suggest fix:

  1. Keep one helper named resolve_generation_max_seq_len in interfaces.py:310-320 next to should_use_async_rollouts, with one rule for a null limit, and call it from both places.
  2. Word the merged helper in terms of max sequence length, without NeMo-Gym, and update the max_total_tokens_per_sample description at rollouts.py:3303 to match:
    """Resolve the active generation backend's max sequence length."""
    ...
    raise ValueError("Unable to resolve the generation max sequence length.")

Comment thread nemo_rl/experience/rollouts.py Outdated
Comment on lines +2731 to +2738
# Preserve compatibility with lightweight GenerationInterface test doubles
# and backends that do not yet expose an explicit backend field.
if "vllm_cfg" in cfg:
return cfg["vllm_cfg"]["max_model_len"]
if "mcore_generation_config" in cfg:
return cfg["mcore_generation_config"]["max_model_len"]
if "trtllm_cfg" in cfg:
return cfg["trtllm_cfg"]["max_model_len"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[DEAD CODE] The vllm_cfg / mcore_generation_config / trtllm_cfg key-presence fallbacks are reached only by test doubles, and the new policy_max_seq_len fallback is not reached at all.

Every production generation's cfg carries the required backend field (interfaces.py:254), so those configs return from the backend checks above. The one production object without backend is a Policy used as its own generation in Megatron distillation (distillation.py:735-737), which only reaches the max_total_sequence_length branch. max_total_sequence_length is a required PolicyConfig key, so nothing falls through to the policy_max_seq_len branch (rollouts.py:2741-2742); the pre-PR lookups had no such fallback either. Keeping the key-presence chain also keeps the lookup that made SGLang read an inherited vllm_cfg before this PR.

Suggest fix:

  1. Drop the key-presence branches (suggestion below). Also drop the policy_max_seq_len branch, the parameter (rollouts.py:2712) and its argument at the call site (rollouts.py:2845).
  2. Add "backend" to the test doubles that rely on the key-presence branches, and update the affected tests accordingly (test_rollouts.py:1724, test_rollouts.py:2044).
Suggested change
# Preserve compatibility with lightweight GenerationInterface test doubles
# and backends that do not yet expose an explicit backend field.
if "vllm_cfg" in cfg:
return cfg["vllm_cfg"]["max_model_len"]
if "mcore_generation_config" in cfg:
return cfg["mcore_generation_config"]["max_model_len"]
if "trtllm_cfg" in cfg:
return cfg["trtllm_cfg"]["max_model_len"]
# A Policy used as its own generation (Megatron distillation) has no backend field.

Comment thread nemo_rl/environments/nemo_gym.py Outdated
Comment on lines +2989 to +2996
if generation_config.get("sglang_cfg") is None:
raise ValueError(
"NeMo Gym with the SGLang backend requires "
"policy.generation.sglang_cfg."
)
# SGLang is always an HTTP server. This switch selects its asynchronous
# rollout control flow without mutating an inherited inactive vLLM block.
generation_config["use_async_rollouts"] = True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: the hand-written is None check on sglang_cfg can go, like in the sibling branches that index their blocks directly (config.md).

sglang_cfg is a required key of SGLangConfig (config.py:290), and this branch never reads it. The comment's second line also describes a path this code does not take.

Suggest fix:

Suggested change
if generation_config.get("sglang_cfg") is None:
raise ValueError(
"NeMo Gym with the SGLang backend requires "
"policy.generation.sglang_cfg."
)
# SGLang is always an HTTP server. This switch selects its asynchronous
# rollout control flow without mutating an inherited inactive vLLM block.
generation_config["use_async_rollouts"] = True
# SGLang is always an HTTP server; this selects its async rollout flow.
generation_config["use_async_rollouts"] = True

Comment thread nemo_rl/algorithms/grpo.py Outdated
# A colocated engine keeps serving between phases (preserves its
# KV/prefix cache); the backend makes that call, not the loop.
policy_generation.finish_generation(release_gpu=False)
if not isinstance(policy_generation, SGLangGeneration):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: this keeps dedicated SGLang engines resident by checking the class in the training loop, but the cause is in SGLangGeneration.finish_generation (sglang_generation.py:1021-1044), which releases weights and KV cache whenever needs_offload is set, even on dedicated GPUs.

The interface docstring says engines on dedicated GPUs ignore release_gpu, and vLLM only resets the prefix cache there (vllm_generation.py:1697). With the check here, the sync GRPO loop still releases dedicated SGLang engines on every step.

Suggest fix:

  1. Read colocated.enabled once in SGLangGeneration.__init__ and return early from finish_generation, before the health-monitor pause, when the engines are not colocated. Then drop the isinstance checks here and at grpo.py:6398, and update the synchronizer docstring that relies on the release.
  2. Update the affected tests accordingly: fixtures that call finish_generation need a colocated value, and test_grpo.py:2846 should check _offloaded_memory_tags instead of finish_generation not being called. Also rerun the non-colocated SGLang nightly, since its refit will then run with the KV cache resident.

Comment on lines +1070 to +1075
if backend == "sglang":
# SGLang collects asynchronously, but its refit protocol pauses the
# rollout engines and cannot overlap pending generation requests.
is_async_engine = False
else:
is_async_engine = should_use_async_rollouts(generation_cfg)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

grpo.async_grpo.in_flight_weight_updates: true is silently turned into a drain for SGLang, so the user's setting is ignored with no message.

This branch forces is_async_engine = False, so prepare_for_refit always waits for pending generations, and the max_trajectory_age_steps warning at grpo.py:5331-5336 is skipped because the setting is still true. The comment says SGLang's refit "cannot overlap pending generation requests", but with the shipped pause_generation_mode: retract SGLang requeues running requests and continues them after the update (scheduler.py:4189-4230), which is what SGLangGeneration.pause_generation_for_refit is for.

Per config.md, a user setting should be rejected at setup rather than overridden.

Suggest fix:

  1. Delete this branch (suggestion below), and reject the combination at setup instead by replacing grpo.py:5298-5305 with the code below; apply both together.
    generation_config = master_config.policy["generation"]
    backend = generation_config.get("backend", "") if generation_config else ""
    assert backend in ("vllm", "megatron", "sglang", "trtllm"), (
        "Async GRPO supports the vLLM, Megatron, SGLang, and TRT-LLM generation backends; "
        f"got policy.generation.backend={backend!r}."
    )
    if backend == "sglang" and master_config.grpo.async_grpo.in_flight_weight_updates:
        raise NotImplementedError(
            "grpo.async_grpo.in_flight_weight_updates=true is not supported with the "
            "SGLang generation backend yet; set it to false."
        )
  1. In async-grpo.md:220, replace the sentence "SGLang instead stops scheduling new trajectories and drains all outstanding trajectories before every refit, regardless of this setting." with:
SGLang does not support this setting yet; setup rejects `in_flight_weight_updates: true` with the SGLang backend, and the collector drains all outstanding trajectories before every refit.
  1. Update test_sglang_prepare_for_refit_drains_pending_generations in test_async_utils.py:2867 to check the setup rejection instead.
Suggested change
if backend == "sglang":
# SGLang collects asynchronously, but its refit protocol pauses the
# rollout engines and cannot overlap pending generation requests.
is_async_engine = False
else:
is_async_engine = should_use_async_rollouts(generation_cfg)
is_async_engine = should_use_async_rollouts(generation_cfg)

Comment thread nemo_rl/environments/nemo_gym.py Outdated
Comment on lines +3022 to +3037
def _normalize_nemo_gym_base_urls(
base_urls: list[str], *, generation_backend: str
) -> list[str]:
"""Return generation URLs in the form expected by NeMo Gym."""
if generation_backend != "sglang":
return list(base_urls)

normalized_urls: list[str] = []
for base_url in base_urls:
base_url = base_url.rstrip("/")
normalized_urls.append(
base_url if base_url.endswith("/v1") else f"{base_url}/v1"
)
return normalized_urls


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SGLang is the only NeMo-RL rollout backend whose dp_openai_server_base_urls does not end in /v1, and this helper exists only to add it back for Gym.

vLLM (vllm_worker_async.py:880), TRT-LLM (trtllm_http_server.py:1002) and Megatron (megatron_generation.py:204) all return /v1 URLs, which Gym takes as-is. SGLangGeneration.dp_openai_server_base_urls is new in this PR and Gym setup is its only consumer; SGLang's own router calls (/generate at sglang_generation.py:1075, /workers at fault_tolerance.py:311) build their URLs from router_ip / router_port directly. Returning /v1 there aligns SGLang with the other backends and removes this helper and the generation_backend parameter threaded through three setup paths.

Suggest fix:

  1. Return the router URL with /v1 in sglang_generation.py:215:
        return [f"http://{self.router_ip}:{self.router_port}/v1"]
  1. Delete this helper (suggestion below), its call in nemo_gym.py:3567-3569, and the generation_backend parameter of build_nemo_gym_actors / spinup_nemo_gym_actor along with the arguments added at grpo.py:1090, distillation.py:567 and single_controller_utils/setup.py:855. Apply together with step 1.
  2. Update the affected tests accordingly.
Suggested change
def _normalize_nemo_gym_base_urls(
base_urls: list[str], *, generation_backend: str
) -> list[str]:
"""Return generation URLs in the form expected by NeMo Gym."""
if generation_backend != "sglang":
return list(base_urls)
normalized_urls: list[str] = []
for base_url in base_urls:
base_url = base_url.rstrip("/")
normalized_urls.append(
base_url if base_url.endswith("/v1") else f"{base_url}/v1"
)
return normalized_urls

should_expose_http_server = generation_config.get(
"mcore_generation_config", {}
).get("expose_http_server")
elif generation_config["backend"] == "sglang":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can you confirm whether we need NVIDIA-NeMo/Gym#1787 or we can run sglang on current gym version that nemorl main pinned?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, this path needs NVIDIA-NeMo/Gym#1787. NeMo-RL main pins 9e2e5d0a. I tested its extractor with the decoded-token response that SGLang returns and it rejected it. This PR pins 666aee20, which includes the native SGLang token-ID and logprob adapter.

should_expose_http_server = generation_config.get(
"mcore_generation_config", {}
).get("expose_http_server")
elif generation_config["backend"] == "sglang":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can you add a nightly test for async grpo + sglang + gym? and also please put the curves in the PR description.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the four-GPU GB200 async GRPO + SGLang + Gym nightly in 442c0d6. I’ve submitted the matched sync/async benchmark and will add the curves to the PR description once both modes have produced measurements.

@Kh4L

Kh4L commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 242152c

@Kh4L

Kh4L commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Correction to my earlier CI diagnosis: the PR API showed an older base SHA while the main branch had advanced to 4580fe0. That introduced a real conflict in the JSON-writer test helper, now resolved by taking the upstream version.

Current head is 3fd278f. I verified that the selected merge commit 1c8840f contains this head before requesting fresh CI. The source review fixes, token-preserving Gym adapter pin, and GB200 async SGLang/Gym nightly are pushed. The matched hardware measurements and curves are still pending.

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 3fd278f (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@Kh4L

Kh4L commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 3fd278f

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 6916b2a (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@Kh4L

Kh4L commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 6916b2a

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 47d2361 (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@Kh4L

Kh4L commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 47d2361

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 1e98139 (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@Kh4L

Kh4L commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 1e98139

@Kh4L

Kh4L commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 442c0d6

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 442c0d6 (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@Kh4L

Kh4L commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 9932471

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 9932471 (PR #3127 from sglang-gym-enablement)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

This branch has not been deployed

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

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants