Skip to content

[Fix] disaggregation: Avoid extra GPU contexts with PD - #45678

Merged
ShangmingCai merged 4 commits into
sgl-project:mainfrom
trevor-m:pd-transfer-thread-device
Oct 27, 2026
Merged

ShangmingCai merged 4 commits into
sgl-project:mainfrom
trevor-m:pd-transfer-thread-device

Conversation

@trevor-m

@trevor-m trevor-m commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

With PD disagg, an extra GPU context is accidently created on GPU0 by the other GPU workers which wastes about 1GB of gpu memory.

[by Claude Code]

Motivation

A PD prefill rank whose GPU is not CUDA device 0 opens a second CUDA context on device 0 the first time it sends KV
for a request with a cached prefix. That rank then holds about 0.6–1 GiB on another rank's GPU (656 MiB in the repro
below, about 1 GiB with DeepSeek-V4.1 attention-DP2 prefill). The memory is taken after that GPU's KV pool was sized
against its free memory, so it eats into the headroom left for activations and graphs.

Cause.

  • With overlap scheduling, maybe_send_cached_prefix_chunk (disaggregation/prefill.py) records a torch.cuda.Event
    on the forward stream for the early cached-prefix send.
  • Mooncake's prefill transfer_worker thread calls wait_event.synchronize() on that event before it reads the KV.
  • That thread never selects a device, so the CUDA runtime runs the call on device 0 and creates device 0's primary
    context in the process.
  • Ranks that already live on device 0 reuse their own context. Every other rank gets a new one.
  • mori's _transfer_worker does the same wait_event.synchronize().

Modifications

  • disaggregation/common/utils.py adds two helpers:
    • bind_thread_to_device(gpu_id) sets the calling thread's device through current_platform. It is a no-op on
      platforms that do not implement set_device.
    • run_on_device(gpu_id, fn, *args) is a thread target that binds the thread, then runs fn(*args).
  • Mooncake:
    • The prefill transfer_worker threads start through run_on_device(kv_args.gpu_id, ...).
    • The transfer thread pools bind each pool thread with initializer=bind_thread_to_device.
  • mori: the _transfer_worker threads start through run_on_device.

The worker functions themselves are unchanged, so existing unit tests that drive them directly need no changes.

Repro (dummy weights, one 4-GPU node)

Prefill runs TP2 on GPUs 0,1, so rank 1 lives on GPU 1. Decode runs TP1 on GPU 2. The same ~2k-token prompt is
sent three times, so requests 2 and 3 hit the radix cache and take the early cached-prefix send.

MODEL=Qwen/Qwen3-0.6B
COMMON="--model-path $MODEL --load-format dummy --disaggregation-transfer-backend mooncake --mem-fraction-static 0.5"
CUDA_VISIBLE_DEVICES=0,1 python3 -m sglang.launch_server $COMMON --tp-size 2 --disaggregation-mode prefill --port 30000 &
CUDA_VISIBLE_DEVICES=2 python3 -m sglang.launch_server $COMMON --tp-size 1 --disaggregation-mode decode --port 30001 &
# wait for both /health, then:
python3 -m sglang_router.launch_router --pd-disaggregation --prefill http://127.0.0.1:30000 8998 \
  --decode http://127.0.0.1:30001 --port 8000 &
PROMPT=$(python3 -c "print(' '.join(['The quick brown fox jumps over the lazy dog.'] * 200))")
for i in 1 2 3; do
  curl -s localhost:8000/generate -H 'Content-Type: application/json' \
    -d "{\"text\": \"$PROMPT\", \"sampling_params\": {\"max_new_tokens\": 8, \"temperature\": 0}}" > /dev/null
done
nvidia-smi

On our nodes, Mooncake moved the KV over NVLink (MC_FORCE_MNNVL=1 SGLANG_MOONCAKE_CUSTOM_MEM_POOL=True). The bug
does not depend on the transport.

Before (main): requests 2 and 3 report cached_tokens 1984 of 2000, and the TP1 prefill scheduler now also
holds a context on GPU 0.

|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|    0   N/A  N/A             492      C   sglang::scheduler_TP0                 (pool)     |
|    0   N/A  N/A             684      C   sglang::scheduler_TP1                   656MiB   |
|    1   N/A  N/A             684      C   sglang::scheduler_TP1                 (pool)     |
|    2   N/A  N/A             491      C   sglang::scheduler                     (pool)     |

The GPU 0 row for pid 684 is absent in nvidia-smi right after startup; it appears with the first cached-prefix
send.

After (this PR), same commands and the same cached_tokens: one context per process.

|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|    0   N/A  N/A             494      C   sglang::scheduler_TP0                 (pool)     |
|    1   N/A  N/A             687      C   sglang::scheduler_TP1                 (pool)     |
|    2   N/A  N/A             495      C   sglang::scheduler                     (pool)     |

Both runs had 0 KV-transfer failures, and every request completed.

Tests

  • New: test/registered/unit/disaggregation/test_transfer_worker_device.py (CPU, 3 tests). It checks that
    bind_thread_to_device calls current_platform.set_device, ignores NotImplementedError, and that run_on_device
    binds on the worker's own thread before the worker runs.
  • Unchanged and passing: test_mooncake_transfer_batching.py (16), test_mooncake_deferred_kv_release.py (9),
    test_mori_deferred_kv_release.py (11), test_disaggregation_wire.py (79).
  • GPU repro above: run on 306ccf6 with this change applied. The diff applies unchanged to both 306ccf6 and
    current main.

Checklist

  • Format your code according to pre-commit.
  • Add unit tests.
  • Accuracy: no numerics change; this only selects which device the transfer threads use. All KV transfers in the
    repro completed before and after (0 failures).

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ✅ Run #40033598784
Latest PR Test (Extra): ❌ Run #40033598750
Latest PR Test (AMD ROCm 10): ❌ Run #40033598646

…device

Prefill KV-transfer worker threads never selected a device, so their first
device call ran on device 0. In Mooncake's transfer_worker that call is
TransferKVChunk.wait_event.synchronize() (the early cached-prefix send waits on
the in-flight forward), which creates device 0's primary context in the
process: every prefill rank whose GPU is not device 0 opens a second, ~1 GiB
context on another rank's GPU once it starts sending KV. Seen on a DeepSeek-V4.1
DEP2 prefill worker: nvidia-smi listed the DP1 scheduler on both GPUs, with the
second context created at its first PD transfer.

Bind the threads to kv_args.gpu_id through the platform layer:
- common/utils: bind_thread_to_device() (current_platform.set_device; no-op
  where the platform does not implement it) and run_on_device(), a thread
  target that binds and then runs the worker.
- mooncake: the transfer_worker threads start through run_on_device, and the
  transfer thread pools bind each thread via the executor initializer.
- mori: the _transfer_worker threads (same wait_event.synchronize()) start
  through run_on_device.

The worker functions are unchanged, so tests that drive them directly are
unaffected. Adds a CPU unit test for the helpers.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@github-actions

This comment has been minimized.

- Rewrite the bind_thread_to_device docstring to state what it does and
  why, without the bug history.
- Remove test_transfer_worker_device.py: it only mocks the platform on
  CPU and never exercises a real device.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Oct 22, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh nvpohanh changed the title [Fix] Avoid extra GPU contexts with PD [Fix] disaggregation: Avoid extra GPU contexts with PD Oct 22, 2026
@github-actions

This comment has been minimized.

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] @trevor-m, the PR Title check failed, so I renamed this PR from [Fix] Avoid extra GPU contexts with PD to [Fix] disaggregation: Avoid extra GPU contexts with PD to match the required [Type] scope: title format. Feel free to change the type or scope if I picked the wrong one.

@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] The relevant CI failure (https://github.com/sgl-project/sglang/actions/runs/39742586359/job/119914902681) is not caused by this PR. It is a known breakage on main, tracked in #45846. CI for this PR is blocked until that is fixed.

@nvpohanh

Copy link
Copy Markdown
Collaborator

@ShangmingCai could you review this small change? Thanks!

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@nvpohanh

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] All NV pipelines have passed.

@nvpohanh

Copy link
Copy Markdown
Collaborator

@ShangmingCai could you review this? Thanks!

@ShangmingCai ShangmingCai left a comment

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.

LGTM

@ShangmingCai
ShangmingCai merged commit 7fe5b12 into sgl-project:main Oct 27, 2026
250 of 274 checks passed
luke396 pushed a commit to Infrawaves/sglang that referenced this pull request Oct 31, 2026
…5678)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Po-Han Huang <[email protected]>
(cherry picked from commit 7fe5b12)
LinyuanLi0046 added a commit to LinyuanLi0046/sglang that referenced this pull request Nov 12, 2026
Backport the early-send wait from sgl-project#41395 (c683190).
Pass the forward-stream event with its cached-prefix chunk and wait for
it before reading source KV. Recheck the room after the wait to skip
transfers aborted in the meantime. The scheduler can launch the suffix
forward as soon as it enqueues the prefix.

Adapt the worker device binding from sgl-project#45678
(7fe5b12). Bind each transfer worker to its rank's device on its
first event wait, preserving the Ascend worker's CPU affinity. Ascend
uses the existing transfer_to_npu mapping for torch.cuda.Event().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mooncake run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants