[Reasoning] Support for speculative decoding with thinking budget (#34668)
Signed-off-by: rishitdholakia13 <rishit+github@cohere.com> Signed-off-by: rishitdholakia13 <123388671+rishitdholakia13@users.noreply.github.com> Co-authored-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Cyrus Leung <tlleungac@connect.ust.hk>
This commit is contained in:
co-authored by
Nick Hill
Cyrus Leung
parent
8a8c9b564e
commit
68dd7db810
@@ -1,18 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""E2E tests for thinking_token_budget with reasoning models."""
|
||||
"""E2E tests for ``thinking_token_budget`` with reasoning models.
|
||||
|
||||
Covers Qwen3-0.6B and Qwen3.5 FP8 + MTP.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Literal
|
||||
|
||||
import openai
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from tests.utils import RemoteOpenAIServer, multi_gpu_only, requires_fp8
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.tokenizers import get_tokenizer
|
||||
|
||||
MODEL_NAME = "Qwen/Qwen3-0.6B"
|
||||
QWEN35_FP8_MTP_MODEL = "Qwen/Qwen3.5-35B-A3B-FP8"
|
||||
MESSAGES = [{"role": "user", "content": "What is 1+1? Be concise."}]
|
||||
THINK_BUDGET = 5
|
||||
|
||||
REASONING_START_STR = "<think>"
|
||||
REASONING_END_STR = "</think>"
|
||||
|
||||
|
||||
def _count_reasoning_decode_token_ids_between_markers(
|
||||
full_token_ids: list[int],
|
||||
reasoning_start_ids: list[int],
|
||||
reasoning_end_ids: list[int],
|
||||
) -> int | None:
|
||||
"""Count decode tokens in the thinking span (after last start, before first end)."""
|
||||
|
||||
if not reasoning_start_ids or not reasoning_end_ids:
|
||||
raise ValueError("reasoning marker token id lists must be non-empty")
|
||||
|
||||
def _last_subseq_index(haystack: list[int], needle: list[int]) -> int:
|
||||
n = len(needle)
|
||||
if n > len(haystack):
|
||||
return -1
|
||||
for i in range(len(haystack) - n, -1, -1):
|
||||
if haystack[i : i + n] == needle:
|
||||
return i
|
||||
return -1
|
||||
|
||||
last_start = _last_subseq_index(full_token_ids, reasoning_start_ids)
|
||||
if last_start < 0:
|
||||
return None
|
||||
|
||||
pos_after_start = last_start + len(reasoning_start_ids)
|
||||
end_n = len(reasoning_end_ids)
|
||||
for j in range(pos_after_start, len(full_token_ids) - end_n + 1):
|
||||
if full_token_ids[j : j + end_n] == reasoning_end_ids:
|
||||
return j - pos_after_start
|
||||
return len(full_token_ids) - pos_after_start
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server():
|
||||
@@ -48,6 +92,51 @@ def server_with_auto_reasoning_config():
|
||||
yield remote_server
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server_qwen35_fp8_mtp_tp2():
|
||||
"""Qwen3.5-35B FP8 with MTP speculative decoding and tensor parallel size 2."""
|
||||
if current_platform.device_count() < 2:
|
||||
pytest.skip("Need at least 2 GPUs for --tensor-parallel-size 2")
|
||||
if not current_platform.supports_fp8():
|
||||
pytest.skip("FP8 is not supported on this platform")
|
||||
|
||||
spec_cfg = {
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 2,
|
||||
"max_model_len": 32768,
|
||||
}
|
||||
args = [
|
||||
"--tensor-parallel-size",
|
||||
"2",
|
||||
"--max-model-len",
|
||||
"32768",
|
||||
"--speculative-config",
|
||||
json.dumps(spec_cfg),
|
||||
"--reasoning-parser",
|
||||
"qwen3",
|
||||
"--reasoning-config",
|
||||
json.dumps(
|
||||
{
|
||||
"reasoning_start_str": REASONING_START_STR,
|
||||
"reasoning_end_str": REASONING_END_STR,
|
||||
}
|
||||
),
|
||||
]
|
||||
# With 4+ GPUs, run TP=2 on physical devices 2,3 so module-scoped 0.6B servers
|
||||
# on 0,1 do not exhaust memory on the same devices as this worker.
|
||||
env_dict = None
|
||||
if current_platform.device_count() >= 4:
|
||||
env_dict = {"CUDA_VISIBLE_DEVICES": "2,3"}
|
||||
|
||||
with RemoteOpenAIServer(
|
||||
QWEN35_FP8_MTP_MODEL,
|
||||
args,
|
||||
max_wait_seconds=3000,
|
||||
env_dict=env_dict,
|
||||
) as remote_server:
|
||||
yield remote_server
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(request, server, server_with_auto_reasoning_config):
|
||||
server_map = {
|
||||
@@ -89,8 +178,10 @@ async def test_thinking_token_budget_mixed_requests(client: openai.AsyncOpenAI):
|
||||
async def test_thinking_token_budget_limits_reasoning(client: openai.AsyncOpenAI):
|
||||
"""Test that thinking_token_budget limits the number of reasoning tokens.
|
||||
|
||||
In streaming mode each reasoning delta corresponds to one token, so
|
||||
counting non-empty reasoning_content chunks gives the exact token count.
|
||||
Counts non-empty streaming ``delta.reasoning`` chunks (coarse proxy; each
|
||||
chunk may represent multiple decode tokens — see
|
||||
``_count_reasoning_decode_token_ids_between_markers`` and the Qwen3.5 MTP
|
||||
test for id-based checks).
|
||||
"""
|
||||
|
||||
reasoning_token_count = 0
|
||||
@@ -110,3 +201,89 @@ async def test_thinking_token_budget_limits_reasoning(client: openai.AsyncOpenAI
|
||||
f"reasoning tokens ({reasoning_token_count}) exceeded "
|
||||
f"thinking_token_budget ({THINK_BUDGET})"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@multi_gpu_only(num_gpus=2)
|
||||
@requires_fp8
|
||||
async def test_thinking_token_budget_qwen35_fp8_mtp_concurrent_mixed_budget_and_plain(
|
||||
server_qwen35_fp8_mtp_tp2,
|
||||
):
|
||||
"""Concurrent chat requests: some with ``thinking_token_budget``, some without.
|
||||
|
||||
Exercises the scheduler / input processor under a mixed batch on the same
|
||||
Qwen3.5 FP8 + MTP (TP=2) server. Budgeted calls are checked with
|
||||
``_count_reasoning_decode_token_ids_between_markers`` on full token ids.
|
||||
"""
|
||||
|
||||
_batch_spec: list[tuple[Literal["budget"], int] | tuple[Literal["plain"], None]] = [
|
||||
("budget", 1),
|
||||
("budget", 12),
|
||||
("plain", None),
|
||||
("budget", 20),
|
||||
("budget", 14),
|
||||
("plain", None),
|
||||
("plain", None),
|
||||
("budget", 12),
|
||||
("plain", None),
|
||||
]
|
||||
|
||||
tokenizer = get_tokenizer(tokenizer_name=QWEN35_FP8_MTP_MODEL)
|
||||
start_ids = list(tokenizer.encode(REASONING_START_STR, add_special_tokens=False))
|
||||
end_ids = list(tokenizer.encode(REASONING_END_STR, add_special_tokens=False))
|
||||
|
||||
async with server_qwen35_fp8_mtp_tp2.get_async_client() as client:
|
||||
|
||||
async def budgeted_call(expected_budget: int):
|
||||
return await client.chat.completions.create(
|
||||
model=QWEN35_FP8_MTP_MODEL,
|
||||
messages=MESSAGES,
|
||||
max_tokens=256,
|
||||
stream=False,
|
||||
extra_body={
|
||||
"thinking_token_budget": expected_budget,
|
||||
"return_token_ids": True,
|
||||
},
|
||||
)
|
||||
|
||||
async def plain_call():
|
||||
return await client.chat.completions.create(
|
||||
model=QWEN35_FP8_MTP_MODEL,
|
||||
messages=MESSAGES,
|
||||
max_tokens=256,
|
||||
stream=False,
|
||||
)
|
||||
|
||||
coros = []
|
||||
for row in _batch_spec:
|
||||
if row[0] == "budget":
|
||||
b = row[1]
|
||||
assert isinstance(b, int)
|
||||
coros.append(budgeted_call(b))
|
||||
else:
|
||||
coros.append(plain_call())
|
||||
results = await asyncio.gather(*coros)
|
||||
|
||||
for i, (response, (kind, expected_budget)) in enumerate(
|
||||
zip(results, _batch_spec, strict=True)
|
||||
):
|
||||
msg = response.choices[0].message
|
||||
assert msg.content or getattr(msg, "reasoning", None), (
|
||||
f"index {i} ({kind}): empty message"
|
||||
)
|
||||
|
||||
if kind == "budget":
|
||||
assert expected_budget is not None
|
||||
assert response.prompt_token_ids is not None
|
||||
assert response.choices[0].token_ids is not None
|
||||
full_ids = list(response.prompt_token_ids) + list(
|
||||
response.choices[0].token_ids
|
||||
)
|
||||
n_reason = _count_reasoning_decode_token_ids_between_markers(
|
||||
full_ids, start_ids, end_ids
|
||||
)
|
||||
assert n_reason is not None, f"index {i}: missing reasoning start in ids"
|
||||
assert n_reason == expected_budget, (
|
||||
f"index {i}: reasoning decode token ids ({n_reason}) != "
|
||||
f"thinking_token_budget ({expected_budget})"
|
||||
)
|
||||
|
||||
@@ -30,10 +30,13 @@ from vllm.v1.sample.logits_processor import (
|
||||
MinPLogitsProcessor,
|
||||
MinTokensLogitsProcessor,
|
||||
MoveDirectionality,
|
||||
ThinkingTokenBudgetLogitsProcessor,
|
||||
build_logitsprocs,
|
||||
)
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.sample.thinking_budget_state import (
|
||||
ThinkingBudgetStateHolder,
|
||||
maybe_create_thinking_budget_state_holder,
|
||||
)
|
||||
|
||||
PIN_MEMORY_AVAILABLE = is_pin_memory_available()
|
||||
MAX_NUM_REQS = 256
|
||||
@@ -48,8 +51,10 @@ MAX_NUM_PROMPT_TOKENS = 64
|
||||
MIN_TOKENS_LEN_THRESHOLD = 5
|
||||
REQS_PER_LOGITPROC = 50
|
||||
STR_NO_LOGITPROC = "none"
|
||||
# Thinking budget uses ``ThinkingBudgetStateHolder`` (not a logits processor).
|
||||
STR_THINKING_BUDGET = "thinking_budget"
|
||||
|
||||
# ThinkingTokenBudgetLogitsProcessor testing constants
|
||||
# Thinking token budget testing constants
|
||||
THINKING_TOKEN_BUDGET = 5
|
||||
THINK_START_TOKEN_ID = 999
|
||||
THINK_END_TOKEN_ID = 998
|
||||
@@ -80,15 +85,8 @@ class LogitsProcsRequestParams:
|
||||
if num_tokens > 0:
|
||||
# Use diverse random tokens
|
||||
self.out_tokens = [random.randint(1, 950) for _ in range(num_tokens)]
|
||||
# Set first token for ThinkingTokenBudget testing
|
||||
is_thinking_processor = (
|
||||
logitproc_type is ThinkingTokenBudgetLogitsProcessor
|
||||
or (
|
||||
hasattr(logitproc_type, "__name__")
|
||||
and logitproc_type.__name__ == "ThinkingTokenBudgetLogitsProcessor"
|
||||
)
|
||||
)
|
||||
if is_thinking_processor:
|
||||
# Think-start seed for ``STR_THINKING_BUDGET`` rows.
|
||||
if logitproc_type == STR_THINKING_BUDGET:
|
||||
self.out_tokens[0] = THINK_START_TOKEN_ID
|
||||
else:
|
||||
self.out_tokens = []
|
||||
@@ -102,7 +100,7 @@ class LogitsProcsRequestParams:
|
||||
|
||||
|
||||
class MockReasoningConfig:
|
||||
"""Mock reasoning config for testing ThinkingTokenBudgetLogitsProcessor."""
|
||||
"""Minimal reasoning config for ``ThinkingBudgetStateHolder`` tests."""
|
||||
|
||||
reasoning_start_token_ids = [THINK_START_TOKEN_ID]
|
||||
reasoning_end_token_ids = [THINK_END_TOKEN_ID]
|
||||
@@ -137,6 +135,18 @@ def _generate_fake_sampling_metadata(
|
||||
is_pin_memory=PIN_MEMORY_AVAILABLE,
|
||||
is_pooling_model=False,
|
||||
)
|
||||
num_spec = (
|
||||
vllm_config.speculative_config.num_speculative_tokens
|
||||
if vllm_config.speculative_config
|
||||
else 0
|
||||
)
|
||||
thinking_holder = maybe_create_thinking_budget_state_holder(
|
||||
vllm_config.reasoning_config,
|
||||
vllm_config.scheduler_config.max_num_seqs,
|
||||
num_spec,
|
||||
device,
|
||||
PIN_MEMORY_AVAILABLE,
|
||||
)
|
||||
fake_sampling_metadata = SamplingMetadata(
|
||||
temperature=torch.full((batch_size,), 0.0),
|
||||
all_greedy=True,
|
||||
@@ -156,6 +166,7 @@ def _generate_fake_sampling_metadata(
|
||||
allowed_token_ids_mask=None,
|
||||
bad_words_token_ids={},
|
||||
logitsprocs=logitsprocs,
|
||||
thinking_budget_state_holder=thinking_holder,
|
||||
)
|
||||
return fake_sampling_metadata
|
||||
|
||||
@@ -187,7 +198,7 @@ def _sampling_params_from_logitproc(logitproc_type: LogitprocType) -> SamplingPa
|
||||
|
||||
def _generate_mixed_logitsprocs_batch_params(
|
||||
reqs_per_logitproc: int,
|
||||
logitsprocs_types: list[str],
|
||||
logitsprocs_types: list[LogitprocType],
|
||||
) -> list[LogitsProcsRequestParams]:
|
||||
"""Define key params for a batch of requests with a different
|
||||
logitproc enabled per request.
|
||||
@@ -450,23 +461,21 @@ def _thinking_budget_validate(
|
||||
request_params: LogitsProcsRequestParams,
|
||||
step_idx: int,
|
||||
) -> None:
|
||||
"""Validate thinking token budget processor behavior"""
|
||||
# Get the ThinkingTokenBudgetLogitsProcessor instance
|
||||
tb_processor: ThinkingTokenBudgetLogitsProcessor = next(
|
||||
test_fakes.get_logitsprocs_by_cls(ThinkingTokenBudgetLogitsProcessor)
|
||||
)
|
||||
"""Validate ``ThinkingBudgetStateHolder`` thinking-budget behavior.
|
||||
|
||||
# Get current request state
|
||||
state = tb_processor._state.get(batch_index)
|
||||
State is keyed by **batch slot** (same index space as logits rows), matching
|
||||
``sync_batch`` / sampler integration (see PR #34668 discussion).
|
||||
"""
|
||||
holder = test_fakes.sampling_metadata.thinking_budget_state_holder
|
||||
assert holder is not None
|
||||
state = holder._state.get(batch_index)
|
||||
params = request_params.params
|
||||
|
||||
# Validate thinking token budget configuration
|
||||
if hasattr(params, "thinking_token_budget") and params.thinking_token_budget:
|
||||
# State should exist for requests with thinking_token_budget
|
||||
if state is None:
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
f"Expected state for batch {batch_index} "
|
||||
f"Expected holder state for batch slot {batch_index} "
|
||||
f"with thinking_token_budget={params.thinking_token_budget}"
|
||||
),
|
||||
batch_index=batch_index,
|
||||
@@ -474,10 +483,8 @@ def _thinking_budget_validate(
|
||||
step_idx=step_idx,
|
||||
)
|
||||
|
||||
# Validate budget matches what was set
|
||||
expected_budget = params.thinking_token_budget
|
||||
actual_budget = state["thinking_token_budget"]
|
||||
|
||||
if actual_budget != expected_budget:
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
@@ -488,13 +495,9 @@ def _thinking_budget_validate(
|
||||
step_idx=step_idx,
|
||||
)
|
||||
|
||||
# Check if we're in thinking mode and validate token counting
|
||||
output_tokens = request_params.out_tokens
|
||||
|
||||
# Find if thinking has started in output tokens
|
||||
start_tokens = holder.think_start_token_ids
|
||||
thinking_started = False
|
||||
start_tokens = tb_processor.reasoning_start_token_ids
|
||||
|
||||
if len(start_tokens) > 0:
|
||||
for i in range(len(output_tokens) - len(start_tokens) + 1):
|
||||
if output_tokens[i : i + len(start_tokens)] == start_tokens:
|
||||
@@ -502,61 +505,42 @@ def _thinking_budget_validate(
|
||||
break
|
||||
|
||||
if thinking_started:
|
||||
# If budget is exceeded, validate end token forcing
|
||||
think_count = state["think_count"]
|
||||
budget = state["thinking_token_budget"]
|
||||
if think_count >= budget and not state["in_end"]:
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
f"Budget exceeded ({think_count} >= {budget}) but "
|
||||
"in_end is false"
|
||||
),
|
||||
batch_index=batch_index,
|
||||
request_params=request_params,
|
||||
step_idx=step_idx,
|
||||
)
|
||||
|
||||
if think_count >= budget:
|
||||
if not state["in_end"]:
|
||||
end_tokens = holder.think_end_token_ids
|
||||
if (
|
||||
think_count >= budget
|
||||
and state["in_end"]
|
||||
and len(end_tokens) > 0
|
||||
and holder.has_tracked_requests()
|
||||
):
|
||||
expected_end_token_id = end_tokens[
|
||||
min(state["end_count"], len(end_tokens) - 1)
|
||||
]
|
||||
# Holder bumps forced vocab positions to 1e9 (does not -inf others).
|
||||
forced_logit = float(logits_new[batch_index, expected_end_token_id])
|
||||
if forced_logit < 1.0e8:
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
f"Budget exceeded ({think_count} >= "
|
||||
f"{budget}) but not "
|
||||
"forcing end tokens"
|
||||
f"Expected forced end token {expected_end_token_id} "
|
||||
f"with large logit, got {forced_logit}"
|
||||
),
|
||||
batch_index=batch_index,
|
||||
request_params=request_params,
|
||||
step_idx=step_idx,
|
||||
)
|
||||
|
||||
# Validate that only end tokens are allowed
|
||||
end_tokens = tb_processor.reasoning_end_token_ids
|
||||
if len(end_tokens) > 0:
|
||||
expected_end_token_id = end_tokens[
|
||||
min(state["end_count"], len(end_tokens) - 1)
|
||||
]
|
||||
|
||||
# Check logits masking
|
||||
batch_logits = logits_new[batch_index]
|
||||
for token_id in range(len(batch_logits)):
|
||||
logit_value = batch_logits[token_id]
|
||||
|
||||
if token_id == expected_end_token_id:
|
||||
# End token should not be masked
|
||||
if logit_value == -float("inf"):
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
f"End token {token_id} should not be "
|
||||
"masked but is"
|
||||
),
|
||||
batch_index=batch_index,
|
||||
request_params=request_params,
|
||||
step_idx=step_idx,
|
||||
)
|
||||
else:
|
||||
# All other tokens should be masked when forcing end
|
||||
if logit_value != -float("inf"):
|
||||
_raise_error_invalid(
|
||||
msg_suffix=(
|
||||
f"Token {token_id} should be masked "
|
||||
f"when forcing end tokens, but "
|
||||
f"logit={logit_value}"
|
||||
),
|
||||
batch_index=batch_index,
|
||||
request_params=request_params,
|
||||
step_idx=step_idx,
|
||||
)
|
||||
|
||||
|
||||
def _none_validate(
|
||||
test_fakes: LogitsprocsTestFakes,
|
||||
@@ -604,7 +588,7 @@ logitsprocs_test_mapping = {
|
||||
MinTokensLogitsProcessor: LogitsprocTestHelpers(
|
||||
gen_request_fxn=_min_tokens_params, eval_fxn=_min_tokens_validate
|
||||
),
|
||||
ThinkingTokenBudgetLogitsProcessor: LogitsprocTestHelpers(
|
||||
STR_THINKING_BUDGET: LogitsprocTestHelpers(
|
||||
gen_request_fxn=_thinking_budget_params, eval_fxn=_thinking_budget_validate
|
||||
),
|
||||
}
|
||||
@@ -614,20 +598,17 @@ def _get_test_cases() -> list[list[str]]:
|
||||
"""Each test case is a set of logitsprocs"""
|
||||
logitsprocs_types = list(logitsprocs_test_mapping.keys())
|
||||
|
||||
# Isolate ThinkingTokenBudgetLogitsProcessor from all other processors
|
||||
# to avoid unexpected modification of logits interference
|
||||
thinking_processor = ThinkingTokenBudgetLogitsProcessor
|
||||
# Isolate thinking-budget handling from other processors to avoid cross-talk.
|
||||
thinking_id: LogitprocType = STR_THINKING_BUDGET
|
||||
other_processors = [
|
||||
p
|
||||
for p in logitsprocs_types
|
||||
if p != STR_NO_LOGITPROC and p != thinking_processor
|
||||
p for p in logitsprocs_types if p != STR_NO_LOGITPROC and p != thinking_id
|
||||
]
|
||||
|
||||
return (
|
||||
[[STR_NO_LOGITPROC]]
|
||||
+ [[logitproc_type, STR_NO_LOGITPROC] for logitproc_type in other_processors]
|
||||
+ [other_processors]
|
||||
+ [[thinking_processor]]
|
||||
+ [[thinking_id]]
|
||||
)
|
||||
|
||||
|
||||
@@ -802,12 +783,23 @@ def _assert_valid(
|
||||
)
|
||||
|
||||
|
||||
def _slot_outputs_for_metadata(
|
||||
persistent_batch: list[LogitsProcsRequestParams], pad_len: int
|
||||
) -> list[list[int]]:
|
||||
"""Per-batch-slot output token ids aligned with ``SamplingMetadata`` rows."""
|
||||
rows: list[list[int]] = [[] for _ in range(pad_len)]
|
||||
for i, req in enumerate(persistent_batch):
|
||||
if i < pad_len:
|
||||
rows[i] = list(req.out_tokens)
|
||||
return rows
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
@pytest.mark.parametrize("reqs_per_logitproc", [REQS_PER_LOGITPROC])
|
||||
@pytest.mark.parametrize("logitsprocs_under_test", _get_test_cases())
|
||||
def test_logitsprocs(
|
||||
device: str, reqs_per_logitproc: int, logitsprocs_under_test: list[str]
|
||||
device: str, reqs_per_logitproc: int, logitsprocs_under_test: list[LogitprocType]
|
||||
):
|
||||
random.seed(40)
|
||||
torch.set_default_device(device)
|
||||
@@ -855,9 +847,10 @@ def test_logitsprocs(
|
||||
# Apply fake batch update to logitsprocs
|
||||
fake_update_logitsprocs_state(test_fakes, batch_update)
|
||||
|
||||
# Emulate application of logits processors in engine
|
||||
# Emulate application of logits processors + thinking holder (sampler order).
|
||||
slice_idxs = [req.workload_index for req in persistent_batch]
|
||||
logits_w_lp = fake_apply_logitsprocs(test_fakes, slice_idxs).cpu()
|
||||
slot_rows = _slot_outputs_for_metadata(persistent_batch, workload_size)
|
||||
logits_w_lp = fake_apply_logitsprocs(test_fakes, slice_idxs, slot_rows).cpu()
|
||||
|
||||
_assert_valid(
|
||||
batch_size=batch_size,
|
||||
@@ -869,3 +862,263 @@ def test_logitsprocs(
|
||||
)
|
||||
|
||||
step_idx += 1
|
||||
|
||||
|
||||
class MockReasoningNoEndTokens:
|
||||
"""Reasoning config with no end token ids (disables enforcement in holder)."""
|
||||
|
||||
reasoning_start_token_ids = [THINK_START_TOKEN_ID]
|
||||
reasoning_end_token_ids: list[int] = []
|
||||
|
||||
|
||||
def test_maybe_create_thinking_budget_holder_without_reasoning():
|
||||
cfg = VllmConfig()
|
||||
assert cfg.reasoning_config is None
|
||||
assert (
|
||||
maybe_create_thinking_budget_state_holder(
|
||||
None,
|
||||
cfg.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_thinking_budget_holder_has_tracked_after_sync_add():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
assert not h.has_tracked_requests()
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=1,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
0,
|
||||
SamplingParams(thinking_token_budget=3),
|
||||
None,
|
||||
[THINK_START_TOKEN_ID],
|
||||
)
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
assert h.has_tracked_requests()
|
||||
assert h._state[0]["thinking_token_budget"] == 3
|
||||
|
||||
|
||||
def test_thinking_budget_holder_sync_remove_clears_state():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=1,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
0,
|
||||
SamplingParams(thinking_token_budget=3),
|
||||
None,
|
||||
[],
|
||||
)
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
assert h.has_tracked_requests()
|
||||
h.sync_batch(BatchUpdate(batch_size=0, removed=(0,), added=(), moved=()))
|
||||
assert not h.has_tracked_requests()
|
||||
|
||||
|
||||
def test_thinking_budget_holder_sync_add_without_budget_drops_row():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=1,
|
||||
removed=(),
|
||||
added=[(0, SamplingParams(), None, [])],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
assert not h.has_tracked_requests()
|
||||
|
||||
|
||||
def test_thinking_budget_holder_swap_exchanges_state():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=2,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
0,
|
||||
SamplingParams(thinking_token_budget=3),
|
||||
None,
|
||||
[],
|
||||
),
|
||||
(
|
||||
1,
|
||||
SamplingParams(thinking_token_budget=7),
|
||||
None,
|
||||
[],
|
||||
),
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
b0, b1 = h._state[0]["thinking_token_budget"], h._state[1]["thinking_token_budget"]
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=2,
|
||||
removed=(),
|
||||
added=(),
|
||||
moved=[(0, 1, MoveDirectionality.SWAP)],
|
||||
)
|
||||
)
|
||||
assert h._state[0]["thinking_token_budget"] == b1
|
||||
assert h._state[1]["thinking_token_budget"] == b0
|
||||
|
||||
|
||||
def test_thinking_budget_holder_unidirectional_move():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=2,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
1,
|
||||
SamplingParams(thinking_token_budget=4),
|
||||
None,
|
||||
[],
|
||||
),
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
assert 1 in h._state and 0 not in h._state
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=2,
|
||||
removed=(),
|
||||
added=(),
|
||||
moved=[(1, 0, MoveDirectionality.UNIDIRECTIONAL)],
|
||||
)
|
||||
)
|
||||
assert 0 in h._state and 1 not in h._state
|
||||
assert h._state[0]["thinking_token_budget"] == 4
|
||||
|
||||
|
||||
def test_thinking_budget_holder_update_state_repeat_indices_last_row_wins():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningConfig()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=1,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
0,
|
||||
SamplingParams(thinking_token_budget=5),
|
||||
None,
|
||||
[THINK_START_TOKEN_ID],
|
||||
)
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
out_lists = [[THINK_START_TOKEN_ID], [THINK_START_TOKEN_ID, 10, 11, 12, 13, 14]]
|
||||
h.update_state(
|
||||
out_lists,
|
||||
None,
|
||||
torch.tensor([0, 0], dtype=torch.long),
|
||||
)
|
||||
assert h._state[0]["output_tok_ids"] == out_lists[1]
|
||||
|
||||
|
||||
def test_thinking_budget_holder_spec_mode_tensor_layout():
|
||||
h = ThinkingBudgetStateHolder(
|
||||
MockReasoningConfig(),
|
||||
8,
|
||||
2,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
assert h.in_spec_mode
|
||||
assert h.mask.shape[0] == 8 * (2 + 1)
|
||||
|
||||
|
||||
def test_thinking_budget_holder_empty_end_tokens_disables_row():
|
||||
vc = VllmConfig()
|
||||
vc.reasoning_config = MockReasoningNoEndTokens()
|
||||
h = ThinkingBudgetStateHolder(
|
||||
vc.reasoning_config,
|
||||
vc.scheduler_config.max_num_seqs,
|
||||
0,
|
||||
torch.device("cpu"),
|
||||
False,
|
||||
)
|
||||
h.sync_batch(
|
||||
BatchUpdate(
|
||||
batch_size=1,
|
||||
removed=(),
|
||||
added=[
|
||||
(
|
||||
0,
|
||||
SamplingParams(thinking_token_budget=5),
|
||||
None,
|
||||
[THINK_START_TOKEN_ID],
|
||||
)
|
||||
],
|
||||
moved=(),
|
||||
)
|
||||
)
|
||||
h.update_state([[THINK_START_TOKEN_ID, 1]], None, None)
|
||||
assert h._state[0]["thinking_token_budget"] == -1
|
||||
|
||||
@@ -198,22 +198,43 @@ class LogitsprocsTestFakes(NamedTuple):
|
||||
|
||||
def fake_update_logitsprocs_state(
|
||||
test_fakes: LogitsprocsTestFakes,
|
||||
batch_update: BatchUpdate,
|
||||
batch_update: BatchUpdate | None,
|
||||
) -> None:
|
||||
"""Imitate logits processors persistent batch state update
|
||||
in engine core"""
|
||||
for logitproc in test_fakes.get_logitsprocs():
|
||||
logitproc.update_state(batch_update)
|
||||
holder = test_fakes.sampling_metadata.thinking_budget_state_holder
|
||||
if holder is not None:
|
||||
holder.sync_batch(batch_update)
|
||||
|
||||
|
||||
def fake_apply_logitsprocs(
|
||||
test_fakes: LogitsprocsTestFakes,
|
||||
slice_indices: list[int],
|
||||
slot_output_token_ids: list[list[int]] | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Imitate application of logits processors in engine core"""
|
||||
"""Imitate application of logits processors in engine core.
|
||||
|
||||
When ``thinking_budget_state_holder`` has tracked requests, this mirrors
|
||||
:meth:`Sampler.apply_logits_processors` by refreshing per-slot
|
||||
``output_token_ids`` (if ``slot_output_token_ids`` is provided), then
|
||||
``update_state`` + ``apply_to_logits`` on the holder after built-in logits
|
||||
processors.
|
||||
"""
|
||||
logits = test_fakes.logits[torch.tensor(slice_indices, dtype=torch.long)].clone()
|
||||
for processor in test_fakes.get_logitsprocs():
|
||||
logits = processor.apply(logits)
|
||||
|
||||
md = test_fakes.sampling_metadata
|
||||
holder = md.thinking_budget_state_holder
|
||||
if holder is not None and holder.has_tracked_requests():
|
||||
if slot_output_token_ids is not None:
|
||||
for i, toks in enumerate(slot_output_token_ids):
|
||||
if i < len(md.output_token_ids):
|
||||
md.output_token_ids[i] = list(toks)
|
||||
holder.update_state(md.output_token_ids, md.spec_token_ids, None)
|
||||
logits = holder.apply_to_logits(logits, False, md.spec_token_ids)
|
||||
return logits
|
||||
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ def mock_model_runner_with_input_batch():
|
||||
vocab_size=32000,
|
||||
block_sizes=[16],
|
||||
kernel_block_sizes=[16],
|
||||
is_spec_decode=False,
|
||||
logitsprocs=None,
|
||||
is_pooling_model=False,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user