Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/random_async/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Random fully-async example

Minimal sibling of `examples/fully_async/`. Exercises the entire async
rollout ↔ trainer loop **without any real dataset, real reward model, or
meaningful generation** — useful as an agent infrastructure stress test
for bigger agentic workloads.

Currently uses a few patches to fix some issues in SGLang.

## Quick start

```bash
# one-time: apply the SGLang patches in your environment
./patches/apply_patches.sh

# default (Qwen3.5-35B-A3B), in_place pause + broadcast weight transfer
python run_random_async_3node.py

# retract pause + p2p weight transfer
python run_random_async_3node.py \
--pause-generation-mode retract \
--update-weight-transfer-mode p2p

# swap in a different model
python run_random_async_3node.py \
--model-name Qwen3.5-35B-A3B --megatron-model-type qwen3.5-35B-A3B
```

## Notes

- `--disable-rollout-global-dataset` is on, so no `--prompt-data` file is
required. The rollout function ignores the data buffer and constructs
`Sample` objects from scratch.
- The rollout uses Qwen3.5-35B's vocab size (151643) for the random
`input_ids`; any model with vocab ≥ that works without changes.
- `ignore_eos=True` in the sampling params means SGLang generates until
it hits `max_new_tokens` (drawn from `MAX_TOKENS_RANGE`). `Sample.status`
is set to `COMPLETED`.
14 changes: 14 additions & 0 deletions examples/random_async/patches/00_tbo_forward_delegate.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
diff --git a/python/sglang/srt/layers/attention/tbo_backend.py b/python/sglang/srt/layers/attention/tbo_backend.py
index 494d82d80..2ae120686 100644
--- a/python/sglang/srt/layers/attention/tbo_backend.py
+++ b/python/sglang/srt/layers/attention/tbo_backend.py
@@ -179,6 +179,9 @@ class TboAttnBackend(AttentionBackend):
assert ans == child.get_cuda_graph_seq_len_fill_value()
return ans

+ def forward(self, *args, **kwargs):
+ return self.primary.forward(*args, **kwargs)
+
def forward_extend(self, *args, **kwargs):
return self.primary.forward_extend(*args, **kwargs)

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
diff --git a/python/sglang/srt/managers/tokenizer_manager.py b/python/sglang/srt/managers/tokenizer_manager.py
index 08c483f2b..f42bbd6b7 100644
--- a/python/sglang/srt/managers/tokenizer_manager.py
+++ b/python/sglang/srt/managers/tokenizer_manager.py
@@ -1470,7 +1470,7 @@ class TokenizerManager(TokenizerCommunicatorMixin, TokenizerManagerMultiItemMixi
async with self.is_pause_cond:
self.is_pause = True
if obj.mode != "abort":
- await self.send_to_scheduler.send_pyobj(obj)
+ self.send_to_scheduler.send_pyobj(obj)
else:
# we are using the model_update_lock to check if there is still on-going requests.
while True:
@@ -1484,7 +1484,7 @@ class TokenizerManager(TokenizerCommunicatorMixin, TokenizerManagerMultiItemMixi
async def continue_generation(self, obj: ContinueGenerationReqInput):
async with self.is_pause_cond:
self.is_pause = False
- await self.send_to_scheduler.send_pyobj(obj)
+ self.send_to_scheduler.send_pyobj(obj)
self.is_pause_cond.notify_all()

async def update_weights_from_disk(
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
--- a/python/sglang/srt/mem_cache/memory_pool_host.py
+++ b/python/sglang/srt/mem_cache/memory_pool_host.py
@@ -1368,21 +1368,26 @@
def _copy_tensor(
src: torch.Tensor,
dst: torch.Tensor,
src_indices: torch.Tensor,
dst_indices: torch.Tensor,
io_backend: str,
) -> None:
if src_indices.numel() == 0:
return
if io_backend == "kernel":
+ kernel_device = src.device if src.is_cuda else dst.device
+ if not src_indices.is_cuda:
+ src_indices = src_indices.to(kernel_device, non_blocking=True)
+ if not dst_indices.is_cuda:
+ dst_indices = dst_indices.to(kernel_device, non_blocking=True)
# TODO: Rename the interface for clarity.
# Here, transfer_kv_per_layer_mla is reused to transfer the Mamba state.
# This has nothing to do with MLA; it's only reused because this interface happens to transfer a single Pool.
transfer_kv_per_layer_mla(
src=src,
dst=dst,
src_indices=src_indices,
dst_indices=dst_indices,
item_size=MambaPoolHost._item_size_per_index(src),
)
elif io_backend == "direct":
@@ -1408,14 +1415,19 @@
) -> None:
if src_indices.numel() == 0:
return
if io_backend == "kernel":
+ kernel_device = src.device if src.is_cuda else dst.device
+ if not src_indices.is_cuda:
+ src_indices = src_indices.to(kernel_device, non_blocking=True)
+ if not dst_indices.is_cuda:
+ dst_indices = dst_indices.to(kernel_device, non_blocking=True)
item_size = MambaPoolHost._item_size_per_index(dst)
transfer_kv_per_layer_mla_pf_lf(
src=src,
dst=dst,
src_indices=src_indices,
dst_indices=dst_indices,
layer_id=layer_id,
item_size=item_size,
src_layout_dim=item_size * num_layers,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
diff --git a/python/sglang/srt/managers/cache_controller.py b/python/sglang/srt/managers/cache_controller.py
index e4f8d0b..63513d5 100644
--- a/python/sglang/srt/managers/cache_controller.py
+++ b/python/sglang/srt/managers/cache_controller.py
@@ -677,6 +677,17 @@ class HiCacheController:
host_indices, device_indices = self.move_indices(op)
self.write_queue.clear()

+ # NOTE: Tag the index tensors on write_stream BEFORE enqueuing the
+ # transfer kernel below. record_stream() makes the caching allocator
+ # aware of write_stream's use, so the underlying storage cannot be
+ # reused by another stream's allocation while the kernel is still
+ # pending. Doing this after the transfer call is too late: the kernel
+ # referencing these indices has already been issued.
+ if host_indices.is_cuda:
+ host_indices.record_stream(self.write_stream)
+ if device_indices.is_cuda:
+ device_indices.record_stream(self.write_stream)
+
start_event = device_module.Event()
finish_event = device_module.Event()

@@ -687,13 +698,6 @@ class HiCacheController:
self.mem_pool_device, host_indices, device_indices, self.io_backend
)
finish_event.record()
- # NOTE: We must save the host indices and device indices here,
- # this is because we need to guarantee that these tensors are
- # still alive when the write stream is executing.
- if host_indices.is_cuda:
- host_indices.record_stream(self.write_stream)
- if device_indices.is_cuda:
- device_indices.record_stream(self.write_stream)

self.ack_write_queue.append(HiCacheAck(start_event, finish_event, op.node_ids))

@@ -748,6 +752,15 @@ class HiCacheController:
producer_event = self.layer_done_counter.events[producer_id]
producer_event.start_event.record()

+ # See the equivalent comment in start_writing(): tag the index
+ # tensors on load_stream BEFORE the per-layer kernels are enqueued
+ # so the caching allocator cannot recycle the underlying storage
+ # out from under an in-flight load.
+ if host_indices.is_cuda:
+ host_indices.record_stream(self.load_stream)
+ if device_indices.is_cuda:
+ device_indices.record_stream(self.load_stream)
+
with device_module.stream(self.load_stream):
producer_event.start_event.wait(self.load_stream)
for i in range(self.layer_num):
@@ -759,13 +772,6 @@ class HiCacheController:
self.io_backend,
)
producer_event.complete(i)
- # NOTE: We must save the host indices and device indices here,
- # this is because we need to guarantee that these tensors are
- # still alive when the load stream is executing.
- if host_indices.is_cuda:
- host_indices.record_stream(self.load_stream)
- if device_indices.is_cuda:
- device_indices.record_stream(self.load_stream)

self.ack_load_queue.append(
HiCacheAck(
diff --git a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py
index 7d6abda..72abf42 100644
--- a/python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py
+++ b/python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py
@@ -248,12 +248,42 @@ class HybridCacheController(BaseHiCacheController):
self.start_writing()
return host_indices

+ @staticmethod
+ def _record_transfer_indices_on_stream(
+ host_indices: torch.Tensor,
+ device_indices: torch.Tensor,
+ pool_transfers: Optional[list[PoolTransfer]],
+ stream,
+ ) -> None:
+ """Tag every index tensor used by an in-flight transfer on ``stream``
+ so the caching allocator cannot recycle the underlying storage before
+ the kernels reading them complete.
+
+ Covers both the merged kv host/device indices and the per-pool
+ ``host_indices``/``device_indices`` carried by ``op.pool_transfers``
+ (e.g. the Mamba HiCache sidecar pool).
+ """
+ for tensor in (host_indices, device_indices):
+ if tensor is not None and tensor.is_cuda:
+ tensor.record_stream(stream)
+ for transfer in pool_transfers or []:
+ for tensor in (transfer.host_indices, transfer.device_indices):
+ if tensor is not None and tensor.is_cuda:
+ tensor.record_stream(stream)
+
def start_writing(self) -> None:
if not self.write_queue:
return
op = CacheOperation.merge_ops(self.write_queue)
host_indices, device_indices = self.move_indices(op)
self.write_queue.clear()
+ # Tag every index tensor on write_stream BEFORE issuing the backup
+ # kernel below; otherwise the caching allocator may hand the bytes
+ # of a pool_transfer device_indices buffer to another stream while
+ # the backup kernel is still reading from it.
+ self._record_transfer_indices_on_stream(
+ host_indices, device_indices, op.pool_transfers, self.write_stream
+ )
start_event = device_module.Event()
finish_event = device_module.Event()
start_event.record()
@@ -267,10 +297,6 @@ class HybridCacheController(BaseHiCacheController):
pool_transfers=op.pool_transfers,
)
finish_event.record()
- if host_indices.is_cuda:
- host_indices.record_stream(self.write_stream)
- if device_indices.is_cuda:
- device_indices.record_stream(self.write_stream)
self.ack_write_queue.append(HiCacheAck(start_event, finish_event, op.node_ids))

def load(
@@ -316,6 +342,13 @@ class HybridCacheController(BaseHiCacheController):
self.load_queue.clear()
producer_event = self.layer_done_counter.events[producer_id]
producer_event.start_event.record()
+ # Same rationale as start_writing(): record stream ownership BEFORE
+ # the load kernels are enqueued, otherwise the Mamba HiCache load
+ # path can read indices whose backing storage was already reused
+ # for an unrelated allocation on the default stream.
+ self._record_transfer_indices_on_stream(
+ host_indices, device_indices, op.pool_transfers, self.load_stream
+ )
with device_module.stream(self.load_stream):
producer_event.start_event.wait(self.load_stream)
for i in range(self.layer_num):
@@ -328,10 +361,6 @@ class HybridCacheController(BaseHiCacheController):
pool_transfers=op.pool_transfers,
)
producer_event.complete(i)
- if host_indices.is_cuda:
- host_indices.record_stream(self.load_stream)
- if device_indices.is_cuda:
- device_indices.record_stream(self.load_stream)
self.ack_load_queue.append(
HiCacheAck(
producer_event.start_event,
58 changes: 58 additions & 0 deletions examples/random_async/patches/14_minimal_pd_pause_gate.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
diff --git a/python/sglang/srt/disaggregation/decode.py b/python/sglang/srt/disaggregation/decode.py
--- a/python/sglang/srt/disaggregation/decode.py
+++ b/python/sglang/srt/disaggregation/decode.py
@@ -1158,6 +1158,12 @@ class SchedulerDisaggregationDecodeMixin:
# Receive requests
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
+ if self._engine_paused:
+ if not getattr(self, "_harmonic_logged_minimal_pd_pause_gate_decode", False):
+ print("HARMONIC_MINIMAL_PD_PAUSE_GATE decode", flush=True)
+ self._harmonic_logged_minimal_pd_pause_gate_decode = True
+ continue
+
# polling and allocating kv cache
self.process_decode_queue()

@@ -1185,6 +1191,12 @@ class SchedulerDisaggregationDecodeMixin:
# Receive requests
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
+ if self._engine_paused:
+ if not getattr(self, "_harmonic_logged_minimal_pd_pause_gate_decode", False):
+ print("HARMONIC_MINIMAL_PD_PAUSE_GATE decode", flush=True)
+ self._harmonic_logged_minimal_pd_pause_gate_decode = True
+ continue
+
# polling and allocating kv cache
self.process_decode_queue()

diff --git a/python/sglang/srt/disaggregation/prefill.py b/python/sglang/srt/disaggregation/prefill.py
--- a/python/sglang/srt/disaggregation/prefill.py
+++ b/python/sglang/srt/disaggregation/prefill.py
@@ -397,6 +397,12 @@ def event_loop_normal_disagg_prefill(self: Scheduler) -> None:
# Receive requests
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
+ if self._engine_paused:
+ if not getattr(self, "_harmonic_logged_minimal_pd_pause_gate_prefill", False):
+ print("HARMONIC_MINIMAL_PD_PAUSE_GATE prefill", flush=True)
+ self._harmonic_logged_minimal_pd_pause_gate_prefill = True
+ continue
+
self.waiting_queue.extend(
self.disagg_prefill_bootstrap_queue.pop_bootstrapped()
)
@@ -428,6 +434,12 @@ def event_loop_overlap_disagg_prefill(self: Scheduler) -> None:
# Receive requests
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
+ if self._engine_paused:
+ if not getattr(self, "_harmonic_logged_minimal_pd_pause_gate_prefill", False):
+ print("HARMONIC_MINIMAL_PD_PAUSE_GATE prefill", flush=True)
+ self._harmonic_logged_minimal_pd_pause_gate_prefill = True
+ continue
+
self.waiting_queue.extend(
self.disagg_prefill_bootstrap_queue.pop_bootstrapped()
)
30 changes: 30 additions & 0 deletions examples/random_async/patches/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Temporary SGLang patches

These patches are required to run the `random_async` example with
disaggregated SGLang. They are temporary workarounds.

| Patch | Targets | Why |
|---|---|---|
| `00_tbo_forward_delegate.patch` | `layers/attention/tbo_backend.py` | TboAttnBackend is missing a generic `forward()` method; delegate to `self.primary.forward(...)`. |
| `01_pause_generation_send_pyobj_sync.patch` | `managers/tokenizer_manager.py` | Make pause-generation sends synchronous so the engine reaches a quiesced state before weight transfer. |
| `04_mamba_hicache_kernel_indices_cuda.patch` | `mem_cache/memory_pool_host.py` | Move Mamba state indices to CUDA before kernel execution. |
| `13_hicache_load_record_stream_early.patch` | `managers/cache_controller.py` | Record index tensor stream associations early so the allocator doesn't recycle them mid-load. |
| `14_minimal_pd_pause_gate.patch` | `disaggregation/decode.py` | Gate prefill/decode scheduling during pause so weight updates don't race in-flight requests. |

## Apply

```bash
./apply_patches.sh
```

Auto-detects the installed SGLang location via
`python -c 'import sglang; ...'` and applies each `.patch` with
`patch -p2`. Fails loudly on any error — re-running on an already-patched
tree will fail. Override the target with
`SGLANG_PARENT=/path/to/sitepackages`.

## Revert

```bash
for p in *.patch; do patch -p2 -R -d "${SGLANG_PARENT}" < "$p"; done
```
17 changes: 17 additions & 0 deletions examples/random_async/patches/apply_patches.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash
# Apply the SGLang patches required to run the random_async example on
# 1P1D4G disaggregation. NOT idempotent — fails if any patch does
# not apply cleanly. Set SGLANG_PARENT to override the auto-detected
# sglang location.
set -euo pipefail

SGLANG_PARENT="${SGLANG_PARENT:-$(python3 -c 'import os, sglang; print(os.path.dirname(os.path.dirname(sglang.__file__)))')}"
PATCH_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"

echo "Applying SGLang patches under ${SGLANG_PARENT}"
for patch in "${PATCH_DIR}"/*.patch; do
name=$(basename "$patch")
echo " [apply] $name"
patch -p2 -d "${SGLANG_PARENT}" < "$patch"
done
echo "All patches applied successfully."
Loading