From db2432b76f2dbb63ff4590519662818893c0b296 Mon Sep 17 00:00:00 2001 From: Xiaoyuan Wang <174581044+XiaoyuanWang111@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:46:45 +0000 Subject: [PATCH] fix(sglang): return log-probs before temperature scaling ROLL's trainer recomputes log-probs from unscaled logits (op_compute_log_probs in the DeepSpeed, FSDP2 and Megatron strategies), and vLLM returns its default raw_logprobs, which are also taken before temperature. SGLang instead returns log softmax(logits / temperature) for the sampled token unless RETURN_ORIGINAL_LOGPROB (0.5.2) or SGLANG_RETURN_ORIGINAL_LOGPROB (0.5.4.post2 and later) is set. With SGLang, infer_logprobs therefore differ from old_log_probs by a temperature term that train_infer_correction (IS weight, filters and its always-on metrics), the SAO ratio and on-policy distillation read as train-infer mismatch, and switching the rollout backend changes what they measure. Set the variable in the patched _set_envs_and_config, which runs before SGLang spawns its scheduler processes, unless it is already set. SGLang 0.4.10.post2 has no such switch and is left unchanged. --- .../Advanced Features/rollout_filtering.md | 2 + roll/third_party/sglang/v052_patch/engine.py | 3 + roll/third_party/sglang/v054_patch/engine.py | 3 + .../sglang/test_original_logprob_env.py | 103 ++++++++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 tests/third_party/sglang/test_original_logprob_env.py diff --git a/docs_roll/docs/User Guides/Advanced Features/rollout_filtering.md b/docs_roll/docs/User Guides/Advanced Features/rollout_filtering.md index 07956262c..92ebcb4af 100644 --- a/docs_roll/docs/User Guides/Advanced Features/rollout_filtering.md +++ b/docs_roll/docs/User Guides/Advanced Features/rollout_filtering.md @@ -357,6 +357,8 @@ This setting primarily reduces waiting caused by slow environments and long-tail Different precision, operators, or execution backends can cause the training model and inference engine to assign different probabilities to the same token. ROLL can generate a filter mask from the divergence between `old_log_probs` and `infer_logprobs`. +Both values are log-probabilities of the sampled token before `temperature`, `top_k` and `top_p` are applied: the trainer computes `old_log_probs` from unscaled logits, vLLM returns its default `raw_logprobs`, and ROLL starts SGLang with `RETURN_ORIGINAL_LOGPROB=1` (SGLang 0.5.2) or `SGLANG_RETURN_ORIGINAL_LOGPROB=1` (SGLang 0.5.4.post2 and later) unless the variable is already set. The divergence therefore measures train-infer numerical mismatch on either backend; it does not include the change of distribution that `temperature`, `top_k` and `top_p` cause during sampling. + Example configuration: ```yaml diff --git a/roll/third_party/sglang/v052_patch/engine.py b/roll/third_party/sglang/v052_patch/engine.py index 48b2098ea..65a657e5c 100644 --- a/roll/third_party/sglang/v052_patch/engine.py +++ b/roll/third_party/sglang/v052_patch/engine.py @@ -23,6 +23,9 @@ def _set_envs_and_config(server_args: ServerArgs): # flashinfer uses this environment variable for various kernels from MoE to quant kernels if os.environ.get("TRTLLM_ENABLE_PDL", "1") != "0": os.environ["TRTLLM_ENABLE_PDL"] = "1" + # Report log-probs before temperature scaling: the trainer recomputes them from unscaled logits + # (op_compute_log_probs) and vLLM's default raw_logprobs are unscaled too. + os.environ.setdefault("RETURN_ORIGINAL_LOGPROB", "1") # Can also be passed as argument os.environ["SGLANG_RUN_ID"] = ( diff --git a/roll/third_party/sglang/v054_patch/engine.py b/roll/third_party/sglang/v054_patch/engine.py index b2beb1d31..46082813b 100644 --- a/roll/third_party/sglang/v054_patch/engine.py +++ b/roll/third_party/sglang/v054_patch/engine.py @@ -30,6 +30,9 @@ def _set_envs_and_config(server_args: ServerArgs): if os.environ.get("CUTE_DSL_LOG_TO_CONSOLE") is None: # Need to set log to console, otherwise the log level won't take effect os.environ["CUTE_DSL_LOG_TO_CONSOLE"] = "1" + # Report log-probs before temperature scaling: the trainer recomputes them from unscaled logits + # (op_compute_log_probs) and vLLM's default raw_logprobs are unscaled too. + os.environ.setdefault("SGLANG_RETURN_ORIGINAL_LOGPROB", "1") # Can also be passed as argument os.environ["SGLANG_RUN_ID"] = ( diff --git a/tests/third_party/sglang/test_original_logprob_env.py b/tests/third_party/sglang/test_original_logprob_env.py new file mode 100644 index 000000000..c17b5c3f4 --- /dev/null +++ b/tests/third_party/sglang/test_original_logprob_env.py @@ -0,0 +1,103 @@ +"""SGLang must report log-probs before temperature scaling, the quantity that ROLL's trainer recomputes. + +op_compute_log_probs computes log-probs from unscaled logits, and vLLM's default raw_logprobs are unscaled +too. SGLang returns log softmax(logits / temperature) unless RETURN_ORIGINAL_LOGPROB (0.5.2) or +SGLANG_RETURN_ORIGINAL_LOGPROB (0.5.4.post2 and later) is set in its scheduler processes, which inherit +the environment prepared by ROLL's _set_envs_and_config. These tests load ROLL's patch modules against +stand-ins for the three SGLang modules they import, so they need neither SGLang nor a GPU. +""" + +import importlib +import importlib.metadata +import importlib.util +import multiprocessing +import os +import pathlib +import sys +import types +from typing import Callable, Iterator + +import pytest + +ENV_NAMES = ("RETURN_ORIGINAL_LOGPROB", "SGLANG_RETURN_ORIGINAL_LOGPROB") +SERVER_ARGS = types.SimpleNamespace(enable_symm_mem=False, enable_nccl_nvls=False, enable_metrics=False) + + +def _is_sglang_module(name: str) -> bool: + return name == "sglang" or name.startswith(("sglang.", "roll.third_party.sglang")) + + +@pytest.fixture +def load_patch_engine(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[str], types.ModuleType]]: + """Return a loader of ROLL's SGLang patch engine module for a given SGLang version string.""" + saved = {name: module for name, module in sys.modules.items() if _is_sglang_module(name)} + for name in saved: + del sys.modules[name] + for name in ENV_NAMES: + monkeypatch.setenv(name, "") # records the original value, restored at teardown + monkeypatch.delenv(name) + monkeypatch.setattr(multiprocessing, "set_start_method", lambda *args, **kwargs: None) + + def load(version: str) -> types.ModuleType: + for name in [name for name in sys.modules if _is_sglang_module(name)]: + del sys.modules[name] + for name in ( + "sglang", + "sglang.srt", + "sglang.srt.entrypoints", + "sglang.srt.entrypoints.engine", + "sglang.srt.server_args", + "sglang.srt.utils", + ): + sys.modules[name] = types.ModuleType(name) + sys.modules["sglang"].__version__ = version + sys.modules["sglang.srt.entrypoints.engine"]._launch_subprocesses = lambda *args, **kwargs: None + sys.modules["sglang.srt.server_args"].ServerArgs = object + sys.modules["sglang.srt.utils"].set_prometheus_multiproc_dir = lambda: None + sys.modules["sglang.srt.utils"].set_ulimit = lambda *args, **kwargs: None + return importlib.import_module("roll.third_party.sglang").patch.engine + + yield load + for name in [name for name in sys.modules if _is_sglang_module(name)]: + del sys.modules[name] + sys.modules.update(saved) + if "roll.third_party.sglang" in saved: + sys.modules["roll.third_party"].sglang = saved["roll.third_party.sglang"] + + +@pytest.mark.parametrize( + "version, env_name", + [ + ("0.5.2", "RETURN_ORIGINAL_LOGPROB"), + ("0.5.4.post2", "SGLANG_RETURN_ORIGINAL_LOGPROB"), + ("0.5.7", "SGLANG_RETURN_ORIGINAL_LOGPROB"), + ], +) +def test_set_envs_requests_logprobs_before_temperature( + load_patch_engine: Callable[[str], types.ModuleType], version: str, env_name: str +) -> None: + engine = load_patch_engine(version) + engine._set_envs_and_config(SERVER_ARGS) + assert os.environ.get(env_name) == "1" + + +def test_set_envs_keeps_explicit_setting( + load_patch_engine: Callable[[str], types.ModuleType], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("SGLANG_RETURN_ORIGINAL_LOGPROB", "0") + engine = load_patch_engine("0.5.7") + engine._set_envs_and_config(SERVER_ARGS) + assert os.environ["SGLANG_RETURN_ORIGINAL_LOGPROB"] == "0" + + +def test_env_name_matches_installed_sglang(load_patch_engine: Callable[[str], types.ModuleType]) -> None: + """The variable ROLL sets must be the one the installed SGLang sampler reads (it was renamed in 0.5.4).""" + spec = importlib.util.find_spec("sglang") + if spec is None or not spec.submodule_search_locations: + pytest.skip("sglang is not installed in this environment.") + sampler_source = (pathlib.Path(spec.submodule_search_locations[0]) / "srt" / "layers" / "sampler.py").read_text() + engine = load_patch_engine(importlib.metadata.version("sglang")) + engine._set_envs_and_config(SERVER_ARGS) + selected = [name for name in ENV_NAMES if os.environ.get(name) == "1"] + assert len(selected) == 1 + assert f'get_bool_env_var("{selected[0]}")' in sampler_source