Repository navigation
[Fix] openai: Validate sampling bounds and preserve chat output limits - #44047
Conversation
95a3519 to
3181bca
Compare
A huge `n` was only rejected after GenerateReqInput had multiplied every input by n (n=3,000,000 took ~113 s and ~18 GB before a 400; n=0 failed with a confusing range() error). - Validate `n` (int in [1, MAX_N=128], bool rejected) in `_handle_parallel_sampling` before any input is expanded, for dict and list sampling_params; keep the same check in SamplingParams.verify. - Bound `n` in the chat and completions request models. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Values that pass request parsing but are invalid for the loaded model could kill the scheduler or garble a batch. - `stop_token_ids` must lie in [0, vocab_size); an id of -1 with `min_new_tokens` hit a CUDA device-side assert. - `logit_bias` values must be finite numbers with |bias| <= 1e30: the float32 bias is divided by a temperature of at least 1e-6, so anything larger overflows to inf and NaNs the softmax. - `top_logprobs_num` must be an integer in [0, vocab_size] when logprobs are requested; torch.topk fails past the vocab size. - Chat `top_logprobs` and `temperature` reject negative values, and temperature rejects inf/nan. - Deliberately leave OpenAI-only limits (temperature <= 2, top_logprobs <= 20, logit_bias in [-100, 100], top_logprobs requires logprobs) unenforced: the engine applies those values correctly and existing clients rely on that. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Chat used `max_completion_tokens or max_tokens`, so an explicit `max_completion_tokens=0` fell back to the legacy limit (or the default), and a preferred limit hid a negative legacy one. - Add `effective_max_tokens`: `max_completion_tokens` wins when set, including an explicit 0. Chat conversion and the context-length check both use it. - Require `max_tokens` and `max_completion_tokens` to be non-negative. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
3181bca to
8fadbaa
Compare
This comment has been minimized.
This comment has been minimized.
|
@TheDuyIT Could you fix the title? Meanwhile, some high level comments that I have:
|
| # The scheduler only reads it when logprobs are requested; a non-int or | ||
| # negative value garbles the batch and torch.topk fails past the vocab size. | ||
| top_logprobs_num = obj.top_logprobs_num | ||
| if not obj.return_logprob or top_logprobs_num is None: |
There was a problem hiding this comment.
Would batch with mixed return logprob slip through the validation?
There was a problem hiding this comment.
No, a mixed batch can't slip through. The batch path validates each item through obj[i], so every item's own return_logprob decides whether its top_logprobs_num is checked. For return_logprob=[True, False, True] with top_logprobs_num=[33, 33, 5] and vocab size 32, only item 0 is rejected. I added test_top_logprobs_num_is_validated_per_item_in_a_mixed_batch 7b71afb to cover this.
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
|
Thanks @YouNeedCryDear
|
Document the bounds enforced on n, stop_token_ids, logit_bias, top_logprobs and chat output limits, the OpenAI limits that are deliberately not enforced, and how admission errors are reported for stream=true. Correct the logit_bias range in the OpenAI-compatible API page: values are not restricted to [-100, 100], only to finite numbers up to 1e30. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
| @@ -528,18 +528,26 @@ def _handle_beam_search_parallel_sampling(self) -> int: | |||
| return 1 | |||
| return self.parallel_sample_num | |||
|
|
|||
| @staticmethod | |||
| def _validated_n(sampling_params: Dict[str, Any]) -> int: | |||
There was a problem hiding this comment.
Would it make more sense to move this to SamplingParams.verify()
There was a problem hiding this comment.
Done in 97f2aa4: moved the check into sampling_params.validate_n() so the logic lives in one place, and SamplingParams.verify() calls it. io_struct.py still calls validate_n too, because _handle_parallel_sampling multiplies the inputs by n before SamplingParams.verify() runs. On main, n=10**7 spends ~17 s and ~3.9 GB in normalization before anything is verified.
…SamplingParams.verify Move the n bound check into sampling_params.validate_n and call it from both SamplingParams.verify and GenerateReqInput._handle_parallel_sampling. The early call stays because normalize_batch_and_arguments multiplies the inputs by n before SamplingParams.verify runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@TheDuyIT could you resolve the conflicts and allow maintainers to modify our PR? Thanks |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks @nvpohanh ! The conflicts are resolved, and maintainer edits are enabled. |
|
/rerun-test test/registered/unit/beam_search/test_beam_search_core.py test/registered/unit/entrypoints/openai/test_protocol.py test/registered/unit/entrypoints/openai/test_serving_chat.py test/registered/unit/entrypoints/openai/test_serving_decisions.py test/registered/unit/entrypoints/openai/test_serving_completions.py test/registered/unit/managers/test_io_struct.py test/registered/unit/managers/test_sampling_mask_validation.py test/registered/unit/managers/test_tokenizer_manager_rid_cleanup.py test/registered/unit/sampling/test_penaltylib.py test/registered/unit/sampling/test_sampling_params.py test/registered/unit/sampling/test_sampling_batch_info.py |
|
🚀 🚀 |
|
/rerun-failed-ci |
2 similar comments
|
/rerun-failed-ci |
|
/rerun-failed-ci |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged the latest main (e8017bc) to pick up the fixes for the two CI failures that weren't from this PR:
|
|
/rerun-failed-ci |
1 similar comment
|
/rerun-failed-ci |
|
CI is green on CUDA (41/41), PR Test Extra (38/38), AMD (22/22), NPU, Lint, Arm64, MUSA, PPU, sgl-router, and sglang-processor. The remaining red checks don't touch this PR's code:
Could you take a look and merge when you get a chance? |
|
Merging. Thanks |
…-num Resolve the tokenizer_manager.py conflict by taking main's _validate_top_logprobs_num (sgl-project#44047), which supersedes this PR's version. Drop the duplicate TokenizerManager test (main's test_sampling_mask_validation.py covers it) and the chat top_logprobs=-1 subtest, which the protocol now rejects with ge=0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arkers consumed; both named classes dead - brp sgl-project#46272 id-set RE-PLANTED at the two sites the take-upstream reverted to O(B) req-in-list scans: the finish-side _prepare_kv_cache_release predicate and the checkpoint elif now consume the per-row is_decoding_req id-set (the sgl-project#49253 deferred kv_ops shape kept -- fork predicate onto upstream structure; entry-265 interlock re-verified: mamba_untracked_decode_batch_idx + its brp arm were DELETED upstream by sgl-project#48328 (02db123) together with the next==last hazard they guarded -> ADOPTED, mixed_track tests re-pinned). - detokenizer: ADOPTED sgl-project#47338 (add6f6d) state-machine move; the fork's sent_offset anti-retreat max() clamp RE-PLANTED at its new home (DetokenizeState.step) -- test_detokenizer_stream_offsets.py 6F -> 7P/3sub, driving _update_detokenize_states + the header-seeded state table. - io_struct: ADOPTED upstream's env-bounded validate_n gate (sgl-project#44047 b2616ca subsumes the entry-157 static-128 loop; both validator helpers stay unit-tested in test_sampling_params) -- the dossier's 'entry-265 brp track field' label on region@551 is a misattribution (the field never lived in io_struct; verified by fork-delta audit). 4 fork-era normalization tests re-pinned to the new contract (above-max bound, null-n, beam message, per-element bound). - tokenizer_manager: DEDUPE candidate resolved as the union -- upstream's return_logprob gate (the mask-validation tests prove the disabled-row design) + the fork's shared validate_top_logprobs_num delegation; the fork-era io_struct top_logprobs test re-pinned to return_logprob=True. - brp mixed_token_ids_logprob ctor seam: enable_overlap fields retired by sgl-project#49019 (d1d317c); harness follows the merged class (still_in_batch, kv_weight_version_tracker, request_retirer, forward_iter, still_in_batch_rows, real LogprobResultProcessor). 3P. - test_sampling_params test_beam_n_below_one_raises message regex re-pinned (validate_n now fires before the beam branch); its sibling test_n_bounds vs test_n_above_max_raises double-gate tension in sampling_params.verify is PRE-EXISTING cascade damage (union of both gates), outside every battery dir -- handed to B6 (env registration). Targeted: 158P + 128sub (io_struct+mask+rid+brp+detok) + sampling sweep. Gates: ruff repo ruleset + format; registration trio rc=0.
…server_args field-order markers, C2's own file) -- WHEEL PAIRING RESOLVED AS VERIFICATION + TWO TREE-SIDE REVERTS TO VENV TRUTH pairing matrix (tree pin | venv | verdict): flashinfer_python[cu13]==0.7.2 | 0.7.2 | MATCH -- engine assert 0.7.2 matches too, sgl-project#48468's 0.7.3 stays HELD (entry-228 rule: wheel+floor move together; docker/Dockerfile* FLASHINFER_VERSION=0.7.3 leaked in with the window -> REVERTED to 0.7.2 to honor pyproject's own "keep aligned with Dockerfile" comment). sglang-kernel==0.4.10 | 0.4.10 | MATCH, engine floor 0.4.9 <= installed (floor-assert is a floor, not a pin). blake3>=1.0.0 | 1.0.11 | SATISFIED (sgl-project#47120 dep). torch==2.14.1 | 2.14.1 | MATCH. nvidia-cutlass-dsl[cu13]==4.8.0 | 4.8.0 | MATCH (b12x >=4.6.0 requirement satisfied). triton: unpinned in pyproject | 3.8.0 | n/a. drift pair REVERTED TO VENV (live-tree law: fix tree, never venv; era base 2d87757 -- the FIRST POST-MERGE PROD BOOT 321 -- pinned exactly the venv versions and the check_dockerfile_wheel_pins gate passed at the base): sgl-deep-gemm 0.2.7->0.2.3.post2 (pyproject + Dockerfile.cu134 DEEPGEMM_REF/SGL_DEEP_GEMM_VERSION), sgl-flash-mla 1.0.4->1.0.0 (pyproject; builder Dockerfile sources-only, no version to move). reachability evidence (deep-reconcile obligation): both wheels import on the live path (SGLANG_ENABLE_JIT_DEEPGEMM default True; SM120 configurer probe fp8_einsum/m_grouped_fp8_fp4_gemm_nt_contiguous/transform_sf_into_required_layout ALL PRESENT in 0.2.3.post2). Every window-grown API the tree touches that 0.2.3.post2/1.0.0 LACK is guarded or arch-inert: get/set_compile_mode behind hasattr (compile_utils.py:252); sparse_decode_num_sm_parts behind supports_native_heads (flash_mla_interface.py:41-44); tf32_hc_prenorm_gemm_dual only on current_arch().is_sm(10) (mhc.py:2772, SM100 -- ours is SM120) inside the dsv4-only mhc sinkhorn route; deep_gemm.localize inside the dsv4 mega_moe weight-localize block. Residual symbol sweep vs the installed wheels: zero ungated misses. non-wheel markers: exec_.py b12x FP8-GEMM help clause RE-PLANTED (choice exists in choices.py since the entry-316 port; help silently lost it); memory.py fast_file descriptor RE-PLANTED (+ server_arguments.mdx row, keeps the new npu_memcache/tensorcast/seaweedfs entries); exec_.py PLE-staging help + server_arguments.mdx PLE row = OBSOLETE-CONSUMED (upstream rewrote the mechanism to direct pageable reads, qwen4_exp_ple_table.py:17-19 documents it, the staging/limits prose describes a removed path); hicache_best_practices.mdx DUAL block = SUPERSEDED-CONSUMED (current text matches the file_storage_path config generation, fast_file_store.py:22); model_hook.py Gemma4: fork flashinfer acceptance RE-HOMED into gemma4_attention_backends() exactly as the marker prescribed (_BUILTIN_ATTENTION_BACKENDS += "flashinfer"; contested-message marker consumed -- the f-string now interpolates the helper, so no stale list can rot); sampling_params.mdx n-bound row = the sgl-project#44047 env-bounded doc, already correct, consumed (its contract is C3's anchor); engine.py pairing marker converted to the durable VERIFIED note; pyproject flashinfer marker likewise. gates: ruff repo ruleset + format clean on all 5 touched .py; check_registered_tests / check_no_registered_tests_in_package / check_no_bare_pytest_main / check_opt_in_ci_tiers / check_dockerfile_wheel_pins ALL rc=0 (the wheel-pin gate was BROKEN by the window's 0.2.7 landing and is GREEN again only because of the revert).
…roject#44047's env-bounded validate_n subsumes the closed PR sgl-project#42779's static validate_sample_count at the verify() boundary; sampling dir 1F -> 0F (252P/98sub) POLICY RECORD: io/sampling... er, sampling/sampling_params.py carried BOTH gates after B4's re-plant (validate_n(sgl-project#44047 env, default 4096, -1 disables, at verify's top) AND validate_sample_count(sgl-project#42779 hard 128 + beam bypass, mid-verify)), which made test_n_bounds (upstream's, sgl-project#44047: n=129 and n=4096 must PASS verify at env 4096) and test_n_above_max_raises (fork's, sgl-project#42779: MAX_PARALLEL_SAMPLES+1=129 must RAISE) mutually exclusive as LITERALLY PROVEN: identical inputs (same class, same _make, same vocab, env default == override == 4096) demand opposite verdicts; no gate placement, message form, or constant redefinition can satisfy both (raising MAX_PARALLEL_SAMPLES to 4096 fixes the sampling file but breaks the managers' beam io_struct pins that use MAX_PARALLEL_SAMPLES+1 AS AN IN-BOUNDS value). Reading of the two PR bodies decides: sgl-project#42779 was CLOSED unmerged (author self-closed 2026-10-09; our port 12e7933 evaluated it); sgl-project#44047 was MERGED (b2616ca) and is the same crash class re-implemented as the env-tunable cap with Rust-server parity -- and the merge resolution ALREADY adopted it at the ONLY site sgl-project#42779 ever mattered (io_struct pre-fan-out, its own comment: 'this env-bounded gate supersedes the fork's static MAX_PARALLEL_SAMPLES/beam-aware loop'; the sgl-project#42779 port itself noted 'verify() runs too late' -- the belt here was never the enforcement point). UNION PRESERVING BOTH INTENTS: (1) sgl-project#42779's -- no oversized n replicates the prompt -- stays enforced pre-fan-out by the env gate (test_parallel_sampling_n_above_max_raises_before_fan_out green, managers dir); beam-slice n>=1 covered by validate_n's type/positive check at both boundaries; top_k/top_logprobs vocab bounds untouched. (2) sgl-project#44047's -- bound is the env, not OpenAI's 128, negative disables, parity with the Rust server -- restored intact in verify(). The static 128 verify-time cap was the genuinely obsolete contract (a double belt predating sgl-project#44047); it is dropped from verify(), validate_sample_count is removed with its last caller, and MAX_PARALLEL_SAMPLES survives as the documented reference constant (io_struct beam tests + docs reference it). test_n_above_max_raises is RE-PINNED to the default env ceiling (4096+1 raises) in the exact style B4 used on its io_struct siblings, with a pointer to the policy note; no test lost, no safety intent weakened -- an operator restores the historical hard 128 with one env value, SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ=128. Gate check: sampling battery 252P/0F/98sub (was 1F); ruff ruleset+format clean; four check_* rc=0.
…+ re-plant era CLOSED at b86b7c9 (125/125 markers; grep census ZERO verified at this tree): header STACK epoch 321-2026-10-30 -> 329-2026-11-10 (supersession note kept) + +merge6-era-closeout-2026-11-10 trailer line + entries-count 1-329; tip/HEAD re-pinned (era CODE TIP b86b7c9 NAMED with the full wave chain, superseded values dea2641/e9f0ae1838/065fdcdf33/b7c656f69f/5cde7a5ede kept, docs tip recorded as this wave) + a prominent ** LIVE/BOOT STATE ** line (main checkout detached @ 2d87757 = the ONLY boot-validated state, 9b 16:58:52 warm all-needles-hit per prod-health-2026-11-10.txt; era branch CPU-green but NOT BOOTED -- switching prod = operator-chosen checkout + the entry-326 boot-watch). ENTRY 324: imports+bootfix trunk wave -- sgl-project#48781 require_attn_tp_gather->dp_attention relocation invisible to markers, base_runner deletion-only fix unmasking the 145E/32E/31E collection cascade (1dcc2d6); THEN the operator-live crash: maybe_init_router_registration read tokenizer_ipc_name before init_ipc_channels at OUR fork's entry-201 init order, call moved back to upstream's position, RED(2F)/GREEN(2P) test_tokenizer_manager_init_order.py, family scan clean + report-only carry (10a1c08). ENTRY 325: RE-PLANT ERA TABLE b1 12 / b3 18 / b4 39 / b5 17 / b2 23 / b6 16 = 125/125 per-wave dispositions (compressed from the commit bodies, all shas cited) + the NINE ERA CATCHES with FULL CREDIT: _rope_cache_key 10/11-arg universal get_rope crash (15 spec F were its fingerprints), PLE file-backend env registration gap (AttributeError every boot), COW-catcher doubled-staging-arm cascade bug, stat_loggers DI test restored from its corrupted merge hybrid, w13 refined-grid mis-key, the budget-contract decision (fork accounting RESTORED, evidence 106.9GB/100GB = the entry-317 leak shape; INDEXER collective order verified), verify-gate SUBSUME pick (sgl-project#44047 eats sgl-project#42779, both intents preserved), mm_process_config ambient-widths root-cause (validators now state the full 8-way layout), TLFIX twin re-pinned 282/285. ENTRY 326: BATTERY RE-PIN TABLE -- era pins managers 1307P/0F, spec 406P/0F, server_args 496P/0F, sampling 252P/0F, distributed 213P/0F, mem_cache 2965P/24F (the ACCEPTED device-only 24-node list over 8 files), cargo 966P/0F/1-ignored, five registration/wheel gates rc=0 + the PATH-TO-BOOTABLE statement: CPU-proven vs GPU-window debt -- first-boot needles incl. the sampling.cuh-vs-0.7.2 JIT arbitration (if it JIT-fails, wheel-trio-then-pin per S-FI073, never a lone re-pin), autotune caches SHOULD hit warm (no retune owed on 0.7.2), entry-322 verify-at-boot quartet, and the still-riding 321-era watches (sgl-project#45472/sgl-project#46643 TTFT+starvation, first-delta tool-stream latency). ENTRY 327: WHEELS & VENV RECORD -- pairing matrix (FI 0.7.2 HELD, sgl-kernel 0.4.10/0.4.10 era-consistent with the RETIRED-rule cross-ref, torch/cutlass-dsl MATCH), blake3 1.0.11 INSTALLED with ZERO-DRIFT PROOF (0 battery lines vs ~380; matrix re-read unchanged; negative-shim prefix-sim causality) + no-pip/uv-note (operator lane), the two tree-side wheel reverts with reachability + residual-symbol evidence, check_dockerfile_wheel_pins re-green, FI-0.7.3 adoption contract restated with post-era facts (upstream code now expects 0.7.3 in one reported JIT path; tree HELD 0.7.2; first boot arbitrates), dist-name/module-name note sglang_kernel/sgl_kernel. ENTRY 328: INCIDENT RECORD 2026-11-10 ~16:4x-16:58, honest narrative -- re-plant waves landed into the EDITABLE-IMPORT working tree while :30000/:30001 ran; 9b died ~pre-16:50 (cause UNVERIFIABLE from the user acct, /root logs unreadable; worker-respawn-importing-changed-code is the LEADING MECHANISM, stated AS SUCH); the operator restart hit the init-order crash = the era's flagship find; recovery = merge6-era-backup @ b069e6a + detached checkout 2d87757, 9b re-booted WARM 16:58:52 all needles hit, 9d NEVER dropped (Nov 3, HTTP 200); NEW ERA LAW: working tree = prod import path, integration by branch ref-move ONLY; b2's emergency-freeze WIP 7ccf76a (author 16:55:02) kept in range and completed as C1 -- provenance note. ENTRY 329: BACKFILL AUDIT RECORD -- window 2026-08-10..2026-10-27, universe 2714 = 1830 in-tree / 255 already-documented / 628 NEW REJECTS / 1 NEW-INTERESTING; method one-liners; the qwen4-main-squashed side-branch class discovery (REJECT-MERGED-TO-SIDE-BRANCH x44 -- future sweeps MUST filter by base; orchestrator's "206" NOT FOUND in the artifacts, 44 recorded as verified); sgl-project#36043 NVFP4 skinny GEMM SM120 full paragraph (closed-unmerged, absent-tree-verified, W4A4 M<=16 = our exact decode cell, BENCHMARK-BEFORE-PORT -> S-36043-BENCH filed); artifact paths. EVALUATED: the 671-line DOCS-BLOCK.txt inserted VERBATIM as its own dated block (165 dropped list-commas tidied at insertion, noted once at the block head; nothing else reflowed). DATED CORRECTIONS where the waves superseded 322/323-era operational text: the header PROD-BOOT-FORBIDDEN bullet and entry 323's WHEEL DRIFT + STATE lines get [11-10 ERA-CLOSE CORRECTION] annotations (classes closed, wheel landed, ban now purely the operator gate); marker-zone math re-verified against the wave ledgers (121-at-merge vs 125 recount stands correct; planted == consumed per zone). WATCH LIST: era-close block appended (sgl-project#36043 bench-gated; sgl-project#42790/sgl-project#40916 arrived-via-merge6 noted; sgl-project#43703 revert-trap cross-ref from entry 323; sgl-project#45520 STILL-OPEN re-confirmed at era close -- zero in-window refs, b5 verified the fail-safe layer intact; bootfix's report-only get_tokenizer_worker_class/entrypoints wiring carry). Docs-only: NO .py touched; check_registered_tests rc=0 re-run against this tree. NOTHING PUSHED; the live tree was NOT touched by this wave (ref-move integration follows with HEAD/status equality proofs).
Conflicts in io_struct.py with sgl-project#44047, which validates n, and sgl-project#48446, which gives each request its own sampling_params dict. Keep both sides: the length check still runs before n is read from the first entry, and a single prompt's one-entry list is copied like the dict case.
…s, logit_bias and top_logprobs Port the admission checks sgl-project#44047 added to Python's request models and SamplingParams, so the Rust server refuses the same requests. Refusals from validate_n, SamplingParams.verify and the top_logprobs check use Python's message. - n: typed chat and completions refuse n outside [1, OPENAI_MAX_N (128)] with a 400 ("n must be at least 1" / "n must be at most 128") before any choice is submitted. Python's request models refuse it in field validation, before the handler runs, so it comes ahead of the model, empty-messages, media, suffix and best_of checks. n is read from the top level of the body as its JSON text (sglang-server enables serde_json's raw_value feature), so an integral n the typed request's u8 cannot hold, such as 256, -1, 200.0 or an integer past 64 bits, gets the n message rather than a deserialization error. As Python's orjson-based body parser does, a number past f64 range or a body that is not UTF-8 keeps its JSON parse error. An explicit "n": null, which the request models refuse as not an integer, gets "n must be an integer"; an omitted n is still 1. Like Python's request models, they do not log a request refused for n outside [1, 128]; the 4096 total across prompts keeps its refusal. Typed chat, completions and lowered chat also refuse n above SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ (a negative value disables the cap) with Python's validate_n message, after logging the request, as Python does; message::request exposes the memoized cap. OPENAI_MAX_N is defined once, in sglang_processor::openai. - Chat output limit: an explicit max_tokens=0 or max_completion_tokens=0 is served as empty choices with a length finish. The typed handler refused it, and lowered chat ignored a zero max_completion_tokens and generated up to the default limit. The effective limit is now Python's effective_max_tokens, max_completion_tokens.or(max_tokens), on the typed path and in the processor's lowered request and context check. /v1/completions still refuses max_tokens=0, as Python does. - Lowered chat (sglang-processor, which serves chat for Jinja templates when the server has a tokenizer) does not lower an n outside [1, 128] or a negative max_tokens, max_completion_tokens or top_logprobs, so the typed handler refuses them with a 400. lower_completion takes the same n bound. - logit_bias: SamplingParams::verify rejects a value that is not finite or whose magnitude exceeds LOGIT_BIAS_ABS_MAX (1e30), after the entry's key check, and prints a float value as Python's repr does (1e+31, nan, inf), the bound Python sets because the scheduler divides the f32 bias by a temperature as low as _SAMPLING_EPS. verify runs for native /generate, gRPC, chat and completions. - top_logprobs_num: with return_logprob, a count outside [0, vocab_size] is refused at intake with Python's message, per batch item after a list splits or a scalar broadcasts. Without return_logprob it is not checked and the scheduler receives 0, as Python sends. Regression tests pin the n, batch-cap and output-limit bounds on the typed and lowered routes, the n check coming first and reading n as Python's orjson parser does, an explicit null n, and the logit_bias and top_logprobs bounds in SamplingParams and intake validation. The per-route batch-cap test runs in a child process because the cap is read once per process. Co-Authored-By: Claude Opus 5.5 <[email protected]>
No behaviour change. Reuse, test consolidation and comment corrections from
four review rounds against the commit below.
Read `n` before the lowerer rather than after it. The lowerer declines every
`n` this refuses, so the answer is the same, but a refused body no longer pays
a parse and a whole-body clone first.
Say that `BodyN` is the same visitor as `dp_relay.rs`'s `BodyRank`. Reading its
keys as `Cow<'de, str>` to match was tried and reverted: serde's `Cow` impl is
`T::Owned::deserialize(..).map(Cow::Owned)`, so it allocates exactly as `String`
does and `BodyRank` pays the same cost.
State the domain of the `logit_bias` float repr and assert it, since it writes
only the exponent form: a value under the bound would come back as `1e+-5`.
Handle the non-finite cases outright rather than relying on `{:e}` leaving
`inf` alone. Note that `check_prompt_copies`'s batch cap now guards other
callers, the OpenAI routes bounding `n` before any prompt is copied.
Tests: one SSE frame parser and one lowered-refusal helper instead of a copy
per test, and drop rows that restate a fact another test pins. Pin what a
repeated `n` does on each route, which differs: chat keeps the last as Python's
dict does, completions refuses it, and only one of those matches Python.
`batch_cap_child` returned early without its environment, and an early return
still prints the "1 passed" its parent greps for; assert instead.
Correct two comments that described the wrong thing: the ordering one outlived
the move above, and the `logit_bias` one described `json.loads` where this path
decodes with orjson, which reads an integer past 64 bits as a float and so
prints it exactly as this does.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Motivation
Several invalid sampling values pass request parsing and only fail later, in serving or in the scheduler. Chat output-limit handling also used
max_completion_tokens or max_tokens, so an explicit0fell back to the legacy limit.Observed on a live server (Qwen2.5-0.5B-Instruct, vocab size 151936):
nis rejected only after the request has been expandedntimes:/generatewithn=3,000,000took ~113 s and grew server memory by ~18 GB before returning 400. Onmain,n=300,000did not complete within 15 minutes and server memory passed 90 GB.n=0was not rejected with a clear message.top_logprobsabove the vocab size (for example 200000) kills the server, becausetorch.topkfails past the vocab size. A list or negativetop_logprobs_numgarbles a batch. A request with logprobs off can crash it too: its count is not checked, but the scheduler takestopkover every request's count when any request in the same prefill batch wants logprobs.logit_biasoverflows toinfin the float32 bias tensor, or after the sampler divides by a temperature below 1, and NaNs the softmax. A sampled request with a1e39bias, or3e38attemperature=0.5, returns garbage tokens ([0, 0, 0, 0]) and, withtop_p, kills the scheduler.-1or999999) kills the server with a CUDA device-side assert once themin_new_tokenspenalizer runs. The penalizer covers the whole batch when any request setsmin_new_tokens, so the stop id and themin_new_tokenscan come from different requests. With beam search, a stop id from2**63to2**64 - 1fails the scheduler's int64 tensor build and kills the server.max_completion_tokens=0is ignored.Modifications
nis validated by one function,sampling_params.validate_n. It requires anint(boolrejected) of at least 1, at mostSGLANG_MAX_BATCH_REQS_PER_HTTP_REQ(default 4096, the limit the Rust server already applies ton). A negative value disables the upper bound, as in the Rust server.GenerateReqInput._handle_parallel_samplingcalls it before any input is multiplied byn, for dict and listsampling_params, andSamplingParams.verifycalls it as a backstop.OPENAI_MAX_N = 128(protocol.py). OpenAI requests then also passvalidate_n, so their effective limit is the smaller of the two.top_logprobs_nummust be an integer in[0, vocab_size]when logprobs are requested (checked next totoken_ids_logprobintokenizer_manager). When logprobs are off the count is not checked and is forwarded to the scheduler as0, so it cannot reach a sharedtopk.SamplingParams.verifyvalidateslogit_biasvalues (numeric, finite,|bias| <= 1e30). The sampler divides by a temperature of at least1e-6, so this bound keeps the float32 bias finite.min_new_tokenspenalizer and beam search drop stop ids outside[0, vocab_size)before building their tensors. Such ids can never be sampled, so they are accepted and never match, as before, and no longer crash the server.top_logprobsandtemperaturereject negative values, andtemperaturerejectsinf/nan.ChatCompletionRequest.effective_max_tokensgivesmax_completion_tokensprecedence, including an explicit0. Chat conversion and the context-length check both use it.max_tokensandmax_completion_tokensmust be non-negative and are not booleans (lax integer parsing would readfalse/trueas a 0- or 1-token limit).Deliberately not enforced
OpenAI documents
temperaturein 0-2,top_logprobs<= 20,logit_biasvalues in [-100, 100], andtop_logprobsonly withlogprobs=true. SGLang does not enforce these. The engine applies those values correctly (temperature=3flattens the sampled distribution,top_logprobs=50returns 50 entries, a-1e4bias suppresses the token) and existing clients rely on that, so rejecting them would only break working requests.ChatCompletionRequestcarries a comment saying so. Happy to revisit if maintainers prefer strict OpenAI parity on the OpenAI routes.Behavior changes
max_completion_tokens=0finish_reason=lengthmax_tokens=5, max_completion_tokens=0max_tokens=-1, max_completion_tokens=1max_tokensormax_completion_tokensset totrue/falsen> 128n>SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ(default 4096)ntimes/generate,Engine.generaten=0/generatetop_logprobs/top_logprobs_num> vocab size, negative, or non-integer, with logprobs requested/generatetop_logprobs/top_logprobs_num> vocab size with logprobs off, in a prefill batch with a logprob request/generatelogit_biaswith|bias| > 1e30logit_biasnon-numeric or non-finite valueSamplingParams.verify/generate, completionsstop_token_idsoutside[0, vocab_size)min_new_tokens(or beam search gets an id from2**63to2**64 - 1)Notes:
max_tokensormax_completion_tokensalready returned 400. Only the combined case above changes.max_tokens=0alone already produced an empty completion. Chat now accepts0for both fields, while/v1/completionsand the Anthropic route still require> 0.generation_configEOS, tokenizer additional stop IDs).nfrom 129 to 4096 behaves as before. Raise or disable the limit withSGLANG_MAX_BATCH_REQS_PER_HTTP_REQ.Known limits (not in this PR)
SGLANG_RUST_SERVER=1,rust/sglang-server) does not go throughtokenizer_manager, so these admission checks do not apply there. The stop-id filters run in the scheduler, so they cover it too. It reads the sameSGLANG_MAX_BATCH_REQS_PER_HTTP_REQlimit fornand rejectsmax_tokens=0. Mirroring the other checks in Rust is a separate change.batch_size * nis still unbounded, andmax_tokens/max_completion_tokenshave no upper bound.lang/ir.py,benchmark/serving.py) only send these fields with real values.Accuracy Tests
No model forward or kernel change. Request-level checks on a live server (single H200, Qwen2.5-0.5B-Instruct,
--sampling-backend pytorch), againstmainat e109bc1 and this branch (stop-id rows re-run on 2026-10-29 againstmainf59cc7e, the main merged into this branch):main/generaten=300000(main) /n=3000000(PR)top_logprobs=200000withlogprobs=truetop_logprobs_num=10000000with logprobs off, in one prefill batch with a logprob request (/generateand chat)selected index k out of range; measured on this branch before the fix, 46f3d08, which forwarded the count unchanged likemain)stop_token_ids=[-1]withmin_new_tokens=2stop_token_ids=[999999]sent while another request withmin_new_tokens=2is decodingbeam_width=2) withstop_token_ids=[2**63]Overflow when unpacking long long)logit_bias1e39(sampled)[0, 0, 0, 0]logit_bias3e38attemperature=0.5top_p=0.9max_completion_tokens=0Unchanged on both:
n=1, 3, 128return the expected number of outputs;temperature=3,top_logprobs=50(with or withoutlogprobs), and a largelogit_biason chat, completions and native all return 200;logit_biasof+-1e30attemperature=0.0005still works.Reproduction (synthetic input only):
Unit tests (CPU), on the current head (main d213124 merged in):
test_io_struct(67, 2 CUDA-only skips),test_protocol(48),test_serving_decisions(28),test_serving_chat(175),test_serving_completions(21),test_sampling_params(83),test_sampling_mask_validation(6),test_tokenizer_manager_rid_cleanup(49),test_penaltylib(42),test_sampling_batch_info(50),test_beam_search_core(11). Onetest_serving_chatsubtest (Inkling streaming) needs the optionaltml-rendererspackage and fails identically onmainwithout it.base-a-test-cpusuite gave 806 of 887 files passing; the 81 failing files fail identically on plainmainin the same environment (missing ffmpeg/torchcodec, prebuilt Rust extensions out of date, model-cache access). It has not been rerun since the merge.Speed Tests and Profiling
Not applicable. Admission-time validation, plus a host-side bounds filter when the
min_new_tokenspenalty or a beam group is built.Checklist
ruff,ruff-format,isort)sampling_params.mdx,openai_api_completions.mdx)CI States
Latest PR Test (Base): ✅ Run #42578311239
Latest PR Test (Extra): ✅ Run #42578311195
Latest PR Test (AMD ROCm 10): ✅ Run #42578311211
Tip
Base CI only covers the core cases, and its workload may not exercise your change. Use
/rerun-testto run the tests your change touches, or copy this prompt for an agent: