Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions roll/third_party/sglang/v052_patch/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"] = (
Expand Down
3 changes: 3 additions & 0 deletions roll/third_party/sglang/v054_patch/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"] = (
Expand Down
103 changes: 103 additions & 0 deletions tests/third_party/sglang/test_original_logprob_env.py
Original file line number Diff line number Diff line change
@@ -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