Repository navigation
Debug(DSpark): Bisect target-verify CUDA Graph replay synchronization - #31455
Phoenix3334 wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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,
)There was a problem hiding this comment.
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.
64abf2b to
5cc0c69
Compare
Final diagnostic statusThe 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: Validated benchmark configuration: Observed on the current machine: 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 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. |
Correction: formal capacity workload reproduces the residual failureThe 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 In the logging-enabled run, TP0–TP7 were all replaying target The correct distinction is now: 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. |
Diagnostic update: fresh direct c384 does not deterministically crashA fresh-service direct high-concurrency control has refined the residual failure boundary. ControlResultThis 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 PRThis PR should remain Open and Draft. The current diagnostic synchronization is still not a production fix. Follow-up diagnostics should distinguish:
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. |
Diagnostic update: fresh-service business-workload matrixA five-stage fresh-service matrix has completed on the pinned A1 revision
What this changesDisabling overlap does not eliminate the residual failure: The overlap-enabled business reproducer remains stronger: 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 PRThe next instrumentation should target compact CUDA-Graph state and request/KV ownership rather than adding more broad performance tiers: 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: This PR remains a diagnostic Draft. The current global synchronization switches remain bisect tools only and are not proposed as the production fix. |
Validation update: c256 matrix did not reproduce, but this remains a diagnostic PRI added a new c256 fresh-service matrix and a reproduction-evidence audit to the linked issue. New matrix scopeResult summary
Across all 8 stages: Interpretation for this PRThis is useful negative reproduction evidence, but it does not change the status of this PR:
The reproduction audit still has a confirmed positive run on the same A1 candidate ( The current matrix only ran two clean repetitions of that exact Next PR-relevant validationThe 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:
Only after a positive crash path is recovered should the synchronization / metadata tracing in this PR be used to localize the exact replay boundary. |
Positive reproduction evidence added — July 26, 2026The latest fresh-service c256 matrix on A1 The PR body has been updated to include:
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. |
|
Stage C Pass-1 completed with valid steady target-verify Graph-key sequences: All profiler rounds completed with 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 |
Mechanism model guiding the debug bisectThis 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 modelThe failing path combines: A captured tier can be reused by batches with the same graph size while their detailed ragged state differs ( Failure modelUnder overlap, batch N can still consume metadata/workspace while batch N+1 is being prepared. Two invariants must hold: Violating either invariant can produce partially updated ragged metadata or use-after-reuse. The asynchronous CUDA error may then surface later at Evidence interpretation
How this maps to D0-D3A 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 |
R2 / Phase D validation updateThe diagnostic commits from this Draft PR were transplanted onto an independent throwaway branch based exactly on the known-positive A1 commit R2 contains this PR's four debug commits plus one local one-line compatibility fix required by the older A1 code: The original A1 worktree was not modified, and the R2 branch has not been pushed. Reproduction equivalenceThe established c256 compact-SPS / CUDA Graph ON / overlap ON workload was run on both paths: This confirms that the transplanted default path retains reproduction capability and is suitable for further diagnostic instrumentation. Sync-free D1 resultThe initial D1 attempt failed with a transplant-only Python After the one-line compatibility fix, D1-fixed reproduced the genuine asynchronous failure with metadata/ragged tracing enabled: The final surfacing path again included Trace coverage correctionThe D1-fixed run emitted approximately: 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:
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 splitThe follow-up instrumentation is now separated into two stages: E1 — low-risk observability
E2 — ownership/lifetime observation
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. |
Local R2 E1/E2 validation updateThe 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 commitsBoth stages remained default-off and diagnostic-only. E1 resultThe E1 patch added one per-runner monotonic 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 E2 designThe local E2 patch added debug ownership state keyed by: It records:
No E2 result
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 priorityThe strongest remaining candidates are outside this host-only observation surface:
D3 component-level localization and |
Diagnostic progress since E1/E2Bug 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 establishedThe sync-free Completed observations:
A comparable Graph-OFF control completed Current localizationNo error was observed in the instrumented host-visible surfaces: 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
Classification: 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 statusThis remains a diagnostic Draft PR. The local extensions are intentionally unpushed and default-off. No Bug 2 production fix is claimed. |
Diagnostic scope update: mode/version provenance and the v0.5.16 decision gateThis 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 pathsThe blog's Figure 5 command is: Without an SPS table, The later c256 reproducer used a different and broader path: The PR and issue should continue to distinguish these two modes; “compact” alone is not a sufficient experiment descriptor. Source provenanceThe stable positive reproducer and local D3/P0-P3 diagnostics were run from a v0.5.14-series base environment while importing source from A1 Therefore:
Current evidence boundaryThe completed investigation has lowered the priority of covered host-visible metadata corruption, explicit covered index OOB, translated Next decision gateA clean v0.5.16 matrix is now required before extending this branch or proposing a fix:
Interpretation: Until that gate completes, this PR should remain Draft and should not be described as a current-release production fix. |
Diagnostic update: clean v0.5.16 exposes a deterministic capture-shape failure at
|
Final diagnostic scope update from the clean v0.5.16 regressionThe 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 evidenceApproximately 42 GB remained free per GPU at failure. Because the failing shape, rank, and surfacing kernel vary, Relation to the runtime Bug 2 investigationThe historical compact+SPS c256/60k/1k workload cannot be faithfully rerun on clean v0.5.16:
Accordingly: 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 artifactsThe second archive contains GPU-only timelines for the passing official small-batch path and is supplemental profiling evidence, not crash evidence. |
|
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: |
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:
However, the residual failure remains present. A fresh-service c256 matrix on A1
22cfd54cpositively reproduced Bug 2:A later valid Stage C forced-fraction probe completed all three mechanism arms without a crash:
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
SGLANG_DEBUG_CUDA_GRAPH_SYNC_BEFORE_LOAD_BATCH=1SGLANG_DEBUG_CUDA_GRAPH_SYNC_AFTER_LOAD_BATCH=1SGLANG_DEBUG_CUDA_GRAPH_SYNC_BEFORE_REPLAY=1SGLANG_LOG_DECODE_GRAPH_KEY, log compact target-verify replay state and selected Graph-stable / nested DSV4 metadata identities, shapes, strides, capacities, and data pointers..item()in the replay-state logger; when CPU-side scalars are unavailable, emit sentinel values rather than forcing a device-to-host synchronization.Current evidence
Cross-TP planning fix (#31195)
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:
Summary:
For overlap-on r1-r3, the asynchronous CUDA error surfaced through:
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:
Pass-1 used minimal Graph-key logging to reduce observer effects.
0.4240only (168=0,240=7304,480=0)match_fraction=1.000.2 -> 0.4168 -> 240(168=7840,240=7368,480=0)match_fraction=1.000.2 -> 0.4168 -> 240(168=6832,240=6504,480=0)match_fraction=1.00Validity gates:
22cfd54c;--disable-overlap-schedule;runwas used; the official SPS table was not overwritten;Interpretation:
The mechanism probe is much lighter than the strong reproducer:
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:
For Stage C:
7722243832273728c3b77a3f15f574a3d95880e2f3fd7667db67ff5322b90f5b.Finite synchronization bisect
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:
DSV4Metadata.copy_before replay.These are audit findings and hypotheses, not proof of the exact root cause.
Hypotheses under test
Current priority after Stage C:
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
22cfd54cwhile this PR branch is based on a newermain, the planned R2 workflow is:22cfd54c.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:
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
main.python/sglang/srt/layers/attention/deepseek_v4_backend.pypython/sglang/srt/model_executor/runner/decode_cuda_graph_runner.pygit diff --checkpasses.py_compilepasses for both modified files..item()fallback and therefore avoids injecting an accidental synchronization point.22cfd54c.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