[Feature]Support async computation and communication across stages by chunks (#727)
Signed-off-by: amy-why-3459 <wuhaiyan17@huawei.com> Signed-off-by: Rein Yang <ruiruyang2@gmail.com> Co-authored-by: Rein Yang <ruiruyang2@gmail.com> Co-authored-by: CHEN <116010019@link.cuhk.edu.cn> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
29 files changed
+1258
-396
No files matched your search
@@ -5,7 +5,14 @@
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .connectors.base import OmniConnectorBase
|
||||
|
||||
from vllm_omni.entrypoints.stage_utils import OmniStageTaskType
|
||||
|
||||
@@ -170,3 +177,225 @@ def try_recv_via_connector(
|
||||
# but for Stage-0 seed it should be there.
|
||||
# We'll return None to let caller handle error if strictly required.
|
||||
return None, None
|
||||
|
||||
|
||||
def get_chunk(
|
||||
connector: "OmniConnectorBase",
|
||||
scheduler_output: SchedulerOutput,
|
||||
) -> None:
|
||||
"""Retrieve a chunk of pooling output.
|
||||
|
||||
Args:
|
||||
connector: OmniConnectorBase instance
|
||||
scheduler_output: Partial scheduler output dictionary
|
||||
|
||||
Returns:
|
||||
None: This function modifies scheduler_output in place
|
||||
"""
|
||||
stage_id = connector.stage_id
|
||||
if stage_id == 0:
|
||||
return
|
||||
|
||||
target_stage_id = stage_id - 1
|
||||
# Handle new requests
|
||||
for new_req_data in scheduler_output.scheduled_new_reqs:
|
||||
req_id = new_req_data.req_id[0:25]
|
||||
chunk_id = connector.get_requests[req_id]
|
||||
connector_get_key = f"{req_id}_{target_stage_id}_{chunk_id}"
|
||||
payload_data = get_through_connector(connector, target_stage_id, stage_id, req_id, connector_get_key)
|
||||
if payload_data:
|
||||
new_req_data.additional_information = payload_data
|
||||
if payload_data.get("finished"):
|
||||
connector.finished_requests.add(req_id)
|
||||
|
||||
# Handle cached/running requests
|
||||
cached_reqs = scheduler_output.scheduled_cached_reqs
|
||||
if not hasattr(cached_reqs, "additional_information"):
|
||||
cached_reqs.additional_information = {}
|
||||
|
||||
for i, cached_req_id in enumerate(cached_reqs.req_ids):
|
||||
req_id = cached_req_id[0:25]
|
||||
if req_id in connector.finished_requests:
|
||||
continue
|
||||
chunk_id = connector.get_requests[req_id]
|
||||
connector_get_key = f"{req_id}_{target_stage_id}_{chunk_id}"
|
||||
payload_data = get_through_connector(connector, target_stage_id, stage_id, req_id, connector_get_key)
|
||||
if payload_data:
|
||||
cached_reqs.additional_information[cached_req_id] = payload_data
|
||||
if payload_data.get("finished"):
|
||||
connector.finished_requests.add(req_id)
|
||||
|
||||
|
||||
def get_through_connector(connector, target_stage_id, stage_id, req_id, connector_get_key):
|
||||
# Wait for data from previous stage
|
||||
import time
|
||||
|
||||
# TODO: add correct check mechanism for the payload_data
|
||||
max_wait = 300
|
||||
for _ in range(max_wait):
|
||||
result = connector.get(
|
||||
from_stage=str(target_stage_id),
|
||||
to_stage=str(stage_id),
|
||||
get_key=connector_get_key,
|
||||
)
|
||||
payload_data = None
|
||||
if result:
|
||||
payload_data, size = result
|
||||
if payload_data:
|
||||
connector.request_prompt_token_ids[req_id] = payload_data.get("thinker_input_ids", [])
|
||||
connector.get_requests[req_id] += 1
|
||||
logger.debug(f"[Stage-{stage_id}] Received one chunk for request {connector_get_key}")
|
||||
break
|
||||
time.sleep(0.1)
|
||||
return payload_data
|
||||
|
||||
|
||||
def get_chunk_for_generation(
|
||||
connector: "OmniConnectorBase",
|
||||
request: Request,
|
||||
) -> None:
|
||||
"""Retrieve a chunk of pooling output.
|
||||
|
||||
Args:
|
||||
connector: OmniConnectorBase instance
|
||||
request: Request object
|
||||
|
||||
Returns:
|
||||
None: This function modifies request in place
|
||||
"""
|
||||
stage_id = connector.stage_id
|
||||
target_stage_id = stage_id - 1
|
||||
request_id = request.request_id[0:25]
|
||||
|
||||
if request_id in connector.finished_requests:
|
||||
return
|
||||
|
||||
chunk_id = connector.get_requests[request_id]
|
||||
connector_get_key = f"{request_id}_{target_stage_id}_{chunk_id}"
|
||||
payload_data = get_through_connector(connector, target_stage_id, stage_id, request_id, connector_get_key)
|
||||
if not payload_data:
|
||||
return
|
||||
|
||||
if payload_data.get("finished"):
|
||||
connector.finished_requests.add(request_id)
|
||||
request.status = RequestStatus.FINISHED_STOPPED
|
||||
|
||||
# TODO: remove special handling for prompt token ids ?
|
||||
if chunk_id == 0:
|
||||
request.prompt_token_ids = payload_data.get("code_predictor_codes", [])
|
||||
else:
|
||||
request.prompt_token_ids += payload_data.get("code_predictor_codes", [])
|
||||
|
||||
|
||||
def put_chunk(
|
||||
connector: "OmniConnectorBase",
|
||||
pooling_output: dict[str, Any],
|
||||
request: Request,
|
||||
custom_process_input_func: Callable[[dict[str, Any], Request], dict[str, Any] | None] | None = None,
|
||||
) -> None:
|
||||
"""Store a chunk of pooling output.
|
||||
|
||||
Args:
|
||||
connector: OmniConnectorBase instance
|
||||
pooling_output: Partial pooling output dictionary
|
||||
request: Request object
|
||||
custom_process_input_func: Optional custom function to process input
|
||||
|
||||
Returns:
|
||||
None: This function sends data via connector
|
||||
"""
|
||||
stage_id = connector.stage_id
|
||||
next_stage_id = stage_id + 1
|
||||
request_id = request.request_id[0:25]
|
||||
prompt_token_ids = request.prompt_token_ids
|
||||
connector.request_prompt_token_ids[request_id] = prompt_token_ids
|
||||
chunk_id = connector.put_requests[request_id]
|
||||
connector_put_key = f"{request_id}_{stage_id}_{chunk_id}"
|
||||
payload_data = None
|
||||
|
||||
# TODO: add default process_input_func to handle the payload_data ?
|
||||
if custom_process_input_func:
|
||||
try:
|
||||
payload_data = custom_process_input_func(
|
||||
pooling_output=pooling_output,
|
||||
request=request,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to use custom_process_input_func for payload extraction: {e}")
|
||||
|
||||
if not payload_data:
|
||||
logger.warning(f"[Stage-{stage_id}] No payload data to send for request {request_id}")
|
||||
return
|
||||
|
||||
if stage_id == 0 and chunk_id == 0:
|
||||
if connector.request_payload.get(request_id) is None:
|
||||
connector.request_payload[request_id] = payload_data
|
||||
return
|
||||
else:
|
||||
save_payload = connector.request_payload.get(request_id)
|
||||
payload_data["thinker_embeddings"] = torch.cat(
|
||||
(save_payload.get("thinker_embeddings"), payload_data.get("thinker_embeddings")), dim=0
|
||||
)
|
||||
payload_data["thinker_hidden_states"] = torch.cat(
|
||||
(save_payload.get("thinker_hidden_states"), payload_data.get("thinker_hidden_states")), dim=0
|
||||
)
|
||||
logger.info(f"[Stage-{stage_id}] Merged embeddings and hidden states for request {request_id}")
|
||||
|
||||
if stage_id == 1:
|
||||
# TODO: Make parameters configurable and optimize algorithms
|
||||
chunk_size = left_context_size = 25
|
||||
connector.code_prompt_token_ids[request_id].append(payload_data.get("code_predictor_codes", []))
|
||||
length = len(connector.code_prompt_token_ids[request_id])
|
||||
chunk_length = length % chunk_size
|
||||
if chunk_length != 0 and not payload_data.get("finished"):
|
||||
return
|
||||
|
||||
context_length = chunk_length if chunk_length != 0 else chunk_size
|
||||
end_index = min(length, left_context_size + context_length)
|
||||
payload_data["code_predictor_codes"] = (
|
||||
torch.tensor(connector.code_prompt_token_ids[request_id][-end_index:])
|
||||
.transpose(0, 1)
|
||||
.reshape(-1)
|
||||
.tolist()
|
||||
)
|
||||
|
||||
success, size, metadata = connector.put(
|
||||
from_stage=str(stage_id), to_stage=str(next_stage_id), put_key=connector_put_key, data=payload_data
|
||||
)
|
||||
|
||||
if success:
|
||||
connector.put_requests[request_id] += 1
|
||||
logger.info(f"[Stage-{stage_id}] Sent {connector_put_key}")
|
||||
|
||||
|
||||
def compute_talker_prompt_ids_length(prompt_ids: list[int]) -> int:
|
||||
"""Compute the length of the talker prompt ids.
|
||||
|
||||
Args:
|
||||
prompt_ids: The prompt ids tensor.
|
||||
|
||||
Returns:
|
||||
The length of the talker prompt ids.
|
||||
"""
|
||||
im_start_token_id = 151644
|
||||
system_token_id = 8948
|
||||
user_token_id = 872
|
||||
assistant_token_id = 77091
|
||||
im_start_indexes = [i for i in range(len(prompt_ids)) if prompt_ids[i] == im_start_token_id]
|
||||
im_start_indexes.append(len(prompt_ids))
|
||||
sum_user_len = 0
|
||||
assistant_len = 0
|
||||
for i in range(len(im_start_indexes) - 1):
|
||||
s = im_start_indexes[i]
|
||||
e = im_start_indexes[i + 1]
|
||||
role = prompt_ids[s + 1]
|
||||
if role == system_token_id:
|
||||
continue
|
||||
elif role == user_token_id:
|
||||
sum_user_len += e - s
|
||||
elif role == assistant_token_id and i == len(im_start_indexes) - 2:
|
||||
assistant_len += 9 # 3 + 4 + 1 + 1
|
||||
else:
|
||||
pass
|
||||
|
||||
return sum_user_len + assistant_len
|
||||
@@ -13,15 +13,13 @@ class OmniConnectorBase(ABC):
|
||||
"""Base class for all OmniConnectors."""
|
||||
|
||||
@abstractmethod
|
||||
def put(
|
||||
self, from_stage: str, to_stage: str, request_id: str, data: Any
|
||||
) -> tuple[bool, int, dict[str, Any] | None]:
|
||||
def put(self, from_stage: str, to_stage: str, put_key: str, data: Any) -> tuple[bool, int, dict[str, Any] | None]:
|
||||
"""Store Python object, internal serialization handled by connector.
|
||||
|
||||
Args:
|
||||
from_stage: Source stage identifier
|
||||
to_stage: Destination stage identifier
|
||||
request_id: Unique request identifier
|
||||
put_key: Unique request identifier
|
||||
data: Python object to store
|
||||
|
||||
Returns:
|
||||
@@ -31,16 +29,13 @@ class OmniConnectorBase(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get(
|
||||
self, from_stage: str, to_stage: str, request_id: str, metadata: dict[str, Any] | None = None
|
||||
) -> tuple[Any, int] | None:
|
||||
def get(self, from_stage: str, to_stage: str, get_key: str, metadata=None) -> tuple[Any, int] | None:
|
||||
"""Retrieve Python object and payload size (bytes).
|
||||
|
||||
Args:
|
||||
from_stage: Source stage identifier
|
||||
to_stage: Destination stage identifier
|
||||
request_id: Unique request identifier
|
||||
metadata: Optional transport-specific metadata from the put operation
|
||||
get_key: Unique request identifier
|
||||
|
||||
Returns:
|
||||
Tuple of (Python object, serialized byte size) if found, None otherwise
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.entrypoints.stage_utils import shm_read_bytes, shm_write_bytes
|
||||
@@ -19,6 +21,14 @@ class SharedMemoryConnector(OmniConnectorBase):
|
||||
|
||||
def __init__(self, config: dict[str, Any]):
|
||||
self.config = config
|
||||
self.stage_id = config.get("stage_id", -1)
|
||||
self.device = config.get("device", "cuda:0")
|
||||
self.put_requests: dict[str, int] = defaultdict(int)
|
||||
self.get_requests: dict[str, int] = defaultdict(int)
|
||||
self.finished_requests: set[str] = set()
|
||||
self.request_payload = {}
|
||||
self.request_prompt_token_ids: dict[str, list[int]] = defaultdict(list)
|
||||
self.code_prompt_token_ids: dict[str, list[list[int]]] = defaultdict(list)
|
||||
# Default threshold matches legacy behavior (64KB)
|
||||
self.threshold = int(config.get("shm_threshold_bytes", 65536))
|
||||
self._metrics = {
|
||||
@@ -29,9 +39,7 @@ class SharedMemoryConnector(OmniConnectorBase):
|
||||
"inline_writes": 0,
|
||||
}
|
||||
|
||||
def put(
|
||||
self, from_stage: str, to_stage: str, request_id: str, data: Any
|
||||
) -> tuple[bool, int, dict[str, Any] | None]:
|
||||
def put(self, from_stage: str, to_stage: str, put_key: str, data: Any) -> tuple[bool, int, dict[str, Any] | None]:
|
||||
try:
|
||||
# Always serialize first to check size (and for SHM writing)
|
||||
# Note: For extremely large objects in "inline" mode (e.g. Ray),
|
||||
@@ -40,18 +48,19 @@ class SharedMemoryConnector(OmniConnectorBase):
|
||||
payload = self.serialize_obj(data)
|
||||
size = len(payload)
|
||||
|
||||
if size > self.threshold:
|
||||
metadata = {}
|
||||
# if size > self.threshold:
|
||||
if True: # TODO: correct put & get logic
|
||||
# Use Shared Memory
|
||||
shm_name = f"omni_{from_stage}_to_{to_stage}_{request_id}"
|
||||
meta = shm_write_bytes(payload, name=shm_name)
|
||||
meta = shm_write_bytes(payload, name=put_key)
|
||||
# meta contains {'name': ..., 'size': ...}
|
||||
metadata = {"shm": meta, "size": size}
|
||||
metadata[put_key] = {"shm": meta, "size": size}
|
||||
self._metrics["shm_writes"] += 1
|
||||
else:
|
||||
# Inline - pass bytes directly to avoid double serialization of the object
|
||||
# We already serialized it to check size, so we pass the bytes.
|
||||
# The Queue will pickle these bytes (fast), avoiding re-serializing the complex object.
|
||||
metadata = {"inline_bytes": payload, "size": size}
|
||||
metadata[put_key] = {"inline_bytes": payload, "size": size}
|
||||
self._metrics["inline_writes"] += 1
|
||||
|
||||
self._metrics["puts"] += 1
|
||||
@@ -60,83 +69,40 @@ class SharedMemoryConnector(OmniConnectorBase):
|
||||
return True, size, metadata
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"SharedMemoryConnector put failed for req {request_id}: {e}")
|
||||
logger.error(f"SharedMemoryConnector put failed for req {put_key}: {e}")
|
||||
return False, 0, None
|
||||
|
||||
def get(
|
||||
self, from_stage: str, to_stage: str, request_id: str, metadata: dict[str, Any] | None = None
|
||||
) -> tuple[Any, int] | None:
|
||||
# Helper to try reading SHM with a specific name
|
||||
def try_read_shm(name: str):
|
||||
# _shm is imported at module level as: import multiprocessing.shared_memory as _shm
|
||||
# but to be safe inside this closure if not picked up:
|
||||
from multiprocessing import shared_memory as shm_pkg
|
||||
def get(self, from_stage: str, to_stage: str, get_key: str, metadata=None) -> tuple[Any, int] | None:
|
||||
from multiprocessing import shared_memory as shm_pkg
|
||||
|
||||
shm = shm_pkg.SharedMemory(name=name)
|
||||
# Wait for shared memory to be available (with retry logic)
|
||||
max_retries = 30
|
||||
retry_delay = 0.1 # 100ms between retries
|
||||
shm = None
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
# We assume the buffer size matches the data size
|
||||
return shm_read_bytes({"name": name, "size": shm.size})
|
||||
finally:
|
||||
shm.close()
|
||||
shm = shm_pkg.SharedMemory(name=get_key)
|
||||
break # Successfully opened, exit retry loop
|
||||
except FileNotFoundError:
|
||||
if attempt < max_retries - 1:
|
||||
time.sleep(retry_delay)
|
||||
else:
|
||||
# Max retries reached, return None
|
||||
logger.warning(f"Shared memory '{get_key}' not found after {max_retries} retries")
|
||||
return None, 0
|
||||
|
||||
if not metadata:
|
||||
# Try to infer metadata from request_id for KV cache transfer scenarios
|
||||
# where metadata is not passed out-of-band.
|
||||
shm_name = f"omni_{from_stage}_to_{to_stage}_{request_id}"
|
||||
|
||||
# We need the size to read from SHM using stage_utils.shm_read_bytes
|
||||
try:
|
||||
# Use local import to avoid potential scope issues if _shm isn't available
|
||||
from multiprocessing import shared_memory as shm_pkg
|
||||
|
||||
temp_shm = shm_pkg.SharedMemory(name=shm_name)
|
||||
size = temp_shm.size
|
||||
temp_shm.close()
|
||||
|
||||
metadata = {"shm": {"name": shm_name, "size": size}, "is_fallback": True}
|
||||
logger.debug(f"SharedMemoryConnector inferred metadata for {request_id}: {metadata}")
|
||||
except Exception as e:
|
||||
# If file not found or other error, standard path will likely fail too, but we let it try or return None
|
||||
logger.debug(f"SharedMemoryConnector failed to infer metadata for {request_id} (fallback): {e}")
|
||||
# We can't proceed without size if we rely on shm_read_bytes
|
||||
return None
|
||||
if shm is None:
|
||||
return None, 0
|
||||
|
||||
try:
|
||||
obj = None
|
||||
size = 0
|
||||
data_bytes = shm_read_bytes({"name": get_key, "size": shm.size})
|
||||
obj = self.deserialize_obj(data_bytes)
|
||||
return obj, shm.size
|
||||
finally:
|
||||
shm.close()
|
||||
|
||||
if "shm" in metadata:
|
||||
meta = metadata["shm"]
|
||||
# shm_read_bytes handles reading and unlinking
|
||||
data_bytes = shm_read_bytes(meta)
|
||||
obj = self.deserialize_obj(data_bytes)
|
||||
size = metadata.get("size", len(data_bytes))
|
||||
elif "inline_bytes" in metadata:
|
||||
# Deserialize bytes back to object
|
||||
payload = metadata["inline_bytes"]
|
||||
obj = self.deserialize_obj(payload)
|
||||
size = metadata.get("size", len(payload))
|
||||
elif "inline" in metadata:
|
||||
obj = metadata["inline"]
|
||||
size = metadata.get("size", 0)
|
||||
if size == 0:
|
||||
# Fallback if size wasn't recorded
|
||||
try:
|
||||
size = len(self.serialize_obj(obj))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
logger.error(
|
||||
f"Unknown metadata format in SharedMemoryConnector for req {request_id}: {list(metadata.keys())}"
|
||||
)
|
||||
return None
|
||||
|
||||
self._metrics["gets"] += 1
|
||||
return obj, size
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"SharedMemoryConnector get failed for req {request_id}: {e}")
|
||||
return None
|
||||
# TODO: update another read method
|
||||
|
||||
def cleanup(self, request_id: str) -> None:
|
||||
# SHM segments are automatically unlinked during 'get' (shm_read_bytes).
|
||||
|
||||
@@ -91,6 +91,8 @@ def get_connectors_config_for_stage(transfer_config: OmniTransferConfig | None,
|
||||
# (Worker needs to create connectors to receive data)
|
||||
if to_stage == target_stage:
|
||||
stage_connectors_config[f"from_stage_{from_stage}"] = {"spec": {"name": spec.name, "extra": spec.extra}}
|
||||
elif from_stage == target_stage and target_stage == "0":
|
||||
stage_connectors_config[f"to_stage_{to_stage}"] = {"spec": {"name": spec.name, "extra": spec.extra}}
|
||||
|
||||
return stage_connectors_config
|
||||
|
||||
|
||||
Reference in new issue
Block a user