Skip to content

[data][llm] Define each SGLang task as one config-driven class - #67655

Merged
jeffreywang88 merged 2 commits into
ray-project:masterfrom
fortunecookiee:sglang-task-handlers
Nov 8, 2026
Merged

jeffreywang88 merged 2 commits into
ray-project:masterfrom
fortunecookiee:sglang-task-handlers

Conversation

@fortunecookiee

@fortunecookiee fortunecookiee commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR defines each SGLang task as one config-driven class. It makes no behavior change for generate.

Today the task type is handled by if task_type == ... branches inside the shared SGLangEngineWrapper, SGLangEngineStage and build_sglang_engine_processor. Each new task (score in #67038, embed in #67548) would add more branches to the same methods, and those PRs would conflict with each other. After this PR, each task is a single class registered by task type, and the shared processor and stage code doesn't change when a task is added.

New package python/ray/llm/_internal/batch/tasks/sglang/:

File Contents
base.py _SGLangTask, the base class
generate.py _SGLangGenerateTask, plus SGLangEngineRequest and SGLangOutputData (moved from sglang_engine_stage.py)
__init__.py The _TASKS registry and get_sglang_task_cls(task_type)

_SGLangTask:

class _SGLangTask:
    # Declared by each task
    required_input_keys: ClassVar[Dict[str, str]] = {}
    optional_input_keys: ClassVar[Dict[str, str]] = {}
    params_column: ClassVar[Optional[str]] = None          # per-row params
    unsupported_stages: ClassVar[Tuple[str, ...]] = ()     # turned off; raises if enabled explicitly
    forced_engine_kwargs: ClassVar[Dict[str, Any]] = {}    # warns, then overrides the user's value
    options_model: ClassVar[Optional[Type[BaseModel]]] = None  # validates task_kwargs

    # Driver, implemented in the base
    @classmethod
    def prepare_config(cls, config) -> config               # applies the rules above
    @classmethod
    def build_tokenize_stage(cls, config, stage_cfg) -> StatefulStage  # default: prompt TokenizeStage

    # Engine stage
    def __init__(self, engine_kwargs, **task_kwargs)
    def prepare_request(self, row, params) -> Any            # implemented by each task
    async def run(self, engine, request) -> Dict[str, Any]   # implemented by each task

The generate task declares its input columns and params_column = "sampling_params", and implements prepare_request and run.

Other changes:

  • SGLangEngineProcessorConfig gets a generic task_kwargs: Dict[str, Any] field. Generate takes none, and a non-empty value raises. Tasks with options declare an options_model that validates it.
  • SGLangEngineWrapper now assigns request IDs, pops the task's params column, limits concurrency, and calls the task. An unknown task type now fails when the wrapper is created instead of on the first request.
  • The processor imports the task registry inside build_sglang_engine_processor, as it already does for stages. The task modules can then import SGLangEngineProcessorConfig directly, without TYPE_CHECKING.
  • The processor passes task_kwargs to the engine stage only when set, so generate's stage kwargs are unchanged.

Planned for the score PR (#67038), where they're first used: a hook for driver-computed worker kwargs (score resolves marker text to token IDs) and a validate_model(hf_config) hook (score checks label_token_ids against the model).

Related issues

Prepares for #67038 (SGLang score task) and #67548 (SGLang embed task). Once this merges, each adds one task class and they no longer conflict with each other.

Additional information

This PR is not a duplicate: it is the refactor the score and embed PRs build on, and no other open PR touches these files. The code was written with AI assistance (GitHub Copilot) and reviewed by me.

Testing (CPU-only macOS, mocked SGLang engine):

  • pytest python/ray/llm/tests/batch/cpu/stages/test_sglang_engine_stage.py python/ray/llm/tests/batch/cpu/processor/test_sglang_engine_proc.py: 14 passed.
    • New tests use a toy task to cover prepare_config: task_kwargs validation, unsupported stages (turned off by default, raising when enabled explicitly), forced engine kwargs, and generate rejecting task_kwargs.
    • Updated tests: the mock patches _SGLangGenerateTask._generate_async, the unknown-task test expects the error at wrapper creation, and the wrapper test checks the params column.
  • pytest python/ray/llm/tests/batch/cpu/processor/test_lazy_imports.py: passed except the vLLM case, which needs vLLM installed.
  • pre-commit run --files <changed files> (ruff, black, pydoclint): passed.

@fortunecookiee
fortunecookiee requested a review from a team as a code owner October 31, 2026 05:51
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit ba1935b. Configure here.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 31, 2026

@jeffreywang88 jeffreywang88 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 @fortunecookiee! Some thoughts about the API shape -- what do you think about this new API proposal? The goal is to consolidate each new task to one class, be config-driven, and tasks-specific logic shouldn't leak into processor and stages (I think this is already respected in the current implementation).

Current

Whenever we introduce a new task, we need to create two new subclasses, a task and a task handler, and register each one in its own registry:

# processor/sglang_task.py: driver. _TASKS holds instances.
class _SGLangTask:
    def prepare_config(self, config) -> config
    def engine_task_options(self, config, tokenizer_source) -> Optional[dict]
    def build_tokenize_stage(self, config, stage_cfg, task_options) -> StatefulStage
    def validate_model(self, config, hf_config) -> None

# stages/sglang_task_handler.py: actor. _TASK_HANDLERS holds classes.
class _SGLangRequest(BaseModel):
    request_id: int
    idx_in_batch: int

class _SGLangTaskHandler:
    required_input_keys: ClassVar[Dict[str, str]] = {}
    optional_input_keys: ClassVar[Dict[str, str]] = {}
    def configure_engine_kwargs(self, engine_kwargs) -> None
    def check_engine(self, engine_cls) -> None
    def prepare_request(self, row, request_id, idx_in_batch) -> _SGLangRequest
    async def run(self, engine, request) -> dict

Proposed

# batch/tasks/sglang/base.py. _TASKS: Dict[str, Type[_SGLangTask]]
class _SGLangTask:
    # Declared by children
    required_input_keys: ClassVar[Dict[str, str]]
    optional_input_keys: ClassVar[Dict[str, str]] = {}
    params_column: ClassVar[Optional[str]] = None        # per-row params
    unsupported_stages: ClassVar[Tuple[str, ...]] = ()   # turned off; raises if set explicitly
    forced_engine_kwargs: ClassVar[Dict[str, Any]] = {}  # warns, then overrides the user's value

    # Implemented once, in the base
    @classmethod
    def prepare_config(cls, config) -> config            # driver: applies the rules above
    def __init__(self, engine_kwargs: Dict[str, Any], **task_kwargs)  # actor

    # Implemented by each task (actor)
    def prepare_request(self, row, params: Optional[dict]) -> Any
    async def run(self, engine, request) -> Dict[str, Any]

Notes:

  • SGLangEngineProcessorConfig will get one generic task_kwargs: Dict[str, Any] field instead of a field per task, e.g. score_options.
  • For run, I considered having the base call getattr(engine, engine_method)(**kwargs) too, but generate streams and rerank is sync-only, so some tasks would override run anyway. So each task implements run.

The tasks look like this under the proposal:

class _SGLangGenerateTask(_SGLangTask):
    required_input_keys = {"prompt": ..., "sampling_params": ...}
    params_column = "sampling_params"
    # prepare_request: prompt / tokenized_prompt and the skip_tokenizer_init check
    # run: async_generate(stream=True) → generated_* columns

class _SGLangEmbedTask(_SGLangTask):
    required_input_keys = {"prompt": ...}
    optional_input_keys = {"embed_params": ...}
    params_column = "embed_params"
    # tokenize_stage is unsupported because Engine.async_encode takes text only, not input_ids.
    unsupported_stages = ("chat_template_stage", "tokenize_stage", "detokenize_stage")
    forced_engine_kwargs = {"is_embedding": True, "skip_tokenizer_init": False}
    # prepare_request: validates embed_params; run: async_encode → embeddings

class _SGLangScoreTask(_SGLangTask):
    required_input_keys = {"query_token_ids": ..., "item_token_ids": ...}
    optional_input_keys = {"query_embed_overrides": ..., "item_embed_overrides": ...}
    unsupported_stages = ("chat_template_stage", "detokenize_stage")
    forced_engine_kwargs = {"skip_tokenizer_init": True}
    # prepare_request: overrides → tensors; run: async_score → scores

@jeffreywang88

Copy link
Copy Markdown
Contributor

Another requirement to check -- when running vLLMEngineProcessor, sglang shouldn't be imported and vice versa, so you may want to adjust the file paths in my proposal.

Move the generate-specific engine and processor logic into a single
_SGLangGenerateTask class under batch/tasks/sglang/, registered by task
type. The _SGLangTask base declares input columns, the per-row params
column, unsupported stages, forced engine kwargs and an options model for
the new task_kwargs config field, and applies them in prepare_config.
Generate's behavior is unchanged.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>
@fortunecookiee fortunecookiee changed the title [data][llm] Split SGLang engine stage and processor into per-task classes [data][llm] Define each SGLang task as one config-driven class Nov 4, 2026
@fortunecookiee

Copy link
Copy Markdown
Contributor Author

Thanks @jeffreywang88, I like this shape. Updated in 40725de and the PR description:

  • One _SGLangTask class per task under batch/tasks/sglang/ (base.py, generate.py, registry in __init__.py), with the class attributes you proposed: required_input_keys, optional_input_keys, params_column, unsupported_stages, forced_engine_kwargs. prepare_config applies them on the driver, and each task implements prepare_request(row, params) and run.
  • SGLangEngineProcessorConfig.task_kwargs: Dict[str, Any] replaces per-task fields like score_options.

Two small additions:

  • options_model: ClassVar[Optional[Type[BaseModel]]]: prepare_config validates task_kwargs against it, so score keeps config-time validation and documented options. Generate has none, so a non-empty task_kwargs raises.
  • build_tokenize_stage as an overridable classmethod. The base default builds the prompt TokenizeStage that generate uses; score overrides it with its own tokenize stage.

Score needs two more hooks. I'll add them in #67038, where they're first used, rather than leaving them unused here:

  • Worker kwargs computed on the driver: score resolves marker text to token IDs with the tokenizer before the engine starts.
  • validate_model(hf_config): score requires label_token_ids for CausalLM models and range-checks token IDs against the vocabulary.

Does that split work for you?

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@jeffreywang88

Copy link
Copy Markdown
Contributor

Kicking off tests first and will circle back on the review later today or tomorrow.

@jeffreywang88 jeffreywang88 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, leaving some NITs / missing test coverage.

- Add the params output column in SGLangEngineWrapper instead of each task.
- Import SGLangEngineProcessorConfig under TYPE_CHECKING in the task base.
- Cover prepare_config through ProcessorBuilder.build and explicit
  detokenize_stage=False.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>

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

@fortunecookiee

Copy link
Copy Markdown
Contributor Author

Thanks @jeffreywang88 , How can I check why the release test failed?

@jeffreywang88

Copy link
Copy Markdown
Contributor

It ran out of GPU capacity. I reran the test.

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

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants