Skip to content

[Fix] openai: Validate sampling bounds and preserve chat output limits - #44047

Merged
nvpohanh merged 19 commits into
sgl-project:mainfrom
TheDuyIT:fix/openai-chat-sampling-bounds
Nov 10, 2026
Merged

nvpohanh merged 19 commits into
sgl-project:mainfrom
TheDuyIT:fix/openai-chat-sampling-bounds

Conversation

@TheDuyIT

@TheDuyIT TheDuyIT commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

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 explicit 0 fell back to the legacy limit.

Observed on a live server (Qwen2.5-0.5B-Instruct, vocab size 151936):

  • A huge n is rejected only after the request has been expanded n times: /generate with n=3,000,000 took ~113 s and grew server memory by ~18 GB before returning 400. On main, n=300,000 did not complete within 15 minutes and server memory passed 90 GB. n=0 was not rejected with a clear message.
  • top_logprobs above the vocab size (for example 200000) kills the server, because torch.topk fails past the vocab size. A list or negative top_logprobs_num garbles a batch. A request with logprobs off can crash it too: its count is not checked, but the scheduler takes topk over every request's count when any request in the same prefill batch wants logprobs.
  • A large logit_bias overflows to inf in the float32 bias tensor, or after the sampler divides by a temperature below 1, and NaNs the softmax. A sampled request with a 1e39 bias, or 3e38 at temperature=0.5, returns garbage tokens ([0, 0, 0, 0]) and, with top_p, kills the scheduler.
  • A stop id outside the vocab (for example -1 or 999999) kills the server with a CUDA device-side assert once the min_new_tokens penalizer runs. The penalizer covers the whole batch when any request sets min_new_tokens, so the stop id and the min_new_tokens can come from different requests. With beam search, a stop id from 2**63 to 2**64 - 1 fails the scheduler's int64 tensor build and kills the server.
  • An explicit max_completion_tokens=0 is ignored.

Modifications

  • n is validated by one function, sampling_params.validate_n. It requires an int (bool rejected) of at least 1, at most SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ (default 4096, the limit the Rust server already applies to n). A negative value disables the upper bound, as in the Rust server. GenerateReqInput._handle_parallel_sampling calls it before any input is multiplied by n, for dict and list sampling_params, and SamplingParams.verify calls it as a backstop.
  • The chat and completions request models keep OpenAI's limit, OPENAI_MAX_N = 128 (protocol.py). OpenAI requests then also pass validate_n, so their effective limit is the smaller of the two.
  • top_logprobs_num must be an integer in [0, vocab_size] when logprobs are requested (checked next to token_ids_logprob in tokenizer_manager). When logprobs are off the count is not checked and is forwarded to the scheduler as 0, so it cannot reach a shared topk.
  • SamplingParams.verify validates logit_bias values (numeric, finite, |bias| <= 1e30). The sampler divides by a temperature of at least 1e-6, so this bound keeps the float32 bias finite.
  • The min_new_tokens penalizer 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.
  • Chat top_logprobs and temperature reject negative values, and temperature rejects inf/nan.
  • ChatCompletionRequest.effective_max_tokens gives max_completion_tokens precedence, including an explicit 0. Chat conversion and the context-length check both use it. max_tokens and max_completion_tokens must be non-negative and are not booleans (lax integer parsing would read false/true as a 0- or 1-token limit).

Deliberately not enforced

OpenAI documents temperature in 0-2, top_logprobs <= 20, logit_bias values in [-100, 100], and top_logprobs only with logprobs=true. SGLang does not enforce these. The engine applies those values correctly (temperature=3 flattens the sampled distribution, top_logprobs=50 returns 50 entries, a -1e4 bias suppresses the token) and existing clients rely on that, so rejecting them would only break working requests. ChatCompletionRequest carries a comment saying so. Happy to revisit if maintainers prefer strict OpenAI parity on the OpenAI routes.

Behavior changes

Request Before After Routes
max_completion_tokens=0 runs with the default limit 0 tokens, finish_reason=length chat
max_tokens=5, max_completion_tokens=0 5 tokens 0 tokens chat
max_tokens=-1, max_completion_tokens=1 200, 1 token 400 chat
max_tokens or max_completion_tokens set to true/false read as a 1- or 0-token limit 400 chat
n > 128 accepted (for example 256 choices) 400 chat, completions
n > SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ (default 4096) accepted, expanded n times 400, checked before inputs are expanded /generate, Engine.generate
n=0 no clear error 400 with a clear message chat, completions, /generate
top_logprobs / top_logprobs_num > vocab size, negative, or non-integer, with logprobs requested scheduler crash or garbled batch 400 chat, /generate
top_logprobs / top_logprobs_num > vocab size with logprobs off, in a prefill batch with a logprob request scheduler crash count ignored, no crash chat, /generate
logit_bias with |bias| > 1e30 accepted; garbage output or scheduler crash when sampling 400 all
logit_bias non-numeric or non-finite value rejected only by the request parser where one applies 400 from SamplingParams.verify native /generate, completions
stop_token_ids outside [0, vocab_size) ignored, but the server crashes when the batch uses min_new_tokens (or beam search gets an id from 2**63 to 2**64 - 1) ignored, no crash all

Notes:

  • A single negative max_tokens or max_completion_tokens already returned 400. Only the combined case above changes.
  • max_tokens=0 alone already produced an empty completion. Chat now accepts 0 for both fields, while /v1/completions and the Anthropic route still require > 0.
  • The same filter covers stop IDs supplied by the model (the generation_config EOS, tokenizer additional stop IDs).
  • Native n from 129 to 4096 behaves as before. Raise or disable the limit with SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ.

Known limits (not in this PR)

  • The opt-in Rust HTTP server (SGLANG_RUST_SERVER=1, rust/sglang-server) does not go through tokenizer_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 same SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ limit for n and rejects max_tokens=0. Mirroring the other checks in Rust is a separate change.
  • batch_size * n is still unbounded, and max_tokens / max_completion_tokens have no upper bound.
  • Zero-length generation with speculative decoding enabled is not covered by tests. In-tree senders (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), against main at e109bc1 and this branch (stop-id rows re-run on 2026-10-29 against main f59cc7e, the main merged into this branch):

Request main This PR
/generate n=300000 (main) / n=3000000 (PR) no reply, server killed 400 in ~3 ms, server healthy
chat top_logprobs=200000 with logprobs=true server dies 400, server healthy
top_logprobs_num=10000000 with logprobs off, in one prefill batch with a logprob request (/generate and chat) server dies (selected index k out of range; measured on this branch before the fix, 46f3d08, which forwarded the count unchanged like main) 200, server healthy
stop_token_ids=[-1] with min_new_tokens=2 server dies 200, id ignored, server healthy
stop_token_ids=[999999] sent while another request with min_new_tokens=2 is decoding both requests lost, server dies both 200, outputs unchanged, server healthy
beam search (beam_width=2) with stop_token_ids=[2**63] server dies (Overflow when unpacking long long) 200, same output as without the id, server healthy
logit_bias 1e39 (sampled) garbage output [0, 0, 0, 0] 400
logit_bias 3e38 at temperature=0.5 garbage output 400
same, with top_p=0.9 server dies 400
chat max_completion_tokens=0 45 tokens 0 tokens

Unchanged on both: n=1, 3, 128 return the expected number of outputs; temperature=3, top_logprobs=50 (with or without logprobs), and a large logit_bias on chat, completions and native all return 200; logit_bias of +-1e30 at temperature=0.0005 still works.

Reproduction (synthetic input only):

# huge n: rejected before the request is expanded
curl -s localhost:30000/generate -H 'Content-Type: application/json' \
  -d '{"text":"Hi","sampling_params":{"max_new_tokens":1,"n":3000000}}'

# top_logprobs above the vocab size
curl -s localhost:30000/v1/chat/completions -H 'Content-Type: application/json' \
  -d '{"model":"m","messages":[{"role":"user","content":"Hi"}],"max_tokens":2,"logprobs":true,"top_logprobs":200000}'

# stop id outside the vocab, with min_new_tokens: kills main, ignored here
curl -s localhost:30000/generate -H 'Content-Type: application/json' \
  -d '{"text":"Hi","sampling_params":{"max_new_tokens":8,"min_new_tokens":2,"stop_token_ids":[-1]}}'

# logit_bias beyond the float32-safe bound
curl -s localhost:30000/generate -H 'Content-Type: application/json' \
  -d '{"text":"Hello","sampling_params":{"max_new_tokens":4,"temperature":0.5,"logit_bias":{"0":3e38}}}'

Unit tests (CPU), on the current head (main d213124 merged in):

  • Touched suites pass: 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). One test_serving_chat subtest (Inkling streaming) needs the optional tml-renderers package and fails identically on main without it.
  • Before main was merged in (base e109bc1), the full base-a-test-cpu suite gave 806 of 887 files passing; the 81 failing files fail identically on plain main in 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_tokens penalty or a beam group is built.

Checklist

  • Format with pre-commit (ruff, ruff-format, isort)
  • Add unit tests (each guard is mutation-checked: removing it turns a test red)
  • Update documentation (sampling_params.mdx, openai_api_completions.mdx)
  • Accuracy and speed benchmarks (not applicable)
  • Follow the SGLang code style guidance

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-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@TheDuyIT
TheDuyIT marked this pull request as ready for review October 13, 2026 11:58
@TheDuyIT TheDuyIT changed the title [Fix] Validate OpenAI chat sampling bounds and logprobs dependencies [Fix] Validate sampling bounds and preserve chat output limits Oct 14, 2026
@TheDuyIT
TheDuyIT force-pushed the fix/openai-chat-sampling-bounds branch from 95a3519 to 3181bca Compare October 14, 2026 13:50
@TheDuyIT
TheDuyIT marked this pull request as draft October 21, 2026 15:14
TheDuyIT and others added 3 commits October 22, 2026 10:07
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]>
@TheDuyIT
TheDuyIT force-pushed the fix/openai-chat-sampling-bounds branch from 3181bca to 8fadbaa Compare October 22, 2026 10:33
@TheDuyIT
TheDuyIT marked this pull request as ready for review October 22, 2026 11:37
@github-actions

This comment has been minimized.

@TheDuyIT TheDuyIT changed the title [Fix] Validate sampling bounds and preserve chat output limits [Fix] openai: Validate sampling bounds and preserve chat output limits Oct 23, 2026
@YouNeedCryDear

Copy link
Copy Markdown
Contributor

@TheDuyIT Could you fix the title? Meanwhile, some high level comments that I have:

  1. native /generate currently commits HTTP 200 before running shared admission. If HTTP 400 is required, you need to run validation before committing the response.
  2. document need to update the change. the new n <= 128 limit,etc.

# 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:

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.

Would batch with mixed return logprob slip through the validation?

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.

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.

@mintlify

mintlify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 0a4798a.

Approve preview

@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Oct 23, 2026
@TheDuyIT

Copy link
Copy Markdown
Contributor Author

Thanks @YouNeedCryDear

  • native /generate currently commits HTTP 200 before running shared admission. If HTTP 400 is required, you need to run validation before committing the response.
  • document need to update the change. the new n <= 128 limit,etc.
  • With stream=false the same requests return a real 400. Making /generate with stream=true return a 4xx instead of committing 200 first is out of scope for this PR. main already behaves this way: for example, an input longer than the context gets HTTP 200, an SSE error frame and [DONE]. This PR keeps that existing contract on /generate, and I can do the change in a follow-up if you want it.
  • Doc updated in 09700d9

TheDuyIT and others added 3 commits October 23, 2026 07:21
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]>
Comment thread python/sglang/srt/managers/io_struct.py Outdated
@@ -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:

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.

Would it make more sense to move this to SamplingParams.verify()

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.

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]>
@nvpohanh

nvpohanh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

@TheDuyIT could you resolve the conflicts and allow maintainers to modify our PR? Thanks

@TheDuyIT

TheDuyIT commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @nvpohanh ! The conflicts are resolved, and maintainer edits are enabled.

@JustinTong0323

Copy link
Copy Markdown
Collaborator

/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

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

🚀 ubuntu-latest (10 tests): ✅ View workflow run

cd test/ && python3 registered/unit/beam_search/test_beam_search_core.py  # base-a
cd test/ && python3 registered/unit/entrypoints/openai/test_protocol.py  # base-a
cd test/ && python3 registered/unit/entrypoints/openai/test_serving_chat.py  # base-a
cd test/ && python3 registered/unit/entrypoints/openai/test_serving_decisions.py  # base-a
cd test/ && python3 registered/unit/entrypoints/openai/test_serving_completions.py  # base-a
cd test/ && python3 registered/unit/managers/test_sampling_mask_validation.py  # base-a
cd test/ && python3 registered/unit/managers/test_tokenizer_manager_rid_cleanup.py  # base-a
cd test/ && python3 registered/unit/sampling/test_penaltylib.py  # base-a
cd test/ && python3 registered/unit/sampling/test_sampling_params.py  # base-a
cd test/ && python3 registered/unit/sampling/test_sampling_batch_info.py  # base-a

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/unit/managers/test_io_struct.py  # base-b

@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

2 similar comments
@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@TheDuyIT

TheDuyIT commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

@TheDuyIT

TheDuyIT commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged the latest main (e8017bc) to pick up the fixes for the two CI failures that weren't from this PR:

@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

1 similar comment
@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@TheDuyIT

Copy link
Copy Markdown
Contributor Author

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:

  • PR Test (XPU): stage-a-test-1-gpu-xpu timed out after 60 min in "Install Dependency". The earlier attempt hit a 504 downloading the XPU kernel wheel.
  • PR Test (Xeon): xeon-gnr fails with "Invalid user token. The token from HF_TOKEN environment variable is invalid", which looks like a CI secret issue.
  • PR Test (MLX): test/registered/unit/hardware_backend/mlx/test_attention_patching.py fails with 'types.SimpleNamespace' object has no attribute 'tree_slots'. This PR doesn't touch MLX, and other recent PRs hit the same failure in this job.
  • PR Test (MLU) / PR Test Extra (AMD): pr-gate label gates (run-ci-mlu / run-ci-amd-extra not set).

Could you take a look and merge when you get a chance?

@nvpohanh

Copy link
Copy Markdown
Collaborator

Merging. Thanks

@nvpohanh
nvpohanh merged commit b2616ca into sgl-project:main Nov 10, 2026
334 of 414 checks passed
nvpohanh added a commit to Kh4L/sglang that referenced this pull request Nov 10, 2026
…-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]>
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…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.
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…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).
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…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.
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…+ 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).
cycancode added a commit to cycancode/sglang that referenced this pull request Nov 14, 2026
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.
TheDuyIT added a commit to TheDuyIT/sglang that referenced this pull request Nov 18, 2026
…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]>
TheDuyIT added a commit to TheDuyIT/sglang that referenced this pull request Nov 18, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) run-ci-nv-extra CI: NVIDIA/shared Extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants