Skip to content

[Refactor] scheduler: Move Req into managers/req.py - #54065

Merged
hnyls2002 merged 3 commits into
mainfrom
lsyin/split-req-module
Nov 30, 2026
Merged

hnyls2002 merged 3 commits into
mainfrom
lsyin/split-req-module

Conversation

@hnyls2002

@hnyls2002 hnyls2002 commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Why

schedule_batch.py holds two core objects: the per-request Req (with ReqKvInfo and ReqLogprob) and the batch ScheduleBatch. Req is shared well beyond the scheduler (speculative, mem_cache, sampling, model_executor, disaggregation), so it gets its own module next to req_types.py. This PR is a pure move: whole classes, bytes unchanged, plus imports.

ScheduleBatch, the batch helpers, the lifecycle helpers (release_req, retract_all, free_beam_member_rows, unresumable_abort_message), NextBatchPlan and the field helpers stay in schedule_batch.py.

Block map

Moved as one contiguous block, in the same order (python/sglang/srt/managers/schedule_batch.py at 6d630df467 -> python/sglang/srt/managers/req.py):

symbol new path old lines new lines
ReqLogprob managers/req.py 234-273 87-126
ReqKvInfo managers/req.py 276-440 129-293
Req managers/req.py 443-1778 296-1631
  • The cut is exactly at the class boundaries (decorators included). schedule_batch.py goes from 3744 to 2128 lines.
  • No other module-level name moves: Req only uses logger from the module level, and schedule_batch.py still uses it.
  • req.py gets only the imports the block needs, and its own logger = logging.getLogger(__name__). Log lines from Req now carry the logger name sglang.srt.managers.req instead of sglang.srt.managers.schedule_batch.
  • No import cycle: req.py imports nothing from schedule_batch.py; schedule_batch.py imports Req from req.py. The TYPE_CHECKING and function-local imports in the moved code are unchanged.
  • No re-export: schedule_batch.py imports Req for its own use only.

Importers

Two commits: the move, then the importer updates (the first commit alone does not import cleanly).

  • 101 files under python/sglang, 111 under test/, 1 in benchmark/, 1 in tools/sglang-simulator.
  • from sglang.srt.managers.schedule_batch import Req (and ReqKvInfo) now reads from sglang.srt.managers.req import ...; the other names of the same import stay.
  • mock.patch("...schedule_batch.get_parallel") in 3 tests that exercise Req.set_finish_with_abort, and patch.object(schedule_batch, "get_parallel") in test_gpu_feature_transport.py, now patch sglang.srt.managers.req because Req reads get_parallel from its own module.
  • The simulator hook paths sglang.srt.managers.schedule_batch.Req are now sglang.srt.managers.req.Req.
  • benchmark/io/bench_mm_token_padding.py imported MultimodalInputs through schedule_batch; it imports it from req_types now.

The script

Rerunnable on another version of the file (it locates the classes by AST and fails if anything else sits inside the block):

python move_req.py <repo_root>          # cuts the block, writes req.py, fixes imports of schedule_batch.py
python update_importers.py <repo_root>  # rewrites `from ...schedule_batch import Req` in tracked .py files
pre-commit run --files <touched files>  # isort / ruff format
python ast_check.py <repo_root> origin/main
move_req.py
#!/usr/bin/env python3
"""Move ReqLogprob, ReqKvInfo and Req out of managers/schedule_batch.py into managers/req.py.

Usage: move_req.py <repo_root>   (rerunnable on another version of the file)

The three classes must be adjacent top-level classes; they are cut as one
contiguous block of lines (decorators included) and written byte for byte.
req.py gets only the imports the block uses (top-level and TYPE_CHECKING),
plus its own `logger` when the block uses it. schedule_batch.py drops the
imports only the block used and imports Req from req.py.
"""
import ast
import builtins
import sys
from pathlib import Path

MOVED = ["ReqLogprob", "ReqKvInfo", "Req"]
SRC = "python/sglang/srt/managers/schedule_batch.py"
DST = "python/sglang/srt/managers/req.py"
MODULE = "sglang.srt.managers.req"
HEADER = '''from __future__ import annotations

# Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""The per-request objects of the scheduler: `Req` and its logprob and KV state."""

'''


def start_line(n):
    return min([d.lineno for d in n.decorator_list] + [n.lineno])


def load_names(nodes):
    r = set()
    for n in nodes:
        for x in ast.walk(n):
            if isinstance(x, ast.Name):
                r.add(x.id)
    return r


def bound(alias):
    return alias.asname or alias.name.split(".")[0]


def render(node, keep, indent):
    node = ast.parse(ast.unparse(node)).body[0]
    node.names = [a for a in node.names if bound(a) in keep]
    if not node.names:
        return None
    return "\n".join(indent + l for l in ast.unparse(node).splitlines())


def main(root):
    root = Path(root)
    src = (root / SRC).read_text()
    lines = src.splitlines(keepends=True)
    tree = ast.parse(src)
    cls = {n.name: n for n in tree.body if isinstance(n, ast.ClassDef)}
    nodes = [cls[k] for k in MOVED]
    first, last = start_line(nodes[0]), nodes[-1].end_lineno
    covered = sum(n.end_lineno - start_line(n) + 1 for n in nodes)
    gaps = [n for n in tree.body if first <= n.lineno <= last and n not in nodes]
    assert not gaps, f"non-moved statements inside the block: {gaps}"
    assert [n.name for n in nodes] == sorted(
        [n.name for n in nodes], key=lambda k: cls[k].lineno
    ), "moved classes are out of order"
    block = "".join(lines[first - 1 : last])
    rest_lines = lines[: first - 1] + lines[last:]
    # drop one of the two blank-line separators the block leaves behind
    assert lines[first - 2].strip() == "" and lines[last].strip() == ""
    del rest_lines[first - 1 : first + 1]

    # imports: (node, indent) for top-level and TYPE_CHECKING imports
    imports = []
    for n in tree.body:
        if isinstance(n, (ast.Import, ast.ImportFrom)):
            imports.append((n, "", False))
        elif (
            isinstance(n, ast.If)
            and ast.unparse(n.test) == "TYPE_CHECKING"
        ):
            for m in n.body:
                assert isinstance(m, (ast.Import, ast.ImportFrom)), ast.dump(m)
                imports.append((m, "    ", True))

    used_moved = load_names(nodes)
    rest_nodes = [n for n in tree.body if n not in nodes]
    used_rest = load_names(rest_nodes)
    bound_names = {bound(a) for n, _, _ in imports for a in n.names}
    module_defs = {
        n.name
        for n in tree.body
        if isinstance(n, (ast.ClassDef, ast.FunctionDef)) and n not in nodes
    } | {
        t.id
        for n in tree.body
        if isinstance(n, (ast.Assign, ast.AnnAssign))
        for t in (n.targets if isinstance(n, ast.Assign) else [n.target])
        if isinstance(t, ast.Name)
    }
    local = {n.name for n in nodes}
    needs_defs = sorted((used_moved & module_defs) - local)
    assert needs_defs == ["logger"], f"moved block needs module-level names: {needs_defs}"
    unresolved = sorted(
        used_moved - bound_names - module_defs - local - set(dir(builtins))
    )
    print("names not imported or defined at module level (locals/params):", len(unresolved))

    # req.py
    # the added `logger = logging.getLogger(...)` and the TYPE_CHECKING guard need these
    need = used_moved | {"logging", "TYPE_CHECKING"}
    top, tc, seen = [], [], set()
    for n, ind, is_tc in imports:
        keep = {bound(a) for a in n.names if bound(a) in need} - (seen if is_tc else set())
        text = render(n, keep, ind)
        if not is_tc:
            seen |= keep
        if text:
            (tc if is_tc else top).append(text)
    out = HEADER + "\n".join(top) + "\n"
    if tc:
        out += "\nif TYPE_CHECKING:\n" + "\n".join(tc) + "\n"
    out += "\nlogger = logging.getLogger(__name__)\n\n\n" + block
    (root / DST).write_text(out)

    # schedule_batch.py: drop imports only the block used, import the moved names
    still = used_rest | {x for x in MOVED if x in used_rest}
    drop = {b for b in bound_names if b in used_moved and b not in used_rest}
    text = "".join(rest_lines)
    rtree_lines = text.splitlines(keepends=True)
    # re-locate import nodes in the shortened file
    rtree = ast.parse(text)
    edits = []
    for n in rtree.body:
        cands = [n] if isinstance(n, (ast.Import, ast.ImportFrom)) else (
            n.body if isinstance(n, ast.If) and ast.unparse(n.test) == "TYPE_CHECKING" else []
        )
        for m in cands:
            if not isinstance(m, (ast.Import, ast.ImportFrom)):
                continue
            if any(bound(a) in drop for a in m.names):
                ind = " " * m.col_offset
                new = render(m, {bound(a) for a in m.names} - drop, ind)
                edits.append((m.lineno, m.end_lineno, new))
    for a, b, new in sorted(edits, reverse=True):
        rtree_lines[a - 1 : b] = [new + "\n"] if new else []
    new_imp = f"from {MODULE} import " + ", ".join(
        sorted(x for x in MOVED if x in used_rest)
    ) + "\n"
    # insert before the first `from sglang.srt.managers.req_types import` (isort fixes order)
    for i, l in enumerate(rtree_lines):
        if l.startswith("from sglang.srt.managers.req_types import"):
            rtree_lines.insert(i, new_imp)
            break
    else:
        raise SystemExit("anchor import not found")
    (root / SRC).write_text("".join(rtree_lines))
    print(f"moved lines {first}-{last} of {SRC}; dropped imports: {sorted(drop)}")
    print("moved symbols:", {k: (start_line(cls[k]), cls[k].end_lineno) for k in MOVED})


if __name__ == "__main__":
    main(sys.argv[1])
update_importers.py
#!/usr/bin/env python3
"""Rewrite `from sglang.srt.managers.schedule_batch import ...` so the moved names
come from sglang.srt.managers.req. Usage: update_importers.py <repo_root>
Prints every touched file. Run isort / ruff-format afterwards."""
import ast
import subprocess
import sys
from pathlib import Path

MOVED = {"ReqLogprob", "ReqKvInfo", "Req"}
OLD, NEW = "sglang.srt.managers.schedule_batch", "sglang.srt.managers.req"


def fmt(indent, module, names, comment):
    parts = ", ".join(names)
    return f"{indent}from {module} import {parts}{comment}\n"


def main(root):
    root = Path(root)
    files = subprocess.run(
        ["git", "-C", str(root), "ls-files", "*.py", "*.pyi"],
        capture_output=True, text=True, check=True,
    ).stdout.split()
    for rel in files:
        p = root / rel
        if rel.endswith("managers/schedule_batch.py") and "/srt/" in rel:
            continue
        src = p.read_text()
        if OLD not in src:
            continue
        try:
            tree = ast.parse(src)
        except SyntaxError:
            continue
        lines = src.splitlines(keepends=True)
        edits = []
        for n in ast.walk(tree):
            if not (isinstance(n, ast.ImportFrom) and n.module == OLD and n.level == 0):
                continue
            moved = [a for a in n.names if a.name in MOVED]
            if not moved:
                continue
            keep = [a for a in n.names if a.name not in MOVED]
            first = lines[n.lineno - 1]
            comment = ""
            if "#" in first.split("import", 1)[-1]:
                comment = "  " + first[first.index("#"):].rstrip("\n")
            ind = " " * n.col_offset
            render = lambda al: [a.name + (f" as {a.asname}" if a.asname else "") for a in al]
            new = ""
            if keep:
                new += fmt(ind, OLD, render(keep), comment)
            new += fmt(ind, NEW, render(moved), comment)
            edits.append((n.lineno, n.end_lineno, new))
        if not edits:
            continue
        for a, b, new in sorted(edits, reverse=True):
            lines[a - 1 : b] = [new]
        p.write_text("".join(lines))
        print(rel)


if __name__ == "__main__":
    main(sys.argv[1])

Checks

  • AST check (ast_check.py): each moved class's source segment in req.py equals the original byte for byte, req.py ends with the original block, and schedule_batch.py minus the moved classes equals the original minus them, imports excluded.
  • Every module under python/sglang touched by the importer commit imports in its own process (103 modules): same 8 failures as origin/main (optional deps missing on the host).
  • CPU unit suites (unit/managers, sampling, spec, speculative, mem_cache, model_executor, disaggregation) on origin/main and on this head: identical failure ids (1445 on both, all pre-existing on a CPU-only host).
  • pre-commit passes on all touched files.

CI States

Latest PR Test (Base): ⏳ Run #46395702463
Latest PR Test (Extra): ⊘ Skipped -- add the run-ci-nv-extra label to opt in.
Latest PR Test (AMD ROCm 10): ❌ Run #46395709061

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@claude claude 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.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@hnyls2002

Copy link
Copy Markdown
Collaborator Author

/rerun-test test_finish_length_speculative.py test_req_finish_state.py test_admission_abort_not_enqueued.py test_gpu_feature_transport.py test_srt_endpoint.py

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🚀 ubuntu-latest (4 tests): ✅ View workflow run

cd test/ && python3 registered/unit/managers/test_finish_length_speculative.py  # base-a
cd test/ && python3 registered/unit/managers/test_req_finish_state.py  # base-a
cd test/ && python3 registered/unit/disaggregation/test_admission_abort_not_enqueued.py  # base-a
cd test/ && python3 registered/unit/multimodal/test_gpu_feature_transport.py  # base-a

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/core/test_srt_endpoint.py  # base-b

@hnyls2002

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Nov 30, 2026
@hnyls2002
hnyls2002 merged commit 57d5896 into main Nov 30, 2026
166 of 188 checks passed
@hnyls2002
hnyls2002 deleted the lsyin/split-req-module branch November 30, 2026 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apple-silicon diffusion SGLang Diffusion hicache Hierarchical Caching for SGLang lora memory-pool Multi-modal multi-modal language model npu run-ci CI: run the baseline test suite on this PR speculative-decoding unified-radix-cache

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant