Skip to content

Debug(DSpark): Bisect target-verify CUDA Graph replay synchronization - #31455

Closed
Phoenix3334 wants to merge 4 commits into
sgl-project:mainfrom
Phoenix3334:debug/dspark-cuda-graph-replay-bisect
Closed

Phoenix3334 wants to merge 4 commits into
sgl-project:mainfrom
Phoenix3334:debug/dspark-cuda-graph-replay-bisect

Conversation

@Phoenix3334

@Phoenix3334 Phoenix3334 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Issue #31023 tracks a timing-sensitive CUDA illegal-memory-access failure in the DSpark compact ragged target-verify CUDA Graph path on TP8.

PR #31195 fixes the previously observed cross-TP verify-budget / Graph-tier mismatch. After that fix, TP0-TP7 agree on:

verify_token_budget
sum(verify_lens)
graph_num_tokens
target Graph key

However, the residual failure remains present. A fresh-service c256 matrix on A1 22cfd54c positively reproduced Bug 2:

compact-SPS + CUDA Graph ON + overlap OFF: 0/5 crashes
compact-SPS + CUDA Graph ON + overlap ON:  4/4 executed runs crashed
overlap-on r5: not run because the pipeline exited during r4

A later valid Stage C forced-fraction probe completed all three mechanism arms without a crash:

C1 direct key_size=240, overlap ON:        VALID_PASS
C2 ordered key_size=168 -> 240, overlap ON: VALID_PASS
C3 ordered key_size=168 -> 240, overlap OFF: VALID_PASS

Stage C is finite negative mechanism-probe evidence only. It does not supersede the c256 4/4 positive reproduction. Current evidence favors a sustained-overlap lifetime/ownership/stream-ordering problem over a simple “one 168 -> 240 transition always fails” model.

Related to #31023.

Scope

This is a diagnostic Draft PR, not the final production fix.

It adds opt-in synchronization and sync-free metadata tracing around the DSpark target-verify CUDA Graph execute/replay boundary. Default behavior remains unchanged.

Modifications

  • Add debug-only environment switches, all defaulting to off:
    • SGLANG_DEBUG_CUDA_GRAPH_SYNC_BEFORE_LOAD_BATCH=1
    • SGLANG_DEBUG_CUDA_GRAPH_SYNC_AFTER_LOAD_BATCH=1
    • SGLANG_DEBUG_CUDA_GRAPH_SYNC_BEFORE_REPLAY=1
  • Synchronize at the selected execute-prologue boundary only when explicitly enabled.
  • Under SGLANG_LOG_DECODE_GRAPH_KEY, log compact target-verify replay state and selected Graph-stable / nested DSV4 metadata identities, shapes, strides, capacities, and data pointers.
  • Avoid CUDA tensor .item() in the replay-state logger; when CPU-side scalars are unavailable, emit sentinel values rather than forcing a device-to-host synchronization.
  • Do not add synchronization or extra logging to the default path.

Current evidence

Cross-TP planning fix (#31195)

N1 no-overlap, same service:          30/30
N2 no-overlap, restart per workload:  30/30
O1 overlap, same service:             30/30
O2 overlap, restart per workload:     30/30
Total:                                120/120

No divergence was observed in verify_token_budget, sum(verify_lens), or target Graph key.

Conclusion: #31195 fixes the control-plane Graph-tier inconsistency. The residual failure investigated here is a separate execution/lifetime/synchronization issue.

Positive c256 reproduction — July 25-26, 2026

Experiment:

tag: bug2-repro-a1-22cfd54c-20260725
A1 commit: 22cfd54c
mode: compact-SPS
CUDA Graph: enabled
concurrency: 256
requests: 2560
input / output: 60000 / 1000
formal seed: 0
warmup seed: 1
shuffle: False
unreproducible: False
fresh service per run: yes
SPS SHA256: 7722243832273728c3b77a3f15f574a3d95880e2f3fd7667db67ff5322b90f5b
Group Stage Overlap Success / Total Classification Server survived Illegal-memory Scheduler exception NCCL watchdog
A overlap-off-c256-r1 OFF 2540 / 2560 completed_with_request_failures yes 0 0 0
A overlap-off-c256-r2 OFF 2546 / 2560 completed_with_request_failures yes 0 0 0
A overlap-off-c256-r3 OFF 2547 / 2560 completed_with_request_failures yes 0 0 0
A overlap-off-c256-r4 OFF 2543 / 2560 completed_with_request_failures yes 0 0 0
A overlap-off-c256-r5 OFF 2542 / 2560 completed_with_request_failures yes 0 0 0
B overlap-on-c256-r1 ON 360 / 2560 bug2_crash no 2 1 0
B overlap-on-c256-r2 ON 217 / 2560 bug2_crash no 2 1 0
B overlap-on-c256-r3 ON 3 / 2560 bug2_crash no 1 1 0
B overlap-on-c256-r4 ON 0 / 2560 bug2_crash, reconstructed status false 2 0 2
B overlap-on-c256-r5 ON not run pipeline exited during r4 — — — —

Summary:

overlap OFF: 0/5 Bug 2 crashes
overlap ON:  4/4 executed runs crashed
overlap ON r5: not run

For overlap-on r1-r3, the asynchronous CUDA error surfaced through:

Scheduler hit an exception
  -> process_batch_result_decode
  -> result.copy_done.synchronize()
  -> torch.AcceleratorError: CUDA error: an illegal memory access was encountered
  -> terminate called
  -> SIGQUIT
  -> Fatal Python error: Aborted

For overlap-on r4, preserved evidence instead shows CUDA illegal-memory-access evidence plus ProcessGroupNCCL watchdog termination on rank 3, without a recorded scheduler-exception line.

result.copy_done.synchronize() is the point where the asynchronous error was observed in r1-r3. It does not prove that the line initiated the invalid access.

The latest matrix establishes that overlap is a strong trigger in the tested environment. It does not establish that overlap is strictly required, because a historical overlap-OFF c256 run (diagnostic-v3 c256-r3) also reproduced the failure.

Stage C Pass-1 — valid forced-fraction probe

Experiment root:

stage-c-a1-22cfd54c-20260726

Pass-1 used minimal Graph-key logging to reduce observer effects.

Stage Fraction sequence Overlap Actual steady keys Result Classification CUDA / scheduler / NCCL
C1 direct240 0.4 ON 240 only (168=0, 240=7304, 480=0) 3/3 rounds, match_fraction=1.00 VALID_PASS 0 / 0 / 0
C2 transition 0.2 -> 0.4 ON ordered 168 -> 240 (168=7840, 240=7368, 480=0) each tier 3/3, match_fraction=1.00 VALID_PASS 0 / 0 / 0
C3 transition control 0.2 -> 0.4 OFF ordered 168 -> 240 (168=6832, 240=6504, 480=0) each tier 3/3, match_fraction=1.00 VALID_PASS 0 / 0 / 0

Validity gates:

  • actual import was A1 22cfd54c;
  • CUDA Graph and compact target verify were active;
  • C1 steady target-verify contained only key 240;
  • C2/C3 contained ordered same-service 168 -> 240 transitions;
  • C3 confirmed --disable-overlap-schedule;
  • no key-size 480 collapse occurred;
  • profiler run was used; the official SPS table was not overwritten;
  • all services survived and returned health 200.

Interpretation:

  • Direct key 240 did not fail in this finite probe.
  • One ordered 168 -> 240 transition did not fail with overlap ON or OFF.
  • A simple “large tier always fails” or “one transition always fails” model is not supported.
  • Stage C does not prove transitions are universally safe and does not weaken the c256 positive reproduction.

The mechanism probe is much lighter than the strong reproducer:

Stage C:
  batch 80, input length 16, short profiler decode,
  forced fractions, 3 repetitions per tier

c256 reproducer:
  concurrency 256, input/output 60000/1000,
  2560 requests, sustained real compact-SPS overlap

Current implication: the failure is more likely to require sustained high-concurrency overlap and longer-lived metadata/workspace/buffer/request/KV state than a single lightweight tier transition.

Evidence integrity

For the positive c256 runs:

  • complete source server logs are preserved;
  • copied logs match source SHA256 values;
  • crash excerpts contain surrounding context;
  • crash evidence checksums are valid;
  • r4 status is explicitly marked reconstructed.

For Stage C:

  • source/copied logs match;
  • C1/C2/C3 stage checksum validation is 9/9 OK for each stage;
  • official SPS SHA256 remained 7722243832273728c3b77a3f15f574a3d95880e2f3fd7667db67ff5322b90f5b.

Finite synchronization bisect

default async on historical failing machine:
  requested 160 tier 5/5, requested 240 tier 4/5, then service exit

sync before load_batch: 10/10
sync after load_batch:  10/10
sync before replay:     10/10

Global synchronization suppresses the failure in this finite matrix, but does not localize the exact producer/consumer streams and is not a production fix.

Source-audit findings

The latest read-only audit found:

  1. The full backend replay path refreshes the selected Graph-static DSV4 metadata via in-place DSV4Metadata.copy_ before replay.
  2. The Graph shape key is primarily based on graph size, stream index, and variant label; it does not directly encode all dynamic ragged layout or workspace dimensions.
  3. Correctness therefore depends on complete metadata refresh, sufficient capacity, valid workspace/buffer ownership, and correct stream ordering before replay.
  4. Some indexer/compressor work is captured inside the graph and may use internal alternate streams; a host-only pre-replay event cannot by itself diagnose or fix every graph-internal race.

These are audit findings and hypotheses, not proof of the exact root cause.

Hypotheses under test

Current priority after Stage C:

  1. Workspace or Graph-stable buffer reuse before a previous consumer completes.
  2. Missing producer/consumer ordering under sustained overlap.
  3. Request-pool / KV-location / ragged metadata lifetime conflicts at high concurrency.
  4. Incomplete recursive refresh of nested DSV4 metadata during repeated replay.
  5. A Graph or metadata cache key omitting a required layout/workspace dimension.
  6. A stale captured tensor view/data pointer or insufficient capacity.
  7. Graph-internal indexer/compressor alternate-stream work.

A simple one-time 168 -> 240 transition is now a lower-priority trigger hypothesis.

Next phase: R2 / D0-D3

Because the stable 4/4 reproducer is on A1 22cfd54c while this PR branch is based on a newer main, the planned R2 workflow is:

  1. Transplant this PR's debug commits onto an independent throwaway branch/worktree based exactly on 22cfd54c.
  2. D0-A: rerun the original A1 c256 overlap-ON minimal-log baseline.
  3. D0-B: run the R2 transplanted branch with all debug switches disabled to verify default-path reproduction equivalence.
  4. D1: enable sync-free core/indexer/c4/c128 metadata identity/capacity tracing on the stable c256 reproducer.
  5. D2: add debug workspace identity/generation/owner tracing.
  6. D3: perform component-level event bisect one boundary at a time.

D0-A and D0-B must both retain reproduction capability before an instrumented non-reproduction can be interpreted.

Non-goals

This PR does not claim that global synchronization is the production fix and does not propose merging an unconditional hot-path torch.cuda.synchronize().

If a missing dependency is proven, the intended follow-up is the smallest correct ordering mechanism at the proven boundary, for example:

metadata_ready_event.record(producer_stream)
replay_stream.wait_event(metadata_ready_event)

If synchronization only masks stale state, the follow-up should instead fix metadata copying, workspace ownership, tensor views, capacities, cache keys, or graph-internal stream ordering.

Validation

  • Branch rebuilt from current upstream main.
  • Diff contains only:
    • python/sglang/srt/layers/attention/deepseek_v4_backend.py
    • python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py
  • git diff --check passes.
  • py_compile passes for both modified files.
  • Default behavior is unchanged when all debug switches are unset.
  • Replay-state logger avoids CUDA tensor .item() fallback and therefore avoids injecting an accidental synchronization point.
  • Before-load, after-load, and before-replay synchronization trials each completed 10/10 in the finite matrix.
  • Latest overlap-OFF fresh-service c256 arm completed 5/5 without Bug 2.
  • Latest overlap-ON fresh-service c256 arm positively reproduced Bug 2 in 4/4 executed runs.
  • Preserved and checksummed complete crash evidence for overlap-on r1-r4.
  • Stage C C1 direct key 240 completed with a valid Graph-key gate.
  • Stage C C2 ordered 168 -> 240 with overlap ON completed with a valid Graph-key gate.
  • Stage C C3 ordered 168 -> 240 with overlap OFF completed with a valid Graph-key gate.
  • Confirmed Stage C is finite negative mechanism-probe evidence only.
  • Build the R2 throwaway worktree on A1 22cfd54c.
  • Revalidate D0-A original A1 reproduction.
  • Revalidate D0-B R2 default-path reproduction equivalence.
  • Run D1 metadata identity/capacity tracing on the stable c256 reproducer.
  • Add D2 workspace generation/owner tracing.
  • Perform D3 component-level event bisect at proven boundaries.
  • Identify the exact producer/consumer stream or stale ownership boundary.
  • Replace diagnostic synchronization with a production-safe fix before marking ready for review.

Expected outcome

This Draft PR provides controlled synchronization and metadata/buffer tracing for determining whether the residual failure is caused by a missing replay dependency or stale/incomplete Graph-associated state.

It should remain in Draft until the production-safe fix is identified.


CI States

Latest PR Test (Base): ❌ Run #29908517098
Latest PR Test (Extra): ❌ Run #29908516844

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces debugging and logging utilities for CUDA Graph execution and DeepSeek-V4 attention metadata. Specifically, it adds _debug_metadata_tensor_state to log tensor metadata states during copy and refresh operations, and _log_ragged_replay_state to log ragged graph replay states. It also introduces environment-variable-controlled synchronization points around batch loading and replay execution for debugging purposes. The review feedback highlights a performance concern in the newly added _log_ragged_replay_state method, where calling .item() on CUDA tensors forces synchronous device-to-host copies on the hot path, and suggests utilizing existing CPU-side metadata instead.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +1220 to +1237
verify_lens = layout.verify_lens
qo_indptr = layout.qo_indptr_device
verify_tokens = int(verify_lens.sum().item())
logger.info(
"Ragged Graph replay state: key_size=%s raw_bs=%d slots=%d "
"graph_tokens=%d verify_tokens=%d verify_lens_ptr=%d "
"qo_indptr_ptr=%d verify_lens_last=%d qo_indptr_last=%d tensors=%s",
self._replay_graph_key.size,
forward_batch.batch_size,
self._ragged_capture_slots(self._replay_graph_key.size),
layout.graph_num_tokens,
verify_tokens,
verify_lens.data_ptr(),
qo_indptr.data_ptr(),
int(verify_lens[-1].item()),
int(qo_indptr[-1].item()),
tensor_state,
)

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.

medium

Calling .item() on CUDA tensors (such as verify_lens and qo_indptr) forces a synchronous device-to-host (D2H) copy. Since this logging function is executed on the hot path during replay when SGLANG_LOG_DECODE_GRAPH_KEY is enabled, these synchronizations can significantly degrade performance.

We can avoid these synchronizations by leveraging the CPU-side metadata already available in layout (i.e., layout.total_verify_tokens and layout.verify_lens_cpu), falling back to .item() only if they are not populated.

        verify_lens = layout.verify_lens
        qo_indptr = layout.qo_indptr_device

        if layout.total_verify_tokens is not None:
            verify_tokens = layout.total_verify_tokens
            qo_indptr_last = layout.total_verify_tokens
        else:
            verify_tokens = int(verify_lens.sum().item())
            qo_indptr_last = int(qo_indptr[-1].item()) if qo_indptr.numel() > 0 else 0

        if layout.verify_lens_cpu is not None and len(layout.verify_lens_cpu) > 0:
            verify_lens_last = layout.verify_lens_cpu[-1]
        else:
            verify_lens_last = int(verify_lens[-1].item()) if verify_lens.numel() > 0 else 0

        logger.info(
            "Ragged Graph replay state: key_size=%s raw_bs=%d slots=%d "
            "graph_tokens=%d verify_tokens=%d verify_lens_ptr=%d "
            "qo_indptr_ptr=%d verify_lens_last=%d qo_indptr_last=%d tensors=%s",
            self._replay_graph_key.size,
            forward_batch.batch_size,
            self._ragged_capture_slots(self._replay_graph_key.size),
            layout.graph_num_tokens,
            verify_tokens,
            verify_lens.data_ptr(),
            qo_indptr.data_ptr(),
            verify_lens_last,
            qo_indptr_last,
            tensor_state,
        )

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.

Addressed in 4581db46.

The replay logger now prefers layout.total_verify_tokens and layout.verify_lens_cpu, avoiding CUDA .item() synchronization when CPU-side metadata is available. CUDA .item() is retained only as a defensive fallback when those fields are not populated.

git diff --check and py_compile pass.

@Phoenix3334
Phoenix3334 force-pushed the debug/dspark-cuda-graph-replay-bisect branch from 64abf2b to 5cc0c69 Compare July 17, 2026 06:40

Copy link
Copy Markdown
Contributor Author

Final diagnostic status

The current investigation phase is complete enough to close this diagnostic Draft PR.

A reproducible benchmark contract is now available on the current machine when the runtime is pinned to either of the following revisions:

A0 baseline:
692c5f7d532f129424b57961c262bbd253b411dc

A1 TP-budget broadcast candidate:
22cfd54cc4684467039ea6ee10612a5a8e19d3c4

Validated benchmark configuration:

Model: DeepSeek-V4-Pro-DSpark
TP: 8
Ragged verify mode: compact
CUDA Graph: enabled
Overlap scheduling: enabled
Radix Cache: disabled
cuda_graph_max_bs_decode: 128
mem_fraction_static: 0.82

Profiler batch size: 80
Forced fractions: 0.2 -> 0.4
Actual target Graph transition: key_size=168 -> key_size=240
Repetitions: 5

Observed on the current machine:

A0: 5/5 valid transitions, 0 CUDA/NCCL/scheduler errors
A1: 5/5 valid transitions, 0 CUDA/NCCL/scheduler errors
key_size=480: not observed in the benchmark interval

No additional SGLang production-code change was required to run this pinned benchmark. The A1 revision itself contains the separate cross-TP verify-budget broadcast candidate. The synchronization and metadata logging added by this PR were diagnostic only and were not required for the successful benchmark runs.

The current-main verify-all uniform-layout path can replay key_size=480 when the SPS table is uninitialized. That path is not equivalent to the validated 168 -> 240 benchmark and is excluded from this benchmark definition.

This result is a finite non-reproduction boundary on the current machine. It does not establish that the residual timing-sensitive failure is fixed. Issue #31023 should remain open until the root cause is identified or the historical failing environment can no longer reproduce under the validated gate.

Closing this Draft PR as diagnostic work is complete for now. If the failure is reproduced again, the next step is to reopen or replace this PR with a production-safe stream-dependency or metadata/workspace ownership fix.

Copy link
Copy Markdown
Contributor Author

Correction: formal capacity workload reproduces the residual failure

The earlier closure note stated that the pinned A0/A1 path could be used for continued formal benchmarking with hard gates. A subsequent formal capacity test shows that statement was too broad and must be corrected.

Using pinned A1 22cfd54cc4684467039ea6ee10612a5a8e19d3c4 with compact ragged verify, the production SPS table, CUDA Graph, overlap scheduling, and a 60k input / 1k output / concurrency 64 / 640 requests workload:

warm-up: 16/16 requests succeeded
formal c64 run with Graph-key logging: CUDA illegal memory access
formal c64 run without Graph-key logging: CUDA illegal memory access

In the logging-enabled run, TP0–TP7 were all replaying target key_size=240 before the failure, and key_size=480 was not observed. The second clean run reproduced without SGLANG_LOG_DECODE_GRAPH_KEY, so this is not a diagnostic-logging artifact.

The correct distinction is now:

forced-fraction transition microbenchmark:
  A0/A1 both complete valid 168 -> 240 transitions

formal capacity workload:
  A1 compact-SPS c64 reproduces the residual crash in 2/2 runs

The benchmark harness is operational, but the service does not pass the formal smoke gate. The full capacity sweep is blocked.

This PR remains diagnostic only: its global synchronization switches and metadata tracing are not a production fix. However, the renewed reproducibility makes the diagnostic branch useful again for localizing the exact metadata/workspace/stream boundary, so the Draft PR is being reopened. It should not be marked ready or merged until a minimal production-safe fix is identified.

@Phoenix3334 Phoenix3334 reopened this Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Diagnostic update: fresh direct c384 does not deterministically crash

A fresh-service direct high-concurrency control has refined the residual failure boundary.

Control

Revision: A1 22cfd54cc4684467039ea6ee10612a5a8e19d3c4
compact-SPS
CUDA Graph enabled
overlap disabled
60000 input / 1000 output tokens
warmup 16
then direct c384 x 3840 requests
no preceding c64/c128/c256 stages

Result

633 / 3840 requests succeeded
3207 / 3840 requests failed
Generation throughput: 52.6751 tok/s
post-workload health: HTTP 200
CUDA illegal-memory-access errors: 0
scheduler fatal errors: 0
NCCL fatal errors: 0

This is a severe capacity failure, but not a residual CUDA-crash reproduction. It must not be counted together with runs where the service terminates from illegal memory access.

The earlier overlap-off ascending sweep crashed during c384 only after the same service had already processed warmup, c64, c128, and c256. The difference makes cumulative state or service age a first-class variable: request/KV-slot reuse, timed-out-request cleanup, retraction generations, compact-layout buffer reuse, or Graph-associated metadata/workspace lifetime may be required before the CUDA failure is exposed.

The strongest current business-workload crash reproducer remains compact-SPS + CUDA Graph + overlap enabled at 60k/1k, c64 x 640, which failed with CUDA illegal memory access in 2/2 clean-service runs.

Implication for this Draft PR

This PR should remain Open and Draft. The current diagnostic synchronization is still not a production fix. Follow-up diagnostics should distinguish:

  • direct high-concurrency capacity failure from service-fatal CUDA failure;
  • fresh-service state from accumulated same-service state;
  • request/KV retraction and allocator generations before and after timed-out requests;
  • compact-layout and Graph-stable metadata/workspace creation, reuse, and retirement across workload stages.

The next controls are fresh overlap-off c256 repetitions, fresh Graph-off c384, and fresh static-verify c384. No Ready-for-review or merge transition is appropriate yet.

Copy link
Copy Markdown
Contributor Author

Diagnostic update: fresh-service business-workload matrix

A five-stage fresh-service matrix has completed on the pinned A1 revision 22cfd54cc4684467039ea6ee10612a5a8e19d3c4 using the real 60k/1k aiakperf workload.

Stage Verify / Graph / overlap Concurrency Succeeded Known CUDA illegal-memory signature Service survived
c256-r1 compact / on / off 256 2548 / 2560 no yes
c256-r2 compact / on / off 256 2546 / 2560 no yes
c256-r3 compact / on / off 256 2508 / 2560 yes no
graph-off-c384 compact / off / on 384 232 / 3840 no no
static-c384 static / on / on 384 696 / 3840 no yes

c256-r3 represents one crashed fresh service out of three. The server log contains two CUDA-error text matches; they are not counted as two independent crashes.

What this changes

Disabling overlap does not eliminate the residual failure:

compact + CUDA Graph + overlap off, fresh c256:
  service crashes = 1 / 3

The overlap-enabled business reproducer remains stronger:

compact + CUDA Graph + overlap on, fresh c64:
  service crashes = 2 / 2

This makes overlap a strong timing amplifier, not a strict prerequisite.

The static c384 control survived an intentionally overloaded workload without the known illegal-memory signature. That is useful negative evidence for the compact-ragged path, although it is not a capacity pass.

The Graph-disabled c384 arm is not a clean control: it lacked the known illegal-memory signature but the service exited after only 232/3840 successful requests. Its exit mechanism remains unclassified and it must not be described as stable.

Diagnostic priority for this Draft PR

The next instrumentation should target compact CUDA-Graph state and request/KV ownership rather than adding more broad performance tiers:

global_num_reqs
verify_token_budget
sum(verify_lens)
compact layout required length
compact layout max index
req_pool_indices count / min / max / unique count
verify_cache_loc count / min / max
Graph key / raw batch size / slots
request ID and batch generation around retraction
buffer object id / data_ptr / storage capacity
producer stream and replay stream
release_kv_cache / allocator.free timing relative to replay completion

The highest-value assertion is whether a request-pool slot, KV location, compact layout buffer, or nested metadata/workspace can be reused or freed before the CUDA Graph replay that references it has completed.

For localization, keep the original overlap-on c64 workload as the fast crash reproducer. Use a same-pressure c256 control matrix for causality:

compact + Graph + overlap off: extend to 5 fresh runs
compact + Graph off + overlap on: 3 fresh runs
static + Graph + overlap on: 3 fresh runs

This PR remains a diagnostic Draft. The current global synchronization switches remain bisect tools only and are not proposed as the production fix.

Copy link
Copy Markdown
Contributor Author

Validation update: c256 matrix did not reproduce, but this remains a diagnostic PR

I added a new c256 fresh-service matrix and a reproduction-evidence audit to the linked issue.

New matrix scope

Candidate: 22cfd54c
Model: DeepSeek-V4-Pro-DSpark
TP: 8
Workload: 60000 input / 1000 output
Concurrency: 256
Formal requests: 2560
Seed contract: random_seed=0, shuffle=False, unreproducible=False
Lifecycle: fresh service per stage

Result summary

Arm CUDA Graph Overlap scheduling Runs Result
compact-SPS ON OFF 2 no Bug2 crash; only small request-level failures
compact-SPS OFF ON 3 capacity/time-out failures; service survived
static ON ON 3 capacity/time-out failures; service survived

Across all 8 stages:

bug2_crash:       0 / 8
CUDA errors:      0
scheduler errors: 0
NCCL errors:      0
post health:      200 for all stages
server survived:  yes for all stages

Interpretation for this PR

This is useful negative reproduction evidence, but it does not change the status of this PR:

  • It does not prove that the residual Bug 2 is fixed.
  • It does not identify the missing dependency or stale metadata/workspace boundary.
  • It does not justify moving this PR out of Draft.
  • It does not make the diagnostic synchronizations production-safe.

The reproduction audit still has a confirmed positive run on the same A1 candidate (22cfd54c) in a diagnostic c256 fresh-service setup:

compact-SPS + CUDA Graph ON + overlap OFF
fresh service
c256 / 2560 requests
60000 / 1000
seed=0, shuffle=False
third repetition -> CUDA illegal memory access + scheduler exception + server exit

The current matrix only ran two clean repetitions of that exact overlap OFF + Graph ON c256 arm, while the historical positive case failed on the third repetition. Therefore the clean matrix is a finite non-reproduction result, not a fix signal.

Next PR-relevant validation

The next useful validation for this Draft PR is to re-enter a positive crash path and then compare metadata / buffer / stream state using the debug switches already introduced here:

  1. Repeat compact-SPS + CUDA Graph ON + overlap OFF + fresh c256 at least 3 times, preferably 5.
  2. Add compact-SPS + CUDA Graph ON + overlap ON + fresh c256 for overlap-path coverage.
  3. If both remain clean, rerun the deterministic batch-80 key_size=168 -> 240 transition gate.

Only after a positive crash path is recovered should the synchronization / metadata tracing in this PR be used to localize the exact replay boundary.

Copy link
Copy Markdown
Contributor Author

Positive reproduction evidence added — July 26, 2026

The latest fresh-service c256 matrix on A1 22cfd54c now provides positive Bug 2 reproduction evidence:

compact-SPS + CUDA Graph ON + overlap OFF: 0/5 crashes
compact-SPS + CUDA Graph ON + overlap ON:  4/4 executed runs crashed
overlap-on r5: not run because the pipeline exited during r4

The PR body has been updated to include:

  • the full positive matrix;
  • distinct r1-r3 scheduler/synchronization surfacing versus the r4 NCCL-watchdog surfacing;
  • evidence provenance and checksum status;
  • the relationship to the earlier v2 negative-control matrix;
  • the remaining directed key_size=168 -> 240 transition and metadata/workspace comparison work.

This PR remains a diagnostic Draft PR. The result confirms Bug 2 remains present and that overlap is a strong trigger in the tested environment; it does not identify the exact failing kernel or justify an unconditional synchronization as the production fix.

Copy link
Copy Markdown
Contributor Author

Stage C Pass-1 completed with valid steady target-verify Graph-key sequences:

C1: direct 240, overlap ON         -> VALID_PASS
C2: ordered 168 -> 240, overlap ON -> VALID_PASS
C3: ordered 168 -> 240, overlap OFF -> VALID_PASS

All profiler rounds completed with match_fraction=1.00; no key-size 480 collapse occurred; CUDA illegal-memory, scheduler-fatal, and NCCL-watchdog counts were all zero.

Interpretation: this is a finite negative mechanism probe, not fix evidence. It does not weaken the c256 overlap-ON 4/4 positive reproduction. A single lightweight tier transition is now a lower-priority trigger model; sustained-overlap metadata/workspace/buffer/request/KV lifetime and stream ownership are higher priority.

Next planned work is R2/D0-D3 and has not yet been executed: transplant this PR's debug commits onto an independent A1 22cfd54c worktree, verify D0-A and D0-B reproduction equivalence, then run sync-free metadata/workspace tracing and component-level event bisect.

Copy link
Copy Markdown
Contributor Author

Mechanism model guiding the debug bisect

This comment records the engineering model behind the R2 / D0-D3 plan. It is a hypothesis framework for instrumentation, not a claim that the exact root cause is already proven.

Execution model

The failing path combines:

per-request speculative verify-length selection
  -> compact ragged target-verify packing
  -> dynamic Graph-tier selection
  -> in-place refresh of Graph-associated metadata/buffers
  -> CUDA Graph replay under overlap scheduling

A captured tier can be reused by batches with the same graph size while their detailed ragged state differs (verify_lens, qo_indptr, page/KV locations, indexer/compressor metadata, and workspace requirements). Reuse is correct only when the selected Graph-static state has stable addresses, sufficient capacity, complete nested refresh, and valid stream/lifetime ordering.

Failure model

Under overlap, batch N can still consume metadata/workspace while batch N+1 is being prepared. Two invariants must hold:

producer completion precedes consumer/replay access;
consumer completion precedes buffer/workspace/request/KV-slot reuse.

Violating either invariant can produce partially updated ragged metadata or use-after-reuse. The asynchronous CUDA error may then surface later at copy_done.synchronize() or through an NCCL watchdog. Those boundaries reveal the poisoned CUDA context but do not identify the originating kernel.

Evidence interpretation

  • Fix(DSpark): Broadcast Verify Budget Across TP Ranks for Compact Graph Tier Alignment #31195 fixed Bug 1: cross-TP planning/Graph-tier divergence.
  • Bug 2 remains with TP agreement, so the current target is execution ownership/lifetime rather than another scalar broadcast issue.
  • Stage C validly passed direct 240 and ordered 168 -> 240 transitions with overlap ON/OFF. This lowers the priority of a simple one-transition trigger model.
  • The c256 overlap-ON workload still crashed in 4/4 executed runs. Its long request lifetime, high concurrency, sustained overlap, and repeated state reuse make it the higher-value localization path.

How this maps to D0-D3

D0-A: confirm the original A1 async reproducer is still active
D0-B: confirm the R2 transplanted debug commits are behaviorally neutral when disabled
D1: correlate replay sequence/Graph key with core/indexer/c4/c128 object identity, data_ptr, and capacity
D2: track workspace generation and ownership to detect early reuse
D3: insert one component-level producer/consumer event dependency at a time

A component event that repeatedly suppresses the stable crash raises the priority of that boundary, but does not by itself prove a production fix; event insertion can alter timing. If host-side component events do not help while global synchronization does, the investigation should move toward Graph-internal alternate streams, allocator/workspace lifetime, stale captured views, or request/KV ownership.

The desired final change is the smallest proven dependency or ownership fix, such as a targeted record() / wait_event() pair, delayed reuse, complete metadata refresh, capacity correction, or cache-key refinement. An unconditional hot-path torch.cuda.synchronize() remains a diagnostic control only.

Copy link
Copy Markdown
Contributor Author

R2 / Phase D validation update

The diagnostic commits from this Draft PR were transplanted onto an independent throwaway branch based exactly on the known-positive A1 commit 22cfd54c.

R2 branch: debug/dspark-bug2-phase-d-r2
R2 HEAD:   d4948a64
base:      22cfd54c

R2 contains this PR's four debug commits plus one local one-line compatibility fix required by the older A1 code:

resolve_ragged_verify_layout(...)
  -> self._ragged_verify_layout(...)

The original A1 worktree was not modified, and the R2 branch has not been pushed.

Reproduction equivalence

The established c256 compact-SPS / CUDA Graph ON / overlap ON workload was run on both paths:

D0-A original A1, minimal logging:
  BUG2_CRASH
  success 0/2560

D0-B R2, all debug switches OFF:
  BUG2_CRASH
  success 221/2560

This confirms that the transplanted default path retains reproduction capability and is suitable for further diagnostic instrumentation.

Sync-free D1 result

The initial D1 attempt failed with a transplant-only Python NameError; it was classified and preserved as INSTRUMENTATION_FAILURE, not Bug 2.

After the one-line compatibility fix, D1-fixed reproduced the genuine asynchronous failure with metadata/ragged tracing enabled:

success: 7/2560
classification: BUG2_CRASH
illegal-memory / scheduler / NCCL: 3 / 1 / 2

The final surfacing path again included result.copy_done.synchronize() and ProcessGroupNCCL watchdog reporting, consistent with an earlier asynchronous CUDA failure. The sync-free logger therefore did not suppress the race through observer effect.

Trace coverage correction

The D1-fixed run emitted approximately:

metadata-state lines: 10080
ragged-state lines:   3360

However, read-only forensic analysis showed that the metadata helper covered only core attention metadata. It did not provide per-replay indexer/c4/c128 ownership:

  • in some decode paths those direct fields are None;
  • genuine target-verify builds PagedIndexerMetadata and FusedCompressMetadata in the captured in-graph metadata construction path;
  • the associated Python builder code runs at capture time, not on every graph replay.

Within the covered core surface, owner identities, pointers, shapes, strides, and storage capacities remained stable; no owner replacement, capacity shrink, or core-pointer alias was found. This weakens a core Graph-static pointer-replacement hypothesis but does not cover graph-internal component workspaces or per-replay contents.

Planned diagnostic split

The follow-up instrumentation is now separated into two stages:

E1 — low-risk observability

  • one CPU-side replay sequence shared by ragged/core logs;
  • core refresh correlation at the actual chosen_metadata.copy_(...) site;
  • explicit phase=capture_static_build identity traces for indexer/c4/c128;
  • default OFF, sync-free, no device-value reads.

E2 — ownership/lifetime observation

  • per-actual-cache-key generation state bound to the selected Graph-static metadata;
  • nonblocking prior completion-event query() before overwrite;
  • post-replay event record;
  • no wait_event() and no synchronization in the observational stage.

E1 has been approved for local implementation on R2 and is currently being written. It is not yet statically validated, committed, experimentally run, or pushed.

This PR remains diagnostic and Draft. No production fix has been identified, and the global synchronization switches remain bisect tools rather than proposed final behavior.

Copy link
Copy Markdown
Contributor Author

Local R2 E1/E2 validation update

The A1-based throwaway R2 branch has now completed two additional diagnostic stages. These commits are local only and have not been pushed to this Draft PR.

Local diagnostic commits

8eed9ad6  E1: opt-in DSV4 component metadata trace + replay_seq correlation
1bb99a93  E2: generation and nonblocking replay-completion observation

Both stages remained default-off and diagnostic-only.

E1 result

The E1 patch added one per-runner monotonic replay_seq and sync-free metadata identity/capacity tracing. On the stable overlap-ON c256 reproducer:

3/3 valid runs reproduced BUG2_CRASH
trace coverage valid in all runs
instrumentation exceptions: 0

The crash still surfaced through the real asynchronous CUDA illegal-memory path. Core Graph-static object identity and covered tensor pointers/capacities remained stable. Indexer capture-static identities were visible, while c4/c128 remained owner_none at the host metadata-copy boundary because those descriptors are constructed inside the captured graph path.

E2 design

The local E2 patch added debug ownership state keyed by:

(bucket, bs, id(chosen_metadata))

It records:

  • metadata generation and owning replay_seq;
  • prior recorded event generation/replay sequence;
  • a nonblocking event.query() before chosen_metadata.copy_(temp_metadata);
  • a replay-stream completion event after Graph replay.

No wait_event(), global synchronization, or production control-flow change was added.

E2 result

Runs Overlap Successful requests before crash previous_complete=false
on1 / on2 / on3 ON 1 / 16 / 116 about 31–47%
off1 OFF 2317 0
off2 OFF 152 0

All five runs reproduced the same service-level Bug 2 failure class.

The overlap-OFF controls show that the host-observed overwrite-before-whole-graph-completion condition is not necessary for the crash and cannot be the sole root-cause explanation. This result narrows, but does not fully eliminate, host metadata ownership as a possible amplifier or secondary race.

Updated localization priority

The strongest remaining candidates are outside this host-only observation surface:

  1. graph-internal c4/c128 compressor workspace or ring/pool reuse;
  2. indexer raw-index / index-KV buffers;
  3. internal alternate-stream ordering;
  4. request/KV-slot lifetime;
  5. dynamic metadata contents, layout/capacity assumptions, or kernel indexing.

D3 component-level localization and dsv4/compressor.py tracing have been authorized locally. No D3 result or production fix is claimed yet. This PR should remain Draft.

Copy link
Copy Markdown
Contributor Author

Diagnostic progress since E1/E2

Bug 1 (#31195, cross-TP verify-budget / Graph-tier divergence) is now treated as a resolved prerequisite. This Draft PR remains focused on observability for the independent residual illegal-memory-access failure, Bug 2.

What the local diagnostic branch established

The sync-free replay_seq and metadata identity work from this PR was extended locally with default-off probes on an A1-based throwaway R2 branch. The current local head is c624ecb1 and has not been pushed.

Completed observations:

  • E1 replay correlation remained valid on real crashing runs (3/3 overlap-ON reproductions).
  • E2 showed that host metadata overwrite before previous whole-Graph completion is not necessary: overlap-OFF runs had previous_complete=false = 0 and still reproduced Bug 2.
  • Active compressor_v2 c4/c128 write_loc bounds were not exceeded in the covered run.
  • Covered core-attention/indexer reads were within capacity after correcting token/page units.
  • Covered Graph-static metadata had no observed source/destination copy mismatch, structural-invariant violation, or TP fingerprint divergence.
  • The aggregate optional-field anomaly was resolved to the known raw_out_loc host int64 -> Graph-static int32 conversion; it was Graph-key/bucket expressed and remained far below the int32 range.
  • Fifteen covered immutable Graph-static fields showed no replay-time mutation across 21,608 nonblocking readbacks while the run still crashed.
  • A preflight Triton probe on the active SITE4 req_to_token -> full_to_swa path found no explicit OOB or address-arithmetic wrap through the last completed readbacks.
  • The translated compressor out_loc boundary was also checked in its translated address space; no OOB was observed.
  • Per-Graph-key SITE4 metadata/output resources were confirmed to use independent storage, with no live-vs-captured dimension mismatch or actionable storage alias.
  • Static auditing of result.copy_done showed the output-copy boundary is explicitly ordered (copy_stream.wait_stream(forward_stream) plus record_stream lifetime protection). copy_done.synchronize() is therefore the surfacing point of an earlier asynchronous fault, not an established copy-chain fault site.

A comparable Graph-OFF control completed 2560/2560. This substantially raises the priority of Graph capture/replay mechanisms, while remaining only one control rather than a universal exclusion proof.

Current localization

No error was observed in the instrumented host-visible surfaces:

metadata content / structure / TP consistency / replay mutation
covered index and translated-address bounds
per-Graph resource ownership and dimensions
result-copy and audited KV/cache stream dependencies

The active candidates are now device-side and Graph-specific: an uninstrumented in-Graph address computation, kernel-local/shared-memory indexing, Graph-associated workspace lifetime/aliasing, or a capture/replay/codegen interaction.

Device-tooling result

compute-sanitizer itself is compatible with a standalone CUDA-Graph + Triton smoke, but the full TP8 model cannot load under memcheck. The shard uses roughly 264/275 GiB per GPU; three smoke attempts OOMed during MxFP4 expert-weight post-processing before Graph capture. Lowering mem_fraction_static cannot address a pre-KV-pool weight-load OOM.

Classification:

SANITIZER_DEVICE_MEMORY_INSUFFICIENT

The next planned step is a low-overhead CUDA GPU coredump-on-exception run after finding a lower-cost bare reproducer. The objective is direct evidence for the faulting rank/kernel/PC/address before adding further waits or changing production kernels.

PR status

This remains a diagnostic Draft PR. The local extensions are intentionally unpushed and default-off. No Bug 2 production fix is claimed.

Copy link
Copy Markdown
Contributor Author

Diagnostic scope update: mode/version provenance and the v0.5.16 decision gate

This Draft PR should remain diagnostic-only. A recent review of the official DSpark blog and v0.5.16 release changes the scope wording, not the recorded Phase-D results.

Official happy path vs. the Bug 2 stress paths

The blog's Figure 5 command is:

compact, no SPS table
TP8 / B300
bs=1, input/output=256/256
cuda-graph-max-bs=4
CUDA Graph ON
optional --disable-overlap-schedule

Without an SPS table, compact is verify-all uniform-ragged mode. The original #31023 bs=64 reproducer stressed that same no-SPS mechanism family over longer repeated replay.

The later c256 reproducer used a different and broader path:

compact + SPS table
confidence-scheduled variable verify lengths
60k/1k, 2560 requests, sustained multi-tier replay

The PR and issue should continue to distinguish these two modes; “compact” alone is not a sufficient experiment descriptor.

Source provenance

The stable positive reproducer and local D3/P0-P3 diagnostics were run from a v0.5.14-series base environment while importing source from A1 22cfd54c (and local default-off diagnostic commits on R2). They were not a clean v0.5.16 release run.

Therefore:

  • the evidence remains valid for the tested development snapshot;
  • it must not be represented as proof that clean v0.5.16 is affected;
  • no local D3/P0-P3 probe commit has been pushed to this PR;
  • no production synchronization or ownership fix is claimed.

Current evidence boundary

The completed investigation has lowered the priority of covered host-visible metadata corruption, explicit covered index OOB, translated out_loc OOB, SITE4 graph-resource structural mismatch, and result-copy handoff. A Graph-OFF strong control survived. The exact faulting in-Graph kernel/resource remains unknown, and full-process memcheck was blocked by device-memory overhead during model loading.

Next decision gate

A clean v0.5.16 matrix is now required before extending this branch or proposing a fix:

  1. official-scale compact/no-SPS happy path;
  2. original compact/no-SPS bs=64 stress path;
  3. compact+SPS c256 60k/1k strong reproducer;
  4. Graph-OFF / overlap-OFF / static controls;
  5. cap-accept only after the primary matrix.

Interpretation:

v0.5.16 reproduces
  -> rebase/recreate the smallest diagnostics on the clean release baseline

v0.5.16 does not reproduce in repeated strong runs
  -> bisect 22cfd54c..v0.5.16 to identify the change that removed the trigger

v0.5.16 fails differently
  -> classify as a new failure before reusing the old diagnosis

Until that gate completes, this PR should remain Draft and should not be described as a current-release production fix.

Copy link
Copy Markdown
Contributor Author

Diagnostic update: clean v0.5.16 exposes a deterministic capture-shape failure at bs=60

The clean v0.5.16 regression has now isolated a new startup-time signature that is separate from the runtime Bug 2 evidence this Draft PR was created to investigate.

Environment and path

image: iregistry.baidu-int.com/nccl/sglang:v0.5.16-cu130
sglang: 0.5.16
model: DeepSeek-V4-Pro-DSpark
TP8
compact / no SPS table
CUDA Graph ON
overlap ON

Fresh-server capture ladder

max-bs=4    -> READY
max-bs=8    -> READY
max-bs=16   -> READY
max-bs=32   -> READY
max-bs=64   -> bs=64 captures, bs=60 illegal-memory failure
max-bs=128  -> larger shapes through bs=64 capture, bs=60 illegal-memory failure

GPU memory returned to 0 MiB after each arm. The repeated stop at the same shape, after larger shapes have already completed in the max-bs=128 arm, makes ordinary cumulative memory pressure or capture-count accumulation unlikely within this test matrix.

The observed exception is raised from the decode Graph-capture path, but that synchronization/exception site is not treated as the faulting kernel.

Scope implications for this PR

This Draft PR should continue to remain diagnostic-only, but the investigation now has two explicitly separate signatures:

  1. historical runtime Bug 2 on the A1 development snapshot: compact target-verify replay under sustained load;
  2. clean v0.5.16-cu130 startup failure: deterministic decode Graph capture at shape bs=60.

The second signature is useful because it may provide a much lower-cost reproducer for kernel-level localization, but common root cause is currently unproven.

The official Figure 5 scale (--cuda-graph-max-bs 4, batch-1 256/256 trace) reaches readiness and must not be described as failing. The new result only appears when the captured shape set is expanded to include bs=60.

The compact+SPS c256 regression is proceeding with max-bs 32 because max-bs 128 cannot start on this image. Any such result must retain the changed-Graph-coverage caveat; a max-bs-32 pass would not establish that the historical max-bs-128 path is fixed.

No production correction is claimed.

Copy link
Copy Markdown
Contributor Author

Final diagnostic scope update from the clean v0.5.16 regression

The current-release matrix has now isolated a new startup-time signature and a stable low-tier control. This Draft PR should remain diagnostic-only; no production fix is claimed.

New clean-release evidence

Official Figure 5-scale path:
  compact / no SPS / max-bs=4 / bs1 / 256-256 -> PASS

Low-tier capture and replay:
  max-bs-decode=32
  max-running-requests=32
  compact + historical SPS
  Gate 1: 32/32, 100% Graph replay
  Gate 2: 320/320 on the same service, 100% Graph replay
  illegal-memory=0, scheduler exception=0

Larger capture shapes:
  run 1 -> first failure at bs=60, TP7, Triton surfacing point
  run 2 -> skip bs=60, first failure at bs=96, TP4,
           TRT-LLM fused-MoE routing surfacing point
  run 3 -> first failure at bs=112, TP6, DeepGEMM surfacing point

Approximately 42 GB remained free per GPU at failure. Because the failing shape, rank, and surfacing kernel vary, bs=60 is not a uniquely corrupt shape. Skipping it only moves the asynchronous illegal-memory exposure.

Relation to the runtime Bug 2 investigation

The historical compact+SPS c256/60k/1k workload cannot be faithfully rerun on clean v0.5.16:

  • capturing the larger Graph range fails during startup;
  • restricting capture to 32 makes c256 exceed the captured range and fall predominantly to eager decode, causing severe throughput collapse and client timeouts.

Accordingly:

large-shape startup capture failure: CONFIRMED
historical runtime Bug 2 on v0.5.16: INCONCLUSIVE
shared root cause: PLAUSIBLE_NOT_PROVEN
exact faulting kernel: UNKNOWN
production fix: NONE

The existing Phase-D probes and local R2 diagnostics remain relevant for contract and instrumentation design, but the new startup signature must not be retroactively presented as proof of the same root cause.

Prepared artifacts

dspark_v0.5.16_bug2_repro_20260803_sanitized.tar.gz
SHA256: 8452ded941ecaa0903b3f12d078fa4cf31c9fa99c435c5f60d4688d379830f28

dspark_v0.5.16_m1_official_trace_20260803_sanitized.tar.zst
SHA256: 18ee74ddc962ac4cd12311ab5169aa9a86540ee00e781afe67e89d76efedca7f

The second archive contains GPU-only timelines for the passing official small-batch path and is supplemental profiling evidence, not crash evidence.

@github-actions

Copy link
Copy Markdown
Contributor

Thanks @Phoenix3334. Closing this because it is still a draft and has not been updated in 53 days.

Reopen it if the work is still relevant.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant