[watermark] compatibility validation (#56801)

Signed-off-by: Raphael Rialland <raphael.rialland@mistral.ai>
Signed-off-by: Simon Veitner <sveitner@redhat.com>
Co-authored-by: Simon Veitner <sveitner@redhat.com>
This commit is contained in:
Raphaël Rialland
2026-10-05 14:37:13 -04:00
committed by GitHub
co-authored by Simon Veitner
parent 88f3c601b3
commit c32495d58f
45 changed files with 1670 additions and 101 deletions
+1
View File
@@ -119,6 +119,7 @@ def main(args: argparse.Namespace):
beam_width=args.n,
max_tokens=args.output_len,
ignore_eos=True,
watermarking=False,
),
)
+3 -1
View File
@@ -241,6 +241,7 @@ def benchmark_multimodal_processor(
temperature=0.0,
max_tokens=output_len,
detokenize=True,
watermarking=False,
)
for output_len in expected_output_lens
]
@@ -262,7 +263,8 @@ def benchmark_multimodal_processor(
warmup_prompts = [req.prompt for req in warmup_requests]
warmup_output_lens = [req.expected_output_len for req in warmup_requests]
warmup_sampling_params = [
SamplingParams(max_tokens=output_len) for output_len in warmup_output_lens
SamplingParams(max_tokens=output_len, watermarking=False)
for output_len in warmup_output_lens
]
llm.chat(
warmup_prompts,
+1
View File
@@ -178,6 +178,7 @@ def _run_vllm_requests(
beam_width=n,
max_tokens=output_len,
ignore_eos=True,
watermarking=False,
),
)
if do_profile:
+47 -7
View File
@@ -60,6 +60,7 @@ if TYPE_CHECKING:
from transformers import PreTrainedConfig
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.sampling_params import BeamSearchParams, SamplingParams
from vllm.v1.kv_cache_interface import KVCacheConfig
else:
PreTrainedConfig = Any
@@ -1314,15 +1315,22 @@ class VllmConfig:
if not self.use_v2_model_runner:
raise ValueError("trace replay requires Model Runner V2")
def _check_watermarking_unsupported(
def _check_supports_watermarking(
self,
config: "SamplingParams | BeamSearchParams | None" = None,
*,
beam_search: bool = False,
custom_sampler: bool = False,
) -> None:
) -> bool:
watermark_config = getattr(self, "watermark_config", None)
if watermark_config is None:
return
if config is not None and config.watermarking is not False:
logger.warning_once(
"Watermarking is enabled for this request, but the engine has no "
"watermark configuration. This and subsequent requests will run "
"without watermarking.",
scope="global",
)
return False
if self.speculative_config is not None:
speculative_config = self.speculative_config
if speculative_config.draft_sample_method != "probabilistic":
@@ -1377,12 +1385,44 @@ class VllmConfig:
watermark_config.alpha,
scope="global",
)
if beam_search:
raise ValueError("Beam search is not supported with watermarking.")
if custom_sampler:
raise ValueError(
"Model-specific custom samplers are not supported with watermarking."
)
if config is None:
return True
if config.watermarking is False:
return False
from vllm.sampling_params import BeamSearchParams, SamplingParams
if isinstance(config, BeamSearchParams):
logger.warning_once(
"Watermarking is enabled, but beam search cannot be watermarked. "
"This and subsequent beam search requests will run without "
"watermarking.",
scope="global",
)
return False
if not isinstance(config, SamplingParams):
raise TypeError(f"Unsupported watermarking config: {type(config).__name__}")
if config.trace_decode_token_ids is not None:
logger.warning_once(
"Watermarking is enabled, but trace replay cannot be watermarked. "
"This and subsequent trace replay requests will run without "
"watermarking.",
scope="global",
)
return False
if config.temperature == 0:
logger.warning_once(
"Watermarking is enabled, but greedy decoding "
"(temperature=0) cannot be watermarked. This and subsequent "
"greedy requests will use ordinary greedy sampling.",
scope="global",
)
return False
return True
def _resolve_and_verify_engram_config(self) -> None:
"""Resolve defaults and validate n-gram embedding settings."""
@@ -1446,7 +1486,7 @@ class VllmConfig:
self.try_verify_and_update_config()
self._resolve_and_verify_engram_config()
self._check_watermarking_unsupported()
self._check_supports_watermarking()
# Models may have supplied their own DCP defaults above; anything still
# unset falls back to the stock ones.
self.parallel_config.set_dcp_defaults()
+6
View File
@@ -242,6 +242,12 @@ class AnthropicMessagesRequest(BaseModel):
"to 256 bit)."
),
)
watermarking: bool | None = Field(
default=None,
description=(
"Whether to apply the engine's configured watermark to this request."
),
)
kv_transfer_params: dict[str, Any] | None = Field(
default=None,
description="KVTransfer parameters used for disaggregated serving.",
+1
View File
@@ -613,6 +613,7 @@ class AnthropicServingMessages(OpenAIServingChat):
temperature=anthropic_request.temperature,
top_p=anthropic_request.top_p,
top_k=anthropic_request.top_k,
watermarking=anthropic_request.watermarking,
cache_salt=anthropic_request.cache_salt,
kv_transfer_params=anthropic_request.kv_transfer_params,
ec_transfer_params=anthropic_request.ec_transfer_params,
+6
View File
@@ -175,6 +175,12 @@ class CohereChatV2Request(BaseModel):
# vLLM-specific extensions (not in Cohere spec). These mirror what the
# Anthropic and OpenAI surfaces already expose so V2 callers can reach
# the same engine knobs when needed.
watermarking: bool | None = Field(
default=None,
description=(
"Whether to apply the engine's configured watermark to this request."
),
)
kv_transfer_params: dict[str, Any] | None = Field(
default=None,
description="KVTransfer parameters used for disaggregated serving.",
+1
View File
@@ -557,6 +557,7 @@ class CohereServingChatV2(OpenAIServingChat):
temperature=request.temperature,
top_p=request.p,
top_k=request.k,
watermarking=request.watermarking,
seed=request.seed,
frequency_penalty=request.frequency_penalty,
presence_penalty=request.presence_penalty,
@@ -82,7 +82,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
temperature = params.temperature
ignore_eos = params.ignore_eos
length_penalty = params.length_penalty
self.llm_engine.vllm_config._check_watermarking_unsupported(beam_search=True)
self.llm_engine.input_processor.resolve_watermarking(params)
tokenizer = self.renderer.get_tokenizer()
eos_token_id = tokenizer.eos_token_id
@@ -120,6 +120,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
logprobs=2 * beam_width,
max_tokens=1,
temperature=temperature,
watermarking=False,
detokenize=False,
skip_clone=True, # Internal beam search, safe to skip clone
)
@@ -457,6 +458,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
logprobs=base_params.logprobs,
max_tokens=1,
temperature=base_params.temperature,
watermarking=base_params.watermarking,
detokenize=False,
allowed_token_ids=(
allowed_ids
@@ -40,6 +40,7 @@ class BeamSearchOnlineMixin(ABC):
temperature = params.temperature
length_penalty = params.length_penalty
include_stop_str_in_output = params.include_stop_str_in_output
self.engine_client.input_processor.resolve_watermarking(params)
tokenizer = self.renderer.get_tokenizer()
eos_token_id = tokenizer.eos_token_id
@@ -62,6 +63,7 @@ class BeamSearchOnlineMixin(ABC):
logprobs=logprobs_num,
max_tokens=1,
temperature=temperature,
watermarking=False,
detokenize=False,
)
all_beams = [
@@ -261,6 +261,7 @@ class ServingGenerativeScoring(BaseServing):
logprobs=len(request.label_token_ids),
logprob_token_ids=request.label_token_ids,
n=1,
watermarking=False,
)
# Get trace headers
@@ -268,7 +268,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
top_k: int | None = None
min_p: float | None = None
repetition_penalty: float | None = None
watermarking: bool = True
watermarking: bool | None = None
length_penalty: float = 1.0
stop_token_ids: list[int] | None = []
include_stop_str_in_output: bool = False
@@ -647,6 +647,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
max_tokens=max_tokens,
ignore_eos=self.ignore_eos,
temperature=temperature,
watermarking=self.watermarking,
length_penalty=self.length_penalty,
include_stop_str_in_output=self.include_stop_str_in_output,
skip_special_tokens=self.skip_special_tokens,
@@ -1100,6 +1101,7 @@ class BatchChatCompletionRequest(OpenAIBaseModel):
top_k: int | None = None
min_p: float | None = None
repetition_penalty: float | None = None
watermarking: bool | None = None
length_penalty: float | None = 1.0
early_stopping: bool = False
structured_outputs: StructuredOutputsParams | None = None
@@ -75,7 +75,7 @@ class CompletionRequest(OpenAIBaseModel):
top_k: int | None = None
min_p: float | None = None
repetition_penalty: float | None = None
watermarking: bool = True
watermarking: bool | None = None
length_penalty: float = 1.0
stop_token_ids: list[int] | None = []
include_stop_str_in_output: bool = False
@@ -303,6 +303,7 @@ class CompletionRequest(OpenAIBaseModel):
max_tokens=max_tokens,
ignore_eos=self.ignore_eos,
temperature=temperature,
watermarking=self.watermarking,
length_penalty=self.length_penalty,
include_stop_str_in_output=self.include_stop_str_in_output,
skip_special_tokens=self.skip_special_tokens,
@@ -245,7 +245,7 @@ class ResponsesRequest(OpenAIBaseModel):
)
# --8<-- [start:responses-extra-params]
watermarking: bool = True
watermarking: bool | None = None
request_id: str = Field(
default_factory=lambda: f"resp_{random_uuid()}",
description=(
@@ -229,6 +229,7 @@ class SpeechToTextBaseServing(GenerateBaseServing):
max_tokens=1,
temperature=0.0,
allowed_token_ids=allowed_token_ids,
watermarking=False,
)
result_generator = self.engine_client.generate(
@@ -151,6 +151,9 @@ class TranscriptionRequest(OpenAIBaseModel):
to automatically increase the temperature until certain thresholds are hit.
"""
watermarking: bool | None = None
"""Whether to apply the engine's configured watermark to this request."""
top_p: float | None = None
"""Enables nucleus (top-p) sampling, where tokens are selected from the
smallest possible set whose cumulative probability exceeds `p`.
@@ -226,6 +229,7 @@ class TranscriptionRequest(OpenAIBaseModel):
beam_width=n,
max_tokens=max_tokens,
temperature=temperature,
watermarking=self.watermarking,
length_penalty=self.length_penalty,
include_stop_str_in_output=self.include_stop_str_in_output,
)
@@ -264,6 +268,7 @@ class TranscriptionRequest(OpenAIBaseModel):
return SamplingParams.from_optional(
temperature=temperature,
watermarking=self.watermarking,
max_tokens=max_tokens,
seed=self.seed,
top_p=top_p,
@@ -102,6 +102,9 @@ class TranslationRequest(OpenAIBaseModel):
to automatically increase the temperature until certain thresholds are hit.
"""
watermarking: bool | None = None
"""Whether to apply the engine's configured watermark to this request."""
top_p: float | None = None
"""Enables nucleus (top-p) sampling, where tokens are selected from the
smallest possible set whose cumulative probability exceeds `p`.
@@ -215,6 +218,7 @@ class TranslationRequest(OpenAIBaseModel):
beam_width=n,
max_tokens=max_tokens,
temperature=temperature,
watermarking=self.watermarking,
length_penalty=self.length_penalty,
include_stop_str_in_output=self.include_stop_str_in_output,
)
@@ -251,6 +255,7 @@ class TranslationRequest(OpenAIBaseModel):
return SamplingParams.from_optional(
temperature=temperature,
watermarking=self.watermarking,
max_tokens=max_tokens,
seed=self.seed,
top_p=top_p,
+7 -3
View File
@@ -251,8 +251,9 @@ class SamplingParams(
"""Controls the randomness of the sampling. Lower values make the model
more deterministic, while higher values make the model more random. Zero
means greedy sampling."""
watermarking: bool = True
"""Whether to apply the engine's configured watermark to this request."""
watermarking: bool | None = None
"""Whether to apply the engine's configured watermark to this request.
``None`` defaults to enabled."""
top_p: float = 1.0
"""Controls the cumulative probability of the top tokens to consider. Must
be in (0, 1]. Set to 1 to consider all tokens."""
@@ -342,6 +343,7 @@ class SamplingParams(
output_text_buffer_length: int = 0
_eos_token_id: int | None = None
_all_stop_token_ids: set[int] = msgspec.field(default_factory=set)
_watermarking_skipped: bool = False
# Fields used to construct logits processors
structured_outputs: StructuredOutputsParams | None = None
@@ -395,7 +397,7 @@ class SamplingParams(
frequency_penalty: float | None = 0.0,
repetition_penalty: float | None = 1.0,
temperature: float | None = 1.0,
watermarking: bool = True,
watermarking: bool | None = None,
top_p: float | None = 1.0,
top_k: int = 0,
min_p: float = 0.0,
@@ -1411,6 +1413,7 @@ class SamplingParams(
_bad_words_token_ids=[[0], [1, 2]],
logprobs=5,
prompt_logprobs=1,
watermarking=True,
)
@@ -1430,6 +1433,7 @@ class BeamSearchParams(
include_stop_str_in_output: bool = False
structured_outputs: StructuredOutputsParams | None = None
skip_special_tokens: bool = True
watermarking: bool | None = None
def __post_init__(self) -> None:
_verify_num_sequences(self.beam_width, "beam_width")
+8
View File
@@ -443,6 +443,13 @@ class AsyncLLM(EngineClient):
"does not match the EngineCoreRequest.request_id attribute. The "
"latter will be used, and the former will be ignored."
)
request_params = request.params
if isinstance(request_params, SamplingParams):
# This request object is owned by the engine from here on.
self.input_processor.apply_watermarking(
request_params,
self.input_processor.resolve_watermarking(request_params),
)
else:
if isinstance(prompt, dict) and "type" in prompt:
# Rendered EngineInput; no blocking preprocessing needed.
@@ -910,6 +917,7 @@ class AsyncLLM(EngineClient):
sampling_params=SamplingParams(
max_tokens=1,
extra_args={"kv_transfer_params": dict(kv_transfer_params)},
watermarking=False,
),
pooling_params=None,
arrival_time=time.time(),
+42 -4
View File
@@ -25,7 +25,7 @@ from vllm.platforms import current_platform
from vllm.pooling_params import PoolingParams
from vllm.renderers import BaseRenderer, renderer_from_config
from vllm.renderers.inputs.preprocess import parse_model_prompt
from vllm.sampling_params import SamplingParams
from vllm.sampling_params import BeamSearchParams, SamplingParams
from vllm.tasks import GENERATION_TASKS, POOLING_TASKS, SupportedTask
from vllm.tokenizers import TokenizerLike
from vllm.utils import length_from_prompt_token_ids_or_embeds, random_uuid
@@ -112,12 +112,41 @@ class InputProcessor:
return partial(validate_logits_processors_parameters, custom_logitsprocs)
def resolve_watermarking(self, params: SamplingParams | BeamSearchParams) -> bool:
"""Return whether watermarking will be applied to this request.
``None`` and ``True`` request watermarking, while ``False`` opts out.
If watermarking is unavailable or incompatible with the request, emit
a warning and return ``False``.
"""
return self.vllm_config._check_supports_watermarking(params)
def apply_watermarking(self, params: SamplingParams, watermarking: bool) -> None:
"""Store the resolved `watermarking` on request-local params.
Also records whether watermarking was requested on a watermarking
engine but could not be applied, as opposed to an explicit opt-out.
"""
# Sticky, so resolving an already resolved request keeps the flag.
params._watermarking_skipped = params._watermarking_skipped or (
self.vllm_config.watermark_config is not None
and params.watermarking is not False
and not watermarking
)
params.watermarking = watermarking
def _validate_params(
self,
params: SamplingParams | PoolingParams,
supported_tasks: tuple[SupportedTask, ...],
) -> None:
"""Raise `ValueError` if SamplingParams or PoolingParams is not valid."""
) -> bool | None:
"""Raise `ValueError` if SamplingParams or PoolingParams is not valid.
Returns the resolved `watermarking` value for `SamplingParams` (`None`
for `PoolingParams`). The caller applies it to its private copy of the
params so that a caller-owned params object is never mutated.
"""
watermarking: bool | None = None
if isinstance(params, SamplingParams):
supported_generation_tasks = [
task for task in supported_tasks if task in GENERATION_TASKS
@@ -189,6 +218,9 @@ class InputProcessor:
"enabled. Start the engine with --enable-trace-replay "
"to use it."
)
# Resolved last so that feature gates above report the missing
# feature rather than its incompatibility with watermarking.
watermarking = self.resolve_watermarking(params)
elif isinstance(params, PoolingParams):
supported_pooling_tasks = [
task for task in supported_tasks if task in POOLING_TASKS
@@ -217,6 +249,8 @@ class InputProcessor:
f"but got {type(params).__name__}"
)
return watermarking
def _normalize_trace_replay_params(
self, sampling_params: SamplingParams, prompt_len: int
) -> None:
@@ -352,7 +386,7 @@ class InputProcessor:
session_id: str | None = None,
kv_hints: KvHintsEnvelope | None = None,
) -> EngineCoreRequest:
self._validate_params(params, supported_tasks)
watermarking = self._validate_params(params, supported_tasks)
self._validate_lora(lora_request)
parallel_config = self.vllm_config.parallel_config
@@ -413,6 +447,10 @@ class InputProcessor:
if isinstance(params, SamplingParams):
# TODO: can we avoid cloning here in multiproc case?
sampling_params = params.clone()
# Resolve on the request-local copy: `params` may be shared across
# prompts, requests and even engines by the caller.
assert watermarking is not None
self.apply_watermarking(sampling_params, watermarking)
prompt_len = length_from_prompt_token_ids_or_embeds(
prompt_token_ids, prompt_embeds
)
+7
View File
@@ -254,6 +254,13 @@ class LLMEngine:
"does not match the EngineCoreRequest.request_id attribute. The "
"latter will be used, and the former will be ignored."
)
request_params = request.params
if isinstance(request_params, SamplingParams):
# This request object is owned by the engine from here on.
self.input_processor.apply_watermarking(
request_params,
self.input_processor.resolve_watermarking(request_params),
)
else:
request = self.input_processor.process_inputs(
request_id,
+1 -1
View File
@@ -221,7 +221,7 @@ class DualKeyGumbelWatermarkDetector(GumbelWatermarkDetector):
p_value_threshold: float = 0.01,
prf: WatermarkPRFName = "philox",
deduplicate_contexts: bool = True,
alpha: float = 0.2,
alpha: float = 0.1,
) -> None:
if not 0 <= alpha <= 1:
raise ValueError("alpha must be between 0 and 1")
+1 -1
View File
@@ -482,7 +482,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
custom = self.model_state.custom_sampler(self.sampler)
if custom:
self.vllm_config._check_watermarking_unsupported(custom_sampler=True)
self.vllm_config._check_supports_watermarking(custom_sampler=True)
self.sampler, self.rejection_sampler = custom
elif self.speculative_config is not None:
self.rejection_sampler = RejectionSampler(
+5 -1
View File
@@ -139,7 +139,11 @@ def run_mixed_prefill_decode_warmup(
next_block_id += num_blocks
return block_ids
sampling_params = SamplingParams(max_tokens=2, temperature=0.0)
sampling_params = SamplingParams(
max_tokens=2,
temperature=0.0,
watermarking=False,
)
decode_prefill_output = SchedulerOutput.make_empty()
decode_prefill_output.scheduled_new_reqs = [