Merge branch 'main' into dev/vllm-align
This commit is contained in:
54 files changed
+1659
-500
No files matched your search
@@ -15,7 +15,7 @@ from collections.abc import Callable, Sequence
|
||||
from contextlib import nullcontext
|
||||
from copy import copy
|
||||
from dataclasses import replace
|
||||
from typing import Any, NamedTuple
|
||||
from typing import Any, NamedTuple, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -87,14 +87,39 @@ def _clone_cuda_tensor_payload(value: Any, sources: list[torch.Tensor]) -> Any:
|
||||
return value.detach().clone()
|
||||
if isinstance(value, dict):
|
||||
return {k: _clone_cuda_tensor_payload(v, sources) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_clone_cuda_tensor_payload(v, sources) for v in value]
|
||||
if isinstance(value, tuple):
|
||||
return tuple(_clone_cuda_tensor_payload(v, sources) for v in value)
|
||||
if isinstance(value, (list, tuple)):
|
||||
if (
|
||||
value
|
||||
and all(
|
||||
isinstance(v, torch.Tensor)
|
||||
and v.is_cuda
|
||||
and v.dtype == value[0].dtype
|
||||
and v.device == value[0].device
|
||||
and v.layout == torch.strided
|
||||
and v.is_contiguous()
|
||||
for v in value
|
||||
)
|
||||
# Keep frame/state packing bounded; large payloads use individual snapshots.
|
||||
and sum(v.numel() * v.element_size() for v in value) <= 1024 * 1024
|
||||
):
|
||||
packed = torch.cat([v.detach().reshape(-1) for v in value])
|
||||
sources.append(packed)
|
||||
return _PackedTensorPayload(packed, [v.shape for v in value], isinstance(value, tuple))
|
||||
items = [_clone_cuda_tensor_payload(v, sources) for v in value]
|
||||
return tuple(items) if isinstance(value, tuple) else items
|
||||
return value
|
||||
|
||||
|
||||
def _copy_tensor_payload_to_cpu(value: Any, pin_memory: bool) -> Any:
|
||||
if isinstance(value, _PackedTensorPayload):
|
||||
flat = _copy_tensor_payload_to_cpu(value.tensor, pin_memory)
|
||||
items = []
|
||||
offset = 0
|
||||
for shape in value.shapes:
|
||||
count = shape.numel()
|
||||
items.append(flat[offset : offset + count].view(shape))
|
||||
offset += count
|
||||
return tuple(items) if value.is_tuple else items
|
||||
if isinstance(value, torch.Tensor):
|
||||
if value.device.type != "cuda":
|
||||
return value
|
||||
@@ -110,6 +135,12 @@ def _copy_tensor_payload_to_cpu(value: Any, pin_memory: bool) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
class _PackedTensorPayload(NamedTuple):
|
||||
tensor: torch.Tensor
|
||||
shapes: list[torch.Size]
|
||||
is_tuple: bool
|
||||
|
||||
|
||||
class _AsyncCPUPayloadSnapshot:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -181,7 +212,7 @@ class OmniAsyncGPUModelRunnerOutput(AsyncGPUModelRunnerOutput):
|
||||
if kwargs:
|
||||
raise TypeError(f"Unexpected OmniAsyncGPUModelRunnerOutput kwargs: {sorted(kwargs)}")
|
||||
|
||||
self._model_runner_output = None
|
||||
self._model_runner_output: OmniModelRunnerOutput | None = None
|
||||
self._invalid_req_indices = invalid_req_indices
|
||||
|
||||
self.async_copy_ready_event = torch.Event()
|
||||
@@ -211,7 +242,7 @@ class OmniAsyncGPUModelRunnerOutput(AsyncGPUModelRunnerOutput):
|
||||
self._num_nans_cpu = self._num_nans.to("cpu", non_blocking=True) if self._num_nans is not None else None
|
||||
self.async_copy_ready_event.record()
|
||||
|
||||
self._model_runner_output_builder = model_runner_output_builder
|
||||
self._model_runner_output_builder: Callable[[], OmniModelRunnerOutput] | None = model_runner_output_builder
|
||||
self._background_exception: BaseException | None = None
|
||||
self._background_thread: threading.Thread | None = None
|
||||
self._cuda_device = cuda_device
|
||||
@@ -226,6 +257,7 @@ class OmniAsyncGPUModelRunnerOutput(AsyncGPUModelRunnerOutput):
|
||||
if self._model_runner_output is not None:
|
||||
return
|
||||
with record_function_or_nullcontext("omni_async_output:get_output/build_model_runner_output"):
|
||||
assert self._model_runner_output_builder is not None
|
||||
self._model_runner_output = self._model_runner_output_builder()
|
||||
self._model_runner_output_builder = None
|
||||
|
||||
@@ -321,6 +353,9 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
outputs per request while keeping Async output semantics.
|
||||
"""
|
||||
|
||||
execute_model_state: ExecuteModelState | None
|
||||
kv_extracted_req_ids: list[str] | None
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.input_ids = self._make_buffer(self.max_num_tokens, dtype=torch.int32)
|
||||
@@ -436,6 +471,8 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
if not isinstance(info, dict):
|
||||
return None
|
||||
val = info.get("omni_final_stage_id")
|
||||
if val is None:
|
||||
return None
|
||||
try:
|
||||
return int(val)
|
||||
except (TypeError, ValueError):
|
||||
@@ -1485,7 +1522,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
)
|
||||
selected_indices.append(idx)
|
||||
selected_req_ids.append(req_id)
|
||||
selected_req_infos.append(req_info)
|
||||
selected_req_infos.append(cast(dict[str, Any], req_info))
|
||||
|
||||
if not selected_indices:
|
||||
return multimodal_outputs
|
||||
@@ -1552,7 +1589,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
|
||||
def _build_multimodal_outputs(
|
||||
self,
|
||||
per_req_payloads: list[dict[str, object] | None] | None,
|
||||
per_req_payloads: Sequence[dict[str, object] | None] | None,
|
||||
) -> list[dict[str, torch.Tensor] | None] | None:
|
||||
"""Build per-request multimodal output payloads (dedicated channel).
|
||||
|
||||
@@ -1648,8 +1685,8 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
|
||||
def _build_omni_step_outputs(
|
||||
self,
|
||||
pooler_inter: list[dict[str, object]],
|
||||
pooler_client: list[dict[str, object]],
|
||||
pooler_inter: Sequence[dict[str, object] | None] | None,
|
||||
pooler_client: Sequence[dict[str, object] | None] | None,
|
||||
*,
|
||||
defer_full_payload_d2h: bool,
|
||||
) -> tuple[
|
||||
@@ -1935,6 +1972,8 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
|
||||
)
|
||||
pooler_output.append(flatten_payload(payload))
|
||||
|
||||
pooler_inter: Sequence[dict[str, object] | None] | None
|
||||
pooler_client: Sequence[dict[str, object] | None] | None
|
||||
pooler_output = pooler_output or []
|
||||
if self._async_chunk and stage_sends_async_output(self.model_config):
|
||||
pooler_inter, pooler_client = partition_payload_list(pooler_output)
|
||||
|
||||
@@ -78,6 +78,8 @@ def _filter_mrope_kwargs_for_model(model: object, kwargs: dict[str, Any]) -> dic
|
||||
|
||||
|
||||
class OmniGPUModelRunner(GPUModelRunner):
|
||||
intermediate_tensors: IntermediateTensors | None
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.model_intermediate_buffer: dict[str, dict[str, Any]] = {}
|
||||
@@ -842,7 +844,9 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
return None
|
||||
|
||||
@torch.inference_mode()
|
||||
def extract_multimodal_outputs(self, hidden_states: torch.Tensor | list[torch.Tensor] | OmniOutput) -> dict:
|
||||
def extract_multimodal_outputs(
|
||||
self, hidden_states: torch.Tensor | list[torch.Tensor] | OmniOutput
|
||||
) -> tuple[Any, Any]:
|
||||
if (
|
||||
hasattr(self.model, "have_multimodal_outputs")
|
||||
and self.model.have_multimodal_outputs
|
||||
@@ -1407,14 +1411,14 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
def _process_additional_information_updates(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
multimodal_outputs: object,
|
||||
multimodal_outputs: Any,
|
||||
num_scheduled_tokens_np: np.ndarray,
|
||||
scheduler_output: "SchedulerOutput",
|
||||
combined_hidden_states: dict[str, torch.Tensor] | None = None,
|
||||
combined_multimodal_outputs: dict[str, object] | None = None,
|
||||
combined_multimodal_outputs: dict[str, Any] | None = None,
|
||||
req_ids_filter: set[str] | None = None,
|
||||
req_ids: list[str] | None = None,
|
||||
query_start_loc_cpu: object | None = None,
|
||||
query_start_loc_cpu: Any = None,
|
||||
) -> None:
|
||||
"""Process model-provided per-request updates and merge into model_intermediate_buffer."""
|
||||
req_ids = req_ids if req_ids is not None else self.input_batch.req_ids
|
||||
@@ -1476,9 +1480,9 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
def _collect_additional_information_for_prefill(
|
||||
self,
|
||||
num_scheduled_tokens_np: np.ndarray,
|
||||
) -> dict[str, dict]:
|
||||
) -> None:
|
||||
"""Overlay per-request prompt_embeds for the prefill portion and collect
|
||||
additional_information slices for this step. Returns a map req_id -> dict."""
|
||||
additional_information slices for this step."""
|
||||
for req_index, req_id in enumerate(self.input_batch.req_ids):
|
||||
req_state = self.requests[req_id]
|
||||
pe_cpu = getattr(req_state, "prompt_embeds_cpu", None)
|
||||
@@ -1707,9 +1711,9 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
|
||||
# Overlay custom prompt_embeds per request for the prompt portion;
|
||||
# collect additional_information (tensor/list) for prefill portion only
|
||||
decode_req_ids = []
|
||||
decode_start_offsets = []
|
||||
decode_batch_items = []
|
||||
decode_req_ids: list[str] = []
|
||||
decode_start_offsets: list[int] = []
|
||||
decode_batch_items: list[tuple[str, int, dict[str, Any]]] = []
|
||||
batch_decode_preprocess = getattr(self.model, "preprocess_decode_batch", None)
|
||||
|
||||
def flush_decode_batch() -> None:
|
||||
@@ -1717,6 +1721,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
if not decode_batch_items:
|
||||
return
|
||||
|
||||
assert callable(batch_decode_preprocess)
|
||||
req_ids_b = [item[0] for item in decode_batch_items]
|
||||
start_offsets_b = [item[1] for item in decode_batch_items]
|
||||
req_infos_b = [item[2] for item in decode_batch_items]
|
||||
@@ -1761,7 +1766,7 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
|
||||
# mimo-audio check
|
||||
req_state = self.requests.get(req_id)
|
||||
req_infos = self._maybe_attach_mimo_audio_req_infos(req_state, req_infos, req_id)
|
||||
req_infos = cast(dict[str, Any], self._maybe_attach_mimo_audio_req_infos(req_state, req_infos, req_id))
|
||||
|
||||
start_offset = int(self.query_start_loc.cpu[req_index])
|
||||
sched_tokens = int(num_scheduled_tokens_np[req_index])
|
||||
@@ -1968,11 +1973,29 @@ class OmniGPUModelRunner(GPUModelRunner):
|
||||
if start_offsets is None:
|
||||
id_to_index = self.input_batch.req_id_to_index
|
||||
start_offsets = [int(self.query_start_loc.cpu[id_to_index[req_id]]) for req_id in decode_req_ids]
|
||||
for idx, (req_id, start_offset) in enumerate(zip(decode_req_ids, start_offsets, strict=True)):
|
||||
inputs_embeds[start_offset : start_offset + 1] = req_embeds[idx : idx + 1]
|
||||
if code_predictor_codes is not None:
|
||||
update_dict = {out_key[0]: {out_key[1]: code_predictor_codes[idx : idx + 1]}}
|
||||
self._update_intermediate_buffer(req_id, update_dict)
|
||||
if start_offsets == list(range(decode_batch_size)):
|
||||
inputs_embeds[:decode_batch_size].copy_(req_embeds[:decode_batch_size])
|
||||
else:
|
||||
# A device tensor constructor waits for the preceding MTP graph.
|
||||
# Enqueue the small host index transfer without synchronizing it.
|
||||
offsets = torch.tensor(start_offsets, device="cpu", dtype=torch.long).to(
|
||||
inputs_embeds.device, non_blocking=True
|
||||
)
|
||||
inputs_embeds.index_copy_(0, offsets, req_embeds[:decode_batch_size])
|
||||
if code_predictor_codes is not None:
|
||||
if out_key in getattr(self.model, "gpu_resident_buffer_keys", set()):
|
||||
# One owned batch snapshot protects all rows from graph reuse.
|
||||
owned_codes = code_predictor_codes[:decode_batch_size].detach().clone()
|
||||
for req_id, row in zip(decode_req_ids, owned_codes.split(1), strict=True):
|
||||
req_state = self.requests.get(req_id)
|
||||
if req_state is not None:
|
||||
existing = self.model_intermediate_buffer.setdefault(req_id, {})
|
||||
existing.setdefault(out_key[0], {})[out_key[1]] = row
|
||||
req_state.additional_information_cpu = existing
|
||||
else:
|
||||
for idx, req_id in enumerate(decode_req_ids):
|
||||
update_dict = {out_key[0]: {out_key[1]: code_predictor_codes[idx : idx + 1]}}
|
||||
self._update_intermediate_buffer(req_id, update_dict)
|
||||
|
||||
def _model_forward(
|
||||
self,
|
||||
|
||||
Reference in new issue
Block a user