Skip to content

Logprobs Refractor - #331

Merged
hnyls2002 merged 13 commits into
mainfrom
logprobs
Mar 28, 2024
Merged

hnyls2002 merged 13 commits into
mainfrom
logprobs

Conversation

@hnyls2002

@hnyls2002 hnyls2002 commented Mar 25, 2024 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

  • Refractor all logits and logprobs handling logic, including:
    • Clarify the naming rules: *_token_logprobs stands for each token' logprobs, *_prompt_logprob stands for the sum of logprobs of a segment of prompt.
    • Split the *_token_logprobs into prefill_token_logprobs and decode_token_logprobs.
  • Refractor SRT API and OpenAI API logprobs response format: List[(logprob, token_id, token_text)]
    • OpenAI API responds with the prefilling and decoding logprobs in one list and always returns all the prefilling logprobs.
    • SRT API can specify the logprob_start_len and respond in meta_data["prefill_token_logprobs"] and meta_data["decode_token_logprobs"] respectively.
  • Support detokenized results in sgl.select response which is the only use case for multiple requests in a single HTTP request.
  • top_logprobs support.

@hnyls2002
hnyls2002 marked this pull request as draft March 25, 2024 09:24
@hnyls2002
hnyls2002 marked this pull request as ready for review March 26, 2024 17:24
@hnyls2002

Copy link
Copy Markdown
Collaborator Author

closes #296
closes #232

@comaniac comaniac left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Overall LGTM. Just a few comments

Comment thread python/sglang/srt/server.py Resolved
Comment thread python/sglang/srt/server.py Resolved
Comment thread python/sglang/srt/server.py Resolved
@hnyls2002
hnyls2002 merged commit 3842eba into main Mar 28, 2024
@hnyls2002
hnyls2002 deleted the logprobs branch March 28, 2024 06:34
This was referenced May 12, 2024
if extend_seq_lens_cpu[i] == 0:
continue
k = input_metadata.top_logprobs_nums[i]
t = all_logprobs[pt : pt + extend_seq_lens_cpu[i]].topk(k)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

pt is not accumulated

extend_seq_lens_cpu = input_metadata.extend_seq_lens
for i in range(len(input_metadata.extend_seq_lens)):
if extend_seq_lens_cpu[i] == 0:
continue

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

continue will result in a out-of-bound error later.

normalized_prompt_logprobs,
prefill_token_logprobs,
decode_token_logprobs,
) = self.backend.select(self, expr.choices, expr.temperature)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

did not modify the openai backend.

timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
liuxianglong17 pushed a commit to shun8686/sglang that referenced this pull request Apr 11, 2026
efschu added a commit to efschu/htsglang that referenced this pull request Jul 31, 2026
…ss card references, 7 index bugs fixed, canonical IdentityMap (sgl-project#331)

# Conflicts:
#	docs/dev/INTEGRATION_R3_VALIDATION.md
efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
…order was guessed

Three bridges answered "which physical card is index i". sgl-project#331's IdentityMap
(registry/nvml.py) keys cards on their NVML UUID and bridges CUDA ordinal <->
NVML index over the PCI BDF; server_args._torch_to_nvml_gpu_index_mapping
built its own PCI-bus mapping; planner/device_map.py built a third from torch
UUIDs. Three answers to one question is three chances to disagree, and this
family has bitten four recorded times: the torch-vs-NVML memory read, runbook
6.1, the sgl-project#331 audit, and sgl-project#349 sweep-3 arm L (sgl-project#392). Everything resolves
through the identity map now.

Migrated, with each caller's refusal semantics preserved:

  * server_args._query_gpu_total_mib (sgl-project#336) already refused to guess; it now
    refuses against the identity map, and the message names the cards present
    and why the CUDA side could not be read.
  * uneven_perf._nvml_gpu_inventory bridged, then filled every gap with
    mapping.get(cuda_idx, cuda_idx) -- the identity substitution that names
    the wrong card on exactly the rigs the bridge exists for. It now refuses
    when it cannot place every card CUDA hands it: this inventory keys the
    hardware profile cache, so one misattributed card persists a profile that
    describes a different machine.
  * planner/energy._torch_to_nvml_index, a fourth copy found by the straggler
    audit below, had the same identity fallback and the same fallback again at
    its call site. A rank that cannot be placed is now left unattributed and
    named, instead of having its compute share added to another card's.
  * planner/flags._cuda_index_at, which produces the values written into
    --base-gpu-id and --rank-gpu-id.

server_args._torch_to_nvml_gpu_index_mapping and planner/device_map.py are
reduced to delegating shells, marked DEPRECATED with a grep-able sgl-project#397 note so
nothing new adopts them. Their remaining callers (disaggregation/topology.py,
model_loader/hibernate.py, and the planner's UI payload paths) keep their
dict/DeviceMap shapes and reach the one map through them.

The silent heuristic is gone. planner/device_map fell back to a FASTEST_FIRST
EMULATION -- a stable sort of the cards by their SEED_CARDS fp16 GEMM peak --
whenever the real order was unreadable. It was labelled "heuristic" and
callers were asked to surface the label, but a label does not make an ordering
right: an unknown card ranked 0.0 and silently kept NVML order, so the
emulation answered most confidently on the rigs nobody had measured. In its
place, IdentityMap.require_cuda_ordinals raises DeviceOrderUnresolvedError
naming WHAT could not be placed (uuid, name, nvml index, BDF, total) and WHY
(no torch / no CUDA device / no context and no licence to create one /
CUDA_VISIBLE_DEVICES masking / no pci_bus_id on this build). All-or-nothing on
purpose: a partial bridge is worse than none, because the caller fills the
gaps with the number it already has.

Consequences, all of them "say nothing" rather than "say something wrong":
the planner UI shows cards without a CUDA index; the single-gpu preset emits
no --base-gpu-id and says why; the stock-subset and co-location presets are
omitted entirely rather than carrying a guessed pin; live_metrics leaves
cuda_index None. cuda_index_source is now "identity-map" or None -- there is
no third, guessed state, and the UI's emulation marker is replaced by an
unresolved marker read off the cards themselves.

An offline --gpu NAME:MIB spec carries no card identity, so there is no live
order to get wrong. Its list order is taken as declared -- the convention sgl-project#392
already fixed for manual HardwareSpecs -- under the source name "declared",
which the preset text now surfaces (the old "identity" last resort did not).
This changes the emitted pin for offline hetero inventories: the emulation
guessed the reference box's real order and was right there by luck, the
declared order is what the operator actually wrote.

Straggler audit around the migrated callers. rig_artifact, split_probe and
rig_coupling were re-checked and are still display-only: split_probe keys
busy cards by UUID and records nvidia-smi's index only into a printed clock
log; rig_coupling's CardFacts.index is never read and its GpuDescriptor
indices are synthetic positions in a virtual pooled card list; rig_artifact's
"index" is a GitHub-issue text index, not a device index. Two genuine
stragglers outside this change's file scope are recorded for a follow-up, both
feeding a CUDA ordinal straight into nvmlDeviceGetHandleByIndex:
device_communicators/barlink_matrix_transport.py:152 (bar1_free -> the BAR1
window size) and utils/common.py:363 (min_visible_cuda_capability_no_init
indexes an NVML-ordered list with a CUDA_VISIBLE_DEVICES entry, while
_nvml_cuda_device0 twenty lines below does the same bridge correctly).

Falsifier, test_device_order_bridges_397.py, built on the sgl-project#392 pattern: every
rig has CUDA and NVML disagreeing in the reference shape (5090 = cuda:0 =
nvml:1), plus one control rig where they agree, because a suite built on an
agreeing rig passes with every bug in place. Agreement is pinned per caller,
not once -- the defect is that two callers answer differently, so a shared
helper asserted once would not catch it. The deleted emulation's ordering rule
is kept verbatim IN the test, applied to a rig of two cards SEED_CARDS does
not know: it returns [0, 1] where the cards are actually reversed, which is
the silent mis-order reproduced against live code, and the same rig now
produces the named error.

Test results, CUDA_VISIBLE_DEVICES=99 (desk, no GPU):
  * 26/26 new falsifier tests green.
  * Regression sweep (planner, server_args, distributed, registry,
    disaggregation, model_loader, boot_matrix, observability): 5047 passed,
    29 failed -- measured against a baseline worktree at the merge-base, which
    fails the same 29 on this host (CUDA-less artifacts: modelopt loader,
    vmm_utils LOCAL_RANK, dcp collective, s12 log fixtures). No new failure;
    one baseline failure (bar1_host_cleanup pgrep self-match) is flaky and
    passed here.
  * ruff (F401, F821, UP037) and codespell: the four ruff findings and the one
    codespell finding on the touched files are byte-identical to the baseline's
    on the same files.

Test suites updated for the removed heuristic: test_device_map (rewritten
around the adapter, the emulation cases replaced by refusal cases),
test_live_metrics (fake rig gained PCI BDFs so the bridged case is still
covered, plus two unbridged cases), test_flags (_HETERO_GPUS carries the
cuda_index a live payload has; the offline shape is now its own fixture),
test_webui (source strings, the JS marker), test_solo_reserve_sizing (fixture
injects at the identity map's seams instead of at server_args' own bridge).
Runbook 6.1 records the consolidation and what an unresolved order now does.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
…dges consolidated onto the sgl-project#331 IdentityMap — including a FOURTH bridge the audit found (planner/energy identity-fallback in bridge AND call site, rank now left unattributed and named); device_map heuristic -> DeviceOrderUnresolvedError (caches the EMPTY map, never a guess), flag pickers omit the pin or the preset rather than emit a guessed --base-gpu-id (offline manual specs get source=declared per the sgl-project#392 convention), uneven_perf inventory keying hardened; deprecated shells keep topology/hibernate dict shapes; heuristic defect kept reproducible verbatim INSIDE the test after the implementation is deleted (17/26 fail on reverted callers, incl. the emulation confidently returning the reverse of the truth on this rig's shape); display-only sites confirmed display-only; two genuine stragglers outside scope recorded for follow-up: barlink bar1_free sizes the BAR1 window from the wrong card, utils/common min_visible_cuda_capability feeds JIT selection through an untranslated ordinal (sgl-project#397)
efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
The sgl-project#397 audit named two callers it could not reach: both passed a CUDA
ordinal straight into nvmlDeviceGetHandleByIndex. NVML enumerates in PCI bus
order, CUDA does not, and on this rig they disagree -- the RTX 5090 is NVML
index 1 and CUDA ordinal 0 -- so both read a card their caller was not asking
about. Neither was display-only.

barlink bar1_free sized the BAR1 receive window from the wrong card's free
aperture. That number is transport-load-bearing in both directions: too large
and the holder answers ENOMEM, too small and every message above the clipped
size drops to the gloo layer while the log still says transport=matrix. It now
resolves the card through the sgl-project#331 identity map, over the PCI address the
device itself reports and, when it has none, over the map's CUDA-ordinal side.
When neither route places the card there is a named DeviceOrderUnresolvedError
and the NVML read is SKIPPED: bar1_free reports "free unknown", which the
caller already handles and states in its arithmetic, instead of another card's
free bytes, which it cannot detect. The refusal is logged at warning level, not
swallowed into the function's debug path.

utils/common min_visible_cuda_capability_no_init indexed the NVML-ordered
device list with a CUDA_VISIBLE_DEVICES entry, and it feeds Triton constexpr
and JIT-backend selection for the whole process. _nvml_cuda_device0, twenty
lines below, already emulated the enumeration order correctly; that emulation
is now a shared helper (_nvml_devices_in_cuda_order) rather than a second,
wrong answer to the same question. Where FASTEST_FIRST leaves a position
unspecified -- past device 0 on a mixed rig -- the answer is the floor over
every card NVML reports, not an error: this is a MINIMUM, the floor over a
superset can only be lower than the true floor, and low forgoes an
optimization while high arms a variant a card cannot launch. The neighbouring
_nvml_cuda_device0 still refuses the same input, because it is asked for the
identity of a card rather than a bound over them.

Tests, the sgl-project#392 falsifier pattern, injected NVML/CUDA orders, no driver:

  test_bar1_card_identity_406.py            12 tests, OK
  test_min_visible_capability_device_order_406.py  14 tests, OK

Both pin the exact pre-fix answer. Reverting each fix in place turns exactly
the divergence cases red and leaves the control rigs green:

  bar1_free with the ordinal restored: 4 red -- 240 MiB free read off the
  3080 where the 5090 has 100, and window_for handing out the full 96 MiB
  request on a card that has 68 MiB to give.
  min_visible with the NVML list restored: 4 red -- CUDA_VISIBLE_DEVICES=0
  answering sm86 for the 5090, and CUDA_VISIBLE_DEVICES=1 answering sm120
  for a 3080, which is the dangerous direction.

Regression, all green: test_per_device_capability (21),
test_cuda_context_free_imports (16), test_device_order_bridges_397 (26),
test_budget_guard_device_order_392 (13), test_barlink_transport_seam (17).
ruff and codespell clean on the four files (common.py's five ruff findings are
pre-existing lines outside the change).

Sibling audit of the barlink transport files: bar1_free held the only NVML
handle acquisition in barlink.py, barlink_matrix.py, barlink_bar1.py and
barlink_matrix_transport.py. The one other NVML-by-index in
device_communicators is upstream custom_all_reduce_utils.is_full_nvlink, which
treats CUDA_VISIBLE_DEVICES entries as NVML indices -- the same question, in
upstream code and out of this task's scope.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 17, 2026
The seam picks one transport for the whole group (barlink.py:554 _select(op,
nbytes) -- refined by op and size, never by peer). The sgl-project#732 survey concluded
the opposite shape: the measured BAR1 standing changes SIGN with edge width,
losing on the fast x8 pair (to 0.81x, 1-8 MiB) and winning everywhere on the
x4 pair (FEATURES_VS_UPSTREAM.md:1349). On a rig whose crossings straddle that
boundary, one verdict is the wrong shape of answer. This closes the
implementability gap I filed against my own recommendation.

barlink_peer_transport.py resolves a directed pair -> transport map ONCE at
world build and hands the dispatch site an immutable result. Desk half only:
it moves no bytes and imports no CUDA, like barlink_bar1_p2p.py beside it, so
existing layouts stay byte-for-byte.

Device identity: edges key on GPU UUID through the sgl-project#397/sgl-project#331 IdentityMap,
never on CUDA ordinals. The width canon is restated from expert_offload.py
:842 with its sgl-project#392 rationale -- WIDTH FROM THE CURRENT LINK, NOT THE MAXIMUM.
MaxPcieLinkWidth reports what the CARD can do (x16 on all three cards here)
while the SLOTS are x4/x8/x8, so a max-derived resolver collapses every edge
to "fast" and silently disables this feature on exactly the box it exists for.
That canon is duplicated rather than imported: pulling layers.moe into world
build is the wrong dependency direction. Consolidation onto registry/nvml.py
is filed, not done here, and the duplication is pinned by CanonTests so it
cannot drift silently.

Refusal algebra. A degraded edge RECORDS rather than raises; require_no_
refusals() is the explicit ask. Absent BAR1 p2p kernel (the shipping state --
BAR1 owns three collective kernels and no p2p kernel) every BAR1-preferring
edge falls back to NCCL LOUDLY: one WARNING per edge naming the fallback.
Forcing bar1_p2p via the override while the kernel is absent REFUSES instead
of degrading, because a silent fallback would answer a different A/B than the
one the operator posed.

On pricing, one deliberate deviation from the brief, flagged rather than
papered over: the fallback line does NOT carry a delta, because there is no
measured BAR1-vs-NCCL margin for sub-x8 edges -- that is gap 8 of my own
survey. Inventing a number here is exactly the "no invented cost terms" rule.
The note instead marks the margin UNMEASURED, cites the gap, and points at
the crossing schedule as the owner of the exposure (the share of crossings on
the degraded edge). What IS priced stays in the docs, where the rig-specific
15-of-31 / 62.5% figures belong; the module stays generic.

Override flag SGLANG_BARLINK_PEER_MAP for A/B: "all=nccl_sendrecv",
"0>1=bar1_p2p", explicit pair beats all regardless of position. Keys are
RANKS, not CUDA ordinals -- rank -> UUID comes from the world list, so the
flag never touches the device-order trap.

Tests (34, all green): the sgl-project#392 falsifier pattern with CUDA and NVML orders
disagreeing in the reference shape (5090 at CUDA 0 / NVML 1) plus a control
rig where they agree. Three can-fail proofs rather than assertions of
success:
- max-width resolution is asserted to collapse all six edges to NCCL, so
  relaxing the canon to "the max is close enough" turns the suite red;
- feeding a CUDA ordinal into NVML is asserted to INVERT the 5090<->x8-3080
  edge from NCCL to BAR1 -- not a cosmetic misread, a wrong transport;
- the no-degradation case is asserted to emit NO warning, so the loud-fallback
  test is proved to be caused by the fallback.
Mutation proof for per-pair dispatch: the rig is asymmetric by construction,
so no uniform answer exists; swapping the queried pair must change the
transport, and every edge must match its own width.

Ruff and codespell clean. Suite run with PYTHONPATH=<worktree>/python (the
documented worktree trap -- without it the module is not importable and the
run is falsely red).
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 11, 2026
…der vector

The first ruling had the launcher publish a new SGLANG_WEG2_XCHG_CARD_UUIDS.
Its premise -- "no publisher exists" -- is falsified by measured code, so that
variable is gone from this module and nothing replaces it here.

WHAT ALREADY EXISTS (sgl-project#407 cut 2, running on our boots):
  RANK_CARD_UUIDS_ENV = "SGLANG_RANK_CARD_UUIDS"        registry/rank_cards.py:82
  publish_rank_card_uuids(server_args)                  entrypoints/engine.py:671
    -- in the PARENT, BEFORE the spawn loop, and that file's own comment states
       our inheritance premise verbatim: "the channel is the environment, and a
       spawned scheduler inherits it only if it is set by now"
  resolve_rank_card_vector -> uuids[rank] = by_cuda_ordinal(ordinals[rank]),
    source "launcher placement (gpu_id_for_rank -> sgl-project#331 IdentityMap)", i.e.
    launcher placement order and explicitly NOT NVML enumeration
  readers rank_card_vector / rank_card_uuids, which own the parse
  weg2/launcher.py already passes --rank-gpu-id 0,1,2, so the publisher's
    CUDA-side gate is satisfied on every weg2 boot

MEASURED, XSN11, both runs, BOTH groups:
  rank->card vector (launcher placement ...): rank0=GPU-31d7ef41 [0A:00.0]
    rank1=GPU-5c648f96 [05:00.0] rank2=GPU-62dbbae1
byte-identical to the parent's CUDA_VISIBLE_DEVICES order, same on P and D,
`no CUDA context` 0. A second publisher would have been the one-job-one-mover
violation the ruling invoked, entered from the producer side.

So uuid_of_card() now takes one hop to the owner and nothing else: no env read
here (the parse stays with rank_cards), no variable named here, no injectable
string seam (every test drives the real reader).

AND THE COINCIDENCE IS ASSERTED, NOT USED. rank_cards indexes by WORLD RANK and
checks world_size; this module indexes by CARD and its invariant is N_CARDS.
They are equal on the Weg-2 form only because each group is three ranks and
"rank n of either group runs on cards[n]". A world of six -- a pipeline stage, a
MoE-TP subgroup -- separates them, and a six-entry vector re-indexed as a card
table would attribute one rank's card to another silently. The length is checked
here, by name, and the refusal SAYS that two different quantities were compared
so the next reader does not "fix" it by slicing to three. The vector is
deliberately fetched without world_size, so the owner's check and this one each
stay with the quantity they are about.

Reasons now: unset (the owner's own reason forwarded verbatim) / count (wrong
length, and where a dropped blank lands) / blank (a ratchet: unreachable while
the owner's parser drops empty fields) / duplicate -- plus `disagrees` at the
door. The no-fallback rule is unchanged and still a test by call shape: on this
rig the launcher's order is 5090-first and NVML's is 3080-first, so a fallback
returns right uuids under WRONG ordinals, which is worse than absence.

Instrument note, recorded because it is the second instance this cycle: one
bulk test edit did not match and failed SILENTLY, leaving a test asserting the
retired variable name. Same shape as the mutant whose edit raised SyntaxError
and scored "survived". Every scripted replacement in this commit asserts its
anchor, and the mutant harness now verifies the file actually changed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants