Repository navigation
[data][llm] Define each SGLang task as one config-driven class - #67655
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
dfd75f1 to
7a1b3c8
Compare
7a1b3c8 to
ba1935b
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit ba1935b. Configure here.
ba1935b to
a305280
Compare
There was a problem hiding this comment.
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) -> dictProposed
# 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:
SGLangEngineProcessorConfigwill get one generictask_kwargs: Dict[str, Any]field instead of a field per task, e.g.score_options.- For
run, I considered having the base callgetattr(engine, engine_method)(**kwargs)too, but generate streams andrerankis sync-only, so some tasks would overriderunanyway. So each task implementsrun.
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|
Another requirement to check -- when running |
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]>
a305280 to
40725de
Compare
|
Thanks @jeffreywang88, I like this shape. Updated in 40725de and the PR description:
Two small additions:
Score needs two more hooks. I'll add them in #67038, where they're first used, rather than leaving them unused here:
Does that split work for you? |
|
Kicking off tests first and will circle back on the review later today or tomorrow. |
jeffreywang88
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
LGTM, thank you @fortunecookiee. Running release test: https://buildkite.com/ray-project/release/builds/114109/canvas?sid=01a1b2ea-44bb-4c71-9545-feb8d6a1e2a5&open=false. Will merge this once tests pass.
|
Thanks @jeffreywang88 , How can I check why the release test failed? |
|
It ran out of GPU capacity. I reran the test. |

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 sharedSGLangEngineWrapper,SGLangEngineStageandbuild_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/:base.py_SGLangTask, the base classgenerate.py_SGLangGenerateTask, plusSGLangEngineRequestandSGLangOutputData(moved fromsglang_engine_stage.py)__init__.py_TASKSregistry andget_sglang_task_cls(task_type)_SGLangTask:The generate task declares its input columns and
params_column = "sampling_params", and implementsprepare_requestandrun.Other changes:
SGLangEngineProcessorConfiggets a generictask_kwargs: Dict[str, Any]field. Generate takes none, and a non-empty value raises. Tasks with options declare anoptions_modelthat validates it.SGLangEngineWrappernow 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.build_sglang_engine_processor, as it already does for stages. The task modules can then importSGLangEngineProcessorConfigdirectly, withoutTYPE_CHECKING.task_kwargsto 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 checkslabel_token_idsagainst 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.prepare_config:task_kwargsvalidation, unsupported stages (turned off by default, raising when enabled explicitly), forced engine kwargs, and generate rejectingtask_kwargs._SGLangGenerateTask._generate_async, the unknown-task test expects the error at wrapper creation, and the wrapper test checks theparamscolumn.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.