[feat] support in-flight weight update (#10071)

Co-authored-by: 赵晨阳 <zhaochen20@outlook.com>
This commit is contained in:
ShawnY112358
2025-11-26 14:03:13 +08:00
committed by GitHub
parent 7130ad3a29
commit 007c3e234c
10 changed files with 401 additions and 34 deletions

View File

@@ -78,6 +78,7 @@ from sglang.srt.managers.io_struct import (
AbortReq,
CloseSessionReqInput,
ConfigureLoggingReq,
ContinueGenerationReqInput,
DestroyWeightsUpdateGroupReqInput,
EmbeddingReqInput,
GenerateReqInput,
@@ -87,6 +88,7 @@ from sglang.srt.managers.io_struct import (
LoadLoRAAdapterReqInput,
OpenSessionReqInput,
ParseFunctionCallReq,
PauseGenerationReqInput,
ProfileReqInput,
ReleaseMemoryOccupationReqInput,
ResumeMemoryOccupationReqInput,
@@ -1087,9 +1089,9 @@ async def separate_reasoning_request(obj: SeparateReasoningReqInput, request: Re
@app.post("/pause_generation")
async def pause_generation(request: Request):
async def pause_generation(obj: PauseGenerationReqInput, request: Request):
"""Pause generation."""
await _global_state.tokenizer_manager.pause_generation()
await _global_state.tokenizer_manager.pause_generation(obj)
return ORJSONResponse(
content={"message": "Generation paused successfully.", "status": "ok"},
status_code=200,
@@ -1097,9 +1099,9 @@ async def pause_generation(request: Request):
@app.post("/continue_generation")
async def continue_generation(request: Request):
async def continue_generation(obj: ContinueGenerationReqInput, request: Request):
"""Continue generation."""
await _global_state.tokenizer_manager.continue_generation()
await _global_state.tokenizer_manager.continue_generation(obj)
return ORJSONResponse(
content={"message": "Generation continued successfully.", "status": "ok"},
status_code=200,

View File

@@ -21,7 +21,7 @@ import uuid
from abc import ABC
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
from sglang.srt.lora.lora_registry import LoRARef
from sglang.srt.managers.schedule_batch import BaseFinishReason
@@ -1064,6 +1064,41 @@ class FlushCacheReqOutput(BaseReq):
success: bool
@dataclass
class PauseGenerationReqInput(BaseReq):
"""
Note that the PauseGenerationRequests is only supported in SGLang Server.
abort: Abort and return all requests currently being processed.
in_place: Pause the scheduler's event_loop from performing inference;
only non-inference requests (e.g., control commands) will be handled.
The requests in the engine will be paused and stay in the event_loop,
then continue generation after continue_generation with the old kv cache.
Note: In 'inplace' mode, flush_cache will fail if there are any requests
in the running_batch.
retract: Pause the scheduler's event loop from performing inference;
only non-inference requests will be handled, and all currently running
requests will be retracted back to the waiting_queue.
Note: The KV cache can be flushed in this mode and will be automatically
recomputed after continue_generation.
"""
mode: Literal["abort", "retract", "in_place"] = "abort"
def __post_init__(self):
allowed = ["abort", "retract", "in_place"]
if self.mode not in allowed:
raise ValueError(
f"Invalid mode: {self.mode!r}. " f"Expected one of {allowed}."
)
@dataclass
class ContinueGenerationReqInput(BaseReq):
pass
@dataclass
class UpdateWeightFromDiskReqInput(BaseReq):
# The model path with the new weights
@@ -1084,6 +1119,8 @@ class UpdateWeightFromDiskReqInput(BaseReq):
recapture_cuda_graph: bool = False
# The trainer step id. Used to know which step's weights are used for sampling.
token_step: int = 0
# Whether to flush the cache after updating weights
flush_cache: bool = True
@dataclass

View File

@@ -1512,8 +1512,17 @@ class ScheduleBatch(ScheduleBatchDisaggregationDecodeMixin):
evict_from_tree_cache(self.tree_cache, num_tokens)
return self._is_available_size_sufficient(num_tokens)
def retract_all(self, server_args: ServerArgs):
retracted_reqs = self.reqs
for idx in range(len(self.reqs)):
self.release_req(idx, len(self.reqs) - idx, server_args)
self.filter_batch(retracted_reqs)
return retracted_reqs
def retract_decode(
self, server_args: ServerArgs
self,
server_args: ServerArgs,
) -> Tuple[List[Req], float, List[Req]]:
"""Retract the decoding requests when there is not enough memory."""
sorted_indices = list(range(len(self.reqs)))

View File

@@ -73,6 +73,7 @@ from sglang.srt.managers.io_struct import (
ClearHiCacheReqInput,
ClearHiCacheReqOutput,
CloseSessionReqInput,
ContinueGenerationReqInput,
DestroyWeightsUpdateGroupReqInput,
ExpertDistributionReq,
ExpertDistributionReqOutput,
@@ -93,6 +94,7 @@ from sglang.srt.managers.io_struct import (
LoadLoRAAdapterReqOutput,
OpenSessionReqInput,
OpenSessionReqOutput,
PauseGenerationReqInput,
ProfileReq,
ReleaseMemoryOccupationReqInput,
ResumeMemoryOccupationReqInput,
@@ -443,6 +445,7 @@ class Scheduler(
if self.device == "cpu":
self.default_stream.synchronize = lambda: None # No-op for CPU
self.forward_sleep_time = None
self._engine_paused = False
# Init chunked prefill
self.chunked_prefill_size = server_args.chunked_prefill_size
@@ -568,6 +571,8 @@ class Scheduler(
(LoadLoRAAdapterReqInput, self.load_lora_adapter),
(UnloadLoRAAdapterReqInput, self.unload_lora_adapter),
(GetLoadReqInput, self.get_load),
(PauseGenerationReqInput, self.pause_generation),
(ContinueGenerationReqInput, self.continue_generation),
]
)
@@ -953,6 +958,9 @@ class Scheduler(
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
if self._engine_paused:
continue
batch = self.get_next_batch_to_run()
self.cur_batch = batch
@@ -985,6 +993,9 @@ class Scheduler(
recv_reqs = self.recv_requests()
self.process_input_requests(recv_reqs)
if self._engine_paused:
continue
batch = self.get_next_batch_to_run()
self.cur_batch = batch
@@ -2154,8 +2165,7 @@ class Scheduler(
def _is_no_request(self):
no_request = (
len(self.waiting_queue) == 0
and self.running_batch.is_empty()
self.running_batch.is_empty()
and (self.last_batch is None or self.last_batch.is_empty())
and (self.cur_batch is None or self.cur_batch.is_empty())
and (not self.enable_overlap or len(self.result_queue) == 0)
@@ -2428,6 +2438,29 @@ class Scheduler(
def _pause_engine(self) -> Tuple[List[Req], int]:
raise NotImplementedError()
def pause_generation(self, recv_req: PauseGenerationReqInput):
self._engine_paused = True
if self.enable_overlap and self.last_batch:
# Process the results of the last batch
tmp_batch, tmp_result = self.result_queue.popleft()
self.process_batch_result(tmp_batch, tmp_result)
self.last_batch = None
self.cur_batch = None
if recv_req.mode == "retract":
self.running_batch.filter_batch()
if len(self.running_batch.reqs) != 0:
retracted_reqs = self.running_batch.retract_all(self.server_args)
for req in retracted_reqs:
self._add_request_to_queue(req)
self.running_batch.batch_is_full = False
self.chunked_req = None
def continue_generation(self, recv_req: ContinueGenerationReqInput):
self._engine_paused = False
def load_lora_adapter(
self, recv_req: LoadLoRAAdapterReqInput
) -> LoadLoRAAdapterReqOutput:

View File

@@ -44,8 +44,9 @@ class SchedulerUpdateWeightsMixin:
"""In-place update of the weights from disk."""
success, message = self.tp_worker.update_weights_from_disk(recv_req)
if success:
flush_cache_success = self.flush_cache()
assert flush_cache_success, "Cache flush failed after updating weights"
if recv_req.flush_cache:
flush_cache_success = self.flush_cache()
assert flush_cache_success, "Cache flush failed after updating weights"
else:
logger.error(message)
return UpdateWeightFromDiskReqOutput(success, message, 0)

View File

@@ -404,6 +404,14 @@ class TokenizerCommunicatorMixin:
if obj.abort_all_requests:
self.abort_request(abort_all=True)
# Immediately update the weights if the engine is in paused state
async with self.is_pause_cond:
if self.is_pause:
result = (await self.update_weights_from_distributed_communicator(obj))[
0
]
return result.success, result.message
# This means that weight sync
# cannot run while requests are in progress.
async with self.model_update_lock.writer_lock:
@@ -457,6 +465,12 @@ class TokenizerCommunicatorMixin:
if obj.abort_all_requests:
self.abort_request(abort_all=True)
# Immediately update the weights if the engine is in paused state
async with self.is_pause_cond:
if self.is_pause:
result = (await self.update_weights_from_tensor_communicator(obj))[0]
return result.success, result.message
# This means that weight sync
# cannot run while requests are in progress.
async with self.model_update_lock.writer_lock:

View File

@@ -55,6 +55,7 @@ from sglang.srt.managers.io_struct import (
BatchTokenizedEmbeddingReqInput,
BatchTokenizedGenerateReqInput,
ConfigureLoggingReq,
ContinueGenerationReqInput,
EmbeddingReqInput,
FreezeGCReq,
GenerateReqInput,
@@ -62,6 +63,7 @@ from sglang.srt.managers.io_struct import (
HealthCheckOutput,
LoadLoRAAdapterReqInput,
OpenSessionReqOutput,
PauseGenerationReqInput,
SessionParams,
TokenizedEmbeddingReqInput,
TokenizedGenerateReqInput,
@@ -1246,21 +1248,25 @@ class TokenizerManager(TokenizerCommunicatorMixin):
self.metrics_collector.labels
)
async def pause_generation(self):
async def pause_generation(self, obj: PauseGenerationReqInput):
async with self.is_pause_cond:
self.is_pause = True
# we are using the model_update_lock to check if there is still on-going requests.
while True:
# TODO: maybe make it async instead of fire-and-forget
self.abort_request(abort_all=True)
is_locked = await self.model_update_lock.is_locked()
if not is_locked:
break
await asyncio.sleep(1.0)
if obj.mode != "abort":
await 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:
# TODO: maybe make it async instead of fire-and-forget
self.abort_request(abort_all=True)
is_locked = await self.model_update_lock.is_locked()
if not is_locked:
break
await asyncio.sleep(1.0)
async def continue_generation(self):
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.is_pause_cond.notify_all()
async def update_weights_from_disk(
@@ -1278,6 +1284,11 @@ class TokenizerManager(TokenizerCommunicatorMixin):
if obj.abort_all_requests:
self.abort_request(abort_all=True)
# Immediately update the weights if the engine is in paused state
async with self.is_pause_cond:
if self.is_pause:
return await self._wait_for_model_update_from_disk(obj)
if True: # Keep this redundant check to simplify some internal code sync
# Hold the lock if it is not async. This means that weight sync
# cannot run while requests are in progress.