Skip to content

Fix token usage with jump forward - #174

Merged
comaniac merged 3 commits into
mainfrom
cody/usage
Feb 10, 2024
Merged

comaniac merged 3 commits into
mainfrom
cody/usage

Conversation

@comaniac

@comaniac comaniac commented Feb 9, 2024

Copy link
Copy Markdown
Contributor

close #173

This PR fixes the incorrect token usage when jump forward is enabled. Specifically, we introduce a new field orig_prompt_tokens, which will be set when the first jump forward happens so that we could know the original number of prompt tokens. When returning a response (a chunk in streaming or a complete response), we use the following equations to correct the token usage:

completion_tokens = curr_prompt_token - orig_prompt_tokens + completion_tokens
prompt_tokens = orig_prompt_tokens

@comaniac
comaniac requested review from hnyls2002 and merrymercy and removed request for merrymercy February 9, 2024 18:59
@hnyls2002

Copy link
Copy Markdown
Collaborator

@comaniac Hi, I suggest initializing the orig_prompt_tokens when constructing the Req so that we can simplify the code.

@comaniac

Copy link
Copy Markdown
Contributor Author

Thanks that makes sense. Meanwhile, can you add some comments back to explain why we need to calculate the token usage in this way?

@comaniac
comaniac merged commit 4d303c4 into main Feb 10, 2024
@comaniac
comaniac deleted the cody/usage branch February 10, 2024 04:06
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
rucnyz added a commit to rucnyz/sglang that referenced this pull request Jun 2, 2026
…tor + DP=2 real-run; TP follow-on blocked on sglang patch (sgl-project#174)

verify/t15/detector.py — pure analysis tool over time-series of
per-rank /aginfer/state snapshots.  Window-based eviction diff
across ranks; reports any window where ranks evicted different
hashes.

verify/t15/verify.py — 11 synthetic stages, all green:
  A0/A1 single-rank → no report (no cross-rank comparison)
  B0/B1 multi-rank, no/identical eviction → no report
  C0   rank-0 evicts u1, rank-1 evicts u2 → 1 report
  C1   partial overlap (rank-1 evicts strictly more) → 1 report
  C2   3 ranks: 2 agree + 1 diverges → 1 report
  C3   sustained divergence across 4 windows → 4 reports
  D0   rank-set change between windows → ValueError
  D1   time_counter propagated to reports
  D2   summarise() smoke

verify/t15/run_tp2_real.py — real DP=2 sglang launcher + churn
driver.  102 snapshots over 60 s × 24-worker churn; 13,620 requests;
8,948 peak units in radix tree; detector reported 34/101 divergent
windows (expected-by-design under DP — replicas serve different
program subsets).

State worth recording (caught during wire-up):
  * UnifiedRadixCache is gated behind SGLANG_ENABLE_UNIFIED_RADIX_TREE=1.
    Without it sglang falls back to HiRadixCache and /aginfer/state
    returns {"unsupported_tree_cache": ...} per rank.
  * DP>1 /aginfer/state exposes per_rank; TP>1 does NOT — the
    multi-rank aggregator runs inside http_server.py before the
    HTTP response.

§6 INVARIANT VERIFICATION BLOCKED on sglang patch (sgl-project#174): real TP-rank
divergence test needs a debug endpoint exposing per-TP-rank state
pre-aggregation.  PLAN §2 T15 status updated accordingly.
rucnyz added a commit to rucnyz/sglang that referenced this pull request Jun 7, 2026
…ints)

Per event the daemon re-scores the units in D_t and pushes ALL of
them to sglang via a fire-and-forget PUT /aginfer/hints, keeping the
inline scorer's V_u inputs warm without an HTTP round-trip at the
allocation callsite.  Full round-trip: daemon emitter + sglang
receiving side + overwrite-by-stamp storage.

Daemon:
* kv_scheduler.hints_from_state — one {hash, p_hat, lambda, stamp}
  per D_t unit, carrying the exact p_hat/lambda the scorer computed.
  stamp = int(sched_state.t) = sglang's own time_counter (monotonic,
  daemon-restart-surviving, read from the snapshot — NO wall-clock in
  the policy path).
* handle() dispatches hints via _dispatch_hints → enqueue_hints
  BEFORE and independent of the migrate decision, every event with a
  non-empty D_t.  NO shadow {hash: last_pushed} cache (DESIGN §10) —
  redundant re-pushes are absorbed by sglang's overwrite-by-stamp.

sglang (full chain, mirrors program_paused):
* PUT /aginfer/hints + _validate_hints_body (p_hat∈[0,1], lambda≥0,
  stamp non-negative int) → UpdateAginferHintsReq → rank fan-out →
  scheduler handler → UnifiedRadixCache.set_aginfer_hints.
* set_aginfer_hints overwrite-by-stamp: newer stamp wins; equal
  stamp = idempotent no-op (§10 R2); older = stale drop.  Plus
  get_aginfer_hint / clear_aginfer_hint; /aginfer/state echoes
  n_aginfer_hints (count, both dump paths).

Scope boundary (deferred, separate tasks): inline scorer CONSUMING
the table for eviction order, unit-birth seeding, eviction-time
clear ordering (T27), V_u-aware should_write_through (T28 sgl-project#178),
cross-rank fan-out atomicity (sgl-project#174).  This is emitter + storage +
overwrite contract only.

verify/t40: 14 stages incl. F0 LIVE e2e against a real sglang launch
(applied counts + cross-run idempotency + n_aginfer_hints readback).
Regression: kv_scheduler_value_rule / T36 / T41 / T6 /
integration_stress (full stack, 6 flavors) all green.
rucnyz added a commit to rucnyz/sglang that referenced this pull request Jun 7, 2026
…; KEEP throughput SUM (not mean)

Systematic field-by-field audit of _flatten_per_rank's cross-rank merge.
Net result after human review: one fix kept, one proposed change reverted.

KEPT — units last_access_time / hit_count: rank-0-verbatim → MAX in the
collision branch.  Same transient-divergence class as the residence/holders
merge: a stale rank-0 last_access inflates age=max(1,now-last_access) →
deflates p_hat=min(1,hits/age) → spuriously demotes a warm unit in
_top_k_by_regret.  MAX (warmest) is order-independent and liveness-
preserving, mirroring residence-union / holders-union.  Pin A1g,
mutation-tested RED→GREEN.

REVERTED — throughput_ema.prefill_bps / decode_per_program: a subagent
changed SUM→MEAN citing DESIGN §6 L766/L767.  That is WRONG here: the daemon
runs in a UNIFORM N×-scaled byte space.  units' n_bytes are agree-or-fatal
across ranks ⇒ KV bytes are MIRRORED (replicated MLA latent), not sharded;
pool_usage + committed + inflight are all SUMmed ⇒ every absolute byte AND
byte-rate is N×.  Uniform scaling means every consumer cancels (occ ratio;
N× budget vs N× weight; (N× inflight)/(N× prefill_bps); N× growth vs N× cap).
MEAN-ing ONLY the two rates while bytes stay SUMmed would BREAK the
cancellation and inject a real N× error.  DESIGN's "mean" assumes a
true-scale/sharded regime this impl doesn't use; true-scale conversion =
de-N×-ing ALL byte fields together, deferred to sgl-project#214 — moot today since the
forecast consumer is dormant (T11/T26) and the whole multi-rank path is dead
code until sgl-project#174 wires per-rank dumps (sglang returns a single pre-aggregated
dump → _flatten_per_rank returns it unchanged).  Reverted the SUM→MEAN code,
docstring, and the A1e/A1f pin stages; documented the SUM rationale inline.

Field-reconciliation contract now complete in the docstring + inline.
Suite 24/24 (A1c/A1d/A1g green); joint_decide + admission green.
WhiteCmile added a commit to WhiteCmile/sglang that referenced this pull request Nov 2, 2026
…he capacity harness

While the Draft queue holds work, log one JSON sample per 2s interval with
pending/max_pending (queue depth), the last max queue delay (wait), the last
submitted batch size, and the GPU time of the last completed DFlash proposal
batch (step time). The marker string lives in dt_protocol so the driver and
the engine share it; samples let the 7T2D capacity curve tell Draft-bound
bending from transport bending without enabling tracing.
WhiteCmile added a commit to WhiteCmile/sglang that referenced this pull request Nov 2, 2026
…posal GPU time

The throttled draft-boundness stats line reported only proposal_gpu_ns
as the step time, so a step whose GPU time grew in the materialization
phase (computed right above) still read as unsaturated. step_ms is the
full GPU service time of the step: materialize_start -> proposal_done.
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.

Incorrect token usage with jump forward

2 participants