Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions docs/source/features/disagg-serving.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,12 @@ curl http://localhost:8000/v1/completions \
}' -w "\n"
```

#### Multimodal context-to-generation handoff

Use `context_first` for requests that need the context worker's mRoPE state or multimodal cache identity. The router forwards the expanded prompt, the position IDs and delta for mRoPE models, and the item hashes and spans used for KV reuse. With `internal_request_auth_key` configured, the router signs the handoff and the generation worker verifies it. Upgrade the router and generation workers together before enabling the new context producer.

LLM API callers can pass the context output's `disaggregated_params` with the expanded token IDs to generation. Set `request_type="generation_only"`. When calling `LLM.preprocess()` separately, supply the same parameters there. A text-only context can report empty item spans, so a literal placeholder in text keeps its ordinary token interpretation. A token-only request from an older context worker can lack this distinction. Under `generation_first`, the generation worker gets no context state and processes the request's own media, so a request without media is served as text.

#### Responses API

The disaggregated server also serves `/v1/responses`, with both `context_first` and `generation_first` scheduling, and `/v1/models`, which it answers from a context worker. A streamed response carries the generation worker's events unchanged. Unlike a single `trtllm-serve` instance, the disaggregated server keeps no response history:
Expand Down
3 changes: 3 additions & 0 deletions tensorrt_llm/_torch/models/modeling_exaone4_5.py
Comment thread
yechank-nvidia marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ def __init__(


class Exaone4_5InputProcessor(Qwen2VLInputProcessorBase):
# Plain RoPE: no mRoPE state (see get_mrope_config below).
uses_mrope = False

def __init__(
self,
model_path: str,
Expand Down
13 changes: 9 additions & 4 deletions tensorrt_llm/_torch/models/modeling_mistral.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,14 +847,18 @@ def dtype(self) -> torch.dtype:
def get_vocab_size(self) -> int:
return self.config.get_text_config().vocab_size

def get_mm_token_ids(self) -> torch.Tensor:
def get_mm_token_ids(self) -> Optional[torch.Tensor]:
if not self._has_vision_encoder():
return None
return torch.tensor([
self.processor.image_token_id,
self.processor.image_break_token_id,
self.processor.image_end_token_id,
])

def get_mm_special_token_ids(self) -> torch.Tensor:
def get_mm_special_token_ids(self) -> Optional[torch.Tensor]:
if not self._has_vision_encoder():
return None
return torch.tensor([
self.processor.image_break_token_id,
self.processor.image_end_token_id,
Expand Down Expand Up @@ -906,8 +910,9 @@ def call_with_token_ids(self, inputs, sampling_params):
images = self.processor.image_list(
inputs.get("multi_modal_data", {}).get("image"))
if not images:
if self._has_vision_encoder() and not set(
self.get_mm_token_ids().tolist()).isdisjoint(token_ids):
mm_token_ids = self.get_mm_token_ids()
if mm_token_ids is not None and not set(
mm_token_ids.tolist()).isdisjoint(token_ids):
raise ValueError("Image tokens require image data")
return token_ids, None
processed = self.processor(text="", images=images)
Expand Down
40 changes: 26 additions & 14 deletions tensorrt_llm/_torch/models/modeling_qwen2vl.py
Comment thread
yechank-nvidia marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
from tensorrt_llm.functional import PositionEmbeddingType
from tensorrt_llm.inputs.multimodal import (
MULTIMODAL_ENCODER_ITEM_METADATA_KEY, MultimodalItemMetadata,
MultimodalItemPartition, MultimodalParams, split_multimodal_embedding_items)
MultimodalItemPartition, MultimodalParams, last_mrope_decode_position,
split_multimodal_embedding_items)

from ..._utils import async_tensor_h2d, nvtx_range
from ...inputs import (BaseMultimodalDummyInputsBuilder,
Expand Down Expand Up @@ -217,6 +218,7 @@ class Qwen2VLInputProcessorBase(BaseMultimodalInputProcessor,
BaseMultimodalDummyInputsBuilder):

supports_tokenization_cache = True
uses_mrope = True

def export_decode_state(
self, multimodal_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
Expand Down Expand Up @@ -274,6 +276,24 @@ def restore_decode_state(
array = np.frombuffer(raw, dtype="<i8").astype(
np.int64).reshape(expected_shape)
arrays[name] = array
self.check_mrope_positions(arrays["mrope_position_ids"],
int(arrays["mrope_position_deltas"][0, 0]),
prompt_length, max_length)
arrays["mrope_position_deltas"] = arrays[
"mrope_position_deltas"].astype(np.int32)
return {
"mrope_config": {
name: torch.from_numpy(array)
for name, array in arrays.items()
}
}

def check_mrope_positions(self,
positions: np.ndarray,
delta: int,
prompt_length: int,
max_length: Optional[int] = None) -> None:
"""Check prefill positions and the decode range shared by worker configurations."""
text_config = getattr(self.config, "text_config", self.config)
max_positions = getattr(text_config, "max_position_embeddings", None)
if type(max_positions) is not int or not 0 < max_positions <= 2**31:
Expand All @@ -282,24 +302,16 @@ def restore_decode_state(
max_length = max_positions
if prompt_length <= 0 or max_length < prompt_length:
raise ValueError("invalid Qwen mRoPE prompt length")
positions = arrays["mrope_position_ids"]
if np.any(positions < 0) or np.any(positions >= max_positions):
raise ValueError("Qwen mRoPE positions exceed model bounds")
delta = int(arrays["mrope_position_deltas"][0, 0])
if delta != int(positions.max()) + 1 - prompt_length:
raise ValueError("inconsistent Qwen mRoPE position delta")
# Include every possible decode position before handing state to the GPU.
last_position = max_length - 1 + delta
if not 0 <= last_position < max_positions:
# The worker checks its final token budget, including longer configured sequences.
last_position = last_mrope_decode_position(
prompt_length,
min(max_length, max_positions) - prompt_length, delta)
if last_position >= max_positions:
raise ValueError("Qwen mRoPE decode positions exceed model bounds")
arrays["mrope_position_deltas"] = arrays[
"mrope_position_deltas"].astype(np.int32)
return {
"mrope_config": {
name: torch.from_numpy(array)
for name, array in arrays.items()
}
}

def __init__(self,
model_path: str,
Expand Down
21 changes: 6 additions & 15 deletions tensorrt_llm/_torch/pyexecutor/engine/runners/decoder/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1805,23 +1805,14 @@ def _pack_context_multimodal(
request.py_multimodal_data = multimodal_params.multimodal_data
multimodal_params_list.append(multimodal_params)

# Re-register mrope tensors for context-only requests (EPD disaggregated serving).
# This creates new IPC handles owned by the prefill worker, so the decode worker
# can access them even after the encode worker's GC deallocates the original memory.
# Without this, the decode worker would receive handles pointing to freed memory.
# Only the final context response carries the full host snapshot.
if (
request.is_context_only_request
and _use_mrope
and "mrope_config" in multimodal_params.multimodal_data
_use_mrope
and request.is_context_only_request
and request.is_last_context_chunk
and request._host_mrope_positions is not None
):
mrope_config = multimodal_params.multimodal_data["mrope_config"]
_mrope_position_ids = mrope_config.get("mrope_position_ids")
_mrope_position_deltas = mrope_config.get("mrope_position_deltas")
if _mrope_position_ids is not None and _mrope_position_deltas is not None:
# Clone to allocate new memory owned by this (prefill) worker.
request.py_result.set_mrope_position(
_mrope_position_ids.clone(), _mrope_position_deltas.clone()
)
request.py_result.set_mrope_position(*request._host_mrope_positions)

def _classify_generation_requests(
self,
Expand Down
10 changes: 6 additions & 4 deletions tensorrt_llm/_torch/pyexecutor/engine/runners/mm_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class _PayloadBatch:
request_indices: list[int]
params: list[MultimodalParams]
embedding_lengths: list[list[int]]
host_mrope_configs: list[dict[str, torch.Tensor]]


class MultimodalEncoderRunner(ScheduledModelRunner):
Expand Down Expand Up @@ -68,6 +69,7 @@ def _prepare_inputs(self, scheduled_requests: ScheduledRequests) -> _PayloadBatc
request_indices = []
params = []
embedding_lengths = []
host_mrope_configs = []
start_offset = 0
for request_idx, request in enumerate(scheduled_requests.context_requests):
request_start = start_offset
Expand All @@ -89,7 +91,8 @@ def _prepare_inputs(self, scheduled_requests: ScheduledRequests) -> _PayloadBatc
request_indices.append(request_idx)
params.append(param)
embedding_lengths.append(list(lengths))
return _PayloadBatch(request_indices, params, embedding_lengths)
host_mrope_configs.append(multimodal_data.get("mrope_config") or {})
return _PayloadBatch(request_indices, params, embedding_lengths, host_mrope_configs)

def warmup(self, resource_manager: ResourceManager | None = None) -> None:
del resource_manager
Expand Down Expand Up @@ -148,11 +151,10 @@ def _forward_step(self, batch: _PayloadBatch) -> dict[str, Any]:
"mm_embedding_lengths"
)

# Extract mrope position data from multimodal_params if available.
# Export from the host so completion can overlap the encoder forward.
mrope_position_ids_list = []
mrope_position_deltas_list = []
for multimodal_param in batch.params:
mrope_config = multimodal_param.multimodal_data.get("mrope_config", {})
for mrope_config in batch.host_mrope_configs:
mrope_position_ids = mrope_config.get("mrope_position_ids")
mrope_position_deltas = mrope_config.get("mrope_position_deltas")
if mrope_position_ids is not None:
Expand Down
13 changes: 11 additions & 2 deletions tensorrt_llm/_torch/pyexecutor/llm_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,9 +691,9 @@ def set_mrope_position(
mrope_position_ids: torch.Tensor,
mrope_position_deltas: torch.Tensor,
):
self._mrope_position_ids = SharedTensorContainer.from_tensor(
self._mrope_position_ids = SharedTensorContainer.from_tensor_bytes(
Comment thread
yechank-nvidia marked this conversation as resolved.
Resolved
Comment thread
yechank-nvidia marked this conversation as resolved.
Resolved
mrope_position_ids).dump_to_dict()
self._mrope_position_deltas = SharedTensorContainer.from_tensor(
self._mrope_position_deltas = SharedTensorContainer.from_tensor_bytes(
mrope_position_deltas).dump_to_dict()
self.diff.mrope_position_ids = self._mrope_position_ids
self.diff.mrope_position_deltas = self._mrope_position_deltas
Expand Down Expand Up @@ -1082,6 +1082,15 @@ def __init__(
self.py_client_id = client_id
self.py_request_id = self.request_id
self.py_llm_request_type = self.llm_request_type
# Staging (including side-stream prefetch) can replace both request tensors.
self._host_mrope_positions: tuple[torch.Tensor,
torch.Tensor] | None = None
if mm_data and self.is_context_only_request:
mrope = mm_data.get("mrope_config") or {}
ids = mrope.get("mrope_position_ids")
deltas = mrope.get("mrope_position_deltas")
if ids is not None and deltas is not None:
self._host_mrope_positions = (ids.cpu(), deltas.cpu())
self.py_min_length = self.sampling_config.min_tokens
# Whether the sampler's in-graph fast tier can sample this request;
# decided on first use (TorchSampler._can_use_fast_path) because it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def retire(self, requests: list[LlmRequest]) -> None:


class MultimodalEmbeddingCompletion:
"""Export each request's multimodal embeddings, and its MRoPE positions, as CUDA IPC handles.
"""Export multimodal embeddings as shared handles and MRoPE positions by value.

A request without multimodal items in the batch completes without a result. Only the rank
whose responses reach the frontend exports: an exported allocation stays alive until a
Expand Down
41 changes: 39 additions & 2 deletions tensorrt_llm/_torch/shared_tensor/shared_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class _SharedTensorRebuildMethodRegistry:
REBUILD_CUDA = 1
REBUILD_CPU = 2
REBUILD_LOCAL = 3
REBUILD_BYTES = 4

_registry: Dict[int, Callable] = {}

Expand Down Expand Up @@ -373,6 +374,25 @@ def from_tensor(cls,
method_key = _SharedTensorRebuildMethodRegistry.register(rebuild_method)
return cls(method_key, tensor_handle)

@classmethod
def from_tensor_bytes(cls, tensor: torch.Tensor) -> 'SharedTensorContainer':
"""Copy tensor values into a JSON-safe, cross-host payload."""
tensor_host = tensor.detach()
if tensor_host.device.type != "cpu":
tensor_host = tensor_host.cpu()
tensor_host = tensor_host.contiguous()
return cls(
_SharedTensorRebuildMethodRegistry.REBUILD_BYTES, {
"tensor_size":
list(tensor_host.shape),
"dtype":
str(tensor_host.dtype),
"data":
base64.b64encode(
tensor_host.reshape(-1).view(
Comment thread
yechank-nvidia marked this conversation as resolved.
Resolved
torch.uint8).numpy().tobytes()).decode('ascii'),
})

@classmethod
def from_dict(cls, tensor_info: Dict[str, Any]) -> 'SharedTensorContainer':
"""Create a SharedTensorContainer from a serialized dictionary (Consumer side).
Expand All @@ -391,6 +411,11 @@ def from_dict(cls, tensor_info: Dict[str, Any]) -> 'SharedTensorContainer':
ValueError: If the method_key is not supported
"""
method_key = tensor_info['method_key']
if method_key == _SharedTensorRebuildMethodRegistry.REBUILD_BYTES:
return cls(method_key, {
key: tensor_info[key]
for key in ("tensor_size", "dtype", "data")
})
if method_key == _SharedTensorRebuildMethodRegistry.REBUILD_LOCAL:
return cls(
method_key, {
Expand All @@ -417,6 +442,14 @@ def get_local_view(self) -> torch.Tensor:
Returns:
The reconstructed tensor
"""
if self.method_key == _SharedTensorRebuildMethodRegistry.REBUILD_BYTES:
dtype = str_to_torch_dtype(self.tensor_handle["dtype"])
data = bytearray(
base64.b64decode(self.tensor_handle["data"], validate=True))
shape = self.tensor_handle["tensor_size"]
if not data:
return torch.empty(0, dtype=dtype).reshape(shape)
return torch.frombuffer(data, dtype=dtype).clone().reshape(shape)
if self.method_key == _SharedTensorRebuildMethodRegistry.REBUILD_LOCAL:
if self.tensor_handle["producer_pid"] != os.getpid():
raise RuntimeError(
Expand All @@ -434,8 +467,10 @@ def get_local_view(self) -> torch.Tensor:
@classmethod
def release_dict(cls, tensor_info: Dict[str, Any]) -> None:
"""Consume an exported handle that will not be delivered to a consumer."""
if tensor_info[
'method_key'] == _SharedTensorRebuildMethodRegistry.REBUILD_CUDA:
method_key = tensor_info['method_key']
if method_key == _SharedTensorRebuildMethodRegistry.REBUILD_BYTES:
return
if method_key == _SharedTensorRebuildMethodRegistry.REBUILD_CUDA:
torch.UntypedStorage._release_ipc_counter(
base64.b64decode(tensor_info['ref_counter_handle']),
tensor_info['ref_counter_offset'],
Expand All @@ -452,6 +487,8 @@ def dump_to_dict(self) -> Dict[str, Any]:
Returns:
Dictionary containing the serialized tensor information
"""
if self.method_key == _SharedTensorRebuildMethodRegistry.REBUILD_BYTES:
return {"method_key": self.method_key, **self.tensor_handle}
if self.method_key == _SharedTensorRebuildMethodRegistry.REBUILD_LOCAL:
return {
"method_key": self.method_key,
Expand Down
21 changes: 20 additions & 1 deletion tensorrt_llm/disaggregated_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from tensorrt_llm.bindings import executor as tllme

if TYPE_CHECKING:
from tensorrt_llm.inputs.multimodal import MultimodalInputLayout
from tensorrt_llm.inputs.multimodal import MultimodalInput, MultimodalInputLayout


class DisaggScheduleStyle(IntEnum):
Expand Down Expand Up @@ -57,6 +57,8 @@ class DisaggregatedParams:
multimodal_hashes (List[List[int]]): The multimodal hashes of each multimodal item in the request.
multimodal_positions (List[int]): Prompt-token offset of each multimodal item.
multimodal_lengths (List[int]): Prompt-token count of each multimodal item.
multimodal_input (MultimodalInput): The context worker's KV cache identity, including
hashes, positions, lengths, UUIDs and runs. When present it supplies the item spans.
multimodal_input_layout (MultimodalInputLayout): Exact encoder-side
prompt and multimodal layout to preserve during E/P handoff.
"""
Expand Down Expand Up @@ -87,6 +89,7 @@ class DisaggregatedParams:
multimodal_hashes: Optional[List[List[int]]] = (
None # user provided mm hashes should be a list of 8 integers
)
multimodal_input: Optional["MultimodalInput"] = None
mrope_position_ids_handle: Optional[Dict[str, Any]] = None
mrope_position_deltas_handle: Optional[Dict[str, Any]] = None
multimodal_input_layout: Optional["MultimodalInputLayout"] = None
Expand Down Expand Up @@ -122,6 +125,22 @@ def get_request_type(self) -> tllme.RequestType:

def __post_init__(self):
"""Restore serialized layout and validate request and multimodal metadata."""
if self.multimodal_input is not None:
from tensorrt_llm.inputs.multimodal import MultimodalInput

if isinstance(self.multimodal_input, dict):
self.multimodal_input = MultimodalInput(**self.multimodal_input)
elif not isinstance(self.multimodal_input, MultimodalInput):
raise TypeError("multimodal_input must be MultimodalInput")
identity = self.multimodal_input
if self.multimodal_positions is None and self.multimodal_lengths is None:
self.multimodal_positions = identity.multimodal_positions
self.multimodal_lengths = identity.multimodal_lengths
elif (
self.multimodal_positions != identity.multimodal_positions
or self.multimodal_lengths != identity.multimodal_lengths
):
raise ValueError("multimodal spans must match the context cache identity")
if self.multimodal_input_layout is not None:
# Defer the import because inputs and executor import these parameters.
from tensorrt_llm.inputs.multimodal import MultimodalInputLayout
Expand Down
Loading