Skip to content

[data][llm] Add SGLang score task: multi-item scoring, embedding overrides, score extraction - #67038

Merged
jeffreywang88 merged 15 commits into
ray-project:masterfrom
fortunecookiee:sglang-score-mis
Nov 24, 2026
Merged

jeffreywang88 merged 15 commits into
ray-project:masterfrom
fortunecookiee:sglang-score-mis

Conversation

@fortunecookiee

@fortunecookiee fortunecookiee commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds task_type="score" to SGLangEngineProcessorConfig, backed by SGLang's Engine.async_score. Each row scores one query against a list of items; the output column scores holds one score list per item, in item order.

This brings the SGLang optimizations for JEV-like decision models (Scaling JEV-like Decision Models with SGLang) to Ray Data batch inference: multi-item scoring (MIS) for pointwise decisions, and setwise scoring through score extraction.

config = SGLangEngineProcessorConfig(
    model_source="Qwen/Qwen3-0.6B",
    task_type="score",
    engine_kwargs=dict(enable_mis=True, attention_backend="flashinfer"),
    task_kwargs=dict(label_token_ids=[yes_id, no_id], apply_softmax=True),
)
# in:  {"query": "Is this relevant to X?", "items": ["doc A", "doc B"]}
# out: {..., "scores": [[p_yes, p_no], [p_yes, p_no]], "num_input_tokens": ...}

Pipeline

  query, items (text)
          |
          v
  +-----------------------------+
  | SGLangScoreTokenizeStage    |  CPU, optional: set tokenize_stage=False
  |   query -> query_token_ids  |  and pass the token IDs directly
  |   items -> item_token_ids   |
  +-----------------------------+
          |
          |   query_embed_overrides, item_embed_overrides (optional)
          v             v
  +-----------------------------+
  | SGLangEngineStage (score)   |  GPU
  |   engine.async_score(...)   |
  +-----------------------------+
          |
          v
  scores, num_input_tokens

Features

Multi-item scoring (MIS): engine_kwargs={"enable_mis": True} scores all of a row's items in one forward pass.

  enable_mis=False   N passes   [q][item_1]   [q][item_2]   ...   [q][item_N]
  enable_mis=True    1 pass     [q] D [item_1] D [item_2] D ... D [item_N] D
                                D = delimiter token 9999

Embedding overrides: replace the embedding at each marker token with a vector from query_embed_overrides / item_embed_overrides, one vector per marker, in order.

  query tokens:           user  <m>  likes  <m>
  query_embed_overrides:        v1          v2

Score extraction (setwise scoring): read a score at every extraction token in an item instead of only at its last token. Each item then gets one score list per extraction token.

  item tokens:   A  <x>  B  <x>  C  <x>
  scores[i]:   [    s1,     s2,     s3   ]

task_kwargs

Key Purpose
label_token_ids Token IDs whose probabilities form each score.
apply_softmax, item_first Passed to async_score.
embed_override_token_id Embedding marker token ID.
score_extraction_token_id Extraction token ID.

Tokenization

The tokenize stage matches SGLang's text path, always with the tokenizer's special tokens:

  • Without MIS, query + item (item + query with item_first) is tokenized as one sequence and query_token_ids is empty, since the engine would concatenate them.
  • With MIS, or when a row has embedding overrides, the query is tokenized with special tokens and each item without.
  • With score extraction, a query containing the extraction token is rejected, as SGLang does.

Validation

Checks are limited to what SGLang can't catch, or would only catch on a GPU worker:

  • At build time: unknown task_kwargs keys; score options placed in engine_kwargs; token IDs outside the model vocabulary (the engine runs with skip_tokenizer_init, so it doesn't range-check them); marker IDs that collide with the MIS delimiter or each other; item_first with MIS.
  • On the worker, before the engine loads weights: sglang>=0.5.21, the first release whose async_score accepts score_extraction_token_id.

Everything else (missing label_token_ids, extraction with item_first/allow_auto_truncate, per-row override counts) is left to SGLang.

Code structure

One class, _SGLangScoreTask in tasks/sglang/score.py, on the _SGLangTask hooks from #67655:

Hook Score task
options_model SGLangScoreOptions
unsupported_stages chat template, detokenize
forced_engine_kwargs skip_tokenizer_init=True
prepare_config build-time checks
build_tokenize_stage SGLangScoreTokenizeStage
validate_model (new, no-op on base) vocabulary checks against the HF config
prepare_request / run row -> async_score -> scores

Shared helpers in stages/common.py: to_token_id_list and is_missing (Ray Data stores a missing value as NaN next to array rows). Embedding overrides are converted from numpy, the form Ray Data rows hold. Generate behavior is unchanged.

Related issues

Additional information

  • vs. vLLM task_type="score": vLLM scores one prompt per row with a cross-encoder. SGLang scores one query against many items, so the inputs are query/items and the output is scores.
  • Why async_score: SGLang's sync score() runs its own event loop and deadlocks inside the stage's loop.

Testing

CPU (macOS, mocked SGLang; tokenize tests use the real Qwen3-0.6B tokenizer from Ray's S3 mirror):

  • pytest python/ray/llm/tests/batch/cpu/processor/test_sglang_score_proc.py python/ray/llm/tests/batch/cpu/stages/test_sglang_score_tokenize_stage.py python/ray/llm/tests/batch/cpu/stages/test_sglang_score_engine_stage.py python/ray/llm/tests/batch/cpu/stages/test_common.py: 56 passed.
  • pre-commit run --files <changed files>: passed.

GPU (release tests, Qwen3-0.6B, sglang==0.5.23), in release/llm_tests/batch/test_batch_sglang.py:

  • test_sglang_score_matches_engine: Ray Data scores match a direct sglang.Engine.score text call using the same engine kwargs, MIS off and on.
  • test_sglang_score_embed_overrides: a marker overridden with a token's own embedding scores like that token, MIS off and on.
  • test_sglang_score_extraction: each anchor's scores match plain scoring of the item truncated at that anchor, MIS off and on.
  • Doc example doc_code/working-with-llms/sglang_score_example.py runs in the new llm_doc_sglang_tests release test.

AI assistance: GitHub Copilot helped write and review this change. I reviewed every changed line and ran the CPU tests above.

@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!

@fortunecookiee fortunecookiee changed the title [data][llm] Add score task with multi-item scoring to SGLangEngineProcessor [data][llm] Add SGLang score task with multi-item scoring and embedding overrides Oct 14, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 29, 2026
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 30, 2026
@fortunecookiee
fortunecookiee marked this pull request as ready for review October 31, 2026 04:56
@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.

Stale Bugbot comment from a previous run.

@fortunecookiee fortunecookiee changed the title [data][llm] Add SGLang score task with multi-item scoring and embedding overrides [data][llm] Add SGLang score task with multi-item scoring, embedding overrides, and score extraction Oct 31, 2026
@fortunecookiee
fortunecookiee force-pushed the sglang-score-mis branch 4 times, most recently from 239eb03 to 7c9a88b Compare October 31, 2026 06:16

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

Stale Bugbot comment from a previous run.

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

Stale Bugbot comment from a previous run.

@fortunecookiee
fortunecookiee requested a review from a team as a code owner November 10, 2026 19:07

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

Stale Bugbot comment from a previous run.

fortunecookiee and others added 2 commits November 10, 2026 11:18
Without MIS, the tokenize stage folds the query into each item, so SGLang's
query-prefix anchor check never sees it. Mirror that check in the stage.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>
- Release test: compare MIS and single-item scoring on the same token IDs,
  since text tokenization differs between the two at the query/item boundary.
- Docs: note MIS tokenization, label order, and score-extraction config.
- Score tokenize stage reports the override columns as optional inputs.
- Docstring and comment fixes.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Nov 17, 2026
jeffreywang88 and others added 2 commits November 17, 2026 11:00
…portorskip

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
…checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>

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

Stale Bugbot comment from a previous run.

fortunecookiee and others added 3 commits November 17, 2026 12:02
The ray logger doesn't propagate to root, so caplog under CI's
pytest 7.4.4 never captured the validate_model warning.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>
Each anchor's scores should match plain scoring of the item truncated
at that anchor, with and without multi-item scoring. Needs sglang
>=0.5.21 (bumped to 0.5.23 in ray-project#68250).

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Jian Sheng <[email protected]>
jeffreywang88 added a commit that referenced this pull request Nov 17, 2026
## Description

Bumps sglang in the release-test BYOD layer (`byod_llm_sglang_test.sh`)
from 0.5.15.post1 to 0.5.23, and drops the inlined Ray metrics patch
(upstreamed) along with its copy in `python/requirements/llm/patches/`.

## Related issues

Needed by #67038 (sglang `task_type="score"`):
- `Engine.async_score` first accepts `score_extraction_token_id` in
0.5.21, so score extraction can't be release-tested on the current pin.
- Since 0.5.21, sglang tokenizes text items without special tokens,
which is what #67038's score tokenize stage does. On 0.5.15.post1,
sglang adds BOS to each item for tokenizers that add one (e.g. Llama),
so its multi-item scoring tokenization differs from Ray's.

AI assistance (Claude Code) was used; I reviewed every changed line.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@jeffreywang88

jeffreywang88 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

@fortunecookiee please merge from the latest master. #68250 (bumping release test's sglang version) just landed.

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

I think there are some unnecessary config checks and tests. In general, I'd follow two principles:

  • If sglang already performs a config check, we shouldn't duplicate it in Ray.
  • Prefer end-to-end integration tests, don't duplicate test coverages, and only add unit tests for functionality we've implemented specifically in ray.

I'd also avoid lazy imports unless necessary and low-signal tests.

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5aa7609. Configure here.

if embed_id is not None and embed_id == extraction_id:
raise ValueError(
"'embed_override_token_id' and 'score_extraction_token_id' must " "differ."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score extraction skips incompatible option checks

Medium Severity

_validate_score_config never rejects score_extraction_token_id paired with item_first or allow_auto_truncate, even though both are documented as unsupported and the helper is meant to catch combinations SGLang would only fail on a worker. With item_first, the tokenize stage still builds item+query sequences, so extraction positions sit in the item prefix and causal scoring never sees the query. That can yield silently wrong scores instead of a build-time error, and allow_auto_truncate still reaches GPU workers before failing.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5aa7609. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SGLang's _validate_score_extraction already rejects item_first and allow_auto_truncate with extraction, and we're not duplicating SGLang's config checks here.

fortunecookiee and others added 3 commits November 17, 2026 16:49
- Always tokenize score queries with special tokens, as SGLang does.
- Drop the ForCausalLM label check and torch override branches; SGLang
  and Ray Data already cover them.
- Use result.prompt_tokens and pydantic ConfigDict.
- Test tokenization against the real Qwen3-0.6B tokenizer and drop
  duplicate or low-signal tests.

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

Copy link
Copy Markdown
Contributor Author

@jeffreywang88 could you pls take another look?

@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 please update PR description as I kick off GPU tests.

@jeffreywang88

Copy link
Copy Markdown
Contributor

@jeffreywang88

Copy link
Copy Markdown
Contributor

Second try https://buildkite.com/ray-project/release/builds/117010/canvas?sid=01a20b54-bfeb-43f8-9d6b-d45ac7de1d53&open=false after fixing / updating the tests.

@jeffreywang88
jeffreywang88 enabled auto-merge (squash) November 24, 2026 06:46
@fortunecookiee

fortunecookiee commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@eicherseiji Copilot suggests getting your approval as well to cover the missing review, could you help ship?

@jeffreywang88
jeffreywang88 merged commit 1444c46 into ray-project:master Nov 24, 2026
6 checks passed
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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants