diff --git a/.gitignore b/.gitignore index 938bb47b943b..29d6be1eccc1 100644 --- a/.gitignore +++ b/.gitignore @@ -135,5 +135,8 @@ examples/kimi_k3/.eval_dflash_runtime.*.yaml # Media a VisualGen server generates, when it is started from the checkout trtllm_generated/ +# Build-time generated Python bindings for contracts/engine/v1/*.proto +tensorrt_llm/contracts/engine/v1/_generated/ + # Standalone static mock interface check output mock_interface_report.json diff --git a/3rdparty/fetch_content.json b/3rdparty/fetch_content.json index ccc804acff9d..c040ee4b997f 100644 --- a/3rdparty/fetch_content.json +++ b/3rdparty/fetch_content.json @@ -1,6 +1,12 @@ { "schema_version": 1, "dependencies": [ + { + "name": "abseil-cpp", + "git_repository": "https://github.com/abseil/abseil-cpp", + "git_tag": "20250512.1", + "git_shallow": true + }, { "name": "cppzmq", "git_repository": "https://github.com/zeromq/cppzmq", @@ -122,6 +128,13 @@ "git_shallow": true, "source_subdir": "dont-add-this-project-with-add-subdirectory" }, + { + "name": "protobuf", + "git_repository": "https://github.com/protocolbuffers/protobuf", + "git_tag": "v33.6", + "git_shallow": true, + "patch_file": "patches/protobuf_libprotobuf_alias.patch" + }, { "name": "pybind11", "git_repository": "https://github.com/pybind/pybind11", diff --git a/3rdparty/patches/protobuf_libprotobuf_alias.patch b/3rdparty/patches/protobuf_libprotobuf_alias.patch new file mode 100644 index 000000000000..14ebc0d014b0 --- /dev/null +++ b/3rdparty/patches/protobuf_libprotobuf_alias.patch @@ -0,0 +1,14 @@ +--- a/cmake/libprotobuf.cmake ++++ b/cmake/libprotobuf.cmake +@@ -43,6 +43,10 @@ + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + ) +-add_library(protobuf::libprotobuf ALIAS libprotobuf) ++# PyTorch's CMake package defines protobuf::libprotobuf as a stand-in when it ++# ships no protobuf, and links its targets through that name: keep it there. ++if(NOT TARGET protobuf::libprotobuf) ++ add_library(protobuf::libprotobuf ALIAS libprotobuf) ++endif() + + target_link_libraries(libprotobuf PUBLIC utf8_validity) diff --git a/contracts/engine/v1/capabilities.proto b/contracts/engine/v1/capabilities.proto new file mode 100644 index 000000000000..0fc28c6f9415 --- /dev/null +++ b/contracts/engine/v1/capabilities.proto @@ -0,0 +1,682 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: typed capability declarations. +// +// The host core builds the capability snapshot it publishes from what the engine adapter declares. +// Most items are the intersection of "declared by the adapter" and "supported by the host core"; the +// host also adds items (Capabilities.mm.media_sources gains BLOB and Capabilities.tensor.deliveries +// gains BLOB_FETCH / SHM) and fills or rewrites host-owned items (Capabilities.disagg.instance_id, +// integrity, and the issued rendezvous[] tickets). The snapshot is sent in SessionAccepted, returned by +// ControlService.GetInfo, and resent in SessionNotice(CAPABILITIES_CHANGED) when static capabilities +// change. +// +// Presence semantics: +// * capability sub-message absent = the (older) host does not know this group or parameter; +// * capability sub-message present with ParamDomain.kind = UNSUPPORTED (or a bool set to false) = +// explicitly unsupported; +// * in both cases the frontend must not send the corresponding request field; the host rejects an +// undeclared field or an out-of-range value per row with UNSUPPORTED. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/common.proto"; +import "engine/v1/disagg.proto"; +import "engine/v1/request.proto"; + +// ============================================================================ +// Parameter domain building blocks +// ============================================================================ + +// Kind of a parameter's accepted value domain. +enum ParamDomainKind { + // Unset / explicitly unsupported: the field cannot be used; a request that sets it is rejected per + // row with UNSUPPORTED. + PARAM_DOMAIN_KIND_UNSUPPORTED = 0; + // Any valid value within the field's protocol-defined range. + PARAM_DOMAIN_KIND_ANY = 1; + // The closed interval [min_value, max_value] (min_exclusive / max_exclusive can make a bound open). + PARAM_DOMAIN_KIND_RANGE = 2; + // Only the discrete set values[]. For example TensorRT-LLM declares beam_width = VALUES{max_beam_width}, + // and one-model speculative decoding accepts only VALUES{0} for some parameters. + PARAM_DOMAIN_KIND_VALUES = 3; + // Only values equivalent to not setting the field (for example an engine whose penalties accept only + // 1.0 / 0.0). The allowed no-effect values are listed in default_value (or values[]) so the frontend + // can check them exactly. + PARAM_DOMAIN_KIND_NO_EFFECT_ONLY = 4; +} + +// Typed value domain of a float parameter. +message FloatParamDomain { + ParamDomainKind kind = 1; + // Lower / upper bound when kind = RANGE; unset = no extra narrowing on that side (only the field's own + // definition applies). + optional float min_value = 2; + optional float max_value = 3; + // true = strictly greater than min_value (for example top_p in (0, 1]). + bool min_exclusive = 4; + // true = strictly less than max_value. + bool max_exclusive = 5; + // Discrete allowed values when kind = VALUES (or NO_EFFECT_ONLY). + repeated float values = 6; + // Value the engine uses when the parameter is unset (lets the frontend know and validate; the protocol + // itself only distinguishes set from unset). + optional float default_value = 7; +} + +// Typed value domain of an unsigned 32-bit integer parameter. +message Uint32ParamDomain { + ParamDomainKind kind = 1; + optional uint32 min_value = 2; + optional uint32 max_value = 3; + repeated uint32 values = 4; + optional uint32 default_value = 5; +} + +// Typed value domain of a signed 32-bit integer parameter (early_stopping, top_p_reset_ids, ...). +message Int32ParamDomain { + ParamDomainKind kind = 1; + optional int32 min_value = 2; + optional int32 max_value = 3; + repeated int32 values = 4; + optional int32 default_value = 5; +} + +// Typed value domain of an unsigned 64-bit integer parameter (seed). +message Uint64ParamDomain { + ParamDomainKind kind = 1; + optional uint64 min_value = 2; + optional uint64 max_value = 3; + repeated uint64 values = 4; + optional uint64 default_value = 5; +} + +// ============================================================================ +// Capability groups (Capabilities fields 1-10) +// ============================================================================ + +// Model and executor basics (Capabilities.model). +message ModelCapabilities { + // Primary model name (for example an HF repo id or a local directory name). + string name = 1; + // Model aliases served externally (shown by /v1/models). + repeated string served_names = 2; + // Model architecture name (for example "LlamaForCausalLM", "Glm4MoeForCausalLM"). + string architecture = 3; + // Engine implementation name (for example "trtllm-pytorch"). + string engine_name = 4; + // Engine version / build identifier (git sha, version number, ...). + string engine_build = 5; + // Vocabulary size. + uint32 vocab_size = 6; + // Whether the model is encoder-decoder (gates Request.encoder_input_tokens). + bool is_encoder_decoder = 7; + // Maximum total length of one sequence (prompt + output); the basis for deriving max_tokens. + uint32 max_seq_len = 8; + // Maximum token budget per iteration (together with chunked_prefill and cp_size it bounds prompt + // admission). + uint32 max_num_tokens = 9; + // Maximum static batch size. + uint32 max_batch_size = 10; + // Whether chunked prefill is enabled. + bool chunked_prefill = 11; + // Default EOS tokens of the model. + repeated sfixed32 eos_token_ids = 12; + // BOS token (unset = none). + optional sfixed32 bos_token_id = 13; + // Default PAD token (unset = none / same as EOS). + optional sfixed32 pad_token_id = 14; + // Engine streaming interval (results are reported at least once every this many iterations). + uint32 stream_interval = 15; + // Default reasoning parser name suggested by the engine (unset = none). + optional string reasoning_parser = 16; + // Default tool call parser name suggested by the engine (unset = none). + optional string tool_call_parser = 17; +} + +// Tokenizer consistency fingerprint (Capabilities.tokenizer). The frontend checks it after loading its +// local tokenizer and fails startup on a mismatch. +message TokenizerFingerprint { + uint32 vocab_size = 1; + repeated sfixed32 eos_token_ids = 2; + optional sfixed32 bos_token_id = 3; + // Canonical SHA-256 (32 B) over the key tokenizer files; empty = no file digest provided. + bytes files_sha256 = 4; +} + +// Reproducibility scope of the random seed (SamplingParams.seed). +enum SeedScope { + // seed is not supported (or reproducibility cannot be guaranteed). + SEED_SCOPE_NONE = 0; + // Reproducible for the same batch composition, not across different batches. + SEED_SCOPE_BATCH_DEPENDENT = 1; + // Reproducible per request, independent of other requests in the batch. + SEED_SCOPE_PER_REQUEST = 2; +} + +// Sparse logit_bias capability (SamplingParams.logit_bias). +message LogitBiasCapability { + bool supported = 1; + // Maximum bias entries per request; 0 = no fixed limit (bounded by max_request_bytes). + uint32 max_entries = 2; +} + +// Sampling parameter capabilities (Capabilities.sampling; one domain per SamplingParams field). +// Parameters unavailable under one-model speculative decoding are declared here as UNSUPPORTED or +// VALUES{0}, so the frontend can reject them with a 4xx up front. +message SamplingCapabilities { + // Upper bound of SamplingParams.num_sequences in sampling mode (1 = n / best_of > 1 unsupported). + uint32 max_num_sequences = 1; + FloatParamDomain temperature = 2; + Uint32ParamDomain top_k = 3; + FloatParamDomain top_p = 4; + FloatParamDomain top_p_decay = 5; + FloatParamDomain top_p_min = 6; + Int32ParamDomain top_p_reset_ids = 7; + FloatParamDomain min_p = 8; + Uint64ParamDomain seed = 9; + SeedScope seed_scope = 10; + FloatParamDomain repetition_penalty = 11; + FloatParamDomain presence_penalty = 12; + FloatParamDomain frequency_penalty = 13; + Uint32ParamDomain prompt_ignore_length = 14; + Uint32ParamDomain no_repeat_ngram_size = 15; + LogitBiasCapability logit_bias = 16; +} + +// Beam search capabilities (Capabilities.beam). +message BeamCapabilities { + // Maximum beam width (1 = beam search unsupported; declared by the adapter from its real + // configuration). + uint32 max_beam_width = 1; + // Exact accepted domain of SamplingParams.beam_width. TensorRT-LLM declares VALUES{max_beam_width}: + // when max_beam_width > 1, plain sampling requests with beam_width = 1 are rejected too. + Uint32ParamDomain beam_width = 2; + // Whether SamplingParams.beam_width_array is supported. + bool width_array = 3; + FloatParamDomain length_penalty = 4; + Int32ParamDomain early_stopping = 5; + FloatParamDomain diversity_rate = 6; +} + +// Stop condition capabilities (Capabilities.stop). +message StopCapabilities { + Uint32ParamDomain min_tokens = 1; + // Maximum number of StopParams.sequences; 0 = stop sequences unsupported. + uint32 max_sequences = 2; + // Maximum token length of each stop sequence. + uint32 max_sequence_len = 3; + // Whether StopParams.bad_sequences is supported. + bool bad_sequences = 4; + // Maximum count and length of bad sequences (0 = same as max_sequences / max_sequence_len, or no fixed + // limit). + uint32 max_bad_sequences = 5; + uint32 max_bad_sequence_len = 6; +} + +// How prompt logprobs are handled on a prefix cache hit. +enum PromptLogprobsCachedPrefixPolicy { + PROMPT_LOGPROBS_CACHED_PREFIX_UNSPECIFIED = 0; + // Skip prefix reuse for requests that ask for prompt_logprobs, so the full [0, prompt_len) is + // returned. + PROMPT_LOGPROBS_CACHED_PREFIX_BYPASS_REUSE = 1; + // Return only the non-cached part; PromptLogprobs.start gives its first position. Padding with NaN + // posing as valid values is not allowed. + PROMPT_LOGPROBS_CACHED_PREFIX_PARTIAL = 2; +} + +// Prompt logprobs capability (OutputOptions.prompt_logprobs). +message PromptLogprobsCapability { + bool supported = 1; + // 0 = only the target token itself; k = also up to top-k candidates. + uint32 max_top_k = 2; + PromptLogprobsCachedPrefixPolicy cached_prefix = 3; +} + +// Logprobs capabilities (Capabilities.logprobs). +message LogprobsCapabilities { + // Unset = generation logprobs unsupported; 0 = only the sampled token itself; k = also up to top-k + // candidates. + optional uint32 max_top_k = 1; + // Whether the full-vocabulary rank can be computed (OutputOptions.logprob_rank). + bool rank = 2; + PromptLogprobsCapability prompt = 3; + // Supported SamplingParams.logprobs_mode values (RAW / PROCESSED). + repeated LogprobsMode modes = 4; +} + +// Time axis of a named additional output tensor. +enum AdditionalOutputAxis { + ADDITIONAL_OUTPUT_AXIS_UNSPECIFIED = 0; + // ADDITIONAL_CONTEXT (prompt-aligned, in PromptInfo.tensors of the first row). + ADDITIONAL_OUTPUT_AXIS_CONTEXT = 1; + // ADDITIONAL_GENERATION (output-aligned, on the terminal row or in a streaming append-only segment). + ADDITIONAL_OUTPUT_AXIS_GENERATION = 2; +} + +// One registered named additional output tensor. +message AdditionalOutputSpec { + string name = 1; + AdditionalOutputAxis axis = 2; + DType dtype = 3; +} + +// Large output tensor capabilities (Capabilities.outputs; gates TensorOutputRequest). +message OutputTensorCapabilities { + bool context_logits = 1; + bool generation_logits = 2; + bool encoder_output = 3; + bool routed_experts = 4; + // Whether ROUTED_EXPERTS can be streamed as per-row slices (default false: the whole-sequence int16 + // tensor comes once on the terminal row). + bool routed_experts_streaming = 5; + repeated AdditionalOutputSpec additional_names = 6; +} + +// Metrics and statistics capabilities (Capabilities.metrics). +message MetricsCapabilities { + bool perf = 1; + bool time_breakdown = 2; + bool decoding_stats = 3; + // perf forced on for the whole server (native return_perf_metrics = true): RequestTiming is returned + // on the terminal row even when the request did not set metrics.perf. + bool forced_perf = 4; + // Whether iteration statistics are enabled (GetIterationStats and session pushes). + bool iteration_stats = 5; + // Maximum iteration statistics records kept in the engine ring buffer. + uint32 iteration_stats_max = 6; + // Whether iteration statistics include per-request details (IterationStats.request_stats). + bool request_stats = 7; +} + +// Processor capabilities (Capabilities.proc). Field 1 (thinking_budget) is retired; the thinking budget +// is implemented by the client layer. +message ProcessorCapabilities { + reserved 1; + reserved "thinking_budget"; + // Names of the batched logits processors registered at engine initialization + // (Request.logits_processors may only use these names). + repeated string registered_names = 2; +} + +// Guided decoding kinds (one-to-one with the GuidedDecoding.kind branches). +enum GuidedDecodingKind { + GUIDED_DECODING_KIND_UNSPECIFIED = 0; + GUIDED_DECODING_KIND_JSON_SCHEMA = 1; + GUIDED_DECODING_KIND_JSON_OBJECT = 2; + GUIDED_DECODING_KIND_REGEX = 3; + GUIDED_DECODING_KIND_EBNF_GRAMMAR = 4; + GUIDED_DECODING_KIND_STRUCTURAL_TAG = 5; + GUIDED_DECODING_KIND_CHOICE = 6; +} + +// Guided decoding capabilities (Capabilities.guided). +message GuidedDecodingCapabilities { + repeated GuidedDecodingKind kinds = 1; + // Informational backend name (for example "xgrammar", "llguidance"). + string backend = 2; +} + +// ============================================================================ +// Capability groups (Capabilities fields 11-21) +// ============================================================================ + +// LoRA capabilities (Capabilities.lora). +message LoraCapabilities { + bool supported = 1; + // Maximum number of adapters resident at the same time. + uint32 max_loras = 2; + // Whether a Request.lora carrying a path is loaded on first use. + bool path_loading = 3; + // Whether LoraLoad / LoraUnload explicit management is supported. + bool preload = 4; + // Supported checkpoint formats (HF / NEMO). + repeated LoraFormat formats = 5; + // Snapshot of the currently loaded adapters (full list in the handshake and GetInfo; run-time changes + // arrive as Frame.lora_set_changed deltas). + repeated LoraAdapterInfo loaded = 6; +} + +// Media source kind (one-to-one with the MediaItem.source branches). +enum MediaSourceKind { + MEDIA_SOURCE_KIND_UNSPECIFIED = 0; + MEDIA_SOURCE_KIND_URL = 1; + MEDIA_SOURCE_KIND_DATA = 2; + MEDIA_SOURCE_KIND_BLOB = 3; +} + +// Value kind of a preprocessed model input (one-to-one with the ModelInput.value branches). +enum ModelInputValueKind { + MODEL_INPUT_VALUE_KIND_UNSPECIFIED = 0; + MODEL_INPUT_VALUE_KIND_TENSOR = 1; + MODEL_INPUT_VALUE_KIND_I64_LIST = 2; + MODEL_INPUT_VALUE_KIND_F64_LIST = 3; + MODEL_INPUT_VALUE_KIND_BOOL = 4; + MODEL_INPUT_VALUE_KIND_I64 = 5; + MODEL_INPUT_VALUE_KIND_F64 = 6; + MODEL_INPUT_VALUE_KIND_STRING = 7; +} + +// Type registration of one preprocessed model input path (ModelInput). +message ModelInputSpec { + // Qualified path (for example "image.pixel_values", "mrope_config.mrope_position_deltas"). + string path = 1; + ModelInputValueKind kind = 2; + // Meaningful only when kind = TENSOR. + DType dtype = 3; + // Meaningful only when kind = TENSOR; unset = variable rank or validated by the model. + optional uint32 rank = 4; +} + +// Multimodal capabilities (Capabilities.mm). +message MultimodalCapabilities { + // Supported modes (MEDIA / PREPROCESSED); empty = multimodal unsupported. + repeated MultimodalMode modes = 1; + repeated Modality modalities = 2; + repeated MediaSourceKind media_sources = 3; + // Registered MultimodalInput.model_inputs paths and their type constraints in preprocessed mode. + repeated ModelInputSpec model_input_names = 6; + // Whether MultimodalInput.item_metadata is required in PREPROCESSED mode. + bool item_metadata = 7; + // Whether precomputed embeddings (MultimodalInput.embeddings) are supported. + bool precomputed_embeddings = 8; + // Maximum multimodal items per request; 0 = no fixed limit. + uint32 max_items = 9; + // Version of the image-aware KV routing convention; 0 = unsupported. + uint32 image_routing_version = 10; + + reserved 4, 5; + reserved "io_option_keys", "processor_option_keys"; +} + +// Priority scheduling capability. +message PriorityCapability { + // Whether SchedulingParams.priority is accepted. + bool supported = 1; + // Whether the engine's waiting-queue policy actually orders by priority (when false, whether the field + // is accepted is decided by `supported`, and the frontend can warn accordingly). + bool effective = 2; +} + +// Scheduling capabilities (Capabilities.sched). +message SchedulingCapabilities { + PriorityCapability priority = 1; + // Whether SchedulingParams.attention_dp_rank / attention_dp_relax are supported. + bool dp_targeting = 2; + // Whether SchedulingParams.agent_hierarchy is supported. + bool agent_hierarchy = 3; + // Whether SchedulingParams.subagent_affinity_id is supported. + bool subagent_affinity = 4; + // Whether SchedulingParams.conversation_id is supported. + bool conversation_id = 5; + // Whether admission ordering by Request.queue_age_us is supported. + bool queue_age = 6; +} + +// KV event delivery mode. +enum KvEventsMode { + // No KV events. + KV_EVENTS_MODE_NONE = 0; + // Only the server push stream SubscribeKvEvents. + KV_EVENTS_MODE_PUSH = 1; + // Only pulling with GetKvEvents. + KV_EVENTS_MODE_PULL = 2; + // Both push and pull. + KV_EVENTS_MODE_BOTH = 3; +} + +// One optional side channel on which the engine publishes KV events directly. +message KvEventSourceInfo { + string transport = 1; + string encoding = 2; + uint32 schema_version = 3; + string endpoint = 4; + string topic = 5; + optional uint32 dp_rank = 6; +} + +// KV event capability. +message KvEventsCapability { + KvEventsMode mode = 1; + // Maximum entries in the engine event ring buffer (0 = disabled). + uint32 buffer_max = 2; + // Side channels on which the engine publishes KV events directly; empty = only through + // SubscribeKvEvents. + repeated KvEventSourceInfo sources = 3; +} + +// KV hints capability (KvParams.hints). +message KvHintsCapability { + // Supported protocol_version values (for example ["0.1"]); empty = KV hints unsupported. + repeated string versions = 1; + // Host backstop limit on the total KvHints bytes per request (natively 64 KiB); beyond it the row is + // rejected with INVALID_ARGUMENT. + uint32 max_bytes = 2; +} + +// KV cache capabilities (Capabilities.kv). +message KvCapabilities { + // tokens_per_block actually in effect at run time (not the static configuration value). + uint32 tokens_per_block = 1; + uint32 total_blocks = 2; + uint32 host_blocks = 3; + bool block_reuse = 4; + // Block hash algorithm name (for example "sha256", "blake3", "none"). + string hash_algo = 5; + KvEventsCapability events = 6; + bool cache_salt = 7; + bool retention = 8; + KvHintsCapability hints = 9; +} + +// KV layout compatibility fingerprint, used by an orchestrator at startup to check that context and +// generation instances are compatible. +message KvLayoutFingerprint { + DType dtype = 1; + // Layout fingerprint bytes computed by the engine (head count, layer count, block size, + // quantization / paging format, ...). + bytes layout_fingerprint = 2; +} + +// Host-level integrity scheme for handoffs and rendezvous tickets. +enum IntegrityScheme { + // No signature (only for trusted isolated networks or tests). + INTEGRITY_SCHEME_NONE = 0; + // HMAC-SHA256 (SignedHandoff and RendezvousTicket share the deployment key). + INTEGRITY_SCHEME_HMAC_SHA256 = 1; +} + +// Integrity declaration. +message IntegrityCapability { + IntegrityScheme scheme = 1; + // Key ids currently accepted (several keys may coexist during key rotation; signing uses the first + // active key). + repeated string key_ids = 2; +} + +// Disaggregated serving capabilities (Capabilities.disagg). +// The host must not silently narrow the adapter's capabilities without declaring it; if the host itself +// cannot support an item (such as signing), it must declare that truthfully. +message DisaggCapabilities { + // Unique id of this host instance (= KvHandoff.ctx_instance_id of handoffs it produces). + string instance_id = 1; + // Phases this instance accepts (AGGREGATED / CONTEXT_ONLY / GENERATION_ONLY); a fixed-role instance + // reports only one. + repeated Phase phases = 2; + // Supported scheduling styles (CONTEXT_FIRST / GENERATION_FIRST). + repeated ScheduleStyle schedule_styles = 3; + // KV transfer backend name (for example "nixl", "ucx", "mpi", "mooncake"); empty = KV transfer + // disabled. + string transfer_backend = 4; + // Generation-first rendezvous tickets (issued by the context host; endpoint is byte-identical to + // KvHandoff.ctx_endpoint of context-first handoffs). + repeated RendezvousTicket rendezvous = 5; + // KV layout fingerprint (compatibility check when pairing at startup). + KvLayoutFingerprint kv_layout = 6; + // Default validity of a context-side handoff (milliseconds; reclaimed by the clock). + uint32 handoff_ttl_ms = 7; + // KV transfer timeout (milliseconds, measured by the adapter from entering the transfer state). + uint32 kv_transfer_timeout_ms = 8; + // Host watchdog limit for a generation leg (milliseconds = engine queueing limit + + // kv_transfer_timeout_ms + margin). + uint32 gen_max_wait_ms = 9; + // Whether ReleaseHandoffs actually frees the KV (false = handoffs can only expire after + // handoff_ttl_ms). + bool supports_release = 10; + // Maximum beam width under disaggregation (1 = beam search unsupported with disaggregation; + // TensorRT-LLM declares it from its real configuration). + uint32 max_beam_width = 11; + // Maximum sampled sequences under disaggregation (must be 1 in this version; any n > 1 is rejected + // with UNSUPPORTED_IN_DISAGG). + uint32 max_num_sequences = 12; + + // Feature combination bits (undeclared = false; requests using the combination are rejected before + // acceptance with UNSUPPORTED_IN_DISAGG). + bool first_gen_logits = 13; + bool remote_tail = 14; + bool multimodal_pd = 15; + // Encoder disaggregation; always false in this version. + bool encoder_disagg = 16; + bool queue_age = 17; + bool pipelined_transfer = 18; + // Whether generation-first provides the real first-token logprob (NaN when false; beam > 1 requests + // are rejected when this is false). + bool gen_first_first_token_logprobs = 19; + bool routed_experts = 20; + + // Maximum SignedHandoff size in bytes (including inline tensors such as first_gen_logits and + // multimodal); larger handoffs are rejected before acceptance with UNSUPPORTED_IN_DISAGG. + uint32 max_handoff_bytes = 21; + // Supported KvHandoff.digest_version values (this version includes 1). + repeated uint32 digest_versions = 22; + // Whether the engine produces / consumes the opaque KvHandoff.engine_state. + bool uses_engine_state = 23; + // Declarative confirmation that the context engine forces CONTEXT_ONLY requests to generate exactly + // one token, so the frontend does not rewrite max_tokens (must be true). + bool ctx_forces_single_token = 24; + // Host-level integrity scheme (shared by SignedHandoff and RendezvousTicket). + IntegrityCapability integrity = 25; + // Whether gen-only benchmark requests without rendezvous information are accepted (test feature, + // default false). + bool benchmark_gen_only = 26; + + // 30-39 are reserved for disaggregated n > 1; 40-49 for encoder disaggregation. + reserved 30 to 39; + reserved 40 to 49; +} + +// Parallel topology (Capabilities.parallel). +message ParallelCapabilities { + uint32 tp = 1; + uint32 pp = 2; + uint32 cp = 3; + uint32 ep = 4; + uint32 attention_dp_size = 5; + bool attention_dp_enabled = 6; +} + +// Host large-object delivery capabilities and quotas (Capabilities.tensor). +message TensorCapabilities { + // Delivery methods available on the host (INLINE / SHM / CUDA_IPC / BLOB_FETCH). + repeated TensorDelivery deliveries = 1; + // Default inline tensor limit allowed by the host (bytes). + uint64 max_inline_bytes = 2; + // Backstop TTL of host blobs (milliseconds). + uint32 blob_ttl_ms = 3; + // Blob byte quota per session (input UploadBlob plus output blobs and pinned CUDA IPC memory). + uint64 session_blob_quota_bytes = 4; + // Global blob byte quota of the host. + uint64 host_blob_quota_bytes = 5; +} + +// Tracing capabilities (Capabilities.trace). +message TraceCapabilities { + // Informational: whether the engine / host emits its own OpenTelemetry spans from Request.trace. + bool engine_spans = 1; +} + +// Admin (operations / RL) command capabilities (Capabilities.admin; one bool per AdminRequest command, +// undeclared = unsupported). +message AdminCapabilities { + bool profile = 1; + bool sleep_wakeup = 2; + bool update_weights = 3; + bool reset_prefix_cache = 4; + bool truncate_kv = 5; + bool memory_status = 6; + bool memory_report = 7; +} + +// Specification of one registered typed-extension key. +message ExtensionKeySpec { + // Key name (two levels, ".", in the "mm.io" namespace). + string key = 1; + // Allowed value kind (must match the TypedValue oneof branch). + TypedValueKind kind = 2; +} + +// Key registry of one typed-extension namespace. +message ExtensionNamespaceSpec { + // Closed list: request direction only "mm.io" and "mm.processor"; output direction only "diag". + string ext_namespace = 1; + repeated ExtensionKeySpec keys = 2; +} + +// Registry of all typed extensions (Capabilities.ext), including "mm.io" and "mm.processor" keys. +// It is the sole run-time gate for typed extensions. +message ExtensionCapabilities { + repeated ExtensionNamespaceSpec namespaces = 1; + // Maximum total bytes of all TypedExtension values in one request. + uint32 max_bytes = 2; +} + +// Speculative decoding mode (informational; its effect on sampling parameters is declared precisely by +// the Capabilities.sampling parameter domains). +enum SpeculativeMode { + SPECULATIVE_MODE_NONE = 0; + SPECULATIVE_MODE_ONE_MODEL = 1; + SPECULATIVE_MODE_TWO_MODEL = 2; +} + +// Speculative decoding capabilities (Capabilities.spec; informational). +message SpeculativeCapabilities { + SpeculativeMode mode = 1; + uint32 max_draft_len = 2; +} + +// ============================================================================ +// Full capability snapshot +// ============================================================================ + +// Full capability snapshot published by the host. Each top-level field is one capability group; fields +// 22-39 are reserved for groups added by later minor versions. +message Capabilities { + ModelCapabilities model = 1; + TokenizerFingerprint tokenizer = 2; + SamplingCapabilities sampling = 3; + BeamCapabilities beam = 4; + StopCapabilities stop = 5; + LogprobsCapabilities logprobs = 6; + OutputTensorCapabilities outputs = 7; + MetricsCapabilities metrics = 8; + ProcessorCapabilities proc = 9; + GuidedDecodingCapabilities guided = 10; + LoraCapabilities lora = 11; + MultimodalCapabilities mm = 12; + SchedulingCapabilities sched = 13; + KvCapabilities kv = 14; + DisaggCapabilities disagg = 15; + ParallelCapabilities parallel = 16; + TensorCapabilities tensor = 17; + TraceCapabilities trace = 18; + AdminCapabilities admin = 19; + ExtensionCapabilities ext = 20; + SpeculativeCapabilities spec = 21; + + // 22-29 are reserved for new capability groups such as encoder disaggregation; 30-39 for later minor + // versions. + reserved 22 to 29; + reserved 30 to 39; +} diff --git a/contracts/engine/v1/common.proto b/contracts/engine/v1/common.proto new file mode 100644 index 000000000000..df233d1e26c0 --- /dev/null +++ b/contracts/engine/v1/common.proto @@ -0,0 +1,514 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: the contract between a serving frontend (the trtllm-serve HTTP frontend +// process, Dynamo, ...) and an engine host. This file holds the enums and small types shared by the +// whole package. +// +// Package-wide conventions: +// 1. Enum numeric values are part of the contract. Every engine implementation uses the same values, +// so values are forwarded as-is without translation tables. +// 2. Every enum value carries its enum name as prefix (generated C++ puts all top-level enum values of +// a package in one scope). +// 3. A proto3 `optional` field distinguishes "unset" from "set to the default value". A scalar without +// `optional` reads as the proto3 zero value when unset; each field documents what zero means. +// 4. Request direction: the host rejects a request row that uses a field or enum value not defined in +// the minor version in effect for the session (ERROR_CODE_UNSUPPORTED, `field` = logical field +// name); it never silently ignores it. Response direction: the frontend ignores unknown fields and +// unknown row_flags bits, and treats an unknown finish value as "terminated with ERROR". +// 5. Within one major version, fields and enum values are only appended. Field numbers are never +// reused; a removed field becomes `reserved`. +// 6. Token ids are always sfixed32 (fixed width, so a reader can view a packed list as an int32 array). + +syntax = "proto3"; + +package trtllm.engine.v1; + +// ============================================================================ +// Version +// ============================================================================ + +// Protocol version major.minor. This package is major 1. +// The version in effect for a session requires equal majors and uses the smaller of the two minors. +message ProtocolVersion { + // Major version; must be 1 to match the package name v1. A session with a different major is + // rejected with FAILED_PRECONDITION. + uint32 major = 1; + // Minor version; within one major only additions are made. The host advertises only capabilities + // the peer's minor understands, and sends only enum values and row_flags bits defined in the minor + // in effect. + uint32 minor = 2; +} + +// ============================================================================ +// Output row enums (value domains of hot columns; the columns themselves are bytes, see output.proto) +// ============================================================================ + +// Why a sequence finished. The hot column `Frame.finish` stores this enum's value as one byte (u8) per +// row. Values 0-5 equal the native C++ `tensorrt_llm::executor::FinishReason`; 6 and 7 are added by this +// protocol. The frontend treats an unknown value as "terminated with ERROR". +enum FinishReason { + // The sequence has not finished (ordinary incremental row). + FINISH_REASON_NOT_FINISHED = 0; + // `stop.end_id` was sampled. The end_id token itself is reported as the last token of this row and + // counts toward completion_tokens. + FINISH_REASON_END_ID = 1; + // One of `stop.sequences` matched. The matched tokens are not trimmed; `stop_index` gives the smallest + // matching index. + FINISH_REASON_STOP_SEQUENCE = 2; + // The effective max_tokens was reached. + FINISH_REASON_LENGTH = 3; + // Engine-side timeout. + FINISH_REASON_TIMED_OUT = 4; + // Cancelled (CancelBatch, host shutdown, or a ReleaseHandoffs tombstone). The terminal row still + // carries FinalInfo; FinalInfo.cancel_reason gives the source. + FINISH_REASON_CANCELLED = 5; + // Failed; the row extra always carries ErrorInfo. + FINISH_REASON_ERROR = 6; + // Disaggregated context leg finished: the row has no tokens and always carries a SignedHandoff and + // FinalInfo.prefill_usage. + FINISH_REASON_CONTEXT_DONE = 7; + // 8 is reserved for a future encoder-disaggregation ENCODE_DONE reason; it must not be sent. + reserved 8; +} + +// Row flag bits. The hot column `Frame.row_flags` stores the bitwise OR of these values as two bytes +// (u16, little-endian) per row. The low 4 bits are defined and the other 12 are reserved; the frontend +// ignores unknown bits. +enum RowFlag { + ROW_FLAG_NONE = 0; + // First row of this (handle, seq). The first row of a request (the FIRST_ROW row with seq = 0) + // carries PromptInfo. + ROW_FLAG_FIRST_ROW = 1; + // The sequence terminated (finish != NOT_FINISHED); the row carries FinalInfo. Sent exactly once per + // sequence. + ROW_FLAG_SEQ_FINAL = 2; + // The request terminated: last row of the request. Does not imply associated blobs have been + // released; handles remain unique for the lifetime of the session and are not reused. + ROW_FLAG_REQUEST_DONE = 4; + // The row has an extra: `Frame.extra_index[row]` points into `Frame.extras[]`. + ROW_FLAG_HAS_EXTRA = 8; +} + +// ============================================================================ +// Request-direction enums +// ============================================================================ + +// Request phase. It must not be inferred from whether a handoff is present; unknown values are rejected. +enum Phase { + // Aggregated serving (including native context_and_generation). Default. + PHASE_AGGREGATED = 0; + // Disaggregated context leg: prefill plus the first token only. Finishes with + // FINISH_REASON_CONTEXT_DONE, or with END_ID / STOP_SEQUENCE when a single-beam request stops at its + // first token. + PHASE_CONTEXT_ONLY = 1; + // Disaggregated generation leg: must carry `disagg.handoff`. + PHASE_GENERATION_ONLY = 2; + // 3 is reserved for a future encoder-disaggregation ENCODE_ONLY phase. + reserved 3; +} + +// Disaggregated scheduling style. Required for CONTEXT_ONLY (UNSPECIFIED is rejected; it does not mean +// CONTEXT_FIRST). +enum ScheduleStyle { + SCHEDULE_STYLE_UNSPECIFIED = 0; + // Context leg first, then generation leg (normal path). + SCHEDULE_STYLE_CONTEXT_FIRST = 1; + // Generation leg first: it arrives early holding a RendezvousTicket. + SCHEDULE_STYLE_GENERATION_FIRST = 2; +} + +// Cancellation reason. The reasons only differ for engine-side counters and logs; in every case the +// engine still reports the terminal row and usage. +enum CancelReason { + CANCEL_REASON_UNSPECIFIED = 0; + // The HTTP client disconnected, or the frontend gave up after hitting its buffering limit. + CANCEL_REASON_CLIENT_DISCONNECTED = 1; + // The frontend matched a stop string in the detokenized text. + CANCEL_REASON_STOP_STRING = 2; + // A frontend post-processing hook asked to terminate. + CANCEL_REASON_POSTPROC_TERMINATE = 3; + // A frontend-side deadline expired. + CANCEL_REASON_DEADLINE = 4; + // Shutdown: sent by a frontend that is shutting down, or used by the host when it writes CANCELLED + // terminal rows for requests left over after the drain timeout. + CANCEL_REASON_SHUTDOWN = 5; + // (Set by the host / engine.) ReleaseHandoffs left a tombstone for a context request that was still + // running, so the request finished as CANCELLED without creating a handoff + // (RELEASE_HANDOFF_STATUS_PENDING_CANCELLED). Frontends must not use it in CancelBatch. + CANCEL_REASON_HANDOFF_RELEASED = 6; + // 16-31 are reserved for engine-internal cancellation reasons (for example session closed, slow + // consumer, watchdog). They are never sent on the wire; reserving them keeps the value ranges disjoint. + reserved 16 to 31; +} + +// Media modality. +enum Modality { + MODALITY_UNSPECIFIED = 0; + MODALITY_IMAGE = 1; + MODALITY_VIDEO = 2; + MODALITY_AUDIO = 3; +} + +// LoRA checkpoint format. UNSPECIFIED (0) means HF, matching the native lora_ckpt_source default "hf". +enum LoraFormat { + LORA_FORMAT_UNSPECIFIED = 0; + LORA_FORMAT_HF = 1; + LORA_FORMAT_NEMO = 2; +} + +// ============================================================================ +// Errors +// ============================================================================ + +// Error code. "Pre" = appears only in SubmitAck.rejected (before acceptance); "post" = appears only in +// the ErrorInfo of a terminal row (after acceptance). The value in parentheses is the HTTP status the +// frontend maps the code to. +enum ErrorCode { + // Must not be sent; a receiver treats it as ERROR_CODE_INTERNAL. + ERROR_CODE_UNSPECIFIED = 0; + // Malformed or out-of-range field, or grammar compilation failure (pre; grammar may be post) (400). + ERROR_CODE_INVALID_ARGUMENT = 1; + // Field or value not declared in the capabilities, or a field / enum value not defined in the session + // minor (pre) (400). `field` is required. + ERROR_CODE_UNSUPPORTED = 2; + // Prompt too long (including max_num_tokens admission, compared as prompt_len / cp_size). Pre for + // text-only and preprocessed requests; post in media mode, where the length is known only after + // expansion (400). + ERROR_CODE_CONTEXT_TOO_LONG = 3; + // The handle duplicates a live request in the session, or repeats within the batch (pre) (500, + // frontend bug). + ERROR_CODE_DUPLICATE_HANDLE = 4; + // Over max_inflight_requests, the session is above its soft watermark, or the estimated output tensor + // size exceeds the blob quota (field = output.tensors) (pre). Exceeding the quota at run time is + // reported as a terminal ERROR(OVERLOADED) row (post) (503). + ERROR_CODE_OVERLOADED = 5; + // The host is draining and accepts no new requests (pre) (503). + ERROR_CODE_DRAINING = 6; + // A LoRA reference without a path names an adapter that is not preloaded (pre) (400). + ERROR_CODE_LORA_NOT_LOADED = 7; + // The same adapter_id was given with a different path (pre) (400). + ERROR_CODE_LORA_CONFLICT = 8; + // Loading an adapter by path on first use failed (post) (400). + ERROR_CODE_LORA_LOAD_FAILED = 9; + // The engine is dead (pre / post) (503). After acceptance the host synthesizes it for every in-flight + // request. + ERROR_CODE_ENGINE_DEAD = 10; + // The session was judged a slow consumer (post) (503). Only the frontend synthesizes it, for in-flight + // requests after the session is closed; the host never sends it. + ERROR_CODE_SLOW_CONSUMER = 11; + // A referenced input blob cannot be read (pre) (400). + ERROR_CODE_BLOB_UNAVAILABLE = 12; + // Internal error (post) (500). The host also rewrites to this code any enum value an adapter emits that + // is outside the session minor. + ERROR_CODE_INTERNAL = 13; + + // ---- Disaggregated serving codes use 100-149; 150-199 are reserved ---- + // In parentheses: pre/post, the RetryScope the host sets, and the HTTP status. + // A disaggregated request reached an engine without KV transfer enabled (pre, NONE, 503). + ERROR_CODE_DISAGG_UNAVAILABLE = 100; + // The phase is not in Capabilities.disagg.phases (pre, NONE, 400). + ERROR_CODE_PHASE_NOT_SUPPORTED = 101; + // Handoff has missing fields, wrong types, mismatched ids, a mismatched digest, or a bad signature or + // ticket (pre, NONE, 400). + ERROR_CODE_HANDOFF_INVALID = 102; + // A combination not declared as supported under disaggregation: n > 1 (always rejected in v1), beam + // width above Capabilities.disagg.max_beam_width, logits, remote tail, multimodal, a handoff above + // max_handoff_bytes, or generation-first with beams but without first-token logprobs (pre, NONE, 400). + ERROR_CODE_UNSUPPORTED_IN_DISAGG = 103; + // disagg_request_id already exists on the same context instance (pre, NEW_DISAGG_ID, 409). + ERROR_CODE_ALREADY_EXISTS = 104; + // Transfer backend, KV layout, digest version, or effective max_tokens is incompatible with the peer + // (pre or post, NONE, 500). + ERROR_CODE_PEER_INCOMPATIBLE = 105; + // At rendezvous the context side no longer has the handoff (expired, released, or consumed) (post, + // FROM_PREFILL, 503). + ERROR_CODE_HANDOFF_NOT_FOUND = 106; + // The rendezvous endpoint could not be reached in time (post, FROM_PREFILL, 503). + ERROR_CODE_PEER_UNREACHABLE = 107; + // KV transfer failed (post, FROM_PREFILL, 503). + ERROR_CODE_KV_TRANSFER_FAILED = 108; + // KV transfer timed out, measured by the adapter from entering the transfer state, or caught by the + // host's gen_max_wait_ms watchdog (post, FROM_PREFILL, 504). + ERROR_CODE_KV_TRANSFER_TIMEOUT = 109; + + // 150-199 are reserved for error codes of encoder disaggregation and disaggregated n > 1. + reserved 150 to 199; +} + +// Retry advice. Phase-aware rules: +// 1. Any error of an accepted GENERATION_ONLY request (including ENGINE_DEAD, INTERNAL, SLOW_CONSUMER, +// and a CANCELLED termination with cancel_reason = SHUTDOWN) is FROM_PREFILL, because the handoff +// may already have been claimed. +// 2. Every retryable error of a CONTEXT_ONLY request is NEW_DISAGG_ID, never SAME_REQUEST. +// 3. When the session breaks before the ack (frontend-synthesized error), treat the request as possibly +// accepted: generation legs use FROM_PREFILL; context legs use NEW_DISAGG_ID and call +// ReleaseHandoffs for the old id. +enum RetryScope { + // Do not retry. Default. + RETRY_SCOPE_NONE = 0; + // Resend the same request unchanged (with a new handle). + RETRY_SCOPE_SAME_REQUEST = 1; + // Resend the context leg with a new disagg_request_id and release the old id. + RETRY_SCOPE_NEW_DISAGG_ID = 2; + // Restart the disaggregated request from the context leg. + RETRY_SCOPE_FROM_PREFILL = 3; +} + +// Error structure shared by row-level errors and submission rejections. +message ErrorInfo { + // Error code. + ErrorCode code = 1; + // Retry advice (see the phase rules on RetryScope). + RetryScope retry_scope = 2; + // Logical name of the offending request field (for example "sampling.top_k", + // "mm.io.video.num_frames"). Required for capability rejections (UNSUPPORTED). + optional string field = 3; + // Human-readable message; for logs and error echo only, frontends must not parse it. + string message = 4; + // The engine is unusable after this error (the host then enters its ENGINE_DEAD handling). + bool engine_fatal = 5; +} + +// ============================================================================ +// Small containers +// ============================================================================ + +// Token sequence (one stop sequence, one bad-word sequence, ...). +message TokenSeq { + repeated sfixed32 tokens = 1; +} + +// u32 list with presence (logical optional>). +message U32List { + repeated uint32 values = 1; +} + +message I64List { + repeated int64 values = 1; +} + +message F64List { + repeated double values = 1; +} + +// Token usage as counted by the context leg. +message PrefillUsage { + // Number of prompt tokens actually prefilled (after expansion in media mode). + uint32 prompt_tokens = 1; + // Number of prompt tokens served from the prefix cache. + uint32 cached_tokens = 2; +} + +// Half-open interval [begin, end) of token positions; the user (OutputTensor.kind) defines the +// coordinate system. +message TokenRange { + uint32 begin = 1; + uint32 end = 2; +} + +// LoRA adapter description. +message LoraAdapterInfo { + // Numeric id assigned by the frontend or operator; the same id with a different path is + // LORA_CONFLICT. + uint64 adapter_id = 1; + // Human-readable name (logs, /v1/models). + string name = 2; + // Checkpoint path. Required for LoraLoad; in Request.lora, absent means the adapter must already be + // preloaded. + optional string path = 3; + LoraFormat format = 4; +} + +// ============================================================================ +// Large objects +// ============================================================================ + +// Tensor element type. +enum DType { + DTYPE_UNSPECIFIED = 0; + DTYPE_F32 = 1; + DTYPE_F16 = 2; + DTYPE_BF16 = 3; + DTYPE_FP8_E4M3 = 4; + DTYPE_I64 = 5; + DTYPE_I32 = 6; + // ROUTED_EXPERTS always uses I16; -1 means the position was not routed (its KV was reused). + DTYPE_I16 = 7; + DTYPE_I8 = 8; + DTYPE_U8 = 9; + // One byte per element, 0 or 1. + DTYPE_BOOL = 10; + DTYPE_F64 = 11; +} + +// How a large object is delivered. +enum TensorDelivery { + TENSOR_DELIVERY_UNSPECIFIED = 0; + // Bytes inlined in the message (at most max_inline_tensor_bytes). + TENSOR_DELIVERY_INLINE = 1; + // Same-machine shared-memory segment. + TENSOR_DELIVERY_SHM = 2; + // Same-machine CUDA IPC (the frontend consumes on GPU). + TENSOR_DELIVERY_CUDA_IPC = 3; + // Cross-machine: the frame carries only a blob_id and the frontend fetches it with + // BlobService.FetchBlob. + TENSOR_DELIVERY_BLOB_FETCH = 4; +} + +// Shared-memory location (POSIX shm segment name plus a range inside it). +message ShmLocation { + // Segment name as passed to shm_open, including the leading "/". + string name = 1; + // Start offset within the segment (bytes). + uint64 offset = 2; + // Data size (bytes). + uint64 size = 3; +} + +// CUDA IPC location. Used only on the same machine and only when Capabilities.tensor.deliveries +// declares CUDA_IPC. +message CudaIpcLocation { + // CUDA device ordinal as seen by the producing process. + int32 device = 1; + // Raw cudaIpcMemHandle_t bytes (64 B). + bytes mem_handle = 2; + // Offset within the allocation (bytes). + uint64 offset = 3; + // Data size (bytes). + uint64 size = 4; + // Raw cudaIpcEventHandle_t bytes (64 B). When non-empty, the consumer must wait on the event first. + bytes event_handle = 5; +} + +// Object in the host's blob store (fetched or uploaded across machines through BlobService). A blob_id +// is valid only on the host that created it and is owned by the session that created or uploaded it. +message BlobLocation { + // Assigned by the host; unique within the host process. + uint64 blob_id = 1; + // Size in bytes of the object (or of the range this reference covers). + uint64 size = 2; + // Optional content digest (SHA-256, 32 B) to verify after fetching. + bytes digest = 3; +} + +// Tensor reference: `location` says where the data lives. Used for context / generation logits, +// encoder and additional outputs, routed experts, preprocessed multimodal model inputs, and precomputed +// embeddings. +message TensorRef { + // Element type. + DType dtype = 1; + // Shape (elements per dimension). The byte size must equal product(shape) * sizeof(dtype). + repeated uint64 shape = 2; + // Data location; exactly one must be set. + oneof location { + // Inline bytes (little-endian, row-major, densely packed). + bytes inline_bytes = 3; + ShmLocation shm = 4; + CudaIpcLocation cuda_ipc = 5; + BlobLocation blob = 6; + } + // Device holding the data: unset = host memory; set = CUDA device ordinal. + optional int32 device = 7; +} + +// Tensor that can only be inlined. Used inside KvHandoff (first-token logits and mRoPE tensors) because +// a handoff travels between hosts and outlives the session, so blob_id / shm references cannot be +// resolved by the peer. +message InlineTensor { + DType dtype = 1; + repeated uint64 shape = 2; + // Little-endian, row-major, densely packed; byte size = product(shape) * sizeof(dtype). + bytes data = 3; +} + +// ============================================================================ +// Lightweight control messages shared by the session and output frames +// (kept here to avoid an output.proto <-> session.proto import cycle) +// ============================================================================ + +// One rejected request of a SubmitBatch. +message RejectedRequest { + // Index in the corresponding SubmitBatch.requests[] (zero-based). + uint32 index = 1; + // Handle of the rejected request; equals SubmitBatch.requests[index].handle. + uint64 handle = 2; + // Rejection reason. A rejected handle never produces any output row. + ErrorInfo error = 3; +} + +// Submission ack. Acks correspond one-to-one, in arrival order, to the SubmitBatch messages sent by the +// frontend. An ack semantically precedes every output row of any handle in its batch. When a frame is +// pending it is piggybacked in Frame.acks[]; otherwise it is sent alone as ServerMessage.submit_ack. +message SubmitAck { + // Ordinal of the SubmitBatch in the session (starts at 1, increases by one each batch). + uint64 batch_seq = 1; + // Rejected requests. Every request not listed here was accepted (there is no partial acceptance). + repeated RejectedRequest rejected = 2; +} + +// Incremental change of the loaded LoRA set at run time. +// Not a barrier (does not block frame merging). Preferably piggybacked on Frame.lora_set_changed; +// without a frame it may be sent as ServerMessage.lora_set_changed. Both explicit LoraLoad / LoraUnload +// and load-by-path on first use emit only this delta, never a full CAPABILITIES_CHANGED barrier. +message LoraSetChanged { + // Newly loaded LoRA adapters. + repeated LoraAdapterInfo added = 1; + // adapter_id of unloaded or evicted LoRA adapters. + repeated uint64 removed = 2; +} + +// ============================================================================ +// Typed extensions +// ============================================================================ + +// Value type of a typed-extension key (used for key registration). +enum TypedValueKind { + TYPED_VALUE_KIND_UNSPECIFIED = 0; + TYPED_VALUE_KIND_BOOL = 1; + TYPED_VALUE_KIND_I64 = 2; + TYPED_VALUE_KIND_F64 = 3; + TYPED_VALUE_KIND_STRING = 4; + TYPED_VALUE_KIND_BYTES = 5; + TYPED_VALUE_KIND_I64_LIST = 6; + TYPED_VALUE_KIND_F64_LIST = 7; + // Canonical JSON text (sorted keys, no extra whitespace) carrying a native nested value of type Any. + TYPED_VALUE_KIND_JSON = 8; +} + +// Value of a typed extension. The oneof branch must match the kind registered in +// Capabilities.ext; otherwise the row is rejected with UNSUPPORTED. +message TypedValue { + oneof value { + bool bool_value = 1; + int64 i64_value = 2; + double f64_value = 3; + string string_value = 4; + bytes bytes_value = 5; + I64List i64_list = 6; + F64List f64_list = 7; + // Canonical JSON text; allowed only for keys registered with kind JSON. + string json = 8; + } +} + +// Extension entry. +message ExtensionEntry { + // Key. In the "mm.io" namespace keys have two levels, "." (for example + // "video.num_frames"). + string key = 1; + TypedValue value = 2; +} + +// Typed extension. Only a closed list of namespaces exists: request direction "mm.io" (media I/O +// options) and "mm.processor" (processor options); output direction "diag" (FinalInfo.diag, +// GetInfoResponse.diag). Rules: an unregistered namespace, key, or type rejects the row with +// UNSUPPORTED (field = "."); there are no ignorable unknown keys. The frontend must not +// depend on the semantics of "diag" values. The total extension bytes per request are bounded by +// Capabilities.ext.max_bytes. +message TypedExtension { + // Namespace (logical name `namespace`, renamed because it is a C++ keyword). + string ext_namespace = 1; + // Entries; a key must not repeat. + repeated ExtensionEntry entries = 2; +} diff --git a/contracts/engine/v1/control.proto b/contracts/engine/v1/control.proto new file mode 100644 index 000000000000..aa71d7c2487d --- /dev/null +++ b/contracts/engine/v1/control.proto @@ -0,0 +1,529 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: session-independent control service and blob service. +// +// Services: +// * ControlService: session-independent queries, health, load, iteration statistics, KV events, +// disaggregated handoff release and transceiver state, LoRA preload management, and optional admin +// (operations / RL) commands. +// * BlobService: cross-machine fetch, upload and explicit release of large objects (FetchBlob / +// UploadBlob / ReleaseBlobs) on separate HTTP/2 streams, so large tensors do not block session +// frames. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/capabilities.proto"; +import "engine/v1/common.proto"; +import "engine/v1/disagg.proto"; +import "engine/v1/stats.proto"; + +// ============================================================================ +// GetInfo +// ============================================================================ + +// Query a full snapshot of host and engine information (for /v1/models, /server_info and orchestrator +// probes; no session needed). +message GetInfoRequest {} + +// Host-level runtime information. +message ServerRuntimeInfo { + // Highest protocol version (major.minor) the host supports. + ProtocolVersion version = 1; + // Host build version / identifier. + string host_build = 2; + // Host process start time (unix milliseconds). + uint64 started_at_unix_ms = 3; + // Host monotonic clock at response time (nanoseconds; same-machine diagnostics only). + uint64 host_clock_ns = 4; + // Engine startup timings (native LLM.startup_metrics, in milliseconds, keys such as + // "model_load_ms"). + map startup_metrics_ms = 5; +} + +// GetInfo response. +message GetInfoResponse { + // Full capability snapshot of the host (same source as SessionAccepted.capabilities, including model + // and disagg). + Capabilities capabilities = 1; + // Host-level runtime information. + ServerRuntimeInfo server = 2; + // Diagnostic typed extension; ext_namespace must be "diag". For logs and operator display only; the + // frontend must not depend on its semantics. + TypedExtension diag = 3; +} + +// ============================================================================ +// Health +// ============================================================================ + +// Health state. +enum HealthState { + HEALTH_STATE_UNSPECIFIED = 0; + // Initializing. + HEALTH_STATE_STARTING = 1; + // Serving normally. + HEALTH_STATE_SERVING = 2; + // Degraded (for example a non-fatal check failed, or draining). + HEALTH_STATE_DEGRADED = 3; + // Temporarily not serving (for example draining or not ready). + HEALTH_STATE_NOT_SERVING = 4; + // The engine died fatally (sticky terminal state). + HEALTH_STATE_DEAD = 5; +} + +// Result of one health check (includes at least "executor_loop" and "adapter", plus "transceiver" with +// disaggregation). +message HealthCheckItem { + string name = 1; + bool ok = 2; + string message = 3; +} + +// Health check request. +message HealthRequest { + // true = the host sends an internal 1-token probe request to verify the end-to-end execution path (a + // frontend may also implement native /health_generate itself over a session). + bool probe = 1; +} + +// Health check response. +message HealthResponse { + HealthState state = 1; + repeated HealthCheckItem checks = 2; + // While draining, the number of disaggregated handoffs still alive; 0 when not disaggregated or not + // draining. + uint32 active_handoffs = 3; +} + +// ============================================================================ +// GetLoad and GetKvCapacity +// ============================================================================ + +// Load snapshot of one attention DP rank. +message DpRankLoad { + uint32 dp_rank = 1; + uint32 running_requests = 2; + uint32 queued_requests = 3; + uint32 kv_blocks_used = 4; + uint32 kv_blocks_total = 5; + uint64 running_tokens = 6; + uint64 waiting_tokens = 7; + // Sampling time of this DP rank's load sample (unix nanoseconds, wall clock); unset = unknown. + optional uint64 sampled_at_unix_nanos = 8; +} + +// Disaggregated-serving load and handoff state machine counters. +// Handoff counters come from the context engine (adapter); the host only adds +// released_undelivered_handoffs and gen_watchdog_fired. +message DisaggLoadInfo { + // Cumulative accepted requests per phase. + uint64 accepted_aggregated = 1; + uint64 accepted_context_only = 2; + uint64 accepted_generation_only = 3; + // Cumulative CONTEXT_DONE rows emitted on the context side. + uint64 context_done_emitted = 4; + // Handoffs currently alive in the context engine (CREATED / CLAIMED / TRANSFERRING); reaching zero is + // one of the conditions for drain completion. + uint32 active_handoffs = 5; + // Cumulative handoffs reclaimed because expires_after_ms elapsed. + uint64 expired_handoffs = 6; + // Cumulative handoffs released explicitly by ReleaseHandoffs. + uint64 released_handoffs = 7; + // Cumulative handoffs the host released automatically because the session disconnected while their + // CONTEXT_DONE rows were still undelivered in the outbox. + uint64 released_undelivered_handoffs = 8; + // Cumulative running context requests cancelled (without creating a handoff) by a ReleaseHandoffs + // tombstone. + uint64 pending_cancelled_handoffs = 9; + // Cumulative handoffs successfully consumed by generation legs. + uint64 consumed_handoffs = 10; + // Cumulative handoffs terminated by transfer failure or timeout. + uint64 failed_handoffs = 11; + // Cumulative firings of the host's gen_max_wait_ms watchdog. + uint64 gen_watchdog_fired = 12; +} + +// Typed load snapshot of the host and engine. +message GetLoadRequest {} + +message LoadInfo { + uint32 running_requests = 1; + uint32 queued_requests = 2; + // In-flight handles summed over all active sessions of the host. + uint32 inflight_handles = 3; + uint32 kv_blocks_used = 4; + uint32 kv_blocks_total = 5; + uint32 kv_blocks_host_used = 6; + uint32 kv_blocks_host_total = 7; + uint64 running_tokens = 8; + uint64 waiting_tokens = 9; + uint32 prefill_batch_size = 10; + uint32 decode_batch_size = 11; + // Disaggregated serving counters (set only when disaggregation is enabled). + DisaggLoadInfo disagg = 12; + // Per-rank load under attention DP (set only when attention DP is enabled). + repeated DpRankLoad per_dp_rank = 13; + // Cumulative rows the host dropped because they could not be routed (for example late engine rows for + // a request the watchdog already terminated). + uint64 dropped_rows = 14; + // Sampling time of the whole load sample (unix nanoseconds, wall clock); unset = unknown. + optional uint64 sampled_at_unix_nanos = 15; +} + +// Runtime KV cache capacity (same meaning as Capabilities.kv; a separate RPC because the KV pool may be +// reconfigured at run time). +message GetKvCapacityRequest {} + +message KvCapacityResponse { + uint32 max_blocks = 1; + uint32 tokens_per_block = 2; + uint64 max_tokens = 3; + uint32 host_blocks = 4; +} + +// ============================================================================ +// GetIterationStats, SubscribeKvEvents and GetKvEvents +// ============================================================================ + +// Pull iteration statistics. +message GetIterationStatsRequest { + // Return only records with iter > since_iter; unset = start from the oldest record still in the ring + // buffer. + optional uint64 since_iter = 1; + // Maximum records to return; 0 = all available records (bounded by + // Capabilities.metrics.iteration_stats_max). + uint32 max_count = 2; +} + +message GetIterationStatsResponse { + repeated IterationStats stats = 1; +} + +// Subscribe to the KV cache event stream (requires Capabilities.kv.events.mode PUSH or BOTH). +message SubscribeKvEventsRequest { + // Resume: push events with event_id > from_event_id; unset = start from the current live position. + optional uint64 from_event_id = 1; +} + +// Pull KV cache events (native POST /kv_cache_events semantics; requires Capabilities.kv.events.mode +// PULL or BOTH). +message GetKvEventsRequest { + // Maximum events to pull; 0 = all currently available events. + uint32 max_count = 1; +} + +// ============================================================================ +// ReleaseHandoffs and GetTransceiverState +// ============================================================================ + +// Result of releasing one handoff. +enum ReleaseHandoffStatus { + RELEASE_HANDOFF_STATUS_UNSPECIFIED = 0; + // KV released and the handoff removed from the active table. + RELEASE_HANDOFF_STATUS_RELEASED = 1; + // Not found (already consumed, expired or released, or an unknown id); treated as idempotent + // success. + RELEASE_HANDOFF_STATUS_NOT_FOUND = 2; + // Currently CLAIMED / TRANSFERRING; the engine releases it once the transfer ends and does not + // interrupt the transfer. + RELEASE_HANDOFF_STATUS_IN_TRANSFER = 3; + // The context request with this disagg_request_id is still running and has not reached + // CONTEXT_DONE: the engine left a tombstone, so the request will finish with FINISH_REASON_CANCELLED + // (cancel_reason = HANDOFF_RELEASED) without creating a handoff. The tombstone is cleared after + // handoff_ttl_ms. + RELEASE_HANDOFF_STATUS_PENDING_CANCELLED = 4; +} + +// Result of one release item. +message ReleaseHandoffResult { + HandoffKey key = 1; + ReleaseHandoffStatus status = 2; +} + +// Batch handoff release (idempotent, not bound to a session; called by the context frontend on the +// context host that owns the handoffs). The host checks that every key.ctx_instance_id equals its own +// Capabilities.disagg.instance_id before forwarding to the adapter; a mismatch returns +// INVALID_ARGUMENT. +message ReleaseHandoffsRequest { + repeated HandoffKey items = 1; +} + +message ReleaseHandoffsResponse { + repeated ReleaseHandoffResult results = 1; +} + +// Get the opaque bytes of the native DataTransceiverState. +message GetTransceiverStateRequest {} + +message GetTransceiverStateResponse { + // Bytes in the transport layer's own format; not interpreted by the protocol and passed to the + // orchestrator unchanged. + bytes state = 1; +} + +// ============================================================================ +// LoRA management (requires Capabilities.lora.preload = true) +// ============================================================================ + +// Preload a LoRA adapter. On success every active session receives a non-barrier LoraSetChanged delta. +// If adapter_id already exists with a different path, the RPC fails with gRPC ALREADY_EXISTS (the only +// status code used for this case; it corresponds to the row-level ERROR_CODE_LORA_CONFLICT). +message LoraLoadRequest { + // adapter_id, name and path are required; format defaults to HF. + LoraAdapterInfo adapter = 1; +} + +message LoraLoadResponse { + LoraAdapterInfo adapter = 1; +} + +// Unload a loaded LoRA adapter (idempotent). +message LoraUnloadRequest { + uint64 adapter_id = 1; +} + +message LoraUnloadResponse {} + +// List all currently loaded LoRA adapters. +message LoraListRequest {} + +message LoraListResponse { + repeated LoraAdapterInfo adapters = 1; +} + +// ============================================================================ +// Admin (optional operations / RL commands, each declared in Capabilities.admin) +// ============================================================================ + +// Start profiling (native StartProfileRequest). +message StartProfileCommand { + // Output directory for profiling artifacts; unset = engine default. + optional string output_dir = 1; + // Number of steps to profile; unset = until StopProfile. + optional uint32 num_steps = 2; + // Number of steps to wait before starting; default 0. + uint32 start_step = 3; + // Profiling activities (for example ["cpu", "cuda"]); empty = engine default. + repeated string activities = 4; +} + +// Stop profiling. +message StopProfileCommand {} + +// Release runtime memory (sleep; native MemoryUpdateRequest / RuntimeMemoryUpdateRequest). +message SleepCommand { + // Memory tags to release (for example "model", "kv_cache", "draft_model"); empty = engine default + // set. + repeated string tags = 1; +} + +// Restore runtime memory (wakeup). +message WakeupCommand { + // Memory tags to restore; empty = the whole default set. + repeated string tags = 1; +} + +// Update weights online (native UpdateWeightsRequest). +message UpdateWeightsCommand { + // Weight handle map (key = parameter / handle name, value = serialized handle or path); may be empty + // with finalize = true to end the update. + map weights = 1; + // true = finish the weight update and commit it (equivalent to native weights = None). + bool finalize = 2; +} + +// Clear the prefix cache (reset_prefix_cache). +message ResetPrefixCacheCommand {} + +// Truncate one prefix in the KV cache (native KVCacheTruncateTokensRequest). +message TruncateKvEntry { + // Full prefix token sequence. + repeated sfixed32 prefix_tokens = 1; + // Number of tokens kept from the start (radix tree blocks beyond this length are cut). + uint32 num_tokens_to_keep = 2; +} + +// Truncate KV cache prefixes in a batch. +message TruncateKvCommand { + repeated TruncateKvEntry entries = 1; +} + +// Query the runtime memory state (native RuntimeMemoryStatus). +message GetMemoryStatusCommand {} + +// Runtime memory state (native RuntimeMemoryStatus.state). +enum RuntimeMemoryState { + RUNTIME_MEMORY_STATE_UNSPECIFIED = 0; + RUNTIME_MEMORY_STATE_RUNNING = 1; + RUNTIME_MEMORY_STATE_PARKING = 2; + RUNTIME_MEMORY_STATE_PARKED = 3; + RUNTIME_MEMORY_STATE_WAKING = 4; + RUNTIME_MEMORY_STATE_FAILED = 5; +} + +// Payload returned by GetMemoryStatus. +message RuntimeMemoryStatusInfo { + RuntimeMemoryState state = 1; + // Memory tags still released (sorted lexicographically). + repeated string parked_tags = 2; +} + +// Query per-rank GPU memory diagnostics (native LLM.get_memory_report / GET /memory_report). +message GetMemoryReportCommand {} + +// Payload returned by GetMemoryReport. Either inline per-rank UTF-8 JSON strings or, when the +// combined payload exceeds single-RPC limits (for example with allocation stacks across many ranks), +// a BlobLocation holding a UTF-8 JSON array of per-rank report objects (rank 0 first). +message MemoryReportInfo { + // Inline UTF-8 JSON report per rank (rank 0 first). Empty when `blob` is set. + repeated string reports_json = 1; + // Optional blob fallback when the combined report exceeds single-RPC size limits. + BlobLocation blob = 2; +} + +// Admin command request. The chosen branch must be declared true in Capabilities.admin, otherwise the +// RPC fails with gRPC UNIMPLEMENTED. +message AdminRequest { + oneof command { + StartProfileCommand start_profile = 1; + StopProfileCommand stop_profile = 2; + SleepCommand sleep = 3; + WakeupCommand wakeup = 4; + UpdateWeightsCommand update_weights = 5; + ResetPrefixCacheCommand reset_prefix_cache = 6; + TruncateKvCommand truncate_kv = 7; + GetMemoryStatusCommand get_memory_status = 8; + GetMemoryReportCommand get_memory_report = 9; + } + + // 20-29 are reserved for admin commands of later minor versions. + reserved 20 to 29; +} + +// Admin command response. +message AdminResponse { + // Short human-readable status or message (for example "ok"). + string message = 1; + oneof result { + RuntimeMemoryStatusInfo memory_status = 2; + MemoryReportInfo memory_report = 3; + } +} + +// ============================================================================ +// BlobService messages +// ============================================================================ + +// Fetch an output blob across machines (or a range [offset, offset + length) of a streaming +// append-only segment). +message FetchBlobRequest { + // Owning session id (ownership check: only the session that created or owns the blob, or an + // authorized caller, may read it). + uint64 session_id = 1; + // Target blob_id (from OutputTensor.ref.blob.blob_id). + uint64 blob_id = 2; + // Start byte offset within the object (default 0). + uint64 offset = 3; + // Number of bytes to read; 0 = from offset to the current end. + uint64 length = 4; +} + +// One chunk of the FetchBlob server stream. +message BlobChunk { + // Data bytes of this chunk. + bytes data = 1; + // Start byte offset of this chunk within the object (for continuity checks). + uint64 offset = 2; + // True only on the last chunk; the last chunk may carry a SHA-256 digest (32 B) of the whole range. + bool eof = 3; + bytes digest = 4; +} + +// Metadata in the first message of the UploadBlob client stream. +message UploadBlobHeader { + // Owning session id (0 = anonymous, reclaimed only by Capabilities.tensor.blob_ttl_ms; non-zero = + // bound to that session and counted against its quota). + uint64 session_id = 1; + // Expected total size in bytes (lets the host check session_blob_quota_bytes / host_blob_quota_bytes + // up front). + uint64 total_size = 2; + // Optional SHA-256 digest (32 B) of the whole object, verified by the host after receiving it. + bytes digest = 3; +} + +// One message of the UploadBlob client stream: the first must be `header`, the rest are consecutive +// chunks. +message UploadBlobRequest { + oneof payload { + UploadBlobHeader header = 1; + bytes chunk = 2; + } +} + +// UploadBlob response. +message UploadBlobResponse { + // Blob reference assigned by the host (put it directly into MediaItem.blob or TensorRef.blob). + BlobLocation blob = 1; +} + +// Explicitly release blobs (idempotent). +// Release individual blob_ids, or release every output blob of some requests at once by +// (session_id, handles), including streaming append-only segments. +message ReleaseBlobsRequest { + uint64 session_id = 1; + repeated uint64 blob_ids = 2; + repeated uint64 handles = 3; +} + +message ReleaseBlobsResponse { + // Number of objects actually released (logs and monitoring only). + uint32 released_count = 1; +} + +// ============================================================================ +// Services +// ============================================================================ + +// Session-independent host / engine control service. +service ControlService { + // Full snapshot of capabilities, model, server and disaggregation information. + rpc GetInfo(GetInfoRequest) returns (GetInfoResponse); + // Health check (with an optional internal 1-token probe). + rpc Health(HealthRequest) returns (HealthResponse); + // Typed load snapshot, including disaggregated handoff state machine counters. + rpc GetLoad(GetLoadRequest) returns (LoadInfo); + // Runtime KV cache capacity. + rpc GetKvCapacity(GetKvCapacityRequest) returns (KvCapacityResponse); + // Pull typed iteration statistics. + rpc GetIterationStats(GetIterationStatsRequest) returns (GetIterationStatsResponse); + // Subscribe to KV cache events (server stream). + rpc SubscribeKvEvents(SubscribeKvEventsRequest) returns (stream KvEventBatch); + // Pull KV cache events (unary). + rpc GetKvEvents(GetKvEventsRequest) returns (KvEventBatch); + // Release disaggregated handoffs in a batch, idempotently (leaves a PENDING_CANCELLED tombstone for a + // context request that is still running). + rpc ReleaseHandoffs(ReleaseHandoffsRequest) returns (ReleaseHandoffsResponse); + // Get the opaque bytes of the native DataTransceiverState. + rpc GetTransceiverState(GetTransceiverStateRequest) returns (GetTransceiverStateResponse); + // LoRA adapter management. + rpc LoraLoad(LoraLoadRequest) returns (LoraLoadResponse); + rpc LoraUnload(LoraUnloadRequest) returns (LoraUnloadResponse); + rpc LoraList(LoraListRequest) returns (LoraListResponse); + // Optional operations / RL commands (each declared in Capabilities.admin). + rpc Admin(AdminRequest) returns (AdminResponse); +} + +// Cross-machine large-object fetch, upload and release service (separate HTTP/2 streams so large +// tensors do not block session frames). +service BlobService { + // Fetch an output blob in chunks (supports incremental reads of [offset, offset + length)). + rpc FetchBlob(FetchBlobRequest) returns (stream BlobChunk); + // Upload an input blob in chunks (preprocessed multimodal tensors, media bytes, precomputed + // embeddings). + rpc UploadBlob(stream UploadBlobRequest) returns (UploadBlobResponse); + // Release the given blob_ids, or every output blob associated with the given request handles. + rpc ReleaseBlobs(ReleaseBlobsRequest) returns (ReleaseBlobsResponse); +} diff --git a/contracts/engine/v1/disagg.proto b/contracts/engine/v1/disagg.proto new file mode 100644 index 000000000000..dd48b3900b26 --- /dev/null +++ b/contracts/engine/v1/disagg.proto @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: disaggregated serving handoff objects. +// +// Flow: the context engine's host (fills ctx_instance_id, request_digest and digest_version per its +// capabilities, inlines tensors, encodes, optionally signs) -> SignedHandoff on the CONTEXT_DONE row -> +// context frontend -> one HTTP hop through the orchestrator -> generation frontend -> `disagg.handoff` +// of the GENERATION_ONLY request -> the generation engine's host (verifies the signature per its +// capabilities and parses). The KV cache itself never travels over this protocol. +// +// Numbering: KvHandoff fields 30-39 are reserved for disaggregated n > 1 and 40-49 for encoder +// disaggregation. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/common.proto"; + +// First-token logprob of one beam. +message FirstTokenLogprob { + // Sampled token. + sfixed32 token_id = 1; + // Logprob of the sampled token; -inf is encoded as IEEE negative infinity (no lower clamp). + float logprob = 2; + // Rank in the full vocabulary (1-based); 0 = not computed. + uint32 rank = 3; + // Top-k candidates in descending logprob order. + repeated TopLogprob topk = 4; +} + +// One top-k candidate. +message TopLogprob { + sfixed32 token_id = 1; + float logprob = 2; +} + +// Multimodal layout for disaggregated prefill/decode. mRoPE tensors can only be inlined. +message MultimodalHandoff { + // Start position of each multimodal item in the (expanded) prompt. + repeated uint32 positions = 1; + // Same length as positions: length of each item (tokens). + repeated uint32 lengths = 2; + // mRoPE position ids (inline form of the native shared tensor handle). + InlineTensor mrope_position_ids = 3; + // mRoPE position deltas. + InlineTensor mrope_position_deltas = 4; +} + +// Effective max_tokens of the context engine (equals PromptInfo.max_tokens of its first row). +message EffectiveMaxTokens { + // Effective value (tokens). The generation engine must use it; if its local limit is smaller it + // rejects before acceptance with PEER_INCOMPATIBLE (field = "stop.max_tokens") instead of silently + // truncating. + uint32 value = 1; + // True when the requested value was clamped. + bool clamped = 2; +} + +// Generation-first rendezvous ticket. The context host issues it with the deployment key; the +// generation frontend obtains it from the context frontend's +// /server_info.disaggregated_params.rendezvous_ticket_b64 and copies it unchanged into the rendezvous +// subset. mac = HMAC-SHA256(key[key_id], canonical encoding of the other ticket fields); the canonical +// encoding is a fixed byte layout defined by the host implementation, not protobuf serialization. +message RendezvousTicket { + // Instance id of the issuing context host (equals Capabilities.disagg.instance_id). + string ctx_instance_id = 1; + // Transfer backend name. + string transfer_backend = 2; + // Targeted attention DP rank; unset = broadcast. + optional uint32 attention_dp_rank = 3; + // Rendezvous address, verbatim; byte-identical to KvHandoff.ctx_endpoint of a context-first handoff. + string endpoint = 4; + // Issue time (unix milliseconds); the clock skew tolerated across machines is a deployment setting. + uint64 issued_at_unix_ms = 5; + // Validity (milliseconds): invalid after issued_at_unix_ms + ttl_ms. + uint32 ttl_ms = 6; + // Signing key id (one of Capabilities.disagg.integrity.key_ids). + string key_id = 7; + // HMAC-SHA256, 32 B; empty when integrity.scheme is NONE. + bytes mac = 8; +} + +// Typed handoff object. +// Who fills what: the engine (adapter) fills disagg_request_id, ctx_engine_request_id through +// multimodal, engine_state, expires_after_ms, expanded_prompt_tokens and effective_max_tokens; the +// context host core fills ctx_instance_id, request_digest and digest_version. For generation-first, the +// generation frontend assembles the rendezvous subset (disagg_request_id, ctx_instance_id, ctx_dp_rank, +// ctx_endpoint, transfer_backend, schedule_style, rendezvous_ticket). +// "Frontend-readable" below only means the frontend may parse a read-only copy; when forwarding, the +// SignedHandoff is always passed on unchanged. "Forward only" fields are opaque to the frontend. +message KvHandoff { + // Pairing key (fixed u64) equal to Request.disagg.request_id of both legs; when the context leg did + // not set it, the pairing id the engine actually used (= engine_request_id). Always present. + // Frontend-readable (orchestration, release). + fixed64 disagg_request_id = 1; + // Instance id of the producing context host (= Capabilities.disagg.instance_id), filled by that host. + // Always present. Frontend-readable. + string ctx_instance_id = 2; + // Context engine local request id (native ctx_request_id), only for log / perf correlation. + optional uint64 ctx_engine_request_id = 3; + // Context-side attention DP rank; unset = the generation side broadcasts to all context DP ranks + // (distinct from an explicit 0). Forward only. + optional uint32 ctx_dp_rank = 4; + // Rendezvous address given by the transceiver, verbatim; a single string, not split into host and + // port. Format depends on the backend. Forward only. + string ctx_endpoint = 5; + // Transfer backend of the producer; if the generation side is incompatible it fails with + // PEER_INCOMPATIBLE before rendezvous. Always present. Forward only. + string transfer_backend = 6; + // Native transceiver communication state, verbatim (not interpreted by the protocol). Forward only. + bytes opaque_state = 7; + // Same as Request.disagg.schedule_style. Always present. Frontend-readable. + ScheduleStyle schedule_style = 8; + // First token, one per beam (including beams whose first token is end_id); empty for remote tail. + // The frontend must not emit it as output. Forward only. + repeated sfixed32 first_gen_tokens = 9; + // One entry per beam; the length must equal the beam width. Required when beam_width > 1 (the + // generation side initializes cum_logprob from it). Forward only. + repeated FirstTokenLogprob first_gen_logprobs = 10; + // One vocabulary-sized vector per beam; inline only; gated by Capabilities.disagg.first_gen_logits. + // Forward only. + repeated InlineTensor first_gen_logits = 11; + // Speculative draft tokens from the context side. Forward only. + repeated sfixed32 draft_tokens = 12; + // When set, the generation leg must be sent and replays the suffix starting at this prompt position. + // Frontend-readable (orchestration). + optional uint32 remote_tail_start = 13; + // Multimodal prefill/decode layout. Forward only. + MultimodalHandoff multimodal = 14; + // Consistency digest of the two legs: SHA-256 (32 B) computed by the context host core over the + // context request, using the field allowlist and TLV canonical encoding selected by digest_version. + // The generation host core recomputes it before acceptance and rejects a mismatch with + // HANDOFF_INVALID. The engine is not involved. Required for context-first (empty in the + // generation-first rendezvous subset). Forward only. + bytes request_digest = 15; + // Engine-specific handoff state that the protocol does not interpret (the only opaque engine field, + // declared by Capabilities.disagg.uses_engine_state). Forward only. + bytes engine_state = 16; + // Validity from CONTEXT_DONE (milliseconds, judged by the context engine's clock); on expiry the + // context side reclaims the KV. Required for context-first (0 in the generation-first rendezvous + // subset). Frontend-readable. + uint32 expires_after_ms = 17; + // Tokens the generation leg must use when the engine rewrote the prompt (media mode); same as + // PromptInfo.expanded_prompt_tokens. Unset = not rewritten. The generation leg uses it as + // prompt_tokens. Frontend-readable. + TokenSeq expanded_prompt_tokens = 18; + // Field 19 is retired: integrity is carried by the enclosing SignedHandoff. The number is not reused. + reserved 19; + reserved "integrity"; + // Effective max_tokens of the context engine. Required for context-first (CONTEXT_DONE); empty in the + // generation-first rendezvous subset. Frontend-readable. + EffectiveMaxTokens effective_max_tokens = 20; + // Version of the allowlist and canonical encoding used for request_digest (logical u16, 1-65535; this + // contract defines version 1). Required for context-first (0 in the generation-first rendezvous + // subset). Forward only. + uint32 digest_version = 21; + // Ticket issued by the context host that the generation-first rendezvous subset must carry verbatim. + // Forward only. + RendezvousTicket rendezvous_ticket = 22; + + // 30-39 are reserved for disaggregated n > 1 (for example one handoff per sequence with a seq_index); + // 40-49 for encoder disaggregation (encoder -> context handoff). To use them, remove the matching + // reserved line and define the fields. + reserved 30 to 39; + reserved 40 to 49; +} + +// Signed envelope. handoff_bytes = the encoded KvHandoff, written once by the context host; +// mac = HMAC-SHA256(key[key_id], +// "trtllm.engine.v1.SignedHandoff\0" || u32_le(len(key_id)) || utf8(key_id) || handoff_bytes) +// The domain-separation prefix and the key_id binding prevent a MAC from being reused for another +// message type or key. The generation host verifies the MAC over the raw bytes before parsing and never +// re-encodes; frontends and orchestrators only parse read-only copies and forward the whole envelope +// unchanged. When a key is configured, a missing MAC or a failed verification is HANDOFF_INVALID. +// Generation-first rendezvous subset (selected by +// Request.disagg.schedule_style == SCHEDULE_STYLE_GENERATION_FIRST, never guessed from an empty mac): +// handoff_bytes encodes the subset and mac and key_id must be empty; after parsing, the host asserts +// KvHandoff.schedule_style == GENERATION_FIRST and that all non-subset fields are empty, then verifies +// the rendezvous_ticket. +message SignedHandoff { + // Encoded KvHandoff bytes (opaque to forwarders). + bytes handoff_bytes = 1; + // HMAC-SHA256, 32 B; empty when Capabilities.disagg.integrity.scheme is NONE. + bytes mac = 2; + // Signing key id. + string key_id = 3; +} + +// Global identity of a handoff: (ctx_instance_id, disagg_request_id). Used by ReleaseHandoffs. +message HandoffKey { + // Equals KvHandoff.ctx_instance_id. + string ctx_instance_id = 1; + // Equals KvHandoff.disagg_request_id. + fixed64 disagg_request_id = 2; +} diff --git a/contracts/engine/v1/output.proto b/contracts/engine/v1/output.proto new file mode 100644 index 000000000000..6e6544ed0172 --- /dev/null +++ b/contracts/engine/v1/output.proto @@ -0,0 +1,438 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: output frames, hot columns, and row extras. +// +// A frame holds all rows that belong to one session from one engine iteration (or, under backlog, +// from several consecutive iterations merged into one frame). +// +// Hot column encoding: each column is one `bytes` field holding a little-endian, densely packed array of +// fixed-width elements. +// * The element width and type are given in each field's comment. The byte length must equal +// element count * width; otherwise the frontend treats it as a protocol violation. +// * Python readers: convert a whole frame in one batch (on little-endian platforms +// memoryview(col).cast('').tolist() or np.frombuffer(...).tolist()) and slice per row +// afterwards, instead of indexing NumPy scalars row by row. Never keep a memoryview / ndarray slice +// of the whole frame's bytes in a per-request queue: the slowest request would pin the whole frame +// buffer. +// C++ readers: memcpy into an aligned buffer before use (bytes content has no alignment guarantee). +// * Omittable columns: when the whole column is empty (length 0) it takes the value given in its +// comment; when present its length must be n_rows (or the stated length). +// * A frame with n_rows = 0 is valid (it only piggybacks acks / iteration_stats / lora_set_changed). +// Field numbers 22-29 and 35-39 are reserved for future hot columns. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/common.proto"; +import "engine/v1/disagg.proto"; +import "engine/v1/stats.proto"; + +// Output frame. +// Apply order: first acks (they semantically precede every row of the frame), then rows in order (one +// (handle, seq) may have several rows in a frame), and finally lora_set_changed / iteration_stats +// (non-barrier). +message Frame { + // Increases by one per frame within the session, starting at 1; the frontend reports progress with + // it as consumed_frame_seq. + uint64 frame_seq = 1; + // First engine iteration covered by this frame (equals iter_last when not merged; the minimum when + // merged). + uint64 iter_first = 2; + // Last engine iteration covered (the maximum when merged). + uint64 iter_last = 3; + // Time the host wrote the frame (host monotonic nanoseconds); only for same-machine diagnostics. + uint64 emit_time_ns = 4; + // Number of rows; used to check the lengths of the hot columns. + uint32 n_rows = 5; + + // Handle of the request the row belongs to. u64 x n_rows. Not omittable. + bytes handle = 10; + // Sequence number (sampling candidate index or beam index). u32 x n_rows. Omittable: empty = all 0. + bytes seq = 11; + // CSR offsets: row i's tokens are tokens[off[i], off[i+1]). u32 x (n_rows + 1), off[0] = 0, + // off[n_rows] = n_tokens. Not omittable (may be empty when n_rows = 0). + bytes token_offsets = 12; + // New tokens of the row. i32 x n_tokens. Non-streaming: all tokens; beam: all tokens from + // replace_from on. An END_ID terminal row includes end_id itself and a STOP_SEQUENCE terminal row + // includes the matched stop tokens (not trimmed); a CONTEXT_DONE row has no tokens. May be empty. + bytes tokens = 13; + // Finish reason, FinishReason value. u8 x n_rows. Not omittable. + bytes finish = 14; + // Row flags, bitwise OR of RowFlag bits. u16 x n_rows. Not omittable. + bytes row_flags = 15; + // When finish = STOP_SEQUENCE, the smallest index among all matching suffixes in stop.sequences; + // otherwise -1. i32 x n_rows. Omittable: empty = all -1. + bytes stop_index = 16; + // Beam rows: output position from which this row's tokens overwrite; 0xFFFFFFFF = append (non-beam + // rows). u32 x n_rows. Omittable: empty = all 0xFFFFFFFF. + bytes replace_from = 17; + // Cumulative logprob of the sequence up to this row; set when the request asked for logprobs, has + // num_sequences > 1, or uses beams; NaN otherwise. f64 x n_rows. Omittable: empty = all NaN. + bytes cum_logprob = 18; + // Decoding iterations used so far by the request (fewer than tokens with speculation); set on rows of + // requests with output.metrics.decoding_stats, 0 otherwise. u32 x n_rows. Omittable: empty = not + // available. + bytes decoding_iter = 19; + // Prompt tokens served from the prefix cache (may change as prefill advances; the terminal-row value + // is the usage value; independent per sequence when n > 1). u32 x n_rows. Omittable: empty = all 0. + bytes cached_tokens = 20; + // Index of the row's extra in extras[] (valid when row_flags has HAS_EXTRA; 0xFFFFFFFF on other + // rows). u32 x n_rows. Omittable: empty = no extras in this frame. + bytes extra_index = 21; + + // Logprob column group: present as a whole as soon as one row in the frame belongs to a request that + // asked for logprobs (OutputOptions.logprobs); lengths follow n_tokens. Token positions of rows that + // did not ask have sampled = NaN, rank = 0 and zero candidates. All empty = no logprobs in this frame. + // Logprobs of beam rows align with the row's tokens (everything from replace_from on); non-beam + // streaming rows only carry the increment. + // Logprob of the sampled token; NaN = none. f32 x n_tokens. + bytes lp_sampled = 30; + // Full-vocabulary rank of the sampled token (1-based); 0 = not computed. u32 x n_tokens. Omittable: + // empty = all 0. + bytes lp_rank = 31; + // CSR: token j's candidates are [off[j], off[j+1]); the count may differ per token. + // u32 x (n_tokens + 1). Omittable: empty = zero candidates everywhere. + bytes lp_topk_offsets = 32; + // Candidate token ids. i32 x total candidates. + bytes lp_topk_ids = 33; + // Candidate logprobs. f32 x total candidates. + bytes lp_topk_logprobs = 34; + + // Row extras, referenced by extra_index; each extra is referenced by exactly one row. + repeated RowExtra extras = 40; + + // Piggybacked SubmitAcks (ascending batch_seq; they semantically precede every row of this frame). + repeated SubmitAck acks = 50; + // Piggybacked iteration statistics (pushed to one session only; may hold several under backlog). + repeated IterationStats iteration_stats = 51; + // LoRA set deltas (non-barrier; in a merged backlog frame they are in the order they happened and the + // frontend must apply them in sequence). + repeated LoraSetChanged lora_set_changed = 52; + + // 22-29 and 35-39 are reserved for future hot columns; 41-49 for row-extra extensions. + reserved 22 to 29; + reserved 35 to 39; + reserved 41 to 49; +} + +// Row extra. The parts are independent and may appear together (for example, the only row of a +// non-streaming request is both FIRST_ROW and SEQ_FINAL). +// When merged rows are folded together: prompt_info keeps the earlier one; final_info / error / +// handoff keep the later one; tensors' token_range values are merged into one range. +// If PromptLogprobs or TimeBreakdown exceed the per-frame limit SessionLimits.max_frame_bytes, the host +// may split them along start / steps boundaries into consecutive rows of the same (handle, seq) (or +// deliver PromptLogprobs through an out-of-band reference); see PromptLogprobs and TimeBreakdown. +message RowExtra { + // On the first row of a request (the FIRST_ROW row with seq = 0), once per request. Only when + // PromptLogprobs is split because it exceeds max_frame_bytes may continuation rows carry an extra with + // only prompt_logprobs (concatenated by start; FIRST_ROW is not counted again). + PromptInfo prompt_info = 1; + // On the terminal row (SEQ_FINAL) of every sequence, including cancelled and failed terminations. If + // TimeBreakdown is split because it exceeds max_frame_bytes, only the row with the last piece carries + // SEQ_FINAL and the complete FinalInfo (other fields). + FinalInfo final_info = 2; + // Required on a terminal row with finish = ERROR. + ErrorInfo error = 3; + // Required on a row with finish = CONTEXT_DONE (signed envelope built by the context host). + SignedHandoff handoff = 4; + // Segment-wise delivery of output-aligned tensors when streaming: one append-only segment per + // (handle, seq, kind, name). The first row extra of that sequence and kind carries `ref`; later rows + // (including the last step slice on the SEQ_FINAL row) always go here and may omit `ref`, carrying + // only token_range. + repeated OutputTensor tensors = 5; +} + +// ============================================================================ +// First-row extra: PromptInfo +// ============================================================================ + +// Prompt logprobs in CSR form; columns use the same encoding as Frame hot columns (little-endian, +// densely packed, fixed width). +// Full mode (cached_prefix = BYPASS_REUSE, or no prefix cache hit): +// * start = 0 and the total count = prompt_len; +// * entry i (i in [0, count)) is the logprob of the token at position start + i + 1 under the logits +// at position start + i; when complete, ids = prompt[1:] + [first generated token], so the last +// entry is the first generated token. +// Partial mode (Capabilities.logprobs.prompt.cached_prefix = PARTIAL and a prefix cache hit): +// * only the non-cached part is reported; the first piece's start gives the prompt position of its +// first entry, and the total count = prompt_len - first start; +// * the cached part must not be padded with NaN posing as valid values. +// Oversized PromptLogprobs: if the serialized PromptLogprobs exceeds SessionLimits.max_frame_bytes, the +// host must not write an oversized frame. Depending on the session's delivery capabilities it uses one +// of: +// 1. Continuation pieces: split along prompt positions into pieces of at most max_frame_bytes, each +// with its own (start, count) and inline columns; every piece except the last sets has_more = true, +// and the frontend concatenates them in start order. +// 2. Out-of-band reference: leave the inline columns empty and set payload_ref (ShmLocation or +// BlobLocation holding the serialized PromptLogprobs, which the frontend reads back and parses; +// counted against session_blob_quota_bytes). +message PromptLogprobs { + // Start prompt position of this piece (0 = complete or first piece; > 0 = PARTIAL offset or the + // offset of a continuation piece). + uint32 start = 1; + // Number of entries in this piece (used to check the column lengths; with payload_ref it still gives + // the total number of entries covered). + uint32 count = 2; + // Target token ids evaluated (positions start + 1 .. start + count). i32 x count. Not omittable in + // inline mode when count > 0. + bytes ids = 3; + // Logprob of each target token. f32 x count. Not omittable in inline mode when count > 0. + bytes sampled = 4; + // Full-vocabulary rank of each target token (1-based); 0 = not computed. u32 x count. Omittable: + // empty = all 0. + bytes rank = 5; + // CSR offsets: entry i's top-k candidates are [off[i], off[i+1]). u32 x (count + 1). Omittable: + // empty = zero candidates everywhere. + bytes topk_offsets = 6; + // Top-k candidate token ids. i32 x total candidates. + bytes topk_ids = 7; + // Top-k candidate logprobs. f32 x total candidates. + bytes topk_logprobs = 8; + // Split flag: true when a following row carries another PromptLogprobs piece with a higher start + // (default false = complete or last piece). + bool has_more = 9; + // Optional out-of-band location: when an oversized PromptLogprobs is not inlined, it holds the + // serialized bytes of a regular PromptLogprobs (fields 1-8 only). When set, fields 3-8 of this message + // must be empty, and the session blob ownership and ReleaseBlobs rules apply. + oneof payload_ref { + ShmLocation shm = 10; + BlobLocation blob = 11; + } +} + +// Chunked-context prefill counters (mirrors LlmResult.ctx_computed_tokens / ctx_first_begin / ctx_num_chunks). +message ContextChunkStats { + uint32 computed_tokens = 1; + optional int32 first_begin = 2; + uint32 num_chunks = 3; +} + +// First-row extra: attached to the first row of a request (the FIRST_ROW row with seq = 0), once per +// request. +message PromptInfo { + // Engine-internal request id (ctx_request_id under disaggregation), only for log and perf + // correlation. Always set. + uint64 engine_request_id = 1; + // Prompt length actually prefilled by the engine (after placeholder expansion in media mode). Always + // set. + uint32 prompt_len = 2; + // Prompt tokens as rewritten by the engine: returned only when media mode rewrote the prompt and + // either phase = CONTEXT_ONLY or the request set output.return_expanded_prompt. For CONTEXT_ONLY it + // equals KvHandoff.expanded_prompt_tokens. Empty = not rewritten or not requested. + repeated sfixed32 expanded_prompt_tokens = 3; + // Effective generation limit (tokens): the engine-derived value, or the requested value after + // clamping. Always set. + uint32 max_tokens = 4; + // True when the requested stop.max_tokens exceeded the engine-derived limit and was clamped (the + // native warning made explicit). + bool max_tokens_clamped = 5; + // Prompt logprobs; set only when the request set output.prompt_logprobs. + PromptLogprobs prompt_logprobs = 6; + // Context-leg usage learned by the generation engine together with the KV in generation-first mode + // (set only when phase = GENERATION_ONLY and schedule_style = GENERATION_FIRST). + PrefillUsage prefill_usage = 7; + // Prompt-aligned tensors (CONTEXT_LOGITS / ENCODER_OUTPUT / ADDITIONAL_CONTEXT). + repeated OutputTensor tensors = 8; + // Chunked-context prefill counters when reported on the first row. + ContextChunkStats ctx_chunks = 9; +} + +// ============================================================================ +// Terminal-row extra: FinalInfo +// ============================================================================ + +// Per-sequence token usage. +// completion_tokens includes the end_id token of an END_ID termination and the matched stop tokens of a +// STOP_SEQUENCE termination; on the generation leg it includes the first token; it is 0 on a +// CONTEXT_DONE row (the first token is counted on the generation leg). The frontend aggregates +// request-level usage. +message Usage { + uint32 prompt_tokens = 1; + uint32 completion_tokens = 2; + uint32 cached_tokens = 3; +} + +// Decoding step statistics as counted by the engine (small; always carried with SEQ_FINAL). +message DecodingStats { + uint32 decoding_iter = 1; + float avg_decoded_tokens_per_iter = 2; +} + +// Speculative decoding counters of this sequence (independent per sequence when n > 1; mirrors the +// native per-request speculative decoding counters). Carried only when the engine uses speculation and +// the sequence had drafts. +message SpecDecodingStats { + // Number of drafts per draft position. + repeated uint32 drafted_per_pos = 1; + // Number of accepted drafts per draft position (same length as drafted_per_pos). + repeated uint32 accepted_per_pos = 2; + uint64 total_drafted = 3; + uint64 total_accepted = 4; +} + +// Per-request KV block statistics (mirrors native RequestPerfMetrics::KvCacheMetrics). +message KvBlockStats { + uint32 allocated = 1; + uint32 new_blocks = 2; + uint32 reused = 3; + uint32 missed = 4; +} + +// Request-level performance timings and KV statistics (duration form of native RequestPerfMetrics). +// Every *_us field is measured from t0 = the time the host accepted the request, in microseconds, so no +// clock synchronization across processes is needed. +message RequestTiming { + // Absolute host monotonic nanoseconds of t0; only for same-machine diagnostics, not comparable across + // machines. + uint64 host_accept_ns = 1; + // First scheduling (queueing time = first_scheduled - accept), microseconds after t0. + uint64 first_scheduled_us = 3; + // First output token, microseconds after t0. + uint64 first_token_us = 4; + // Last output token, microseconds after t0. + uint64 last_token_us = 5; + // Start / end of the disaggregated KV transfer, microseconds after t0; unset when not disaggregated or + // no transfer happened. + optional uint64 kv_transfer_start_us = 6; + optional uint64 kv_transfer_end_us = 7; + // Bytes moved by the disaggregated KV transfer; unset when no transfer happened. + optional uint64 kv_transfer_bytes = 8; + // Request-level KV block allocation and reuse counts. + KvBlockStats kv_blocks = 9; + // reused / (reused + missed); 0 when the denominator is 0. + float kv_cache_hit_rate = 10; + // First engine iteration the request took part in (relates to IterationStats.iter and + // Frame.iter_first). + uint64 first_iter = 11; + // Last engine iteration the request took part in. + uint64 last_iter = 12; + + reserved 2; + reserved "queue_us"; +} + +// Fine-grained timing of one step or one prefill chunk. +// CPU timestamps are converted to microsecond durations relative to t0 (host_accept_ns); GPU durations +// are in milliseconds (same as native). +message StepTiming { + // Decoding iteration number (set for steps; may be unset for ctx_chunks). + optional uint64 iter = 1; + uint64 forward_start_us = 2; + uint64 forward_end_us = 3; + uint64 sample_start_us = 4; + uint64 sample_end_us = 5; + optional double gpu_forward_ms = 6; + optional double gpu_sample_ms = 7; + uint64 token_us = 8; +} + +// Per-step timing details (size grows linearly with steps; carried on the terminal row only when +// metrics.time_breakdown = true). +// Oversized TimeBreakdown: if steps[] makes the frame exceed SessionLimits.max_frame_bytes, the host may +// split it into consecutive rows of the same (handle, seq). Earlier pieces set has_more = true and their +// rows do not carry SEQ_FINAL; steps_offset gives each piece's start index in the full steps list and +// the frontend concatenates them in order. The last piece sets has_more = false and comes with SEQ_FINAL +// and the complete FinalInfo. +message TimeBreakdown { + repeated StepTiming steps = 1; + repeated StepTiming ctx_chunks = 2; + // Total GPU forward / sample time of the context phase (milliseconds, summed over chunks). + optional double ctx_gpu_forward_ms = 3; + optional double ctx_gpu_sample_ms = 4; + // Start index of this piece's steps[] when split (default 0). + uint32 steps_offset = 5; + // Split flag: true when a following row carries another TimeBreakdown piece (default false = complete + // or last piece). + bool has_more = 6; +} + +// Terminal-row extra: attached to the terminal row (SEQ_FINAL) of every sequence, including cancelled +// and failed terminations. +message FinalInfo { + // Token usage of this sequence. Always carried. + Usage usage = 1; + // Context-leg usage: required on a CONTEXT_DONE row; also returned on the generation leg of + // generation-first. + PrefillUsage prefill_usage = 2; + // Engine decoding statistics. Always carried. + DecodingStats decoding = 3; + // Speculative decoding counters; carried when speculation is on and the sequence had drafts. + SpecDecodingStats spec = 4; + // Request-level performance timings and KV block statistics; carried with metrics.perf or + // Capabilities.metrics.forced_perf. + RequestTiming timing = 5; + // Per-step timing details; carried with metrics.time_breakdown. + TimeBreakdown time_breakdown = 6; + // Whole tensors delivered at once: only GENERATION_LOGITS / ADDITIONAL_GENERATION of non-streaming + // requests, and ROUTED_EXPERTS (delivered at once by default). For streaming requests every + // output-aligned step slice (including the last step on the SEQ_FINAL row) goes in + // RowExtra.tensors[], never here. + repeated OutputTensor tensors = 7; + // Cancellation source when finish = CANCELLED (frontend CancelBatch, host SHUTDOWN, or + // HANDOFF_RELEASED from a ReleaseHandoffs PENDING_CANCELLED tombstone); CANCEL_REASON_UNSPECIFIED + // otherwise. + CancelReason cancel_reason = 8; + // Diagnostic typed extension; ext_namespace must be "diag". Logs only; the frontend must not depend on + // its semantics. + TypedExtension diag = 9; + // Chunked-context prefill counters when reported on the terminal row. + ContextChunkStats ctx_chunks = 10; +} + +// ============================================================================ +// Output tensors +// ============================================================================ + +// Output tensor kind. +enum OutputTensorKind { + OUTPUT_TENSOR_KIND_UNSPECIFIED = 0; + // Prompt-aligned (PromptInfo.tensors). + OUTPUT_TENSOR_KIND_CONTEXT_LOGITS = 1; + // Output-aligned (FinalInfo.tensors when not streaming; when streaming every step slice, including + // the last one on the SEQ_FINAL row, goes into the append-only segment in RowExtra.tensors). + OUTPUT_TENSOR_KIND_GENERATION_LOGITS = 2; + // Prompt-aligned (PromptInfo.tensors). + OUTPUT_TENSOR_KIND_ENCODER_OUTPUT = 3; + // Aligned to the whole sequence [0, prompt_len + output_len - 1), dtype = I16, -1 = not routed + // because the KV was reused; delivered once on the terminal row by default. + OUTPUT_TENSOR_KIND_ROUTED_EXPERTS = 4; + // Prompt-aligned named additional output (name in Capabilities.outputs.additional_names with + // axis = CONTEXT). + OUTPUT_TENSOR_KIND_ADDITIONAL_CONTEXT = 5; + // Output-aligned named additional output (name in Capabilities.outputs.additional_names with + // axis = GENERATION). + OUTPUT_TENSOR_KIND_ADDITIONAL_GENERATION = 6; + reserved 7; + reserved "OUTPUT_TENSOR_KIND_FIRST_GEN_LOGITS"; +} + +// Output tensor item. +// Streaming output-aligned tensors (GENERATION_LOGITS / ADDITIONAL_GENERATION) use one append-only +// segment per (handle, seq, kind, name), so that num_sequences > 1 and beam_width > 1 do not overwrite +// each other: +// * every step slice of a streaming request (including the last one on the SEQ_FINAL row) is attached +// to RowExtra.tensors[], never to FinalInfo.tensors[]; +// * the first row extra of that (handle, seq, kind, name) carries `ref` (shm segment or blob) and the +// row's token_range; +// * later row extras may omit `ref` and carry only the row's token_range (the frontend reads the shm +// incrementally or calls FetchBlob(blob_id, offset, length)); +// * when rows are merged into one frame, adjacent token_range values of the same (handle, seq) are +// merged into one range; beam rows overwrite the matching positions of the segment from +// replace_from; +// * after the request finishes, the frontend may call ReleaseBlobs(session_id, handles=[handle]) to +// release the segments of all its sequences at once. +message OutputTensor { + // Tensor kind. + OutputTensorKind kind = 1; + // Name of an additional output; required only when kind = ADDITIONAL_CONTEXT / + // ADDITIONAL_GENERATION, and must be registered in Capabilities.outputs.additional_names. + optional string name = 2; + // Half-open token range [begin, end) covered by dimension 0 of the tensor; the coordinate system is + // fixed by kind (see OutputTensorKind). + TokenRange token_range = 3; + // Reference to the data; may be omitted on later rows of a streaming append-only segment (the ref of + // the first row extra applies). + TensorRef ref = 4; +} diff --git a/contracts/engine/v1/request.proto b/contracts/engine/v1/request.proto new file mode 100644 index 000000000000..959e03dc94c7 --- /dev/null +++ b/contracts/engine/v1/request.proto @@ -0,0 +1,552 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: generation request. +// +// Conventions: +// * Every field is per request (per row of a SubmitBatch); there are no batch-wide parameters. +// * One message per request, not columnar; token lists are packed sfixed32. +// * "Default" describes the meaning when unset. Materializing defaults is the frontend's job; the one +// exception is max_tokens, which the engine derives when unset. +// * Every field that changes engine behavior is gated by a capability in `Capabilities`. The frontend +// sends only fields and values the host declared; the host rejects an undeclared field or +// out-of-range value per row before acceptance with UNSUPPORTED. +// * Top-level Request fields are grouped; a grouped sub-message takes the first number of its group. +// Fields inside sub-messages are numbered sequentially. +// * Request fields 74-79 are reserved for disaggregated n > 1 and encoder disaggregation; numbers +// 100 and above are left for later minor versions. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/common.proto"; +import "engine/v1/disagg.proto"; + +// One engine generation request. +message Request { + // Request handle within the session (assigned by the frontend, u64). Must remain unique for the + // lifetime of the session (never reused after REQUEST_DONE or rejection, so delayed blob releases + // cannot release blobs belonging to a later request). Routing key. Required (0 is a valid value). + uint64 handle = 1; + // Frontend's human-readable id (<= 128 B); only for logs, traces and error echo, never for routing or + // deduplication. Default empty. + string request_id = 2; + // Input tokens (already rendered and tokenized). In media mode they contain unexpanded placeholders; + // in preprocessed mode they are already expanded. For GENERATION_ONLY this is + // KvHandoff.expanded_prompt_tokens if present, otherwise the user prompt. Required (non-empty). + repeated sfixed32 prompt_tokens = 3; + // Encoder input tokens of an encoder-decoder model; empty = none. Capability: + // Capabilities.model.is_encoder_decoder. + repeated sfixed32 encoder_input_tokens = 4; + // Phase; default AGGREGATED. GENERATION_ONLY must carry disagg.handoff; other phases must not. + // Capability: Capabilities.disagg.phases. + Phase phase = 5; + // true: emit rows per iteration at the engine's streaming cadence; false (default): emit one row only + // when the sequence terminates (full output). + bool streaming = 6; + // Time the request had already waited before reaching this host (microseconds). The engine uses it + // for admission ordering (older first); it does not move the zero point of perf timings. Unset = the + // host acceptance time is the arrival time. Not set on the generation leg of generation-first. + // Capability: Capabilities.sched.queue_age. + optional uint64 queue_age_us = 7; + + // Multimodal input; unset = mode NONE. + MultimodalInput mm = 10; + // Sampling; unset = all engine defaults (num_sequences = beam_width = 1). + SamplingParams sampling = 20; + // Stop conditions; end_id is required, so this sub-message is always present. + StopParams stop = 40; + // Output options; unset = no optional outputs. + OutputOptions output = 47; + // Field 52 (thinking_budget) is retired: the thinking budget is implemented by the client layer + // (CancelBatch, then resubmission with the end-of-thinking tag appended). The number is not reused. + reserved 52; + reserved "thinking_budget"; + // Batched logits processors registered at engine initialization, by name; each name must be in + // Capabilities.proc.registered_names. Default empty. + repeated string logits_processors = 53; + // Guided decoding (at most one kind); unset = none. Capability: Capabilities.guided.kinds. + GuidedDecoding guided = 54; + // LoRA adapter reference; unset = base model. Capability: Capabilities.lora. + LoraRef lora = 55; + // Scheduling. + SchedulingParams sched = 60; + // KV cache policy. + KvParams kv = 66; + // W3C trace context; unset = none. + TraceContext trace = 69; + // Disaggregated serving fields; must not be set when phase = AGGREGATED. + DisaggParams disagg = 70; + + // 74-79 are reserved for disaggregated n > 1 and encoder disaggregation. + reserved 74 to 79; +} + +// ============================================================================ +// Multimodal +// ============================================================================ + +// Multimodal mode; a request uses exactly one. +enum MultimodalMode { + // No multimodal input. Default. + MULTIMODAL_MODE_NONE = 0; + // Media mode: the frontend only passes media references; the engine fetches and decodes media, runs + // HF preprocessing and expands placeholders. The expanded length is reported in + // PromptInfo.prompt_len of the first row. + MULTIMODAL_MODE_MEDIA = 1; + // Preprocessed mode: the frontend runs the input processor and sends the expanded tokens, the layout + // and the model input tensors (the TensorRT-LLM default). + MULTIMODAL_MODE_PREPROCESSED = 2; +} + +// One media item in media mode (in order of appearance). +message MediaItem { + // Modality; must be in Capabilities.mm.modalities. + Modality modality = 1; + // Media source; the branch must be in Capabilities.mm.media_sources. + oneof source { + // URL (http(s), file or data URL), fetched by the engine. + string url = 2; + // Inline media bytes (bounded by SessionLimits.max_request_bytes; larger media go through a blob). + bytes data = 3; + // Uploaded first with BlobService.UploadBlob, then referenced. + BlobLocation blob = 4; + } + // MIME type (for example "image/png"); empty = sniffed by the engine. + string mime_type = 5; + // Media uuid (used for the KV reuse hash); unset = the engine hashes the content. + optional string uuid = 6; + // Index of the placeholder in the prompt this item fills (zero-based). + uint32 placeholder_index = 7; +} + +// One multimodal item in preprocessed mode (KV reuse hash and position in the expanded prompt). +message MultimodalItem { + // KV reuse hash (8 x int32 = 32 B). + bytes hash = 1; + optional string uuid = 2; + // Start position in the expanded prompt. + uint32 position = 3; + // Length (tokens). + uint32 length = 4; + // Segmented items: start position of each run (same length as run_lengths); empty = one run. + repeated uint32 run_positions = 5; + repeated uint32 run_lengths = 6; +} + +// Preprocessed mode: one output of the input processor (qualified path plus typed value). +message ModelInput { + // Qualified path (for example "image.pixel_values", "mrope_config.mrope_position_deltas", + // "multimodal_embedding", "mm_bidirectional_blocks"). It must be registered in + // Capabilities.mm.model_input_names, and the value type must match the registered kind / dtype / + // rank. + string path = 1; + oneof value { + TensorRef tensor = 2; + I64List i64_list = 3; + F64List f64_list = 4; + bool bool_value = 5; + int64 i64_value = 6; + double f64_value = 7; + string string_value = 8; + } +} + +// Precomputed embedding (skips the vision encoder); mutually exclusive with model_inputs for the same +// item. +message PrecomputedEmbedding { + // Index of the multimodal item (zero-based). + uint32 item_index = 1; + // Embedding tensor; may be a CUDA IPC or blob reference. + TensorRef tensor = 2; +} + +// Reference to one item of the native MultimodalItemMetadata. +message MultimodalItemRef { + // Modality name (native string, for example "image"). + string modality = 1; + // Index within that modality. + uint32 index = 2; +} + +// Partition of a field along the item axis. +message MultimodalPartition { + string modality = 1; + // A ModelInput.path. + string field = 2; + // Item axis; unset = native default. + optional uint32 item_axis = 3; + // Length of each item along the item axis. + repeated uint32 item_lengths = 4; +} + +// Preprocessed mode: native MultimodalItemMetadata. Must be complete before admission; required when +// Capabilities.mm.item_metadata is true. +message MultimodalItemMetadata { + // Items in prompt order. + repeated MultimodalItemRef item_refs = 1; + // Encoder token length of each item; unset = none. + U32List encoder_token_lengths = 2; + // Output embedding length of each item; unset = none. + U32List output_embedding_lengths = 3; + repeated MultimodalPartition partitions = 4; +} + +// Multimodal input. Capability: Capabilities.mm. +message MultimodalInput { + // Mode; default NONE. Must be in Capabilities.mm.modes. + MultimodalMode mode = 1; + // Media items in media mode (mode = MEDIA). + repeated MediaItem media = 2; + // media_io_kwargs as a typed extension: ext_namespace must be "mm.io"; keys have two levels, + // ".", and must be registered in Capabilities.ext. + TypedExtension io_options = 3; + // mm_processor_kwargs as a typed extension: ext_namespace must be "mm.processor"; keys must be + // registered in Capabilities.ext. In preprocessed mode the frontend consumes them itself and does not + // send them. + TypedExtension processor_options = 4; + // Preprocessed mode: hash and position of each item. + repeated MultimodalItem items = 5; + // Preprocessed mode: input processor outputs. + repeated ModelInput model_inputs = 6; + // Precomputed embeddings. Capability: Capabilities.mm.precomputed_embeddings. + repeated PrecomputedEmbedding embeddings = 7; + // Preprocessed mode: item metadata. + MultimodalItemMetadata item_metadata = 8; +} + +// ============================================================================ +// Sampling +// ============================================================================ + +// Source of logprob values. +enum LogprobsMode { + // Unset = engine default (native LogprobMode.RAW). + LOGPROBS_MODE_UNSPECIFIED = 0; + // Raw logits. + LOGPROBS_MODE_RAW = 1; + // After sampling transforms (temperature, top-k/p, ...). + LOGPROBS_MODE_PROCESSED = 2; +} + +// One entry of a sparse logit bias. +message LogitBias { + sfixed32 token_id = 1; + float bias = 2; +} + +// Sampling parameters. All scalars are optional: unset = the engine default declared as default_value +// in the matching Capabilities.sampling / Capabilities.beam ParamDomain. The protocol only distinguishes +// set from unset; materializing defaults is the frontend's job. Accepted values of each parameter are +// given by its ParamDomain. +message SamplingParams { + // Number of sequences the engine generates in sampling mode (= native best_of); the frontend picks the + // best by cum_logprob. 0 or unset = 1. Bounded by Capabilities.sampling.max_num_sequences; under + // disaggregation any value > 1 is rejected before acceptance with UNSUPPORTED_IN_DISAGG. + uint32 num_sequences = 1; + // > 1 selects beam search, in which case num_sequences must be 1. 0 or unset = 1. Domain: + // Capabilities.beam.beam_width (TensorRT-LLM declares VALUES{max_beam_width}). + uint32 beam_width = 2; + // Number of beams returned in beam mode (native num_return_sequences); unset = beam_width. + optional uint32 num_return_beams = 3; + // Per-iteration beam widths (non-decreasing); empty = not used. Capability: + // Capabilities.beam.width_array. + repeated uint32 beam_width_array = 4; + // >= 0; 0 = greedy. + optional float temperature = 5; + // 0 = no limit. + optional uint32 top_k = 6; + // In (0, 1]. + optional float top_p = 7; + // Top-p decay factor. Capability: Capabilities.sampling.top_p_decay. + optional float top_p_decay = 8; + // Lower bound of top-p decay. Capability: Capabilities.sampling.top_p_min. + optional float top_p_min = 9; + // Token id that resets top-p decay. Capability: Capabilities.sampling.top_p_reset_ids. + optional sfixed32 top_p_reset_ids = 10; + // In [0, 1]. + optional float min_p = 11; + // Unset = engine default (native 0); reproducibility scope is Capabilities.sampling.seed_scope. + optional uint64 seed = 12; + // Repetition penalty. + optional float repetition_penalty = 13; + // Presence penalty. + optional float presence_penalty = 14; + // Frequency penalty. + optional float frequency_penalty = 15; + // Length (tokens) of the prompt prefix ignored when counting penalties. + optional uint32 prompt_ignore_length = 16; + // Size of n-grams that must not repeat. + optional uint32 no_repeat_ngram_size = 17; + // Beam length penalty. Capability: Capabilities.beam.length_penalty. + optional float length_penalty = 18; + // HF tri-state integer semantics kept as-is (for example 0 / 1 / -1). Capability: + // Capabilities.beam.early_stopping. + optional int32 early_stopping = 19; + // Beam diversity. Capability: Capabilities.beam.diversity_rate. + optional float beam_search_diversity_rate = 20; + // Sparse logit bias. The frontend converts both the HTTP logit_bias and the LLM API dense + // embedding_bias (its non-zero entries) into it. At most Capabilities.sampling.logit_bias.max_entries + // entries; a token must not repeat. + repeated LogitBias logit_bias = 21; + // Whether logprobs come from raw or processed logits; must be in Capabilities.logprobs.modes. + LogprobsMode logprobs_mode = 22; +} + +// ============================================================================ +// Stop conditions +// ============================================================================ + +// Stop conditions. Handled by the frontend and not part of the protocol: include_stop_str_in_output +// (trimmed by stop_index), stop-string text matching, all detokenization options, +// truncate_prompt_tokens, exclude_input_from_output, and similar. +message StopParams { + // Generation limit (>= 1, including the disaggregated first token). Unset = the engine derives + // the limit from its effective sequence-length constraints. A value above that limit is clamped + // and flagged in PromptInfo.max_tokens_clamped; a derived limit <= 0 is CONTEXT_TOO_LONG. On the + // disaggregated generation leg, KvHandoff.effective_max_tokens takes precedence. + optional uint32 max_tokens = 1; + // Minimum number of generated tokens (suppresses end_id and stop sequences); unset = engine default + // (native 1). Domain: Capabilities.stop.min_tokens. + optional uint32 min_tokens = 2; + // EOS token, required (materialized by the frontend; natively tokenizer.eos_token_id). Unset is + // rejected before acceptance with INVALID_ARGUMENT (field = "stop.end_id"). With ignore_eos = false, + // sampling it ends the sequence with END_ID and the token is reported as the last output token. + optional sfixed32 end_id = 3; + // Padding token; unset = end_id. + optional sfixed32 pad_id = 4; + // Ignore end_id only (it no longer stops the sequence); stop sequences are unaffected. The native + // behavior of also clearing stop sequences is implemented by the frontend not sending them. + bool ignore_eos = 5; + // Stop sequences, assembled in native order: first stop_token_ids (each of length 1), then the + // tokenized stop strings; extra EOS tokens from generation_config are also added with length 1. A + // match ends with STOP_SEQUENCE and stop_index = the smallest index among all matching suffixes; the + // engine does not trim the matched tokens. At most Capabilities.stop.max_sequences entries, each at + // most max_sequence_len long. + repeated TokenSeq sequences = 6; + // Bad-word sequences (tokenized bad strings plus bad_token_ids). Capability: + // Capabilities.stop.bad_sequences. + repeated TokenSeq bad_sequences = 7; +} + +// ============================================================================ +// Output options +// ============================================================================ + +// Which large output tensors to return. +message TensorOutputRequest { + // CONTEXT_LOGITS, returned in PromptInfo.tensors of the first row. Capability: + // Capabilities.outputs.context_logits. + bool context_logits = 1; + // GENERATION_LOGITS: once on the terminal row when not streaming; an append-only segment when + // streaming. Capability: Capabilities.outputs.generation_logits. + bool generation_logits = 2; + // ENCODER_OUTPUT, returned on the first row. Capability: Capabilities.outputs.encoder_output. + bool encoder_output = 3; + // ROUTED_EXPERTS (whole sequence, int16, once on the terminal row). Capability: + // Capabilities.outputs.routed_experts. + bool routed_experts = 4; + // Names of ADDITIONAL_CONTEXT outputs; each must be registered in Capabilities.outputs.additional_names + // with axis = CONTEXT. + repeated string additional_context = 5; + // Names of ADDITIONAL_GENERATION outputs; each must be registered in + // Capabilities.outputs.additional_names with axis = GENERATION. + repeated string additional_generation = 6; +} + +// Metrics switches. +message MetricsRequest { + // Terminal row carries RequestTiming; the host may force it on (Capabilities.metrics.forced_perf). + bool perf = 1; + // Terminal row carries per-step timings (TimeBreakdown). + bool time_breakdown = 2; + // Every row carries the decoding_iter column and the terminal row carries speculative decoding + // counters. + bool decoding_stats = 3; +} + +// Output options. +message OutputOptions { + // Unset = no logprobs; 0 = only the logprob (and rank) of the sampled token; k = plus top-k + // candidates. Bounded by Capabilities.logprobs.max_top_k. + optional uint32 logprobs = 1; + // Whether to compute the full-vocabulary rank of the sampled token; unset = true; false leaves the + // rank column 0 (not computed). Capability: Capabilities.logprobs.rank. + optional bool logprob_rank = 2; + // Prompt logprobs top-k (same values as `logprobs`), returned in PromptInfo.prompt_logprobs of the + // first row. Capability: Capabilities.logprobs.prompt. + optional uint32 prompt_logprobs = 3; + // Large tensors. + TensorOutputRequest tensors = 4; + // Metrics. + MetricsRequest metrics = 5; + // Ask the first row to return the prompt tokens as rewritten by the engine + // (PromptInfo.expanded_prompt_tokens). Requires MEDIA in Capabilities.mm.modes. Default false. + bool return_expanded_prompt = 6; +} + +// ============================================================================ +// Guided decoding and LoRA +// ============================================================================ + +// List of choices (a oneof cannot hold a repeated field directly). +message ChoiceList { + repeated string choices = 1; +} + +// Guided decoding, at most one kind; the branch must be in Capabilities.guided.kinds. A grammar +// compilation failure is INVALID_ARGUMENT (possibly after acceptance). +message GuidedDecoding { + oneof kind { + // JSON schema text (the frontend normalizes dict / BaseModel inputs into a JSON string). + string json_schema = 1; + // Any JSON object (the value must be true). + bool json_object = 2; + string regex = 3; + string ebnf_grammar = 4; + string structural_tag = 5; + ChoiceList choice = 6; + } +} + +// Adapter reference. With a path, the engine loads the adapter from that path on first use +// (Capabilities.lora.path_loading). Without a path, the adapter must already be preloaded with +// LoraLoad, otherwise LORA_NOT_LOADED. The same adapter_id with a different path is LORA_CONFLICT. +message LoraRef { + uint64 adapter_id = 1; + string name = 2; + optional string path = 3; + LoraFormat format = 4; +} + +// ============================================================================ +// Scheduling, KV cache and tracing +// ============================================================================ + +// One (agent_type, node_id) entry of an agent tree path (native AgentHierarchy = List[Tuple[str, int]]). +message AgentHierarchyNode { + string agent_type = 1; + // Node id (not the depth). + int64 node_id = 2; +} + +// Scheduling parameters. +message SchedulingParams { + // Waiting-queue priority in [0, 1], higher first (native float scale); unset = 0.5. Takes effect only + // when Capabilities.sched.priority.effective. Capability: Capabilities.sched.priority. + optional float priority = 1; + // Target a specific attention DP rank; unset = no target. Capability: Capabilities.sched.dp_targeting. + optional uint32 attention_dp_rank = 2; + // Whether the request may be moved to another rank (name and default follow the native + // SchedulingParams); unset = true. + optional bool attention_dp_relax = 3; + // Agent tree path from the root to this request; empty = none. Capability: + // Capabilities.sched.agent_hierarchy. + repeated AgentHierarchyNode agent_hierarchy = 4; + // Sub-agent affinity id (its signature was already verified by the frontend; the session is a trusted + // channel). Capability: Capabilities.sched.subagent_affinity. + optional string subagent_affinity_id = 5; + // Multi-turn conversation routing / cache affinity id (non-empty). Capability: + // Capabilities.sched.conversation_id. + optional string conversation_id = 6; +} + +// KV offload transfer mode; values equal the native C++ KvCacheTransferMode. +enum KvTransferMode { + KV_TRANSFER_MODE_DRAM = 0; + KV_TRANSFER_MODE_GDS = 1; + KV_TRANSFER_MODE_POSIX_DEBUG_FALLBACK = 2; +} + +// Retention policy of one token range (native TokenRangeRetentionConfig). +message TokenRangeRetention { + uint32 token_start = 1; + // Exclusive; unset = to the end of the sequence. + optional uint32 token_end = 2; + // Priority in [0, 100]; higher is less likely to be evicted (native default 35). The proto3 zero value + // 0 is valid, so the frontend must materialize the default explicitly. + uint32 priority = 3; + // How long (milliseconds) the blocks stay at this priority; unset = no expiry. + optional uint32 duration_ms = 4; +} + +// KV block eviction priority and duration (native KvCacheRetentionConfig). Capability: +// Capabilities.kv.retention. +message KvRetention { + repeated TokenRangeRetention ranges = 1; + // Priority of decode-phase blocks in [0, 100] (the frontend materializes the native default 35). + uint32 decode_priority = 2; + optional uint32 decode_duration_ms = 3; + KvTransferMode transfer_mode = 4; + // Offload directory (GDS / POSIX modes). + optional string directory = 5; +} + +// One action of kv_hints (native KvHintsEnvelope.actions[]). +message KvHintAction { + string action_id = 1; + string action_type = 2; + string action_version = 3; + // Native dict[str, JsonValue] ("opaque JSON object owned by the action consumer") as canonical JSON + // bytes. + bytes payload = 4; + // Unknown optional fields kept by native extra="allow" (canonical JSON object), passed through + // unchanged; unset = none. + optional bytes extra_fields = 5; +} + +// Typed outer fields of the native KvHintsEnvelope. Admission (version "0.1" only, 64 KiB limit, +// malformed hints ignored and counted) is done by the frontend; the host only enforces +// Capabilities.kv.hints.max_bytes as a backstop (over the limit: row-level INVALID_ARGUMENT). +message KvHints { + string protocol_version = 1; + string message_id = 2; + repeated KvHintAction actions = 3; + optional bytes extra_fields = 4; +} + +// KV cache policy. +message KvParams { + // Reuse KV only with requests that have the same salt (<= 256 B). Capability: + // Capabilities.kv.cache_salt. + optional string cache_salt = 1; + // Unset = none. + KvRetention retention = 2; + // Unset = none. + KvHints hints = 3; +} + +// W3C trace context. +message TraceContext { + string traceparent = 1; + string tracestate = 2; +} + +// ============================================================================ +// Disaggregated serving +// ============================================================================ + +// Per-request disaggregated serving fields. +message DisaggParams { + // Global id shared by both legs (KV transfer pairing key, fixed 64-bit). CONTEXT_ONLY + + // CONTEXT_FIRST: may be unset (the engine uses engine_request_id and reports it in + // KvHandoff.disagg_request_id); CONTEXT_ONLY + GENERATION_FIRST: required; GENERATION_ONLY: must + // equal KvHandoff.disagg_request_id of the handoff. Ids generated by a frontend or orchestrator are in + // [2^40, 2^63). A duplicate on the same context instance is ALREADY_EXISTS. + optional fixed64 request_id = 1; + // Scheduling style; required for CONTEXT_ONLY. Capability: Capabilities.disagg.schedule_styles. + ScheduleStyle schedule_style = 2; + // Handoff for GENERATION_ONLY: the SignedHandoff the frontend copied unchanged from the context + // result; for generation-first, the unsigned rendezvous subset (which must contain + // KvHandoff.rendezvous_ticket). An integrity check failure is HANDOFF_INVALID. + SignedHandoff handoff = 3; + // On GENERATION_ONLY, copied by the frontend from the context result (FinalInfo.prefill_usage of the + // context leg); the engine may ignore it (used for echo and consistency checks). + PrefillUsage prefill_usage = 4; + + // 10-19 are reserved for disaggregated n > 1 (an independent disagg_request_id per sequence); 20-29 + // for encoder disaggregation. + reserved 10 to 19; + reserved 20 to 29; +} diff --git a/contracts/engine/v1/session.proto b/contracts/engine/v1/session.proto new file mode 100644 index 000000000000..a85bc1946cf0 --- /dev/null +++ b/contracts/engine/v1/session.proto @@ -0,0 +1,252 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: bidirectional session stream service. +// +// Session model: +// * Each frontend process opens exactly one SessionService.Stream per host; the stream is the route. +// * Opening handshake: the first ClientMessage must be `open` and the first ServerMessage must be +// `accepted`. A major version mismatch closes the stream with gRPC FAILED_PRECONDITION; any other +// message before `open` closes it with INVALID_ARGUMENT. +// * An error of a single request never closes the session: errors before acceptance go to +// SubmitAck.rejected, errors after acceptance are terminal ERROR rows in a Frame. +// * A session closes for only three reasons: a protocol violation (INVALID_ARGUMENT); host shutdown or +// engine death (terminal rows and a SessionNotice are written first); or the slow-consumer hard +// limit / stall timeout (UNAVAILABLE; the host writes no terminal rows and the frontend synthesizes +// SLOW_CONSUMER for its in-flight requests). +// * When the frontend disconnects or cancels the stream, the host cancels all in-flight requests of the +// session, frees the session's blobs, and automatically releases the handoffs of CONTEXT_DONE rows +// still unsent in the outbox (counted in DisaggLoadInfo.released_undelivered_handoffs). Handoffs +// already delivered are not affected. + +syntax = "proto3"; + +package trtllm.engine.v1; + +import "engine/v1/capabilities.proto"; +import "engine/v1/common.proto"; +import "engine/v1/output.proto"; +import "engine/v1/request.proto"; +import "engine/v1/stats.proto"; + +// ============================================================================ +// Session handshake and limits +// ============================================================================ + +// Frontend session preferences. +message SessionPreferences { + // Large-object delivery methods in order of preference (for example [SHM, INLINE, BLOB_FETCH] or + // [CUDA_IPC, SHM, INLINE, BLOB_FETCH]); empty = [INLINE, BLOB_FETCH]. The host picks the delivery + // method by intersecting this list, in order, with Capabilities.tensor.deliveries. + repeated TensorDelivery tensor_delivery = 1; + // Maximum inline tensor size the frontend wants (bytes; 0 = host default); the effective value is + // min(frontend value, Capabilities.tensor.max_inline_bytes). + uint64 max_inline_tensor_bytes = 2; + // Whether this session wants per-iteration statistics pushes (default false). To avoid N duplicate + // copies across frontends, the host pushes only to the earliest-opened session that asked for them. + bool want_iteration_stats = 3; +} + +// First message sent by the frontend. +message SessionOpen { + // Protocol version supported by the frontend (major must be 1; minor is the highest minor the + // frontend supports). + ProtocolVersion version = 1; + // Human-readable frontend label (host name, pid, role, ...), for logs and monitoring only; not used + // for routing. + string frontend_label = 2; + // Frontend preferences. + SessionPreferences want = 3; +} + +// Session limits and flow-control parameters set by the host. +message SessionLimits { + // Maximum rows per frame. + uint32 max_rows_per_frame = 1; + // Maximum bytes per frame (the host leaves enough headroom below the gRPC per-message limit). + uint64 max_frame_bytes = 2; + // Maximum in-flight requests of this session (beyond it rows are rejected with OVERLOADED). + uint32 max_inflight_requests = 3; + // Maximum requests per SubmitBatch. + uint32 max_submit_batch = 4; + // Maximum serialized bytes per SubmitBatch; must be <= the host's gRPC MaxReceiveMessageSize minus + // headroom. + uint64 max_submit_bytes = 5; + // Maximum bytes per Request. Beyond it the frontend must move payloads to UploadBlob first; if it still + // does not fit, the frontend fails the request locally with 400 and does not send it. + uint64 max_request_bytes = 6; + // Maximum inline tensor bytes in effect for this session. + uint64 max_inline_tensor_bytes = 7; + // The frontend reports consumed_frame_seq at least once every this many consumed frames (frame-count + // trigger). + uint32 progress_interval_frames = 8; + // Unconsumed-frame threshold that triggers merging of backlogged frames (merge when emitted frame_seq + // - consumed_frame_seq > this value). + uint32 merge_unconsumed_frames = 9; + // Unconsumed-byte threshold that triggers merging of backlogged frames. + uint64 merge_unconsumed_bytes = 10; + // Soft watermark (unconsumed bytes = outbox bytes + bytes written but not acknowledged): above it new + // submissions are rejected per row with OVERLOADED. + uint64 session_soft_unconsumed_bytes = 11; + // Hard limit: above it the session is judged a slow consumer; in-flight requests are cancelled and the + // session is closed with UNAVAILABLE. + uint64 session_hard_unconsumed_bytes = 12; + // Stall timeout (milliseconds). The timer runs only while there are unacknowledged frames + // (emitted_frame_seq > consumed_frame_seq) and either the outbox is non-empty or the unconsumed bytes + // exceed merge_unconsumed_bytes; if consumed_frame_seq does not advance for this long, the session is + // judged a slow consumer. With an empty outbox and unconsumed bytes <= merge_unconsumed_bytes the timer + // does not run, so infrequent trailing frames do not kill a healthy session. + uint32 session_stall_timeout_ms = 13; + // Blob byte quota in effect for this session. + uint64 session_blob_quota_bytes = 14; + // Timer fallback for standalone Progress messages (milliseconds): when consumed frames remain + // unreported and more than this long has passed since the last report, the frontend must send a + // standalone Progress. 0 = not overridden by the host; the frontend then uses + // max(1, session_stall_timeout_ms / 4). + uint32 progress_interval_ms = 15; +} + +// First message sent by the host. +message SessionAccepted { + // Protocol version in effect for this session: majors must be equal and minor = min(frontend minor, + // host minor). + ProtocolVersion version = 1; + // Session id assigned by the host (unique within the host process; for logs only). + uint64 session_id = 2; + // Full snapshot of the host's current capabilities (the host merges what the engine adapter declares + // with what the host core supports), filtered to the minor in effect. + Capabilities capabilities = 3; + // Session limits and flow-control parameters. + SessionLimits limits = 4; + // Host monotonic clock at handshake (nanoseconds); only for same-machine diagnostics, not comparable + // across machines. + uint64 host_clock_ns = 5; +} + +// ============================================================================ +// Submission, cancellation and consumption progress +// ============================================================================ + +// Batch submission of requests. +// The frontend batches per event-loop turn (no timers), with at most limits.max_submit_batch requests +// and at most limits.max_submit_bytes in total. One batch may mix AGGREGATED, CONTEXT_ONLY and +// GENERATION_ONLY requests; handles must not repeat within a batch. +message SubmitBatch { + repeated Request requests = 1; + // Piggybacked consumption progress (the largest frame_seq the frontend reader has decoded and + // dispatched); 0 = not carried / no frame consumed yet. + uint64 consumed_frame_seq = 2; +} + +// One cancellation item. +message CancelItem { + // Handle of the request to cancel. + uint64 handle = 1; + // Cancellation source (frontends may only send CLIENT_DISCONNECTED, STOP_STRING, POSTPROC_TERMINATE, + // DEADLINE or SHUTDOWN). + CancelReason reason = 2; +} + +// Batch cancellation. Asynchronous and idempotent, with no separate ack (the terminal row of each +// in-flight request is the ack). A no-op for handles that are DONE, CONTEXT_DONE or unknown (the engine +// guarantees that cancelling after CONTEXT_DONE does nothing). +message CancelBatch { + repeated CancelItem cancels = 1; + // true = cancel every in-flight request of this session (cancels[] may then be ignored; all_reason is + // used). + bool all = 2; + // Cancellation reason used when all = true. + CancelReason all_reason = 3; + // Piggybacked consumption progress; 0 = not carried / no frame consumed yet. + uint64 consumed_frame_seq = 4; +} + +// Standalone consumption progress report. +// When a SubmitBatch or CancelBatch is going out, progress is piggybacked on its consumed_frame_seq. +// Otherwise, while consumed frames remain unreported (local_consumed > last_reported), a Progress is +// sent as soon as any one of these holds: +// 1. frames: local_consumed - last_reported >= limits.progress_interval_frames; +// 2. bytes: bytes of frames consumed since the last report >= min(limits.session_soft_unconsumed_bytes +// / 4, limits.merge_unconsumed_bytes / 2) (a term whose limit is 0 is ignored); +// 3. timer: more than progress_interval_ms has passed since the last report (or since the first +// unreported frame arrived), where progress_interval_ms = limits.progress_interval_ms if > 0, else +// max(1, session_stall_timeout_ms / 4). +message Progress { + // Largest Frame.frame_seq the frontend reader has decoded and dispatched. + uint64 consumed_frame_seq = 1; +} + +// ============================================================================ +// Session notices +// ============================================================================ + +// Session-level notice kind (every notice is a frame-merging barrier). +enum SessionNoticeKind { + SESSION_NOTICE_KIND_UNSPECIFIED = 0; + // The host is draining: new submissions are rejected per row with DRAINING, while in-flight requests + // and active handoffs drain normally. + SESSION_NOTICE_KIND_DRAINING = 1; + // The engine died fatally: the host has already written ERROR(ENGINE_DEAD) terminal rows for all + // in-flight requests, then sends this notice and closes the session. + SESSION_NOTICE_KIND_ENGINE_DEAD = 2; + // Static capabilities changed (run-time LoRA set changes are excluded; they use the non-barrier + // LoraSetChanged). Always carries a full capabilities snapshot. + SESSION_NOTICE_KIND_CAPABILITIES_CHANGED = 3; +} + +// Session-level barrier notice. +message SessionNotice { + SessionNoticeKind kind = 1; + // Set only when kind = CAPABILITIES_CHANGED (full snapshot). + Capabilities capabilities = 2; + // Human-readable message (logs only). + string message = 3; +} + +// ============================================================================ +// Stream envelopes and service +// ============================================================================ + +// Frontend -> host message envelope. +message ClientMessage { + oneof payload { + // First message of the session; sent exactly once. + SessionOpen open = 1; + // Batch submission (may piggyback consumed_frame_seq). + SubmitBatch submit_batch = 2; + // Batch cancellation (may piggyback consumed_frame_seq). + CancelBatch cancel_batch = 3; + // Standalone consumption progress report. + Progress progress = 4; + } + + // 10-19 are reserved for upstream session messages of later minor versions. + reserved 10 to 19; +} + +// Host -> frontend message envelope. +message ServerMessage { + oneof payload { + // First reply of the session; sent exactly once. + SessionAccepted accepted = 1; + // Output frame (acks / iteration_stats / lora_set_changed are preferably piggybacked on it). + Frame frame = 2; + // SubmitAck sent alone when no frame is pending (otherwise piggybacked in Frame.acks[]). + SubmitAck submit_ack = 3; + // Session-level barrier notice (DRAINING / ENGINE_DEAD / CAPABILITIES_CHANGED). + SessionNotice notice = 4; + // Iteration statistics pushed alone when no frame is pending (only to the one session that set + // want_iteration_stats). + IterationStats iteration_stats = 5; + // LoRA set delta sent alone when no frame is pending (non-barrier). + LoraSetChanged lora_set_changed = 6; + } + + // 10-19 are reserved for downstream session messages of later minor versions. + reserved 10 to 19; +} + +// Frontend <-> host session service (one bidirectional stream per frontend per host). +service SessionService { + rpc Stream(stream ClientMessage) returns (stream ServerMessage); +} diff --git a/contracts/engine/v1/stats.proto b/contracts/engine/v1/stats.proto new file mode 100644 index 000000000000..05a2071bce9c --- /dev/null +++ b/contracts/engine/v1/stats.proto @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// trtllm.engine.v1: iteration statistics and KV cache events. +// +// Referenced by output.proto (IterationStats piggybacked on Frame.iteration_stats), session.proto +// (standalone IterationStats pushes) and control.proto (GetIterationStats, SubscribeKvEvents, +// GetKvEvents). This file does not import output.proto, session.proto or control.proto, so there is no +// import cycle. + +syntax = "proto3"; + +package trtllm.engine.v1; + +// ============================================================================ +// Iteration statistics +// ============================================================================ + +// KV cache statistics of one iteration (mirrors native C++ executor::KvCacheStats). +message KvCacheStats { + uint32 max_num_blocks = 1; + uint32 free_num_blocks = 2; + uint32 used_num_blocks = 3; + uint32 tokens_per_block = 4; + uint32 alloc_total_blocks = 5; + uint32 alloc_new_blocks = 6; + uint32 reused_blocks = 7; + uint32 missed_blocks = 8; + // reused_blocks / (reused_blocks + missed_blocks); 0 when the denominator is 0. + float cache_hit_rate = 9; +} + +// Static batching scheduler statistics (mirrors native StaticBatchingStats). +message StaticBatchingStats { + uint32 num_scheduled_requests = 1; + uint32 num_context_requests = 2; + uint32 num_ctx_tokens = 3; + uint32 num_gen_tokens = 4; + uint32 empty_gen_slots = 5; +} + +// In-flight batching statistics (mirrors native InflightBatchingStats). +message InflightBatchingStats { + uint32 num_scheduled_requests = 1; + uint32 num_context_requests = 2; + uint32 num_gen_requests = 3; + uint32 num_paused_requests = 4; + uint32 num_ctx_tokens = 5; + uint32 micro_batch_id = 6; + float avg_num_decoded_tokens_per_iter = 7; + // Context tokens read from the KV cache instead of recomputed in this iteration (prefix hits plus + // earlier chunked-prefill chunks). + uint32 num_ctx_kv_tokens = 8; + // Sum of the KV context lengths of the scheduled decode requests. + uint32 num_gen_kv_tokens = 9; + uint32 num_queued_context_requests = 10; + uint32 num_queued_ctx_tokens = 11; + // Number of queued generation-only requests waiting for KV transfer on a disaggregated decode engine, + // and their token budget. + uint32 num_queued_gen_requests = 12; + uint32 num_queued_gen_kv_tokens = 13; + uint32 num_paused_kv_tokens = 14; +} + +// Engine-level speculative decoding statistics of one iteration (mirrors native SpecDecodingStats). +message IterSpecDecodingStats { + uint64 num_draft_tokens = 1; + uint64 num_accepted_tokens = 2; + uint64 num_requests_with_draft_tokens = 3; + // Average tokens produced per step, over requests with at least one draft token. + double acceptance_length = 4; + // Latency of the iteration spent generating draft tokens only (milliseconds). + double iter_latency_ms = 5; + // Fraction of the iteration latency spent on drafting. + double draft_overhead = 6; +} + +// Current execution stage of a request (mirrors native executor::RequestStage). +enum RequestStage { + REQUEST_STAGE_UNSPECIFIED = 0; + REQUEST_STAGE_QUEUED = 1; + REQUEST_STAGE_ENCODER_IN_PROGRESS = 2; + REQUEST_STAGE_CONTEXT_IN_PROGRESS = 3; + REQUEST_STAGE_GENERATION_IN_PROGRESS = 4; + REQUEST_STAGE_GENERATION_COMPLETE = 5; +} + +// Per-iteration, per-request disaggregated serving statistics (mirrors native DisServingRequestStats). +message DisServingRequestStats { + // Total KV cache transfer time (milliseconds). + double kv_transfer_ms = 1; + // Total KV cache transfer size (bytes). + uint64 kv_size_bytes = 2; +} + +// Per-iteration, per-request statistics (mirrors native RequestStats). +// Filled only when Capabilities.metrics.request_stats is true (native enable_iter_req_stats). +message RequestIterationStats { + // Engine-internal request id (same as PromptInfo.engine_request_id). + uint64 engine_request_id = 1; + RequestStage stage = 2; + // Current prefill position under chunked prefill. + uint32 context_prefill_position = 3; + uint32 num_generated_tokens = 4; + float avg_decoded_tokens_per_iter = 5; + bool scheduled = 6; + bool paused = 7; + DisServingRequestStats dis_serving = 8; + uint32 alloc_total_blocks = 9; + uint32 alloc_new_blocks = 10; + uint32 reused_blocks = 11; + uint32 missed_blocks = 12; + float kv_cache_hit_rate = 13; +} + +// Scheduler mode of the PyTorch executor. +enum SchedulerMode { + SCHEDULER_MODE_UNSPECIFIED = 0; + SCHEDULER_MODE_NON_OVERLAP = 1; + SCHEDULER_MODE_OVERLAP = 2; +} + +// Typed statistics of one engine iteration (replaces the native JSON string). +message IterationStats { + // Engine iteration number (relates to Frame.iter_first / iter_last and + // RequestTiming.first_iter / last_iter). + uint64 iter = 1; + // End of this iteration (host monotonic nanoseconds); only for same-machine correlation and relative + // differences. + uint64 timestamp_ns = 2; + // Optional wall-clock time (unix milliseconds) for /metrics-compatible output; 0 = not provided. + uint64 wall_time_unix_ms = 3; + // Iteration latency (milliseconds). In overlap mode it may span about two loop turns (see + // scheduler_mode). + double iter_latency_ms = 4; + // Total time the requests newly activated in this iteration waited in the queue (milliseconds). + double new_active_requests_queue_latency_ms = 5; + + uint32 num_new_active_requests = 6; + uint32 num_active_requests = 7; + uint32 num_queued_requests = 8; + uint32 num_completed_requests = 9; + uint32 max_num_active_requests = 10; + + // Batch-size and token limits in three forms: static configuration, tuner recommendation, and the + // value in effect at run time. + uint32 max_batch_size_static = 11; + uint32 max_batch_size_tuner_recommended = 12; + uint32 max_batch_size_runtime = 13; + uint32 max_num_tokens_static = 14; + uint32 max_num_tokens_tuner_recommended = 15; + uint32 max_num_tokens_runtime = 16; + + // Memory usage (bytes). + uint64 gpu_mem_usage_bytes = 17; + uint64 cpu_mem_usage_bytes = 18; + uint64 pinned_mem_usage_bytes = 19; + + // Sub-statistics; absent when not enabled or not applicable. + KvCacheStats kv = 20; + KvCacheStats cross_kv = 21; + StaticBatchingStats static_batching = 22; + InflightBatchingStats inflight_batching = 23; + IterSpecDecodingStats spec_decoding = 24; + + // Fine-grained per-iteration timings and identification from the PyTorch executor. + optional double host_step_ms = 25; + optional double prev_device_step_ms = 26; + optional double gpu_forward_ms = 27; + SchedulerMode scheduler_mode = 28; + // Rank that produced these statistics (may be unset without attention DP or when aggregated over + // ranks). + optional uint32 rank = 29; + // Per-request statistics of this iteration (present when Capabilities.metrics.request_stats is true). + repeated RequestIterationStats request_stats = 30; + // Optional canonical JSON with per-window / per-pool KV iteration statistics, filled only when the + // engine reports multi-window or tiered-pool statistics. The protocol does not flatten these internal + // pool structures, which change with the KV cache manager. + optional bytes kv_iter_stats_json = 31; +} + +// ============================================================================ +// KV cache events +// ============================================================================ + +// KV event kind: the four native KVCacheEventData event types plus ALL_CLEARED. +enum KvEventKind { + KV_EVENT_KIND_UNSPECIFIED = 0; + KV_EVENT_KIND_CREATED = 1; + KV_EVENT_KIND_STORED = 2; + KV_EVENT_KIND_REMOVED = 3; + KV_EVENT_KIND_UPDATED = 4; + KV_EVENT_KIND_ALL_CLEARED = 5; +} + +// Unique token within a KV block (mirrors native UniqueToken). +message KvUniqueToken { + sfixed32 token_id = 1; + // Extra id that distinguishes the same token_id from different sources (multimodal placeholders, + // LoRA, ...). + uint64 token_extra_id = 2; +} + +// Multimodal key of a KV event (mirrors the native multimodal key serialization). +// hash and uuid may both be present (when the digest hash is preserved) or only one of them. +message KvMmKey { + // Content digest bytes (usually 32 B); empty means no digest, uuid only. + bytes hash = 1; + // Multimodal item uuid; unset = none. + optional string uuid = 2; + // Start offset (tokens) of this multimodal item within the current block. + uint32 start_offset = 3; +} + +// Metadata of one newly stored KV block (mirrors native KVCacheStoredBlockData). +message KvStoredBlock { + // Block hash (fixed 64-bit, native IdType). + fixed64 block_hash = 1; + // Tokens in the block (length usually <= tokens_per_block). + repeated KvUniqueToken tokens = 2; + // LoRA task id; unset = base model. + optional uint64 lora_id = 3; + // Cache salt (Request.kv.cache_salt); unset = none. + optional string cache_salt = 4; + // Cache level (0 = primary GPU pool, 1 = secondary host pool, ...). + int32 cache_level = 5; + // Eviction priority (0-100). + int32 priority = 6; + // Multimodal keys of the block. + repeated KvMmKey mm_keys = 7; +} + +// Payload of KV_EVENT_KIND_CREATED. +message KvEventCreated { + // Number of blocks created per cache level. + repeated uint32 num_blocks_per_cache_level = 1; +} + +// Payload of KV_EVENT_KIND_STORED. +message KvEventStored { + // Hash of the parent block; unset = root block. + optional fixed64 parent_hash = 1; + // Stored blocks in prefix-chain order (the parent of blocks[i] is blocks[i-1]). + repeated KvStoredBlock blocks = 2; +} + +// Payload of KV_EVENT_KIND_REMOVED. +message KvEventRemoved { + repeated fixed64 block_hashes = 1; +} + +// Change of an integer field (mirrors native KVCacheEventDiff). +message KvEventIntDiff { + int32 old_value = 1; + int32 new_value = 2; +} + +// Payload of KV_EVENT_KIND_UPDATED. +message KvEventUpdated { + fixed64 block_hash = 1; + // Cache level change; unset = unchanged. + KvEventIntDiff cache_level = 2; + // Priority change; unset = unchanged. + KvEventIntDiff priority = 3; +} + +// Payload of KV_EVENT_KIND_ALL_CLEARED (explicit marker that the whole pool was cleared). +message KvEventAllCleared {} + +// One KV cache event (mirrors native KVCacheEvent). +message KvEvent { + // Monotonic event id within the engine (resume key for SubscribeKvEvents). + uint64 event_id = 1; + // Sliding window size (0 or the global context window, depending on the KV cache manager + // configuration). + int32 window_size = 2; + // Layer group id of a multi-group KV cache manager; unset = the single default group. + optional int32 layer_group = 3; + // Attention DP rank; unset = attention DP is off or ranks are not distinguished. + optional uint32 dp_rank = 4; + // Event kind (redundant tag; must match the `data` branch). + KvEventKind kind = 5; + // Optional hash algorithm name, set only when it overrides Capabilities.kv.hash_algo for this event. + optional string hash_algo = 6; + // Event payload; corresponds one-to-one to `kind`. + oneof data { + KvEventCreated created = 10; + KvEventStored stored = 11; + KvEventRemoved removed = 12; + KvEventUpdated updated = 13; + KvEventAllCleared all_cleared = 14; + } +} + +// Batch of KV events. +message KvEventBatch { + repeated KvEvent events = 1; + // True when the engine ring buffer overflowed and dropped older events before this delivery because + // they were not consumed in time (a router should refresh its state). + bool truncated = 2; +} diff --git a/cpp/tensorrt_llm/nanobind/CMakeLists.txt b/cpp/tensorrt_llm/nanobind/CMakeLists.txt index 0cb9b25d6804..c689180202a6 100755 --- a/cpp/tensorrt_llm/nanobind/CMakeLists.txt +++ b/cpp/tensorrt_llm/nanobind/CMakeLists.txt @@ -17,6 +17,9 @@ set(TRTLLM_NB_MODULE ${TRTLLM_NB_MODULE} PARENT_SCOPE) +# Native codec of the trtllm.engine.v1 wire, built from its own directory +add_subdirectory(${TRT_LLM_ROOT_DIR}/tensorrt_llm/executor/native engine_wire) + set(SRCS batch_manager/algorithms.cpp batch_manager/bindings.cpp @@ -26,6 +29,7 @@ set(SRCS batch_manager/kvCacheManagerV2Utils.cpp batch_manager/kvCacheManagerV2.cpp common/tllmExceptions.cpp + ${ENGINE_WIRE_SOURCES} executor/bindings.cpp executor/executorConfig.cpp executor/request.cpp @@ -65,6 +69,12 @@ target_include_directories( ${TRTLLM_NB_MODULE} PRIVATE ${PROJECT_SOURCE_DIR}/tensorrt_llm/common/sha256) target_include_directories(${TRTLLM_NB_MODULE} PRIVATE ${TRTLLM_FMHA_PARAMS_GENERATED_INCLUDE_DIR}) +target_include_directories(${TRTLLM_NB_MODULE} + PRIVATE ${ENGINE_WIRE_INCLUDE_DIRS}) +add_dependencies(${TRTLLM_NB_MODULE} engine_wire_proto) +# protobuf's own target: PyTorch's CMake package can define +# protobuf::libprotobuf +target_link_libraries(${TRTLLM_NB_MODULE} PRIVATE libprotobuf) set_property(TARGET ${TRTLLM_NB_MODULE} PROPERTY POSITION_INDEPENDENT_CODE ON) target_link_directories(${TRTLLM_NB_MODULE} PUBLIC diff --git a/cpp/tensorrt_llm/nanobind/bindings.cpp b/cpp/tensorrt_llm/nanobind/bindings.cpp index c9521c76f6a9..07075b257a83 100644 --- a/cpp/tensorrt_llm/nanobind/bindings.cpp +++ b/cpp/tensorrt_llm/nanobind/bindings.cpp @@ -29,6 +29,7 @@ #include #include +#include "engineWire.h" #include "tensorrt_llm/batch_manager/peftCacheManagerConfig.h" #include "tensorrt_llm/common/cudaArchitectures.h" #include "tensorrt_llm/common/quantization.h" @@ -532,6 +533,9 @@ NB_MODULE(TRTLLM_NB_MODULE, m) auto mSuffixAutomaton = mInternal.def_submodule("suffix_automaton", "Suffix automaton internal bindings"); tensorrt_llm::nanobind::suffix_automaton::initBindings(mSuffixAutomaton); + auto mEngineWire = mInternal.def_submodule("engine_wire", "Native codec of the trtllm.engine.v1 wire"); + tensorrt_llm::nanobind::engine_wire::initBindings(mEngineWire); + // NVLS allocators nb::class_(m, "IpcNvlsHandle") .def(nb::init<>()) diff --git a/docker/Dockerfile.multi b/docker/Dockerfile.multi index 8684db91a7ea..3ee91dccaf11 100644 --- a/docker/Dockerfile.multi +++ b/docker/Dockerfile.multi @@ -166,6 +166,7 @@ RUN --mount=type=bind,source=docker/common,target=/opt/docker/common \ FROM ${DEVEL_IMAGE} AS wheel WORKDIR /src/tensorrt_llm +COPY contracts contracts COPY cpp cpp COPY docker docker COPY scripts scripts diff --git a/pyproject.toml b/pyproject.toml index 8d8977dfb1e9..c02c620ae16d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,6 +64,7 @@ exclude = [ "tensorrt_llm/_torch/moe/kernels/rubin/manual_mma_128dp.py", "tensorrt_llm/_torch/moe/kernels/rubin/rubin_contiguous_grouped_blockscaled_gemm_fused_fc12.py", "tensorrt_llm/grpc/openengine/_generated/**", + "tensorrt_llm/contracts/engine/v1/_generated/**", ] diff --git a/requirements.txt b/requirements.txt index 44647d9f30e3..884637c7f198 100644 --- a/requirements.txt +++ b/requirements.txt @@ -119,10 +119,11 @@ grpcio>=1.73.1,<2 # Provides the standard async gRPC Health service used by OpenEngine. grpcio-health-checking>=1.73.1,<1.82 # etcd-sdk-python imports google.protobuf but omits it from its package metadata. -# The binding lower bound comes from the CUTLASS DSL libraries, which need protobuf 6.x. +# The binding lower bound matches the CMake-bundled protobuf (v33.6) used to +# generate the trtllm.engine.v1 Python bindings at build time (6.33.6 gencode). # sentencepiece>=0.2.3 needs a protobuf>=7.36.1 runtime; drop the sentencepiece<0.2.3 cap # above only once this floor reaches 7.36.1. -protobuf>=6.30.2,<7 +protobuf>=6.33.6,<7 python-multipart cache-dit>=1.3.5 librosa diff --git a/scripts/build_wheel.py b/scripts/build_wheel.py index 35243c4312b1..a774a4f73fa2 100755 --- a/scripts/build_wheel.py +++ b/scripts/build_wheel.py @@ -1562,6 +1562,16 @@ def get_binding_lib(subdirectory, name): binding_lib_file_name = binding_lib_dir.name install_file(binding_lib_dir, pkg_dir) + engine_v1_generated_src = (build_dir / "tensorrt_llm" / "nanobind" / + "engine_wire" / "generated_py") + if not (engine_v1_generated_src / "common_pb2.py").is_file(): + raise FileNotFoundError( + f"Generated trtllm.engine.v1 Python bindings missing at " + f"{engine_v1_generated_src}; CMake target engine_wire_proto " + "did not populate them.") + install_tree(engine_v1_generated_src, + pkg_dir / "contracts" / "engine" / "v1" / "_generated") + with (build_dir / "tensorrt_llm" / "deep_ep" / "cuda_architectures.txt").open() as f: deep_ep_cuda_architectures = f.read().strip().strip(";") diff --git a/scripts/generate_contract_protos.py b/scripts/generate_contract_protos.py new file mode 100644 index 000000000000..b8c494cf0631 --- /dev/null +++ b/scripts/generate_contract_protos.py @@ -0,0 +1,494 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Generate or verify TRT-LLM's Python bindings for contracts/engine/v1/*.proto. + +Bindings are generated at build time into ``tensorrt_llm/contracts/engine/v1/_generated/`` +and are not checked into git. The generator accepts ``--protoc `` (such as +the ``protoc`` binary built by CMake), or auto-discovers a protobuf 6.x-compatible +compiler (``grpc_tools.protoc`` or a version-checked ``protoc`` on PATH). +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +_PROTO_NAMES = ( + "common", + "disagg", + "stats", + "request", + "output", + "capabilities", + "session", + "control", +) +_GRPC_PROTO_NAMES = ("session", "control") +_CONTRACT_NAME = "trtllm.engine.v1" +_PROTO_REL_DIR = "engine/v1" +_BINDINGS_PACKAGE = "tensorrt_llm.contracts.engine.v1._generated" +_RUNTIME_PROTOBUF_FLOOR = "6.33.6" +# Minimum protoc minor/edition version that emits Protobuf 6.x gencode (libprotoc >= 30.0 +# emits 6.30+; older Debian/Ubuntu libprotoc 3.21.x emits legacy 4.x gencode). +_MIN_STANDALONE_PROTOC_VERSION = (30, 0) +_COPYRIGHT_HEADER = ( + "# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. " + "All rights reserved.\n" + "# SPDX-License-Identifier: Apache-2.0\n\n" +) +_MARKER_NAME = ".contracts-generated" +_MARKER_HEADER = "Owned by scripts/generate_contract_protos.py; safe to replace." +_INIT_CONTENT = ( + _COPYRIGHT_HEADER + '"""Generated Python bindings for trtllm.engine.v1 (protocol v1.1)."""\n' +) +_PROTOBUF_GENCODE_RE = re.compile( + r"^# Protobuf Python Version: ([0-9]+(?:\.[0-9]+)*)$", re.MULTILINE +) +_PROTOC_VERSION_RE = re.compile(r"libprotoc\s+([0-9]+)\.([0-9]+)") + + +def _version_tuple(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + +def _sha256_tree(proto_root: Path) -> tuple[dict[str, str], str]: + per_file: dict[str, str] = {} + h = hashlib.sha256() + for name in sorted(_PROTO_NAMES): + rel = f"{_PROTO_REL_DIR}/{name}.proto" + data = (proto_root / rel).read_bytes() + digest = hashlib.sha256(data).hexdigest() + per_file[rel] = digest + h.update(f"{rel}\0{digest}\n".encode("utf-8")) + return per_file, f"sha256-tree-v1:{h.hexdigest()}" + + +def _rewrite_generated(path: Path, bindings_pkg: str) -> None: + text = path.read_text(encoding="utf-8") + text = re.sub( + r"^from engine\.v1 import ([A-Za-z0-9_]+)( as |$)", + r"from . import \1\2", + text, + flags=re.MULTILINE, + ) + for name in _PROTO_NAMES: + for quote in ("'", '"'): + text = text.replace( + f"{quote}engine.v1.{name}_pb2{quote}", + f"{quote}{bindings_pkg}.{name}_pb2{quote}", + ) + if re.search( + r"^(?:from\s+engine\.v1|import\s+engine\.v1)", + text, + flags=re.MULTILINE, + ): + raise RuntimeError(f"Retained top-level engine.v1 import in {path}") + if text.startswith("# -*- coding: utf-8 -*-\n"): + text = text.replace( + "# -*- coding: utf-8 -*-\n", + f"# -*- coding: utf-8 -*-\n{_COPYRIGHT_HEADER}", + 1, + ) + else: + text = _COPYRIGHT_HEADER + text + path.write_text(text, encoding="utf-8", newline="\n") + + +def _has_grpc_tools() -> bool: + try: + import importlib.util + + return importlib.util.find_spec("grpc_tools.protoc") is not None + except ImportError: + return False + + +def _probe_protoc_version(protoc_path: str | Path) -> tuple[int, int] | None: + try: + done = subprocess.run( + [str(protoc_path), "--version"], + capture_output=True, + text=True, + check=True, + ) + except (OSError, subprocess.SubprocessError): + return None + match = _PROTOC_VERSION_RE.search(done.stdout + done.stderr) + if match is None: + return None + return (int(match.group(1)), int(match.group(2))) + + +def _resolve_protoc_cmd(protoc: str | Path | None, include_grpc: bool) -> list[str]: + if protoc is not None: + if include_grpc: + raise RuntimeError( + "--with-grpc requires grpc_tools.protoc rather than standalone protoc" + ) + protoc_path = Path(protoc) + if not protoc_path.is_file(): + raise FileNotFoundError(f"protoc binary not found: {protoc_path}") + return [str(protoc_path)] + if include_grpc: + if not _has_grpc_tools(): + raise RuntimeError( + "grpc_tools.protoc is required when --with-grpc is set " + "(install grpcio-tools or omit --with-grpc)." + ) + return [sys.executable, "-m", "grpc_tools.protoc"] + # Prefer a standalone protoc on PATH only when it is new enough to emit Protobuf 6.x + # gencode (e.g. libprotoc >= 30.0, avoiding legacy distro /usr/bin/protoc 3.21.x). + # Otherwise prefer grpc_tools.protoc, which ships a modern bundled compiler. + found = shutil.which("protoc") + if found: + ver = _probe_protoc_version(found) + if ver is not None and ver >= _MIN_STANDALONE_PROTOC_VERSION: + return [found] + if _has_grpc_tools(): + return [sys.executable, "-m", "grpc_tools.protoc"] + if found: + ver = _probe_protoc_version(found) + raise RuntimeError( + f"Found protoc at {found} (version {ver}), which is older than the required " + f"libprotoc >= {_MIN_STANDALONE_PROTOC_VERSION[0]}.{_MIN_STANDALONE_PROTOC_VERSION[1]} " + "for Protobuf 6.x gencode, and grpc_tools.protoc is not installed. " + "Pass --protoc (e.g. CMake-built protobuf::protoc) or install grpcio-tools." + ) + raise RuntimeError( + "No compatible protoc compiler found. Pass --protoc , put protoc >= 30.0 on PATH, " + "or install grpcio-tools." + ) + + +def _validate_gencode_floor(artifacts: dict[str, bytes], runtime_floor: str) -> None: + """Reject generated bindings whose gencode version exceeds the declared runtime floor.""" + floor_tuple = _version_tuple(runtime_floor) + for name, content in artifacts.items(): + if not name.endswith("_pb2.py"): + continue + match = _PROTOBUF_GENCODE_RE.search(content.decode("utf-8")) + if match is None: + continue + gencode_str = match.group(1) + gencode_tuple = _version_tuple(gencode_str) + if gencode_tuple > floor_tuple: + raise RuntimeError( + f"Generated {name} targets Protobuf Python gencode {gencode_str}, which is " + f"newer than the declared runtime floor {runtime_floor} in manifest.json " + "and requirements.txt." + ) + if floor_tuple[0] not in {gencode_tuple[0], gencode_tuple[0] + 1}: + raise RuntimeError( + f"Generated {name} targets Protobuf Python gencode {gencode_str}, whose major " + f"version is incompatible with runtime floor {runtime_floor}." + ) + + +def _marker_content(tree_digest: str) -> bytes: + return f"{_MARKER_HEADER}\ntree_digest={tree_digest}\n".encode("utf-8") + + +def _expected_artifact_names(include_grpc: bool = False) -> set[str]: + names = { + "__init__.py", + _MARKER_NAME, + *(f"{name}_pb2.py" for name in _PROTO_NAMES), + *(f"{name}_pb2.pyi" for name in _PROTO_NAMES), + } + if include_grpc: + names.update(f"{name}_pb2_grpc.py" for name in _GRPC_PROTO_NAMES) + return names + + +def generate_artifacts( + proto_root: Path, + bindings_pkg: str = _BINDINGS_PACKAGE, + *, + protoc: str | Path | None = None, + include_grpc: bool = False, + runtime_protobuf_floor: str | None = None, +) -> dict[str, bytes]: + _, tree_digest = _sha256_tree(proto_root) + cmd_prefix = _resolve_protoc_cmd(protoc, include_grpc=include_grpc) + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + proto_files = [str(proto_root / f"{_PROTO_REL_DIR}/{name}.proto") for name in _PROTO_NAMES] + cmd = [ + *cmd_prefix, + f"-I{proto_root}", + f"--python_out={tmp_path}", + f"--pyi_out={tmp_path}", + ] + if include_grpc: + cmd.append(f"--grpc_python_out={tmp_path}") + cmd.extend(proto_files) + subprocess.run(cmd, check=True) + pkg_dir = tmp_path / _PROTO_REL_DIR + artifacts: dict[str, bytes] = {} + for name in _PROTO_NAMES: + for suffix in ("_pb2.py", "_pb2.pyi"): + p = pkg_dir / f"{name}{suffix}" + _rewrite_generated(p, bindings_pkg) + artifacts[p.name] = p.read_bytes() + if include_grpc: + for name in _GRPC_PROTO_NAMES: + p = pkg_dir / f"{name}_pb2_grpc.py" + _rewrite_generated(p, bindings_pkg) + artifacts[p.name] = p.read_bytes() + artifacts["__init__.py"] = _INIT_CONTENT.encode("utf-8") + artifacts[_MARKER_NAME] = _marker_content(tree_digest) + if runtime_protobuf_floor is not None: + _validate_gencode_floor(artifacts, runtime_protobuf_floor) + return artifacts + + +def write_artifacts(out_dir: Path, artifacts: dict[str, bytes]) -> None: + """Atomically publish generated artifacts to ``out_dir``, preserving ownership safety.""" + out_dir.parent.mkdir(parents=True, exist_ok=True) + + # Validate ownership before staging so we fail fast on an unowned directory. + if not out_dir.is_symlink() and out_dir.exists(): + if not out_dir.is_dir(): + raise RuntimeError(f"Refusing to replace non-directory output path: {out_dir}") + marker = out_dir / _MARKER_NAME + owned = marker.is_file() and not marker.is_symlink() + if not owned: + existing = [p.name for p in out_dir.iterdir() if p.name != "__pycache__"] + if existing: + raise RuntimeError( + f"Refusing to overwrite {out_dir}: missing {_MARKER_NAME} ownership marker." + ) + + with tempfile.TemporaryDirectory(prefix=".contracts-staging-", dir=out_dir.parent) as tmp: + staged = Path(tmp) / "generated" + staged.mkdir() + for name, content in artifacts.items(): + (staged / name).write_bytes(content) + + if out_dir.is_symlink(): + # Replace the symlink itself without modifying its target (e.g. CMake build dir). + out_dir.unlink() + staged.rename(out_dir) + return + + if out_dir.exists(): + previous = Path(tmp) / "previous" + out_dir.rename(previous) + try: + staged.rename(out_dir) + except OSError: + previous.rename(out_dir) + raise + return + + staged.rename(out_dir) + + +def generate_to_dir( + proto_root: Path, + out_dir: Path, + bindings_pkg: str = _BINDINGS_PACKAGE, + *, + protoc: str | Path | None = None, + include_grpc: bool = False, + runtime_protobuf_floor: str | None = None, +) -> dict[str, bytes]: + artifacts = generate_artifacts( + proto_root, + bindings_pkg, + protoc=protoc, + include_grpc=include_grpc, + runtime_protobuf_floor=runtime_protobuf_floor, + ) + write_artifacts(out_dir, artifacts) + return artifacts + + +def _read_requirements_protobuf_floor(requirements_path: Path) -> str | None: + if not requirements_path.is_file(): + return None + pattern = re.compile(r"^protobuf>=(?P[0-9]+(?:\.[0-9]+)*)(?:,|$)") + for raw_line in requirements_path.read_text(encoding="utf-8").splitlines(): + match = pattern.match(raw_line.strip()) + if match is not None: + return match.group("floor") + return None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Generate or verify Python bindings for contracts/engine/v1/*.proto." + ) + parser.add_argument( + "--check", + action="store_true", + help="Verify manifest.json matches contracts/engine/v1/*.proto (and _generated if present).", + ) + parser.add_argument( + "--update-manifest", + action="store_true", + help="Rewrite tensorrt_llm/contracts/engine/v1/manifest.json from contracts/engine/v1/*.proto.", + ) + parser.add_argument( + "--proto-root", + type=Path, + default=None, + help="Override proto root directory (contains engine/v1/*.proto).", + ) + parser.add_argument( + "--out-dir", + type=Path, + default=None, + help="Override generated Python output directory.", + ) + parser.add_argument( + "--bindings-package", + type=str, + default=_BINDINGS_PACKAGE, + ) + parser.add_argument( + "--protoc", + type=Path, + default=None, + help="Explicit path to a protoc executable (e.g. CMake-built protobuf::protoc).", + ) + parser.add_argument( + "--with-grpc", + action="store_true", + help="Also emit *_pb2_grpc.py stubs (requires grpcio-tools).", + ) + args = parser.parse_args(argv) + + project_root = Path(__file__).resolve().parents[1] + proto_root = args.proto_root or (project_root / "contracts") + out_dir = args.out_dir or (project_root / "tensorrt_llm/contracts/engine/v1/_generated") + manifest_path = project_root / "tensorrt_llm/contracts/engine/v1/manifest.json" + requirements_path = project_root / "requirements.txt" + + per_file, tree_digest = _sha256_tree(proto_root) + req_pb_floor = _read_requirements_protobuf_floor(requirements_path) + + if args.check: + checked_manifest = False + if args.proto_root is None: + if not manifest_path.is_file(): + print(f"Missing contract manifest: {manifest_path}", file=sys.stderr) + return 1 + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if manifest.get("contract") != _CONTRACT_NAME: + print( + f"Manifest contract mismatch: {manifest.get('contract')} != {_CONTRACT_NAME}", + file=sys.stderr, + ) + return 1 + if manifest.get("files") != per_file: + print( + "Manifest file digests drift from contracts/engine/v1/*.proto", file=sys.stderr + ) + return 1 + if manifest.get("tree_digest") != tree_digest: + print( + f"Manifest tree_digest drift: {manifest.get('tree_digest')} != {tree_digest}", + file=sys.stderr, + ) + return 1 + manifest_pb_floor = manifest.get("runtime_floors", {}).get("protobuf") + if req_pb_floor is not None and manifest_pb_floor != req_pb_floor: + print( + f"Manifest runtime_floors.protobuf ({manifest_pb_floor}) != " + f"requirements.txt protobuf>={req_pb_floor}", + file=sys.stderr, + ) + return 1 + checked_manifest = True + + if out_dir.is_dir(): + expected_names = _expected_artifact_names(include_grpc=args.with_grpc) + actual_names = {p.name for p in out_dir.iterdir() if p.is_file()} + if expected_names != actual_names: + print( + f"File mismatch in {out_dir}: extra={actual_names - expected_names} " + f"missing={expected_names - actual_names}", + file=sys.stderr, + ) + return 1 + marker = out_dir / _MARKER_NAME + if not marker.is_file() or marker.is_symlink(): + print(f"Missing or invalid {_MARKER_NAME} in {out_dir}", file=sys.stderr) + return 1 + marker_lines = marker.read_text(encoding="utf-8").splitlines() + if f"tree_digest={tree_digest}" not in marker_lines: + print(f"Generated bindings tree_digest drift in {out_dir}", file=sys.stderr) + return 1 + if req_pb_floor is not None: + actual_pb2 = { + p.name: p.read_bytes() for p in out_dir.iterdir() if p.name.endswith("_pb2.py") + } + _validate_gencode_floor(actual_pb2, req_pb_floor) + if args.protoc is not None: + artifacts = generate_artifacts( + proto_root, + args.bindings_package, + protoc=args.protoc, + include_grpc=args.with_grpc, + runtime_protobuf_floor=req_pb_floor, + ) + for name, expected in artifacts.items(): + actual = (out_dir / name).read_bytes() + if actual != expected: + print(f"Drift in {out_dir / name}", file=sys.stderr) + return 1 + scope = "manifest and generated bindings" if checked_manifest else "generated bindings" + print(f"OK: {scope} ({len(actual_names)} files) match ({tree_digest})") + return 0 + + if args.out_dir is not None: + print(f"Generated bindings directory not found: {out_dir}", file=sys.stderr) + return 1 + if not checked_manifest: + print( + "Nothing checked: --proto-root skipped default manifest and _generated/ is absent.", + file=sys.stderr, + ) + return 1 + print(f"OK: manifest matches contracts/engine/v1/*.proto ({tree_digest})") + return 0 + + runtime_floor = req_pb_floor or _RUNTIME_PROTOBUF_FLOOR + artifacts = generate_to_dir( + proto_root, + out_dir, + args.bindings_package, + protoc=args.protoc, + include_grpc=args.with_grpc, + runtime_protobuf_floor=runtime_floor, + ) + + if args.update_manifest and args.proto_root is None: + manifest = { + "contract": _CONTRACT_NAME, + "protocol_version": {"major": 1, "minor": 1}, + "tree_digest": tree_digest, + "files": per_file, + "runtime_floors": { + "protobuf": runtime_floor, + }, + } + manifest_path.write_text( + json.dumps(manifest, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + print(f"Generated {len(artifacts)} files into {out_dir} ({tree_digest})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/security_scanning/pyproject.toml b/security_scanning/pyproject.toml index 637b97179095..9e5edec6e0dc 100644 --- a/security_scanning/pyproject.toml +++ b/security_scanning/pyproject.toml @@ -94,7 +94,7 @@ dependencies = [ "etcd-sdk-python (==0.0.7)", "grpcio (>=1.73.1,<2)", "grpcio-health-checking (>=1.73.1,<1.82)", - "protobuf (>=6.30.2,<7)", + "protobuf (>=6.33.6,<7)", "python-multipart (>=0.0.34,<0.0.35)", "cache-dit (>=1.3.5)", "librosa (>=1.0.1,<2.0.0)", diff --git a/setup.py b/setup.py index 0020b0f631c0..c9c12f6d16e4 100644 --- a/setup.py +++ b/setup.py @@ -74,6 +74,27 @@ def sanity_check(): raise ImportError( 'The checked-in private OpenEngine bindings are missing. Please check the package integrity.' ) + engine_v1_gen = (tensorrt_llm_path / "contracts" / "engine" / "v1" / + "_generated") + missing_engine_v1 = [ + name for name in ( + "__init__.py", + "capabilities_pb2.py", + "common_pb2.py", + "control_pb2.py", + "disagg_pb2.py", + "output_pb2.py", + "request_pb2.py", + "session_pb2.py", + "stats_pb2.py", + ) if not (engine_v1_gen / name).is_file() + ] + if missing_engine_v1: + raise ImportError( + 'Generated trtllm.engine.v1 protobuf bindings are missing ' + f'under {engine_v1_gen} ({", ".join(missing_engine_v1)}). ' + 'Run `scripts/build_wheel.py` or ' + '`python3 scripts/generate_contract_protos.py` before packaging.') def get_version(): @@ -215,6 +236,10 @@ def has_ext_modules(self): 'grpc/openengine/proto/manifest.json', 'grpc/openengine/proto/openengine/v1/*.proto', 'grpc/openengine/proto/trtllm/openengine/v1/*.proto', + 'contracts/engine/v1/_generated/*.py', + 'contracts/engine/v1/_generated/*.pyi', + 'contracts/engine/v1/_generated/.contracts-generated', + 'contracts/engine/v1/manifest.json', ] # MSA packages staged under 3rdparty/ by scripts/build_wheel.py from the msa_vllm @@ -334,6 +359,7 @@ def should_skip_precompiled_package_data(filename: str) -> bool: return filename.startswith(( "tensorrt_llm/grpc/openengine/_generated/", "tensorrt_llm/grpc/openengine/proto/", + "tensorrt_llm/contracts/engine/v1/manifest.json", )) @@ -349,11 +375,13 @@ def warn_on_build_skew(precompiled_location: str) -> None: import subprocess NATIVE_BUILD_INPUTS = [ + "contracts/", "cpp/", "3rdparty/", "setup.py", "scripts/build_wheel.py", "requirements.txt", + "tensorrt_llm/executor/native/", ":(glob)tensorrt_llm/_torch/modeling_v2/models/**/csrc/**", ":(glob)tensorrt_llm/_torch/visual_gen/modeling_v2/catalog/**/csrc/**", ":(glob)tensorrt_llm/_torch/visual_gen/modeling_v2/models/**/csrc/**", @@ -483,12 +511,16 @@ def extract_from_precompiled(precompiled_location: str, package_data: list[str], if should_skip_precompiled_package_data(dst_file): continue - # Skip .py files EXCEPT for generated C++ extension wrappers - # (deep_gemm, deep_ep, flash_mla Python files are generated during build) + # Skip .py files EXCEPT for build-generated extension wrappers and + # contract bindings (generated during CMake build, verified against + # the local proto tree_digest afterwards). if dst_file.endswith(".py"): - allowed_dirs = ("tensorrt_llm/deep_gemm/", - "tensorrt_llm/deep_ep/", - "tensorrt_llm/flash_mla/") + allowed_dirs = ( + "tensorrt_llm/deep_gemm/", + "tensorrt_llm/deep_ep/", + "tensorrt_llm/flash_mla/", + "tensorrt_llm/contracts/engine/v1/_generated/", + ) if not any(dst_file.startswith(d) for d in allowed_dirs): continue @@ -691,13 +723,15 @@ def extract_from_precompiled(precompiled_location: str, package_data: list[str], wheel.extract(file, path=dst_nccl_extensions) continue - # Skip .py files EXCEPT for generated C++ extension wrappers - # (deep_gemm, deep_ep, flash_mla Python files are generated during build) + # Skip .py files EXCEPT for build-generated extension wrappers and + # contract bindings (generated during CMake build, verified against + # the local proto tree_digest afterwards). if file.filename.endswith(".py"): allowed_dirs = ( "tensorrt_llm/deep_gemm/", "tensorrt_llm/deep_ep/", "tensorrt_llm/flash_mla/", + "tensorrt_llm/contracts/engine/v1/_generated/", ) if not any(file.filename.startswith(d) for d in allowed_dirs): continue @@ -722,6 +756,79 @@ def extract_from_precompiled(precompiled_location: str, package_data: list[str], and precompiled != "0") or (precompiled_location is not None) + +def _maybe_generate_engine_v1_contract_bindings() -> None: + """Generate tensorrt_llm/contracts/engine/v1/_generated/ when building from a checkout. + + scripts/build_wheel.py populates `_generated/` from CMake's `engine_wire_proto` + target before invoking setuptools (and in out-of-tree staging does not copy `contracts/` + or `scripts/`). When installing directly from a source checkout (e.g. + `TRTLLM_USE_PRECOMPILED=1 pip install -e .`), reuse pre-populated `_generated/` only + when all expected files are present and `.contracts-generated` matches the live SHA-256 + tree digest of `contracts/engine/v1/*.proto`; otherwise regenerate from source. + """ + import hashlib + + repo_root = Path(__file__).resolve().parent + gen_dir = (repo_root / "tensorrt_llm" / "contracts" / "engine" / "v1" / + "_generated") + proto_dir = repo_root / "contracts" / "engine" / "v1" + generator = repo_root / "scripts" / "generate_contract_protos.py" + if not (proto_dir.is_dir() and generator.is_file()): + return + + proto_names = ( + "capabilities", + "common", + "control", + "disagg", + "output", + "request", + "session", + "stats", + ) + h = hashlib.sha256() + for name in proto_names: + proto_file = proto_dir / f"{name}.proto" + if not proto_file.is_file(): + return + digest = hashlib.sha256(proto_file.read_bytes()).hexdigest() + h.update(f"engine/v1/{name}.proto\0{digest}\n".encode("utf-8")) + live_digest = f"sha256-tree-v1:{h.hexdigest()}" + + expected_files = ( + "__init__.py", + ".contracts-generated", + *(f"{name}_pb2.py" for name in proto_names), + *(f"{name}_pb2.pyi" for name in proto_names), + ) + marker = gen_dir / ".contracts-generated" + if (all((gen_dir / name).is_file() for name in expected_files) + and f"tree_digest={live_digest}" + in marker.read_text(encoding="utf-8").splitlines()): + return + + if gen_dir.is_symlink(): + gen_dir.unlink() + elif gen_dir.is_dir(): + # Clear individual file symlinks (e.g. stale precompiled link-mode entries) + # before regenerating into a clean owned directory. + for entry in list(gen_dir.iterdir()): + if entry.is_symlink(): + entry.unlink() + if not any(entry.name != "__pycache__" for entry in gen_dir.iterdir()): + import shutil + shutil.rmtree(gen_dir) + subprocess.check_call([ + sys.executable, + str(generator), + "--proto-root", + str(repo_root / "contracts"), + "--out-dir", + str(gen_dir), + ]) + + if use_precompiled: from tempfile import TemporaryDirectory with TemporaryDirectory() as tempdir: @@ -730,6 +837,7 @@ def extract_from_precompiled(precompiled_location: str, package_data: list[str], precompiled_location = download_precompiled(tempdir, version) extract_from_precompiled(precompiled_location, package_data, tempdir) +_maybe_generate_engine_v1_contract_bindings() sanity_check() with open("README.md", "r", encoding="utf-8") as fh: diff --git a/tensorrt_llm/contracts/__init__.py b/tensorrt_llm/contracts/__init__.py new file mode 100644 index 000000000000..859fd9431530 --- /dev/null +++ b/tensorrt_llm/contracts/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Protocol contract bindings and helpers owned by TensorRT-LLM. + +The shared ``.proto`` schemas live at repository top-level ``contracts/``. +Keep this package root strictly lazy so importing ``tensorrt_llm`` does not load protobuf/gRPC. +""" diff --git a/tensorrt_llm/contracts/engine/__init__.py b/tensorrt_llm/contracts/engine/__init__.py new file mode 100644 index 000000000000..30f267928eec --- /dev/null +++ b/tensorrt_llm/contracts/engine/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Engine protocol contracts package root.""" diff --git a/tensorrt_llm/contracts/engine/v1/__init__.py b/tensorrt_llm/contracts/engine/v1/__init__.py new file mode 100644 index 000000000000..9dafc19fd86b --- /dev/null +++ b/tensorrt_llm/contracts/engine/v1/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Engine protocol v1 (v1.1) contract bindings and helpers.""" diff --git a/tensorrt_llm/contracts/engine/v1/_native.py b/tensorrt_llm/contracts/engine/v1/_native.py new file mode 100644 index 000000000000..b1a068b3e1f5 --- /dev/null +++ b/tensorrt_llm/contracts/engine/v1/_native.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Backend selection for the trtllm.engine.v1 wire codec. + +``TLLM_SERVE_ENGINE_WIRE_BACKEND`` picks the codec used by ``wire_codec``: + +* ``auto`` (default): the native module when it imports, otherwise pure Python + (``wire_codec.parse_client_message`` stays on Python, see ``resolve``); +* ``cpp``: the native module, raising ``ImportError`` when it does not import; +* ``python``: pure Python. + +The native module is ``tensorrt_llm.bindings.internal.engine_wire``, or the +standalone build of the same sources (``engine_wire_standalone``) when the +bindings module does not carry it. It is imported once, on first use. +""" + +from __future__ import annotations + +import importlib +import os +from types import ModuleType + +BACKEND_ENV = "TLLM_SERVE_ENGINE_WIRE_BACKEND" +BACKENDS = ("auto", "cpp", "python") + +_UNSET = object() +_native_module: ModuleType | None | object = _UNSET +_native_import_error: str = "" + + +def _import_native() -> ModuleType | None: + global _native_import_error + errors = [] + try: + from tensorrt_llm.bindings.internal import engine_wire + + return engine_wire + except ImportError as exc: + errors.append(f"tensorrt_llm.bindings.internal.engine_wire: {exc}") + try: + return importlib.import_module("engine_wire_standalone") + except ImportError as exc: + errors.append(f"engine_wire_standalone: {exc}") + _native_import_error = "; ".join(errors) + return None + + +def native_module() -> ModuleType | None: + """The native codec module, or None when it does not import.""" + global _native_module + if _native_module is _UNSET: + _native_module = _import_native() + return _native_module if isinstance(_native_module, ModuleType) else None + + +def backend_name(value: str | None = None) -> str: + """The configured backend: ``value``, else the environment, else ``auto``.""" + name = os.environ.get(BACKEND_ENV, "auto") if value is None else value + name = name.strip().lower() or "auto" + if name not in BACKENDS: + raise ValueError(f"{BACKEND_ENV}={name!r}; expected one of {', '.join(BACKENDS)}") + return name + + +def resolve(value: str | None = None, *, auto_native: bool = True) -> ModuleType | None: + """The native module to use for ``value`` (see ``backend_name``), or None for Python. + + ``auto_native=False`` keeps ``auto`` on Python, for operations where the native + codec is not faster than protobuf's own parser. + """ + name = backend_name(value) + if name == "python" or (name == "auto" and not auto_native): + return None + native = native_module() + if native is None and name == "cpp": + raise ImportError( + f"{BACKEND_ENV}=cpp but the native engine_wire module does not import: " + f"{_native_import_error}" + ) + return native diff --git a/tensorrt_llm/contracts/engine/v1/bindings.py b/tensorrt_llm/contracts/engine/v1/bindings.py new file mode 100644 index 000000000000..2649a30955f3 --- /dev/null +++ b/tensorrt_llm/contracts/engine/v1/bindings.py @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Stable internal facade for trtllm.engine.v1 (protocol v1.1) bindings.""" + +from __future__ import annotations + +import json +import warnings +from importlib.resources import files + +_MANIFEST = json.loads( + files("tensorrt_llm.contracts.engine.v1").joinpath("manifest.json").read_text(encoding="utf-8") +) +PROTOCOL_MAJOR = int(_MANIFEST["protocol_version"]["major"]) +PROTOCOL_MINOR = int(_MANIFEST["protocol_version"]["minor"]) +TREE_DIGEST = str(_MANIFEST["tree_digest"]) + +with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"^Protobuf gencode version .* at engine/v1/[A-Za-z0-9_]+\.proto\.", + category=UserWarning, + ) + try: + from ._generated import ( + capabilities_pb2, + common_pb2, + control_pb2, + disagg_pb2, + output_pb2, + request_pb2, + session_pb2, + stats_pb2, + ) + except ModuleNotFoundError as exc: + if exc.name and ( + exc.name == f"{__package__}._generated" + or exc.name.startswith(f"{__package__}._generated.") + ): + raise ModuleNotFoundError( + "Generated trtllm.engine.v1 protobuf bindings are missing under " + "tensorrt_llm/contracts/engine/v1/_generated/. Build the package " + "(scripts/build_wheel.py / pip install) or run " + "`python3 scripts/generate_contract_protos.py`.", + name=exc.name, + ) from exc + raise + +__all__ = [ + "PROTOCOL_MAJOR", + "PROTOCOL_MINOR", + "TREE_DIGEST", + "capabilities_pb2", + "common_pb2", + "control_pb2", + "disagg_pb2", + "output_pb2", + "request_pb2", + "session_pb2", + "stats_pb2", +] diff --git a/tensorrt_llm/contracts/engine/v1/manifest.json b/tensorrt_llm/contracts/engine/v1/manifest.json new file mode 100644 index 000000000000..d713a80f9b18 --- /dev/null +++ b/tensorrt_llm/contracts/engine/v1/manifest.json @@ -0,0 +1,21 @@ +{ + "contract": "trtllm.engine.v1", + "files": { + "engine/v1/capabilities.proto": "54ceb10ff5f2e11e4792060dc1def2cae4617b0cf86eb0f7a90bdd63c832bb7b", + "engine/v1/common.proto": "8a6ecd2502f715e8977f64fab562eba039695d08728a423aa96385654d7ac154", + "engine/v1/control.proto": "380d438812746d4e53d55b7de56b9261f10a93b317956c47523640194c71f0ea", + "engine/v1/disagg.proto": "3349fafe49f3444ed27d0a20e01e8e331081c529f0b87cd485ed80b5dbb0e0ce", + "engine/v1/output.proto": "9290fc911233f6f6dfbc52a664754b3bc93de13ee0582aff53bc414493a1f2d4", + "engine/v1/request.proto": "69c2542094d5ea5945e1ad114bc1e067d4ac5fbbef5034b6196b33e672f0bd29", + "engine/v1/session.proto": "1f8d0adefb5c42cbb6d9afbf08917a80b63a3a05f03adb2ad15b4678c45e0c69", + "engine/v1/stats.proto": "9d0caf7c84334ec2d0c9c5b8e4b554230bb2ed8ee66b14aa2a32cb59c9e1bf03" + }, + "protocol_version": { + "major": 1, + "minor": 1 + }, + "runtime_floors": { + "protobuf": "6.33.6" + }, + "tree_digest": "sha256-tree-v1:becf8eb3d361ed90a305cb309addc4239e32e3717eb432eef9179e739a1bf01f" +} diff --git a/tensorrt_llm/contracts/engine/v1/wire_codec.py b/tensorrt_llm/contracts/engine/v1/wire_codec.py new file mode 100644 index 000000000000..0efea8461da6 --- /dev/null +++ b/tensorrt_llm/contracts/engine/v1/wire_codec.py @@ -0,0 +1,1165 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Columnar Frame encoder/decoder, TensorRef/SHM/CUDA_IPC helpers, and TLV/HMAC helpers for trtllm.engine.v1. + +Pure-Python + stdlib/array/memoryview helpers shared by both gRPC and ZMQ transports. +""" + +from __future__ import annotations + +import array +import dataclasses +import hashlib +import hmac +import json +import logging +import math +import mmap +import os +import re +import stat +import struct +import sys +import tempfile +import uuid +from pathlib import Path +from typing import Mapping, Sequence, TypeVar + +from google.protobuf.message import DecodeError +from google.protobuf.message import Message as ProtoMessage + +from . import _native +from . import bindings as pb + +_MsgT = TypeVar("_MsgT", bound=ProtoMessage) + +logger = logging.getLogger(__name__) + +_SHM_SAFE_BASENAME_RE = re.compile(r"^[A-Za-z0-9._-]+$") +_CUDA_IPC_HANDLE_BYTES = 64 + +# RowFlag bit constants matching common.proto RowFlag +ROW_FLAG_NONE = 0 +ROW_FLAG_FIRST_ROW = 1 +ROW_FLAG_SEQ_FINAL = 2 +ROW_FLAG_REQUEST_DONE = 4 +ROW_FLAG_HAS_EXTRA = 8 + +NO_STOP_INDEX = -1 +NO_REPLACE_FROM = 0xFFFFFFFF +NO_EXTRA_INDEX = 0xFFFFFFFF + +_IS_LITTLE_ENDIAN = sys.byteorder == "little" + +# Mapping between common.proto DType and (struct_fmt / numpy_dtype_name / torch_dtype_name / itemsize) +DTYPE_INFO: dict[int, tuple[str, str, int]] = { + pb.common_pb2.DTYPE_F32: ("float32", "float32", 4), + pb.common_pb2.DTYPE_F16: ("float16", "float16", 2), + pb.common_pb2.DTYPE_BF16: ("bfloat16", "bfloat16", 2), + pb.common_pb2.DTYPE_FP8_E4M3: ("float8_e4m3fn", "float8_e4m3fn", 1), + pb.common_pb2.DTYPE_I64: ("int64", "int64", 8), + pb.common_pb2.DTYPE_I32: ("int32", "int32", 4), + pb.common_pb2.DTYPE_I16: ("int16", "int16", 2), + pb.common_pb2.DTYPE_I8: ("int8", "int8", 1), + pb.common_pb2.DTYPE_U8: ("uint8", "uint8", 1), + pb.common_pb2.DTYPE_BOOL: ("bool", "bool", 1), + pb.common_pb2.DTYPE_F64: ("float64", "float64", 8), +} +_NAME_TO_DTYPE: dict[str, int] = { + "float32": pb.common_pb2.DTYPE_F32, + "torch.float32": pb.common_pb2.DTYPE_F32, + "float16": pb.common_pb2.DTYPE_F16, + "torch.float16": pb.common_pb2.DTYPE_F16, + "bfloat16": pb.common_pb2.DTYPE_BF16, + "torch.bfloat16": pb.common_pb2.DTYPE_BF16, + "float8_e4m3fn": pb.common_pb2.DTYPE_FP8_E4M3, + "torch.float8_e4m3fn": pb.common_pb2.DTYPE_FP8_E4M3, + "int64": pb.common_pb2.DTYPE_I64, + "torch.int64": pb.common_pb2.DTYPE_I64, + "int32": pb.common_pb2.DTYPE_I32, + "torch.int32": pb.common_pb2.DTYPE_I32, + "int16": pb.common_pb2.DTYPE_I16, + "torch.int16": pb.common_pb2.DTYPE_I16, + "int8": pb.common_pb2.DTYPE_I8, + "torch.int8": pb.common_pb2.DTYPE_I8, + "uint8": pb.common_pb2.DTYPE_U8, + "torch.uint8": pb.common_pb2.DTYPE_U8, + "bool": pb.common_pb2.DTYPE_BOOL, + "torch.bool": pb.common_pb2.DTYPE_BOOL, + "float64": pb.common_pb2.DTYPE_F64, + "torch.float64": pb.common_pb2.DTYPE_F64, +} + + +def _pack_array(typecode: str, values: Sequence[int | float]) -> bytes: + arr = array.array(typecode, values) + if not _IS_LITTLE_ENDIAN and arr.itemsize > 1: + arr.byteswap() + return arr.tobytes() + + +def _unpack_col(raw: bytes, fmt_char: str, expected_count: int, col_name: str) -> list[int | float]: + itemsize = struct.calcsize(f"<{fmt_char}") + expected_bytes = expected_count * itemsize + if len(raw) != expected_bytes: + raise ValueError( + f"Frame column {col_name!r} byte length {len(raw)} != expected {expected_bytes} " + f"(count={expected_count}, itemsize={itemsize})" + ) + if expected_count == 0: + return [] + if _IS_LITTLE_ENDIAN: + return memoryview(raw).cast(fmt_char).tolist() + return list(struct.unpack(f"<{expected_count}{fmt_char}", raw)) + + +@dataclasses.dataclass(slots=True) +class FrameRow: + """One decoded or to-be-encoded output row in a columnar Frame.""" + + handle: int + tokens: list[int] + finish: int = 0 + row_flags: int = 0 + seq: int = 0 + stop_index: int = NO_STOP_INDEX + replace_from: int = NO_REPLACE_FROM + cum_logprob: float | None = None + decoding_iter: int = 0 + cached_tokens: int = 0 + # Per-token logprobs aligned with `tokens` (optional) + lp_sampled: list[float] | None = None + lp_rank: list[int] | None = None + # Per-token top-k list: list[list[tuple[int, float]]] aligned with `tokens` + lp_topk: list[list[tuple[int, float]]] | None = None + extra: ProtoMessage | bytes | None = None # output_pb2.RowExtra or None + + +def encode_frame( + rows: Sequence[FrameRow], + *, + frame_seq: int, + iter_first: int = 0, + iter_last: int = 0, + emit_time_ns: int = 0, + acks: Sequence[ProtoMessage | bytes] = (), + iteration_stats: Sequence[ProtoMessage | bytes] = (), + lora_set_changed: Sequence[ProtoMessage | bytes] = (), + backend: str | None = None, +) -> ProtoMessage: + """Encode a sequence of FrameRow objects into a columnar output_pb2.Frame. + + ``backend`` overrides ``TLLM_SERVE_ENGINE_WIRE_BACKEND`` (see ``_native``). + """ + native = _native.resolve(backend) + if native is not None: + return pb.output_pb2.Frame.FromString( + native.encode_frame( + rows, + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=emit_time_ns, + acks=acks, + iteration_stats=iteration_stats, + lora_set_changed=lora_set_changed, + ) + ) + return _encode_frame_python( + rows, + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=emit_time_ns, + acks=acks, + iteration_stats=iteration_stats, + lora_set_changed=lora_set_changed, + ) + + +def _encode_frame_python( + rows: Sequence[FrameRow], + *, + frame_seq: int, + iter_first: int, + iter_last: int, + emit_time_ns: int, + acks: Sequence[ProtoMessage | bytes], + iteration_stats: Sequence[ProtoMessage | bytes], + lora_set_changed: Sequence[ProtoMessage | bytes], +) -> ProtoMessage: + n = len(rows) + frame = pb.output_pb2.Frame( + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last or iter_first, + emit_time_ns=emit_time_ns, + n_rows=n, + ) + if acks: + frame.acks.extend(acks) + if iteration_stats: + frame.iteration_stats.extend(iteration_stats) + if lora_set_changed: + frame.lora_set_changed.extend(lora_set_changed) + + if n == 0: + return frame + + handles: list[int] = [] + seqs: list[int] = [] + token_offsets: list[int] = [0] + all_tokens: list[int] = [] + finishes: list[int] = [] + row_flags: list[int] = [] + stop_indices: list[int] = [] + replace_froms: list[int] = [] + cum_logprobs: list[float] = [] + decoding_iters: list[int] = [] + cached_tokens: list[int] = [] + extra_indices: list[int] = [] + extras: list[ProtoMessage | bytes] = [] + + need_seq = False + need_stop_index = False + need_replace_from = False + need_cum_logprob = False + need_decoding_iter = False + need_cached_tokens = False + need_lp_sampled = False + need_lp_rank = False + need_lp_topk = False + + for r in rows: + if r.seq != 0: + need_seq = True + if r.stop_index != NO_STOP_INDEX: + need_stop_index = True + if r.replace_from != NO_REPLACE_FROM: + need_replace_from = True + if r.cum_logprob is not None: + need_cum_logprob = True + if r.decoding_iter != 0: + need_decoding_iter = True + if r.cached_tokens != 0: + need_cached_tokens = True + if r.lp_sampled is not None: + need_lp_sampled = True + if r.lp_rank is not None: + need_lp_rank = True + if r.lp_topk is not None: + need_lp_topk = True + + lp_sampled_all: list[float] = [] + lp_rank_all: list[int] = [] + lp_topk_offsets: list[int] = [0] + lp_topk_ids: list[int] = [] + lp_topk_lps: list[float] = [] + + for r in rows: + handles.append(r.handle) + seqs.append(r.seq) + all_tokens.extend(r.tokens) + token_offsets.append(len(all_tokens)) + finishes.append(r.finish) + flags = r.row_flags + if r.extra is not None: + flags |= ROW_FLAG_HAS_EXTRA + extra_indices.append(len(extras)) + extras.append(r.extra) + else: + flags &= ~ROW_FLAG_HAS_EXTRA + extra_indices.append(NO_EXTRA_INDEX) + row_flags.append(flags) + stop_indices.append(r.stop_index) + replace_froms.append(r.replace_from) + cum_logprobs.append(float("nan") if r.cum_logprob is None else float(r.cum_logprob)) + decoding_iters.append(r.decoding_iter) + cached_tokens.append(r.cached_tokens) + + nt = len(r.tokens) + if need_lp_sampled: + if r.lp_sampled is not None: + if len(r.lp_sampled) != nt: + raise ValueError(f"lp_sampled length {len(r.lp_sampled)} != tokens {nt}") + lp_sampled_all.extend(r.lp_sampled) + else: + lp_sampled_all.extend([float("nan")] * nt) + if need_lp_rank: + if r.lp_rank is not None: + if len(r.lp_rank) != nt: + raise ValueError(f"lp_rank length {len(r.lp_rank)} != tokens {nt}") + lp_rank_all.extend(r.lp_rank) + else: + lp_rank_all.extend([0] * nt) + if need_lp_topk: + if r.lp_topk is not None: + if len(r.lp_topk) != nt: + raise ValueError(f"lp_topk length {len(r.lp_topk)} != tokens {nt}") + for cand_list in r.lp_topk: + for cid, clp in cand_list: + lp_topk_ids.append(int(cid)) + lp_topk_lps.append(float(clp)) + lp_topk_offsets.append(len(lp_topk_ids)) + else: + for _ in range(nt): + lp_topk_offsets.append(len(lp_topk_ids)) + + frame.handle = _pack_array("Q", handles) + if need_seq: + frame.seq = _pack_array("I", seqs) + frame.token_offsets = _pack_array("I", token_offsets) + if all_tokens: + frame.tokens = _pack_array("i", all_tokens) + frame.finish = _pack_array("B", finishes) + frame.row_flags = _pack_array("H", row_flags) + if need_stop_index: + frame.stop_index = _pack_array("i", stop_indices) + if need_replace_from: + frame.replace_from = _pack_array("I", replace_froms) + if need_cum_logprob: + frame.cum_logprob = _pack_array("d", cum_logprobs) + if need_decoding_iter: + frame.decoding_iter = _pack_array("I", decoding_iters) + if need_cached_tokens: + frame.cached_tokens = _pack_array("I", cached_tokens) + if extras: + frame.extra_index = _pack_array("I", extra_indices) + frame.extras.extend(extras) + + total_tokens = len(all_tokens) + if total_tokens > 0: + if need_lp_sampled: + frame.lp_sampled = _pack_array("f", lp_sampled_all) + if need_lp_rank: + frame.lp_rank = _pack_array("I", lp_rank_all) + if need_lp_topk: + frame.lp_topk_offsets = _pack_array("I", lp_topk_offsets) + if lp_topk_ids: + frame.lp_topk_ids = _pack_array("i", lp_topk_ids) + frame.lp_topk_logprobs = _pack_array("f", lp_topk_lps) + + return frame + + +def decode_frame(frame: ProtoMessage, *, backend: str | None = None) -> list[FrameRow]: + """Decode a columnar output_pb2.Frame into FrameRow objects with strict CSR validation. + + ``backend`` overrides ``TLLM_SERVE_ENGINE_WIRE_BACKEND`` (see ``_native``). + """ + native = _native.resolve(backend) + if native is not None: + _, rows = native.decode_frame(frame.SerializeToString(), FrameRow) + return _parse_row_extras(rows) + return _decode_frame_python(frame) + + +def _parse_row_extras(rows: list[FrameRow]) -> list[FrameRow]: + """Turn the serialized RowExtra the native decoder leaves on rows into messages.""" + for row in rows: + if row.extra is not None: + row.extra = pb.output_pb2.RowExtra.FromString(row.extra) + return rows + + +def _decode_frame_python(frame: ProtoMessage) -> list[FrameRow]: + n = int(frame.n_rows) + if n == 0: + return [] + + handles = _unpack_col(frame.handle, "Q", n, "handle") + seqs = _unpack_col(frame.seq, "I", n, "seq") if frame.seq else [0] * n + token_offsets = _unpack_col(frame.token_offsets, "I", n + 1, "token_offsets") + if token_offsets[0] != 0: + raise ValueError(f"token_offsets[0]={token_offsets[0]} != 0") + for i in range(n): + if token_offsets[i] > token_offsets[i + 1]: + raise ValueError( + f"token_offsets not monotonic at {i}: {token_offsets[i]} > {token_offsets[i + 1]}" + ) + total_tokens = token_offsets[-1] + all_tokens = _unpack_col(frame.tokens, "i", total_tokens, "tokens") if total_tokens > 0 else [] + if total_tokens == 0 and frame.tokens: + raise ValueError(f"tokens column non-empty ({len(frame.tokens)}B) when total_tokens==0") + + finishes = _unpack_col(frame.finish, "B", n, "finish") + row_flags = _unpack_col(frame.row_flags, "H", n, "row_flags") + stop_indices = ( + _unpack_col(frame.stop_index, "i", n, "stop_index") + if frame.stop_index + else [NO_STOP_INDEX] * n + ) + replace_froms = ( + _unpack_col(frame.replace_from, "I", n, "replace_from") + if frame.replace_from + else [NO_REPLACE_FROM] * n + ) + cum_logprobs = ( + _unpack_col(frame.cum_logprob, "d", n, "cum_logprob") if frame.cum_logprob else None + ) + decoding_iters = ( + _unpack_col(frame.decoding_iter, "I", n, "decoding_iter") + if frame.decoding_iter + else [0] * n + ) + cached_tokens = ( + _unpack_col(frame.cached_tokens, "I", n, "cached_tokens") + if frame.cached_tokens + else [0] * n + ) + + extra_indices = ( + _unpack_col(frame.extra_index, "I", n, "extra_index") if frame.extra_index else None + ) + num_extras = len(frame.extras) + + lp_sampled_all = ( + _unpack_col(frame.lp_sampled, "f", total_tokens, "lp_sampled") + if (frame.lp_sampled and total_tokens > 0) + else None + ) + lp_rank_all = ( + _unpack_col(frame.lp_rank, "I", total_tokens, "lp_rank") + if (frame.lp_rank and total_tokens > 0) + else None + ) + lp_topk_offsets = ( + _unpack_col(frame.lp_topk_offsets, "I", total_tokens + 1, "lp_topk_offsets") + if (frame.lp_topk_offsets and total_tokens > 0) + else None + ) + lp_topk_ids = None + lp_topk_lps = None + if lp_topk_offsets is not None: + if lp_topk_offsets[0] != 0: + raise ValueError(f"lp_topk_offsets[0]={lp_topk_offsets[0]} != 0") + for i in range(total_tokens): + if lp_topk_offsets[i] > lp_topk_offsets[i + 1]: + raise ValueError(f"lp_topk_offsets not monotonic at {i}") + total_cands = lp_topk_offsets[-1] + lp_topk_ids = ( + _unpack_col(frame.lp_topk_ids, "i", total_cands, "lp_topk_ids") + if total_cands > 0 + else [] + ) + lp_topk_lps = ( + _unpack_col(frame.lp_topk_logprobs, "f", total_cands, "lp_topk_logprobs") + if total_cands > 0 + else [] + ) + + rows: list[FrameRow] = [] + for i in range(n): + t0, t1 = token_offsets[i], token_offsets[i + 1] + toks = all_tokens[t0:t1] + flags = row_flags[i] + extra_obj = None + if flags & ROW_FLAG_HAS_EXTRA: + if extra_indices is None: + raise ValueError(f"Row {i} sets HAS_EXTRA but extra_index column is absent") + eidx = extra_indices[i] + if eidx >= num_extras: + raise ValueError(f"Row {i} extra_index {eidx} >= len(extras) {num_extras}") + extra_obj = frame.extras[eidx] + + clp = None + if cum_logprobs is not None: + v = cum_logprobs[i] + if not math.isnan(v): + clp = v + + row_lp_sampled = None + if lp_sampled_all is not None and t1 > t0: + sl = lp_sampled_all[t0:t1] + if not all(math.isnan(x) for x in sl): + row_lp_sampled = sl + + row_lp_rank = None + if lp_rank_all is not None and t1 > t0 and row_lp_sampled is not None: + row_lp_rank = lp_rank_all[t0:t1] + + row_lp_topk = None + if ( + lp_topk_offsets is not None + and t1 > t0 + and lp_topk_ids is not None + and lp_topk_lps is not None + ): + cands_per_tok: list[list[tuple[int, float]]] = [] + any_cand = False + for ti in range(t0, t1): + c0, c1 = lp_topk_offsets[ti], lp_topk_offsets[ti + 1] + if c1 > c0: + any_cand = True + cands_per_tok.append([(lp_topk_ids[ci], lp_topk_lps[ci]) for ci in range(c0, c1)]) + if any_cand or row_lp_sampled is not None: + row_lp_topk = cands_per_tok + + rows.append( + FrameRow( + handle=handles[i], + seq=seqs[i], + tokens=toks, + finish=finishes[i], + row_flags=flags, + stop_index=stop_indices[i], + replace_from=replace_froms[i], + cum_logprob=clp, + decoding_iter=decoding_iters[i], + cached_tokens=cached_tokens[i], + lp_sampled=row_lp_sampled, + lp_rank=row_lp_rank, + lp_topk=row_lp_topk, + extra=extra_obj, + ) + ) + return rows + + +# ============================================================================ +# Serialized Frame / ServerMessage / ClientMessage helpers +# ============================================================================ + + +@dataclasses.dataclass(slots=True) +class DecodedFrame: + """A Frame decoded from its serialized bytes.""" + + frame_seq: int + iter_first: int + iter_last: int + emit_time_ns: int + rows: list[FrameRow] + acks: list[ProtoMessage] + iteration_stats: list[ProtoMessage] + lora_set_changed: list[ProtoMessage] + + +@dataclasses.dataclass(slots=True) +class ClientMessageView: + """The fields of a ClientMessage that the engine reads, by payload ``kind``. + + ``kind`` is ``"submit_batch"``, ``"cancel_batch"``, ``"progress"``, ``"open"`` or + None when no payload is set. + """ + + kind: str | None + consumed_frame_seq: int = 0 + requests: list[ProtoMessage] = dataclasses.field(default_factory=list) + cancels: list[tuple[int, int]] = dataclasses.field(default_factory=list) + cancel_all: bool = False + cancel_all_reason: int = 0 + open: ProtoMessage | None = None + + +_SERVER_PAYLOAD_TYPES: dict[str, type[ProtoMessage]] = { + "accepted": pb.session_pb2.SessionAccepted, + "submit_ack": pb.common_pb2.SubmitAck, + "notice": pb.session_pb2.SessionNotice, + "iteration_stats": pb.stats_pb2.IterationStats, + "lora_set_changed": pb.common_pb2.LoraSetChanged, +} + + +def _parse_message(message_type: type[_MsgT], data: bytes) -> _MsgT: + try: + return message_type.FromString(data) + except DecodeError as exc: + raise ValueError(f"malformed {message_type.DESCRIPTOR.name}: {exc}") from exc + + +def _decoded_frame_from_native( + decoded: tuple[tuple[object, ...], list[FrameRow]], +) -> DecodedFrame: + header, rows = decoded + frame_seq, iter_first, iter_last, emit_time_ns, _, acks, stats, lora = header + return DecodedFrame( + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=emit_time_ns, + rows=_parse_row_extras(rows), + acks=[pb.common_pb2.SubmitAck.FromString(b) for b in acks], + iteration_stats=[pb.stats_pb2.IterationStats.FromString(b) for b in stats], + lora_set_changed=[pb.common_pb2.LoraSetChanged.FromString(b) for b in lora], + ) + + +def _decoded_frame_from_message(frame: ProtoMessage) -> DecodedFrame: + return DecodedFrame( + frame_seq=frame.frame_seq, + iter_first=frame.iter_first, + iter_last=frame.iter_last, + emit_time_ns=frame.emit_time_ns, + rows=_decode_frame_python(frame), + acks=list(frame.acks), + iteration_stats=list(frame.iteration_stats), + lora_set_changed=list(frame.lora_set_changed), + ) + + +def encode_frame_bytes( + rows: Sequence[FrameRow], + *, + frame_seq: int, + iter_first: int = 0, + iter_last: int = 0, + emit_time_ns: int = 0, + acks: Sequence[ProtoMessage | bytes] = (), + iteration_stats: Sequence[ProtoMessage | bytes] = (), + lora_set_changed: Sequence[ProtoMessage | bytes] = (), + server_message: bool = False, + backend: str | None = None, +) -> bytes: + """``encode_frame(...)`` serialized, wrapped in ServerMessage{frame} when ``server_message``.""" + kwargs = dict( + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=emit_time_ns, + acks=acks, + iteration_stats=iteration_stats, + lora_set_changed=lora_set_changed, + ) + native = _native.resolve(backend) + if native is not None: + return native.encode_frame(rows, server_message=server_message, **kwargs) + frame = _encode_frame_python(rows, **kwargs) + if server_message: + return pb.session_pb2.ServerMessage(frame=frame).SerializeToString() + return frame.SerializeToString() + + +def decode_frame_bytes(data: bytes, *, backend: str | None = None) -> DecodedFrame: + """Decode serialized Frame bytes. Raises ValueError on malformed bytes or columns.""" + native = _native.resolve(backend) + if native is not None: + return _decoded_frame_from_native(native.decode_frame(data, FrameRow)) + return _decoded_frame_from_message(_parse_message(pb.output_pb2.Frame, data)) + + +def parse_server_message( + data: bytes, *, backend: str | None = None +) -> tuple[str | None, DecodedFrame | ProtoMessage | None]: + """Parse ServerMessage bytes into ``(kind, payload)``. + + ``kind`` names the oneof payload (None when unset); a frame payload is a + DecodedFrame, any other payload its message. Raises ValueError on malformed bytes. + """ + native = _native.resolve(backend) + if native is not None: + kind, payload = native.parse_server_message(data, FrameRow) + if kind is None: + return None, None + if kind == "frame": + return kind, _decoded_frame_from_native(payload) + return kind, _SERVER_PAYLOAD_TYPES[kind].FromString(payload) + message = _parse_message(pb.session_pb2.ServerMessage, data) + kind = message.WhichOneof("payload") + if kind is None: + return None, None + if kind == "frame": + return kind, _decoded_frame_from_message(message.frame) + return kind, getattr(message, kind) + + +def parse_client_message(data: bytes, *, backend: str | None = None) -> ClientMessageView: + """Parse and validate ClientMessage bytes. Raises ValueError on malformed bytes. + + The native parser hands each Request back as bytes that are parsed again here, + which is slower than protobuf's own parser, so ``auto`` uses Python. + """ + native = _native.resolve(backend, auto_native=False) + if native is not None: + parsed = native.parse_client_message(data) + kind = parsed[0] + if kind == "submit_batch": + return ClientMessageView( + kind=kind, + consumed_frame_seq=parsed[1], + requests=[pb.request_pb2.Request.FromString(b) for b in parsed[2]], + ) + if kind == "cancel_batch": + return ClientMessageView( + kind=kind, + consumed_frame_seq=parsed[1], + cancel_all=parsed[2], + cancel_all_reason=parsed[3], + cancels=list(parsed[4]), + ) + if kind == "progress": + return ClientMessageView(kind=kind, consumed_frame_seq=parsed[1]) + if kind == "open": + return ClientMessageView( + kind=kind, open=pb.session_pb2.SessionOpen.FromString(parsed[1]) + ) + return ClientMessageView(kind=None) + message = _parse_message(pb.session_pb2.ClientMessage, data) + kind = message.WhichOneof("payload") + if kind == "submit_batch": + batch = message.submit_batch + return ClientMessageView( + kind=kind, + consumed_frame_seq=batch.consumed_frame_seq, + requests=list(batch.requests), + ) + if kind == "cancel_batch": + batch = message.cancel_batch + return ClientMessageView( + kind=kind, + consumed_frame_seq=batch.consumed_frame_seq, + cancel_all=batch.all, + cancel_all_reason=batch.all_reason, + cancels=[(item.handle, item.reason) for item in batch.cancels], + ) + if kind == "progress": + return ClientMessageView(kind=kind, consumed_frame_seq=message.progress.consumed_frame_seq) + if kind == "open": + return ClientMessageView(kind=kind, open=message.open) + return ClientMessageView(kind=None) + + +def encode_submit_batch( + requests: Sequence[ProtoMessage | bytes], + *, + consumed_frame_seq: int = 0, + backend: str | None = None, +) -> bytes: + """Serialized ClientMessage{submit_batch} carrying Request messages.""" + native = _native.resolve(backend) + if native is not None: + return native.encode_submit_batch(requests, consumed_frame_seq=consumed_frame_seq) + batch = pb.session_pb2.SubmitBatch(requests=requests, consumed_frame_seq=consumed_frame_seq) + return pb.session_pb2.ClientMessage(submit_batch=batch).SerializeToString() + + +def encode_cancel_batch( + cancels: Sequence[tuple[int, int]], + *, + cancel_all: bool = False, + cancel_all_reason: int = 0, + consumed_frame_seq: int = 0, + backend: str | None = None, +) -> bytes: + """Serialized ClientMessage{cancel_batch} from ``(handle, reason)`` pairs.""" + native = _native.resolve(backend) + if native is not None: + return native.encode_cancel_batch( + cancels, + all=cancel_all, + all_reason=cancel_all_reason, + consumed_frame_seq=consumed_frame_seq, + ) + batch = pb.session_pb2.CancelBatch( + cancels=[pb.session_pb2.CancelItem(handle=h, reason=r) for h, r in cancels], + all=cancel_all, + all_reason=cancel_all_reason, + consumed_frame_seq=consumed_frame_seq, + ) + return pb.session_pb2.ClientMessage(cancel_batch=batch).SerializeToString() + + +# ============================================================================ +# TensorRef / InlineTensor / SHM / CUDA_IPC / Blob helpers +# ============================================================================ + + +def dtype_from_tensor(tensor: object) -> int: + name = str(getattr(tensor, "dtype", "")) + dt = _NAME_TO_DTYPE.get(name) + if dt is None: + raise ValueError(f"Unsupported tensor dtype: {name!r}") + return dt + + +def tensor_to_raw_bytes(tensor: object) -> tuple[int, list[int], bytes]: + """Convert torch.Tensor or numpy.ndarray into (DType, shape, raw_le_bytes).""" + dt, shape, mv = tensor_to_raw_view(tensor) + return dt, shape, mv.tobytes() + + +def tensor_to_raw_view(tensor: object) -> tuple[int, list[int], memoryview]: + """Convert torch.Tensor or numpy.ndarray into (DType, shape, 1D uint8 memoryview) without copying.""" + dt = dtype_from_tensor(tensor) + shape = [int(d) for d in tensor.shape] + if hasattr(tensor, "detach"): # torch.Tensor + import torch + + t = tensor.detach().cpu().contiguous() + if t.dtype == torch.bfloat16 or ( + hasattr(torch, "float8_e4m3fn") and t.dtype == torch.float8_e4m3fn + ): + arr = t.view(torch.uint8).numpy() + else: + arr = t.numpy() + return dt, shape, memoryview(arr).cast("B") + import numpy as np + + arr = np.ascontiguousarray(tensor) + return dt, shape, memoryview(arr).cast("B") + + +def raw_bytes_to_tensor( + dtype: int, + shape: Sequence[int], + raw: bytes | bytearray | memoryview, + *, + prefer_torch: bool = True, +) -> object: + """Reconstruct torch.Tensor (preferred if installed) or numpy.ndarray from (DType, shape, raw_bytes).""" + info = DTYPE_INFO.get(dtype) + if info is None: + raise ValueError(f"Unsupported DType enum: {dtype}") + np_name, torch_name, itemsize = info + numel = 1 + for d in shape: + numel *= int(d) + expected = numel * itemsize + if len(raw) != expected: + raise ValueError( + f"Tensor byte size {len(raw)} != expected {expected} for shape={list(shape)} dtype={torch_name}" + ) + if prefer_torch: + try: + import torch + + tdtype = getattr(torch, torch_name) + if numel == 0: + return torch.empty(tuple(shape), dtype=tdtype) + buf = raw if isinstance(raw, bytearray) else bytearray(raw) + return torch.frombuffer(buf, dtype=torch.uint8).view(tdtype).reshape(tuple(shape)) + except ImportError: + pass + import numpy as np + + if np_name in ("bfloat16", "float8_e4m3fn"): + # Fallback to uint8 view when torch is unavailable + return np.frombuffer(raw, dtype=np.uint8).copy() + return np.frombuffer(raw, dtype=np.dtype(np_name)).reshape(tuple(shape)).copy() + + +def tensor_to_inline_tensor(tensor: object) -> ProtoMessage: + dt, shape, raw = tensor_to_raw_bytes(tensor) + return pb.common_pb2.InlineTensor(dtype=dt, shape=shape, data=raw) + + +def inline_tensor_to_tensor(msg: ProtoMessage, *, prefer_torch: bool = True) -> object: + return raw_bytes_to_tensor(msg.dtype, list(msg.shape), msg.data, prefer_torch=prefer_torch) + + +def _shm_root_dir() -> Path: + shm_root = Path("/dev/shm") # nosec B108 + if shm_root.is_dir() and os.access(shm_root, os.W_OK): + return shm_root + return Path(tempfile.gettempdir()) + + +def _shm_path_for_name(name: str) -> Path: + if not isinstance(name, str) or not name: + raise ValueError(f"Invalid SHM name: {name!r}") + if "\x00" in name: + raise ValueError(f"Invalid SHM name containing NUL byte: {name!r}") + # Strip at most one leading '/' (POSIX shm_open convention); reject any other separators. + clean = name[1:] if name.startswith("/") else name + if not clean or clean in (".", "..") or "/" in clean or "\\" in clean: + raise ValueError(f"Invalid SHM segment name (path traversal rejected): {name!r}") + if not _SHM_SAFE_BASENAME_RE.match(clean): + raise ValueError(f"Invalid SHM segment name characters: {name!r}") + root = _shm_root_dir().resolve() + candidate = root / clean + if candidate.parent.resolve() != root: + raise ValueError(f"SHM path escapes root directory: {name!r}") + return candidate + + +def write_shm_bytes( + raw: bytes | bytearray | memoryview, *, prefix: str = "trtllm_se_" +) -> ProtoMessage: + """Write raw bytes-like buffer to a shared-memory file and return common_pb2.ShmLocation.""" + name = f"/{prefix}{os.getpid()}_{uuid.uuid4().hex}" + path = _shm_path_for_name(name) + flags = os.O_CREAT | os.O_EXCL | os.O_RDWR | getattr(os, "O_CLOEXEC", 0) + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + mv = memoryview(raw).cast("B") + size = len(mv) + fd = os.open(str(path), flags, 0o600) + try: + if size: + os.ftruncate(fd, size) + with mmap.mmap(fd, size, access=mmap.ACCESS_WRITE) as mm: + mm[:] = mv + finally: + os.close(fd) + return pb.common_pb2.ShmLocation(name=name, offset=0, size=size) + + +def _read_shm_into_bytearray(loc: ProtoMessage, *, unlink: bool = False) -> bytearray: + path = _shm_path_for_name(loc.name) + offset = int(loc.offset) + size = int(loc.size) + if offset < 0 or size < 0: + raise ValueError(f"Invalid SHM bounds: offset={offset}, size={size}") + + open_flags = ( + os.O_RDONLY + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_NONBLOCK", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + fd = os.open(str(path), open_flags) + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + raise ValueError(f"SHM target is not a regular file: {loc.name!r}") + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + raise PermissionError( + f"SHM segment {loc.name!r} uid={st.st_uid} does not match current uid={os.getuid()}" + ) + if offset + size > st.st_size: + raise ValueError( + f"SHM slice [{offset}:{offset + size}] exceeds segment size {st.st_size}" + ) + buf = bytearray(size) + if size > 0: + with os.fdopen(fd, "rb") as f: + fd = -1 + f.seek(offset) + nread = f.readinto(buf) + if nread != size: + raise ValueError(f"SHM short read: got {nread} bytes, expected {size}") + finally: + if fd >= 0: + os.close(fd) + + if unlink: + unlink_shm(loc) + return buf + + +def read_shm_bytes(loc: ProtoMessage, *, unlink: bool = False) -> bytes: + return bytes(_read_shm_into_bytearray(loc, unlink=unlink)) + + +def read_shm_bytearray(loc: ProtoMessage, *, unlink: bool = False) -> bytearray: + """Read an SHM slice directly into a fresh mutable bytearray (avoids bytes->bytearray copy).""" + return _read_shm_into_bytearray(loc, unlink=unlink) + + +def unlink_shm(loc: ProtoMessage) -> None: + path = _shm_path_for_name(loc.name) + try: + st = os.lstat(path) + except FileNotFoundError: + return + if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode): + raise ValueError(f"Refusing to unlink non-regular SHM path: {loc.name!r}") + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + raise PermissionError( + f"Refusing to unlink SHM segment {loc.name!r} owned by uid={st.st_uid}" + ) + try: + path.unlink() + except FileNotFoundError: + pass + + +def make_cuda_ipc_ref(tensor: object) -> tuple[ProtoMessage, object] | None: + """Create a TensorRef using CUDA IPC if `tensor` is a CUDA torch.Tensor. + + Returns (TensorRef, keepalive_tensor) or None if unavailable. + """ + if not (hasattr(tensor, "is_cuda") and tensor.is_cuda): + return None + t = tensor.detach().contiguous() + storage = t.untyped_storage() + try: + # _share_cuda_() tuple: + # (device, handle, size, offset, ref_cnt_handle, ref_cnt_offset, event_handle, sync) + info = storage._share_cuda_() + except RuntimeError as exc: + logger.debug("CUDA IPC _share_cuda_ unavailable: %s", exc) + return None + if len(info) > 4 and info[4]: + logger.debug( + "CUDA IPC skipped: storage carries a PyTorch caching-allocator ref_counter_handle, " + "which CudaIpcLocation cannot transport; falling back to non-IPC delivery" + ) + return None + dev_idx = int(info[0]) + mem_handle = bytes(info[1]) + offset_bytes = int(info[3]) + int(t.storage_offset()) * int(t.element_size()) + event_handle = bytes(info[6]) if info[6] else b"" + dt = dtype_from_tensor(t) + ref = pb.common_pb2.TensorRef( + dtype=dt, + shape=[int(d) for d in t.shape], + cuda_ipc=pb.common_pb2.CudaIpcLocation( + device=dev_idx, + mem_handle=mem_handle, + offset=offset_bytes, + size=t.numel() * t.element_size(), + event_handle=event_handle, + ), + device=dev_idx, + ) + return ref, t + + +def open_cuda_ipc_ref(ref: ProtoMessage) -> object: + """Validate TensorRef.cuda_ipc and reject PyTorch caching-allocator reconstruction.""" + import torch + + loc = ref.cuda_ipc + info = DTYPE_INFO.get(int(ref.dtype)) + if info is None: + raise ValueError(f"Unsupported DType enum for CUDA IPC: {ref.dtype}") + dev_idx = int(loc.device) + dev_count = torch.cuda.device_count() + if dev_idx < 0 or dev_idx >= dev_count: + raise ValueError(f"CUDA IPC device {dev_idx} out of range [0, {dev_count})") + if len(loc.mem_handle) != _CUDA_IPC_HANDLE_BYTES: + raise ValueError( + f"CUDA IPC mem_handle must be {_CUDA_IPC_HANDLE_BYTES} bytes, got {len(loc.mem_handle)}" + ) + if len(loc.event_handle) not in (0, _CUDA_IPC_HANDLE_BYTES): + raise ValueError( + f"CUDA IPC event_handle must be 0 or {_CUDA_IPC_HANDLE_BYTES} bytes, " + f"got {len(loc.event_handle)}" + ) + offset = int(loc.offset) + size = int(loc.size) + if offset < 0 or size < 0: + raise ValueError(f"Invalid CUDA IPC bounds: offset={offset}, size={size}") + numel = 1 + for d in ref.shape: + di = int(d) + if di < 0: + raise ValueError(f"Invalid negative dimension in CUDA IPC shape: {list(ref.shape)}") + numel *= di + expected_bytes = numel * info[2] + if size != expected_bytes: + raise ValueError( + f"CUDA IPC size {size} != expected {expected_bytes} for shape={list(ref.shape)} " + f"dtype={info[1]}" + ) + raise NotImplementedError( + "CudaIpcLocation does not carry PyTorch CUDA IPC refcounter metadata " + "(ref_counter_handle / ref_counter_offset) required by " + "torch.UntypedStorage._new_shared_cuda; CUDA IPC tensors cannot be safely " + "reconstructed via the PyTorch caching allocator without refcounter handles" + ) + + +# ============================================================================ +# TypedExtension helpers +# ============================================================================ + + +def python_to_typed_value(value: object) -> ProtoMessage: + """Convert a Python scalar/bytes/list/JSON value to common_pb2.TypedValue.""" + if isinstance(value, bool): + return pb.common_pb2.TypedValue(bool_value=value) + if isinstance(value, int): + return pb.common_pb2.TypedValue(i64_value=value) + if isinstance(value, float): + return pb.common_pb2.TypedValue(f64_value=value) + if isinstance(value, str): + return pb.common_pb2.TypedValue(string_value=value) + if isinstance(value, (bytes, bytearray)): + return pb.common_pb2.TypedValue(bytes_value=bytes(value)) + if isinstance(value, (list, tuple)): + if all(isinstance(x, int) and not isinstance(x, bool) for x in value): + return pb.common_pb2.TypedValue(i64_list=pb.common_pb2.I64List(values=list(value))) + if all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in value): + return pb.common_pb2.TypedValue( + f64_list=pb.common_pb2.F64List(values=[float(x) for x in value]) + ) + return pb.common_pb2.TypedValue(json=json.dumps(value, sort_keys=True, separators=(",", ":"))) + + +def typed_value_to_python(tv: ProtoMessage) -> object: + kind = tv.WhichOneof("value") + if kind == "bool_value": + return bool(tv.bool_value) + if kind == "i64_value": + return int(tv.i64_value) + if kind == "f64_value": + return float(tv.f64_value) + if kind == "string_value": + return str(tv.string_value) + if kind == "bytes_value": + return bytes(tv.bytes_value) + if kind == "i64_list": + return list(tv.i64_list.values) + if kind == "f64_list": + return list(tv.f64_list.values) + if kind == "json": + return json.loads(tv.json) + return None + + +def dict_to_typed_extension(namespace: str, mapping: Mapping[str, object]) -> ProtoMessage: + entries = [ + pb.common_pb2.ExtensionEntry(key=str(k), value=python_to_typed_value(v)) + for k, v in sorted(mapping.items()) + ] + return pb.common_pb2.TypedExtension(ext_namespace=namespace, entries=entries) + + +def typed_extension_to_dict(ext: ProtoMessage) -> dict[str, object]: + return {e.key: typed_value_to_python(e.value) for e in ext.entries} + + +# ============================================================================ +# SignedHandoff / RendezvousTicket HMAC helpers (kept in contract for custom engines & tests) +# ============================================================================ + +_SIGNED_HANDOFF_DOMAIN = b"trtllm.engine.v1.SignedHandoff\x00" + + +def sign_handoff( + handoff_msg: ProtoMessage, key: bytes | None = None, key_id: str = "" +) -> ProtoMessage: + """Wrap KvHandoff in SignedHandoff. When key is None/empty, emits an unsigned envelope.""" + raw = handoff_msg.SerializeToString() + if not key: + return pb.disagg_pb2.SignedHandoff(handoff_bytes=raw, mac=b"", key_id="") + kid_bytes = key_id.encode("utf-8") + mac = hmac.new( + key, + _SIGNED_HANDOFF_DOMAIN + struct.pack(" ProtoMessage: + """Verify MAC (if keys configured, required, or present) before parsing KvHandoff.""" + must_verify = bool(keys) if require_signature is None else bool(require_signature) + if signed.key_id and not signed.mac: + raise ValueError(f"SignedHandoff carries key_id={signed.key_id!r} with empty mac") + if must_verify or signed.mac: + if not signed.mac: + raise ValueError("SignedHandoff missing required HMAC signature") + if not keys or signed.key_id not in keys: + raise ValueError(f"Unknown or missing HMAC key_id={signed.key_id!r}") + kid_bytes = signed.key_id.encode("utf-8") + expected = hmac.new( + keys[signed.key_id], + _SIGNED_HANDOFF_DOMAIN + + struct.pack(" None: def handle_for_ipc_batched(self, responses: List[tllm.Response]) -> None: ''' Perform the IPC in batch explicitly. ''' + if self.serve_engine_wire_mode != "off": + from .zmq_wire.worker_bridge import worker_publish_responses + if worker_publish_responses( + self.worker, + responses, + mode=self.serve_engine_wire_mode, + enable_postproc=self.enable_postprocprocess_parallel): + return postproc_batches = [ [] for _ in range(self.worker.postproc_config.num_postprocess_workers) diff --git a/tensorrt_llm/executor/ipc.py b/tensorrt_llm/executor/ipc.py index 8f10f68308de..e32aa3f6a678 100644 --- a/tensorrt_llm/executor/ipc.py +++ b/tensorrt_llm/executor/ipc.py @@ -21,7 +21,7 @@ import time import traceback from queue import Queue -from typing import Any, Callable, Optional +from typing import Any, Callable, NamedTuple, Optional import zmq import zmq.asyncio @@ -36,6 +36,18 @@ # default, so closing never waits forever for a peer that has exited. CLOSE_LINGER_MS = 1000 +# serve_engine.v1 frames (tensorrt_llm/executor/zmq_wire/transport.py) start with this +# magic byte and one of these channel tags; pickled messages start with 0x80. +SERVE_ENGINE_FRAME_MAGIC = 0x53 +SERVE_ENGINE_CHANNEL_TAGS = frozenset((1, 2, 3, 4, 5)) +# 6-byte header + 32-byte HMAC-SHA256. +SERVE_ENGINE_MIN_FRAME_SIZE = 38 + + +class RawServeEngineFrame(NamedTuple): + """An authenticated serve_engine.v1 frame returned by ZeroMqQueue.get() unparsed.""" + data: bytes + class ZeroMqQueue: ''' A Queue-like container for IPC using ZeroMQ. ''' @@ -48,6 +60,9 @@ class ZeroMqQueue: zmq.DEALER: "DEALER", } + _serve_engine_wire_enabled = False + _serve_engine_wire_strict = False + def __init__(self, address: Optional[tuple[str, Optional[bytes]]] = None, *, @@ -55,7 +70,9 @@ def __init__(self, is_server: bool, is_async: bool = False, name: Optional[str] = None, - use_hmac_encryption: bool = True): + use_hmac_encryption: bool = True, + serve_engine_wire_enabled: bool = False, + serve_engine_wire_strict: bool = False): ''' Parameters: address (tuple[str, Optional[bytes]], optional): The address (tcp-ip_port, hmac_auth_key) for the IPC. Defaults to None. If hmac_auth_key is None and use_hmac_encryption is False, the queue will not use HMAC encryption. @@ -64,6 +81,10 @@ def __init__(self, is_async (bool): Whether to use asyncio for the socket. Defaults to False. name (str, optional): The name of the queue. Defaults to None. use_hmac_encryption (bool): Whether to use HMAC encryption for pickled data. Defaults to True. + serve_engine_wire_enabled (bool): Whether get() returns authenticated serve_engine.v1 + frames (magic 0x53) as RawServeEngineFrame instead of unpickling them. Defaults to False. + serve_engine_wire_strict (bool): Whether get() rejects every message that is not a + serve_engine.v1 frame before unpickling it. Defaults to False. ''' if not use_hmac_encryption: @@ -89,6 +110,12 @@ def __init__(self, self.hmac_key = address[1] if address is not None else None self.use_hmac_encryption = use_hmac_encryption + self._serve_engine_wire_enabled = bool(serve_engine_wire_enabled + or serve_engine_wire_strict) + self._serve_engine_wire_strict = bool(serve_engine_wire_strict) + # Serializes sends from the threads that share this socket when it carries + # serve_engine.v1 frames. + self._send_lock = threading.Lock() # Run on the receiving thread between receiving a message and parsing it. self.parse_gate: Optional[Callable[[], None]] = None @@ -107,6 +134,9 @@ def __init__(self, raise ValueError( "Server and client should not receive HMAC key when encryption is disabled" ) + if self._serve_engine_wire_strict and not self.use_hmac_encryption: + raise ValueError( + "serve_engine_wire_strict requires use_hmac_encryption=True") if self.should_bind_socket(): self.socket.bind( @@ -371,6 +401,11 @@ async def get_async_noblock(self, if self.use_hmac_encryption: data = await self.socket.recv(flags=zmq.NOBLOCK) obj = self._parse_data(data) + elif self._serve_engine_wire_strict: + from .zmq_wire.transport import StrictProtoWireError + raise StrictProtoWireError( + "Strict serve_engine ZMQ mode forbids unencrypted recv_pyobj()" + ) else: obj = await self.socket.recv_pyobj(flags=zmq.NOBLOCK ) @@ -442,6 +477,10 @@ def _prepare_data(self, obj: Any) -> bytes: def _parse_data(self, data: bytes) -> Any: """Parse data and optionally verify HMAC signature.""" + if self._serve_engine_wire_enabled: + raw = self._parse_serve_engine_frame(data) + if raw is not None: + return raw if self.use_hmac_encryption: # Split data and HMAC message_data = data[:-32] @@ -455,18 +494,94 @@ def _parse_data(self, data: bytes) -> Any: else: return pickle.loads(data) # nosec B301 + def _parse_serve_engine_frame( + self, data: bytes) -> Optional["RawServeEngineFrame"]: + """Return an authenticated serve_engine.v1 frame, or None for a pickled message. + + The HMAC of a serve_engine.v1 frame is verified before the frame is returned. In strict + mode any other message is rejected here, before it can reach pickle.loads. + """ + if (self.use_hmac_encryption + and len(data) >= SERVE_ENGINE_MIN_FRAME_SIZE + and data[0] == SERVE_ENGINE_FRAME_MAGIC + and data[1] in SERVE_ENGINE_CHANNEL_TAGS): + if not self.hmac_key or not self._verify_hmac( + data[:-32], data[-32:]): + raise RuntimeError("HMAC verification failed") + return RawServeEngineFrame(data) + if self._serve_engine_wire_strict: + from .zmq_wire.transport import StrictProtoWireError + raise StrictProtoWireError( + f"Strict serve_engine ZMQ mode rejected a non-serve_engine message " + f"(len={len(data)}, first_byte={data[0] if data else None!r}) " + "before pickle.loads") + return None + def _send_data(self, data: bytes, flags: int = 0, routing_id: Optional[bytes] = None): """Send data using appropriate API based on socket type.""" - if self.socket_type == zmq.ROUTER: - identity = routing_id if routing_id is not None else self._last_identity - if identity is None: - raise ValueError("ROUTER socket requires identity") - self.socket.send_multipart([identity, data], flags=flags) - else: - self.socket.send(data, flags=flags) + with self._send_lock: + if self.socket_type == zmq.ROUTER: + identity = routing_id if routing_id is not None else self._last_identity + if identity is None: + raise ValueError("ROUTER socket requires identity") + self.socket.send_multipart([identity, data], flags=flags) + else: + self.socket.send(data, flags=flags) + + def send_raw(self, data: bytes) -> None: + """Send pre-serialized bytes, such as a signed serve_engine.v1 frame.""" + self.setup_lazily() + self._send_data(data) + + def send_raw_noblock(self, + data: bytes, + *, + retry: int = 1, + wait_time: float = 0.001, + timeout_ms: Optional[int] = None) -> bool: + """Send pre-serialized bytes without blocking, retrying like ``put_noblock``. + + When ``timeout_ms`` is provided, polls for ``zmq.POLLOUT`` up to that bounded + budget before each non-blocking send so lazy connection handshakes and transient + backpressure succeed while a peerless socket still returns promptly. + + Returns whether the bytes were sent; like ``put_noblock`` it logs + instead of raising when the peer does not take them. + """ + self.setup_lazily() + if timeout_ms is not None: + if timeout_ms < 0: + raise ValueError(f"timeout_ms must be >= 0, got {timeout_ms}") + deadline = time.monotonic() + (timeout_ms / 1000.0) + while True: + try: + self._send_data(data, flags=zmq.NOBLOCK) + return True + except zmq.Again: + remaining_ms = int((deadline - time.monotonic()) * 1000) + if remaining_ms <= 0: + break + if self.socket.poll(timeout=remaining_ms, + flags=zmq.POLLOUT) == 0: + break + logger.warning( + f"Failed to send {len(data)} raw bytes on {self.name} within {timeout_ms}ms" + ) + return False + + assert 0 <= retry <= 10, "Retry must be between 0 and 10, adjust the wait_time if needed" + for attempt in range(retry + 1): + try: + self._send_data(data, flags=zmq.NOBLOCK) + return True + except zmq.Again: + if attempt < retry: + time.sleep(wait_time) + logger.error(f"Failed to send {len(data)} raw bytes on {self.name}") + return False async def _send_data_async(self, data: bytes, @@ -495,6 +610,11 @@ def _recv_data(self, return_identity: bool = False) -> Any: data = self.socket.recv() self._wait_for_parse_gate() obj = self._parse_data(data) + elif self._serve_engine_wire_strict: + from .zmq_wire.transport import StrictProtoWireError + raise StrictProtoWireError( + "Strict serve_engine ZMQ mode forbids unencrypted recv_pyobj()" + ) else: obj = self.socket.recv_pyobj() @@ -519,6 +639,11 @@ async def _recv_data_async(self, return_identity: bool = False) -> Any: if self.use_hmac_encryption: data = await self.socket.recv() obj = self._parse_data(data) + elif self._serve_engine_wire_strict: + from .zmq_wire.transport import StrictProtoWireError + raise StrictProtoWireError( + "Strict serve_engine ZMQ mode forbids unencrypted recv_pyobj()" + ) else: obj = await self.socket.recv_pyobj() diff --git a/tensorrt_llm/executor/native/CMakeLists.txt b/tensorrt_llm/executor/native/CMakeLists.txt new file mode 100644 index 000000000000..3189ceb6f430 --- /dev/null +++ b/tensorrt_llm/executor/native/CMakeLists.txt @@ -0,0 +1,113 @@ +# +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# + +# Native codec of the trtllm.engine.v1 wire, compiled into the bindings module +# as tensorrt_llm.bindings.internal.engine_wire. The eight contract protos under +# contracts/engine/v1/ are compiled with protoc into C++. protobuf and abseil +# are linked statically with hidden visibility so their symbols stay inside the +# module. +# +# Sets ENGINE_WIRE_SOURCES and ENGINE_WIRE_INCLUDE_DIRS in the parent scope; the +# consumer must depend on the engine_wire_proto target and link libprotobuf. + +function(engine_wire_fetch_protobuf) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) + set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) + set(ABSL_PROPAGATE_CXX_STD ON) + set(ABSL_ENABLE_INSTALL OFF) + set(ABSL_BUILD_TESTING OFF) + set(protobuf_BUILD_TESTS OFF) + set(protobuf_INSTALL OFF) + set(protobuf_BUILD_SHARED_LIBS OFF) + set(protobuf_WITH_ZLIB OFF) + set(protobuf_ABSL_PROVIDER module) + FetchContent_MakeAvailable(abseil-cpp protobuf) +endfunction() + +if(NOT TARGET libprotobuf) + engine_wire_fetch_protobuf() +endif() + +get_filename_component(ENGINE_WIRE_PROTO_ROOT + ${CMAKE_CURRENT_SOURCE_DIR}/../../../contracts ABSOLUTE) +set(ENGINE_WIRE_PROTO_NAMES + capabilities + common + control + disagg + output + request + session + stats) +set(ENGINE_WIRE_GENERATED_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated) +set(ENGINE_WIRE_PY_GENERATED_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated_py) +set(ENGINE_WIRE_PROTO_FILES) +set(ENGINE_WIRE_PB_SOURCES) +set(ENGINE_WIRE_PB_OUTPUTS) +set(ENGINE_WIRE_PY_OUTPUTS ${ENGINE_WIRE_PY_GENERATED_DIR}/__init__.py + ${ENGINE_WIRE_PY_GENERATED_DIR}/.contracts-generated) +foreach(name ${ENGINE_WIRE_PROTO_NAMES}) + list(APPEND ENGINE_WIRE_PROTO_FILES + ${ENGINE_WIRE_PROTO_ROOT}/engine/v1/${name}.proto) + set(stem ${ENGINE_WIRE_GENERATED_DIR}/engine/v1/${name}) + list(APPEND ENGINE_WIRE_PB_SOURCES ${stem}.pb.cc) + list(APPEND ENGINE_WIRE_PB_OUTPUTS ${stem}.pb.cc ${stem}.pb.h) + list(APPEND ENGINE_WIRE_PY_OUTPUTS + ${ENGINE_WIRE_PY_GENERATED_DIR}/${name}_pb2.py + ${ENGINE_WIRE_PY_GENERATED_DIR}/${name}_pb2.pyi) +endforeach() + +add_custom_command( + OUTPUT ${ENGINE_WIRE_PB_OUTPUTS} + COMMAND ${CMAKE_COMMAND} -E make_directory ${ENGINE_WIRE_GENERATED_DIR} + COMMAND $ -I ${ENGINE_WIRE_PROTO_ROOT} + --cpp_out=${ENGINE_WIRE_GENERATED_DIR} ${ENGINE_WIRE_PROTO_FILES} + DEPENDS ${ENGINE_WIRE_PROTO_FILES} protobuf::protoc + COMMENT "Generating C++ for trtllm.engine.v1") + +if(NOT Python3_EXECUTABLE) + find_package( + Python3 + COMPONENTS Interpreter + REQUIRED) +endif() +get_filename_component( + ENGINE_WIRE_PROTO_GENERATOR + ${CMAKE_CURRENT_SOURCE_DIR}/../../../scripts/generate_contract_protos.py + ABSOLUTE) +add_custom_command( + OUTPUT ${ENGINE_WIRE_PY_OUTPUTS} + COMMAND + ${Python3_EXECUTABLE} ${ENGINE_WIRE_PROTO_GENERATOR} --proto-root + ${ENGINE_WIRE_PROTO_ROOT} --out-dir ${ENGINE_WIRE_PY_GENERATED_DIR} --protoc + $ + DEPENDS ${ENGINE_WIRE_PROTO_FILES} ${ENGINE_WIRE_PROTO_GENERATOR} + protobuf::protoc + COMMENT "Generating Python bindings for trtllm.engine.v1") + +# The outputs of a custom command get a build rule only in this directory, so +# other directories depend on this target instead of on the files. +add_custom_target(engine_wire_proto DEPENDS ${ENGINE_WIRE_PB_OUTPUTS} + ${ENGINE_WIRE_PY_OUTPUTS}) + +set(ENGINE_WIRE_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/engineWire.cpp ${ENGINE_WIRE_PB_SOURCES} + PARENT_SCOPE) +set(ENGINE_WIRE_INCLUDE_DIRS + ${CMAKE_CURRENT_SOURCE_DIR} ${ENGINE_WIRE_GENERATED_DIR} + PARENT_SCOPE) diff --git a/tensorrt_llm/executor/native/engineWire.cpp b/tensorrt_llm/executor/native/engineWire.cpp new file mode 100644 index 000000000000..e4af0c3f682b --- /dev/null +++ b/tensorrt_llm/executor/native/engineWire.cpp @@ -0,0 +1,3054 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Native codec of the trtllm.engine.v1 wire. It mirrors +// tensorrt_llm/contracts/engine/v1/wire_codec.py (encode_frame / decode_frame) +// byte for byte, and parses or builds the ClientMessage / ServerMessage envelopes. +// Every function reads its Python arguments while holding the GIL, then releases +// the GIL for column packing, validation, protobuf parsing and serialization. + +#include "engineWire.h" + +#include "engine/v1/output.pb.h" +#include "engine/v1/request.pb.h" +#include "engine/v1/session.pb.h" + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(__BYTE_ORDER__) || __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +#error "engineWire packs little-endian columns with memcpy and needs a little-endian target" +#endif + +namespace nb = ::nanobind; +namespace pbv1 = ::trtllm::engine::v1; + +namespace tensorrt_llm::nanobind::engine_wire +{ +namespace +{ + +// RowFlag bits and sentinels of common.proto / output.proto, as in wire_codec.py. +constexpr uint32_t kRowFlagFirstRow = 1; +constexpr uint32_t kRowFlagSeqFinal = 2; +constexpr uint32_t kRowFlagRequestDone = 4; +constexpr uint32_t kRowFlagHasExtra = 8; +constexpr int32_t kNoStopIndex = -1; +constexpr uint32_t kNoReplaceFrom = 0xFFFFFFFFU; +constexpr uint32_t kNoExtraIndex = 0xFFFFFFFFU; + +// Field numbers of the repeated message fields of Frame that are appended to the +// serialized columns, and of the payloads of ClientMessage / ServerMessage. +constexpr uint32_t kFrameExtrasField = 40; +constexpr uint32_t kFrameAcksField = 50; +constexpr uint32_t kFrameIterationStatsField = 51; +constexpr uint32_t kFrameLoraSetChangedField = 52; +constexpr uint32_t kServerMessageFrameField = 2; +constexpr uint32_t kClientMessageSubmitBatchField = 2; +constexpr uint32_t kSubmitBatchRequestsField = 1; +constexpr uint32_t kSubmitBatchConsumedFrameSeqField = 2; + +// Maximum protobuf length-delimited header for a low field number (1-byte tag + 10-byte varint). +constexpr size_t kMaxLengthDelimitedHeaderBytes = 11; + +//! Raised as a Python ValueError: malformed wire bytes or inconsistent columns. +class WireError : public std::invalid_argument +{ +public: + using std::invalid_argument::invalid_argument; +}; + +[[noreturn]] void throwPythonError() +{ + throw nb::python_error(); +} + +[[noreturn]] void raise(PyObject* type, std::string const& message) +{ + PyErr_SetString(type, message.c_str()); + throwPythonError(); +} + +// --------------------------------------------------------------------------- +// Varint / tag helpers for the raw parts of the wire +// --------------------------------------------------------------------------- + +void appendVarint(std::string& out, uint64_t value) +{ + while (value >= 0x80) + { + out.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + out.push_back(static_cast(value)); +} + +void appendLengthDelimited(std::string& out, uint32_t field, std::string_view payload) +{ + appendVarint(out, (static_cast(field) << 3) | 2U); + appendVarint(out, payload.size()); + out.append(payload.data(), payload.size()); +} + +template +std::string packColumn(std::vector const& values) +{ + std::string out; + if (!values.empty()) + { + out.resize(values.size() * sizeof(T)); + std::memcpy(out.data(), values.data(), out.size()); + } + return out; +} + +// --------------------------------------------------------------------------- +// Python value extraction (GIL held). The conversions follow the array module +// type codes wire_codec.py packs with: integers go through __index__ and raise +// OverflowError when out of range, floats go through PyFloat_AsDouble. +// --------------------------------------------------------------------------- + +class Ref +{ +public: + Ref() = default; + + explicit Ref(PyObject* obj) + : mObj(obj) + { + } + + Ref(Ref const&) = delete; + Ref& operator=(Ref const&) = delete; + + Ref(Ref&& other) noexcept + : mObj(other.mObj) + { + other.mObj = nullptr; + } + + Ref& operator=(Ref&& other) noexcept + { + if (this != &other) + { + Py_XDECREF(mObj); + mObj = other.mObj; + other.mObj = nullptr; + } + return *this; + } + + ~Ref() + { + Py_XDECREF(mObj); + } + + PyObject* get() const + { + return mObj; + } + + PyObject* checked() const + { + if (mObj == nullptr) + { + throwPythonError(); + } + return mObj; + } + + PyObject* release() + { + PyObject* obj = mObj; + mObj = nullptr; + return obj; + } + +private: + PyObject* mObj{nullptr}; +}; + +int64_t toInt64(PyObject* obj, int64_t lo, int64_t hi, char const* what) +{ + PyObject* longObj = obj; + Ref index; + if (!PyLong_CheckExact(obj)) + { + index = Ref(PyNumber_Index(obj)); + longObj = index.checked(); + } + int overflow = 0; + long long value = PyLong_AsLongLongAndOverflow(longObj, &overflow); + if (value == -1 && PyErr_Occurred()) + { + throwPythonError(); + } + if (overflow != 0 || value < lo || value > hi) + { + raise(PyExc_OverflowError, std::string(what) + " is out of range"); + } + return value; +} + +uint64_t toUint64(PyObject* obj, char const* what) +{ + PyObject* longObj = obj; + Ref index; + if (!PyLong_CheckExact(obj)) + { + index = Ref(PyNumber_Index(obj)); + longObj = index.checked(); + } + unsigned long long value = PyLong_AsUnsignedLongLong(longObj); + if (value == static_cast(-1) && PyErr_Occurred()) + { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + { + PyErr_Clear(); + raise(PyExc_OverflowError, std::string(what) + " is out of range"); + } + throwPythonError(); + } + return value; +} + +uint32_t toUint32(PyObject* obj, char const* what) +{ + return static_cast(toInt64(obj, 0, std::numeric_limits::max(), what)); +} + +int32_t toInt32(PyObject* obj, char const* what) +{ + return static_cast( + toInt64(obj, std::numeric_limits::min(), std::numeric_limits::max(), what)); +} + +double toDouble(PyObject* obj) +{ + if (PyFloat_CheckExact(obj)) + { + return PyFloat_AS_DOUBLE(obj); + } + double value = PyFloat_AsDouble(obj); + if (value == -1.0 && PyErr_Occurred()) + { + throwPythonError(); + } + return value; +} + +//! float(obj): what wire_codec.py applies to cum_logprob and top-k logprobs. +double toPyFloat(PyObject* obj) +{ + if (PyFloat_CheckExact(obj)) + { + return PyFloat_AS_DOUBLE(obj); + } + Ref asFloat(PyNumber_Float(obj)); + return PyFloat_AS_DOUBLE(asFloat.checked()); +} + +//! int(obj): what wire_codec.py applies to top-k token ids. +int32_t toPyIntInt32(PyObject* obj, char const* what) +{ + if (PyLong_CheckExact(obj)) + { + return toInt32(obj, what); + } + Ref asInt(PyNumber_Long(obj)); + return toInt32(asInt.checked(), what); +} + +Ref getAttr(PyObject* obj, PyObject* name) +{ + Ref value(PyObject_GetAttr(obj, name)); + value.checked(); + return value; +} + +//! A sequence view over any iterable (list and tuple are used in place). +Ref fastSequence(PyObject* obj, char const* what) +{ + Ref seq(PySequence_Fast(obj, what)); + seq.checked(); + return seq; +} + +//! Interned attribute names read from FrameRow-like objects. +struct Names +{ + PyObject* handle; + PyObject* tokens; + PyObject* finish; + PyObject* rowFlags; + PyObject* seq; + PyObject* stopIndex; + PyObject* replaceFrom; + PyObject* cumLogprob; + PyObject* decodingIter; + PyObject* cachedTokens; + PyObject* lpSampled; + PyObject* lpRank; + PyObject* lpTopk; + PyObject* extra; + PyObject* descriptor; + PyObject* fullName; + PyObject* serializeToString; + + static Names const& get() + { + // Created once with the GIL held and kept for the life of the process. + static Names const names = [] + { + Names n{}; + auto intern = [](char const* s) + { + PyObject* o = PyUnicode_InternFromString(s); + if (o == nullptr) + { + throwPythonError(); + } + return o; + }; + n.handle = intern("handle"); + n.tokens = intern("tokens"); + n.finish = intern("finish"); + n.rowFlags = intern("row_flags"); + n.seq = intern("seq"); + n.stopIndex = intern("stop_index"); + n.replaceFrom = intern("replace_from"); + n.cumLogprob = intern("cum_logprob"); + n.decodingIter = intern("decoding_iter"); + n.cachedTokens = intern("cached_tokens"); + n.lpSampled = intern("lp_sampled"); + n.lpRank = intern("lp_rank"); + n.lpTopk = intern("lp_topk"); + n.extra = intern("extra"); + n.descriptor = intern("DESCRIPTOR"); + n.fullName = intern("full_name"); + n.serializeToString = intern("SerializeToString"); + return n; + }(); + return names; + } +}; + +//! Serialized bytes of a protobuf message of type \p fullName. Accepts bytes as +//! already serialized when \p allowBytes; any other object must be a message of +//! that type (TypeError otherwise, as the Python repeated-field setters raise). +std::string serializeMessage(PyObject* msg, char const* fullName, bool allowBytes, bool* fromBytes = nullptr) +{ + if (fromBytes != nullptr) + { + *fromBytes = false; + } + if (allowBytes && PyBytes_Check(msg)) + { + if (fromBytes != nullptr) + { + *fromBytes = true; + } + return std::string(PyBytes_AS_STRING(msg), static_cast(PyBytes_GET_SIZE(msg))); + } + Names const& names = Names::get(); + Ref descriptor(PyObject_GetAttr(reinterpret_cast(Py_TYPE(msg)), names.descriptor)); + if (descriptor.get() == nullptr) + { + PyErr_Clear(); + raise(PyExc_TypeError, std::string("expected a ") + fullName + " message, got " + Py_TYPE(msg)->tp_name); + } + Ref name = getAttr(descriptor.get(), names.fullName); + char const* actual = PyUnicode_Check(name.get()) ? PyUnicode_AsUTF8(name.get()) : nullptr; + if (actual == nullptr || std::strcmp(actual, fullName) != 0) + { + PyErr_Clear(); + raise(PyExc_TypeError, std::string("expected a ") + fullName + " message, got " + Py_TYPE(msg)->tp_name); + } + Ref raw(PyObject_CallMethodNoArgs(msg, names.serializeToString)); + raw.checked(); + if (!PyBytes_Check(raw.get())) + { + raise(PyExc_TypeError, "SerializeToString() did not return bytes"); + } + return std::string(PyBytes_AS_STRING(raw.get()), static_cast(PyBytes_GET_SIZE(raw.get()))); +} + +std::vector serializeMessages( + PyObject* seqObj, char const* fullName, bool allowBytes, std::vector* fromBytes = nullptr) +{ + std::vector out; + if (seqObj == nullptr || seqObj == Py_None) + { + return out; + } + Ref seq = fastSequence(seqObj, "expected a sequence of messages"); + Py_ssize_t const count = PySequence_Fast_GET_SIZE(seq.get()); + PyObject** items = PySequence_Fast_ITEMS(seq.get()); + out.reserve(static_cast(count)); + for (Py_ssize_t i = 0; i < count; ++i) + { + bool isBytes = false; + out.push_back(serializeMessage(items[i], fullName, allowBytes, &isBytes)); + if (fromBytes != nullptr) + { + fromBytes->push_back(isBytes); + } + } + return out; +} + +// --------------------------------------------------------------------------- +// Frame encode +// --------------------------------------------------------------------------- + +//! Everything encode_frame reads from Python, gathered with the GIL held. +struct EncodeInput +{ + uint64_t frameSeq{0}; + uint64_t iterFirst{0}; + uint64_t iterLast{0}; + uint64_t emitTimeNs{0}; + size_t nRows{0}; + + std::vector handle; + std::vector seq; + std::vector tokenOffsets; + std::vector tokens; + std::vector finish; + std::vector rowFlags; + std::vector stopIndex; + std::vector replaceFrom; + std::vector cumLogprob; + std::vector decodingIter; + std::vector cachedTokens; + std::vector extraIndex; + std::vector extras; + std::vector extraFromBytes; + + bool needSeq{false}; + bool needStopIndex{false}; + bool needReplaceFrom{false}; + bool needCumLogprob{false}; + bool needDecodingIter{false}; + bool needCachedTokens{false}; + bool needLpSampled{false}; + bool needLpRank{false}; + bool needLpTopk{false}; + + // Per-row presence of the logprob lists and their values, concatenated over + // the rows that carry them. Rows without them are filled in at packing time. + std::vector hasLpSampled; + std::vector hasLpRank; + std::vector hasLpTopk; + std::vector lpSampledValues; + std::vector lpRankValues; + std::vector lpTopkCounts; + std::vector lpTopkIds; + std::vector lpTopkLogprobs; + + std::vector acks; + std::vector iterationStats; + std::vector loraSetChanged; + std::vector acksFromBytes; + std::vector iterationStatsFromBytes; + std::vector loraSetChangedFromBytes; +}; + +//! Bytes given in place of a message must parse as that message. Runs without the GIL. +template +void checkParses(std::vector const& items, std::vector const& fromBytes, char const* what) +{ + for (size_t i = 0; i < items.size(); ++i) + { + if (fromBytes[i]) + { + Message message; + if (!message.ParseFromString(items[i])) + { + throw WireError(std::string(what) + " bytes do not parse"); + } + } + } +} + +void readRow(EncodeInput& in, PyObject* row, Names const& names) +{ + in.handle.push_back(toUint64(getAttr(row, names.handle).get(), "handle")); + + Ref tokensObj = getAttr(row, names.tokens); + Ref tokens = fastSequence(tokensObj.get(), "FrameRow.tokens must be a sequence"); + Py_ssize_t const nt = PySequence_Fast_GET_SIZE(tokens.get()); + PyObject** tokenItems = PySequence_Fast_ITEMS(tokens.get()); + for (Py_ssize_t t = 0; t < nt; ++t) + { + in.tokens.push_back(toInt32(tokenItems[t], "token")); + } + in.tokenOffsets.push_back(static_cast(in.tokens.size())); + + in.finish.push_back(static_cast(toInt64(getAttr(row, names.finish).get(), 0, 255, "finish"))); + + Ref extra = getAttr(row, names.extra); + int64_t flags = toInt64(getAttr(row, names.rowFlags).get(), std::numeric_limits::min(), + std::numeric_limits::max(), "row_flags"); + if (extra.get() != Py_None) + { + flags |= kRowFlagHasExtra; + in.extraIndex.push_back(static_cast(in.extras.size())); + bool fromBytes = false; + in.extras.push_back(serializeMessage(extra.get(), "trtllm.engine.v1.RowExtra", true, &fromBytes)); + in.extraFromBytes.push_back(fromBytes); + } + else + { + flags &= ~static_cast(kRowFlagHasExtra); + in.extraIndex.push_back(kNoExtraIndex); + } + if (flags < 0 || flags > std::numeric_limits::max()) + { + raise(PyExc_OverflowError, "row_flags is out of range"); + } + in.rowFlags.push_back(static_cast(flags)); + + uint32_t const seq = toUint32(getAttr(row, names.seq).get(), "seq"); + in.needSeq |= seq != 0; + in.seq.push_back(seq); + + int32_t const stopIndex = toInt32(getAttr(row, names.stopIndex).get(), "stop_index"); + in.needStopIndex |= stopIndex != kNoStopIndex; + in.stopIndex.push_back(stopIndex); + + uint32_t const replaceFrom = toUint32(getAttr(row, names.replaceFrom).get(), "replace_from"); + in.needReplaceFrom |= replaceFrom != kNoReplaceFrom; + in.replaceFrom.push_back(replaceFrom); + + Ref cum = getAttr(row, names.cumLogprob); + if (cum.get() == Py_None) + { + in.cumLogprob.push_back(std::numeric_limits::quiet_NaN()); + } + else + { + in.needCumLogprob = true; + in.cumLogprob.push_back(toPyFloat(cum.get())); + } + + uint32_t const decodingIter = toUint32(getAttr(row, names.decodingIter).get(), "decoding_iter"); + in.needDecodingIter |= decodingIter != 0; + in.decodingIter.push_back(decodingIter); + + uint32_t const cachedTokens = toUint32(getAttr(row, names.cachedTokens).get(), "cached_tokens"); + in.needCachedTokens |= cachedTokens != 0; + in.cachedTokens.push_back(cachedTokens); + + auto checkLength = [nt](Py_ssize_t got, char const* what) + { + if (got != nt) + { + raise(PyExc_ValueError, + std::string(what) + " length " + std::to_string(got) + " != tokens " + std::to_string(nt)); + } + }; + + Ref lpSampledObj = getAttr(row, names.lpSampled); + in.hasLpSampled.push_back(lpSampledObj.get() != Py_None); + if (lpSampledObj.get() != Py_None) + { + in.needLpSampled = true; + Ref values = fastSequence(lpSampledObj.get(), "FrameRow.lp_sampled must be a sequence"); + checkLength(PySequence_Fast_GET_SIZE(values.get()), "lp_sampled"); + PyObject** items = PySequence_Fast_ITEMS(values.get()); + for (Py_ssize_t t = 0; t < nt; ++t) + { + in.lpSampledValues.push_back(static_cast(toDouble(items[t]))); + } + } + + Ref lpRankObj = getAttr(row, names.lpRank); + in.hasLpRank.push_back(lpRankObj.get() != Py_None); + if (lpRankObj.get() != Py_None) + { + in.needLpRank = true; + Ref values = fastSequence(lpRankObj.get(), "FrameRow.lp_rank must be a sequence"); + checkLength(PySequence_Fast_GET_SIZE(values.get()), "lp_rank"); + PyObject** items = PySequence_Fast_ITEMS(values.get()); + for (Py_ssize_t t = 0; t < nt; ++t) + { + in.lpRankValues.push_back(toUint32(items[t], "lp_rank")); + } + } + + Ref lpTopkObj = getAttr(row, names.lpTopk); + in.hasLpTopk.push_back(lpTopkObj.get() != Py_None); + if (lpTopkObj.get() != Py_None) + { + in.needLpTopk = true; + Ref perToken = fastSequence(lpTopkObj.get(), "FrameRow.lp_topk must be a sequence"); + checkLength(PySequence_Fast_GET_SIZE(perToken.get()), "lp_topk"); + PyObject** tokenLists = PySequence_Fast_ITEMS(perToken.get()); + for (Py_ssize_t t = 0; t < nt; ++t) + { + Ref cands = fastSequence(tokenLists[t], "FrameRow.lp_topk entries must be sequences"); + Py_ssize_t const nc = PySequence_Fast_GET_SIZE(cands.get()); + PyObject** candItems = PySequence_Fast_ITEMS(cands.get()); + for (Py_ssize_t c = 0; c < nc; ++c) + { + Ref pair = fastSequence(candItems[c], "lp_topk candidates must be (token_id, logprob) pairs"); + if (PySequence_Fast_GET_SIZE(pair.get()) != 2) + { + raise(PyExc_ValueError, "lp_topk candidates must be (token_id, logprob) pairs"); + } + PyObject** pairItems = PySequence_Fast_ITEMS(pair.get()); + in.lpTopkIds.push_back(toPyIntInt32(pairItems[0], "lp_topk token id")); + in.lpTopkLogprobs.push_back(static_cast(toPyFloat(pairItems[1]))); + } + in.lpTopkCounts.push_back(static_cast(nc)); + } + } +} + +//! Packs the columns and serializes the Frame (or ServerMessage{frame}). Runs +//! without the GIL. +std::string packFrame(EncodeInput const& in, bool serverMessage) +{ + pbv1::Frame frame; + frame.set_frame_seq(in.frameSeq); + frame.set_iter_first(in.iterFirst); + frame.set_iter_last(in.iterLast != 0 ? in.iterLast : in.iterFirst); + frame.set_emit_time_ns(in.emitTimeNs); + frame.set_n_rows(static_cast(in.nRows)); + + size_t const n = in.nRows; + if (n > 0) + { + frame.set_handle(packColumn(in.handle)); + if (in.needSeq) + { + frame.set_seq(packColumn(in.seq)); + } + frame.set_token_offsets(packColumn(in.tokenOffsets)); + if (!in.tokens.empty()) + { + frame.set_tokens(packColumn(in.tokens)); + } + frame.set_finish(packColumn(in.finish)); + frame.set_row_flags(packColumn(in.rowFlags)); + if (in.needStopIndex) + { + frame.set_stop_index(packColumn(in.stopIndex)); + } + if (in.needReplaceFrom) + { + frame.set_replace_from(packColumn(in.replaceFrom)); + } + if (in.needCumLogprob) + { + frame.set_cum_logprob(packColumn(in.cumLogprob)); + } + if (in.needDecodingIter) + { + frame.set_decoding_iter(packColumn(in.decodingIter)); + } + if (in.needCachedTokens) + { + frame.set_cached_tokens(packColumn(in.cachedTokens)); + } + if (!in.extras.empty()) + { + frame.set_extra_index(packColumn(in.extraIndex)); + } + + size_t const totalTokens = in.tokens.size(); + if (totalTokens > 0) + { + if (in.needLpSampled) + { + std::vector column; + column.reserve(totalTokens); + size_t cursor = 0; + for (size_t i = 0; i < n; ++i) + { + size_t const nt = in.tokenOffsets[i + 1] - in.tokenOffsets[i]; + if (in.hasLpSampled[i]) + { + column.insert(column.end(), in.lpSampledValues.begin() + cursor, + in.lpSampledValues.begin() + cursor + nt); + cursor += nt; + } + else + { + column.insert(column.end(), nt, std::numeric_limits::quiet_NaN()); + } + } + frame.set_lp_sampled(packColumn(column)); + } + if (in.needLpRank) + { + std::vector column; + column.reserve(totalTokens); + size_t cursor = 0; + for (size_t i = 0; i < n; ++i) + { + size_t const nt = in.tokenOffsets[i + 1] - in.tokenOffsets[i]; + if (in.hasLpRank[i]) + { + column.insert( + column.end(), in.lpRankValues.begin() + cursor, in.lpRankValues.begin() + cursor + nt); + cursor += nt; + } + else + { + column.insert(column.end(), nt, 0U); + } + } + frame.set_lp_rank(packColumn(column)); + } + if (in.needLpTopk) + { + std::vector offsets; + offsets.reserve(totalTokens + 1); + offsets.push_back(0); + uint32_t total = 0; + size_t cursor = 0; + for (size_t i = 0; i < n; ++i) + { + size_t const nt = in.tokenOffsets[i + 1] - in.tokenOffsets[i]; + for (size_t t = 0; t < nt; ++t) + { + if (in.hasLpTopk[i]) + { + total += in.lpTopkCounts[cursor++]; + } + offsets.push_back(total); + } + } + frame.set_lp_topk_offsets(packColumn(offsets)); + if (!in.lpTopkIds.empty()) + { + frame.set_lp_topk_ids(packColumn(in.lpTopkIds)); + frame.set_lp_topk_logprobs(packColumn(in.lpTopkLogprobs)); + } + } + } + } + + // Every column has a field number below 40, so appending the repeated message + // fields in field-number order gives the same bytes as serializing them in place. + std::string body; + if (!frame.SerializeToString(&body)) + { + throw WireError("failed to serialize Frame"); + } + for (auto const& extra : in.extras) + { + appendLengthDelimited(body, kFrameExtrasField, extra); + } + for (auto const& ack : in.acks) + { + appendLengthDelimited(body, kFrameAcksField, ack); + } + for (auto const& stats : in.iterationStats) + { + appendLengthDelimited(body, kFrameIterationStatsField, stats); + } + for (auto const& lora : in.loraSetChanged) + { + appendLengthDelimited(body, kFrameLoraSetChangedField, lora); + } + if (!serverMessage) + { + return body; + } + std::string out; + out.reserve(body.size() + kMaxLengthDelimitedHeaderBytes); + appendLengthDelimited(out, kServerMessageFrameField, body); + return out; +} + +nb::bytes toBytes(std::string const& s) +{ + return nb::bytes(s.data(), s.size()); +} + +nb::bytes encodeFrame(nb::handle rows, uint64_t frameSeq, uint64_t iterFirst, uint64_t iterLast, uint64_t emitTimeNs, + nb::handle acks, nb::handle iterationStats, nb::handle loraSetChanged, bool serverMessage) +{ + Names const& names = Names::get(); + EncodeInput in; + in.frameSeq = frameSeq; + in.iterFirst = iterFirst; + in.iterLast = iterLast; + in.emitTimeNs = emitTimeNs; + in.acks = serializeMessages(acks.ptr(), "trtllm.engine.v1.SubmitAck", true, &in.acksFromBytes); + in.iterationStats + = serializeMessages(iterationStats.ptr(), "trtllm.engine.v1.IterationStats", true, &in.iterationStatsFromBytes); + in.loraSetChanged + = serializeMessages(loraSetChanged.ptr(), "trtllm.engine.v1.LoraSetChanged", true, &in.loraSetChangedFromBytes); + + Ref seq = fastSequence(rows.ptr(), "rows must be a sequence"); + Py_ssize_t const n = PySequence_Fast_GET_SIZE(seq.get()); + PyObject** items = PySequence_Fast_ITEMS(seq.get()); + in.nRows = static_cast(n); + in.tokenOffsets.reserve(in.nRows + 1); + in.tokenOffsets.push_back(0); + for (Py_ssize_t i = 0; i < n; ++i) + { + readRow(in, items[i], names); + } + + std::string out; + { + nb::gil_scoped_release release; + checkParses(in.extras, in.extraFromBytes, "RowExtra"); + checkParses(in.acks, in.acksFromBytes, "SubmitAck"); + checkParses(in.iterationStats, in.iterationStatsFromBytes, "IterationStats"); + checkParses(in.loraSetChanged, in.loraSetChangedFromBytes, "LoraSetChanged"); + out = packFrame(in, serverMessage); + } + return toBytes(out); +} + +// --------------------------------------------------------------------------- +// Frame decode +// --------------------------------------------------------------------------- + +//! A Frame unpacked and validated without the GIL. +struct DecodedFrame +{ + uint64_t frameSeq{0}; + uint64_t iterFirst{0}; + uint64_t iterLast{0}; + uint64_t emitTimeNs{0}; + uint32_t nRows{0}; + + std::vector handle; + std::vector seq; + std::vector tokenOffsets; + std::vector tokens; + std::vector finish; + std::vector rowFlags; + std::vector stopIndex; + std::vector replaceFrom; + bool hasCumLogprob{false}; + std::vector cumLogprob; + std::vector decodingIter; + std::vector cachedTokens; + bool hasExtraIndex{false}; + std::vector extraIndex; + // Serialized RowExtra per row; empty when the row has none. + std::vector> rowExtras; + + bool hasLpSampled{false}; + std::vector lpSampled; + bool hasLpRank{false}; + std::vector lpRank; + bool hasLpTopk{false}; + std::vector lpTopkOffsets; + std::vector lpTopkIds; + std::vector lpTopkLogprobs; + + std::vector acks; + std::vector iterationStats; + std::vector loraSetChanged; +}; + +template +void unpackColumn(std::string const& raw, uint64_t count, char const* name, std::vector& out) +{ + uint64_t const expected = count * sizeof(T); + if (raw.size() != expected) + { + throw WireError(std::string("Frame column '") + name + "' byte length " + std::to_string(raw.size()) + + " != expected " + std::to_string(expected) + " (count=" + std::to_string(count) + + ", itemsize=" + std::to_string(sizeof(T)) + ")"); + } + out.resize(count); + if (count > 0) + { + std::memcpy(out.data(), raw.data(), raw.size()); + } +} + +template +void unpackOrFill(std::string const& raw, uint64_t count, char const* name, T fill, std::vector& out) +{ + if (raw.empty()) + { + out.assign(count, fill); + } + else + { + unpackColumn(raw, count, name, out); + } +} + +//! Mirrors wire_codec.decode_frame: the same columns are validated in the same order. +void unpackFrame(pbv1::Frame const& frame, DecodedFrame& out) +{ + out.frameSeq = frame.frame_seq(); + out.iterFirst = frame.iter_first(); + out.iterLast = frame.iter_last(); + out.emitTimeNs = frame.emit_time_ns(); + out.nRows = frame.n_rows(); + for (auto const& ack : frame.acks()) + { + out.acks.push_back(ack.SerializeAsString()); + } + for (auto const& stats : frame.iteration_stats()) + { + out.iterationStats.push_back(stats.SerializeAsString()); + } + for (auto const& lora : frame.lora_set_changed()) + { + out.loraSetChanged.push_back(lora.SerializeAsString()); + } + + uint64_t const n = out.nRows; + if (n == 0) + { + return; + } + unpackColumn(frame.handle(), n, "handle", out.handle); + unpackOrFill(frame.seq(), n, "seq", 0, out.seq); + unpackColumn(frame.token_offsets(), n + 1, "token_offsets", out.tokenOffsets); + if (out.tokenOffsets[0] != 0) + { + throw WireError("token_offsets[0]=" + std::to_string(out.tokenOffsets[0]) + " != 0"); + } + for (uint64_t i = 0; i < n; ++i) + { + if (out.tokenOffsets[i] > out.tokenOffsets[i + 1]) + { + throw WireError("token_offsets not monotonic at " + std::to_string(i) + ": " + + std::to_string(out.tokenOffsets[i]) + " > " + std::to_string(out.tokenOffsets[i + 1])); + } + } + uint64_t const totalTokens = out.tokenOffsets[n]; + if (totalTokens > 0) + { + unpackColumn(frame.tokens(), totalTokens, "tokens", out.tokens); + } + else if (!frame.tokens().empty()) + { + throw WireError( + "tokens column non-empty (" + std::to_string(frame.tokens().size()) + "B) when total_tokens==0"); + } + unpackColumn(frame.finish(), n, "finish", out.finish); + unpackColumn(frame.row_flags(), n, "row_flags", out.rowFlags); + unpackOrFill(frame.stop_index(), n, "stop_index", kNoStopIndex, out.stopIndex); + unpackOrFill(frame.replace_from(), n, "replace_from", kNoReplaceFrom, out.replaceFrom); + if (!frame.cum_logprob().empty()) + { + out.hasCumLogprob = true; + unpackColumn(frame.cum_logprob(), n, "cum_logprob", out.cumLogprob); + } + unpackOrFill(frame.decoding_iter(), n, "decoding_iter", 0, out.decodingIter); + unpackOrFill(frame.cached_tokens(), n, "cached_tokens", 0, out.cachedTokens); + if (!frame.extra_index().empty()) + { + out.hasExtraIndex = true; + unpackColumn(frame.extra_index(), n, "extra_index", out.extraIndex); + } + + if (!frame.lp_sampled().empty() && totalTokens > 0) + { + out.hasLpSampled = true; + unpackColumn(frame.lp_sampled(), totalTokens, "lp_sampled", out.lpSampled); + } + if (!frame.lp_rank().empty() && totalTokens > 0) + { + out.hasLpRank = true; + unpackColumn(frame.lp_rank(), totalTokens, "lp_rank", out.lpRank); + } + if (!frame.lp_topk_offsets().empty() && totalTokens > 0) + { + out.hasLpTopk = true; + unpackColumn(frame.lp_topk_offsets(), totalTokens + 1, "lp_topk_offsets", out.lpTopkOffsets); + if (out.lpTopkOffsets[0] != 0) + { + throw WireError("lp_topk_offsets[0]=" + std::to_string(out.lpTopkOffsets[0]) + " != 0"); + } + for (uint64_t i = 0; i < totalTokens; ++i) + { + if (out.lpTopkOffsets[i] > out.lpTopkOffsets[i + 1]) + { + throw WireError("lp_topk_offsets not monotonic at " + std::to_string(i)); + } + } + uint64_t const totalCands = out.lpTopkOffsets[totalTokens]; + if (totalCands > 0) + { + unpackColumn(frame.lp_topk_ids(), totalCands, "lp_topk_ids", out.lpTopkIds); + unpackColumn(frame.lp_topk_logprobs(), totalCands, "lp_topk_logprobs", out.lpTopkLogprobs); + } + } + + auto const numExtras = static_cast(frame.extras_size()); + std::vector> serialized(numExtras); + out.rowExtras.resize(n); + for (uint64_t i = 0; i < n; ++i) + { + if ((out.rowFlags[i] & kRowFlagHasExtra) == 0) + { + continue; + } + if (!out.hasExtraIndex) + { + throw WireError("Row " + std::to_string(i) + " sets HAS_EXTRA but extra_index column is absent"); + } + uint32_t const index = out.extraIndex[i]; + if (index >= numExtras) + { + throw WireError("Row " + std::to_string(i) + " extra_index " + std::to_string(index) + " >= len(extras) " + + std::to_string(numExtras)); + } + if (!serialized[index]) + { + serialized[index] = frame.extras(static_cast(index)).SerializeAsString(); + } + out.rowExtras[i] = serialized[index]; + } +} + +PyObject* newLong(int64_t v) +{ + PyObject* o = PyLong_FromLongLong(v); + if (o == nullptr) + { + throwPythonError(); + } + return o; +} + +PyObject* newULong(uint64_t v) +{ + PyObject* o = PyLong_FromUnsignedLongLong(v); + if (o == nullptr) + { + throwPythonError(); + } + return o; +} + +PyObject* newFloat(double v) +{ + PyObject* o = PyFloat_FromDouble(v); + if (o == nullptr) + { + throwPythonError(); + } + return o; +} + +PyObject* newBytes(std::string const& s) +{ + PyObject* o = PyBytes_FromStringAndSize(s.data(), static_cast(s.size())); + if (o == nullptr) + { + throwPythonError(); + } + return o; +} + +template +PyObject* newList(T const* values, size_t count, Make make) +{ + Ref list(PyList_New(static_cast(count))); + list.checked(); + for (size_t i = 0; i < count; ++i) + { + PyList_SET_ITEM(list.get(), static_cast(i), make(values[i])); + } + return list.release(); +} + +PyObject* newBytesList(std::vector const& items) +{ + return newList(items.data(), items.size(), [](std::string const& s) { return newBytes(s); }); +} + +//! The fields of one row, in FrameRow's field order. +constexpr int kRowFields = 14; + +void buildRowFields(DecodedFrame const& d, size_t i, Ref (&fields)[kRowFields]) +{ + uint32_t const t0 = d.tokenOffsets[i]; + uint32_t const t1 = d.tokenOffsets[i + 1]; + auto const asLong = [](auto v) { return newLong(static_cast(v)); }; + auto const asFloat = [](float v) { return newFloat(static_cast(v)); }; + + fields[0] = Ref(newULong(d.handle[i])); + fields[1] = Ref(newList(d.tokens.data() + t0, t1 - t0, asLong)); + fields[2] = Ref(newLong(d.finish[i])); + fields[3] = Ref(newLong(d.rowFlags[i])); + fields[4] = Ref(newLong(d.seq[i])); + fields[5] = Ref(newLong(d.stopIndex[i])); + fields[6] = Ref(newLong(d.replaceFrom[i])); + if (d.hasCumLogprob && !std::isnan(d.cumLogprob[i])) + { + fields[7] = Ref(newFloat(d.cumLogprob[i])); + } + else + { + fields[7] = Ref(Py_NewRef(Py_None)); + } + fields[8] = Ref(newLong(d.decodingIter[i])); + fields[9] = Ref(newLong(d.cachedTokens[i])); + + bool sampledPresent = false; + if (d.hasLpSampled && t1 > t0) + { + for (uint32_t t = t0; t < t1; ++t) + { + if (!std::isnan(d.lpSampled[t])) + { + sampledPresent = true; + break; + } + } + } + fields[10] = sampledPresent ? Ref(newList(d.lpSampled.data() + t0, t1 - t0, asFloat)) : Ref(Py_NewRef(Py_None)); + fields[11] = (d.hasLpRank && t1 > t0 && sampledPresent) ? Ref(newList(d.lpRank.data() + t0, t1 - t0, asLong)) + : Ref(Py_NewRef(Py_None)); + + PyObject* topk = nullptr; + if (d.hasLpTopk && t1 > t0) + { + bool anyCand = false; + for (uint32_t t = t0; t < t1; ++t) + { + if (d.lpTopkOffsets[t + 1] > d.lpTopkOffsets[t]) + { + anyCand = true; + break; + } + } + if (anyCand || sampledPresent) + { + Ref perToken(PyList_New(t1 - t0)); + perToken.checked(); + for (uint32_t t = t0; t < t1; ++t) + { + uint32_t const c0 = d.lpTopkOffsets[t]; + uint32_t const c1 = d.lpTopkOffsets[t + 1]; + Ref cands(PyList_New(c1 - c0)); + cands.checked(); + for (uint32_t c = c0; c < c1; ++c) + { + Ref id(newLong(d.lpTopkIds[c])); + Ref lp(newFloat(static_cast(d.lpTopkLogprobs[c]))); + PyObject* pair = PyTuple_Pack(2, id.get(), lp.get()); + if (pair == nullptr) + { + throwPythonError(); + } + PyList_SET_ITEM(cands.get(), c - c0, pair); + } + PyList_SET_ITEM(perToken.get(), t - t0, cands.release()); + } + topk = perToken.release(); + } + } + fields[12] = topk != nullptr ? Ref(topk) : Ref(Py_NewRef(Py_None)); + fields[13] = d.rowExtras[i] ? Ref(newBytes(*d.rowExtras[i])) : Ref(Py_NewRef(Py_None)); +} + +//! (header, rows): header is (frame_seq, iter_first, iter_last, emit_time_ns, n_rows, +//! acks, iteration_stats, lora_set_changed) with the repeated messages as serialized +//! bytes; each row is a tuple in FrameRow field order, or an instance of \p rowType +//! (created without calling __init__, its fields set as attributes) when given. +nb::object buildDecoded(DecodedFrame const& d, nb::handle rowType) +{ + Names const& names = Names::get(); + PyObject* const fieldNames[kRowFields] = {names.handle, names.tokens, names.finish, names.rowFlags, names.seq, + names.stopIndex, names.replaceFrom, names.cumLogprob, names.decodingIter, names.cachedTokens, names.lpSampled, + names.lpRank, names.lpTopk, names.extra}; + + PyTypeObject* type = nullptr; + Ref emptyArgs; + if (rowType.is_valid() && !rowType.is_none()) + { + if (!PyType_Check(rowType.ptr())) + { + raise(PyExc_TypeError, "row_type must be a class"); + } + type = reinterpret_cast(rowType.ptr()); + if (type->tp_new == nullptr) + { + raise(PyExc_TypeError, "row_type cannot be instantiated"); + } + emptyArgs = Ref(PyTuple_New(0)); + emptyArgs.checked(); + } + + size_t const n = d.nRows; + Ref rows(PyList_New(static_cast(n))); + rows.checked(); + for (size_t i = 0; i < n; ++i) + { + Ref fields[kRowFields]; + buildRowFields(d, i, fields); + PyObject* row = nullptr; + if (type != nullptr) + { + Ref obj(type->tp_new(type, emptyArgs.get(), nullptr)); + obj.checked(); + for (int f = 0; f < kRowFields; ++f) + { + if (PyObject_SetAttr(obj.get(), fieldNames[f], fields[f].get()) < 0) + { + throwPythonError(); + } + } + row = obj.release(); + } + else + { + Ref tuple(PyTuple_New(kRowFields)); + tuple.checked(); + for (int f = 0; f < kRowFields; ++f) + { + PyTuple_SET_ITEM(tuple.get(), f, fields[f].release()); + } + row = tuple.release(); + } + PyList_SET_ITEM(rows.get(), static_cast(i), row); + } + + Ref header(PyTuple_New(8)); + header.checked(); + PyTuple_SET_ITEM(header.get(), 0, newULong(d.frameSeq)); + PyTuple_SET_ITEM(header.get(), 1, newULong(d.iterFirst)); + PyTuple_SET_ITEM(header.get(), 2, newULong(d.iterLast)); + PyTuple_SET_ITEM(header.get(), 3, newULong(d.emitTimeNs)); + PyTuple_SET_ITEM(header.get(), 4, newULong(d.nRows)); + PyTuple_SET_ITEM(header.get(), 5, newBytesList(d.acks)); + PyTuple_SET_ITEM(header.get(), 6, newBytesList(d.iterationStats)); + PyTuple_SET_ITEM(header.get(), 7, newBytesList(d.loraSetChanged)); + + PyObject* result = PyTuple_Pack(2, header.get(), rows.get()); + if (result == nullptr) + { + throwPythonError(); + } + return nb::steal(result); +} + +//! Holds a read-only view of a Python bytes-like argument for the duration of a call. +//! Immutable ``bytes`` objects are borrowed zero-copy; other buffer exporters (such as writable +//! ``bytearray`` or ``memoryview``) are copied into owned storage while the GIL is held so +//! releasing the GIL during protobuf parsing cannot race with concurrent Python mutations. +class BytesArg +{ +public: + explicit BytesArg(nb::handle data) + { + if (PyBytes_Check(data.ptr())) + { + mData = {PyBytes_AS_STRING(data.ptr()), static_cast(PyBytes_GET_SIZE(data.ptr()))}; + return; + } + Py_buffer view{}; + if (PyObject_GetBuffer(data.ptr(), &view, PyBUF_C_CONTIGUOUS) < 0) + { + throwPythonError(); + } + + struct BufferGuard + { + Py_buffer* view; + + ~BufferGuard() + { + PyBuffer_Release(view); + } + } guard{&view}; + + if (view.len > 0) + { + mOwned.assign(static_cast(view.buf), static_cast(view.len)); + } + mData = mOwned; + } + + BytesArg(BytesArg const&) = delete; + BytesArg& operator=(BytesArg const&) = delete; + + std::string_view data() const + { + return mData; + } + +private: + std::string mOwned; + std::string_view mData; +}; + +template +void parseOrThrow(Message& message, std::string_view data, char const* what) +{ + if (data.size() > static_cast(std::numeric_limits::max()) + || !message.ParseFromArray(data.data(), static_cast(data.size()))) + { + throw WireError(std::string("malformed ") + what); + } +} + +nb::object decodeFrame(nb::handle data, nb::handle rowType) +{ + BytesArg arg(data); + DecodedFrame decoded; + { + nb::gil_scoped_release release; + pbv1::Frame frame; + parseOrThrow(frame, arg.data(), "Frame"); + unpackFrame(frame, decoded); + } + return buildDecoded(decoded, rowType); +} + +char const* serverPayloadName(pbv1::ServerMessage::PayloadCase c) +{ + switch (c) + { + case pbv1::ServerMessage::kAccepted: return "accepted"; + case pbv1::ServerMessage::kFrame: return "frame"; + case pbv1::ServerMessage::kSubmitAck: return "submit_ack"; + case pbv1::ServerMessage::kNotice: return "notice"; + case pbv1::ServerMessage::kIterationStats: return "iteration_stats"; + case pbv1::ServerMessage::kLoraSetChanged: return "lora_set_changed"; + case pbv1::ServerMessage::PAYLOAD_NOT_SET: return nullptr; + } + return nullptr; +} + +//! (kind, payload): kind names the ServerMessage oneof (None when unset); a frame +//! payload is decoded as by decode_frame, any other payload is its serialized bytes. +nb::object parseServerMessage(nb::handle data, nb::handle rowType) +{ + BytesArg arg(data); + DecodedFrame decoded; + std::string payload; + pbv1::ServerMessage::PayloadCase payloadCase{}; + { + nb::gil_scoped_release release; + pbv1::ServerMessage message; + parseOrThrow(message, arg.data(), "ServerMessage"); + payloadCase = message.payload_case(); + switch (payloadCase) + { + case pbv1::ServerMessage::kFrame: unpackFrame(message.frame(), decoded); break; + case pbv1::ServerMessage::kAccepted: payload = message.accepted().SerializeAsString(); break; + case pbv1::ServerMessage::kSubmitAck: payload = message.submit_ack().SerializeAsString(); break; + case pbv1::ServerMessage::kNotice: payload = message.notice().SerializeAsString(); break; + case pbv1::ServerMessage::kIterationStats: payload = message.iteration_stats().SerializeAsString(); break; + case pbv1::ServerMessage::kLoraSetChanged: payload = message.lora_set_changed().SerializeAsString(); break; + case pbv1::ServerMessage::PAYLOAD_NOT_SET: break; + } + } + char const* kind = serverPayloadName(payloadCase); + if (kind == nullptr) + { + return nb::make_tuple(nb::none(), nb::none()); + } + if (payloadCase == pbv1::ServerMessage::kFrame) + { + return nb::make_tuple(nb::str(kind), buildDecoded(decoded, rowType)); + } + return nb::make_tuple(nb::str(kind), toBytes(payload)); +} + +// --------------------------------------------------------------------------- +// ClientMessage envelopes +// --------------------------------------------------------------------------- + +//! Parses and validates a ClientMessage. Returns, by payload: +//! ("submit_batch", consumed_frame_seq, [serialized Request, ...]) +//! ("cancel_batch", consumed_frame_seq, all, all_reason, [(handle, reason), ...]) +//! ("progress", consumed_frame_seq) +//! ("open", serialized SessionOpen) +//! (None,) when no payload is set. +nb::object parseClientMessage(nb::handle data) +{ + BytesArg arg(data); + pbv1::ClientMessage message; + std::vector requests; + { + nb::gil_scoped_release release; + parseOrThrow(message, arg.data(), "ClientMessage"); + if (message.payload_case() == pbv1::ClientMessage::kSubmitBatch) + { + auto const& batch = message.submit_batch(); + requests.reserve(static_cast(batch.requests_size())); + for (auto const& request : batch.requests()) + { + requests.push_back(request.SerializeAsString()); + } + } + } + switch (message.payload_case()) + { + case pbv1::ClientMessage::kSubmitBatch: + { + Ref list(newBytesList(requests)); + return nb::make_tuple( + nb::str("submit_batch"), message.submit_batch().consumed_frame_seq(), nb::steal(list.release())); + } + case pbv1::ClientMessage::kCancelBatch: + { + auto const& batch = message.cancel_batch(); + nb::list cancels; + for (auto const& item : batch.cancels()) + { + cancels.append(nb::make_tuple(item.handle(), static_cast(item.reason()))); + } + return nb::make_tuple(nb::str("cancel_batch"), batch.consumed_frame_seq(), batch.all(), + static_cast(batch.all_reason()), cancels); + } + case pbv1::ClientMessage::kProgress: + return nb::make_tuple(nb::str("progress"), message.progress().consumed_frame_seq()); + case pbv1::ClientMessage::kOpen: + return nb::make_tuple(nb::str("open"), toBytes(message.open().SerializeAsString())); + case pbv1::ClientMessage::PAYLOAD_NOT_SET: break; + } + return nb::make_tuple(nb::none()); +} + +//! ClientMessage{submit_batch: SubmitBatch{requests, consumed_frame_seq}} as bytes. +//! Each request is a Request message or its serialized bytes (which must parse). +nb::bytes encodeSubmitBatch(nb::handle requests, uint64_t consumedFrameSeq) +{ + std::vector fromBytes; + std::vector payloads = serializeMessages(requests.ptr(), "trtllm.engine.v1.Request", true, &fromBytes); + std::string out; + { + nb::gil_scoped_release release; + checkParses(payloads, fromBytes, "Request"); + std::string batch; + for (auto const& payload : payloads) + { + appendLengthDelimited(batch, kSubmitBatchRequestsField, payload); + } + if (consumedFrameSeq != 0) + { + appendVarint(batch, static_cast(kSubmitBatchConsumedFrameSeqField) << 3); + appendVarint(batch, consumedFrameSeq); + } + appendLengthDelimited(out, kClientMessageSubmitBatchField, batch); + } + return toBytes(out); +} + +//! ClientMessage{cancel_batch: CancelBatch{...}} as bytes; \p cancels holds +//! (handle, reason) pairs. +nb::bytes encodeCancelBatch(nb::handle cancels, bool all, int32_t allReason, uint64_t consumedFrameSeq) +{ + pbv1::ClientMessage message; + auto* batch = message.mutable_cancel_batch(); + Ref seq = fastSequence(cancels.ptr(), "cancels must be a sequence of (handle, reason) pairs"); + Py_ssize_t const n = PySequence_Fast_GET_SIZE(seq.get()); + PyObject** items = PySequence_Fast_ITEMS(seq.get()); + for (Py_ssize_t i = 0; i < n; ++i) + { + Ref pair = fastSequence(items[i], "cancels must be a sequence of (handle, reason) pairs"); + if (PySequence_Fast_GET_SIZE(pair.get()) != 2) + { + raise(PyExc_ValueError, "cancels must be a sequence of (handle, reason) pairs"); + } + PyObject** pairItems = PySequence_Fast_ITEMS(pair.get()); + auto* item = batch->add_cancels(); + item->set_handle(toUint64(pairItems[0], "handle")); + item->set_reason(static_cast(toInt32(pairItems[1], "reason"))); + } + batch->set_all(all); + batch->set_all_reason(static_cast(allReason)); + batch->set_consumed_frame_seq(consumedFrameSeq); + std::string out; + { + nb::gil_scoped_release release; + if (!message.SerializeToString(&out)) + { + throw WireError("failed to serialize ClientMessage"); + } + } + return toBytes(out); +} + +// --------------------------------------------------------------------------- +// Fast-path native step-response encode / decode +// +// Directly bridges Python LlmResponse / ZmqStepResponse objects and serialized +// ServerMessage{frame} bytes without allocating intermediate FrameRow objects +// or round-tripping through Python protobuf messages. +// --------------------------------------------------------------------------- + +struct StepNames +{ + // Response / Result read attributes + PyObject* clientId; + PyObject* requestId; + PyObject* errorMsg; + PyObject* result; + PyObject* privateResponse; + PyObject* privateResult; + PyObject* privatePyResult; + PyObject* privateLogProbs; + PyObject* privateContextLogits; + PyObject* privateGenerationLogits; + PyObject* privateFirstGenLogProbs; + PyObject* privateMmEmbeddings; + PyObject* privateMropePosIds; + PyObject* privateMropePosDeltas; + PyObject* privateAddCtxOutputs; + PyObject* privateAddGenOutputs; + PyObject* privateEncoderOutput; + PyObject* ctxPromptLogprobRows; + PyObject* ctxPromptLastLogprobs; + PyObject* isFinal; + PyObject* isRequestDone; + PyObject* isSequenceFinal; + PyObject* sequenceIndex; + PyObject* outputTokenIds; + PyObject* finishReasons; + PyObject* cumLogProbs; + PyObject* logProbs; + PyObject* stopIndex; + PyObject* replaceFrom; + PyObject* rowFlags; + PyObject* decodingIter; + PyObject* cachedTokens; + PyObject* avgDecodedTokensPerIter; + PyObject* perPosDrafted; + PyObject* perPosAccepted; + PyObject* specDecTotals; + PyObject* ctxUsage; + PyObject* remoteTailStart; + PyObject* timeBreakdownMetrics; + PyObject* requestPerfMetrics; + PyObject* contextPhaseParams; + PyObject* signedHandoff; + PyObject* logprob; + PyObject* rank; + PyObject* name; + PyObject* value; + PyObject* samplingParams; + PyObject* useBeamSearch; + PyObject* logprobsSimpleFormat; + PyObject* frameSeq; + PyObject* errorInfo; + PyObject* hasError; + PyObject* promptLogprobs; + PyObject* contextLogits; + PyObject* generationLogits; + PyObject* encoderOutput; + PyObject* routedExperts; + PyObject* addCtxOutputs; + PyObject* addGenOutputs; + PyObject* expandedPromptTokens; + PyObject* streamingTensorRanges; + PyObject* mmEmbeddingHandles; + PyObject* mropePosIdsHandle; + PyObject* mropePosDeltasHandle; + + static StepNames const& get() + { + static StepNames const s = [] + { + StepNames n{}; + auto intern = [](char const* str) + { + PyObject* o = PyUnicode_InternFromString(str); + if (o == nullptr) + { + throwPythonError(); + } + return o; + }; + n.clientId = intern("client_id"); + n.requestId = intern("request_id"); + n.errorMsg = intern("error_msg"); + n.result = intern("result"); + n.privateResponse = intern("_response"); + n.privateResult = intern("_result"); + n.privatePyResult = intern("_py_result"); + n.privateLogProbs = intern("_log_probs"); + n.privateContextLogits = intern("_context_logits"); + n.privateGenerationLogits = intern("_generation_logits"); + n.privateFirstGenLogProbs = intern("_first_gen_log_probs"); + n.privateMmEmbeddings = intern("_mm_embeddings"); + n.privateMropePosIds = intern("_mrope_position_ids"); + n.privateMropePosDeltas = intern("_mrope_position_deltas"); + n.privateAddCtxOutputs = intern("_additional_context_outputs"); + n.privateAddGenOutputs = intern("_additional_generation_outputs"); + n.privateEncoderOutput = intern("_encoder_output"); + n.ctxPromptLogprobRows = intern("context_prompt_logprob_rows"); + n.ctxPromptLastLogprobs = intern("context_prompt_last_logprobs"); + n.isFinal = intern("is_final"); + n.isRequestDone = intern("is_request_done"); + n.isSequenceFinal = intern("is_sequence_final"); + n.sequenceIndex = intern("sequence_index"); + n.outputTokenIds = intern("output_token_ids"); + n.finishReasons = intern("finish_reasons"); + n.cumLogProbs = intern("cum_log_probs"); + n.logProbs = intern("log_probs"); + n.stopIndex = intern("stop_index"); + n.replaceFrom = intern("replace_from"); + n.rowFlags = intern("row_flags"); + n.decodingIter = intern("decoding_iter"); + n.cachedTokens = intern("cached_tokens"); + n.avgDecodedTokensPerIter = intern("avg_decoded_tokens_per_iter"); + n.perPosDrafted = intern("per_pos_drafted"); + n.perPosAccepted = intern("per_pos_accepted"); + n.specDecTotals = intern("spec_dec_totals"); + n.ctxUsage = intern("ctx_usage"); + n.remoteTailStart = intern("remote_tail_start"); + n.timeBreakdownMetrics = intern("time_breakdown_metrics"); + n.requestPerfMetrics = intern("request_perf_metrics"); + n.contextPhaseParams = intern("context_phase_params"); + n.signedHandoff = intern("signed_handoff"); + n.logprob = intern("logprob"); + n.rank = intern("rank"); + n.name = intern("name"); + n.value = intern("value"); + n.samplingParams = intern("sampling_params"); + n.useBeamSearch = intern("use_beam_search"); + n.logprobsSimpleFormat = intern("logprobs_simple_format"); + n.frameSeq = intern("frame_seq"); + n.errorInfo = intern("error_info"); + n.hasError = intern("has_error"); + n.promptLogprobs = intern("prompt_logprobs"); + n.contextLogits = intern("context_logits"); + n.generationLogits = intern("generation_logits"); + n.encoderOutput = intern("encoder_output"); + n.routedExperts = intern("routed_experts"); + n.addCtxOutputs = intern("additional_context_outputs"); + n.addGenOutputs = intern("additional_generation_outputs"); + n.expandedPromptTokens = intern("expanded_prompt_tokens"); + n.streamingTensorRanges = intern("streaming_tensor_ranges"); + n.mmEmbeddingHandles = intern("mm_embedding_handles"); + n.mropePosIdsHandle = intern("mrope_position_ids_handle"); + n.mropePosDeltasHandle = intern("mrope_position_deltas_handle"); + return n; + }(); + return s; + } +}; + +//! Read an optional attribute; returns nullptr (without error set) when absent. +//! Checks instance ``__dict__`` first to avoid invoking custom ``__getattr__`` +//! (such as ``LlmResult.__getattr__``) or throwing/clearing AttributeError on +//! missing cold attributes. +Ref getAttrOpt(PyObject* obj, PyObject* attrName) +{ + PyObject** dictPtr = _PyObject_GetDictPtr(obj); + if (dictPtr != nullptr && *dictPtr != nullptr && PyDict_CheckExact(*dictPtr)) + { + PyObject* val = PyDict_GetItemWithError(*dictPtr, attrName); + if (val != nullptr) + { + return Ref(Py_NewRef(val)); + } + if (PyErr_Occurred()) + { + throwPythonError(); + } + // Only fall back to PyObject_GetAttr when the type defines a descriptor/method + // (e.g. property or class attribute), not when __getattr__ would just fail. + if (_PyType_Lookup(Py_TYPE(obj), attrName) == nullptr) + { + return Ref(); + } + } + PyObject* val = PyObject_GetAttr(obj, attrName); + if (val == nullptr) + { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + { + PyErr_Clear(); + return Ref(); + } + throwPythonError(); + } + return Ref(val); +} + +//! Borrowed instance-__dict__ lookup (returns nullptr when missing or no exact dict). +//! Caller must ensure the type does not override the attribute with a data descriptor. +PyObject* dictGetBorrowed(PyObject* dict, PyObject* attrName) +{ + if (dict == nullptr) + { + return nullptr; + } + PyObject* val = PyDict_GetItemWithError(dict, attrName); + if (val == nullptr && PyErr_Occurred()) + { + throwPythonError(); + } + return val; +} + +bool pyTruthy(PyObject* obj) +{ + int const r = PyObject_IsTrue(obj); + if (r < 0) + { + throwPythonError(); + } + return r != 0; +} + +//! Minimal cursor over tensorrt_llm::executor::Serialization::serialize(Result) bytes. +//! Only handles the common non-disagg, no-perf-metrics fast path; any optional +//! ContextPhaseParams or RequestPerfMetrics returns false so the caller falls back. +struct RawResultReader +{ + char const* cur; + char const* end; + + bool readBytes(void* dst, size_t len) + { + if (static_cast(end - cur) < len) + { + return false; + } + std::memcpy(dst, cur, len); + cur += len; + return true; + } + + template + bool readPod(T& out) + { + return readBytes(&out, sizeof(T)); + } +}; + +struct DecodedCppResultFast +{ + bool isFinal{false}; + std::vector> outputTokenIds; + std::vector finishReasons; + int32_t decodingIter{0}; + float avgDecodedTokensPerIter{0.0F}; + int32_t sequenceIndex{0}; + bool isSequenceFinal{false}; +}; + +//! Parses serialized C++ bindings.executor.Result bytes when neither ContextPhaseParams nor +//! RequestPerfMetrics is present. Returns false if either optional is set or bytes are malformed. +bool parseSerializedCppResultFast(char const* data, size_t size, DecodedCppResultFast& out) +{ + RawResultReader r{data, data + size}; + if (!r.readPod(out.isFinal)) + { + return false; + } + size_t nBeams = 0; + if (!r.readPod(nBeams) || nBeams == 0 || nBeams > 1024) + { + return false; + } + out.outputTokenIds.resize(nBeams); + for (size_t b = 0; b < nBeams; ++b) + { + size_t nToks = 0; + if (!r.readPod(nToks) || nToks > (1U << 24)) + { + return false; + } + out.outputTokenIds[b].resize(nToks); + if (nToks > 0 && !r.readBytes(out.outputTokenIds[b].data(), nToks * sizeof(int32_t))) + { + return false; + } + } + size_t nReasons = 0; + if (!r.readPod(nReasons) || nReasons == 0 || nReasons > 1024) + { + return false; + } + out.finishReasons.resize(nReasons); + for (size_t i = 0; i < nReasons; ++i) + { + // C++ tensorrt_llm::executor::FinishReason has underlying type int (4 bytes). + int32_t fr = 0; + if (!r.readPod(fr) || fr < 0 || fr > 255) + { + return false; + } + out.finishReasons[i] = static_cast(fr); + } + bool hasContextPhaseParams = false; + if (!r.readPod(hasContextPhaseParams) || hasContextPhaseParams) + { + return false; + } + if (!r.readPod(out.decodingIter) || !r.readPod(out.avgDecodedTokensPerIter) || !r.readPod(out.sequenceIndex) + || !r.readPod(out.isSequenceFinal)) + { + return false; + } + bool hasRequestPerfMetrics = false; + if (!r.readPod(hasRequestPerfMetrics) || hasRequestPerfMetrics) + { + return false; + } + return r.cur == r.end; +} + +//! Split one Python {token_id: Logprob} dict into (sampled_lp, sampled_rank, topk_cands), +//! matching codec._split_logprob_entry(). Returns false on unsupported entry types. +bool extractDictLogprobEntry(PyObject* dictObj, int32_t targetTid, StepNames const& sn, float& sampledLp, + uint32_t& sampledRank, std::vector>& candsOut) +{ + if (!PyDict_Check(dictObj)) + { + return false; + } + Py_ssize_t const nItems = PyDict_Size(dictObj); + if (nItems == 0) + { + sampledLp = std::numeric_limits::quiet_NaN(); + sampledRank = 0; + candsOut.clear(); + return true; + } + + struct RawEntry + { + int32_t tid; + float lp; + uint32_t rank; + }; + + std::vector raw; + raw.reserve(static_cast(nItems)); + + bool foundTarget = false; + float chosenLp = std::numeric_limits::quiet_NaN(); + uint32_t chosenRank = 0; + uint32_t nonTargetCount = 0; + bool anyPositiveRank = false; + + PyObject* key = nullptr; + PyObject* val = nullptr; + Py_ssize_t pos = 0; + while (PyDict_Next(dictObj, &pos, &key, &val)) + { + int32_t const cid = toPyIntInt32(key, "logprob token id"); + float lpVal = 0.0F; + uint32_t rkVal = 0; + if (PyFloat_Check(val) || PyLong_Check(val)) + { + lpVal = static_cast(toDouble(val)); + } + else + { + PyObject** vDictPtr = _PyObject_GetDictPtr(val); + PyObject* vDict + = (vDictPtr != nullptr && *vDictPtr != nullptr && PyDict_CheckExact(*vDictPtr)) ? *vDictPtr : nullptr; + if (vDict != nullptr) + { + PyObject* lpPtr = dictGetBorrowed(vDict, sn.logprob); + if (lpPtr == nullptr) + { + return false; + } + lpVal = static_cast(toDouble(lpPtr)); + PyObject* rkPtr = dictGetBorrowed(vDict, sn.rank); + if (rkPtr != nullptr && rkPtr != Py_None) + { + int64_t const rk = toInt64(rkPtr, 0, std::numeric_limits::max(), "rank"); + rkVal = static_cast(rk); + } + } + else + { + Ref lpAttr = getAttrOpt(val, sn.logprob); + if (lpAttr.get() == nullptr) + { + return false; + } + lpVal = static_cast(toDouble(lpAttr.get())); + Ref rkAttr = getAttrOpt(val, sn.rank); + if (rkAttr.get() != nullptr && rkAttr.get() != Py_None) + { + int64_t const rk = toInt64(rkAttr.get(), 0, std::numeric_limits::max(), "rank"); + rkVal = static_cast(rk); + } + } + } + if (rkVal > 0) + { + anyPositiveRank = true; + } + if (cid == targetTid) + { + foundTarget = true; + chosenLp = lpVal; + chosenRank = rkVal; + } + else + { + ++nonTargetCount; + } + raw.push_back(RawEntry{cid, lpVal, rkVal}); + } + + if (!foundTarget) + { + // Fall back to Python for out-of-target-id heuristic matching. + return false; + } + + sampledLp = chosenLp; + sampledRank = chosenRank; + candsOut.clear(); + + // k = 0 single-entry dict carrying only target token with rank > 0. + if (raw.size() == 1 && raw[0].tid == targetTid && chosenRank != 0) + { + return true; + } + + // Separate in-top-k candidates from an appended out-of-top-k target token. + bool targetOutsideTopk = chosenRank > 0 && chosenRank > nonTargetCount + 1; + if (!targetOutsideTopk && chosenRank > 0 && nonTargetCount > 0) + { + std::vector nonTargetRanks; + nonTargetRanks.reserve(nonTargetCount); + uint32_t maxNonTarget = 0; + for (auto const& e : raw) + { + if (e.tid != targetTid && e.rank > 0) + { + nonTargetRanks.push_back(e.rank); + maxNonTarget = std::max(maxNonTarget, e.rank); + } + } + if (nonTargetRanks.size() == nonTargetCount) + { + if (maxNonTarget <= nonTargetCount && chosenRank > nonTargetCount) + { + targetOutsideTopk = true; + } + else + { + std::sort(nonTargetRanks.begin(), nonTargetRanks.end()); + bool contiguous = true; + for (uint32_t k = 0; k < nonTargetCount; ++k) + { + if (nonTargetRanks[k] != k + 1) + { + contiguous = false; + break; + } + } + if (contiguous) + { + targetOutsideTopk = true; + } + } + } + } + + std::vector filtered; + filtered.reserve(raw.size()); + for (auto const& e : raw) + { + if (targetOutsideTopk && e.tid == targetTid) + { + continue; + } + filtered.push_back(e); + } + if (anyPositiveRank && filtered.size() > 1) + { + uint32_t const fallbackOrder = static_cast(filtered.size() + 1); + std::stable_sort(filtered.begin(), filtered.end(), + [fallbackOrder](RawEntry const& a, RawEntry const& b) + { + uint32_t const ka = a.rank > 0 ? a.rank : fallbackOrder; + uint32_t const kb = b.rank > 0 ? b.rank : fallbackOrder; + return ka < kb; + }); + } + candsOut.reserve(filtered.size()); + for (auto const& e : filtered) + { + candsOut.emplace_back(e.tid, e.lp); + } + return true; +} + +//! Fast-path encoder for a batch of homogeneous non-extra responses (plain decode / beam steps, +//! with or without logprobs / cum_log_probs, and with serialized C++ LlmResult._result bytes). +//! Returns serialized ServerMessage{frame} bytes (or Frame bytes if !serverMessage) when EVERY +//! response in the batch is eligible for the fast path; returns None if any response requires +//! RowExtra (error, first-row PromptInfo, SEQ_FINAL FinalInfo, handoff, tensors, perf metrics, +//! spec-dec counters, ResponseWrapper, or unsupported types) so the Python encoder handles it. +nb::object encodeStepFast(nb::handle responses, uint64_t frameSeq, uint64_t iterFirst, uint64_t iterLast, + uint64_t emitTimeNs, bool serverMessage) +{ + StepNames const& sn = StepNames::get(); + Ref seq = fastSequence(responses.ptr(), "responses must be a sequence"); + Py_ssize_t const nResp = PySequence_Fast_GET_SIZE(seq.get()); + PyObject** items = PySequence_Fast_ITEMS(seq.get()); + + EncodeInput in; + in.frameSeq = frameSeq; + in.iterFirst = iterFirst; + in.iterLast = iterLast; + in.emitTimeNs = emitTimeNs; + // Reserve column buffers upfront so steady-state decode batches do not reallocate. + size_t const reserveRows = static_cast(nResp); + in.handle.reserve(reserveRows); + in.seq.reserve(reserveRows); + in.tokens.reserve(reserveRows); + in.tokenOffsets.reserve(reserveRows + 1); + in.tokenOffsets.push_back(0); + in.finish.reserve(reserveRows); + in.rowFlags.reserve(reserveRows); + in.stopIndex.reserve(reserveRows); + in.replaceFrom.reserve(reserveRows); + in.extraIndex.reserve(reserveRows); + in.decodingIter.reserve(reserveRows); + in.cachedTokens.reserve(reserveRows); + in.cumLogprob.reserve(reserveRows); + in.hasLpSampled.reserve(reserveRows); + in.hasLpRank.reserve(reserveRows); + in.hasLpTopk.reserve(reserveRows); + + std::vector> tmpCands; + DecodedCppResultFast cppRes; + + auto hasNonNoneAttr = [](PyObject* obj, PyObject* attr) -> bool + { + Ref v = getAttrOpt(obj, attr); + return v.get() != nullptr && v.get() != Py_None; + }; + auto hasTruthyAttr = [](PyObject* obj, PyObject* attr) -> bool + { + Ref v = getAttrOpt(obj, attr); + return v.get() != nullptr && v.get() != Py_None && pyTruthy(v.get()); + }; + auto dictHasNonNone = [](PyObject* dict, PyObject* attr) -> bool + { + PyObject* v = dictGetBorrowed(dict, attr); + return v != nullptr && v != Py_None; + }; + auto mappingHasNonEmptyValues = [](PyObject* obj) -> bool + { + if (obj == nullptr || obj == Py_None) + { + return false; + } + if (!PyDict_Check(obj)) + { + return pyTruthy(obj); + } + if (PyDict_Size(obj) == 0) + { + return false; + } + PyObject* k = nullptr; + PyObject* v = nullptr; + Py_ssize_t pos = 0; + while (PyDict_Next(obj, &pos, &k, &v)) + { + if (v != nullptr && v != Py_None && pyTruthy(v)) + { + return true; + } + } + return false; + }; + + for (Py_ssize_t i = 0; i < nResp; ++i) + { + PyObject* rsp = items[i]; + // Fast path for standard instance-dict responses (LlmResponse, ZmqStepResponse, etc.): + // avoids creating bound method objects or raising/clearing AttributeError per row. + PyObject** rspDictPtr = _PyObject_GetDictPtr(rsp); + PyObject* rspDict = (rspDictPtr != nullptr && *rspDictPtr != nullptr && PyDict_CheckExact(*rspDictPtr)) + ? *rspDictPtr + : nullptr; + + if (rspDict != nullptr && dictGetBorrowed(rspDict, sn.privateResponse) != nullptr) + { + return nb::none(); + } + if (rspDict == nullptr && PyObject_HasAttr(rsp, sn.privateResponse)) + { + return nb::none(); + } + PyObject* errBorrowed = rspDict != nullptr ? dictGetBorrowed(rspDict, sn.errorMsg) : nullptr; + if (errBorrowed != nullptr) + { + if (errBorrowed != Py_None) + { + return nb::none(); + } + } + else + { + Ref errObj = getAttrOpt(rsp, sn.errorMsg); + if (errObj.get() != nullptr && errObj.get() != Py_None) + { + return nb::none(); + } + Ref hasErrMethod = getAttrOpt(rsp, sn.hasError); + if (hasErrMethod.get() != nullptr && PyCallable_Check(hasErrMethod.get())) + { + Ref isErr(PyObject_CallNoArgs(hasErrMethod.get())); + isErr.checked(); + if (pyTruthy(isErr.get())) + { + return nb::none(); + } + } + } + Ref cidOwned; + PyObject* cidPtr = rspDict != nullptr ? dictGetBorrowed(rspDict, sn.clientId) : nullptr; + if (cidPtr == nullptr) + { + cidOwned = getAttrOpt(rsp, sn.clientId); + cidPtr = cidOwned.get(); + } + if (cidPtr == nullptr || cidPtr == Py_None) + { + return nb::none(); + } + uint64_t const handle = toUint64(cidPtr, "client_id"); + + Ref resOwned; + PyObject* res = rspDict != nullptr ? dictGetBorrowed(rspDict, sn.result) : nullptr; + if (res == nullptr) + { + resOwned = getAttrOpt(rsp, sn.result); + res = resOwned.get(); + } + if (res == nullptr || res == Py_None) + { + return nb::none(); + } + + // Check instance dict of result directly when available (LlmResult stores all + // attributes directly in __dict__ and defines custom __getattr__). + PyObject** resDictPtr = _PyObject_GetDictPtr(res); + PyObject* resDict = (resDictPtr != nullptr && *resDictPtr != nullptr && PyDict_CheckExact(*resDictPtr)) + ? *resDictPtr + : nullptr; + + PyObject* rawResultPtr = resDict != nullptr ? dictGetBorrowed(resDict, sn.privateResult) : nullptr; + PyObject* pyResultPtr = resDict != nullptr ? dictGetBorrowed(resDict, sn.privatePyResult) : nullptr; + Ref rawResultOwned; + Ref pyResultOwned; + if (resDict == nullptr) + { + rawResultOwned = getAttrOpt(res, sn.privateResult); + rawResultPtr = rawResultOwned.get(); + pyResultOwned = getAttrOpt(res, sn.privatePyResult); + pyResultPtr = pyResultOwned.get(); + } + bool const isSerializedLlmResult = rawResultPtr != nullptr && PyBytes_Check(rawResultPtr) + && pyResultPtr != nullptr && pyResultPtr != Py_None; + + uint16_t explicitFlags = 0; + Ref logProbsSeq; + Ref cumLogProbsSeq; + int32_t stopIdx = kNoStopIndex; + uint32_t replaceFrom = kNoReplaceFrom; + uint32_t decodingIter = 0; + uint32_t baseSeq = 0; + uint32_t cachedTokens = 0; + bool useCppTokens = false; + + if (isSerializedLlmResult) + { + // Fast dict-backed checks for PyExecutor LlmResult + PyResult: + // skips LlmResult.__getattr__ completely. + PyObject* isFinalPtr = resDict != nullptr ? dictGetBorrowed(resDict, sn.isFinal) : nullptr; + if (isFinalPtr != nullptr) + { + if (isFinalPtr == Py_True || (isFinalPtr != Py_False && pyTruthy(isFinalPtr))) + { + return nb::none(); + } + } + else if (hasTruthyAttr(res, sn.isFinal)) + { + return nb::none(); + } + + if (resDict != nullptr) + { + if (dictHasNonNone(resDict, sn.ctxUsage) || dictHasNonNone(resDict, sn.remoteTailStart) + || dictHasNonNone(resDict, sn.timeBreakdownMetrics) || dictHasNonNone(resDict, sn.routedExperts) + || dictHasNonNone(resDict, sn.perPosDrafted) || dictHasNonNone(resDict, sn.perPosAccepted) + || dictHasNonNone(resDict, sn.specDecTotals)) + { + return nb::none(); + } + PyObject* rfPtr = dictGetBorrowed(resDict, sn.rowFlags); + if (rfPtr != nullptr && rfPtr != Py_None) + { + int64_t const rf = toInt64(rfPtr, 0, std::numeric_limits::max(), "row_flags"); + explicitFlags = static_cast(rf); + if ((explicitFlags & (kRowFlagFirstRow | kRowFlagSeqFinal | kRowFlagHasExtra)) != 0) + { + return nb::none(); + } + } + PyObject* cachedPtr = dictGetBorrowed(resDict, sn.cachedTokens); + if (cachedPtr != nullptr && cachedPtr != Py_None) + { + cachedTokens = toUint32(cachedPtr, "cached_tokens"); + } + } + else + { + if (hasNonNoneAttr(res, sn.ctxUsage) || hasNonNoneAttr(res, sn.remoteTailStart) + || hasNonNoneAttr(res, sn.timeBreakdownMetrics) || hasNonNoneAttr(res, sn.routedExperts) + || hasNonNoneAttr(res, sn.perPosDrafted) || hasNonNoneAttr(res, sn.perPosAccepted) + || hasNonNoneAttr(res, sn.specDecTotals)) + { + return nb::none(); + } + Ref rfObj = getAttrOpt(res, sn.rowFlags); + if (rfObj.get() != nullptr && rfObj.get() != Py_None) + { + int64_t const rf = toInt64(rfObj.get(), 0, std::numeric_limits::max(), "row_flags"); + explicitFlags = static_cast(rf); + if ((explicitFlags & (kRowFlagFirstRow | kRowFlagSeqFinal | kRowFlagHasExtra)) != 0) + { + return nb::none(); + } + } + Ref cachedObj = getAttrOpt(res, sn.cachedTokens); + if (cachedObj.get() != nullptr && cachedObj.get() != Py_None) + { + cachedTokens = toUint32(cachedObj.get(), "cached_tokens"); + } + } + + PyObject* pyRes = pyResultPtr; + PyObject** pyResDictPtr = _PyObject_GetDictPtr(pyRes); + PyObject* pyResDict + = (pyResDictPtr != nullptr && *pyResDictPtr != nullptr && PyDict_CheckExact(*pyResDictPtr)) + ? *pyResDictPtr + : nullptr; + if (pyResDict != nullptr) + { + if (dictHasNonNone(pyResDict, sn.privateContextLogits) + || dictHasNonNone(pyResDict, sn.privateGenerationLogits) + || dictHasNonNone(pyResDict, sn.privateFirstGenLogProbs) + || dictHasNonNone(pyResDict, sn.privateMmEmbeddings) + || dictHasNonNone(pyResDict, sn.privateMropePosIds) + || dictHasNonNone(pyResDict, sn.privateMropePosDeltas) + || mappingHasNonEmptyValues(dictGetBorrowed(pyResDict, sn.privateAddCtxOutputs)) + || mappingHasNonEmptyValues(dictGetBorrowed(pyResDict, sn.privateAddGenOutputs)) + || dictHasNonNone(pyResDict, sn.privateEncoderOutput) + || dictHasNonNone(pyResDict, sn.ctxPromptLogprobRows) + || dictHasNonNone(pyResDict, sn.ctxPromptLastLogprobs)) + { + return nb::none(); + } + } + else + { + Ref addCtx = getAttrOpt(pyRes, sn.privateAddCtxOutputs); + Ref addGen = getAttrOpt(pyRes, sn.privateAddGenOutputs); + if (hasNonNoneAttr(pyRes, sn.privateContextLogits) || hasNonNoneAttr(pyRes, sn.privateGenerationLogits) + || hasNonNoneAttr(pyRes, sn.privateFirstGenLogProbs) + || hasNonNoneAttr(pyRes, sn.privateMmEmbeddings) || hasNonNoneAttr(pyRes, sn.privateMropePosIds) + || hasNonNoneAttr(pyRes, sn.privateMropePosDeltas) || mappingHasNonEmptyValues(addCtx.get()) + || mappingHasNonEmptyValues(addGen.get()) || hasNonNoneAttr(pyRes, sn.privateEncoderOutput) + || hasNonNoneAttr(pyRes, sn.ctxPromptLogprobRows) + || hasNonNoneAttr(pyRes, sn.ctxPromptLastLogprobs)) + { + return nb::none(); + } + } + + if (!parseSerializedCppResultFast( + PyBytes_AS_STRING(rawResultPtr), static_cast(PyBytes_GET_SIZE(rawResultPtr)), cppRes)) + { + return nb::none(); + } + if (cppRes.isFinal || cppRes.isSequenceFinal) + { + return nb::none(); + } + for (uint8_t fr : cppRes.finishReasons) + { + if (fr != 0) + { + return nb::none(); + } + } + PyObject* lpStoragePtr = pyResDict != nullptr ? dictGetBorrowed(pyResDict, sn.privateLogProbs) : nullptr; + Ref lpStorageOwned; + if (pyResDict == nullptr) + { + lpStorageOwned = getAttrOpt(pyRes, sn.privateLogProbs); + lpStoragePtr = lpStorageOwned.get(); + } + if (lpStoragePtr != nullptr && lpStoragePtr != Py_None) + { + PyObject** lpsDictPtr = _PyObject_GetDictPtr(lpStoragePtr); + PyObject* lpsDict = (lpsDictPtr != nullptr && *lpsDictPtr != nullptr && PyDict_CheckExact(*lpsDictPtr)) + ? *lpsDictPtr + : nullptr; + if (lpsDict != nullptr) + { + PyObject* lpVal = dictGetBorrowed(lpsDict, sn.logProbs); + PyObject* clpVal = dictGetBorrowed(lpsDict, sn.cumLogProbs); + if (lpVal != nullptr) + { + logProbsSeq = Ref(Py_NewRef(lpVal)); + } + if (clpVal != nullptr) + { + cumLogProbsSeq = Ref(Py_NewRef(clpVal)); + } + } + else + { + logProbsSeq = getAttrOpt(lpStoragePtr, sn.logProbs); + cumLogProbsSeq = getAttrOpt(lpStoragePtr, sn.cumLogProbs); + } + } + decodingIter = cppRes.decodingIter > 0 ? static_cast(cppRes.decodingIter) : 0U; + baseSeq = cppRes.sequenceIndex > 0 ? static_cast(cppRes.sequenceIndex) : 0U; + useCppTokens = true; + } + else + { + // Quick bail on final responses (require FinalInfo RowExtra) or special flags/extras. + Ref isFinalObj = getAttrOpt(res, sn.isFinal); + if (isFinalObj.get() != nullptr && pyTruthy(isFinalObj.get())) + { + return nb::none(); + } + Ref isReqDoneObj = getAttrOpt(res, sn.isRequestDone); + if (isReqDoneObj.get() != nullptr && pyTruthy(isReqDoneObj.get())) + { + return nb::none(); + } + Ref rowFlagsObj = getAttrOpt(res, sn.rowFlags); + if (rowFlagsObj.get() != nullptr && rowFlagsObj.get() != Py_None) + { + int64_t const rf = toInt64(rowFlagsObj.get(), 0, std::numeric_limits::max(), "row_flags"); + explicitFlags = static_cast(rf); + if ((explicitFlags & (kRowFlagFirstRow | kRowFlagSeqFinal | kRowFlagHasExtra)) != 0) + { + return nb::none(); + } + } + // Bail if any cold/extra/disagg field is populated on a Python result object. + if (hasNonNoneAttr(res, sn.contextPhaseParams) || hasNonNoneAttr(res, sn.signedHandoff) + || hasNonNoneAttr(res, sn.promptLogprobs) || hasNonNoneAttr(res, sn.contextLogits) + || hasNonNoneAttr(res, sn.generationLogits) || hasNonNoneAttr(res, sn.encoderOutput) + || hasNonNoneAttr(res, sn.routedExperts) || hasNonNoneAttr(res, sn.addCtxOutputs) + || hasNonNoneAttr(res, sn.addGenOutputs) || hasNonNoneAttr(res, sn.expandedPromptTokens) + || hasNonNoneAttr(res, sn.requestPerfMetrics) || hasNonNoneAttr(res, sn.timeBreakdownMetrics) + || hasNonNoneAttr(res, sn.ctxUsage) || hasNonNoneAttr(res, sn.remoteTailStart) + || hasTruthyAttr(res, sn.streamingTensorRanges) || hasTruthyAttr(res, sn.mmEmbeddingHandles) + || hasTruthyAttr(res, sn.mropePosIdsHandle) || hasTruthyAttr(res, sn.mropePosDeltasHandle)) + { + return nb::none(); + } + Ref frSeqObj = getAttrOpt(res, sn.finishReasons); + if (frSeqObj.get() != nullptr && frSeqObj.get() != Py_None) + { + Ref frFast = fastSequence(frSeqObj.get(), "finish_reasons must be a sequence"); + Py_ssize_t const nFr = PySequence_Fast_GET_SIZE(frFast.get()); + PyObject** frItems = PySequence_Fast_ITEMS(frFast.get()); + for (Py_ssize_t f = 0; f < nFr; ++f) + { + PyObject* frItem = frItems[f]; + if (PyLong_Check(frItem)) + { + if (PyLong_AsLong(frItem) != 0 || PyErr_Occurred()) + { + PyErr_Clear(); + return nb::none(); + } + } + else + { + Ref frName = getAttrOpt(frItem, sn.name); + if (frName.get() == nullptr || !PyUnicode_Check(frName.get()) + || std::strcmp(PyUnicode_AsUTF8(frName.get()), "NOT_FINISHED") != 0) + { + return nb::none(); + } + } + } + } + Ref seqIdxObj = getAttrOpt(res, sn.sequenceIndex); + if (seqIdxObj.get() != nullptr && seqIdxObj.get() != Py_None) + { + baseSeq = toUint32(seqIdxObj.get(), "sequence_index"); + } + Ref stopObj = getAttrOpt(res, sn.stopIndex); + if (stopObj.get() != nullptr && stopObj.get() != Py_None) + { + stopIdx = toPyIntInt32(stopObj.get(), "stop_index"); + } + Ref replObj = getAttrOpt(res, sn.replaceFrom); + if (replObj.get() != nullptr && replObj.get() != Py_None) + { + replaceFrom = toUint32(replObj.get(), "replace_from"); + } + Ref decIterObj = getAttrOpt(res, sn.decodingIter); + if (decIterObj.get() != nullptr && decIterObj.get() != Py_None) + { + decodingIter = toUint32(decIterObj.get(), "decoding_iter"); + } + Ref cachedObj = getAttrOpt(res, sn.cachedTokens); + if (cachedObj.get() != nullptr && cachedObj.get() != Py_None) + { + cachedTokens = toUint32(cachedObj.get(), "cached_tokens"); + } + logProbsSeq = getAttrOpt(res, sn.logProbs); + cumLogProbsSeq = getAttrOpt(res, sn.cumLogProbs); + } + + Py_ssize_t lpBeams = 0; + PyObject** lpBeamItems = nullptr; + Ref lpFast; + if (logProbsSeq.get() != nullptr && logProbsSeq.get() != Py_None) + { + lpFast = fastSequence(logProbsSeq.get(), "log_probs must be a sequence"); + lpBeams = PySequence_Fast_GET_SIZE(lpFast.get()); + lpBeamItems = PySequence_Fast_ITEMS(lpFast.get()); + } + Py_ssize_t clpBeams = 0; + PyObject** clpBeamItems = nullptr; + Ref clpFast; + if (cumLogProbsSeq.get() != nullptr && cumLogProbsSeq.get() != Py_None) + { + clpFast = fastSequence(cumLogProbsSeq.get(), "cum_log_probs must be a sequence"); + clpBeams = PySequence_Fast_GET_SIZE(clpFast.get()); + clpBeamItems = PySequence_Fast_ITEMS(clpFast.get()); + } + + // Read output_token_ids for Branch B. + Ref pyOutToksFast; + PyObject** pyOutTokBeamItems = nullptr; + size_t numSeqs = 0; + if (useCppTokens) + { + numSeqs = cppRes.outputTokenIds.size(); + } + else + { + Ref outToksObj = getAttrOpt(res, sn.outputTokenIds); + if (outToksObj.get() == nullptr || outToksObj.get() == Py_None) + { + return nb::none(); + } + pyOutToksFast = fastSequence(outToksObj.get(), "output_token_ids must be a sequence"); + Py_ssize_t const nBeams = PySequence_Fast_GET_SIZE(pyOutToksFast.get()); + if (nBeams <= 0) + { + return nb::none(); + } + numSeqs = static_cast(nBeams); + pyOutTokBeamItems = PySequence_Fast_ITEMS(pyOutToksFast.get()); + } + + std::vector pyTokBuf; + for (size_t sIdx = 0; sIdx < numSeqs; ++sIdx) + { + uint32_t const seqNum = numSeqs > 1 ? static_cast(sIdx) : baseSeq; + int32_t const* tokPtr = nullptr; + size_t nt = 0; + if (useCppTokens) + { + auto const& toks = cppRes.outputTokenIds[sIdx]; + tokPtr = toks.data(); + nt = toks.size(); + } + else + { + Ref beamToks = fastSequence(pyOutTokBeamItems[sIdx], "output_token_ids row must be a sequence"); + nt = static_cast(PySequence_Fast_GET_SIZE(beamToks.get())); + PyObject** tokItems = PySequence_Fast_ITEMS(beamToks.get()); + pyTokBuf.resize(nt); + for (size_t t = 0; t < nt; ++t) + { + pyTokBuf[t] = toPyIntInt32(tokItems[t], "token"); + } + tokPtr = pyTokBuf.data(); + } + + in.handle.push_back(handle); + in.seq.push_back(seqNum); + in.needSeq |= seqNum != 0; + in.tokens.insert(in.tokens.end(), tokPtr, tokPtr + nt); + in.tokenOffsets.push_back(static_cast(in.tokens.size())); + in.finish.push_back(0U); + in.rowFlags.push_back(explicitFlags); + in.stopIndex.push_back(stopIdx); + in.needStopIndex |= stopIdx != kNoStopIndex; + in.replaceFrom.push_back(replaceFrom); + in.needReplaceFrom |= replaceFrom != kNoReplaceFrom; + in.extraIndex.push_back(kNoExtraIndex); + in.decodingIter.push_back(decodingIter); + in.needDecodingIter |= decodingIter != 0; + in.cachedTokens.push_back(cachedTokens); + in.needCachedTokens |= cachedTokens != 0; + + if (clpBeamItems != nullptr && static_cast(sIdx) < clpBeams && clpBeamItems[sIdx] != Py_None) + { + in.needCumLogprob = true; + in.cumLogprob.push_back(toPyFloat(clpBeamItems[sIdx])); + } + else + { + in.cumLogprob.push_back(std::numeric_limits::quiet_NaN()); + } + + bool rowHasSampled = false; + bool rowHasRank = false; + bool rowHasTopk = false; + if (lpBeamItems != nullptr && static_cast(sIdx) < lpBeams && lpBeamItems[sIdx] != Py_None + && nt > 0) + { + Ref rowLpFast = fastSequence(lpBeamItems[sIdx], "log_probs row must be a sequence"); + if (static_cast(PySequence_Fast_GET_SIZE(rowLpFast.get())) != nt) + { + return nb::none(); + } + PyObject** entryItems = PySequence_Fast_ITEMS(rowLpFast.get()); + rowHasSampled = true; + in.needLpSampled = true; + + size_t const rankStart = in.lpRankValues.size(); + size_t const topkCountStart = in.lpTopkCounts.size(); + size_t const topkIdsStart = in.lpTopkIds.size(); + for (size_t t = 0; t < nt; ++t) + { + PyObject* entry = entryItems[t]; + if (PyFloat_Check(entry) || PyLong_Check(entry)) + { + in.lpSampledValues.push_back(static_cast(toDouble(entry))); + in.lpRankValues.push_back(0U); + in.lpTopkCounts.push_back(0U); + } + else if (PyDict_Check(entry)) + { + float sLp = 0.0F; + uint32_t sRk = 0; + if (!extractDictLogprobEntry(entry, tokPtr[t], sn, sLp, sRk, tmpCands)) + { + return nb::none(); + } + in.lpSampledValues.push_back(sLp); + in.lpRankValues.push_back(sRk); + if (sRk != 0) + { + rowHasRank = true; + } + in.lpTopkCounts.push_back(static_cast(tmpCands.size())); + if (!tmpCands.empty()) + { + rowHasTopk = true; + for (auto const& kv : tmpCands) + { + in.lpTopkIds.push_back(kv.first); + in.lpTopkLogprobs.push_back(kv.second); + } + } + } + else + { + return nb::none(); + } + } + if (rowHasRank) + { + in.needLpRank = true; + } + else + { + in.lpRankValues.resize(rankStart); + } + if (rowHasTopk) + { + in.needLpTopk = true; + } + else + { + in.lpTopkCounts.resize(topkCountStart); + in.lpTopkIds.resize(topkIdsStart); + in.lpTopkLogprobs.resize(topkIdsStart); + } + } + in.hasLpSampled.push_back(rowHasSampled ? 1 : 0); + in.hasLpRank.push_back(rowHasRank ? 1 : 0); + in.hasLpTopk.push_back(rowHasTopk ? 1 : 0); + ++in.nRows; + } + } + + std::string out; + { + nb::gil_scoped_release release; + out = packFrame(in, serverMessage); + } + return toBytes(out); +} + +//! Fast-path proxy decoder for ServerMessage{frame} bytes without RowExtra. +//! Directly unpacks the protobuf Frame without the GIL and constructs (frame_seq, responses) +//! where each response is an instance of \p responseType holding a \p resultType (with +//! __slots__), Logprob instances built via tp_new, and multi-beam rows coalesced in C++. +//! Returns None if the message is not a "frame" or if ANY row carries a RowExtra or +//! FINISH_REASON_ERROR / FINISH_REASON_CONTEXT_DONE, letting the full Python path handle it. +nb::object decodeStepServerMessageFast(nb::handle data, nb::handle resultsMap, nb::handle responseType, + nb::handle resultType, nb::tuple finishReasons, nb::handle logprobType) +{ + BytesArg arg(data); + size_t const nFinishReasons = finishReasons.size(); + DecodedFrame d; + bool eligible = false; + { + nb::gil_scoped_release release; + pbv1::ServerMessage message; + parseOrThrow(message, arg.data(), "ServerMessage"); + if (message.payload_case() == pbv1::ServerMessage::kFrame) + { + auto const& frame = message.frame(); + if (frame.extras_size() == 0 && frame.extra_index().empty()) + { + unpackFrame(frame, d); + eligible = true; + for (size_t i = 0; i < d.nRows; ++i) + { + if (d.finish[i] >= nFinishReasons || (d.rowFlags[i] & kRowFlagHasExtra) != 0) + { + eligible = false; + break; + } + } + } + } + } + if (!eligible) + { + return nb::none(); + } + + StepNames const& sn = StepNames::get(); + if (!PyType_Check(responseType.ptr()) || !PyType_Check(resultType.ptr()) || !PyType_Check(logprobType.ptr())) + { + raise(PyExc_TypeError, "response_type, result_type, and logprob_type must be classes"); + } + PyTypeObject* const rspT = reinterpret_cast(responseType.ptr()); + PyTypeObject* const resT = reinterpret_cast(resultType.ptr()); + PyTypeObject* const lpT = reinterpret_cast(logprobType.ptr()); + if (rspT->tp_new == nullptr || resT->tp_new == nullptr || lpT->tp_new == nullptr) + { + raise(PyExc_TypeError, "response_type, result_type, and logprob_type must be instantiable classes"); + } + bool const hasResultsMap = resultsMap.is_valid() && !resultsMap.is_none(); + if (hasResultsMap && !PyDict_Check(resultsMap.ptr())) + { + return nb::none(); + } + Ref emptyArgs(PyTuple_New(0)); + emptyArgs.checked(); + Ref frameSeqObj(newULong(d.frameSeq)); + + auto setAttr = [](PyObject* obj, PyObject* attr, PyObject* val) + { + if (PyObject_SetAttr(obj, attr, val) < 0) + { + throwPythonError(); + } + }; + + auto makeLogprob = [&](float val, PyObject* rkObj) -> PyObject* + { + Ref obj(lpT->tp_new(lpT, emptyArgs.get(), nullptr)); + obj.checked(); + Ref fl(newFloat(static_cast(val))); + setAttr(obj.get(), sn.logprob, fl.get()); + setAttr(obj.get(), sn.rank, rkObj); + return obj.release(); + }; + + // Helper: lookup sampling_params for a client handle. + auto lookupSamplingParams = [&](PyObject* cidObj) -> Ref + { + if (!hasResultsMap) + { + return Ref(); + } + PyObject* genRes = PyDict_GetItemWithError(resultsMap.ptr(), cidObj); + if (genRes == nullptr) + { + if (PyErr_Occurred()) + { + throwPythonError(); + } + return Ref(); + } + return getAttrOpt(genRes, sn.samplingParams); + }; + + auto isBeamRow = [&](Ref const& spObj, uint32_t replaceFrom) -> bool + { + if (spObj.get() != nullptr && spObj.get() != Py_None) + { + Ref ubs = getAttrOpt(spObj.get(), sn.useBeamSearch); + if (ubs.get() != nullptr) + { + return pyTruthy(ubs.get()); + } + } + return replaceFrom != kNoReplaceFrom; + }; + + auto buildRowLogprobs = [&](size_t rowIdx, bool simpleFormat) -> PyObject* + { + uint32_t const t0 = d.tokenOffsets[rowIdx]; + uint32_t const t1 = d.tokenOffsets[rowIdx + 1]; + if (!d.hasLpSampled || t1 <= t0) + { + return nullptr; + } + bool sampledPresent = false; + for (uint32_t t = t0; t < t1; ++t) + { + if (!std::isnan(d.lpSampled[t])) + { + sampledPresent = true; + break; + } + } + if (!sampledPresent) + { + return nullptr; + } + Ref perTok(PyList_New(static_cast(t1 - t0))); + perTok.checked(); + for (uint32_t t = t0; t < t1; ++t) + { + float const sampledLp = d.lpSampled[t]; + if (simpleFormat) + { + PyList_SET_ITEM( + perTok.get(), static_cast(t - t0), newFloat(static_cast(sampledLp))); + continue; + } + int32_t const tokId = d.tokens[t]; + uint32_t const rk = d.hasLpRank ? d.lpRank[t] : 0U; + uint32_t const c0 = d.hasLpTopk ? d.lpTopkOffsets[t] : 0U; + uint32_t const c1 = d.hasLpTopk ? d.lpTopkOffsets[t + 1] : 0U; + if (c1 > c0 || rk != 0) + { + Ref dict(PyDict_New()); + dict.checked(); + bool hasTok = false; + for (uint32_t c = c0; c < c1; ++c) + { + int32_t const cid = d.lpTopkIds[c]; + uint32_t const candRank = (cid == tokId && rk != 0) ? rk : (c - c0 + 1); + if (cid == tokId) + { + hasTok = true; + } + Ref keyObj(newLong(cid)); + Ref rkObj(newLong(candRank)); + Ref lpObj(makeLogprob(d.lpTopkLogprobs[c], rkObj.get())); + if (PyDict_SetItem(dict.get(), keyObj.get(), lpObj.get()) < 0) + { + throwPythonError(); + } + } + if (!hasTok) + { + Ref keyObj(newLong(tokId)); + Ref rkObj(rk != 0 ? newLong(rk) : Py_NewRef(Py_None)); + Ref lpObj(makeLogprob(sampledLp, rkObj.get())); + if (PyDict_SetItem(dict.get(), keyObj.get(), lpObj.get()) < 0) + { + throwPythonError(); + } + } + PyList_SET_ITEM(perTok.get(), static_cast(t - t0), dict.release()); + } + else + { + PyList_SET_ITEM( + perTok.get(), static_cast(t - t0), newFloat(static_cast(sampledLp))); + } + } + return perTok.release(); + }; + + size_t const n = d.nRows; + Ref outList(PyList_New(0)); + outList.checked(); + + // Map handle -> first response result seen for this handle, plus its beam metadata, + // so multi-beam coalescing mirrors proxy_decode_raw_frame and bails to Python on any + // mismatched optional column presence or duplicate-sequence multi-iteration rows. + struct HandleAnchor + { + PyObject* resPtr{nullptr}; + uint32_t seq{0}; + bool isBeam{false}; + bool hasClp{false}; + bool hasLp{false}; + }; + + std::unordered_map handleAnchors; + + auto const asLong = [](int32_t v) { return newLong(v); }; + + for (size_t i = 0; i < n; ++i) + { + uint64_t const handle = d.handle[i]; + Ref cidObj(newULong(handle)); + Ref spObj = lookupSamplingParams(cidObj.get()); + bool const beam = isBeamRow(spObj, d.replaceFrom[i]); + bool simpleLp = false; + if (spObj.get() != nullptr && spObj.get() != Py_None) + { + Ref sFmt = getAttrOpt(spObj.get(), sn.logprobsSimpleFormat); + if (sFmt.get() != nullptr) + { + simpleLp = pyTruthy(sFmt.get()); + } + } + + uint32_t const t0 = d.tokenOffsets[i]; + uint32_t const t1 = d.tokenOffsets[i + 1]; + Ref rowToks(newList(d.tokens.data() + t0, t1 - t0, asLong)); + PyObject* frObj = finishReasons[d.finish[i]].ptr(); + bool const reqDone = (d.rowFlags[i] & kRowFlagRequestDone) != 0; + bool const hasClp = d.hasCumLogprob && !std::isnan(d.cumLogprob[i]); + Ref rowLp(buildRowLogprobs(i, simpleLp)); + bool const hasLp = rowLp.get() != nullptr; + + auto const anchorIt = handleAnchors.find(handle); + if (anchorIt != handleAnchors.end()) + { + HandleAnchor& anchor = anchorIt->second; + if (anchor.seq != d.seq[i] && (beam || anchor.isBeam)) + { + // If optional per-beam columns disagree across beams, fall back to Python + // rather than misaligning beam indices in cum_log_probs / log_probs. + if (anchor.hasClp != hasClp || anchor.hasLp != hasLp) + { + return nb::none(); + } + PyObject* prevRes = anchor.resPtr; + Ref prevToks = getAttr(prevRes, sn.outputTokenIds); + if (PyList_Append(prevToks.get(), rowToks.get()) < 0) + { + throwPythonError(); + } + Ref prevFrs = getAttr(prevRes, sn.finishReasons); + if (PyList_Append(prevFrs.get(), frObj) < 0) + { + throwPythonError(); + } + if (hasClp) + { + Ref prevClps = getAttr(prevRes, sn.cumLogProbs); + Ref clpVal(newFloat(d.cumLogprob[i])); + if (PyList_Append(prevClps.get(), clpVal.get()) < 0) + { + throwPythonError(); + } + } + if (hasLp) + { + Ref prevLps = getAttr(prevRes, sn.logProbs); + if (PyList_Append(prevLps.get(), rowLp.get()) < 0) + { + throwPythonError(); + } + } + if (reqDone) + { + setAttr(prevRes, sn.isRequestDone, Py_True); + setAttr(prevRes, sn.isFinal, Py_True); + } + anchor.isBeam = true; + continue; + } + if (anchor.seq == d.seq[i] && (beam || anchor.isBeam)) + { + // Multiple rows for the same beam sequence in one frame (e.g. merged iterations); + // bail to Python so ordering matches the reference decoder. + return nb::none(); + } + } + + // Allocate lightweight ZmqStepResult + ZmqStepResponse directly via tp_new. + Ref resObj(resT->tp_new(resT, emptyArgs.get(), nullptr)); + resObj.checked(); + PyObject* const resPtr = resObj.get(); + PyObject* const doneBool = reqDone ? Py_True : Py_False; + setAttr(resPtr, sn.isFinal, doneBool); + setAttr(resPtr, sn.isRequestDone, doneBool); + Ref seqObj(newLong(d.seq[i])); + setAttr(resPtr, sn.sequenceIndex, seqObj.get()); + + Ref tokOuter(PyList_New(1)); + tokOuter.checked(); + PyList_SET_ITEM(tokOuter.get(), 0, rowToks.release()); + setAttr(resPtr, sn.outputTokenIds, tokOuter.get()); + + if (hasClp) + { + Ref clpOuter(PyList_New(1)); + clpOuter.checked(); + PyList_SET_ITEM(clpOuter.get(), 0, newFloat(d.cumLogprob[i])); + setAttr(resPtr, sn.cumLogProbs, clpOuter.get()); + } + else + { + setAttr(resPtr, sn.cumLogProbs, Py_None); + } + + if (rowLp.get() != nullptr) + { + Ref lpOuter(PyList_New(1)); + lpOuter.checked(); + PyList_SET_ITEM(lpOuter.get(), 0, rowLp.release()); + setAttr(resPtr, sn.logProbs, lpOuter.get()); + } + else + { + setAttr(resPtr, sn.logProbs, Py_None); + } + + Ref frOuter(PyList_New(1)); + frOuter.checked(); + PyList_SET_ITEM(frOuter.get(), 0, Py_NewRef(frObj)); + setAttr(resPtr, sn.finishReasons, frOuter.get()); + + Ref stopIdxObj(newLong(d.stopIndex[i])); + setAttr(resPtr, sn.stopIndex, stopIdxObj.get()); + Ref replFromObj(newULong(d.replaceFrom[i])); + setAttr(resPtr, sn.replaceFrom, replFromObj.get()); + Ref rFlagsObj(newLong(d.rowFlags[i])); + setAttr(resPtr, sn.rowFlags, rFlagsObj.get()); + Ref cachedObj(newULong(d.cachedTokens[i])); + setAttr(resPtr, sn.cachedTokens, cachedObj.get()); + Ref decIterObj(newULong(d.decodingIter[i])); + setAttr(resPtr, sn.decodingIter, decIterObj.get()); + + Ref rspObj(rspT->tp_new(rspT, emptyArgs.get(), nullptr)); + rspObj.checked(); + PyObject* const rspPtr = rspObj.get(); + setAttr(rspPtr, sn.clientId, cidObj.get()); + setAttr(rspPtr, sn.requestId, cidObj.get()); + setAttr(rspPtr, sn.result, resPtr); + setAttr(rspPtr, sn.errorMsg, Py_None); + setAttr(rspPtr, sn.errorInfo, Py_None); + setAttr(rspPtr, sn.frameSeq, frameSeqObj.get()); + + if (anchorIt == handleAnchors.end()) + { + handleAnchors.emplace(handle, HandleAnchor{resPtr, d.seq[i], beam, hasClp, hasLp}); + } + if (PyList_Append(outList.get(), rspPtr) < 0) + { + throwPythonError(); + } + } + + PyObject* ret = PyTuple_Pack(2, frameSeqObj.get(), outList.get()); + if (ret == nullptr) + { + throwPythonError(); + } + return nb::steal(ret); +} + +} // namespace + +void initBindings(nb::module_& m) +{ + m.attr("PROTOBUF_VERSION") = PROTOBUF_VERSION; + + m.def("encode_frame", &encodeFrame, nb::arg("rows"), nb::kw_only(), nb::arg("frame_seq"), nb::arg("iter_first") = 0, + nb::arg("iter_last") = 0, nb::arg("emit_time_ns") = 0, nb::arg("acks") = nb::none(), + nb::arg("iteration_stats") = nb::none(), nb::arg("lora_set_changed") = nb::none(), + nb::arg("server_message") = false, + "Encode FrameRow-like objects into serialized Frame bytes, or ServerMessage{frame} bytes " + "when server_message is true. Byte-identical to wire_codec.encode_frame(...).SerializeToString(). " + "RowExtra, SubmitAck, IterationStats and LoraSetChanged may be given as messages or serialized bytes."); + m.def("decode_frame", &decodeFrame, nb::arg("data"), nb::arg("row_type") = nb::none(), + "Decode serialized Frame bytes into (header, rows) with the validation of wire_codec.decode_frame. " + "Raises ValueError on malformed bytes or inconsistent columns."); + m.def("parse_server_message", &parseServerMessage, nb::arg("data"), nb::arg("row_type") = nb::none(), + "Parse ServerMessage bytes into (kind, payload); a frame payload is decoded as by decode_frame."); + m.def("parse_client_message", &parseClientMessage, nb::arg("data"), + "Parse and validate ClientMessage bytes; see the module documentation for the returned tuples."); + m.def("encode_submit_batch", &encodeSubmitBatch, nb::arg("requests"), nb::kw_only(), + nb::arg("consumed_frame_seq") = 0, "Serialize ClientMessage{submit_batch} from Request messages or bytes."); + m.def("encode_cancel_batch", &encodeCancelBatch, nb::arg("cancels"), nb::kw_only(), nb::arg("all") = false, + nb::arg("all_reason") = 0, nb::arg("consumed_frame_seq") = 0, + "Serialize ClientMessage{cancel_batch} from (handle, reason) pairs."); + m.def("encode_step_fast", &encodeStepFast, nb::arg("responses"), nb::kw_only(), nb::arg("frame_seq"), + nb::arg("iter_first") = 0, nb::arg("iter_last") = 0, nb::arg("emit_time_ns") = 0, + nb::arg("server_message") = true, + "Fast-path native encoder for plain step responses into ServerMessage{frame} bytes; returns None when " + "any response requires RowExtra or full Python encoding."); + m.def("decode_step_server_message_fast", &decodeStepServerMessageFast, nb::arg("data"), + nb::arg("results_map") = nb::none(), nb::kw_only(), nb::arg("response_type"), nb::arg("result_type"), + nb::arg("finish_reasons"), nb::arg("logprob_type"), + "Fast-path native decoder for ServerMessage{frame} bytes without RowExtra; returns (frame_seq, responses) " + "or None when full Python decoding is required."); +} + +} // namespace tensorrt_llm::nanobind::engine_wire + +#if defined(TRTLLM_ENGINE_WIRE_STANDALONE_MODULE) +// A module of its own, for building and testing the codec without the bindings +// module: import engine_wire_standalone. +NB_MODULE(engine_wire_standalone, m) +{ + tensorrt_llm::nanobind::engine_wire::initBindings(m); +} +#endif diff --git a/tensorrt_llm/executor/native/engineWire.h b/tensorrt_llm/executor/native/engineWire.h new file mode 100644 index 000000000000..068d818a9b55 --- /dev/null +++ b/tensorrt_llm/executor/native/engineWire.h @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace tensorrt_llm::nanobind::engine_wire +{ + +//! Registers the native codec of the trtllm.engine.v1 wire on \p m: +//! columnar output Frame encode/decode and the ClientMessage / ServerMessage +//! envelopes used over the ZeroMQ IPC. Exposed to Python as +//! tensorrt_llm.bindings.internal.engine_wire. +void initBindings(::nanobind::module_& m); + +} // namespace tensorrt_llm::nanobind::engine_wire diff --git a/tensorrt_llm/executor/result.py b/tensorrt_llm/executor/result.py index 2a4089dbfe30..4ac5fcf93932 100644 --- a/tensorrt_llm/executor/result.py +++ b/tensorrt_llm/executor/result.py @@ -664,11 +664,15 @@ def _handle_response(self, context_phase_params = response_result.context_phase_params self.decoding_iter = response_result.decoding_iter self.cached_tokens = getattr(response_result, 'cached_tokens', 0) - self.ctx_computed_tokens = getattr(response_result, - 'ctx_computed_tokens', 0) - self.ctx_first_begin = getattr(response_result, 'ctx_first_begin', - -1) - self.ctx_num_chunks = getattr(response_result, 'ctx_num_chunks', 0) + ctx_computed_tokens = getattr(response_result, + 'ctx_computed_tokens', 0) + ctx_first_begin = getattr(response_result, 'ctx_first_begin', -1) + ctx_num_chunks = getattr(response_result, 'ctx_num_chunks', 0) + if (ctx_num_chunks > 0 or ctx_computed_tokens > 0 + or ctx_first_begin >= 0): + self.ctx_computed_tokens = ctx_computed_tokens + self.ctx_first_begin = ctx_first_begin + self.ctx_num_chunks = ctx_num_chunks self.per_pos_drafted = getattr(response_result, 'per_pos_drafted', None) self.per_pos_accepted = getattr(response_result, 'per_pos_accepted', diff --git a/tensorrt_llm/executor/worker.py b/tensorrt_llm/executor/worker.py index a2d162ab208e..c89e86fe095a 100644 --- a/tensorrt_llm/executor/worker.py +++ b/tensorrt_llm/executor/worker.py @@ -20,6 +20,7 @@ import threading import time import traceback +from collections.abc import Iterator from concurrent.futures import ProcessPoolExecutor from pathlib import Path from typing import List, Optional @@ -39,7 +40,7 @@ from ..llmapi.tracer import VizTracer, set_global_tracer from ..llmapi.utils import ManagedThread, logger_debug, print_traceback_on_error from .base_worker import BaseWorker, _init_hf_modules, pack_final_responses -from .ipc import FusedIpcQueue, IpcQueue +from .ipc import FusedIpcQueue, IpcQueue, RawServeEngineFrame from .postproc_worker import PostprocWorker, postproc_worker_main from .request import (CancellingRequest, GenerationRequest, StartProfileRequest, StopProfileRequest) @@ -48,6 +49,7 @@ RequestError, WorkerCommIpcAddrs, _check_collective_rpc_guard) from .worker_process_monitor import capture_worker_process_identity +from .zmq_wire.transport import get_zmq_wire_mode __all__ = [ "GenerationExecutorWorker", @@ -368,15 +370,40 @@ def block_subordinates(self): self.engine.wait_shutdown() -def _incoming_requests(request_queue: IpcQueue): +def _incoming_requests( + request_queue: IpcQueue, + worker: BaseWorker | None = None, + serve_engine_wire_mode: str = "off", +) -> Iterator[object]: """Yield the proxy's requests until its shutdown sentinel arrives. With TRTLLM_PROXY_BATCH_REQUESTS=1 the proxy sends a burst of requests as one list of pickled requests. ``request_queue.get()`` has already authenticated that message, and with it every payload inside. + + With TLLM_SERVE_ENGINE_ZMQ=auto|strict the proxy may also send + serve_engine.v1 frames, which ``request_queue.get()`` returns as + RawServeEngineFrame after checking their HMAC; in strict mode it sends + nothing else. A request in such a frame that cannot be rebuilt is yielded + as the ErrorResponse that fails only that request. """ + strict = serve_engine_wire_mode == "strict" while (msg := request_queue.get()) is not None: - if isinstance(msg, list): + if isinstance(msg, RawServeEngineFrame): + from .zmq_wire.worker_bridge import worker_decode_raw_frame + for item in worker_decode_raw_frame(msg.data, + request_queue.hmac_key, + worker=worker, + strict=strict): + if item is None: + return + yield item + elif strict: + from .zmq_wire.transport import StrictProtoWireError + raise StrictProtoWireError( + "Strict serve_engine ZMQ mode rejected a pickled request " + f"message ({type(msg).__name__})") + elif isinstance(msg, list): for payload in msg: yield pickle.loads(payload) # nosec B301 else: @@ -470,15 +497,23 @@ def _print_stacks(): set_mpi_session_cpp(mpi_comm()) + serve_engine_wire_mode = get_zmq_wire_mode() + if is_leader and serve_engine_wire_mode != "off": + from .zmq_wire.worker_bridge import reset_worker_wire_state + reset_worker_wire_state() + if is_leader: # Only set the log level for the leader process, the other processes will # inherit the log level from "TLLM_LOG_LEVEL" environment variable logger.set_level(log_level) - request_queue = IpcQueue(worker_queues.request_queue_addr, - is_server=multi_frontend_addrs is not None, - socket_type=zmq.PULL if multi_frontend_addrs - is not None else zmq.PAIR, - name="worker_request_queue") + request_queue = IpcQueue( + worker_queues.request_queue_addr, + is_server=multi_frontend_addrs is not None, + socket_type=zmq.PULL + if multi_frontend_addrs is not None else zmq.PAIR, + name="worker_request_queue", + serve_engine_wire_enabled=serve_engine_wire_mode != "off", + serve_engine_wire_strict=serve_engine_wire_mode == "strict") worker_init_status_queue = IpcQueue( worker_queues.worker_init_status_queue_addr, is_server=False, @@ -536,6 +571,26 @@ def send_profile_ack(kind: str, err, req) -> None: def notify_proxy_threads_to_quit(): # Signal the dispatcher thread in every frontend proxy to quit + if serve_engine_wire_mode != "off" and ( + result_queue is not None or frontend_result_queues is not None): + from .zmq_wire.worker_bridge import (dump_wire_stats_if_configured, + reset_worker_wire_state, + send_shutdown_sentinel) + try: + if result_queue is not None: + send_shutdown_sentinel( + result_queue, + strict=(serve_engine_wire_mode == "strict")) + else: + for frontend_id, q in enumerate(frontend_result_queues): + send_shutdown_sentinel( + q, + sub_tag=frontend_id, + strict=(serve_engine_wire_mode == "strict")) + finally: + dump_wire_stats_if_configured() + reset_worker_wire_state() + return if result_queue is not None: result_queue.put(None) elif frontend_result_queues is not None: @@ -636,9 +691,10 @@ def notify_proxy_threads_to_quit(): return # The leader sends responses straight to the proxy unless it post-processes - # them or routes them to frontends, so the other ranks can pack the final - # responses of their prefill-only requests. - if not postproc_worker_config.enabled and multi_frontend_addrs is None: + # them, routes them to frontends, or encodes them as serve_engine.v1 frames, + # so the other ranks can pack the final responses of their prefill-only requests. + if (not postproc_worker_config.enabled and multi_frontend_addrs is None + and serve_engine_wire_mode == "off"): worker.engine.peer_response_packer = pack_final_responses # Optionally disable GC (default: not disabled) @@ -662,6 +718,9 @@ def notify_proxy_threads_to_quit(): else: worker.set_result_queue(result_queue) worker.proxy_holds_results = True + # Only these ZeroMQ IPC result queues carry serve_engine.v1 frames. + worker._await_response_helper.serve_engine_wire_mode = ( + serve_engine_wire_mode) # Send ready signal with confirmation ready_msg = (ready_signal, None, worker_process_identities) @@ -680,7 +739,10 @@ def notify_proxy_threads_to_quit(): # Parse each received request while the executor waits on the GPU. request_queue.parse_gate = worker.engine.wait_for_intake_window - for req in _incoming_requests(request_queue): + for req in _incoming_requests( + request_queue, + worker=worker, + serve_engine_wire_mode=serve_engine_wire_mode): if isinstance(req, CancellingRequest): worker.abort_request(req.id) elif isinstance(req, StartProfileRequest): @@ -714,6 +776,13 @@ def notify_proxy_threads_to_quit(): logger.warning(f"stop_profile rejected: {e}") ack_err = str(e) send_profile_ack("stop", ack_err, req) + elif isinstance(req, ErrorResponse): + # A serve_engine.v1 request that could not be rebuilt: + # only that client gets the error. Ensure the response + # thread is running even if this is the very first request. + worker.start() + worker._await_response_helper.temp_error_responses.put( + req) elif isinstance(req, GenerationRequest): try: worker.submit(req) diff --git a/tensorrt_llm/executor/zmq_wire/__init__.py b/tensorrt_llm/executor/zmq_wire/__init__.py new file mode 100644 index 000000000000..fa0a22388d72 --- /dev/null +++ b/tensorrt_llm/executor/zmq_wire/__init__.py @@ -0,0 +1,122 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""trtllm.engine.v1 (v1.1) over the executor's ZeroMQ queues, without pickle. + +Controlled by ``TLLM_SERVE_ENGINE_ZMQ=auto|strict|off`` (default ``auto``). Modules: + - transport: binary HMAC framing (magic 0x53), ZmqRawSocketWrapper, InMemoryZmqQueue, mode + - codec: Request / CancelBatch / columnar Frame codec and ZmqStepResponse + - disagg_codec: disaggregated-serving phase, DisaggParams and KvHandoff codec + - worker_bridge: the rank-0 worker's side of the executor integration + +The names below load their module on first access, so importing ``transport`` alone (as the +executor does to read the mode) does not import protobuf. +""" + +import importlib + +_EXPORTS = { + "BlobRecord": "codec", + "DecodedCancelBatch": "codec", + "DecodedRequest": "codec", + "DisaggNotSupportedError": "disagg_codec", + "ZmqContextPhaseParams": "disagg_codec", + "LocalBlobStore": "codec", + "RawTensor": "codec", + "ZmqFinishReason": "codec", + "ZmqLogprob": "codec", + "ZmqStepResponse": "codec", + "ZmqStepResult": "codec", + "decode_cancel_batch": "codec", + "decode_inline_tensor": "codec", + "decode_prompt_logprobs": "codec", + "decode_request_proto": "codec", + "decode_step_frame": "codec", + "decode_step_server_message_bytes": "codec", + "decode_submit_batch": "codec", + "decode_tensor_ref": "codec", + "encode_cancel_batch": "codec", + "encode_generation_requests": "codec", + "encode_inline_tensor": "codec", + "encode_prompt_logprobs": "codec", + "encode_step_responses": "codec", + "encode_step_responses_bytes": "codec", + "encode_tensor_ref": "codec", + "unsupported_request_reason": "disagg_codec", + "unsupported_result_reason": "disagg_codec", + "materialize_embedding_bias": "codec", + "ChannelTag": "transport", + "FRAME_MAGIC": "transport", + "FrameAuthError": "transport", + "FrameFormatError": "transport", + "HEADER_SIZE": "transport", + "HMAC_SIZE": "transport", + "InMemoryZmqQueue": "transport", + "MIN_FRAME_SIZE": "transport", + "ServeEngineZmqError": "transport", + "StrictProtoWireError": "transport", + "UnsupportedCallableError": "transport", + "WireStats": "transport", + "ZmqRawSocketWrapper": "transport", + "get_zmq_wire_mode": "transport", + "is_raw_proto_frame": "transport", + "pack_raw_frame": "transport", + "unpack_raw_frame": "transport", +} + +__all__ = [ + "BlobRecord", + "ChannelTag", + "DecodedCancelBatch", + "DecodedRequest", + "DisaggNotSupportedError", + "FRAME_MAGIC", + "FrameAuthError", + "FrameFormatError", + "HEADER_SIZE", + "HMAC_SIZE", + "InMemoryZmqQueue", + "LocalBlobStore", + "MIN_FRAME_SIZE", + "RawTensor", + "ServeEngineZmqError", + "StrictProtoWireError", + "UnsupportedCallableError", + "WireStats", + "ZmqFinishReason", + "ZmqLogprob", + "ZmqRawSocketWrapper", + "ZmqStepResponse", + "ZmqContextPhaseParams", + "ZmqStepResult", + "decode_cancel_batch", + "decode_inline_tensor", + "decode_prompt_logprobs", + "decode_request_proto", + "decode_step_frame", + "decode_step_server_message_bytes", + "decode_submit_batch", + "decode_tensor_ref", + "encode_cancel_batch", + "encode_generation_requests", + "encode_inline_tensor", + "encode_prompt_logprobs", + "encode_step_responses", + "encode_step_responses_bytes", + "encode_tensor_ref", + "get_zmq_wire_mode", + "is_raw_proto_frame", + "materialize_embedding_bias", + "pack_raw_frame", + "unpack_raw_frame", + "unsupported_request_reason", + "unsupported_result_reason", +] + + +def __getattr__(name: str) -> object: + module = _EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(importlib.import_module(f"{__name__}.{module}"), name) + globals()[name] = value + return value diff --git a/tensorrt_llm/executor/zmq_wire/codec.py b/tensorrt_llm/executor/zmq_wire/codec.py new file mode 100644 index 000000000000..893865b4a066 --- /dev/null +++ b/tensorrt_llm/executor/zmq_wire/codec.py @@ -0,0 +1,4033 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Full bidirectional trtllm.engine.v1 (v1.1) codec for the ZeroMQ executor transport. + +Covers the feature families of aggregated serving: + 1. prompt_tokens, encoder_input_tokens, multimodal (MEDIA + PREPROCESSED + CAP-20 extensions + + large tensors via INLINE / SHM / CUDA_IPC / BLOB_FETCH) + 2. SamplingParams (all 22 optional/repeated/enum fields, sparse logit_bias <-> dense bias) + 3. StopParams (7 fields: max_tokens, min_tokens, end_id, pad_id, ignore_eos, sequences, bad_sequences) + 4. OutputOptions (logprobs, logprob_rank, prompt_logprobs, tensors, metrics, return_expanded_prompt) + 5. n / best_of / beam search (num_sequences, beam_width, num_return_beams, beam_width_array, + length_penalty, early_stopping, beam_search_diversity_rate, replace_from) + 6. GuidedDecoding (all 6 kinds incl. choice), LoRA (LoraRef), named logits_processors + (strict mode raises UnsupportedCallableError on arbitrary Python callables; + thinking_token_budget is handled on the client layer without a wire field) + 7. SchedulingParams (6 fields) + queue_age_us + TraceContext + 8. KvParams (cache_salt, retention incl. TokenRangeRetention, hints incl. KvHintAction) + 9. Disaggregated serving: Request.phase / Request.disagg, RowExtra.handoff, + FINISH_REASON_CONTEXT_DONE and PromptInfo / FinalInfo.prefill_usage (see disagg_codec.py) + 10. CancelBatch (handles, reasons, all_flag, consumed_frame_seq) + 11. Columnar output Frame (12 hot columns + 5 logprobs columns + PromptInfo + FinalInfo + + ErrorInfo + SignedHandoff + append-only streaming OutputTensor segments) + 12. GenerationResult._handle_response duck-typed response interface (ZmqStepResponse) + +This module avoids top-level imports of torch/numpy/bindings so it runs cleanly in pure-Python +CPU test environments as well as full GPU runtime environments. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import enum +import hashlib +import json +import logging +import math +import secrets +import struct +import sys +import threading +import time +from typing import Iterator, Mapping, Optional, Sequence + +from google.protobuf.message import Message as ProtoMessage + +from tensorrt_llm.contracts.engine.v1 import _native +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc + +from .transport import StrictProtoWireError, UnsupportedCallableError + +logger = logging.getLogger(__name__) + +_IS_LITTLE_ENDIAN = sys.byteorder == "little" + +# ============================================================================ +# Pure-Python Tensor Wrapper + BlobStore (works with or without torch/numpy) +# ============================================================================ + + +@dataclasses.dataclass +class RawTensor: + """Lightweight tensor container used when neither torch nor numpy is installed.""" + + dtype: int # common_pb2.DType enum int + shape: tuple[int, ...] + data: bytes + device: Optional[int] = None + + @property + def dtype_name(self) -> str: + return wc.DTYPE_INFO[self.dtype][1] + + @property + def nbytes(self) -> int: + return len(self.data) + + def to_list(self) -> list[int | float | bool]: + """Decode flat little-endian numeric values (for assertions/debugging).""" + fmt_map = { + pb.common_pb2.DTYPE_F32: "f", + pb.common_pb2.DTYPE_F64: "d", + pb.common_pb2.DTYPE_I64: "q", + pb.common_pb2.DTYPE_I32: "i", + pb.common_pb2.DTYPE_I16: "h", + pb.common_pb2.DTYPE_I8: "b", + pb.common_pb2.DTYPE_U8: "B", + pb.common_pb2.DTYPE_BOOL: "?", + } + ch = fmt_map.get(self.dtype) + if ch is None: + return list(self.data) + itemsize = struct.calcsize(f"<{ch}") + count = len(self.data) // itemsize + if count == 0: + return [] + return list(struct.unpack(f"<{count}{ch}", self.data)) + + def tolist(self) -> list[int | float | bool]: + """Alias matching torch.Tensor.tolist() / numpy.ndarray.tolist().""" + return self.to_list() + + def reshape(self, *shape: int) -> "RawTensor": + """Minimal reshape returning self (flat tolist() already returns 1D list).""" + return self + + def __len__(self) -> int: + return self.shape[0] if self.shape else 0 + + +def materialize_embedding_bias( + logit_bias: Sequence[tuple[int, float]], + vocab_size: int, + *, + prefer_torch: bool = True, +) -> object: + """Materialize sparse [(token_id, bias), ...] into a dense float32 [vocab_size] tensor.""" + if vocab_size < 0: + raise ValueError(f"vocab_size must be non-negative, got {vocab_size}") + vals = [0.0] * vocab_size + for tid, bias in logit_bias: + idx = int(tid) + if not (0 <= idx < vocab_size): + raise IndexError(f"logit_bias token_id {idx} out of range [0, {vocab_size})") + vals[idx] = float(bias) + raw = struct.pack(f"<{vocab_size}f", *vals) if vocab_size else b"" + return _raw_to_tensor(pb.common_pb2.DTYPE_F32, (vocab_size,), raw, prefer_torch=prefer_torch) + + +@dataclasses.dataclass +class BlobRecord: + """Stored blob entry owned by a session (or anonymous when session_id == 0).""" + + blob_id: int + session_id: int + data: bytearray + digest: bytes + handle: Optional[int] = None + created_at_s: float = dataclasses.field(default_factory=time.monotonic) + + +class LocalBlobStore: + """In-memory BlobStore + SHM/CUDA_IPC tracker used by the codec.""" + + def __init__( + self, + *, + session_quota_bytes: int = 1 << 30, + host_quota_bytes: int = 4 << 30, + ) -> None: + self._lock = threading.Lock() + self._blobs: dict[int, BlobRecord] = {} + self._by_session_handle: dict[tuple[int, int], set[int]] = {} + self._session_bytes: dict[int, int] = {} + self._total_bytes = 0 + self._session_quota_bytes = session_quota_bytes + self._host_quota_bytes = host_quota_bytes + self._shm_by_handle: dict[tuple[int, int], list[ProtoMessage]] = {} + self._cuda_keepalive_by_handle: dict[tuple[int, int], list[object]] = {} + self._cuda_keepalive_ring: list[object] = [] + self._cuda_keepalive_max_ring = 256 + + def _alloc_blob_id_locked(self) -> int: + while True: + bid = secrets.randbits(63) | 1 + if bid not in self._blobs: + return bid + + def track_cuda_ipc( + self, + session_id: int, + keepalive_tensor: object, + *, + handle: Optional[int] = None, + ) -> None: + """Pin a CUDA tensor for CUDA IPC until the handle/session is released.""" + with self._lock: + if handle is not None: + self._cuda_keepalive_by_handle.setdefault( + (int(session_id), int(handle)), [] + ).append(keepalive_tensor) + else: + self._cuda_keepalive_ring.append(keepalive_tensor) + if len(self._cuda_keepalive_ring) > self._cuda_keepalive_max_ring: + del self._cuda_keepalive_ring[ + : len(self._cuda_keepalive_ring) - self._cuda_keepalive_max_ring + ] + + def put_blob( + self, + data: bytes | bytearray | memoryview, + *, + session_id: int = 0, + handle: Optional[int] = None, + expected_digest: bytes = b"", + ) -> ProtoMessage: + raw = bytes(data) + digest = hashlib.sha256(raw).digest() + if expected_digest and expected_digest != digest: + raise ValueError("Blob SHA-256 digest mismatch on upload") + size = len(raw) + with self._lock: + if self._total_bytes + size > self._host_quota_bytes: + raise MemoryError("Host blob quota exceeded") + if session_id != 0: + cur_sess = self._session_bytes.get(session_id, 0) + if cur_sess + size > self._session_quota_bytes: + raise MemoryError(f"Session {session_id} blob quota exceeded") + self._session_bytes[session_id] = cur_sess + size + blob_id = self._alloc_blob_id_locked() + self._blobs[blob_id] = BlobRecord( + blob_id=blob_id, + session_id=session_id, + data=bytearray(raw), + digest=digest, + handle=handle, + ) + self._total_bytes += size + if handle is not None: + self._by_session_handle.setdefault((session_id, handle), set()).add(blob_id) + return pb.common_pb2.BlobLocation(blob_id=blob_id, size=size, digest=digest) + + def append_blob( + self, + blob_id: int, + chunk: bytes, + *, + session_id: int = 0, + ) -> ProtoMessage: + """Append bytes to an existing append-only streaming blob segment.""" + size = len(chunk) + with self._lock: + rec = self._blobs.get(blob_id) + if rec is None: + raise KeyError(f"Unknown blob_id={blob_id}") + if rec.session_id != session_id: + raise PermissionError( + f"Session {session_id} cannot append to blob {blob_id} owned by {rec.session_id}" + ) + if self._total_bytes + size > self._host_quota_bytes: + raise MemoryError("Host blob quota exceeded") + if rec.session_id != 0: + cur_sess = self._session_bytes.get(rec.session_id, 0) + if cur_sess + size > self._session_quota_bytes: + raise MemoryError(f"Session {rec.session_id} blob quota exceeded") + self._session_bytes[rec.session_id] = cur_sess + size + rec.data.extend(chunk) + rec.digest = hashlib.sha256(rec.data).digest() + self._total_bytes += size + return pb.common_pb2.BlobLocation( + blob_id=blob_id, size=len(rec.data), digest=rec.digest + ) + + def get_blob( + self, + blob_id: int, + *, + session_id: int = 0, + offset: int = 0, + length: int = 0, + ) -> tuple[bytes, bytes]: + """Return (slice_bytes, full_blob_sha256).""" + offset = int(offset) + length = int(length) + if offset < 0 or length < 0: + raise ValueError( + f"Blob offset/length must be >= 0, got offset={offset}, length={length}" + ) + with self._lock: + rec = self._blobs.get(blob_id) + if rec is None: + raise KeyError(f"Blob not found: blob_id={blob_id}") + if rec.session_id != session_id: + raise PermissionError( + f"Session {session_id} cannot read blob {blob_id} owned by {rec.session_id}" + ) + total = len(rec.data) + if offset > total: + raise ValueError(f"Blob offset {offset} > size {total}") + end = total if length == 0 else min(total, offset + length) + return bytes(rec.data[offset:end]), rec.digest + + def track_shm(self, session_id: int, handle: int, loc: ProtoMessage) -> None: + with self._lock: + self._shm_by_handle.setdefault((session_id, handle), []).append(loc) + + def release( + self, + *, + session_id: int = 0, + blob_ids: Sequence[int] = (), + handles: Sequence[int] = (), + ) -> int: + released = 0 + shm_to_unlink: list[ProtoMessage] = [] + with self._lock: + ids_to_drop: set[int] = set(int(b) for b in blob_ids) + for h in handles: + key = (session_id, int(h)) + ids_to_drop.update(self._by_session_handle.pop(key, set())) + shm_to_unlink.extend(self._shm_by_handle.pop(key, ())) + self._cuda_keepalive_by_handle.pop(key, None) + for bid in ids_to_drop: + rec = self._blobs.get(bid) + if rec is None: + continue + if rec.session_id != session_id: + continue + self._blobs.pop(bid) + size = len(rec.data) + self._total_bytes = max(0, self._total_bytes - size) + if rec.session_id != 0: + self._session_bytes[rec.session_id] = max( + 0, self._session_bytes.get(rec.session_id, 0) - size + ) + if rec.handle is not None: + s = self._by_session_handle.get((rec.session_id, rec.handle)) + if s is not None: + s.discard(bid) + released += 1 + for loc in shm_to_unlink: + wc.unlink_shm(loc) + return released + + def release_session(self, session_id: int) -> int: + with self._lock: + ids = [bid for bid, rec in self._blobs.items() if rec.session_id == session_id] + handles = list( + {h for (sid, h) in self._shm_by_handle.keys() if sid == session_id} + | {h for (sid, h) in self._cuda_keepalive_by_handle.keys() if sid == session_id} + ) + return self.release(session_id=session_id, blob_ids=ids, handles=handles) + + @property + def total_bytes(self) -> int: + with self._lock: + return self._total_bytes + + @property + def blob_count(self) -> int: + with self._lock: + return len(self._blobs) + + +# ============================================================================ +# TensorRef / InlineTensor helpers (support RawTensor, torch.Tensor, np.ndarray) +# ============================================================================ + + +def _tensor_to_raw_view( + tensor: object, +) -> tuple[int, list[int], bytes | bytearray | memoryview, Optional[int]]: + if isinstance(tensor, RawTensor): + return tensor.dtype, list(tensor.shape), tensor.data, tensor.device + device = None + if hasattr(tensor, "is_cuda") and tensor.is_cuda: + device = int(tensor.device.index) + dt, shape, mv = wc.tensor_to_raw_view(tensor) + return dt, shape, mv, device + + +def _raw_to_tensor( + dtype: int, + shape: Sequence[int], + raw: bytes | bytearray | memoryview, + *, + device: Optional[int] = None, + prefer_torch: bool = True, +) -> object: + if prefer_torch: + try: + import torch # noqa: F401 + + t = wc.raw_bytes_to_tensor(dtype, shape, raw, prefer_torch=True) + if device is not None: + try: + t = t.to(f"cuda:{device}") + except (RuntimeError, ValueError, OSError): + pass + return t + except ImportError: + pass + try: + import numpy # noqa: F401 + + return wc.raw_bytes_to_tensor(dtype, shape, raw, prefer_torch=False) + except ImportError: + return RawTensor( + dtype=dtype, + shape=tuple(int(d) for d in shape), + data=raw if isinstance(raw, bytes) else bytes(raw), + device=device, + ) + + +def encode_tensor_ref( + tensor: object, + *, + delivery_pref: Sequence[int] = ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ), + max_inline_bytes: int = 256 * 1024, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + handle: Optional[int] = None, +) -> ProtoMessage: + """Encode a tensor (RawTensor / torch.Tensor / np.ndarray) into common_pb2.TensorRef.""" + if isinstance(tensor, pb.common_pb2.TensorRef): + return tensor + + # Try CUDA_IPC first if explicitly preferred, tensor is on CUDA, and we have a blob_store + # to pin the keepalive tensor (preventing immediate dangling IPC handles). + if ( + delivery_pref + and delivery_pref[0] == pb.common_pb2.TENSOR_DELIVERY_CUDA_IPC + and blob_store is not None + ): + ipc_res = wc.make_cuda_ipc_ref(tensor) + if ipc_res is not None: + ref_ipc, keepalive_t = ipc_res + blob_store.track_cuda_ipc(session_id, keepalive_t, handle=handle) + return ref_ipc + + dt, shape, raw_buf, device = _tensor_to_raw_view(tensor) + + # Select delivery in preference order + chosen = None + for pref in delivery_pref: + if pref == pb.common_pb2.TENSOR_DELIVERY_INLINE: + if len(raw_buf) <= max_inline_bytes: + chosen = pref + break + elif pref == pb.common_pb2.TENSOR_DELIVERY_SHM: + chosen = pref + break + elif pref == pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH and blob_store is not None: + chosen = pref + break + elif pref == pb.common_pb2.TENSOR_DELIVERY_CUDA_IPC and blob_store is not None: + ipc_res = wc.make_cuda_ipc_ref(tensor) + if ipc_res is not None: + ref_ipc, keepalive_t = ipc_res + blob_store.track_cuda_ipc(session_id, keepalive_t, handle=handle) + return ref_ipc + + if chosen is None: + if blob_store is not None: + chosen = pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH + else: + chosen = pb.common_pb2.TENSOR_DELIVERY_INLINE + + ref = pb.common_pb2.TensorRef(dtype=dt, shape=shape) + if device is not None: + ref.device = int(device) + + if chosen == pb.common_pb2.TENSOR_DELIVERY_INLINE: + ref.inline_bytes = raw_buf if isinstance(raw_buf, bytes) else bytes(raw_buf) + elif chosen == pb.common_pb2.TENSOR_DELIVERY_SHM: + loc = wc.write_shm_bytes(raw_buf) + ref.shm.CopyFrom(loc) + if blob_store is not None and handle is not None: + blob_store.track_shm(session_id, handle, loc) + else: + _record_untracked_shm(loc) + elif chosen == pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH: + assert blob_store is not None + loc = blob_store.put_blob(raw_buf, session_id=session_id, handle=handle) + ref.blob.CopyFrom(loc) + return ref + + +# SHM segments written by request/response encoders on this thread that no blob store tracks; +# only the reader unlinks them, so a frame that is never sent must unlink them itself. +_UNTRACKED_SHM = threading.local() + + +def _record_untracked_shm(loc: ProtoMessage) -> None: + written = getattr(_UNTRACKED_SHM, "locations", None) + if written is not None: + written.append(loc) + + +@contextlib.contextmanager +def capture_untracked_shm() -> Iterator[list[ProtoMessage]]: + """Collect SHM locations written on this thread so callers can unlink them on send failure.""" + captured: list[ProtoMessage] = [] + outer = getattr(_UNTRACKED_SHM, "locations", None) + _UNTRACKED_SHM.locations = captured + try: + yield captured + finally: + _UNTRACKED_SHM.locations = outer + if outer is not None: + outer.extend(captured) + + +def unlink_untracked_shm(locations: Sequence[ProtoMessage]) -> None: + """Unlink SHM segments of an encoded frame that will not reach its reader.""" + for loc in locations: + try: + wc.unlink_shm(loc) + except OSError as exc: + logger.warning("Failed to unlink serve_engine SHM segment %s: %s", loc.name, exc) + + +def shm_locations_in(message: ProtoMessage) -> list[ProtoMessage]: + """Return every common_pb2.ShmLocation inside a protobuf message.""" + found: list[ProtoMessage] = [] + stack: list[ProtoMessage] = [message] + while stack: + msg = stack.pop() + if isinstance(msg, pb.common_pb2.ShmLocation): + found.append(msg) + continue + for field, value in msg.ListFields(): + if field.message_type is None: + continue + if field.label == field.LABEL_REPEATED: + if field.message_type.GetOptions().map_entry: + stack.extend(v for v in value.values() if hasattr(v, "ListFields")) + else: + stack.extend(value) + else: + stack.append(value) + return found + + +def decode_tensor_ref( + ref: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, +) -> object: + """Decode common_pb2.TensorRef into a torch.Tensor / np.ndarray / RawTensor.""" + loc_kind = ref.WhichOneof("location") + device = ref.device if ref.HasField("device") else None + if loc_kind == "inline_bytes": + return _raw_to_tensor( + ref.dtype, + list(ref.shape), + ref.inline_bytes, + device=device, + prefer_torch=prefer_torch, + ) + if loc_kind == "shm": + raw = wc.read_shm_bytearray(ref.shm, unlink=unlink_shm) + return _raw_to_tensor( + ref.dtype, list(ref.shape), raw, device=device, prefer_torch=prefer_torch + ) + if loc_kind == "cuda_ipc": + return wc.open_cuda_ipc_ref(ref) + if loc_kind == "blob": + if blob_store is None: + raise ValueError( + f"Cannot decode TensorRef.blob (blob_id={ref.blob.blob_id}) without blob_store" + ) + raw, digest = blob_store.get_blob(ref.blob.blob_id, session_id=session_id) + if ref.blob.digest and bytes(ref.blob.digest) != digest: + raise ValueError(f"Blob {ref.blob.blob_id} SHA-256 verification failed") + return _raw_to_tensor( + ref.dtype, list(ref.shape), raw, device=device, prefer_torch=prefer_torch + ) + raise ValueError(f"TensorRef missing location oneof (got {loc_kind!r})") + + +def encode_inline_tensor(tensor: object) -> ProtoMessage: + if isinstance(tensor, pb.common_pb2.InlineTensor): + return tensor + dt, shape, raw_buf, _dev = _tensor_to_raw_view(tensor) + raw = raw_buf if isinstance(raw_buf, bytes) else bytes(raw_buf) + return pb.common_pb2.InlineTensor(dtype=dt, shape=shape, data=raw) + + +def decode_inline_tensor(msg: ProtoMessage, *, prefer_torch: bool = True) -> object: + return _raw_to_tensor(msg.dtype, list(msg.shape), msg.data, prefer_torch=prefer_torch) + + +# ============================================================================ +# FinishReason compatibility enum (mirrors bindings.executor.FinishReason 0..5 + protocol 6..7) +# ============================================================================ + + +class ZmqFinishReason(enum.IntEnum): + """Numeric FinishReason matching both common.proto FinishReason and bindings.executor.FinishReason.""" + + NOT_FINISHED = 0 + END_ID = 1 + STOP_WORDS = 2 + LENGTH = 3 + TIMED_OUT = 4 + CANCELLED = 5 + ERROR = 6 + CONTEXT_DONE = 7 + + +_FINISH_REASON_CACHE: dict[int, object] | None = None +_FINISH_REASON_TUPLE_CACHE: tuple[object, ...] | None = None + + +def _get_finish_reason_map() -> dict[int, object]: + global _FINISH_REASON_CACHE, _FINISH_REASON_TUPLE_CACHE + if _FINISH_REASON_CACHE is None: + try: + from tensorrt_llm.bindings import executor as tllm + + _FINISH_REASON_CACHE = { + 0: tllm.FinishReason.NOT_FINISHED, + 1: tllm.FinishReason.END_ID, + 2: tllm.FinishReason.STOP_WORDS, + 3: tllm.FinishReason.LENGTH, + 4: tllm.FinishReason.TIMED_OUT, + 5: tllm.FinishReason.CANCELLED, + # Protocol CONTEXT_DONE (7) maps to NOT_FINISHED on GenerationResult._handle_sequence + 7: tllm.FinishReason.NOT_FINISHED, + } + except (ImportError, AttributeError): + _FINISH_REASON_CACHE = { + 0: ZmqFinishReason.NOT_FINISHED, + 1: ZmqFinishReason.END_ID, + 2: ZmqFinishReason.STOP_WORDS, + 3: ZmqFinishReason.LENGTH, + 4: ZmqFinishReason.TIMED_OUT, + 5: ZmqFinishReason.CANCELLED, + 7: ZmqFinishReason.NOT_FINISHED, + } + _FINISH_REASON_TUPLE_CACHE = tuple(_FINISH_REASON_CACHE[i] for i in range(6)) + return _FINISH_REASON_CACHE + + +def _get_finish_reason_tuple() -> tuple[object, ...]: + if _FINISH_REASON_TUPLE_CACHE is None: + _get_finish_reason_map() + assert _FINISH_REASON_TUPLE_CACHE is not None + return _FINISH_REASON_TUPLE_CACHE + + +def _resolve_finish_reason_enum(code: int) -> object: + """Return bindings.executor.FinishReason if installed, else ZmqFinishReason.""" + cached = _get_finish_reason_map().get(code) + if cached is not None: + return cached + return ZmqFinishReason(code) + + +# ============================================================================ +# Mapping tables for Request & Response enums +# ============================================================================ + +_MODALITY_STR_TO_PROTO: dict[str, int] = { + "image": pb.common_pb2.MODALITY_IMAGE, + "video": pb.common_pb2.MODALITY_VIDEO, + "audio": pb.common_pb2.MODALITY_AUDIO, +} +_PROTO_TO_MODALITY_STR: dict[int, str] = {v: k for k, v in _MODALITY_STR_TO_PROTO.items()} + +_LORA_FORMAT_STR_TO_PROTO: dict[str, int] = { + "hf": pb.common_pb2.LORA_FORMAT_HF, + "nemo": pb.common_pb2.LORA_FORMAT_NEMO, +} +_PROTO_TO_LORA_FORMAT_STR: dict[int, str] = { + pb.common_pb2.LORA_FORMAT_UNSPECIFIED: "hf", + pb.common_pb2.LORA_FORMAT_HF: "hf", + pb.common_pb2.LORA_FORMAT_NEMO: "nemo", +} + +_LOGPROBS_MODE_STR_TO_PROTO: dict[str, int] = { + "raw": pb.request_pb2.LOGPROBS_MODE_RAW, + "processed": pb.request_pb2.LOGPROBS_MODE_PROCESSED, +} +_PROTO_TO_LOGPROBS_MODE_STR: dict[int, str] = { + pb.request_pb2.LOGPROBS_MODE_UNSPECIFIED: "raw", + pb.request_pb2.LOGPROBS_MODE_RAW: "raw", + pb.request_pb2.LOGPROBS_MODE_PROCESSED: "processed", +} + + +def _extract_tokens_list(obj: object) -> list[int]: + if obj is None: + return [] + if isinstance(obj, list): + return [int(x) for x in obj] + if isinstance(obj, tuple): + return [int(x) for x in obj] + if hasattr(obj, "tolist"): + return [int(x) for x in obj.tolist()] + return [int(x) for x in obj] + + +# ============================================================================ +# Decoded Request representation (host/worker side) +# ============================================================================ + + +@dataclasses.dataclass(slots=True) +class DecodedRequest: + """Complete structured request decoded from request_pb2.Request on rank0/worker.""" + + handle: int + request_id: str + prompt_tokens: list[int] + encoder_input_tokens: list[int] + streaming: bool + queue_age_us: Optional[int] + # Group 2: Sampling + sampling: dict[str, object] + # Group 3: Stop + stop: dict[str, object] + # Group 4: Output + output: dict[str, object] + # Group 5/6: Guided / LoRA / Named processors + guided: Optional[dict[str, object]] + lora: Optional[dict[str, object]] + logits_processors: list[str] + # Group 7: Scheduling + Trace + sched: Optional[dict[str, object]] + trace: Optional[dict[str, str]] + # Group 8: KV + kv: Optional[dict[str, object]] + # Group 1: Multimodal (MEDIA or PREPROCESSED) + mm: Optional[dict[str, object]] + # Group 9: Disaggregated serving; DisaggregatedParams fields, None for an aggregated request + disagg: Optional[dict[str, object]] = None + # Raw protobuf message preserved for zero-loss inspection / digest computation + raw_proto: Optional[ProtoMessage] = None + + +@dataclasses.dataclass(slots=True) +class DecodedCancelBatch: + """Decoded CancelBatch message.""" + + cancels: list[tuple[int, int]] # list of (handle, CancelReason) + all: bool + all_reason: int + consumed_frame_seq: int + + +# ============================================================================ +# Request Encoding Helpers +# ============================================================================ + + +def _extract_logit_bias(sp: object) -> list[ProtoMessage]: + """Extract sparse logit_bias entries from sparse pairs, dict, or dense tensor/list.""" + entries: list[ProtoMessage] = [] + # Explicit sparse list/dict on sampling_params if present (e.g. logit_bias) + sparse = getattr(sp, "logit_bias", None) + if sparse is not None: + if isinstance(sparse, Mapping): + for tid, bias in sparse.items(): + val = float(bias) + if val != 0.0: + entries.append(pb.request_pb2.LogitBias(token_id=int(tid), bias=val)) + return entries + for pair in sparse: + tid, bias = pair + val = float(bias) + if val != 0.0: + entries.append(pb.request_pb2.LogitBias(token_id=int(tid), bias=val)) + return entries + + emb_bias = getattr(sp, "embedding_bias", None) + if emb_bias is None: + return entries + + # Sparse tuple form: tuple of (token_id, bias) pairs. + # Preserve all entries (including bias == 0.0) so worker-side _validate_embedding_bias + # still rejects out-of-range indices such as ((-1, 0.0),). + if isinstance(emb_bias, tuple) and ( + len(emb_bias) == 0 or isinstance(emb_bias[0], (tuple, list)) + ): + for tid, bias in emb_bias: + entries.append(pb.request_pb2.LogitBias(token_id=int(tid), bias=float(bias))) + return entries + + # Dense RawTensor / torch.Tensor / np.ndarray / list[float] + if isinstance(emb_bias, RawTensor): + if len(emb_bias.shape) != 1: + raise ValueError(f"embedding_bias must be 1D, got shape {emb_bias.shape}") + vals = emb_bias.to_list() + elif hasattr(emb_bias, "detach"): + if len(emb_bias.shape) != 1: + raise ValueError(f"embedding_bias must be 1D, got shape {tuple(emb_bias.shape)}") + vals = emb_bias.detach().cpu().tolist() + elif hasattr(emb_bias, "tolist"): + shape = getattr(emb_bias, "shape", None) + if shape is not None and len(shape) != 1: + raise ValueError(f"embedding_bias must be 1D, got shape {tuple(shape)}") + vals = emb_bias.tolist() + else: + vals = list(emb_bias) + if any(isinstance(x, (list, tuple)) for x in vals): + raise ValueError("embedding_bias must be 1D, got nested sequence") + for tid, bias in enumerate(vals): + fval = float(bias) + if fval != 0.0: + entries.append(pb.request_pb2.LogitBias(token_id=tid, bias=fval)) + return entries + + +def _encode_sampling_params(sp: object, msg: Optional[ProtoMessage] = None) -> ProtoMessage: + """Encode SamplingParams (all 22 proto fields) into request_pb2.SamplingParams.""" + if msg is None: + msg = pb.request_pb2.SamplingParams() + use_beam = bool(getattr(sp, "use_beam_search", False)) + n = int(getattr(sp, "n", 1) or 1) + best_of = getattr(sp, "best_of", None) + best_of_val = int(best_of) if best_of is not None else n + + if use_beam: + msg.num_sequences = 1 + msg.beam_width = best_of_val + if n != best_of_val or getattr(sp, "num_return_beams", None) is not None: + nrb = getattr(sp, "num_return_beams", None) + msg.num_return_beams = int(nrb if nrb is not None else n) + else: + msg.num_sequences = best_of_val + msg.beam_width = int(getattr(sp, "beam_width", 1) or 1) + nrb = getattr(sp, "num_return_beams", None) + if nrb is not None: + msg.num_return_beams = int(nrb) + + bwa = getattr(sp, "beam_width_array", None) + if bwa: + msg.beam_width_array.extend(int(x) for x in bwa) + + # All optional scalar fields + optional_float_fields = ( + "temperature", + "top_p", + "top_p_decay", + "top_p_min", + "min_p", + "repetition_penalty", + "presence_penalty", + "frequency_penalty", + "length_penalty", + "beam_search_diversity_rate", + ) + for fname in optional_float_fields: + val = getattr(sp, fname, None) + if val is not None: + setattr(msg, fname, float(val)) + + optional_int_fields = ( + "top_k", + "top_p_reset_ids", + "seed", + "prompt_ignore_length", + "no_repeat_ngram_size", + "early_stopping", + ) + for fname in optional_int_fields: + val = getattr(sp, fname, None) + if val is not None: + setattr(msg, fname, int(val)) + + bias_entries = _extract_logit_bias(sp) + if bias_entries: + msg.logit_bias.extend(bias_entries) + + lp_mode = getattr(sp, "logprobs_mode", None) + if lp_mode is not None: + if isinstance(lp_mode, int): + msg.logprobs_mode = lp_mode + else: + mode_str = str(getattr(lp_mode, "value", lp_mode)).lower() + msg.logprobs_mode = _LOGPROBS_MODE_STR_TO_PROTO.get( + mode_str, pb.request_pb2.LOGPROBS_MODE_RAW + ) + return msg + + +def _encode_stop_params(sp: object, msg: Optional[ProtoMessage] = None) -> ProtoMessage: + """Encode StopParams (all 7 fields) into request_pb2.StopParams.""" + if msg is None: + msg = pb.request_pb2.StopParams() + max_tokens = getattr(sp, "max_tokens", None) + if max_tokens is not None: + prefix = getattr(sp, "_decoder_output_token_prefix", ()) + adj = int(max_tokens) - len(prefix) + msg.max_tokens = max(0, adj) + min_tokens = getattr(sp, "min_tokens", None) + if min_tokens is not None: + msg.min_tokens = int(min_tokens) + end_id = getattr(sp, "end_id", None) + if end_id is not None: + msg.end_id = int(end_id) + pad_id = getattr(sp, "pad_id", None) + if pad_id is not None: + msg.pad_id = int(pad_id) + ignore_eos = bool(getattr(sp, "ignore_eos", False)) + msg.ignore_eos = ignore_eos + + # Stop sequences: prefer _get_stop_words() if callable, else stop_token_ids + _stop_word_ids + stop_seqs: list[list[int]] = [] + if not ignore_eos: + explicit_seqs = getattr(sp, "stop_sequences", None) + if explicit_seqs is not None: + stop_seqs = [[int(t) for t in seq] for seq in explicit_seqs] + elif callable(getattr(sp, "_get_stop_words", None)): + stop_seqs = [[int(t) for t in seq] for seq in (sp._get_stop_words() or ())] + else: + for tid in getattr(sp, "stop_token_ids", None) or (): + stop_seqs.append([int(tid)]) + for seq in getattr(sp, "_stop_word_ids", None) or (): + stop_seqs.append([int(t) for t in seq]) + for seq in stop_seqs: + msg.sequences.append(pb.common_pb2.TokenSeq(tokens=seq)) + + # Bad sequences + bad_seqs: list[list[int]] = [] + explicit_bad = getattr(sp, "bad_sequences", None) + if explicit_bad is not None: + bad_seqs = [[int(t) for t in seq] for seq in explicit_bad] + elif callable(getattr(sp, "_get_bad_words", None)): + bad_seqs = [[int(t) for t in seq] for seq in (sp._get_bad_words() or ())] + else: + for tid in getattr(sp, "bad_token_ids", None) or (): + bad_seqs.append([int(tid)]) + for seq in getattr(sp, "_bad_word_ids", None) or (): + bad_seqs.append([int(t) for t in seq]) + for seq in bad_seqs: + msg.bad_sequences.append(pb.common_pb2.TokenSeq(tokens=seq)) + return msg + + +def _encode_output_options(sp: object, req: object) -> Optional[ProtoMessage]: + """Encode OutputOptions into request_pb2.OutputOptions.""" + msg = pb.request_pb2.OutputOptions() + has_any = False + + logprobs = getattr(sp, "logprobs", None) + if logprobs is not None: + msg.logprobs = int(logprobs) + has_any = True + + lp_rank = getattr(sp, "logprob_rank", None) + if lp_rank is not None: + msg.logprob_rank = bool(lp_rank) + has_any = True + elif bool(getattr(sp, "logprobs_simple_format", False)) and logprobs == 0: + # Flat simple_format with top-k=0 needs only sampled logprob floats, not full-vocab ranks. + msg.logprob_rank = False + has_any = True + + prompt_lp = getattr(sp, "prompt_logprobs", None) + if prompt_lp is not None: + msg.prompt_logprobs = int(prompt_lp) + has_any = True + + # Tensors + ctx_logits = bool(getattr(sp, "return_context_logits", False)) + gen_logits = bool(getattr(sp, "return_generation_logits", False)) + enc_out = bool(getattr(sp, "return_encoder_output", False)) + routed_exp = bool(getattr(sp, "return_routed_experts", False)) + add_ctx = list(getattr(sp, "additional_context_outputs", None) or ()) + add_gen = list(getattr(sp, "additional_generation_outputs", None) or ()) + add_model = list(getattr(sp, "additional_model_outputs", None) or ()) + # Legacy additional_model_outputs populates both context & generation unless split + for name in add_model: + if name not in add_ctx and name not in add_gen: + add_gen.append(str(name)) + if ctx_logits or gen_logits or enc_out or routed_exp or add_ctx or add_gen: + msg.tensors.context_logits = ctx_logits + msg.tensors.generation_logits = gen_logits + msg.tensors.encoder_output = enc_out + msg.tensors.routed_experts = routed_exp + msg.tensors.additional_context.extend(add_ctx) + msg.tensors.additional_generation.extend(add_gen) + has_any = True + + # Metrics + perf = bool(getattr(sp, "return_perf_metrics", False)) + tb = bool( + getattr(sp, "return_time_breakdown", False) or getattr(req, "return_time_breakdown", False) + ) + dec_stats = bool( + getattr(sp, "return_decoding_stats", False) or getattr(req, "return_decoding_stats", False) + ) + if perf or tb or dec_stats: + msg.metrics.perf = perf + msg.metrics.time_breakdown = tb + msg.metrics.decoding_stats = dec_stats + has_any = True + + ret_exp = bool( + getattr(sp, "return_expanded_prompt", False) + or getattr(req, "return_expanded_prompt", False) + ) + if ret_exp: + msg.return_expanded_prompt = True + has_any = True + + return msg if has_any else None + + +def _encode_guided_decoding(gd: object) -> Optional[ProtoMessage]: + """Encode GuidedDecoding (all 6 kinds including choice).""" + if gd is None: + return None + if isinstance(gd, pb.request_pb2.GuidedDecoding): + return gd + msg = pb.request_pb2.GuidedDecoding() + + if isinstance(gd, Mapping): + json_schema = gd.get("json_schema") or gd.get("json") + json_obj = gd.get("json_object", False) + regex = gd.get("regex") + grammar = gd.get("ebnf_grammar") or gd.get("grammar") + stag = gd.get("structural_tag") + choice = gd.get("choice") or gd.get("choices") + else: + json_schema = getattr(gd, "json_schema", None) + if json_schema is None: + json_schema = getattr(gd, "json", None) + json_obj = bool(getattr(gd, "json_object", False)) + regex = getattr(gd, "regex", None) + grammar = getattr(gd, "ebnf_grammar", None) + if grammar is None: + grammar = getattr(gd, "grammar", None) + stag = getattr(gd, "structural_tag", None) + choice = getattr(gd, "choice", None) + if choice is None: + choice = getattr(gd, "choices", None) + + if json_schema is not None: + if isinstance(json_schema, str): + msg.json_schema = json_schema + elif hasattr(json_schema, "model_json_schema"): + msg.json_schema = json.dumps(json_schema.model_json_schema(), sort_keys=True) + else: + msg.json_schema = json.dumps(json_schema, sort_keys=True) + return msg + if json_obj: + msg.json_object = True + return msg + if regex is not None: + msg.regex = str(regex) + return msg + if grammar is not None: + msg.ebnf_grammar = str(grammar) + return msg + if stag is not None: + msg.structural_tag = str(stag) + return msg + if choice is not None: + msg.choice.choices.extend(str(c) for c in choice) + return msg + return None + + +def _encode_processors(sp: object, req: object, *, strict: bool) -> list[str]: + """Extract named logits_processors; reject arbitrary callables in strict mode. + + ``Request.thinking_budget`` was removed from the serve_engine v1.1 wire contract + (thinking_token_budget is enforced on the client layer). Any remaining callable + ``logits_processor`` is rejected in strict proto mode. + """ + named_procs: list[str] = [] + + # 1. Named logits processors list (string names) + explicit_names = getattr(req, "logits_processors", None) or getattr( + sp, "logits_processors", None + ) + if explicit_names: + for item in explicit_names: + if isinstance(item, str): + named_procs.append(item) + else: + if strict: + raise UnsupportedCallableError( + f"Arbitrary Python logits processor {item!r} cannot be sent in strict proto mode; " + "register a named processor on the engine instead." + ) + raise StrictProtoWireError(f"Non-string logits_processors entry: {item!r}") + + # 2. Legacy SamplingParams.logits_processor (named strings only in strict proto mode) + raw_proc = getattr(sp, "logits_processor", None) + if raw_proc is not None: + proc_list = raw_proc if isinstance(raw_proc, (list, tuple)) else [raw_proc] + for proc in proc_list: + if proc is None: + continue + if isinstance(proc, str): + named_procs.append(proc) + continue + if strict: + raise UnsupportedCallableError( + f"Arbitrary Python callable logits_processor ({type(proc).__qualname__}) " + "is rejected in strict proto mode; use a registered processor name instead." + ) + raise UnsupportedCallableError( + f"Cannot encode callable logits_processor ({type(proc).__qualname__}) into proto" + ) + + # 3. apply_batched_logits_processor legacy flag + if ( + bool(getattr(sp, "apply_batched_logits_processor", False)) + and "default_batched" not in named_procs + ): + named_procs.append("default_batched") + + return named_procs + + +def _encode_lora(lora: object) -> Optional[ProtoMessage]: + if lora is None: + return None + if isinstance(lora, pb.request_pb2.LoraRef): + return lora + if isinstance(lora, Mapping): + adapter_id = int(lora["adapter_id"]) + name = str(lora.get("name", str(adapter_id))) + path = lora.get("path") + fmt = lora.get("format", "hf") + else: + adapter_id = int(getattr(lora, "adapter_id", getattr(lora, "lora_int_id", 0))) + name = str(getattr(lora, "name", getattr(lora, "lora_name", str(adapter_id)))) + path = getattr(lora, "path", getattr(lora, "lora_path", None)) + fmt = getattr(lora, "ckpt_source", getattr(lora, "lora_ckpt_source", "hf")) + msg = pb.request_pb2.LoraRef(adapter_id=adapter_id, name=name) + if path is not None and path != "": + msg.path = str(path) + if isinstance(fmt, int): + msg.format = fmt + else: + msg.format = _LORA_FORMAT_STR_TO_PROTO.get(str(fmt).lower(), pb.common_pb2.LORA_FORMAT_HF) + return msg + + +def _encode_scheduling(req: object) -> Optional[ProtoMessage]: + sched = getattr(req, "scheduling_params", None) + conv = getattr(req, "conversation_params", None) + priority = getattr(req, "priority", None) + if sched is None and conv is None and priority is None: + return None + msg = pb.request_pb2.SchedulingParams() + has_any = False + if priority is not None: + msg.priority = float(priority) + has_any = True + if sched is not None: + dp_rank = getattr(sched, "attention_dp_rank", None) + if dp_rank is not None: + msg.attention_dp_rank = int(dp_rank) + has_any = True + dp_relax = getattr(sched, "attention_dp_relax", None) + if dp_relax is not None: + msg.attention_dp_relax = bool(dp_relax) + has_any = True + hierarchy = getattr(sched, "agent_hierarchy", None) + if hierarchy: + for agent_type, node_id in hierarchy: + msg.agent_hierarchy.append( + pb.request_pb2.AgentHierarchyNode( + agent_type=str(agent_type), node_id=int(node_id) + ) + ) + has_any = True + affinity = getattr(sched, "subagent_affinity_id", None) + if affinity is not None: + msg.subagent_affinity_id = str(affinity) + has_any = True + conv_id = getattr(sched, "conversation_id", None) + if conv_id is not None: + msg.conversation_id = str(conv_id) + has_any = True + if conv is not None: + cid = getattr(conv, "conversation_id", None) + if cid is not None: + msg.conversation_id = str(cid) + has_any = True + return msg if has_any else None + + +def _encode_kv_params(req: object) -> Optional[ProtoMessage]: + salt = getattr(req, "cache_salt", None) + ret = getattr(req, "kv_cache_retention_config", None) + hints = getattr(req, "kv_hints", None) + if salt is None and ret is None and hints is None: + return None + msg = pb.request_pb2.KvParams() + if salt is not None: + msg.cache_salt = str(salt) + if ret is not None: + if isinstance(ret, pb.request_pb2.KvRetention): + msg.retention.CopyFrom(ret) + else: + ranges = getattr(ret, "token_range_retention_configs", None) + if ranges is None: + ranges = getattr(ret, "ranges", ()) + for r in ranges or (): + tr = pb.request_pb2.TokenRangeRetention( + token_start=int(getattr(r, "token_start", 0)), + priority=int(getattr(r, "priority", 35)), + ) + te = getattr(r, "token_end", None) + if te is not None: + tr.token_end = int(te) + dur = getattr(r, "duration_ms", None) + if dur is not None: + # Handle datetime.timedelta or int ms + if hasattr(dur, "total_seconds"): + tr.duration_ms = int(dur.total_seconds() * 1000) + else: + tr.duration_ms = int(dur) + msg.retention.ranges.append(tr) + dec_prio = getattr(ret, "decode_retention_priority", None) + if dec_prio is None: + dec_prio = getattr(ret, "decode_priority", 35) + msg.retention.decode_priority = int(dec_prio if dec_prio is not None else 35) + dec_dur = getattr(ret, "decode_duration_ms", None) + if dec_dur is not None: + if hasattr(dec_dur, "total_seconds"): + msg.retention.decode_duration_ms = int(dec_dur.total_seconds() * 1000) + else: + msg.retention.decode_duration_ms = int(dec_dur) + tmode = getattr(ret, "transfer_mode", 0) + if tmode is not None: + if isinstance(tmode, int): + msg.retention.transfer_mode = int(tmode) + elif hasattr(tmode, "value") and isinstance(tmode.value, int): + msg.retention.transfer_mode = int(tmode.value) + else: + tmode_name = str(getattr(tmode, "name", tmode)).upper() + tmode_map = { + "DRAM": pb.request_pb2.KV_TRANSFER_MODE_DRAM, + "GDS": pb.request_pb2.KV_TRANSFER_MODE_GDS, + "POSIX_DEBUG_FALLBACK": ( + pb.request_pb2.KV_TRANSFER_MODE_POSIX_DEBUG_FALLBACK + ), + } + if tmode_name not in tmode_map: + raise ValueError(f"Unsupported KvCacheTransferMode: {tmode!r}") + msg.retention.transfer_mode = tmode_map[tmode_name] + directory = getattr(ret, "directory", None) + if directory is not None: + msg.retention.directory = str(directory) + if hints is not None: + if isinstance(hints, pb.request_pb2.KvHints): + msg.hints.CopyFrom(hints) + else: + # Support KvHintsSnapshot (.wire_json), KvHintsEnvelope, or plain dict + if hasattr(hints, "wire_json"): + env_dict = json.loads(hints.wire_json.decode("utf-8")) + elif hasattr(hints, "model_dump"): + env_dict = hints.model_dump(mode="json") + elif isinstance(hints, Mapping): + env_dict = dict(hints) + else: + raise TypeError(f"Unsupported kv_hints type: {type(hints).__name__}") + known_env = {"protocol_version", "message_id", "actions"} + msg.hints.protocol_version = str(env_dict.get("protocol_version", "0.1")) + msg.hints.message_id = str(env_dict.get("message_id", "")) + extra_env = {k: v for k, v in env_dict.items() if k not in known_env} + if extra_env: + msg.hints.extra_fields = json.dumps( + extra_env, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + known_act = {"action_id", "action_type", "action_version", "payload"} + for act in env_dict.get("actions", ()): + act_msg = pb.request_pb2.KvHintAction( + action_id=str(act["action_id"]), + action_type=str(act["action_type"]), + action_version=str(act["action_version"]), + payload=json.dumps( + act.get("payload", {}), sort_keys=True, separators=(",", ":") + ).encode("utf-8"), + ) + extra_act = {k: v for k, v in act.items() if k not in known_act} + if extra_act: + act_msg.extra_fields = json.dumps( + extra_act, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + msg.hints.actions.append(act_msg) + return msg + + +def _encode_trace(headers: object) -> Optional[ProtoMessage]: + if not headers: + return None + if isinstance(headers, pb.request_pb2.TraceContext): + return headers + tp = headers.get("traceparent", "") + ts = headers.get("tracestate", "") + if not tp and not ts: + return None + return pb.request_pb2.TraceContext(traceparent=str(tp), tracestate=str(ts)) + + +def _encode_multimodal( + mm_params: object, + *, + delivery_pref: Sequence[int], + max_inline_bytes: int, + blob_store: Optional[LocalBlobStore], + session_id: int, + handle: int, +) -> Optional[ProtoMessage]: + """Encode MultimodalInput (MEDIA or PREPROCESSED + CAP-20 extensions + large tensors).""" + if mm_params is None: + return None + if isinstance(mm_params, pb.request_pb2.MultimodalInput): + return mm_params + + msg = pb.request_pb2.MultimodalInput() + + # Check MEDIA mode first + media_items = getattr(mm_params, "media", None) + if media_items is None and isinstance(mm_params, Mapping): + media_items = mm_params.get("media") + if media_items: + msg.mode = pb.request_pb2.MULTIMODAL_MODE_MEDIA + for idx, item in enumerate(media_items): + if isinstance(item, pb.request_pb2.MediaItem): + msg.media.append(item) + continue + get_f = ( + (lambda k, d=None, o=item: o.get(k, d)) + if isinstance(item, Mapping) + else (lambda k, d=None, o=item: getattr(o, k, d)) + ) + mod = get_f("modality", "image") + mod_enum = ( + mod + if isinstance(mod, int) + else _MODALITY_STR_TO_PROTO.get(str(mod).lower(), pb.common_pb2.MODALITY_IMAGE) + ) + mi = pb.request_pb2.MediaItem( + modality=mod_enum, + mime_type=str(get_f("mime_type", "") or ""), + placeholder_index=int(get_f("placeholder_index", idx)), + ) + uid = get_f("uuid") + if uid is not None: + mi.uuid = str(uid) + url = get_f("url") + data = get_f("data") + blob = get_f("blob") + if blob is not None: + if isinstance(blob, pb.common_pb2.BlobLocation): + mi.blob.CopyFrom(blob) + else: + mi.blob.blob_id = int(blob["blob_id"]) + mi.blob.size = int(blob.get("size", 0)) + if blob.get("digest"): + mi.blob.digest = bytes(blob["digest"]) + elif url is not None: + mi.url = str(url) + elif data is not None: + raw_data = bytes(data) + if len(raw_data) > max_inline_bytes and blob_store is not None: + loc = blob_store.put_blob(raw_data, session_id=session_id, handle=handle) + mi.blob.CopyFrom(loc) + else: + mi.data = raw_data + msg.media.append(mi) + + io_opts = ( + mm_params.get("io_options") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "io_options", None) + ) + if io_opts: + msg.io_options.CopyFrom(wc.dict_to_typed_extension("mm.io", dict(io_opts))) + proc_opts = ( + mm_params.get("processor_options") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "processor_options", None) + ) + if proc_opts: + msg.processor_options.CopyFrom( + wc.dict_to_typed_extension("mm.processor", dict(proc_opts)) + ) + return msg + + # PREPROCESSED mode (native MultimodalParams or dict) + msg.mode = pb.request_pb2.MULTIMODAL_MODE_PREPROCESSED + mm_input = ( + mm_params.get("multimodal_input") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "multimodal_input", None) + ) + mm_data = ( + mm_params.get("multimodal_data") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "multimodal_data", None) + ) + io_opts = ( + mm_params.get("io_options") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "io_options", None) + ) + proc_opts = ( + mm_params.get("processor_options") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "processor_options", None) + ) + if io_opts: + msg.io_options.CopyFrom(wc.dict_to_typed_extension("mm.io", dict(io_opts))) + if proc_opts: + msg.processor_options.CopyFrom(wc.dict_to_typed_extension("mm.processor", dict(proc_opts))) + + # Items + if mm_input is not None: + hashes = getattr(mm_input, "multimodal_hashes", ()) or () + positions = getattr(mm_input, "multimodal_positions", ()) or () + lengths = getattr(mm_input, "multimodal_lengths", ()) or () + uuids = getattr(mm_input, "multimodal_uuids", None) + offsets = getattr(mm_input, "multimodal_item_run_cu_offsets", None) + run_pos = getattr(mm_input, "multimodal_run_positions", None) or () + run_len = getattr(mm_input, "multimodal_run_lengths", None) or () + for i, h in enumerate(hashes): + if isinstance(h, (bytes, bytearray)): + h_bytes = bytes(h) + else: + h_bytes = struct.pack(f"<{len(h)}i", *[int(v) for v in h]) + item_msg = pb.request_pb2.MultimodalItem( + hash=h_bytes, + position=int(positions[i]), + length=int(lengths[i]), + ) + if uuids is not None and i < len(uuids) and uuids[i] is not None: + item_msg.uuid = str(uuids[i]) + if offsets is not None and i + 1 < len(offsets): + r0, r1 = int(offsets[i]), int(offsets[i + 1]) + item_msg.run_positions.extend(int(p) for p in run_pos[r0:r1]) + item_msg.run_lengths.extend(int(x) for x in run_len[r0:r1]) + msg.items.append(item_msg) + + # Precomputed embeddings + embeddings = ( + mm_params.get("embeddings") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "embeddings", None) + ) + if embeddings: + for idx, emb in enumerate(embeddings): + if isinstance(emb, tuple) and len(emb) == 2: + e_idx, e_tensor = emb + elif isinstance(emb, Mapping): + e_idx, e_tensor = int(emb["item_index"]), emb["tensor"] + else: + e_idx, e_tensor = idx, emb + msg.embeddings.append( + pb.request_pb2.PrecomputedEmbedding( + item_index=int(e_idx), + tensor=encode_tensor_ref( + e_tensor, + delivery_pref=delivery_pref, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + + # Model inputs & ItemMetadata + def _is_shared_tensor_dict(obj: object) -> bool: + if not isinstance(obj, Mapping) or "method_key" not in obj: + return False + return ("tensor_size" in obj and ("storage_handle" in obj or "local_token" in obj)) or ( + "local_token" in obj and "producer_pid" in obj + ) + + def _resolve_shared_tensor_dict(obj: Mapping[str, object]) -> object: + from tensorrt_llm._torch.shared_tensor import SharedTensorContainer + + return SharedTensorContainer.from_dict(dict(obj)).get_local_view() + + def _flatten_model_inputs(prefix: str, obj: object) -> None: + # Paths join nested keys with '.', and the decoder rebuilds the nesting from them, so a + # structure the paths cannot express raises TypeError (auto mode then pickles). + if isinstance(obj, Mapping): + if prefix and not obj: + raise TypeError(f"model_input {prefix!r} is an empty mapping") + for k, v in obj.items(): + if k == "multimodal_encoder_item_metadata": + _encode_item_metadata(v, msg.item_metadata) + continue + if not isinstance(k, str) or "." in k or k.startswith("__str__:"): + raise TypeError(f"model_input key {k!r} under {prefix!r} has no path form") + path = f"{prefix}.{k}" if prefix else str(k) + if _is_shared_tensor_dict(v): + _append_model_input(path, _resolve_shared_tensor_dict(v)) + elif isinstance(v, Mapping): + _flatten_model_inputs(path, v) + else: + _append_model_input(path, v) + + def _append_model_input(path: str, val: object) -> None: + if val is None: + raise TypeError(f"model_input {path!r} holds NoneType, which the contract cannot carry") + if isinstance(val, bool): + msg.model_inputs.append(pb.request_pb2.ModelInput(path=path, bool_value=val)) + return + if isinstance(val, int): + msg.model_inputs.append(pb.request_pb2.ModelInput(path=path, i64_value=int(val))) + return + if isinstance(val, float): + msg.model_inputs.append(pb.request_pb2.ModelInput(path=path, f64_value=float(val))) + return + if isinstance(val, str): + msg.model_inputs.append(pb.request_pb2.ModelInput(path=path, string_value=val)) + return + if _is_shared_tensor_dict(val): + val = _resolve_shared_tensor_dict(val) + if isinstance(val, (RawTensor, pb.common_pb2.TensorRef)) or hasattr(val, "shape"): + ref = encode_tensor_ref( + val, + delivery_pref=delivery_pref, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ) + msg.model_inputs.append(pb.request_pb2.ModelInput(path=path, tensor=ref)) + elif isinstance(val, (list, tuple)): + if len(val) == 0: + msg.model_inputs.append( + pb.request_pb2.ModelInput(path=path, i64_list=pb.common_pb2.I64List(values=[])) + ) + elif all(isinstance(x, int) and not isinstance(x, bool) for x in val): + msg.model_inputs.append( + pb.request_pb2.ModelInput( + path=path, i64_list=pb.common_pb2.I64List(values=[int(x) for x in val]) + ) + ) + elif all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in val): + msg.model_inputs.append( + pb.request_pb2.ModelInput( + path=path, f64_list=pb.common_pb2.F64List(values=[float(x) for x in val]) + ) + ) + elif all( + isinstance(x, (RawTensor, pb.common_pb2.TensorRef, bool, int, float, str)) + or hasattr(x, "shape") + or _is_shared_tensor_dict(x) + for x in val + ): + for idx_i, elem in enumerate(val): + _append_model_input(f"{path}.__list__.{idx_i}", elem) + else: + raise TypeError(f"Unsupported model_input list at {path!r}: {val!r}") + else: + raise TypeError(f"Unsupported model_input value at {path!r}: {type(val).__name__}") + + def _encode_item_metadata(meta: object, dst: ProtoMessage) -> None: + if meta is None: + return + for mod, idx in getattr(meta, "item_refs", ()): + dst.item_refs.append( + pb.request_pb2.MultimodalItemRef(modality=str(mod), index=int(idx)) + ) + enc_lens = getattr(meta, "encoder_token_lengths", None) + if enc_lens is not None: + dst.encoder_token_lengths.values.extend(int(x) for x in enc_lens) + out_lens = getattr(meta, "output_embedding_lengths", None) + if out_lens is not None: + dst.output_embedding_lengths.values.extend(int(x) for x in out_lens) + partitions = getattr(meta, "input_partitions", None) or {} + for mod, fields_map in partitions.items(): + for fname, part in fields_map.items(): + pmsg = pb.request_pb2.MultimodalPartition(modality=str(mod), field=str(fname)) + iax = getattr(part, "item_axis", None) + if iax is not None: + pmsg.item_axis = int(iax) + ilens = getattr(part, "item_lengths", None) + if ilens is not None: + pmsg.item_lengths.extend(int(x) for x in ilens) + dst.partitions.append(pmsg) + + if mm_data: + _flatten_model_inputs("", mm_data) + + explicit_meta = ( + mm_params.get("item_metadata") + if isinstance(mm_params, Mapping) + else getattr(mm_params, "item_metadata", None) + ) + if explicit_meta is not None and not msg.item_metadata.item_refs: + _encode_item_metadata(explicit_meta, msg.item_metadata) + + return msg + + +# SamplingParams fields the rank-0 worker reads that serve_engine.v1 has no field for, with the +# value that needs none. Fields only the client reads (detokenization, stop strings, simple +# logprobs formatting) are absent. +_UNCARRIED_SAMPLING_DEFAULTS: tuple[tuple[str, object], ...] = ( + ("exclude_input_from_output", True), + ("watermarking", None), + ("_decoder_output_token_prefix", ()), +) +# GenerationRequest fields likewise. ``arrival_time`` is not listed: the worker stamps its own +# arrival time, which only perf metrics read. +_UNCARRIED_REQUEST_DEFAULTS: tuple[tuple[str, object], ...] = (("prompt_adapter_request", None),) + + +def _is_dense_embedding_bias(emb_bias: object) -> bool: + """Return True for a dense embedding_bias (tensor / ndarray / list), False for sparse tuples.""" + if emb_bias is None: + return False + if isinstance(emb_bias, tuple) and ( + len(emb_bias) == 0 or isinstance(emb_bias[0], (tuple, list)) + ): + return False + return True + + +def uncarried_field_reason(req: object) -> Optional[str]: + """Return why ``req`` sets a field serve_engine.v1 cannot carry, or None if it sets none.""" + sp = getattr(req, "sampling_params", None) + for owner, name_defaults in ( + ("sampling_params", _UNCARRIED_SAMPLING_DEFAULTS), + ("request", _UNCARRIED_REQUEST_DEFAULTS), + ): + obj = sp if owner == "sampling_params" else req + if obj is None: + continue + for name, default in name_defaults: + value = getattr(obj, name, default) + if value is None and default is None: + continue + if isinstance(default, tuple): + if tuple(value or ()) == default: + continue + elif value is default or value == default: + continue + return f"its {owner}.{name}={value!r} has no serve_engine.v1 field" + if sp is not None: + emb_bias = getattr(sp, "embedding_bias", None) + if _is_dense_embedding_bias(emb_bias): + return ( + "its dense sampling_params.embedding_bias shape/length requires C++ " + "tensor validation that sparse LogitBias cannot express" + ) + if getattr(sp, "use_beam_search", False): + best_of = getattr(sp, "best_of", None) + best_of_val = int(best_of) if best_of is not None else int(getattr(sp, "n", 1) or 1) + if best_of_val <= 1 and not getattr(sp, "beam_width_array", None): + return ( + "its sampling_params.use_beam_search=True with best_of<=1 and no " + "beam_width_array cannot be distinguished from non-beam sampling in " + "serve_engine.v1" + ) + mm_params = getattr(req, "multimodal_params", None) + if mm_params is not None and not isinstance(mm_params, Mapping): + if getattr(mm_params, "embeddings", None): + return ( + "its multimodal_params.embeddings cannot be reconstructed into native " + "MultimodalParams on the worker" + ) + return None + + +def encode_generation_requests( + requests: Sequence[object], + *, + consumed_frame_seq: int = 0, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + delivery_pref: Sequence[int] = ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ), + max_inline_bytes: int = 256 * 1024, + strict: bool = True, +) -> ProtoMessage: + """Encode GenerationRequest objects into session_pb2.ClientMessage(submit_batch=...). + + Raises DisaggNotSupportedError for a request whose disaggregated-serving state has no + serve_engine.v1 field (see disagg_codec.unsupported_request_reason), and + StrictProtoWireError for one that sets a field with no serve_engine.v1 field + (``uncarried_field_reason``). SHM segments written for a batch that raises are unlinked. + """ + cmsg = pb.session_pb2.ClientMessage() + batch = cmsg.submit_batch + batch.consumed_frame_seq = int(consumed_frame_seq) + seen_handles: set[int] = set() + written_shm: list[ProtoMessage] = [] + outer_shm = getattr(_UNTRACKED_SHM, "locations", None) + _UNTRACKED_SHM.locations = written_shm + encoded = False + try: + _encode_requests_into( + batch, + requests, + seen_handles, + blob_store=blob_store, + session_id=session_id, + delivery_pref=delivery_pref, + max_inline_bytes=max_inline_bytes, + strict=strict, + ) + encoded = True + finally: + if not encoded: + unlink_untracked_shm(written_shm) + written_shm = [] + _UNTRACKED_SHM.locations = outer_shm + if outer_shm is not None: + outer_shm.extend(written_shm) + return cmsg + + +def _encode_requests_into( + batch: ProtoMessage, + requests: Sequence[object], + seen_handles: set[int], + *, + blob_store: Optional[LocalBlobStore], + session_id: int, + delivery_pref: Sequence[int], + max_inline_bytes: int, + strict: bool, +) -> None: + from . import disagg_codec + + for idx, req in enumerate(requests): + if isinstance(req, pb.request_pb2.Request): + batch.requests.append(req) + continue + + handle = getattr(req, "id", None) + if handle is None: + handle = getattr(req, "handle", idx) + handle = int(handle) + if handle in seen_handles: + raise ValueError(f"Duplicate handle {handle} within SubmitBatch") + seen_handles.add(handle) + + uncarried = uncarried_field_reason(req) + if uncarried is not None: + raise StrictProtoWireError( + f"Request {handle} cannot use the serve_engine.v1 ZeroMQ wire: {uncarried}" + ) + + sp = req.sampling_params + prompt_tokens = _extract_tokens_list(getattr(req, "prompt_token_ids", None)) + enc_tokens = _extract_tokens_list(getattr(req, "encoder_input_token_ids", None)) + + reason = disagg_codec.unsupported_request_reason(req) + if reason is not None: + raise disagg_codec.DisaggNotSupportedError( + f"Request {handle} cannot use the serve_engine.v1 ZeroMQ wire: {reason}" + ) + dp = getattr(req, "disaggregated_params", None) + phase, disagg_msg = disagg_codec.encode_request_disagg(dp) + + pb_req = batch.requests.add() + pb_req.handle = handle + req_id_str = str(getattr(req, "request_id", "") or "") + if req_id_str: + pb_req.request_id = req_id_str + if prompt_tokens: + pb_req.prompt_tokens.extend(prompt_tokens) + if enc_tokens: + pb_req.encoder_input_tokens.extend(enc_tokens) + pb_req.phase = phase + pb_req.streaming = bool(getattr(req, "streaming", False)) + if disagg_msg is not None: + pb_req.disagg.CopyFrom(disagg_msg) + + q_age = getattr(req, "queue_age_us", None) + if q_age is None: + q_age = disagg_codec.queue_age_us_from_params(dp) + if q_age is not None: + pb_req.queue_age_us = int(q_age) + + # Sampling & Stop populated directly in-place on pb_req (avoids submessage CopyFrom). + _encode_sampling_params(sp, pb_req.sampling) + _encode_stop_params(sp, pb_req.stop) + + # Output options + out_msg = _encode_output_options(sp, req) + if out_msg is not None: + pb_req.output.CopyFrom(out_msg) + + # Named logits processors (strict rejects arbitrary callables) + proc_names = _encode_processors(sp, req, strict=strict) + if proc_names: + pb_req.logits_processors.extend(proc_names) + + # Guided decoding + gd_msg = _encode_guided_decoding(getattr(sp, "guided_decoding", None)) + if gd_msg is not None: + pb_req.guided.CopyFrom(gd_msg) + + # LoRA + lora_msg = _encode_lora(getattr(req, "lora_request", None)) + if lora_msg is not None: + pb_req.lora.CopyFrom(lora_msg) + + # Scheduling + sched_msg = _encode_scheduling(req) + if sched_msg is not None: + pb_req.sched.CopyFrom(sched_msg) + + # KV + kv_msg = _encode_kv_params(req) + if kv_msg is not None: + pb_req.kv.CopyFrom(kv_msg) + + # Trace + trace_msg = _encode_trace(getattr(req, "trace_headers", None)) + if trace_msg is not None: + pb_req.trace.CopyFrom(trace_msg) + + # Multimodal + mm_msg = _encode_multimodal( + getattr(req, "multimodal_params", None), + delivery_pref=delivery_pref, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ) + if mm_msg is not None: + pb_req.mm.CopyFrom(mm_msg) + + +# ============================================================================ +# Request Decoding (SubmitBatch -> list[DecodedRequest]) +# ============================================================================ + + +def _decode_sampling_params(msg: ProtoMessage) -> dict[str, object]: + out: dict[str, object] = { + "num_sequences": int(msg.num_sequences) if msg.num_sequences else 1, + "beam_width": int(msg.beam_width) if msg.beam_width else 1, + "num_return_beams": int(msg.num_return_beams) if msg.HasField("num_return_beams") else None, + "beam_width_array": list(msg.beam_width_array) if msg.beam_width_array else None, + "logprobs_mode": _PROTO_TO_LOGPROBS_MODE_STR.get(msg.logprobs_mode, "raw"), + } + for fname in ( + "temperature", + "top_k", + "top_p", + "top_p_decay", + "top_p_min", + "top_p_reset_ids", + "min_p", + "seed", + "repetition_penalty", + "presence_penalty", + "frequency_penalty", + "prompt_ignore_length", + "no_repeat_ngram_size", + "length_penalty", + "early_stopping", + "beam_search_diversity_rate", + ): + out[fname] = getattr(msg, fname) if msg.HasField(fname) else None + out["logit_bias"] = [(int(lb.token_id), float(lb.bias)) for lb in msg.logit_bias] + return out + + +def _decode_stop_params(msg: ProtoMessage) -> dict[str, object]: + return { + "max_tokens": int(msg.max_tokens) if msg.HasField("max_tokens") else None, + "min_tokens": int(msg.min_tokens) if msg.HasField("min_tokens") else None, + "end_id": int(msg.end_id) if msg.HasField("end_id") else None, + "pad_id": int(msg.pad_id) if msg.HasField("pad_id") else None, + "ignore_eos": bool(msg.ignore_eos), + "sequences": [list(s.tokens) for s in msg.sequences], + "bad_sequences": [list(s.tokens) for s in msg.bad_sequences], + } + + +def _decode_output_options(msg: ProtoMessage) -> dict[str, object]: + return { + "logprobs": int(msg.logprobs) if msg.HasField("logprobs") else None, + "logprob_rank": bool(msg.logprob_rank) if msg.HasField("logprob_rank") else True, + "prompt_logprobs": int(msg.prompt_logprobs) if msg.HasField("prompt_logprobs") else None, + "tensors": { + "context_logits": bool(msg.tensors.context_logits), + "generation_logits": bool(msg.tensors.generation_logits), + "encoder_output": bool(msg.tensors.encoder_output), + "routed_experts": bool(msg.tensors.routed_experts), + "additional_context": list(msg.tensors.additional_context), + "additional_generation": list(msg.tensors.additional_generation), + }, + "metrics": { + "perf": bool(msg.metrics.perf), + "time_breakdown": bool(msg.metrics.time_breakdown), + "decoding_stats": bool(msg.metrics.decoding_stats), + }, + "return_expanded_prompt": bool(msg.return_expanded_prompt), + } + + +def _decode_guided(msg: ProtoMessage) -> Optional[dict[str, object]]: + kind = msg.WhichOneof("kind") + if kind is None: + return None + if kind == "choice": + return {"kind": "choice", "choices": list(msg.choice.choices)} + return {"kind": kind, "value": getattr(msg, kind)} + + +def _decode_multimodal( + msg: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore], + session_id: int, + unlink_shm: bool, + prefer_torch: bool, +) -> Optional[dict[str, object]]: + if msg.mode == pb.request_pb2.MULTIMODAL_MODE_NONE: + return None + res: dict[str, object] = { + "mode": "media" if msg.mode == pb.request_pb2.MULTIMODAL_MODE_MEDIA else "preprocessed", + "io_options": wc.typed_extension_to_dict(msg.io_options) + if msg.HasField("io_options") + else {}, + "processor_options": ( + wc.typed_extension_to_dict(msg.processor_options) + if msg.HasField("processor_options") + else {} + ), + } + if msg.mode == pb.request_pb2.MULTIMODAL_MODE_MEDIA: + media_list = [] + for item in msg.media: + src_kind = item.WhichOneof("source") + entry: dict[str, object] = { + "modality": _PROTO_TO_MODALITY_STR.get(item.modality, "image"), + "mime_type": item.mime_type, + "uuid": item.uuid if item.HasField("uuid") else None, + "placeholder_index": int(item.placeholder_index), + "source_kind": src_kind, + } + if src_kind == "url": + entry["url"] = item.url + elif src_kind == "data": + entry["data"] = bytes(item.data) + elif src_kind == "blob": + entry["blob_id"] = int(item.blob.blob_id) + if blob_store is not None: + raw, digest = blob_store.get_blob(item.blob.blob_id, session_id=session_id) + if item.blob.digest and bytes(item.blob.digest) != digest: + raise ValueError(f"Media blob {item.blob.blob_id} digest mismatch") + entry["data"] = raw + media_list.append(entry) + res["media"] = media_list + return res + + # PREPROCESSED + res["items"] = [ + { + "hash": bytes(it.hash), + "hash_i32": list(struct.unpack(f"<{len(it.hash) // 4}i", it.hash)) + if len(it.hash) % 4 == 0 + else [], + "uuid": it.uuid if it.HasField("uuid") else None, + "position": int(it.position), + "length": int(it.length), + "run_positions": list(it.run_positions), + "run_lengths": list(it.run_lengths), + } + for it in msg.items + ] + model_inputs: dict[str, object] = {} + for mi in msg.model_inputs: + vkind = mi.WhichOneof("value") + if vkind == "tensor": + model_inputs[mi.path] = decode_tensor_ref( + mi.tensor, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + elif vkind == "i64_list": + model_inputs[mi.path] = list(mi.i64_list.values) + elif vkind == "f64_list": + model_inputs[mi.path] = list(mi.f64_list.values) + elif vkind == "bool_value": + model_inputs[mi.path] = bool(mi.bool_value) + elif vkind == "i64_value": + model_inputs[mi.path] = int(mi.i64_value) + elif vkind == "f64_value": + model_inputs[mi.path] = float(mi.f64_value) + elif vkind == "string_value": + model_inputs[mi.path] = str(mi.string_value) + res["model_inputs"] = model_inputs + + res["embeddings"] = [ + { + "item_index": int(emb.item_index), + "tensor": decode_tensor_ref( + emb.tensor, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ), + } + for emb in msg.embeddings + ] + + if msg.HasField("item_metadata"): + im = msg.item_metadata + res["item_metadata"] = { + "item_refs": [(r.modality, int(r.index)) for r in im.item_refs], + "encoder_token_lengths": ( + list(im.encoder_token_lengths.values) + if im.HasField("encoder_token_lengths") + else None + ), + "output_embedding_lengths": ( + list(im.output_embedding_lengths.values) + if im.HasField("output_embedding_lengths") + else None + ), + "partitions": [ + { + "modality": p.modality, + "field": p.field, + "item_axis": int(p.item_axis) if p.HasField("item_axis") else None, + "item_lengths": list(p.item_lengths) if p.item_lengths else None, + } + for p in im.partitions + ], + } + else: + res["item_metadata"] = None + return res + + +def decode_request_proto( + req: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, +) -> DecodedRequest: + """Decode one request_pb2.Request into a DecodedRequest.""" + from . import disagg_codec + + disagg = disagg_codec.decode_request_disagg(req, prefer_torch=prefer_torch) + sampling = _decode_sampling_params(req.sampling) + stop = _decode_stop_params(req.stop) + output = _decode_output_options(req.output) + guided = _decode_guided(req.guided) if req.HasField("guided") else None + lora = None + if req.HasField("lora"): + lora = { + "adapter_id": int(req.lora.adapter_id), + "name": req.lora.name, + "path": req.lora.path if req.lora.HasField("path") else None, + "format": _PROTO_TO_LORA_FORMAT_STR.get(req.lora.format, "hf"), + } + sched = None + if req.HasField("sched"): + s = req.sched + sched = { + "priority": float(s.priority) if s.HasField("priority") else None, + "attention_dp_rank": ( + int(s.attention_dp_rank) if s.HasField("attention_dp_rank") else None + ), + "attention_dp_relax": ( + bool(s.attention_dp_relax) if s.HasField("attention_dp_relax") else None + ), + "agent_hierarchy": [(n.agent_type, int(n.node_id)) for n in s.agent_hierarchy], + "subagent_affinity_id": ( + s.subagent_affinity_id if s.HasField("subagent_affinity_id") else None + ), + "conversation_id": s.conversation_id if s.HasField("conversation_id") else None, + } + trace = None + if req.HasField("trace"): + trace = { + "traceparent": req.trace.traceparent, + "tracestate": req.trace.tracestate, + } + kv = None + if req.HasField("kv"): + kv = { + "cache_salt": req.kv.cache_salt if req.kv.HasField("cache_salt") else None, + "retention": None, + "hints": None, + } + if req.kv.HasField("retention"): + r = req.kv.retention + kv["retention"] = { + "ranges": [ + { + "token_start": int(tr.token_start), + "token_end": int(tr.token_end) if tr.HasField("token_end") else None, + "priority": int(tr.priority), + "duration_ms": ( + int(tr.duration_ms) if tr.HasField("duration_ms") else None + ), + } + for tr in r.ranges + ], + "decode_priority": int(r.decode_priority), + "decode_duration_ms": ( + int(r.decode_duration_ms) if r.HasField("decode_duration_ms") else None + ), + "transfer_mode": int(r.transfer_mode), + "directory": r.directory if r.HasField("directory") else None, + } + if req.kv.HasField("hints"): + h = req.kv.hints + + def _decode_json_object(raw: bytes, field_name: str) -> dict[str, object]: + parsed = json.loads(raw.decode("utf-8")) + if not isinstance(parsed, dict): + raise ValueError( + f"kv.hints.{field_name} must decode to a JSON object, got " + f"{type(parsed).__name__}" + ) + return parsed + + kv["hints"] = { + "protocol_version": h.protocol_version, + "message_id": h.message_id, + "extra_fields": ( + _decode_json_object(h.extra_fields, "extra_fields") + if h.HasField("extra_fields") + else None + ), + "actions": [ + { + "action_id": a.action_id, + "action_type": a.action_type, + "action_version": a.action_version, + "payload": _decode_json_object(a.payload, "actions[].payload") + if a.payload + else {}, + "extra_fields": ( + _decode_json_object(a.extra_fields, "actions[].extra_fields") + if a.HasField("extra_fields") + else None + ), + } + for a in h.actions + ], + } + mm = ( + _decode_multimodal( + req.mm, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + if req.HasField("mm") + else None + ) + + return DecodedRequest( + handle=int(req.handle), + request_id=req.request_id, + prompt_tokens=list(req.prompt_tokens), + encoder_input_tokens=list(req.encoder_input_tokens), + streaming=bool(req.streaming), + queue_age_us=int(req.queue_age_us) if req.HasField("queue_age_us") else None, + sampling=sampling, + stop=stop, + output=output, + guided=guided, + lora=lora, + logits_processors=list(req.logits_processors), + sched=sched, + trace=trace, + kv=kv, + mm=mm, + disagg=disagg, + raw_proto=req, + ) + + +def decode_submit_batch( + batch: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, +) -> list[DecodedRequest]: + """Decode session_pb2.SubmitBatch (or ClientMessage) into list[DecodedRequest]. + + Raises ValueError for an unknown phase, a GENERATION_ONLY request without a handoff, and + DisaggNotSupportedError for a signed handoff (this wire accepts integrity scheme NONE only). + """ + if isinstance(batch, pb.session_pb2.ClientMessage): + if batch.WhichOneof("payload") != "submit_batch": + raise ValueError( + f"Expected submit_batch ClientMessage, got {batch.WhichOneof('payload')!r}" + ) + batch = batch.submit_batch + + return [ + decode_request_proto( + req, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + for req in batch.requests + ] + + +# ============================================================================ +# CancelBatch Codec +# ============================================================================ + + +def encode_cancel_batch( + handles: Sequence[int] = (), + *, + reason: int = pb.common_pb2.CANCEL_REASON_CLIENT_DISCONNECTED, + reasons: Optional[Sequence[int]] = None, + all_flag: bool = False, + all_reason: Optional[int] = None, + consumed_frame_seq: int = 0, +) -> ProtoMessage: + """Encode a CancelBatch inside session_pb2.ClientMessage.""" + cb = pb.session_pb2.CancelBatch( + all=bool(all_flag), + all_reason=int(all_reason if all_reason is not None else reason), + consumed_frame_seq=int(consumed_frame_seq), + ) + for i, h in enumerate(handles): + r = int(reasons[i]) if (reasons is not None and i < len(reasons)) else int(reason) + cb.cancels.append(pb.session_pb2.CancelItem(handle=int(h), reason=r)) + return pb.session_pb2.ClientMessage(cancel_batch=cb) + + +def decode_cancel_batch(msg: ProtoMessage) -> DecodedCancelBatch: + """Decode session_pb2.CancelBatch (or ClientMessage) into DecodedCancelBatch.""" + if isinstance(msg, pb.session_pb2.ClientMessage): + if msg.WhichOneof("payload") != "cancel_batch": + raise ValueError( + f"Expected cancel_batch ClientMessage, got {msg.WhichOneof('payload')!r}" + ) + msg = msg.cancel_batch + return DecodedCancelBatch( + cancels=[(int(c.handle), int(c.reason)) for c in msg.cancels], + all=bool(msg.all), + all_reason=int(msg.all_reason), + consumed_frame_seq=int(msg.consumed_frame_seq), + ) + + +# ============================================================================ +# PromptLogprobs columnar codec (supports inline, sharded has_more, SHM, BLOB) +# ============================================================================ + + +@dataclasses.dataclass(slots=True) +class _FallbackLogprob: + """Duck-typed fallback for tensorrt_llm.executor.logprobs.Logprob.""" + + logprob: float + rank: Optional[int] = None + + +try: + from tensorrt_llm.executor.logprobs import Logprob as _NativeLogprob + + ZmqLogprob: type[object] = _NativeLogprob +except ImportError: + ZmqLogprob = _FallbackLogprob + + +def _pick_out_of_topk_fallback( + raw_items: Sequence[tuple[int, float, int]], +) -> tuple[int, float, int]: + """Choose the target (tid, lp, rank) from raw_items when the supplied target_tid is absent.""" + n_items = len(raw_items) + if n_items >= 2: + # 1. Rank strictly > n_items is unconditionally out-of-top-k. + for it in raw_items: + if it[2] > n_items: + return it + # 2. Duplicate rank marks an appended out-of-top-k target tied with a top-k candidate. + seen_ranks: set[int] = set() + for it in raw_items: + if it[2] > 0: + if it[2] in seen_ranks: + return it + seen_ranks.add(it[2]) + # 3. Rank == n_items covers out-of-top-k rank == k + 1 while remaining lossless for + # pure top-k dicts (decode restores ranks 1..n_items). + for it in raw_items: + if it[2] == n_items: + return it + return raw_items[0] + + +def _split_logprob_entry( + entry: Mapping[int | str, object], target_tid: int +) -> tuple[int, float, int, list[tuple[int, float]]]: + """Split a native {token_id: Logprob} entry into (resolved_tid, sampled_lp, sampled_rank, topk_cands). + + Native logprob dicts store up to ``k`` top-k candidates (ranks 1..k) plus the + sampled/target token if it fell outside top-k (rank > k, or tied with a top-k candidate). + Keeping only the in-top-k candidates in ``topk_cands`` lets the columnar decoder reconstruct + exact 1..k ranks for the top-k entries and restore the out-of-top-k target token with its + full-vocab ``sampled_rank``. + """ + chosen_lp = float("nan") + chosen_rank = 0 + raw_items: list[tuple[int, float, int]] = [] + for cid, lp_obj in entry.items(): + cid_i = int(cid) + lp_val = float(getattr(lp_obj, "logprob", lp_obj)) + rk_val = int(getattr(lp_obj, "rank", 0) or 0) + if cid_i == target_tid: + chosen_lp = lp_val + chosen_rank = rk_val + raw_items.append((cid_i, lp_val, rk_val)) + if math.isnan(chosen_lp) and raw_items: + fallback = _pick_out_of_topk_fallback(raw_items) + target_tid = fallback[0] + chosen_lp = fallback[1] + chosen_rank = fallback[2] + + # When the entry holds only the target token (k=0), omit topk_cands so the decoder + # restores {target_tid: Logprob(sampled_lp, chosen_rank)} from the sampled/rank columns. + if len(raw_items) == 1 and raw_items[0][0] == target_tid and chosen_rank != 0: + return target_tid, chosen_lp, chosen_rank, [] + + # Separate in-top-k candidates from an appended out-of-top-k target token. + non_target_count = sum(1 for cid_i, _, _ in raw_items if cid_i != target_tid) + target_outside_topk = chosen_rank > 0 and chosen_rank > non_target_count + 1 + if not target_outside_topk and chosen_rank > 0 and non_target_count > 0: + non_target_ranks = [rk for cid_i, _, rk in raw_items if cid_i != target_tid and rk > 0] + if len(non_target_ranks) == non_target_count: + # Either non-target entries already occupy 1..k (covers tied target rank <= k as well + # as rank == k + 1), or all non-target ranks are <= k while target rank > k (covers + # tied top-k candidates like [1, 1] with target rank 3). + if sorted(non_target_ranks) == list(range(1, non_target_count + 1)) or ( + max(non_target_ranks) <= non_target_count and chosen_rank > non_target_count + ): + target_outside_topk = True + + cands_with_rank = [ + (cid_i, lp_val, rk_val) + for cid_i, lp_val, rk_val in raw_items + if not (target_outside_topk and cid_i == target_tid) + ] + if any(rk > 0 for _, _, rk in cands_with_rank): + cands_with_rank.sort( + key=lambda item: (item[2] if item[2] > 0 else len(cands_with_rank) + 1) + ) + cands = [(cid_i, lp_val) for cid_i, lp_val, _ in cands_with_rank] + return target_tid, chosen_lp, chosen_rank, cands + + +def _infer_prompt_logprob_target_id(entry: object) -> int: + """Infer the target token id from a prompt_logprobs entry when prompt_token_ids are unavailable.""" + if not isinstance(entry, Mapping) or not entry: + return 0 + raw_items = [ + (int(cid), float(getattr(lp_obj, "logprob", lp_obj)), int(getattr(lp_obj, "rank", 0) or 0)) + for cid, lp_obj in entry.items() + ] + return _pick_out_of_topk_fallback(raw_items)[0] + + +def encode_prompt_logprobs( + entries: Sequence[object], + target_token_ids: Sequence[int], + *, + start: int = 0, + has_more: bool = False, + max_inline_bytes: int = 0, + delivery_pref: Sequence[int] = (pb.common_pb2.TENSOR_DELIVERY_INLINE,), + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + handle: Optional[int] = None, +) -> ProtoMessage: + """Encode prompt logprobs into output_pb2.PromptLogprobs (inline, SHM, or Blob).""" + count = len(entries) + if len(target_token_ids) != count: + raise ValueError( + f"target_token_ids length {len(target_token_ids)} != entries length {count}" + ) + ids: list[int] = [int(t) for t in target_token_ids] + sampled: list[float] = [] + ranks: list[int] = [] + topk_offsets: list[int] = [0] + topk_ids: list[int] = [] + topk_lps: list[float] = [] + has_rank = False + has_topk = False + + for idx, entry in enumerate(entries): + tid = ids[idx] + if isinstance(entry, (int, float)): + sampled.append(float(entry)) + ranks.append(0) + topk_offsets.append(len(topk_ids)) + elif isinstance(entry, Mapping): + resolved_tid, chosen_lp, chosen_rank, cands = _split_logprob_entry(entry, tid) + ids[idx] = resolved_tid + for cid_i, lp_val in cands: + topk_ids.append(cid_i) + topk_lps.append(lp_val) + if chosen_rank != 0: + has_rank = True + if cands: + has_topk = True + sampled.append(chosen_lp) + ranks.append(chosen_rank) + topk_offsets.append(len(topk_ids)) + else: + raise TypeError(f"Unsupported prompt_logprobs entry type: {type(entry).__name__}") + + inline_msg = pb.output_pb2.PromptLogprobs( + start=int(start), + count=count, + has_more=bool(has_more), + ) + if count > 0: + inline_msg.ids = wc._pack_array("i", ids) + inline_msg.sampled = wc._pack_array("f", sampled) + if has_rank: + inline_msg.rank = wc._pack_array("I", ranks) + if has_topk: + inline_msg.topk_offsets = wc._pack_array("I", topk_offsets) + inline_msg.topk_ids = wc._pack_array("i", topk_ids) + inline_msg.topk_logprobs = wc._pack_array("f", topk_lps) + + # Check if we need sideband SHM / BLOB delivery + if max_inline_bytes > 0 and inline_msg.ByteSize() > max_inline_bytes: + raw = inline_msg.SerializeToString() + out = pb.output_pb2.PromptLogprobs(start=int(start), count=count, has_more=bool(has_more)) + for pref in delivery_pref: + if pref == pb.common_pb2.TENSOR_DELIVERY_SHM: + loc = wc.write_shm_bytes(raw) + out.shm.CopyFrom(loc) + if blob_store is not None and handle is not None: + blob_store.track_shm(session_id, handle, loc) + else: + _record_untracked_shm(loc) + return out + if pref == pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH and blob_store is not None: + loc = blob_store.put_blob(raw, session_id=session_id, handle=handle) + out.blob.CopyFrom(loc) + return out + if blob_store is not None: + loc = blob_store.put_blob(raw, session_id=session_id, handle=handle) + out.blob.CopyFrom(loc) + return out + return inline_msg + + +def decode_prompt_logprobs( + msg: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, +) -> dict[str, object]: + """Decode output_pb2.PromptLogprobs (inline, SHM, or Blob) into structured prompt logprobs.""" + ref_kind = msg.WhichOneof("payload_ref") + if ref_kind == "shm": + raw = wc.read_shm_bytes(msg.shm, unlink=unlink_shm) + inner = pb.output_pb2.PromptLogprobs() + inner.ParseFromString(raw) + return decode_prompt_logprobs(inner, blob_store=blob_store, session_id=session_id) + if ref_kind == "blob": + if blob_store is None: + raise ValueError("Cannot decode PromptLogprobs.blob without blob_store") + raw, digest = blob_store.get_blob(msg.blob.blob_id, session_id=session_id) + if msg.blob.digest and bytes(msg.blob.digest) != digest: + raise ValueError("PromptLogprobs blob SHA-256 verification failed") + inner = pb.output_pb2.PromptLogprobs() + inner.ParseFromString(raw) + return decode_prompt_logprobs(inner, blob_store=blob_store, session_id=session_id) + + count = int(msg.count) + if count == 0: + return { + "start": int(msg.start), + "count": 0, + "has_more": bool(msg.has_more), + "entries": [], + "ids": [], + } + ids = wc._unpack_col(msg.ids, "i", count, "prompt_logprobs.ids") + sampled = wc._unpack_col(msg.sampled, "f", count, "prompt_logprobs.sampled") + ranks = ( + wc._unpack_col(msg.rank, "I", count, "prompt_logprobs.rank") if msg.rank else [0] * count + ) + if msg.topk_offsets: + offs = wc._unpack_col(msg.topk_offsets, "I", count + 1, "prompt_logprobs.topk_offsets") + total = offs[-1] + t_ids = ( + wc._unpack_col(msg.topk_ids, "i", total, "prompt_logprobs.topk_ids") + if total > 0 + else [] + ) + t_lps = ( + wc._unpack_col(msg.topk_logprobs, "f", total, "prompt_logprobs.topk_logprobs") + if total > 0 + else [] + ) + entries: list[float | dict[int, ZmqLogprob]] = [] + for i in range(count): + d: dict[int, ZmqLogprob] = {} + c0, c1 = offs[i], offs[i + 1] + for r_idx, ci in enumerate(range(c0, c1), 1): + cid = t_ids[ci] + rk = ranks[i] if (cid == ids[i] and ranks[i] != 0) else r_idx + d[cid] = ZmqLogprob(logprob=t_lps[ci], rank=rk) + if ids[i] not in d: + d[ids[i]] = ZmqLogprob(logprob=sampled[i], rank=ranks[i] or None) + entries.append(d) + else: + entries = [ + {ids[i]: ZmqLogprob(logprob=sampled[i], rank=ranks[i] or None)} + if ranks[i] != 0 + else sampled[i] + for i in range(count) + ] + return { + "start": int(msg.start), + "count": count, + "has_more": bool(msg.has_more), + "entries": entries, + "ids": ids, + } + + +# ============================================================================ +# Duck-typed response objects compatible with GenerationResult._handle_response +# ============================================================================ + + +@dataclasses.dataclass(slots=True) +class ZmqStepResult: + """Duck-typed match for LlmResult consumed by GenerationResult._handle_response / _handle_sequence.""" + + is_final: bool = False + is_request_done: bool = False + sequence_index: int = 0 + output_token_ids: list[list[int]] = dataclasses.field(default_factory=lambda: [[]]) + cum_log_probs: Optional[list[float]] = None + log_probs: Optional[list[list[float | dict[int, ZmqLogprob]]]] = None + finish_reasons: list[object] = dataclasses.field( + default_factory=lambda: [_resolve_finish_reason_enum(0)] + ) + stop_index: int = wc.NO_STOP_INDEX + replace_from: int = wc.NO_REPLACE_FROM + row_flags: int = 0 + context_phase_params: object = None + signed_handoff: object = None + context_logits: object = None + generation_logits: object = None + encoder_output: object = None + routed_experts: object = None + additional_context_outputs: Optional[dict[str, object]] = None + additional_generation_outputs: Optional[dict[str, object]] = None + request_perf_metrics: object = None + time_breakdown_metrics: Optional[dict[str, object]] = None + cached_tokens: int = 0 + ctx_computed_tokens: int = 0 + ctx_first_begin: int = -1 + ctx_num_chunks: int = 0 + decoding_iter: int = 0 + avg_decoded_tokens_per_iter: Optional[float] = None + per_pos_drafted: Optional[list[int]] = None + per_pos_accepted: Optional[list[int]] = None + spec_dec_totals: Optional[tuple[int, int]] = None + ctx_usage: Optional[dict[str, object]] = None + usage: Optional[dict[str, int]] = None + remote_tail_start: Optional[int] = None + first_gen_log_probs: Optional[list[object]] = None + first_gen_logits: Optional[list[object]] = None + mm_embedding_handles: object = None + mrope_position_ids: object = None + mrope_position_deltas: object = None + mrope_position_ids_handle: object = None + mrope_position_deltas_handle: object = None + prompt_logprobs: Optional[dict[str, object]] = None + expanded_prompt_tokens: Optional[list[int]] = None + prompt_len: Optional[int] = None + effective_max_tokens: Optional[int] = None + max_tokens_clamped: bool = False + cancel_reason: int = 0 + streaming_tensor_ranges: list[tuple[int, str, tuple[int, int], object]] = dataclasses.field( + default_factory=list + ) + + +class _FastZmqStepResult: + """Slotted hot-path ZmqStepResult constructed by C++ decode_step_server_message_fast. + + Only the 12 per-step attributes occupy per-instance slots; cold/extra attributes resolve to + read-only class defaults matching ``ZmqStepResult``, avoiding 30+ unnecessary slot stores on + every decoded decode step while remaining fully compatible with ``GenerationResult._handle_response``. + """ + + __slots__ = ( + "is_final", + "is_request_done", + "sequence_index", + "output_token_ids", + "cum_log_probs", + "log_probs", + "finish_reasons", + "stop_index", + "replace_from", + "row_flags", + "cached_tokens", + "decoding_iter", + ) + + context_phase_params: object = None + signed_handoff: object = None + context_logits: object = None + generation_logits: object = None + encoder_output: object = None + routed_experts: object = None + additional_context_outputs: Optional[dict[str, object]] = None + additional_generation_outputs: Optional[dict[str, object]] = None + request_perf_metrics: object = None + time_breakdown_metrics: Optional[dict[str, object]] = None + avg_decoded_tokens_per_iter: Optional[float] = None + per_pos_drafted: Optional[list[int]] = None + per_pos_accepted: Optional[list[int]] = None + spec_dec_totals: Optional[tuple[int, int]] = None + ctx_computed_tokens: int = 0 + ctx_first_begin: int = -1 + ctx_num_chunks: int = 0 + ctx_usage: Optional[dict[str, object]] = None + usage: Optional[dict[str, int]] = None + remote_tail_start: Optional[int] = None + first_gen_log_probs: Optional[list[object]] = None + first_gen_logits: Optional[list[object]] = None + mm_embedding_handles: object = None + mrope_position_ids: object = None + mrope_position_deltas: object = None + mrope_position_ids_handle: object = None + mrope_position_deltas_handle: object = None + prompt_logprobs: Optional[dict[str, object]] = None + expanded_prompt_tokens: Optional[list[int]] = None + prompt_len: Optional[int] = None + effective_max_tokens: Optional[int] = None + max_tokens_clamped: bool = False + cancel_reason: int = 0 + streaming_tensor_ranges: tuple[tuple[int, str, tuple[int, int], object], ...] = () + + +@dataclasses.dataclass(slots=True) +class ZmqStepResponse: + """Duck-typed match for LlmResponse consumed by proxy.py and GenerationResult._handle_response. + + Satisfies `is_llm_response(rsp)` (`hasattr(rsp, "has_error")`), carries `client_id`, + `request_id`, `error_msg`, `error_info`, and `result: ZmqStepResult | _FastZmqStepResult`. + """ + + client_id: int + request_id: int + result: Optional[ZmqStepResult | _FastZmqStepResult] = None + error_msg: Optional[str] = None + error_info: Optional[dict[str, object]] = None + frame_seq: int = 0 + + def has_error(self) -> bool: + return self.error_msg is not None + + +# ============================================================================ +# Response Encoding (Step responses -> ServerMessage(frame=...)) +# ============================================================================ + + +def _encode_timing(timing: object) -> ProtoMessage: + if isinstance(timing, pb.output_pb2.RequestTiming): + return timing + # Native C++ bindings.executor.RequestPerfMetrics has .timing_metrics & .kv_cache_metrics + tm = getattr(timing, "timing_metrics", None) + if tm is not None: + arr_s = ( + tm.arrival_time.total_seconds() if hasattr(tm.arrival_time, "total_seconds") else 0.0 + ) + sched_s = ( + tm.first_scheduled_time.total_seconds() + if hasattr(tm.first_scheduled_time, "total_seconds") + else 0.0 + ) + ft_s = ( + tm.first_token_time.total_seconds() + if hasattr(tm.first_token_time, "total_seconds") + else 0.0 + ) + lt_s = ( + tm.last_token_time.total_seconds() + if hasattr(tm.last_token_time, "total_seconds") + else 0.0 + ) + msg = pb.output_pb2.RequestTiming( + host_accept_ns=int(arr_s * 1e9), + first_scheduled_us=max(0, int((sched_s - arr_s) * 1e6)) if sched_s >= arr_s else 0, + first_token_us=max(0, int((ft_s - arr_s) * 1e6)) if ft_s >= arr_s else 0, + last_token_us=max(0, int((lt_s - arr_s) * 1e6)) if lt_s >= arr_s else 0, + first_iter=int(getattr(timing, "first_iter", 0) or 0), + last_iter=int(getattr(timing, "last_iter", None) or getattr(timing, "iter", 0) or 0), + ) + kv_start = getattr(tm, "kv_cache_transfer_start", None) + kv_end = getattr(tm, "kv_cache_transfer_end", None) + if ( + kv_start is not None + and hasattr(kv_start, "total_seconds") + and kv_start.total_seconds() > 0 + ): + msg.kv_transfer_start_us = max(0, int((kv_start.total_seconds() - arr_s) * 1e6)) + if kv_end is not None and hasattr(kv_end, "total_seconds") and kv_end.total_seconds() > 0: + msg.kv_transfer_end_us = max(0, int((kv_end.total_seconds() - arr_s) * 1e6)) + kv_sz = getattr(tm, "kv_cache_size", 0) + if kv_sz: + msg.kv_transfer_bytes = int(kv_sz) + kvm = getattr(timing, "kv_cache_metrics", None) + if kvm is not None: + reused = int(getattr(kvm, "num_reused_blocks", 0) or 0) + missed = int(getattr(kvm, "num_missed_blocks", 0) or 0) + msg.kv_blocks.allocated = int(getattr(kvm, "num_total_allocated_blocks", 0) or 0) + msg.kv_blocks.new_blocks = int(getattr(kvm, "num_new_allocated_blocks", 0) or 0) + msg.kv_blocks.reused = reused + msg.kv_blocks.missed = missed + hit_rate = getattr(kvm, "kv_cache_hit_rate", None) + if hit_rate is not None and float(hit_rate) != 0.0: + msg.kv_cache_hit_rate = float(hit_rate) + elif reused + missed > 0: + msg.kv_cache_hit_rate = float(reused) / float(reused + missed) + return msg + + # Native RequestEventTiming -> float seconds dict (from _build_perf_metrics_dict) + if isinstance(timing, Mapping): + try: + from tensorrt_llm.metrics.enums import RequestEventTiming + + if RequestEventTiming.ARRIVAL_TIME in timing: + arr_s = float(timing.get(RequestEventTiming.ARRIVAL_TIME, 0.0) or 0.0) + sched_s = float(timing.get(RequestEventTiming.FIRST_SCHEDULED_TIME, 0.0) or 0.0) + ft_s = float(timing.get(RequestEventTiming.FIRST_TOKEN_TIME, 0.0) or 0.0) + lt_s = float(timing.get(RequestEventTiming.LAST_TOKEN_TIME, 0.0) or 0.0) + msg = pb.output_pb2.RequestTiming( + host_accept_ns=int(arr_s * 1e9), + first_scheduled_us=max(0, int((sched_s - arr_s) * 1e6)) + if sched_s >= arr_s + else 0, + first_token_us=max(0, int((ft_s - arr_s) * 1e6)) if ft_s >= arr_s else 0, + last_token_us=max(0, int((lt_s - arr_s) * 1e6)) if lt_s >= arr_s else 0, + ) + kv_s = float(timing.get(RequestEventTiming.KV_CACHE_TRANSFER_START, 0.0) or 0.0) + kv_e = float(timing.get(RequestEventTiming.KV_CACHE_TRANSFER_END, 0.0) or 0.0) + if kv_s > 0: + msg.kv_transfer_start_us = max(0, int((kv_s - arr_s) * 1e6)) + if kv_e > 0: + msg.kv_transfer_end_us = max(0, int((kv_e - arr_s) * 1e6)) + kv_sz = timing.get(RequestEventTiming.KV_CACHE_SIZE, 0) + if kv_sz: + msg.kv_transfer_bytes = int(kv_sz) + return msg + except (ImportError, AttributeError, KeyError, TypeError, ValueError): + pass + + def get_f(k: str, d: object = None) -> object: + return timing.get(k, d) if isinstance(timing, Mapping) else getattr(timing, k, d) + + msg = pb.output_pb2.RequestTiming( + host_accept_ns=int(get_f("host_accept_ns", 0) or 0), + first_scheduled_us=int(get_f("first_scheduled_us", 0) or 0), + first_token_us=int(get_f("first_token_us", 0) or 0), + last_token_us=int(get_f("last_token_us", 0) or 0), + kv_cache_hit_rate=float(get_f("kv_cache_hit_rate", 0.0) or 0.0), + first_iter=int(get_f("first_iter", 0) or 0), + last_iter=int(get_f("last_iter", 0) or 0), + ) + for opt_k in ("kv_transfer_start_us", "kv_transfer_end_us", "kv_transfer_bytes"): + v = get_f(opt_k) + if v is not None: + setattr(msg, opt_k, int(v)) + kvb = get_f("kv_blocks") + if kvb is not None: + if isinstance(kvb, Mapping): + msg.kv_blocks.allocated = int(kvb.get("allocated", 0)) + msg.kv_blocks.new_blocks = int(kvb.get("new_blocks", 0)) + msg.kv_blocks.reused = int(kvb.get("reused", 0)) + msg.kv_blocks.missed = int(kvb.get("missed", 0)) + else: + msg.kv_blocks.allocated = int(getattr(kvb, "allocated", 0)) + msg.kv_blocks.new_blocks = int(getattr(kvb, "new_blocks", 0)) + msg.kv_blocks.reused = int(getattr(kvb, "reused", 0)) + msg.kv_blocks.missed = int(getattr(kvb, "missed", 0)) + return msg + + +def _encode_time_breakdown(tb: object, *, base_s: float = 0.0) -> ProtoMessage: + if isinstance(tb, pb.output_pb2.TimeBreakdown): + return tb + msg = pb.output_pb2.TimeBreakdown( + steps_offset=int(tb.get("steps_offset", 0)), + has_more=bool(tb.get("has_more", False)), + ) + ctx_gpu_fwd = tb.get("ctx_gpu_forward_ms") + if ctx_gpu_fwd is None: + ctx_gpu_fwd = tb.get("ctx_gpu_forward_time") + if ctx_gpu_fwd is not None: + msg.ctx_gpu_forward_ms = float(ctx_gpu_fwd) + ctx_gpu_smp = tb.get("ctx_gpu_sample_ms") + if ctx_gpu_smp is None: + ctx_gpu_smp = tb.get("ctx_gpu_sample_time") + if ctx_gpu_smp is not None: + msg.ctx_gpu_sample_ms = float(ctx_gpu_smp) + + def _ts_to_us(st: Mapping[str, object], us_key: str, s_key: str) -> int: + if us_key in st and st[us_key] is not None: + return int(st[us_key]) + s_val = st.get(s_key) + if s_val is None: + return 0 + delta_s = float(s_val) - base_s + return max(0, int(round(delta_s * 1e6))) + + for keys, target in ( + (("steps", "step_metrics"), msg.steps), + (("ctx_chunks", "ctx_chunk_metrics"), msg.ctx_chunks), + ): + items = None + for k in keys: + if k in tb and tb[k] is not None: + items = tb[k] + break + if not items: + continue + for st in items: + sm = pb.output_pb2.StepTiming( + forward_start_us=_ts_to_us(st, "forward_start_us", "forward_start_time"), + forward_end_us=_ts_to_us(st, "forward_end_us", "forward_end_time"), + sample_start_us=_ts_to_us(st, "sample_start_us", "sample_start_time"), + sample_end_us=_ts_to_us(st, "sample_end_us", "sample_end_time"), + token_us=_ts_to_us(st, "token_us", "token_time"), + ) + if st.get("iter") is not None: + sm.iter = int(st["iter"]) + gpu_fwd = st.get("gpu_forward_ms") + if gpu_fwd is None: + gpu_fwd = st.get("gpu_forward_time") + if gpu_fwd is not None: + sm.gpu_forward_ms = float(gpu_fwd) + gpu_smp = st.get("gpu_sample_ms") + if gpu_smp is None: + gpu_smp = st.get("gpu_sample_time") + if gpu_smp is not None: + sm.gpu_sample_ms = float(gpu_smp) + target.append(sm) + return msg + + +def _extract_row_logprobs( + lp_seq: Sequence[object] | None, tokens: Sequence[int] +) -> tuple[Optional[list[float]], Optional[list[int]], Optional[list[list[tuple[int, float]]]]]: + """Convert per-token logprobs (list[float] or list[dict[int, Logprob]]) into columnar lists.""" + if lp_seq is None or len(tokens) == 0: + return None, None, None + sampled: list[float] = [] + ranks: list[int] = [] + topk: list[list[tuple[int, float]]] = [] + has_rank = False + has_topk = False + if len(lp_seq) > len(tokens): + lp_seq = lp_seq[: len(tokens)] + aligned_tokens = tokens + elif len(lp_seq) == len(tokens) - 1: + # Disaggregated generation_only without transferred first-token logprobs omits token 0. + # Encode a leading NaN placeholder aligned with token 0 so the wire column stays token-aligned. + sampled.append(math.nan) + ranks.append(0) + topk.append([]) + aligned_tokens = tokens[1:] + elif len(lp_seq) == len(tokens): + aligned_tokens = tokens + else: + raise ValueError(f"log_probs length {len(lp_seq)} != tokens length {len(tokens)}") + for tid, entry in zip(aligned_tokens, lp_seq): + if isinstance(entry, (int, float)): + sampled.append(float(entry)) + ranks.append(0) + topk.append([]) + elif isinstance(entry, Mapping): + _, chosen_lp, chosen_rank, cands = _split_logprob_entry(entry, int(tid)) + if chosen_rank != 0: + has_rank = True + if cands: + has_topk = True + sampled.append(chosen_lp) + ranks.append(chosen_rank) + topk.append(cands) + else: + raise TypeError(f"Unsupported log_probs entry: {type(entry).__name__}") + return sampled, (ranks if has_rank else None), (topk if has_topk else None) + + +def _has_ctx_chunk_stats(res: object) -> bool: + """Return True when ``res`` carries non-default chunked-context prefill counters.""" + return ( + int(getattr(res, "ctx_num_chunks", 0) or 0) > 0 + or int(getattr(res, "ctx_computed_tokens", 0) or 0) > 0 + or int(getattr(res, "ctx_first_begin", -1)) >= 0 + ) + + +def _populate_ctx_chunk_stats(target: ProtoMessage, res: object) -> None: + """Copy chunked-context prefill counters from ``res`` onto ``target.ctx_chunks``.""" + if not _has_ctx_chunk_stats(res): + return + cc = target.ctx_chunks + cc.computed_tokens = int(getattr(res, "ctx_computed_tokens", 0) or 0) + first_begin = int(getattr(res, "ctx_first_begin", -1)) + if first_begin >= 0: + cc.first_begin = first_begin + cc.num_chunks = int(getattr(res, "ctx_num_chunks", 0) or 0) + + +def _restore_ctx_chunk_stats(res: ZmqStepResult, cc: ProtoMessage) -> None: + """Restore chunked-context prefill counters from a decoded ContextChunkStats message.""" + res.ctx_computed_tokens = int(cc.computed_tokens) + res.ctx_first_begin = int(cc.first_begin) if cc.HasField("first_begin") else -1 + res.ctx_num_chunks = int(cc.num_chunks) + + +def _finish_reason_to_proto_int(fr: object) -> int: + if isinstance(fr, int): + return int(fr) + name = getattr(fr, "name", None) + if name is not None: + map_by_name = { + "NOT_FINISHED": pb.common_pb2.FINISH_REASON_NOT_FINISHED, + "END_ID": pb.common_pb2.FINISH_REASON_END_ID, + "STOP_WORDS": pb.common_pb2.FINISH_REASON_STOP_SEQUENCE, + "STOP_SEQUENCE": pb.common_pb2.FINISH_REASON_STOP_SEQUENCE, + "LENGTH": pb.common_pb2.FINISH_REASON_LENGTH, + "TIMED_OUT": pb.common_pb2.FINISH_REASON_TIMED_OUT, + "CANCELLED": pb.common_pb2.FINISH_REASON_CANCELLED, + "ERROR": pb.common_pb2.FINISH_REASON_ERROR, + "CONTEXT_DONE": pb.common_pb2.FINISH_REASON_CONTEXT_DONE, + } + if name in map_by_name: + return int(map_by_name[name]) + return int(fr) + + +def _build_frame_rows( + responses: Sequence[object], + *, + tensor_delivery: Sequence[int] = ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ), + max_inline_bytes: int = 256 * 1024, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + prompt_token_ids_by_client: Optional[Mapping[int, Sequence[int]]] = None, + first_gen_token_by_client: Optional[Mapping[int, int]] = None, +) -> list[wc.FrameRow]: + from . import disagg_codec + + frame_rows: list[wc.FrameRow] = [] + + for rsp in responses: + if isinstance(rsp, wc.FrameRow): + frame_rows.append(rsp) + continue + + # Unwrap ResponseWrapper (attaches prompt logprobs & request_perf_metrics dict) + wrapper_lp = None + wrapper_perf = None + if hasattr(rsp, "_response") and not hasattr(rsp, "has_error"): + wrapper_lp = getattr(rsp, "logprobs", None) + wrapper_perf = getattr(rsp, "request_perf_metrics", None) + rsp = rsp._response + elif ( + hasattr(rsp, "_response") + and hasattr(rsp, "logprobs") + and hasattr(rsp, "request_perf_metrics") + ): + wrapper_lp = getattr(rsp, "logprobs", None) + wrapper_perf = getattr(rsp, "request_perf_metrics", None) + rsp = rsp._response + + # Error response path + has_err = ( + rsp.has_error() + if callable(getattr(rsp, "has_error", None)) + else bool(getattr(rsp, "error_msg", None)) + ) + handle = int(getattr(rsp, "client_id", getattr(rsp, "handle", 0))) + if has_err: + err_msg = str(getattr(rsp, "error_msg", "unknown error")) + err_meta = getattr(rsp, "error_info", None) or {} + extra = pb.output_pb2.RowExtra( + error=pb.common_pb2.ErrorInfo( + code=int(err_meta.get("code", pb.common_pb2.ERROR_CODE_INTERNAL)), + retry_scope=int(err_meta.get("retry_scope", pb.common_pb2.RETRY_SCOPE_NONE)), + message=err_msg, + engine_fatal=bool(err_meta.get("engine_fatal", False)), + ), + final_info=pb.output_pb2.FinalInfo( + usage=pb.output_pb2.Usage( + prompt_tokens=int(err_meta.get("prompt_tokens", 0)), + completion_tokens=int(err_meta.get("completion_tokens", 0)), + cached_tokens=int(err_meta.get("cached_tokens", 0)), + ), + decoding=pb.output_pb2.DecodingStats( + decoding_iter=int(err_meta.get("decoding_iter", 0)), + avg_decoded_tokens_per_iter=float( + err_meta.get("avg_decoded_tokens_per_iter", 0.0) + ), + ), + ), + ) + if err_meta.get("field") is not None: + extra.error.field = str(err_meta["field"]) + frame_rows.append( + wc.FrameRow( + handle=handle, + tokens=[], + finish=pb.common_pb2.FINISH_REASON_ERROR, + row_flags=wc.ROW_FLAG_SEQ_FINAL + | wc.ROW_FLAG_REQUEST_DONE + | wc.ROW_FLAG_HAS_EXTRA, + extra=extra, + ) + ) + continue + + res = rsp.result + # Native PyExecutor produces LlmResult whose underlying C++ bindings.executor.Result + # is still serialized bytes until deserialize() is called. Without deserializing first, + # getattr(res, "finish_reasons", [0]) fails on bytes._result and falls back to [0] + # (NOT_FINISHED), causing GenerationResult._handle_sequence to crash when is_final=True. + if hasattr(res, "_result") and isinstance(getattr(res, "_result", None), bytes): + res.deserialize() + reason = disagg_codec.unsupported_result_reason(res) + if reason is not None: + raise disagg_codec.DisaggNotSupportedError( + f"Result for request {handle} cannot use the serve_engine.v1 ZeroMQ wire: {reason}" + ) + has_handoff = disagg_codec.result_has_handoff(res) + ctx_usage = getattr(res, "ctx_usage", None) + output_token_ids = getattr(res, "output_token_ids", [[]]) or [[]] + finish_reasons = getattr(res, "finish_reasons", [0]) or [0] + cum_lps = getattr(res, "cum_log_probs", None) + log_probs = getattr(res, "log_probs", None) + is_final = bool(getattr(res, "is_final", False)) + is_req_done = bool(getattr(res, "is_request_done", is_final)) + base_seq = int(getattr(res, "sequence_index", 0) or 0) + stop_index = int(getattr(res, "stop_index", wc.NO_STOP_INDEX)) + replace_from = int(getattr(res, "replace_from", wc.NO_REPLACE_FROM)) + decoding_iter = int(getattr(res, "decoding_iter", 0) or 0) + cached_tokens = int(getattr(res, "cached_tokens", 0) or 0) + explicit_flags = int(getattr(res, "row_flags", 0) or 0) + + num_seqs = len(output_token_ids) + for s_idx in range(num_seqs): + seq_num = s_idx if num_seqs > 1 else base_seq + toks = [int(t) for t in output_token_ids[s_idx]] + fr_raw = finish_reasons[s_idx] if s_idx < len(finish_reasons) else finish_reasons[0] + finish_code = _finish_reason_to_proto_int(fr_raw) + not_finished = finish_code == pb.common_pb2.FINISH_REASON_NOT_FINISHED + if has_handoff and is_final and not_finished: + finish_code = pb.common_pb2.FINISH_REASON_CONTEXT_DONE + context_done = finish_code == pb.common_pb2.FINISH_REASON_CONTEXT_DONE + + flags = explicit_flags + if is_final or finish_code != pb.common_pb2.FINISH_REASON_NOT_FINISHED: + flags |= wc.ROW_FLAG_SEQ_FINAL + if is_req_done and s_idx == num_seqs - 1: + flags |= wc.ROW_FLAG_REQUEST_DONE + + clp = None + if cum_lps is not None and s_idx < len(cum_lps) and cum_lps[s_idx] is not None: + clp = float(cum_lps[s_idx]) + + lp_s, lp_r, lp_tk = (None, None, None) + row_lp = None + if log_probs is not None and s_idx < len(log_probs) and log_probs[s_idx] is not None: + row_lp = log_probs[s_idx] + if not context_done: + lp_s, lp_r, lp_tk = _extract_row_logprobs(row_lp, toks) + + # Lazily allocate RowExtra only when at least one cold field is emitted. + extra: ProtoMessage | None = None + + def _ensure_extra() -> ProtoMessage: + nonlocal extra + if extra is None: + extra = pb.output_pb2.RowExtra() + return extra + + # PromptInfo (first row / prompt_logprobs / prompt-aligned tensors) + wrapper_prompt_lp = ( + getattr(wrapper_lp, "prompt", None) if wrapper_lp is not None else None + ) + has_prompt_info = s_idx == 0 and ( + (flags & wc.ROW_FLAG_FIRST_ROW) != 0 + or wrapper_prompt_lp is not None + or getattr(res, "prompt_logprobs", None) is not None + or getattr(res, "context_logits", None) is not None + or getattr(res, "encoder_output", None) is not None + or getattr(res, "additional_context_outputs", None) is not None + or getattr(res, "expanded_prompt_tokens", None) is not None + ) + if has_prompt_info: + pi = _ensure_extra().prompt_info + pi.engine_request_id = int(getattr(rsp, "request_id", handle) or handle) + pi.prompt_len = int(getattr(res, "prompt_len", 0) or 0) + exp_pt = getattr(res, "expanded_prompt_tokens", None) + if exp_pt: + pi.expanded_prompt_tokens.extend(int(t) for t in exp_pt) + pi.max_tokens = int(getattr(res, "effective_max_tokens", 0) or 0) + pi.max_tokens_clamped = bool(getattr(res, "max_tokens_clamped", False)) + if ctx_usage is not None and not is_final: + pi.prefill_usage.CopyFrom(disagg_codec.encode_prefill_usage(ctx_usage)) + _populate_ctx_chunk_stats(pi, res) + + plp = getattr(res, "prompt_logprobs", None) + if plp is None and wrapper_prompt_lp is not None: + plp_entries_list = list(wrapper_prompt_lp) + inferred_ids: Optional[list[int]] = None + if prompt_token_ids_by_client is not None: + req_prompt_ids = prompt_token_ids_by_client.get(handle) + if req_prompt_ids is not None: + candidate_ids = [int(t) for t in req_prompt_ids[1:]] + last_entry = plp_entries_list[-1] if plp_entries_list else None + if ( + first_gen_token_by_client is not None + and handle in first_gen_token_by_client + ): + first_tok: Optional[int] = int(first_gen_token_by_client[handle]) + elif toks and ( + not isinstance(last_entry, Mapping) or int(toks[0]) in last_entry + ): + first_tok = int(toks[0]) + elif last_entry is not None: + first_tok = _infer_prompt_logprob_target_id(last_entry) + else: + first_tok = None + if first_tok is not None: + candidate_ids.append(first_tok) + if len(candidate_ids) == len(plp_entries_list): + inferred_ids = candidate_ids + if inferred_ids is None: + inferred_ids = [ + _infer_prompt_logprob_target_id(entry) for entry in plp_entries_list + ] + plp = {"entries": plp_entries_list, "ids": inferred_ids, "start": 0} + if plp is not None: + if isinstance(plp, pb.output_pb2.PromptLogprobs): + pi.prompt_logprobs.CopyFrom(plp) + elif isinstance(plp, Mapping): + pi.prompt_logprobs.CopyFrom( + encode_prompt_logprobs( + plp["entries"], + plp["ids"], + start=int(plp.get("start", 0)), + has_more=bool(plp.get("has_more", False)), + max_inline_bytes=int(plp.get("max_inline_bytes", 0)), + delivery_pref=tensor_delivery, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ) + ) + + # Prompt-aligned tensors + ctx_logits = getattr(res, "context_logits", None) + if ctx_logits is not None: + pi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_CONTEXT_LOGITS, + token_range=pb.common_pb2.TokenRange( + begin=0, end=int(getattr(res, "prompt_len", 0) or 0) + ), + ref=encode_tensor_ref( + ctx_logits, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + enc_out = getattr(res, "encoder_output", None) + if enc_out is not None: + pi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_ENCODER_OUTPUT, + ref=encode_tensor_ref( + enc_out, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + add_ctx = getattr(res, "additional_context_outputs", None) + if add_ctx: + for name, t in add_ctx.items(): + pi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_CONTEXT, + name=str(name), + ref=encode_tensor_ref( + t, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + + # Streaming append-only OutputTensor segments (RowExtra.tensors[]) + stream_segs = getattr(res, "streaming_tensor_ranges", None) or () + for kind_val, name_val, trange, t_or_ref in stream_segs: + out_tensor = pb.output_pb2.OutputTensor( + kind=int(kind_val), + token_range=pb.common_pb2.TokenRange(begin=int(trange[0]), end=int(trange[1])), + ) + if name_val: + out_tensor.name = str(name_val) + if t_or_ref is not None: + out_tensor.ref.CopyFrom( + encode_tensor_ref( + t_or_ref, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ) + ) + _ensure_extra().tensors.append(out_tensor) + + # Non-final streaming responses can carry generation_logits / additional_generation_outputs + # directly on LlmResult (without streaming_tensor_ranges); transport them on RowExtra.tensors. + if (flags & wc.ROW_FLAG_SEQ_FINAL) == 0 and not stream_segs and s_idx == 0: + stream_gen_logits = getattr(res, "generation_logits", None) + if stream_gen_logits is not None: + _ensure_extra().tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_GENERATION_LOGITS, + token_range=pb.common_pb2.TokenRange(begin=0, end=len(toks)), + ref=encode_tensor_ref( + stream_gen_logits, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + stream_add_gen = getattr(res, "additional_generation_outputs", None) + if stream_add_gen: + extra_tensors = _ensure_extra().tensors + for name, t in stream_add_gen.items(): + extra_tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_GENERATION, + name=str(name), + ref=encode_tensor_ref( + t, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + + # The context phase's handoff (CONTEXT_DONE) + if s_idx == 0 and has_handoff: + handoff_lps = row_lp + if ( + context_done + and num_seqs > 1 + and log_probs is not None + and len(log_probs) >= num_seqs + and all( + log_probs[bi] is not None and len(log_probs[bi]) > 0 + for bi in range(num_seqs) + ) + ): + handoff_lps = [log_probs[bi][0] for bi in range(num_seqs)] + _ensure_extra().handoff.CopyFrom( + disagg_codec.encode_result_handoff(res, handle, handoff_lps) + ) + + # FinalInfo on SEQ_FINAL + if (flags & wc.ROW_FLAG_SEQ_FINAL) != 0: + fi = _ensure_extra().final_info + usage_d = getattr(res, "usage", None) or {} + fi.usage.prompt_tokens = int( + usage_d.get("prompt_tokens", getattr(res, "prompt_len", 0) or 0) + ) + fi.usage.completion_tokens = int( + usage_d.get( + "completion_tokens", + 0 if context_done else len(toks), + ) + ) + fi.usage.cached_tokens = int(usage_d.get("cached_tokens", cached_tokens)) + if ctx_usage is not None: + fi.prefill_usage.CopyFrom(disagg_codec.encode_prefill_usage(ctx_usage)) + _populate_ctx_chunk_stats(fi, res) + + fi.decoding.decoding_iter = decoding_iter + avg_d = getattr(res, "avg_decoded_tokens_per_iter", None) + fi.decoding.avg_decoded_tokens_per_iter = float(avg_d if avg_d is not None else 0.0) + + drafted = getattr(res, "per_pos_drafted", None) + accepted = getattr(res, "per_pos_accepted", None) + totals = getattr(res, "spec_dec_totals", None) + if drafted is not None or accepted is not None or totals is not None: + if drafted: + fi.spec.drafted_per_pos.extend(int(x) for x in drafted) + if accepted: + fi.spec.accepted_per_pos.extend(int(x) for x in accepted) + if totals is not None: + # Native LlmResult.spec_dec_totals is (accepted, drafted) + fi.spec.total_accepted = int(totals[0]) + fi.spec.total_drafted = int(totals[1]) + + perf = getattr(res, "request_perf_metrics", None) + if perf is None and wrapper_perf: + perf = wrapper_perf + base_s = 0.0 + if perf is not None: + timing_msg = _encode_timing(perf) + fi.timing.CopyFrom(timing_msg) + base_s = float(timing_msg.host_accept_ns) * 1e-9 + + tb = getattr(res, "time_breakdown_metrics", None) + if tb is not None: + if base_s == 0.0 and isinstance(tb, Mapping): + # If time_breakdown uses native steady-clock seconds without a positive + # RequestTiming anchor, anchor against the earliest step/chunk timestamp + # and store it in fi.timing.host_accept_ns so the proxy can restore it. + tb_times = [ + float(st[k]) + for list_k in ("step_metrics", "ctx_chunk_metrics") + for st in (tb.get(list_k) or ()) + for k in ( + "forward_start_time", + "forward_end_time", + "sample_start_time", + "sample_end_time", + "token_time", + ) + if st.get(k) is not None + ] + if tb_times: + base_s = min(tb_times) + fi.timing.host_accept_ns = int(base_s * 1e9) + fi.time_breakdown.CopyFrom(_encode_time_breakdown(tb, base_s=base_s)) + + # Non-streaming final tensors (or routed_experts once on final) + gen_logits = getattr(res, "generation_logits", None) + if gen_logits is not None and not stream_segs and s_idx == 0: + fi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_GENERATION_LOGITS, + token_range=pb.common_pb2.TokenRange(begin=0, end=len(toks)), + ref=encode_tensor_ref( + gen_logits, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + rexp = getattr(res, "routed_experts", None) + if rexp is not None and s_idx == 0: + fi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_ROUTED_EXPERTS, + ref=encode_tensor_ref( + rexp, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + add_gen = getattr(res, "additional_generation_outputs", None) + if add_gen and not stream_segs and s_idx == 0: + for name, t in add_gen.items(): + fi.tensors.append( + pb.output_pb2.OutputTensor( + kind=pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_GENERATION, + name=str(name), + ref=encode_tensor_ref( + t, + delivery_pref=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + handle=handle, + ), + ) + ) + cancel_r = int(getattr(res, "cancel_reason", 0) or 0) + if cancel_r: + fi.cancel_reason = cancel_r + + frame_rows.append( + wc.FrameRow( + handle=handle, + seq=seq_num, + tokens=[] if context_done else toks, + finish=finish_code, + row_flags=flags, + stop_index=stop_index, + replace_from=replace_from, + cum_logprob=clp, + decoding_iter=decoding_iter, + cached_tokens=cached_tokens, + lp_sampled=lp_s, + lp_rank=lp_r, + lp_topk=lp_tk, + extra=extra, + ) + ) + + return frame_rows + + +def encode_step_responses_bytes( + responses: Sequence[object], + *, + frame_seq: int, + iter_first: int = 0, + iter_last: int = 0, + emit_time_ns: int = 0, + acks: Sequence[ProtoMessage | bytes] = (), + iteration_stats: Sequence[ProtoMessage | bytes] = (), + lora_set_changed: Sequence[ProtoMessage | bytes] = (), + tensor_delivery: Sequence[int] = ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ), + max_inline_bytes: int = 256 * 1024, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + prompt_token_ids_by_client: Optional[Mapping[int, Sequence[int]]] = None, + first_gen_token_by_client: Optional[Mapping[int, int]] = None, + backend: str | None = None, +) -> bytes: + """Encode step responses directly into serialized ServerMessage{frame} bytes. + + Uses the native C++ fast encoder when available and every response is a plain step row + without RowExtra; otherwise builds FrameRow objects and encodes directly to ServerMessage + bytes without a Frame.FromString / ServerMessage.SerializeToString round-trip. + """ + ts = emit_time_ns or time.monotonic_ns() + if not acks and not iteration_stats and not lora_set_changed: + native = _native.resolve(backend) + if native is not None and hasattr(native, "encode_step_fast"): + fast_bytes = native.encode_step_fast( + responses, + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=ts, + server_message=True, + ) + if fast_bytes is not None: + return fast_bytes + + written_shm: list[ProtoMessage] = [] + outer_shm = getattr(_UNTRACKED_SHM, "locations", None) + _UNTRACKED_SHM.locations = written_shm + encoded = False + try: + frame_rows = _build_frame_rows( + responses, + tensor_delivery=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + prompt_token_ids_by_client=prompt_token_ids_by_client, + first_gen_token_by_client=first_gen_token_by_client, + ) + out = wc.encode_frame_bytes( + frame_rows, + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=ts, + acks=acks, + iteration_stats=iteration_stats, + lora_set_changed=lora_set_changed, + server_message=True, + backend=backend, + ) + encoded = True + return out + finally: + _UNTRACKED_SHM.locations = outer_shm + if encoded and outer_shm is not None: + outer_shm.extend(written_shm) + elif not encoded: + unlink_untracked_shm(written_shm) + + +def encode_step_responses( + responses: Sequence[object], + *, + frame_seq: int, + iter_first: int = 0, + iter_last: int = 0, + emit_time_ns: int = 0, + acks: Sequence[ProtoMessage | bytes] = (), + iteration_stats: Sequence[ProtoMessage | bytes] = (), + lora_set_changed: Sequence[ProtoMessage | bytes] = (), + tensor_delivery: Sequence[int] = ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ), + max_inline_bytes: int = 256 * 1024, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + prompt_token_ids_by_client: Optional[Mapping[int, Sequence[int]]] = None, + first_gen_token_by_client: Optional[Mapping[int, int]] = None, +) -> ProtoMessage: + """Encode step responses (LlmResponse / ZmqStepResponse / dict) into ServerMessage(frame=...). + + Raises DisaggNotSupportedError for a result whose disaggregated-serving state has no + serve_engine.v1 field (see disagg_codec.unsupported_result_reason). + """ + written_shm: list[ProtoMessage] = [] + outer_shm = getattr(_UNTRACKED_SHM, "locations", None) + _UNTRACKED_SHM.locations = written_shm + encoded = False + try: + frame_rows = _build_frame_rows( + responses, + tensor_delivery=tensor_delivery, + max_inline_bytes=max_inline_bytes, + blob_store=blob_store, + session_id=session_id, + prompt_token_ids_by_client=prompt_token_ids_by_client, + first_gen_token_by_client=first_gen_token_by_client, + ) + frame = wc.encode_frame( + frame_rows, + frame_seq=frame_seq, + iter_first=iter_first, + iter_last=iter_last, + emit_time_ns=emit_time_ns or time.monotonic_ns(), + acks=acks, + iteration_stats=iteration_stats, + lora_set_changed=lora_set_changed, + ) + out = pb.session_pb2.ServerMessage(frame=frame) + encoded = True + return out + finally: + _UNTRACKED_SHM.locations = outer_shm + if encoded and outer_shm is not None: + outer_shm.extend(written_shm) + elif not encoded: + unlink_untracked_shm(written_shm) + + +# ============================================================================ +# Response Decoding (Frame / ServerMessage -> list[ZmqStepResponse]) +# ============================================================================ + + +def _decode_timing(msg: ProtoMessage) -> dict[str, object]: + out: dict[str, object] = { + "host_accept_ns": int(msg.host_accept_ns), + "first_scheduled_us": int(msg.first_scheduled_us), + "first_token_us": int(msg.first_token_us), + "last_token_us": int(msg.last_token_us), + "kv_cache_hit_rate": float(msg.kv_cache_hit_rate), + "first_iter": int(msg.first_iter), + "last_iter": int(msg.last_iter), + } + for opt_k in ("kv_transfer_start_us", "kv_transfer_end_us", "kv_transfer_bytes"): + if msg.HasField(opt_k): + out[opt_k] = int(getattr(msg, opt_k)) + if msg.HasField("kv_blocks"): + out["kv_blocks"] = { + "allocated": int(msg.kv_blocks.allocated), + "new_blocks": int(msg.kv_blocks.new_blocks), + "reused": int(msg.kv_blocks.reused), + "missed": int(msg.kv_blocks.missed), + } + return out + + +def _decode_time_breakdown(msg: ProtoMessage) -> dict[str, object]: + def _dec_step(st: ProtoMessage) -> dict[str, object]: + d: dict[str, object] = { + "forward_start_us": int(st.forward_start_us), + "forward_end_us": int(st.forward_end_us), + "sample_start_us": int(st.sample_start_us), + "sample_end_us": int(st.sample_end_us), + "token_us": int(st.token_us), + } + if st.HasField("iter"): + d["iter"] = int(st.iter) + if st.HasField("gpu_forward_ms"): + d["gpu_forward_ms"] = float(st.gpu_forward_ms) + if st.HasField("gpu_sample_ms"): + d["gpu_sample_ms"] = float(st.gpu_sample_ms) + return d + + out: dict[str, object] = { + "steps": [_dec_step(s) for s in msg.steps], + "ctx_chunks": [_dec_step(s) for s in msg.ctx_chunks], + "steps_offset": int(msg.steps_offset), + "has_more": bool(msg.has_more), + } + if msg.HasField("ctx_gpu_forward_ms"): + out["ctx_gpu_forward_ms"] = float(msg.ctx_gpu_forward_ms) + if msg.HasField("ctx_gpu_sample_ms"): + out["ctx_gpu_sample_ms"] = float(msg.ctx_gpu_sample_ms) + return out + + +def _decode_frame_rows( + rows: Sequence[wc.FrameRow], + fseq: int, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, +) -> list[ZmqStepResponse]: + """Decode validated ``FrameRow`` objects into ``ZmqStepResponse`` objects.""" + from . import disagg_codec + + responses: list[ZmqStepResponse] = [] + ctx_done_rows_by_handle: dict[int, list[ZmqStepResponse]] = {} + fr_map = _get_finish_reason_map() + + for row in rows: + extra = row.extra + # Error termination row + if row.finish == pb.common_pb2.FINISH_REASON_ERROR: + err_msg = "Engine error" + err_info: dict[str, object] = { + "code": int(pb.common_pb2.ERROR_CODE_INTERNAL), + "retry_scope": int(pb.common_pb2.RETRY_SCOPE_NONE), + "engine_fatal": False, + } + if extra is not None and extra.HasField("error"): + e = extra.error + err_msg = e.message or err_msg + err_info = { + "code": int(e.code), + "retry_scope": int(e.retry_scope), + "field": e.field if e.HasField("field") else None, + "message": e.message, + "engine_fatal": bool(e.engine_fatal), + } + responses.append( + ZmqStepResponse( + client_id=row.handle, + request_id=row.handle, + result=None, + error_msg=err_msg, + error_info=err_info, + frame_seq=fseq, + ) + ) + continue + + # Reconstruct per-token logprobs + log_probs_out: Optional[list[list[float | dict[int, ZmqLogprob]]]] = None + if row.lp_sampled is not None: + per_tok: list[float | dict[int, ZmqLogprob]] = [] + for ti, tok_id in enumerate(row.tokens): + sampled_lp = row.lp_sampled[ti] + rk = row.lp_rank[ti] if row.lp_rank is not None else 0 + cands = row.lp_topk[ti] if row.lp_topk is not None else [] + if cands or rk != 0: + d: dict[int, ZmqLogprob] = {} + for r_idx, (cid, clp) in enumerate(cands, 1): + d[cid] = ZmqLogprob( + logprob=clp, rank=rk if (cid == tok_id and rk != 0) else r_idx + ) + if tok_id not in d: + d[tok_id] = ZmqLogprob(logprob=sampled_lp, rank=rk or None) + per_tok.append(d) + else: + per_tok.append(sampled_lp) + # Strip the leading NaN sentinel inserted by _extract_row_logprobs when disaggregated + # generation_only omits logprobs for token 0 (len(lp_seq) == len(tokens) - 1). + if ( + len(per_tok) == len(row.tokens) + and len(per_tok) >= 1 + and isinstance(per_tok[0], float) + and math.isnan(per_tok[0]) + and (row.lp_rank is None or row.lp_rank[0] == 0) + and (row.lp_topk is None or not row.lp_topk[0]) + and ( + len(per_tok) == 1 + or any(not (isinstance(x, float) and math.isnan(x)) for x in per_tok[1:]) + ) + ): + per_tok = per_tok[1:] + log_probs_out = [per_tok] + + fr_enum = fr_map.get(row.finish) + if fr_enum is None: + fr_enum = ZmqFinishReason(row.finish) + res = ZmqStepResult( + is_final=bool(row.row_flags & wc.ROW_FLAG_SEQ_FINAL), + is_request_done=bool(row.row_flags & wc.ROW_FLAG_REQUEST_DONE), + sequence_index=row.seq, + output_token_ids=[row.tokens if isinstance(row.tokens, list) else list(row.tokens)], + cum_log_probs=[row.cum_logprob] if row.cum_logprob is not None else None, + log_probs=log_probs_out, + finish_reasons=[fr_enum], + stop_index=row.stop_index, + replace_from=row.replace_from, + row_flags=row.row_flags, + cached_tokens=row.cached_tokens, + decoding_iter=row.decoding_iter, + ) + + req_id = row.handle + if extra is not None: + if extra.HasField("prompt_info"): + pi = extra.prompt_info + req_id = int(pi.engine_request_id) or row.handle + res.prompt_len = int(pi.prompt_len) + res.effective_max_tokens = int(pi.max_tokens) + res.max_tokens_clamped = bool(pi.max_tokens_clamped) + if pi.expanded_prompt_tokens: + res.expanded_prompt_tokens = list(pi.expanded_prompt_tokens) + if pi.HasField("prompt_logprobs"): + res.prompt_logprobs = decode_prompt_logprobs( + pi.prompt_logprobs, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + ) + if pi.HasField("prefill_usage"): + res.ctx_usage = disagg_codec.decode_prefill_usage(pi.prefill_usage) + if pi.HasField("ctx_chunks"): + _restore_ctx_chunk_stats(res, pi.ctx_chunks) + for out_tensor in pi.tensors: + t = decode_tensor_ref( + out_tensor.ref, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + if out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_CONTEXT_LOGITS: + res.context_logits = t + elif out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_ENCODER_OUTPUT: + res.encoder_output = t + elif out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_CONTEXT: + if res.additional_context_outputs is None: + res.additional_context_outputs = {} + res.additional_context_outputs[out_tensor.name] = t + + if extra.HasField("handoff"): + disagg_codec.apply_result_handoff(res, extra.handoff, prefer_torch=prefer_torch) + + # Streaming append-only OutputTensor segments + for out_tensor in extra.tensors: + decoded_t = ( + decode_tensor_ref( + out_tensor.ref, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + if out_tensor.HasField("ref") + else None + ) + trange = (int(out_tensor.token_range.begin), int(out_tensor.token_range.end)) + name = out_tensor.name if out_tensor.HasField("name") else "" + res.streaming_tensor_ranges.append((int(out_tensor.kind), name, trange, decoded_t)) + if decoded_t is not None: + if out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_GENERATION_LOGITS: + res.generation_logits = decoded_t + elif out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_GENERATION: + if res.additional_generation_outputs is None: + res.additional_generation_outputs = {} + res.additional_generation_outputs[name] = decoded_t + + if extra.HasField("final_info"): + fi = extra.final_info + if fi.HasField("usage"): + res.usage = { + "prompt_tokens": int(fi.usage.prompt_tokens), + "completion_tokens": int(fi.usage.completion_tokens), + "cached_tokens": int(fi.usage.cached_tokens), + } + if res.cached_tokens == 0: + res.cached_tokens = int(fi.usage.cached_tokens) + if fi.HasField("prefill_usage"): + res.ctx_usage = disagg_codec.decode_prefill_usage(fi.prefill_usage) + if fi.HasField("ctx_chunks"): + _restore_ctx_chunk_stats(res, fi.ctx_chunks) + if fi.HasField("decoding"): + if fi.decoding.decoding_iter: + res.decoding_iter = int(fi.decoding.decoding_iter) + res.avg_decoded_tokens_per_iter = float(fi.decoding.avg_decoded_tokens_per_iter) + if fi.HasField("spec"): + res.per_pos_drafted = list(fi.spec.drafted_per_pos) + res.per_pos_accepted = list(fi.spec.accepted_per_pos) + res.spec_dec_totals = ( + int(fi.spec.total_accepted), + int(fi.spec.total_drafted), + ) + if fi.HasField("timing"): + res.request_perf_metrics = _decode_timing(fi.timing) + if fi.HasField("time_breakdown"): + res.time_breakdown_metrics = _decode_time_breakdown(fi.time_breakdown) + if fi.cancel_reason: + res.cancel_reason = int(fi.cancel_reason) + for out_tensor in fi.tensors: + t = decode_tensor_ref( + out_tensor.ref, + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + if out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_GENERATION_LOGITS: + res.generation_logits = t + elif out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_ROUTED_EXPERTS: + res.routed_experts = t + if res.additional_generation_outputs is None: + res.additional_generation_outputs = {} + res.additional_generation_outputs["routed_experts"] = t + elif out_tensor.kind == pb.output_pb2.OUTPUT_TENSOR_KIND_ADDITIONAL_GENERATION: + if res.additional_generation_outputs is None: + res.additional_generation_outputs = {} + res.additional_generation_outputs[out_tensor.name] = t + + step_rsp = ZmqStepResponse( + client_id=row.handle, + request_id=req_id, + result=res, + frame_seq=fseq, + ) + responses.append(step_rsp) + if row.finish == pb.common_pb2.FINISH_REASON_CONTEXT_DONE: + ctx_done_rows_by_handle.setdefault(row.handle, []).append(step_rsp) + + # For CONTEXT_DONE responses, only row 0 carries RowExtra.handoff with the full per-beam + # first_gen_tokens vector while sibling rows carry empty tokens. Distribute one first token to + # each returned beam row (including beam_width > num_return_beams where len(first_tokens) > + # len(group)) so downstream beam coalescing reconstructs [[t0], [t1], ...] instead of + # [[t0, t1, ...], []]. + for group in ctx_done_rows_by_handle.values(): + handoff_row = next( + ( + r + for r in group + if r.result is not None and r.result.context_phase_params is not None + ), + None, + ) + if handoff_row is None or handoff_row.result is None: + continue + first_tokens = list(handoff_row.result.context_phase_params.first_gen_tokens or ()) + if not first_tokens or len(first_tokens) < len(group): + continue + first_lps = list(handoff_row.result.first_gen_log_probs or ()) + # Only redistribute when the handoff row absorbed the full vector and every sibling row is empty. + if ( + (len(group) > 1 or len(first_tokens) > 1) + and handoff_row.result.output_token_ids == [first_tokens] + and all( + r.result is not None and r.result.output_token_ids == [[]] + for r in group + if r is not handoff_row + ) + ): + ordered_group = sorted( + group, key=lambda r: r.result.sequence_index if r.result is not None else 0 + ) + can_distribute_lps = len(first_lps) >= len(ordered_group) and all( + r.result is not None and r.result.log_probs is None + for r in ordered_group + if r is not handoff_row + ) + for idx, r in enumerate(ordered_group): + if r.result is not None: + r.result.output_token_ids = [[first_tokens[idx]]] + if can_distribute_lps: + r.result.log_probs = [[first_lps[idx]]] + + return responses + + +def decode_step_server_message_bytes( + payload: bytes, + *, + results_map: Mapping[int, object] | None = None, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, + backend: str | None = None, +) -> tuple[Optional[int], list[ZmqStepResponse], bool]: + """Decode serialized ``ServerMessage`` bytes directly without protobuf round-trips. + + Returns ``(frame_seq, responses, pre_finalized)`` where ``frame_seq`` is None when the + ``ServerMessage`` carries a non-frame payload, and ``pre_finalized`` is True when the native + C++ fast path already applied beam coalescing, ``is_final = is_request_done``, and + ``logprobs_simple_format`` collapsing (so no RowExtra post-processing is needed). + """ + native = _native.resolve(backend) + if native is not None and hasattr(native, "decode_step_server_message_fast"): + fast = native.decode_step_server_message_fast( + payload, + results_map, + response_type=ZmqStepResponse, + result_type=_FastZmqStepResult, + finish_reasons=_get_finish_reason_tuple(), + logprob_type=ZmqLogprob, + ) + if fast is not None: + fseq, rsps = fast + return int(fseq), rsps, True + + kind, decoded = wc.parse_server_message(payload, backend=backend) + if kind != "frame" or not isinstance(decoded, wc.DecodedFrame): + return None, [], False + rsps = _decode_frame_rows( + decoded.rows, + int(decoded.frame_seq), + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + return int(decoded.frame_seq), rsps, False + + +def decode_step_frame( + frame: ProtoMessage, + *, + blob_store: Optional[LocalBlobStore] = None, + session_id: int = 0, + unlink_shm: bool = False, + prefer_torch: bool = True, +) -> list[ZmqStepResponse]: + """Decode output_pb2.Frame (or ServerMessage) into GenerationResult-compatible ZmqStepResponse objects. + + Raises DisaggNotSupportedError for a row whose handoff is signed (this wire accepts + integrity scheme NONE only). + """ + if isinstance(frame, pb.session_pb2.ServerMessage): + if frame.WhichOneof("payload") != "frame": + raise ValueError(f"Expected frame ServerMessage, got {frame.WhichOneof('payload')!r}") + frame = frame.frame + + rows = wc.decode_frame(frame) + return _decode_frame_rows( + rows, + int(frame.frame_seq), + blob_store=blob_store, + session_id=session_id, + unlink_shm=unlink_shm, + prefer_torch=prefer_torch, + ) + + +__all__ = [ + "BlobRecord", + "DecodedCancelBatch", + "DecodedRequest", + "LocalBlobStore", + "RawTensor", + "ZmqFinishReason", + "ZmqLogprob", + "ZmqStepResponse", + "ZmqStepResult", + "decode_cancel_batch", + "decode_inline_tensor", + "decode_prompt_logprobs", + "decode_request_proto", + "decode_step_frame", + "decode_step_server_message_bytes", + "decode_submit_batch", + "decode_tensor_ref", + "encode_cancel_batch", + "encode_generation_requests", + "encode_inline_tensor", + "encode_prompt_logprobs", + "encode_step_responses", + "encode_step_responses_bytes", + "encode_tensor_ref", + "materialize_embedding_bias", +] diff --git a/tensorrt_llm/executor/zmq_wire/disagg_codec.py b/tensorrt_llm/executor/zmq_wire/disagg_codec.py new file mode 100644 index 000000000000..9ff73a6db256 --- /dev/null +++ b/tensorrt_llm/executor/zmq_wire/disagg_codec.py @@ -0,0 +1,606 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Disaggregated-serving fields of trtllm.engine.v1 on the executor's ZeroMQ wire. + +Requests: + - ``DisaggregatedParams.request_type`` maps to ``Request.phase`` (AGGREGATED / CONTEXT_ONLY / + GENERATION_ONLY). + - ``disagg_request_id``, ``schedule_style`` and ``ctx_usage`` map to ``Request.disagg`` + (``request_id``, ``schedule_style``, ``prefill_usage``); ``orig_elapsed_s`` maps to + ``Request.queue_age_us``. + - A GENERATION_ONLY request carries the context phase's state as an unsigned ``SignedHandoff`` + (integrity scheme NONE: empty ``mac`` and ``key_id``) around a ``KvHandoff``. + +Results: + - A final result with ``context_phase_params`` that is not otherwise finished becomes a + ``FINISH_REASON_CONTEXT_DONE`` row with no tokens; ``RowExtra.handoff`` carries the first + generated tokens, their logprobs and logits, draft tokens, the remote-tail start, and mRoPE + tensors. + - ``ctx_usage`` maps to ``PromptInfo.prefill_usage`` on a non-final first row and to + ``FinalInfo.prefill_usage`` on a final row. + +State with no field in the contract (multimodal embedding and mRoPE IPC handles, the +multimodal input layout, and the prompt-tail transport) is reported by +``unsupported_request_reason`` / ``unsupported_result_reason``; callers take the pickle path in +``auto`` mode and raise ``DisaggNotSupportedError`` in ``strict`` mode. +""" + +from __future__ import annotations + +import dataclasses +import math +from typing import Mapping, Optional, Sequence + +from google.protobuf.message import Message as ProtoMessage + +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc + +from .codec import ZmqLogprob, _split_logprob_entry, decode_inline_tensor, encode_inline_tensor +from .transport import StrictProtoWireError + +# ============================================================================ +# Enum mappings +# ============================================================================ + +REQUEST_TYPE_TO_PHASE: dict[str, int] = { + "context_and_generation": pb.common_pb2.PHASE_AGGREGATED, + "context_only": pb.common_pb2.PHASE_CONTEXT_ONLY, + "generation_only": pb.common_pb2.PHASE_GENERATION_ONLY, +} +PHASE_TO_REQUEST_TYPE: dict[int, str] = {v: k for k, v in REQUEST_TYPE_TO_PHASE.items()} + +# tensorrt_llm.disaggregated_params.DisaggScheduleStyle values (CONTEXT_FIRST=0, +# GENERATION_FIRST=1) and their common_pb2.ScheduleStyle counterparts (0 is UNSPECIFIED). +NATIVE_SCHEDULE_STYLE_TO_PROTO: dict[int, int] = { + 0: pb.common_pb2.SCHEDULE_STYLE_CONTEXT_FIRST, + 1: pb.common_pb2.SCHEDULE_STYLE_GENERATION_FIRST, +} +PROTO_SCHEDULE_STYLE_TO_NATIVE: dict[int, int] = { + v: k for k, v in NATIVE_SCHEDULE_STYLE_TO_PROTO.items() +} +_SCHEDULE_STYLE_NAME_TO_PROTO: dict[str, int] = { + "context_first": pb.common_pb2.SCHEDULE_STYLE_CONTEXT_FIRST, + "generation_first": pb.common_pb2.SCHEDULE_STYLE_GENERATION_FIRST, +} + +# DisaggregatedParams fields with no counterpart in the contract. +_UNSUPPORTED_PARAM_FIELDS = ( + "multimodal_embedding_handles", + "multimodal_hashes", + "mrope_position_ids_handle", + "mrope_position_deltas_handle", + "multimodal_input_layout", +) +# Engine result fields with no counterpart in the contract. +_UNSUPPORTED_RESULT_FIELDS = ( + "mm_embedding_handles", + "mrope_position_ids_handle", + "mrope_position_deltas_handle", +) + + +class DisaggNotSupportedError(StrictProtoWireError): + """A request or result carries disaggregated-serving state the contract has no field for.""" + + +def _has_value(value: object) -> bool: + if value is None: + return False + if isinstance(value, (list, tuple, dict)): + return len(value) > 0 + return True + + +def unsupported_request_reason(req: object) -> Optional[str]: + """Return why a GenerationRequest cannot be encoded, or None if it can.""" + if getattr(req, "_prompt_tail_tokens", 0): + return "it uses the prompt-tail transport (gen_prompt_tail_tokens)" + dp = getattr(req, "disaggregated_params", None) + if dp is None: + return None + request_type = getattr(dp, "request_type", None) + if request_type is not None and str(request_type).lower() not in REQUEST_TYPE_TO_PHASE: + return f"its disaggregated request_type {request_type!r} is unknown" + for name in _UNSUPPORTED_PARAM_FIELDS: + if _has_value(getattr(dp, name, None)): + return f"its disaggregated_params.{name} has no serve_engine.v1 field" + return None + + +def unsupported_result_reason(res: object) -> Optional[str]: + """Return why an engine result cannot be encoded, or None if it can.""" + if res is None: + return None + for name in _UNSUPPORTED_RESULT_FIELDS: + if _has_value(getattr(res, name, None)): + return f"its {name} has no serve_engine.v1 field" + return None + + +def schedule_style_to_proto(style: object) -> int: + """Map a DisaggScheduleStyle, its integer value, or its lower-case name to ScheduleStyle.""" + if style is None: + return pb.common_pb2.SCHEDULE_STYLE_UNSPECIFIED + if isinstance(style, str): + value = _SCHEDULE_STYLE_NAME_TO_PROTO.get(style.lower()) + if value is None: + raise ValueError(f"Unknown disaggregated schedule_style: {style!r}") + return value + value = NATIVE_SCHEDULE_STYLE_TO_PROTO.get(int(style)) + if value is None: + raise ValueError(f"Unknown disaggregated schedule_style: {style!r}") + return value + + +def schedule_style_from_proto(value: int) -> Optional[int]: + """Map a ScheduleStyle to the DisaggScheduleStyle integer value (None for UNSPECIFIED).""" + if value == pb.common_pb2.SCHEDULE_STYLE_UNSPECIFIED: + return None + native = PROTO_SCHEDULE_STYLE_TO_NATIVE.get(int(value)) + if native is None: + raise ValueError(f"Unknown serve_engine.v1 ScheduleStyle: {int(value)}") + return native + + +# ============================================================================ +# Prefill usage and first-token logprobs +# ============================================================================ + + +def encode_prefill_usage(usage: object) -> Optional[ProtoMessage]: + """Encode a ctx_usage dict / UsageInfo / PrefillUsage into common_pb2.PrefillUsage.""" + if usage is None: + return None + if isinstance(usage, pb.common_pb2.PrefillUsage): + return usage + if isinstance(usage, Mapping): + details = usage.get("prompt_tokens_details") or {} + cached = details.get("cached_tokens") if isinstance(details, Mapping) else None + if cached is None: + cached = usage.get("cached_tokens", 0) + return pb.common_pb2.PrefillUsage( + prompt_tokens=int(usage.get("prompt_tokens", 0) or 0), cached_tokens=int(cached or 0) + ) + details = getattr(usage, "prompt_tokens_details", None) + cached = getattr(details, "cached_tokens", None) if details is not None else None + if cached is None: + cached = getattr(usage, "cached_tokens", 0) + return pb.common_pb2.PrefillUsage( + prompt_tokens=int(getattr(usage, "prompt_tokens", 0) or 0), cached_tokens=int(cached or 0) + ) + + +def decode_prefill_usage(msg: ProtoMessage) -> dict[str, object]: + """Decode common_pb2.PrefillUsage into the ctx_usage dict the engine and frontend read.""" + prompt_tokens = int(msg.prompt_tokens) + return { + "prompt_tokens": prompt_tokens, + "completion_tokens": 0, + "total_tokens": prompt_tokens, + "prompt_tokens_details": {"cached_tokens": int(msg.cached_tokens)}, + } + + +def _pick_first_token_id_from_mapping(entry: Mapping[int | str, object]) -> int: + """Choose the best token id when first_gen_tokens is absent: smallest positive rank, else max logprob.""" + ranked: list[tuple[int, float, int]] = [] + unranked: list[tuple[float, int]] = [] + for cid, lp_obj in entry.items(): + cid_i = int(cid) + lp_val = float(getattr(lp_obj, "logprob", lp_obj)) + rk_raw = getattr(lp_obj, "rank", None) + rk_val = int(rk_raw) if rk_raw is not None else 0 + if rk_val > 0: + ranked.append((rk_val, -lp_val, cid_i)) + else: + unranked.append((lp_val, cid_i)) + if ranked: + ranked.sort() + return ranked[0][2] + # Fall back to highest logprob (NaN treated as -inf so finite values win). + return max(unranked, key=lambda item: (-math.inf if math.isnan(item[0]) else item[0]))[1] + + +def encode_first_token_logprobs( + entries: Sequence[object], first_gen_tokens: Sequence[int] +) -> list[ProtoMessage]: + """Encode one first-token logprob entry per output: a dict[token_id, Logprob] or a float.""" + out: list[ProtoMessage] = [] + for idx, entry in enumerate(entries): + has_target = idx < len(first_gen_tokens) + sampled_id: int | None = int(first_gen_tokens[idx]) if has_target else None + if isinstance(entry, list) and len(entry) == 1: + entry = entry[0] + if isinstance(entry, (int, float)) and not isinstance(entry, bool): + out.append( + pb.disagg_pb2.FirstTokenLogprob( + token_id=sampled_id if sampled_id is not None else 0, + logprob=float(entry), + rank=0, + ) + ) + continue + if not isinstance(entry, Mapping): + raise TypeError(f"Unsupported first-token logprob entry: {type(entry).__name__}") + if not entry: + # Sentinel (token_id=-1, logprob=NaN, rank=0, no topk) distinguishes {} from a scalar float. + out.append( + pb.disagg_pb2.FirstTokenLogprob( + token_id=-1, + logprob=math.nan, + rank=0, + ) + ) + continue + if sampled_id is None: + # No first_gen_tokens available (e.g. remote_tail_start): pick smallest positive rank, + # falling back to highest logprob, rather than colliding with sentinel 0 or insertion order. + sampled_id = _pick_first_token_id_from_mapping(entry) + resolved_id, chosen_lp, chosen_rank, topk_cands = _split_logprob_entry(entry, sampled_id) + rk_int = int(chosen_rank or 0) + if rk_int == 0 and not topk_cands: + # 1-entry dict {tid: Logprob(lp, rank=None)}: keep the token in topk so decode + # recognizes a dict instead of a scalar float and preserves rank=None. + topk_cands = [(resolved_id, chosen_lp)] + out.append( + pb.disagg_pb2.FirstTokenLogprob( + token_id=resolved_id, + logprob=chosen_lp, + rank=rk_int, + topk=[pb.disagg_pb2.TopLogprob(token_id=t, logprob=lp) for t, lp in topk_cands], + ) + ) + return out + + +def decode_first_token_logprobs( + entries: Sequence[ProtoMessage], +) -> list[float | dict[int, ZmqLogprob]]: + """Inverse of ``encode_first_token_logprobs``; reconstructs 1..k ranks plus out-of-top-k target.""" + out: list[float | dict[int, ZmqLogprob]] = [] + for entry in entries: + tok_id = int(entry.token_id) + rk = int(entry.rank) + if not entry.topk and rk == 0: + if tok_id == -1 and math.isnan(float(entry.logprob)): + out.append({}) + else: + out.append(float(entry.logprob)) + continue + decoded: dict[int, ZmqLogprob] = {} + has_tok = False + for position, cand in enumerate(entry.topk, 1): + cid = int(cand.token_id) + if cid == tok_id: + has_tok = True + cand_rank: Optional[int] = rk if rk != 0 else None + else: + cand_rank = position + decoded[cid] = ZmqLogprob(logprob=float(cand.logprob), rank=cand_rank) + if not has_tok: + decoded[tok_id] = ZmqLogprob(logprob=float(entry.logprob), rank=rk if rk != 0 else None) + out.append(decoded) + return out + + +def _sign_unsigned(handoff: ProtoMessage) -> ProtoMessage: + """Wrap a KvHandoff in a SignedHandoff of integrity scheme NONE.""" + return wc.sign_handoff(handoff) + + +def _unpack_unsigned(signed: ProtoMessage) -> ProtoMessage: + """Parse the KvHandoff of a SignedHandoff of integrity scheme NONE; a signed one is rejected.""" + if signed.mac or signed.key_id: + raise DisaggNotSupportedError( + "SignedHandoff carries a MAC; this wire accepts integrity scheme NONE only" + ) + return wc.verify_and_unpack_handoff(signed, require_signature=False) + + +def _set_multimodal( + handoff: ProtoMessage, + positions: Sequence[int] | None, + lengths: Sequence[int] | None, + ids: object, + deltas: object, +) -> None: + if positions: + handoff.multimodal.positions.extend(int(p) for p in positions) + if lengths: + handoff.multimodal.lengths.extend(int(n) for n in lengths) + if ids is not None: + handoff.multimodal.mrope_position_ids.CopyFrom(encode_inline_tensor(ids)) + if deltas is not None: + handoff.multimodal.mrope_position_deltas.CopyFrom(encode_inline_tensor(deltas)) + + +# ============================================================================ +# Requests +# ============================================================================ + + +def encode_request_disagg(dp: object) -> tuple[int, Optional[ProtoMessage]]: + """Encode DisaggregatedParams into (Request.phase, request_pb2.DisaggParams or None).""" + if dp is None: + return pb.common_pb2.PHASE_AGGREGATED, None + request_type = str(getattr(dp, "request_type", None) or "context_and_generation").lower() + phase = REQUEST_TYPE_TO_PHASE.get(request_type) + if phase is None: + raise ValueError(f"Unknown disaggregated request_type: {request_type!r}") + + msg = pb.request_pb2.DisaggParams() + disagg_request_id = getattr(dp, "disagg_request_id", None) + if disagg_request_id is not None: + msg.request_id = int(disagg_request_id) + msg.schedule_style = schedule_style_to_proto(getattr(dp, "schedule_style", None)) + prefill_usage = encode_prefill_usage(getattr(dp, "ctx_usage", None)) + if prefill_usage is not None: + msg.prefill_usage.CopyFrom(prefill_usage) + + if phase == pb.common_pb2.PHASE_GENERATION_ONLY: + signed = getattr(dp, "signed_handoff", None) + if isinstance(signed, pb.disagg_pb2.SignedHandoff): + msg.handoff.CopyFrom(signed) + else: + msg.handoff.CopyFrom(_sign_unsigned(_handoff_from_params(dp, msg))) + elif ( + phase == pb.common_pb2.PHASE_AGGREGATED + and msg.ByteSize() == 0 + and getattr(dp, "orig_elapsed_s", None) is None + ): + return phase, None + return phase, msg + + +def _handoff_from_params(dp: object, msg: ProtoMessage) -> ProtoMessage: + handoff = pb.disagg_pb2.KvHandoff( + disagg_request_id=int(getattr(dp, "disagg_request_id", None) or 0), + ctx_instance_id=str(getattr(dp, "ctx_instance_id", "") or ""), + ctx_endpoint=str(getattr(dp, "ctx_info_endpoint", None) or ""), + transfer_backend=str(getattr(dp, "transfer_backend", "") or ""), + schedule_style=msg.schedule_style, + ) + ctx_request_id = getattr(dp, "ctx_request_id", None) + if ctx_request_id is not None: + handoff.ctx_engine_request_id = int(ctx_request_id) + ctx_dp_rank = getattr(dp, "ctx_dp_rank", None) + if ctx_dp_rank is not None: + handoff.ctx_dp_rank = int(ctx_dp_rank) + opaque_state = getattr(dp, "opaque_state", None) + if opaque_state is not None: + handoff.opaque_state = bytes(opaque_state) + first_gen_tokens = getattr(dp, "first_gen_tokens", None) or () + handoff.first_gen_tokens.extend(int(t) for t in first_gen_tokens) + first_gen_log_probs = getattr(dp, "first_gen_log_probs", None) + if first_gen_log_probs: + handoff.first_gen_logprobs.extend( + encode_first_token_logprobs(first_gen_log_probs, first_gen_tokens) + ) + for logits in getattr(dp, "first_gen_logits", None) or (): + handoff.first_gen_logits.append(encode_inline_tensor(logits)) + handoff.draft_tokens.extend(int(t) for t in getattr(dp, "draft_tokens", None) or ()) + remote_tail_start = getattr(dp, "remote_tail_start", None) + if remote_tail_start is not None: + handoff.remote_tail_start = int(remote_tail_start) + _set_multimodal( + handoff, + getattr(dp, "multimodal_positions", None), + getattr(dp, "multimodal_lengths", None), + None, + None, + ) + return handoff + + +def queue_age_us_from_params(dp: object) -> Optional[int]: + """Request.queue_age_us for DisaggregatedParams.orig_elapsed_s (None when unset).""" + orig_elapsed_s = getattr(dp, "orig_elapsed_s", None) if dp is not None else None + if orig_elapsed_s is None: + return None + return max(0, int(round(float(orig_elapsed_s) * 1_000_000))) + + +def decode_handoff(signed: ProtoMessage, *, prefer_torch: bool = True) -> dict[str, object]: + """Decode an unsigned SignedHandoff into a dict of its KvHandoff fields.""" + handoff = _unpack_unsigned(signed) + multimodal = None + if handoff.HasField("multimodal"): + mm = handoff.multimodal + multimodal = { + "positions": list(mm.positions), + "lengths": list(mm.lengths), + "mrope_position_ids": ( + decode_inline_tensor(mm.mrope_position_ids, prefer_torch=prefer_torch) + if mm.HasField("mrope_position_ids") + else None + ), + "mrope_position_deltas": ( + decode_inline_tensor(mm.mrope_position_deltas, prefer_torch=prefer_torch) + if mm.HasField("mrope_position_deltas") + else None + ), + } + return { + "disagg_request_id": int(handoff.disagg_request_id), + "ctx_instance_id": handoff.ctx_instance_id, + "ctx_engine_request_id": ( + int(handoff.ctx_engine_request_id) + if handoff.HasField("ctx_engine_request_id") + else None + ), + "ctx_dp_rank": int(handoff.ctx_dp_rank) if handoff.HasField("ctx_dp_rank") else None, + "ctx_endpoint": handoff.ctx_endpoint or None, + "transfer_backend": handoff.transfer_backend, + "opaque_state": bytes(handoff.opaque_state) if handoff.opaque_state else None, + "schedule_style": schedule_style_from_proto(handoff.schedule_style), + "first_gen_tokens": list(handoff.first_gen_tokens), + "first_gen_logprobs": decode_first_token_logprobs(handoff.first_gen_logprobs), + "first_gen_logits": [ + decode_inline_tensor(t, prefer_torch=prefer_torch) for t in handoff.first_gen_logits + ], + "draft_tokens": list(handoff.draft_tokens), + "remote_tail_start": ( + int(handoff.remote_tail_start) if handoff.HasField("remote_tail_start") else None + ), + "multimodal": multimodal, + } + + +def decode_request_disagg( + req: ProtoMessage, *, prefer_torch: bool = True +) -> Optional[dict[str, object]]: + """Decode Request.phase / Request.disagg into the fields of DisaggregatedParams. + + Returns None for an aggregated request without DisaggParams. A GENERATION_ONLY request must + carry a handoff. + """ + request_type = PHASE_TO_REQUEST_TYPE.get(int(req.phase)) + if request_type is None: + raise ValueError(f"Request {int(req.handle)} has unknown phase {int(req.phase)}") + if not req.HasField("disagg"): + if req.phase == pb.common_pb2.PHASE_AGGREGATED: + return None + if req.phase == pb.common_pb2.PHASE_GENERATION_ONLY: + raise ValueError(f"GENERATION_ONLY request {int(req.handle)} carries no handoff") + return {"request_type": request_type} + d = req.disagg + params: dict[str, object] = { + "request_type": request_type, + "disagg_request_id": int(d.request_id) if d.HasField("request_id") else None, + "schedule_style": schedule_style_from_proto(d.schedule_style), + "ctx_usage": decode_prefill_usage(d.prefill_usage) if d.HasField("prefill_usage") else None, + } + if req.phase == pb.common_pb2.PHASE_GENERATION_ONLY: + if not d.HasField("handoff"): + raise ValueError(f"GENERATION_ONLY request {int(req.handle)} carries no handoff") + ho = decode_handoff(d.handoff, prefer_torch=prefer_torch) + mm = ho["multimodal"] or {} + if params["schedule_style"] is None: + params["schedule_style"] = ho["schedule_style"] + params.update( + ctx_request_id=ho["ctx_engine_request_id"], + ctx_dp_rank=ho["ctx_dp_rank"], + ctx_info_endpoint=ho["ctx_endpoint"], + opaque_state=ho["opaque_state"], + first_gen_tokens=ho["first_gen_tokens"] or None, + first_gen_log_probs=ho["first_gen_logprobs"] or None, + first_gen_logits=ho["first_gen_logits"] or None, + draft_tokens=ho["draft_tokens"] or None, + remote_tail_start=ho["remote_tail_start"], + multimodal_positions=mm.get("positions") or None, + multimodal_lengths=mm.get("lengths") or None, + ) + if req.HasField("queue_age_us"): + params["orig_elapsed_s"] = int(req.queue_age_us) / 1_000_000 + return params + + +# ============================================================================ +# Results +# ============================================================================ + + +@dataclasses.dataclass(slots=True) +class ZmqContextPhaseParams: + """Duck-typed match for bindings.executor.ContextPhaseParams.""" + + first_gen_tokens: list[int] + req_id: int + opaque_state: Optional[bytes] = None + draft_tokens: Optional[list[int]] = None + ctx_dp_rank: Optional[int] = None + disagg_info_endpoint: Optional[str] = None + + +def result_has_handoff(res: object) -> bool: + """Return True if an engine result ends a context phase with handoff state.""" + return ( + getattr(res, "context_phase_params", None) is not None + or getattr(res, "signed_handoff", None) is not None + ) + + +def encode_result_handoff( + res: object, handle: int, row_logprobs: Sequence[object] | None = None +) -> ProtoMessage: + """Encode the context phase's handoff state of an engine result as an unsigned SignedHandoff. + + ``row_logprobs`` is the row's per-token logprobs; its first entry becomes the first-token + logprob when the result carries no ``first_gen_log_probs``. + """ + signed = getattr(res, "signed_handoff", None) + if isinstance(signed, pb.disagg_pb2.SignedHandoff): + return signed + cpp = getattr(res, "context_phase_params", None) + req_id = getattr(cpp, "req_id", None) + req_id = int(handle) if req_id is None else int(req_id) + handoff = pb.disagg_pb2.KvHandoff( + disagg_request_id=req_id, + ctx_engine_request_id=req_id, + ctx_endpoint=str(getattr(cpp, "disagg_info_endpoint", None) or ""), + ) + ctx_dp_rank = getattr(cpp, "ctx_dp_rank", None) + if ctx_dp_rank is not None: + handoff.ctx_dp_rank = int(ctx_dp_rank) + opaque_state = getattr(cpp, "opaque_state", None) + if opaque_state: + handoff.opaque_state = bytes(opaque_state) + first_gen_tokens = [int(t) for t in getattr(cpp, "first_gen_tokens", None) or ()] + handoff.first_gen_tokens.extend(first_gen_tokens) + first_gen_log_probs = getattr(res, "first_gen_log_probs", None) + if first_gen_log_probs is None and row_logprobs: + if len(first_gen_tokens) > 1 and len(row_logprobs) >= len(first_gen_tokens): + first_gen_log_probs = list(row_logprobs[: len(first_gen_tokens)]) + else: + first_gen_log_probs = [row_logprobs[0]] + if first_gen_log_probs: + handoff.first_gen_logprobs.extend( + encode_first_token_logprobs(first_gen_log_probs, first_gen_tokens) + ) + for logits in getattr(res, "first_gen_logits", None) or (): + handoff.first_gen_logits.append(encode_inline_tensor(logits)) + handoff.draft_tokens.extend(int(t) for t in getattr(cpp, "draft_tokens", None) or ()) + remote_tail_start = getattr(res, "remote_tail_start", None) + if remote_tail_start is not None: + handoff.remote_tail_start = int(remote_tail_start) + _set_multimodal( + handoff, + None, + None, + getattr(res, "mrope_position_ids", None), + getattr(res, "mrope_position_deltas", None), + ) + return _sign_unsigned(handoff) + + +def apply_result_handoff(res: object, signed: ProtoMessage, *, prefer_torch: bool = True) -> None: + """Set the context-phase fields of a decoded ZmqStepResult from RowExtra.handoff. + + A CONTEXT_DONE row has no tokens; its first generated tokens become the output tokens, as on + the pickle path. + """ + ho = decode_handoff(signed, prefer_torch=prefer_torch) + res.signed_handoff = signed + res.context_phase_params = ZmqContextPhaseParams( + first_gen_tokens=list(ho["first_gen_tokens"]), + req_id=int(ho["disagg_request_id"]), + opaque_state=ho["opaque_state"], + draft_tokens=list(ho["draft_tokens"]) if ho["draft_tokens"] else None, + ctx_dp_rank=ho["ctx_dp_rank"], + disagg_info_endpoint=ho["ctx_endpoint"], + ) + res.remote_tail_start = ho["remote_tail_start"] + if ho["first_gen_logprobs"]: + first_lps = list(ho["first_gen_logprobs"]) + res.first_gen_log_probs = first_lps + if getattr(res, "log_probs", None) is None: + res.log_probs = [[first_lps[0]]] if len(first_lps) == 1 else [[lp] for lp in first_lps] + if ho["first_gen_logits"]: + res.first_gen_logits = ho["first_gen_logits"] + if ho["multimodal"] is not None: + res.mrope_position_ids = ho["multimodal"]["mrope_position_ids"] + res.mrope_position_deltas = ho["multimodal"]["mrope_position_deltas"] + tokens = res.output_token_ids + if tokens and not tokens[0] and ho["first_gen_tokens"]: + res.output_token_ids = [list(ho["first_gen_tokens"])] diff --git a/tensorrt_llm/executor/zmq_wire/transport.py b/tensorrt_llm/executor/zmq_wire/transport.py new file mode 100644 index 000000000000..cdfa6fd65a96 --- /dev/null +++ b/tensorrt_llm/executor/zmq_wire/transport.py @@ -0,0 +1,598 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Zero-pickle binary HMAC frame transport primitives for trtllm.engine.v1 over ZeroMQ. + +Wire layout (little-endian): + [0] magic : 1B 0x53 ('S') — serves to distinguish raw serve_engine proto frames + from Python pickle frames (which begin with 0x80). + [1] channel_tag : 1B ChannelTag enum (0x01..0x05) + [2:6] sub_tag : 4B u32_le (e.g. RPC method_id or frontend_id) + [6:-32] payload : N B serialized protobuf bytes (or empty for ShutdownSentinel) + [-32:] mac : 32B HMAC-SHA256(hmac_key, header + payload) + +HMAC is verified in constant time (hmac.compare_digest) BEFORE parsing any bytes. +In strict mode (TLLM_SERVE_ENGINE_ZMQ=strict), any pickle fallback immediately raises +StrictProtoWireError; pickle.loads/dumps is never imported or invoked on the raw proto path. +""" + +from __future__ import annotations + +import collections +import dataclasses +import enum +import hashlib +import hmac +import os +import queue +import struct +import threading +import time +from typing import TYPE_CHECKING, Callable, Optional, Protocol + +if TYPE_CHECKING: + from google.protobuf.message import Message as ProtoMessage + +# 1B magic ('S' = 0x53) + 1B channel_tag + 4B u32_le sub_tag +FRAME_MAGIC = 0x53 +_HEADER_STRUCT = struct.Struct(" str: + """Resolve TLLM_SERVE_ENGINE_ZMQ mode into one of {'off', 'auto', 'strict'}. + + Defaults to ``auto``: sends a request or result as a serve_engine.v1 frame when the contract + carries all of its fields and pickles it otherwise. ``strict`` never pickles: a request the + contract cannot carry raises in the client, a result it cannot carry fails only that request, + and the executor proxy rejects ``num_postprocess_workers > 0`` (postprocess workers send + pickled results). ``off`` / ``0`` forces the legacy pickle path. Only the rank-0 worker's + ZeroMQ IPC result queues use the wire; RPC and Ray workers do not. + """ + raw = os.environ.get(_ZMQ_WIRE_MODE_ENV_VAR, "auto") if override is None else override + key = str(raw).strip().lower() + if key not in _MODE_MAP: + raise ValueError( + f"Invalid {_ZMQ_WIRE_MODE_ENV_VAR}={raw!r}; expected one of '0'/'off', 'auto', 'strict'" + ) + return _MODE_MAP[key] + + +def is_raw_proto_frame(raw: bytes | bytearray | memoryview) -> bool: + """Return True if `raw` begins with the serve_engine raw proto magic and meets minimum length.""" + if not isinstance(raw, (bytes, bytearray, memoryview)): + return False + if len(raw) < MIN_FRAME_SIZE: + return False + return raw[0] == FRAME_MAGIC and raw[1] in _VALID_CHANNEL_TAGS + + +def pack_raw_frame( + channel_tag: int | ChannelTag, + sub_tag: int, + payload: bytes | bytearray | memoryview, + hmac_key: bytes, +) -> bytes: + """Pack header + protobuf payload + 32B HMAC-SHA256. Never calls pickle.""" + tag_int = int(channel_tag) + if tag_int not in _VALID_CHANNEL_TAGS: + raise FrameFormatError(f"Unknown channel_tag: {channel_tag!r}") + if not isinstance(hmac_key, (bytes, bytearray)) or len(hmac_key) == 0: + raise ValueError("hmac_key must be non-empty bytes") + if not (0 <= sub_tag <= 0xFFFFFFFF): + raise ValueError(f"sub_tag out of u32 range: {sub_tag}") + header = _HEADER_STRUCT.pack(FRAME_MAGIC, tag_int, sub_tag) + body_mv = memoryview(payload).cast("B") + mac_ctx = hmac.new(hmac_key, header, hashlib.sha256) + mac_ctx.update(body_mv) + mac = mac_ctx.digest() + out = bytearray(HEADER_SIZE + len(body_mv) + HMAC_SIZE) + out[:HEADER_SIZE] = header + out[HEADER_SIZE : HEADER_SIZE + len(body_mv)] = body_mv + out[HEADER_SIZE + len(body_mv) :] = mac + return bytes(out) + + +def unpack_raw_frame( + raw: bytes | bytearray | memoryview, + hmac_key: bytes, +) -> tuple[ChannelTag, int, bytes]: + """Verify HMAC-SHA256 in constant time, then unpack (ChannelTag, sub_tag, payload_bytes). + + Never calls pickle.loads. Raises FrameFormatError on structural errors and FrameAuthError + when HMAC verification fails. + """ + if not isinstance(hmac_key, (bytes, bytearray)) or len(hmac_key) == 0: + raise ValueError("hmac_key must be non-empty bytes") + if not isinstance(raw, (bytes, bytearray, memoryview)): + raise FrameFormatError(f"Expected bytes-like frame, got {type(raw).__name__}") + mv = memoryview(raw).cast("B") + n = len(mv) + if n < MIN_FRAME_SIZE: + raise FrameFormatError(f"Truncated raw proto frame: {n}B < minimum {MIN_FRAME_SIZE}B") + if mv[0] != FRAME_MAGIC: + raise FrameFormatError(f"Invalid frame magic 0x{mv[0]:02x} (expected 0x{FRAME_MAGIC:02x})") + body_end = n - HMAC_SIZE + body_with_header = mv[:body_end] + actual_mac = mv[body_end:] + expected_mac = hmac.new(hmac_key, body_with_header, hashlib.sha256).digest() + if not hmac.compare_digest(expected_mac, actual_mac): + raise FrameAuthError("serve_engine raw proto frame HMAC-SHA256 verification failed") + + _magic, tag_int, sub_tag = _HEADER_STRUCT.unpack_from(body_with_header, 0) + if tag_int not in _VALID_CHANNEL_TAGS: + raise FrameFormatError(f"Unknown channel_tag 0x{tag_int:02x} in verified frame") + payload = ( + raw[HEADER_SIZE:body_end] if isinstance(raw, bytes) else bytes(mv[HEADER_SIZE:body_end]) + ) + return ChannelTag(tag_int), sub_tag, payload + + +class _RawSocketLike(Protocol): + def send(self, data: bytes, flags: int = 0) -> object: ... + def send_multipart(self, parts: list[bytes], flags: int = 0) -> object: ... + def recv(self, flags: int = 0) -> bytes: ... + def recv_multipart(self, flags: int = 0) -> list[bytes]: ... + def poll(self, timeout: int = 0) -> int: ... + + +@dataclasses.dataclass(slots=True) +class WireStats: + """Thread-safe counters for serve_engine ZMQ wire frames and pickle fallbacks.""" + + proto_frames_sent: int = 0 + proto_frames_recv: int = 0 + control_frames_sent: int = 0 + control_frames_recv: int = 0 + pickle_fallbacks: int = 0 + + def as_dict(self) -> dict[str, int]: + return { + "proto_frames_sent": self.proto_frames_sent, + "proto_frames_recv": self.proto_frames_recv, + "control_frames_sent": self.control_frames_sent, + "control_frames_recv": self.control_frames_recv, + "pickle_fallbacks": self.pickle_fallbacks, + } + + +class InMemoryZmqQueue: + """In-memory raw-bytes transport double supporting PAIR and ROUTER/DEALER patterns. + + Exposes a pyzmq-compatible surface (send, recv, send_multipart, recv_multipart, poll) + so ZmqRawSocketWrapper can run identically with either real pyzmq sockets or pure-Python + unit tests without pyzmq. + """ + + def __init__(self, *, is_router: bool = False, name: str = "inmem") -> None: + self.is_router = is_router + self.name = name + self._peer: Optional[InMemoryZmqQueue] = None + self._peers_by_id: dict[bytes, InMemoryZmqQueue] = {} + self._identity: bytes = f"{name}-{id(self)}".encode("utf-8") + self._inbox: collections.deque[bytes | list[bytes]] = collections.deque() + self._cond = threading.Condition() + self._closed = False + + @classmethod + def make_pair( + cls, name_a: str = "client", name_b: str = "server" + ) -> tuple[InMemoryZmqQueue, InMemoryZmqQueue]: + """Create a bidirectional pair of connected queues.""" + a = cls(is_router=False, name=name_a) + b = cls(is_router=False, name=name_b) + a._peer = b + b._peer = a + return a, b + + @classmethod + def make_router(cls, name: str = "router") -> InMemoryZmqQueue: + """Create a ROUTER-like queue that multiple DEALER queues can connect to.""" + return cls(is_router=True, name=name) + + def connect_dealer(self, router: InMemoryZmqQueue, identity: Optional[bytes] = None) -> None: + """Attach this queue as a DEALER client of `router`.""" + if not router.is_router: + raise ValueError("Target queue is not a router") + if identity is not None: + self._identity = bytes(identity) + self._peer = router + router._peers_by_id[self._identity] = self + + def _enqueue_local(self, item: bytes | list[bytes]) -> None: + with self._cond: + if self._closed: + raise ServeEngineZmqError(f"Queue {self.name!r} is closed") + self._inbox.append(item) + self._cond.notify_all() + + def send(self, data: bytes, flags: int = 0) -> None: + del flags + if self._peer is None: + raise ServeEngineZmqError(f"Queue {self.name!r} is not connected to a peer") + raw = bytes(data) + if self._peer.is_router: + self._peer._enqueue_local([self._identity, raw]) + else: + self._peer._enqueue_local(raw) + + def send_multipart(self, parts: list[bytes], flags: int = 0) -> None: + del flags + if self.is_router: + if len(parts) < 2: + raise ValueError("ROUTER send_multipart requires [identity, payload, ...]") + identity = bytes(parts[0]) + peer = self._peers_by_id.get(identity) + if peer is None: + raise ServeEngineZmqError(f"Unknown ROUTER client identity: {identity!r}") + if len(parts) == 2: + peer._enqueue_local(bytes(parts[1])) + else: + peer._enqueue_local([bytes(p) for p in parts[1:]]) + else: + if self._peer is None: + raise ServeEngineZmqError(f"Queue {self.name!r} is not connected") + if self._peer.is_router: + self._peer._enqueue_local([self._identity] + [bytes(p) for p in parts]) + else: + self._peer._enqueue_local([bytes(p) for p in parts]) + + def recv(self, flags: int = 0, timeout: Optional[float] = None) -> bytes: + item = self._recv_raw(flags=flags, timeout=timeout) + if isinstance(item, list): + return item[-1] + return item + + def recv_multipart(self, flags: int = 0, timeout: Optional[float] = None) -> list[bytes]: + item = self._recv_raw(flags=flags, timeout=timeout) + if isinstance(item, list): + return item + return [item] + + def _recv_raw(self, *, flags: int = 0, timeout: Optional[float] = None) -> bytes | list[bytes]: + # Support pyzmq NOBLOCK (= 1) semantics + noblock = bool(flags & 1) + deadline = None if (timeout is None or noblock) else (time.monotonic() + timeout) + with self._cond: + while not self._inbox: + if self._closed: + raise ServeEngineZmqError(f"Queue {self.name!r} is closed") + if noblock: + raise queue.Empty() + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise queue.Empty() + self._cond.wait(timeout=remaining) + else: + self._cond.wait() + return self._inbox.popleft() + + def poll(self, timeout: int = 0) -> int: + """Poll for readability; `timeout` is in milliseconds (matching pyzmq Socket.poll).""" + deadline = None if timeout < 0 else (time.monotonic() + timeout / 1000.0) + with self._cond: + while not self._inbox: + if self._closed: + return 0 + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + return 0 + self._cond.wait(timeout=remaining) + else: + self._cond.wait() + return 1 + + def close(self) -> None: + with self._cond: + self._closed = True + self._cond.notify_all() + + +class ZmqRawSocketWrapper: + """Wrapper over a real pyzmq socket (or ZeroMqQueue.socket) OR InMemoryZmqQueue. + + Provides zero-pickle raw protobuf framing with mandatory HMAC-SHA256 verification and + strict mode enforcement. Tracks frame and fallback counters atomically. + """ + + def __init__( + self, + socket_or_queue: object, + hmac_key: bytes, + *, + mode: Optional[str] = None, + is_router: Optional[bool] = None, + stats: Optional[WireStats] = None, + pickle_send_fallback: Optional[Callable[[object, Optional[bytes]], None]] = None, + pickle_recv_fallback: Optional[Callable[[bytes], object]] = None, + ) -> None: + if not isinstance(hmac_key, (bytes, bytearray)) or len(hmac_key) == 0: + raise ValueError("hmac_key must be non-empty bytes") + self._sock = socket_or_queue + self._hmac_key = bytes(hmac_key) + self._mode = get_zmq_wire_mode(mode) + if is_router is None: + self._is_router = self._detect_router(socket_or_queue) + else: + self._is_router = bool(is_router) + self._stats = stats if stats is not None else WireStats() + self._lock = threading.Lock() + self._last_identity: Optional[bytes] = None + self._pickle_send_fallback = pickle_send_fallback + self._pickle_recv_fallback = pickle_recv_fallback + + @staticmethod + def _detect_router(sock: object) -> bool: + if isinstance(sock, InMemoryZmqQueue): + return sock.is_router + sock_type = getattr(sock, "socket_type", None) + if sock_type is None: + sock_type = getattr(sock, "type", None) + try: + import zmq + + return sock_type == zmq.ROUTER + except ImportError: + return False + + @property + def mode(self) -> str: + return self._mode + + @property + def hmac_key(self) -> bytes: + return self._hmac_key + + @property + def stats(self) -> WireStats: + return self._stats + + @property + def proto_frames_sent(self) -> int: + return self._stats.proto_frames_sent + + @property + def proto_frames_recv(self) -> int: + return self._stats.proto_frames_recv + + @property + def control_frames_sent(self) -> int: + return self._stats.control_frames_sent + + @property + def control_frames_recv(self) -> int: + return self._stats.control_frames_recv + + @property + def pickle_fallbacks(self) -> int: + return self._stats.pickle_fallbacks + + def get_wire_stats(self) -> dict[str, int]: + with self._lock: + return self._stats.as_dict() + + def _raw_socket(self) -> object: + """Return underlying raw socket if wrapped in a ZeroMqQueue-like object.""" + if hasattr(self._sock, "setup_lazily"): + self._sock.setup_lazily() + if hasattr(self._sock, "socket") and self._sock.socket is not None: + return self._sock.socket + return self._sock + + def send_proto( + self, + channel_tag: int | ChannelTag, + sub_tag: int, + message_or_bytes: ProtoMessage | bytes | bytearray | memoryview, + *, + routing_id: Optional[bytes] = None, + flags: int = 0, + ) -> bytes: + """Serialize protobuf message (or raw bytes), wrap in HMAC frame, and send.""" + if hasattr(message_or_bytes, "SerializeToString"): + payload = message_or_bytes.SerializeToString() + elif isinstance(message_or_bytes, (bytes, bytearray, memoryview)): + payload = bytes(message_or_bytes) + else: + raise TypeError( + f"send_proto expects protobuf Message or bytes, got {type(message_or_bytes).__name__}" + ) + tag = ChannelTag(int(channel_tag)) + frame = pack_raw_frame(tag, sub_tag, payload, self._hmac_key) + sock = self._raw_socket() + if self._is_router: + ident = routing_id if routing_id is not None else self._last_identity + if ident is None: + raise ValueError("ROUTER socket requires routing_id") + sock.send_multipart([ident, frame], flags=flags) + else: + sock.send(frame, flags=flags) + with self._lock: + self._stats.proto_frames_sent += 1 + if tag in (ChannelTag.CONTROL_REQUEST, ChannelTag.CONTROL_RESPONSE): + self._stats.control_frames_sent += 1 + return frame + + def send_raw_bytes( + self, raw_frame: bytes, *, routing_id: Optional[bytes] = None, flags: int = 0 + ) -> None: + """Send an already-constructed raw bytes buffer (e.g. for tamper/protocol tests).""" + sock = self._raw_socket() + if self._is_router: + ident = routing_id if routing_id is not None else self._last_identity + if ident is None: + raise ValueError("ROUTER socket requires routing_id") + sock.send_multipart([ident, raw_frame], flags=flags) + else: + sock.send(raw_frame, flags=flags) + + def send_shutdown(self, sub_tag: int = 0, *, routing_id: Optional[bytes] = None) -> bytes: + """Send a signed SHUTDOWN_SENTINEL frame without touching pickle.""" + return self.send_proto(ChannelTag.SHUTDOWN_SENTINEL, sub_tag, b"", routing_id=routing_id) + + def send_with_fallback( + self, obj: object, *, routing_id: Optional[bytes] = None, reason: str = "unspecified" + ) -> None: + """Explicitly invoke fallback send path; raises StrictProtoWireError in strict mode.""" + if self._mode == "strict": + raise StrictProtoWireError( + f"Pickle fallback forbidden in strict mode (send reason: {reason})" + ) + with self._lock: + self._stats.pickle_fallbacks += 1 + if self._pickle_send_fallback is not None: + self._pickle_send_fallback(obj, routing_id) + return + if hasattr(self._sock, "put"): + self._sock.put(obj, routing_id=routing_id) + return + raise StrictProtoWireError(f"No pickle fallback transport available (reason: {reason})") + + def poll(self, timeout_s: float = 0.0) -> bool: + """Return True if a frame is available within `timeout_s` seconds.""" + sock = self._raw_socket() + timeout_ms = -1 if timeout_s < 0 else int(timeout_s * 1000) + return bool(sock.poll(timeout_ms)) + + def recv_frame( + self, + *, + timeout: Optional[float] = None, + return_identity: bool = False, + ) -> ( + tuple[ChannelTag, int, bytes] + | tuple[str, object] + | tuple[tuple[ChannelTag, int, bytes] | tuple[str, object], Optional[bytes]] + ): + """Receive one frame. + + Returns: + For raw proto frames: (ChannelTag, sub_tag, payload_bytes) or + ((ChannelTag, sub_tag, payload_bytes), identity) when return_identity=True. + For non-proto frames: + - In strict mode: raises StrictProtoWireError immediately (never calls pickle). + - In auto/off mode: records pickle_fallbacks += 1 and delegates to + pickle_recv_fallback, returning ('pickle', obj) or (('pickle', obj), identity). + """ + sock = self._raw_socket() + identity: Optional[bytes] = None + + if isinstance(sock, InMemoryZmqQueue): + if self._is_router: + parts = sock.recv_multipart(timeout=timeout) + identity = parts[0] + raw = parts[1] + self._last_identity = identity + else: + raw = sock.recv(timeout=timeout) + else: + if timeout is not None and not sock.poll(int(timeout * 1000)): + raise queue.Empty() + if self._is_router: + identity, raw = sock.recv_multipart() + self._last_identity = identity + else: + raw = sock.recv() + + if is_raw_proto_frame(raw): + tag, sub_tag, payload = unpack_raw_frame(raw, self._hmac_key) + with self._lock: + self._stats.proto_frames_recv += 1 + if tag in (ChannelTag.CONTROL_REQUEST, ChannelTag.CONTROL_RESPONSE): + self._stats.control_frames_recv += 1 + result = (tag, sub_tag, payload) + return (result, identity) if return_identity else result + + # Non-proto frame (e.g. legacy pickled payload starting with 0x80) + if self._mode == "strict": + first_byte = raw[0] if raw else -1 + raise StrictProtoWireError( + f"Received non-proto frame (first_byte=0x{first_byte:02x}, len={len(raw)}) " + "in strict zero-pickle mode" + ) + with self._lock: + self._stats.pickle_fallbacks += 1 + if self._pickle_recv_fallback is not None: + obj = self._pickle_recv_fallback(raw) + elif hasattr(self._sock, "_parse_data"): + obj = self._sock._parse_data(raw) + else: + raise StrictProtoWireError( + "Received non-proto frame and no pickle fallback parser is configured" + ) + wrapped = ("pickle", obj) + return (wrapped, identity) if return_identity else wrapped + + def close(self) -> None: + if hasattr(self._sock, "close"): + self._sock.close() + + +__all__ = [ + "ChannelTag", + "FRAME_MAGIC", + "FrameAuthError", + "FrameFormatError", + "HEADER_SIZE", + "HMAC_SIZE", + "InMemoryZmqQueue", + "MIN_FRAME_SIZE", + "ServeEngineZmqError", + "StrictProtoWireError", + "UnsupportedCallableError", + "WireStats", + "ZmqRawSocketWrapper", + "get_zmq_wire_mode", + "is_raw_proto_frame", + "pack_raw_frame", + "unpack_raw_frame", +] diff --git a/tensorrt_llm/executor/zmq_wire/worker_bridge.py b/tensorrt_llm/executor/zmq_wire/worker_bridge.py new file mode 100644 index 000000000000..93c01962cc10 --- /dev/null +++ b/tensorrt_llm/executor/zmq_wire/worker_bridge.py @@ -0,0 +1,1071 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The rank-0 worker's side of trtllm.engine.v1 over the executor's ZeroMQ queues. + +Controlled by ``TLLM_SERVE_ENGINE_ZMQ=auto|strict|off`` (default ``auto``): + - ``worker_decode_raw_frame`` turns an authenticated ClientMessage frame from a frontend into + the GenerationRequest / CancellingRequest / Start- and StopProfileRequest objects that + ``worker_main`` already handles. + - ``worker_publish_responses`` encodes one batch of engine responses into a columnar + ServerMessage frame per frontend lane instead of pickling them. + - ``send_raw_proto`` / ``send_shutdown_sentinel`` sign and send frames; the frontend client + (tensorrt_llm/llmapi/engine_client/zmq_wire.py) uses them too. + +Disaggregated-serving requests and results are carried (disagg_codec.py); state with no +serve_engine.v1 field takes the pickle path in ``auto`` mode. In ``strict`` mode such a request +raises DisaggNotSupportedError in the client, and such a result fails only its own request. + +Process-wide counters (``get_global_wire_stats``) are appended as one JSON line to +``TLLM_SERVE_ENGINE_ZMQ_STATS_PATH`` at exit when that variable is set. +""" + +from __future__ import annotations + +import atexit +import dataclasses +import datetime +import fcntl +import json +import logging +import os +import re +import threading +import time +from pathlib import Path +from typing import Callable, Literal, Optional, Sequence + +from google.protobuf.message import Message as ProtoMessage + +from tensorrt_llm.contracts.engine.v1 import bindings as pb + +from ..ipc import RawServeEngineFrame +from .codec import ( + DecodedRequest, + capture_untracked_shm, + decode_cancel_batch, + decode_request_proto, + encode_step_responses_bytes, + shm_locations_in, + unlink_untracked_shm, +) +from .disagg_codec import unsupported_result_reason +from .transport import ( + ChannelTag, + StrictProtoWireError, + WireStats, + get_zmq_wire_mode, + pack_raw_frame, + unpack_raw_frame, +) + +logger = logging.getLogger(__name__) + +_PROFILE_SUB_TAG_START = 1 +_PROFILE_SUB_TAG_STOP = 2 + +STATS_PATH_ENV = "TLLM_SERVE_ENGINE_ZMQ_STATS_PATH" + +_GLOBAL_LOCK = threading.Lock() +_GLOBAL_STATS = WireStats() +_WORKER_FRAME_SEQ: dict[int, int] = {} +_WORKER_ITER_COUNTER = 0 +_CLIENT_FIRST_GEN_TOKEN: dict[int, int] = {} +_DUMP_REGISTERED = False + + +@dataclasses.dataclass(frozen=True, slots=True) +class _PublishHelpers: + release_undelivered_response: Callable[[object], None] + drop_refused_response: Callable[[object, object], bool] + maybe_wrap_response: Callable[[object, object], object] + error_response_cls: Callable[[int, str, int], object] + frontend_lane_index: Callable[[int, int], int] + + +# Lazy-cached hot-path helpers from base_worker / llm_request / utils (avoid repeated +# per-step local imports while preserving circular-import safety at module load time). +_PUBLISH_HELPERS: _PublishHelpers | None = None + + +def _get_publish_helpers() -> _PublishHelpers: + global _PUBLISH_HELPERS + if _PUBLISH_HELPERS is None: + from tensorrt_llm._torch.pyexecutor.llm_request import release_undelivered_response + from tensorrt_llm.executor.base_worker import _drop_refused_response, _maybe_wrap_response + from tensorrt_llm.executor.utils import ErrorResponse, frontend_lane_index + + _PUBLISH_HELPERS = _PublishHelpers( + release_undelivered_response=release_undelivered_response, + drop_refused_response=_drop_refused_response, + maybe_wrap_response=_maybe_wrap_response, + error_response_cls=ErrorResponse, + frontend_lane_index=frontend_lane_index, + ) + return _PUBLISH_HELPERS + + +def zmq_wire_enabled() -> bool: + """Return True when TLLM_SERVE_ENGINE_ZMQ is 'auto' or 'strict'.""" + return get_zmq_wire_mode() != "off" + + +def zmq_wire_strict() -> bool: + """Return True when TLLM_SERVE_ENGINE_ZMQ is 'strict'.""" + return get_zmq_wire_mode() == "strict" + + +def get_global_wire_stats() -> dict[str, int]: + with _GLOBAL_LOCK: + return _GLOBAL_STATS.as_dict() + + +def reset_global_wire_stats() -> None: + with _GLOBAL_LOCK: + _GLOBAL_STATS.proto_frames_sent = 0 + _GLOBAL_STATS.proto_frames_recv = 0 + _GLOBAL_STATS.control_frames_sent = 0 + _GLOBAL_STATS.control_frames_recv = 0 + _GLOBAL_STATS.pickle_fallbacks = 0 + + +_StatField = Literal[ + "proto_frames_sent", + "proto_frames_recv", + "control_frames_sent", + "control_frames_recv", + "pickle_fallbacks", +] + + +def _bump_stat(field: _StatField, delta: int = 1) -> None: + global _DUMP_REGISTERED + with _GLOBAL_LOCK: + if field == "proto_frames_sent": + _GLOBAL_STATS.proto_frames_sent += delta + elif field == "proto_frames_recv": + _GLOBAL_STATS.proto_frames_recv += delta + elif field == "control_frames_sent": + _GLOBAL_STATS.control_frames_sent += delta + elif field == "control_frames_recv": + _GLOBAL_STATS.control_frames_recv += delta + elif field == "pickle_fallbacks": + _GLOBAL_STATS.pickle_fallbacks += delta + else: + raise ValueError(f"Unknown wire stat field: {field!r}") + if not _DUMP_REGISTERED: + _DUMP_REGISTERED = True + atexit.register(dump_wire_stats_if_configured) + + +def reset_worker_wire_state() -> None: + """Reset per-session worker sequence and first-token caches (e.g. on worker init/shutdown).""" + global _WORKER_ITER_COUNTER + with _GLOBAL_LOCK: + _WORKER_FRAME_SEQ.clear() + _WORKER_ITER_COUNTER = 0 + _CLIENT_FIRST_GEN_TOKEN.clear() + + +def dump_wire_stats_if_configured() -> None: + """Append this process's wire stats JSON line to TLLM_SERVE_ENGINE_ZMQ_STATS_PATH if set.""" + target = os.environ.get(STATS_PATH_ENV) + if not target: + return + try: + stats = get_global_wire_stats() + stats["pid"] = os.getpid() + stats["mode"] = get_zmq_wire_mode() + p = Path(target) + p.parent.mkdir(parents=True, exist_ok=True) + line = json.dumps(stats) + "\n" + with open(p, "a", encoding="utf-8") as f: + fcntl.flock(f.fileno(), fcntl.LOCK_EX) + try: + f.write(line) + f.flush() + finally: + fcntl.flock(f.fileno(), fcntl.LOCK_UN) + except OSError as exc: + logger.warning("Failed to write serve_engine ZMQ wire stats to %s: %s", target, exc) + + +def send_raw_proto( + queue_obj: object, + channel_tag: ChannelTag, + sub_tag: int, + msg: ProtoMessage | bytes | bytearray | memoryview, + *, + strict: bool | None = None, + request_sender: object = None, +) -> int: + """Sign ``msg`` into a serve_engine.v1 frame and send it on a ZeroMqQueue / FusedIpcQueue. + + With ``request_sender`` (the proxy's batching sender) the frame is handed to the sender's + thread, the only writer of that queue. Returns the frame length, or 0 when ``strict`` is + False and the queue has no HMAC key, so that ``auto`` mode can pickle instead. + """ + zmq_q = getattr(queue_obj, "queue", queue_obj) + hmac_key = getattr(zmq_q, "hmac_key", None) + eff_strict = zmq_wire_strict() if strict is None else bool(strict) + if not hmac_key: + if eff_strict: + raise StrictProtoWireError( + "ZeroMqQueue has no hmac_key for raw serve_engine proto frame" + ) + return 0 + if isinstance(msg, (bytes, bytearray, memoryview)): + payload = msg + elif hasattr(msg, "SerializeToString"): + payload = msg.SerializeToString() + else: + payload = bytes(msg) + raw = pack_raw_frame(channel_tag, sub_tag, payload, hmac_key) + if request_sender is not None: + request_sender.send(RawServeEngineFrame(raw)) + else: + zmq_q.send_raw(raw) + if channel_tag in (ChannelTag.CONTROL_REQUEST, ChannelTag.CONTROL_RESPONSE): + _bump_stat("control_frames_sent") + else: + _bump_stat("proto_frames_sent") + return len(raw) + + +def send_shutdown_sentinel( + queue_obj: object, sub_tag: int = 0, *, strict: bool | None = None +) -> None: + """Send a SHUTDOWN_SENTINEL frame, or a pickled None in auto mode without an HMAC key.""" + zmq_q = getattr(queue_obj, "queue", queue_obj) + hmac_key = getattr(zmq_q, "hmac_key", None) + eff_strict = zmq_wire_strict() if strict is None else bool(strict) + if not hmac_key: + if eff_strict: + raise StrictProtoWireError("ZeroMqQueue has no hmac_key for shutdown sentinel") + queue_obj.put_noblock(None, retry=4) + return + raw = pack_raw_frame(ChannelTag.SHUTDOWN_SENTINEL, sub_tag, b"", hmac_key) + # Like the pickled sentinel, never block indefinitely on a peer that has already gone away, + # while allowing a bounded 500ms budget for lazy connect handshakes and transient HWM pressure. + if zmq_q.send_raw_noblock(raw, timeout_ms=500): + _bump_stat("proto_frames_sent") + + +def _build_native_sampling_params(dreq: DecodedRequest) -> object: + """Reconstruct tensorrt_llm.sampling_params.SamplingParams from DecodedRequest.""" + from tensorrt_llm.sampling_params import GuidedDecodingParams, SamplingParams + + sp_kwargs: dict[str, object] = {} + s = dreq.sampling + st = dreq.stop + out = dreq.output + + # Sampling fields + mapping_fields = ( + ("num_sequences", "n"), + ("beam_width", "best_of"), + ("temperature", "temperature"), + ("top_k", "top_k"), + ("top_p", "top_p"), + ("top_p_decay", "top_p_decay"), + ("top_p_min", "top_p_min"), + ("top_p_reset_ids", "top_p_reset_ids"), + ("min_p", "min_p"), + ("seed", "seed"), + ("repetition_penalty", "repetition_penalty"), + ("presence_penalty", "presence_penalty"), + ("frequency_penalty", "frequency_penalty"), + ("prompt_ignore_length", "prompt_ignore_length"), + ("no_repeat_ngram_size", "no_repeat_ngram_size"), + ("length_penalty", "length_penalty"), + ("early_stopping", "early_stopping"), + ("beam_search_diversity_rate", "beam_search_diversity_rate"), + ) + for src_k, dst_k in mapping_fields: + val = s.get(src_k) + if val is not None: + sp_kwargs[dst_k] = val + + bw = s.get("beam_width") + nseq = s.get("num_sequences") + bwa = s.get("beam_width_array") + if (bw is not None and bw > 1) or bool(bwa): + sp_kwargs["use_beam_search"] = True + eff_bw = bw if (bw is not None and bw > 0) else (int(bwa[0]) if bwa else 1) + sp_kwargs["best_of"] = eff_bw + sp_kwargs["n"] = s.get("num_return_beams") or eff_bw + elif nseq is not None: + sp_kwargs["n"] = nseq + sp_kwargs["best_of"] = nseq + else: + sp_kwargs.pop("best_of", None) + + if bwa: + sp_kwargs["beam_width_array"] = list(bwa) + + if s.get("logit_bias"): + # Pass sparse dict/list; materialized to embedding_bias tensor on worker if vocab_size known + sp_kwargs["_serve_engine_logit_bias"] = list(s["logit_bias"]) + + # Stop fields + if st.get("max_tokens") is not None: + sp_kwargs["max_tokens"] = st["max_tokens"] + else: + # Preserve unset max_tokens=None instead of falling back to SamplingParams default (32). + sp_kwargs["max_tokens"] = None + if st.get("min_tokens") is not None: + sp_kwargs["min_tokens"] = st["min_tokens"] + if st.get("end_id") is not None: + sp_kwargs["end_id"] = st["end_id"] + if st.get("pad_id") is not None: + sp_kwargs["pad_id"] = st["pad_id"] + if st.get("ignore_eos"): + sp_kwargs["ignore_eos"] = True + if st.get("sequences"): + single_ids = [seq[0] for seq in st["sequences"] if len(seq) == 1] + multi_seqs = [list(seq) for seq in st["sequences"] if len(seq) > 1] + if single_ids: + sp_kwargs["stop_token_ids"] = single_ids + if multi_seqs: + sp_kwargs["_stop_word_ids"] = multi_seqs + if st.get("bad_sequences"): + single_bad = [seq[0] for seq in st["bad_sequences"] if len(seq) == 1] + multi_bad = [list(seq) for seq in st["bad_sequences"] if len(seq) > 1] + if single_bad: + sp_kwargs["bad_token_ids"] = single_bad + if multi_bad: + sp_kwargs["_bad_word_ids"] = multi_bad + + if s.get("logprobs_mode"): + sp_kwargs["logprobs_mode"] = s["logprobs_mode"] + + # Output options + if out.get("logprobs") is not None: + sp_kwargs["logprobs"] = out["logprobs"] + if out["logprobs"] == 0 and out.get("logprob_rank") is False: + sp_kwargs["logprobs_simple_format"] = True + if out.get("prompt_logprobs") is not None: + sp_kwargs["prompt_logprobs"] = out["prompt_logprobs"] + tensors = out.get("tensors") or {} + if tensors.get("context_logits"): + sp_kwargs["return_context_logits"] = True + if tensors.get("generation_logits"): + sp_kwargs["return_generation_logits"] = True + if tensors.get("encoder_output"): + sp_kwargs["return_encoder_output"] = True + if tensors.get("routed_experts"): + sp_kwargs["return_routed_experts"] = True + additional_names: list[str] = [] + for name in list(tensors.get("additional_generation") or ()) + list( + tensors.get("additional_context") or () + ): + if name not in additional_names: + additional_names.append(str(name)) + if additional_names: + sp_kwargs["additional_model_outputs"] = additional_names + metrics = out.get("metrics") or {} + if ( + metrics.get("perf") + or metrics.get("timing") + or metrics.get("time_breakdown") + or metrics.get("decoding_stats") + ): + sp_kwargs["return_perf_metrics"] = True + + # Guided decoding + if dreq.guided: + g = dreq.guided + kind = g.get("kind") + val = g.get("value") + if kind == "json_schema": + sp_kwargs["guided_decoding"] = GuidedDecodingParams(json=val) + elif kind == "json_object": + sp_kwargs["guided_decoding"] = GuidedDecodingParams(json_object=bool(val)) + elif kind == "regex": + sp_kwargs["guided_decoding"] = GuidedDecodingParams(regex=val) + elif kind == "ebnf_grammar": + sp_kwargs["guided_decoding"] = GuidedDecodingParams(grammar=val) + elif kind == "structural_tag": + sp_kwargs["guided_decoding"] = GuidedDecodingParams(structural_tag=val) + elif kind == "choice": + choices = list(g.get("choices") or ()) + if choices: + pattern = "^(?:" + "|".join(re.escape(str(c)) for c in choices) + ")$" + sp_kwargs["guided_decoding"] = GuidedDecodingParams(regex=pattern) + + if "default_batched" in (dreq.logits_processors or ()): + sp_kwargs["apply_batched_logits_processor"] = True + + # Detokenize stays on frontend; worker only deals with token ids + sp_kwargs.setdefault("detokenize", False) + sp_kwargs.pop("_serve_engine_logit_bias", None) + stop_word_ids = sp_kwargs.pop("_stop_word_ids", None) + bad_word_ids = sp_kwargs.pop("_bad_word_ids", None) + + # Filter kwargs to accepted SamplingParams fields safely + import dataclasses as _dc + + valid_fields = {f.name for f in _dc.fields(SamplingParams)} + filtered = {k: v for k, v in sp_kwargs.items() if k in valid_fields} + sp = SamplingParams(**filtered) + # The contract carries stop and bad words as token sequences only. The rank-0 worker reads + # them through _get_stop_words / _get_bad_words, which return _stop_word_ids / _bad_word_ids + # only while ``stop`` / ``bad`` is set, so one non-empty placeholder string per sequence is + # assigned after validation. Stop-reason strings are resolved by the client's own + # SamplingParams, never by these placeholders. + if stop_word_ids: + sp.stop = [_WIRE_WORD_PLACEHOLDER] * len(stop_word_ids) + sp._stop_word_ids = stop_word_ids + if bad_word_ids: + sp.bad = [_WIRE_WORD_PLACEHOLDER] * len(bad_word_ids) + sp._bad_word_ids = bad_word_ids + + return sp + + +# Stands in for a stop / bad word string the contract does not carry (see above). +_WIRE_WORD_PLACEHOLDER = "" + + +def _reconstruct_generation_request(dreq: DecodedRequest, worker: object = None) -> object: + """Rebuild a native GenerationRequest on rank0 from a protocol v1.1 DecodedRequest.""" + from tensorrt_llm.conversation_params import ConversationParams + from tensorrt_llm.executor.request import GenerationRequest, LoRARequest + from tensorrt_llm.scheduling_params import SchedulingParams + + sp = _build_native_sampling_params(dreq) + + # Reconstruct sparse logit_bias as the native EmbeddingBias tuple of (token_id, bias) pairs. + # base_worker passes sparse tuples straight to PyExecutor._validate_embedding_bias, which + # preserves native bounds checks and avoids allocating a full-vocab dense float32 tensor. + sparse_lb = dreq.sampling.get("logit_bias") if dreq.sampling else None + if sparse_lb: + sp.embedding_bias = tuple((int(tid), float(bias)) for tid, bias in sparse_lb) + + # LoRA + lora_req = None + if dreq.lora: + lora_req = LoRARequest( + lora_name=dreq.lora.get("name") or f"lora-{dreq.lora.get('adapter_id', 0)}", + lora_int_id=int(dreq.lora.get("adapter_id", 0)), + lora_path=dreq.lora.get("path") or "", + lora_ckpt_source=dreq.lora.get("format") or "hf", + ) + + disagg_params = _reconstruct_disaggregated_params(dreq) + + # SchedulingParams & ConversationParams + sched_params = None + conv_params = None + priority = None + if dreq.sched: + priority = dreq.sched.get("priority") + sc_kwargs: dict[str, object] = {} + if dreq.sched.get("attention_dp_rank") is not None: + sc_kwargs["attention_dp_rank"] = dreq.sched["attention_dp_rank"] + if dreq.sched.get("attention_dp_relax") is not None: + sc_kwargs["attention_dp_relax"] = dreq.sched["attention_dp_relax"] + if dreq.sched.get("agent_hierarchy"): + sc_kwargs["agent_hierarchy"] = [ + (str(t), int(nid)) for t, nid in dreq.sched["agent_hierarchy"] + ] + if dreq.sched.get("subagent_affinity_id") is not None: + sc_kwargs["subagent_affinity_id"] = str(dreq.sched["subagent_affinity_id"]) + if sc_kwargs: + sched_params = SchedulingParams(**sc_kwargs) + conv_id = dreq.sched.get("conversation_id") + if conv_id is not None and str(conv_id).strip(): + conv_params = ConversationParams(conversation_id=str(conv_id)) + + # KvParams + cache_salt = dreq.kv.get("cache_salt") if dreq.kv else None + kv_retention = None + kv_hints = None + if dreq.kv and dreq.kv.get("retention"): + try: + from tensorrt_llm.bindings.executor import KvCacheRetentionConfig, KvCacheTransferMode + + mode_map = { + pb.request_pb2.KV_TRANSFER_MODE_DRAM: KvCacheTransferMode.DRAM, + pb.request_pb2.KV_TRANSFER_MODE_GDS: KvCacheTransferMode.GDS, + pb.request_pb2.KV_TRANSFER_MODE_POSIX_DEBUG_FALLBACK: ( + KvCacheTransferMode.POSIX_DEBUG_FALLBACK + ), + } + ret = dreq.kv["retention"] + ranges = [ + KvCacheRetentionConfig.TokenRangeRetentionConfig( + token_start=r["token_start"], + token_end=r.get("token_end"), + priority=r["priority"], + duration_ms=( + datetime.timedelta(milliseconds=int(r["duration_ms"])) + if r.get("duration_ms") is not None + else None + ), + ) + for r in ret.get("ranges", []) + ] + dec_dur = ret.get("decode_duration_ms") + kv_retention = KvCacheRetentionConfig( + token_range_retention_configs=ranges, + decode_retention_priority=ret.get("decode_priority", 35), + decode_duration_ms=( + datetime.timedelta(milliseconds=int(dec_dur)) if dec_dur is not None else None + ), + transfer_mode=mode_map.get( + int(ret.get("transfer_mode", 0)), KvCacheTransferMode.DRAM + ), + directory=ret.get("directory") or "", + ) + except (KeyError, TypeError, ValueError) as exc: + logger.warning("Failed to reconstruct KvCacheRetentionConfig: %s", exc) + raise + if dreq.kv and dreq.kv.get("hints"): + try: + from tensorrt_llm.kv_hints.protocol import KvHintsSnapshot + + hdict = dreq.kv["hints"] + extra_env = hdict.get("extra_fields") + if extra_env is not None and not isinstance(extra_env, dict): + raise ValueError( + f"kv.hints.extra_fields must be a dict, got {type(extra_env).__name__}" + ) + # Apply extra_fields first so typed protobuf fields always take precedence. + env_dict: dict[str, object] = dict(extra_env) if extra_env else {} + actions_out: list[dict[str, object]] = [] + for act in hdict.get("actions") or (): + extra_act = act.get("extra_fields") + if extra_act is not None and not isinstance(extra_act, dict): + raise ValueError( + f"kv.hints.actions[].extra_fields must be a dict, got " + f"{type(extra_act).__name__}" + ) + entry: dict[str, object] = dict(extra_act) if extra_act else {} + entry["action_id"] = act["action_id"] + entry["action_type"] = act["action_type"] + entry["action_version"] = act["action_version"] + entry["payload"] = act.get("payload", {}) + actions_out.append(entry) + env_dict["protocol_version"] = hdict["protocol_version"] + env_dict["message_id"] = hdict["message_id"] + env_dict["actions"] = actions_out + kv_hints = KvHintsSnapshot( + wire_json=json.dumps(env_dict, sort_keys=True, separators=(",", ":")).encode( + "utf-8" + ) + ) + except (KeyError, TypeError, ValueError, AttributeError) as exc: + logger.warning("Failed to reconstruct KvHintsSnapshot: %s", exc) + raise + + # Multimodal: unflatten dotted model_inputs back into nested multimodal_data + # and reconstruct MultimodalInput + MultimodalItemMetadata for native PyExecutor. + mm_params = None + if dreq.mm: + if dreq.mm.get("embeddings"): + raise StrictProtoWireError( + "Precomputed MultimodalInput.embeddings cannot be reconstructed into native " + "MultimodalParams on the rank-0 worker" + ) + from tensorrt_llm.inputs.multimodal import ( + MULTIMODAL_ENCODER_ITEM_METADATA_KEY, + MultimodalInput, + MultimodalItemMetadata, + MultimodalItemPartition, + MultimodalParams, + ) + + flat_inputs = dreq.mm.get("model_inputs") or {} + nested_mm: dict[str, object] = {} + list_buckets: dict[str, dict[int, object]] = {} + for k, v in flat_inputs.items(): + if ".__list__." in k: + base_k, idx_s = k.rsplit(".__list__.", 1) + list_buckets.setdefault(base_k, {})[int(idx_s)] = v + continue + parts = k.split(".") + cur = nested_mm + for p in parts[:-1]: + nxt = cur.setdefault(p, {}) + if not isinstance(nxt, dict): + raise ValueError(f"Conflicting multimodal model_input path at {k!r}") + cur = nxt + cur[parts[-1]] = v + for base_k, idx_map in list_buckets.items(): + ordered = [idx_map[i] for i in sorted(idx_map)] + parts = base_k.split(".") + cur = nested_mm + for p in parts[:-1]: + nxt = cur.setdefault(p, {}) + if not isinstance(nxt, dict): + raise ValueError(f"Conflicting multimodal model_input path at {base_k!r}") + cur = nxt + cur[parts[-1]] = ordered + + im_dict = dreq.mm.get("item_metadata") + if im_dict: + partitions_map: dict[str, dict[str, MultimodalItemPartition]] = {} + for p in im_dict.get("partitions") or (): + partitions_map.setdefault(p["modality"], {})[p["field"]] = MultimodalItemPartition( + item_axis=p.get("item_axis"), + item_lengths=( + tuple(p["item_lengths"]) if p.get("item_lengths") is not None else None + ), + ) + nested_mm[MULTIMODAL_ENCODER_ITEM_METADATA_KEY] = MultimodalItemMetadata( + item_refs=im_dict.get("item_refs") or (), + encoder_token_lengths=im_dict.get("encoder_token_lengths"), + output_embedding_lengths=im_dict.get("output_embedding_lengths"), + input_partitions=partitions_map, + ) + + mm_input_obj = None + items = dreq.mm.get("items") or [] + if items: + hashes = [it["hash_i32"] for it in items] + positions = [int(it["position"]) for it in items] + lengths = [int(it["length"]) for it in items] + uuids = [it.get("uuid") for it in items] + has_runs = any(it.get("run_positions") for it in items) + if has_runs: + cu = [0] + rpos: list[int] = [] + rlen: list[int] = [] + for it in items: + rpos.extend(int(x) for x in it.get("run_positions") or ()) + rlen.extend(int(x) for x in it.get("run_lengths") or ()) + cu.append(len(rpos)) + mm_input_obj = MultimodalInput.from_components( + hashes, + positions, + lengths, + mm_uuids=uuids if any(u is not None for u in uuids) else None, + mm_item_run_cu_offsets=cu, + mm_run_positions=rpos, + mm_run_lengths=rlen, + ) + else: + mm_input_obj = MultimodalInput.from_components( + hashes, + positions, + lengths, + mm_uuids=uuids if any(u is not None for u in uuids) else None, + ) + + mm_params = MultimodalParams( + multimodal_input=mm_input_obj, + multimodal_data=nested_mm, + ) + + req_kwargs: dict[str, object] = { + "prompt_token_ids": list(dreq.prompt_tokens), + "sampling_params": sp, + "encoder_input_token_ids": ( + list(dreq.encoder_input_tokens) if dreq.encoder_input_tokens else None + ), + "lora_request": lora_req, + "streaming": bool(dreq.streaming), + "kv_cache_retention_config": kv_retention, + "cache_salt": cache_salt, + "scheduling_params": sched_params, + "conversation_params": conv_params, + "multimodal_params": mm_params, + "disaggregated_params": disagg_params, + } + if priority is not None: + req_kwargs["priority"] = priority + if sp.return_perf_metrics or ( + worker is not None + and getattr(getattr(worker, "llm_args", None), "return_perf_metrics", False) + ): + from tensorrt_llm.bindings import steady_clock_now + + req_kwargs["arrival_time"] = steady_clock_now() + gen_req = GenerationRequest(**req_kwargs) + gen_req.set_id(int(dreq.handle)) + if kv_hints is not None: + gen_req.kv_hints = kv_hints + if dreq.trace: + gen_req.trace_headers = dict(dreq.trace) + return gen_req + + +def _reconstruct_disaggregated_params(dreq: DecodedRequest) -> object: + """Rebuild DisaggregatedParams from the decoded Request.phase / Request.disagg fields.""" + if dreq.disagg is None: + return None + from tensorrt_llm.disaggregated_params import DisaggregatedParams, DisaggScheduleStyle + from tensorrt_llm.executor.logprobs import Logprob + + fields = dict(dreq.disagg) + style = fields.get("schedule_style") + if style is not None: + fields["schedule_style"] = DisaggScheduleStyle(style) + first_gen_log_probs = fields.get("first_gen_log_probs") + if first_gen_log_probs: + fields["first_gen_log_probs"] = [ + {tid: Logprob(logprob=lp.logprob, rank=lp.rank) for tid, lp in entry.items()} + if isinstance(entry, dict) + else entry + for entry in first_gen_log_probs + ] + return DisaggregatedParams(**{k: v for k, v in fields.items() if v is not None}) + + +def encode_profile_control_payload(request: object) -> tuple[int, bytes]: + """Encode StartProfileRequest or StopProfileRequest into (sub_tag, JSON payload bytes).""" + from tensorrt_llm.executor.request import StartProfileRequest, StopProfileRequest + + ack_addr = getattr(request, "ack_addr", None) + ack_endpoint = None + ack_hmac_hex = None + ack_is_tuple = False + if isinstance(ack_addr, tuple) and len(ack_addr) == 2: + ack_is_tuple = True + ack_endpoint = str(ack_addr[0]) + ack_hmac_hex = ack_addr[1].hex() if isinstance(ack_addr[1], (bytes, bytearray)) else None + elif isinstance(ack_addr, str) and ack_addr: + ack_endpoint = ack_addr + + if isinstance(request, StartProfileRequest): + cmd = pb.control_pb2.StartProfileCommand(start_step=int(request.start_step or 0)) + if request.output_dir is not None: + cmd.output_dir = str(request.output_dir) + if request.num_steps is not None: + cmd.num_steps = int(request.num_steps) + if request.activities: + cmd.activities.extend(str(a) for a in request.activities) + admin_req = pb.control_pb2.AdminRequest(start_profile=cmd) + sub_tag = _PROFILE_SUB_TAG_START + elif isinstance(request, StopProfileRequest): + admin_req = pb.control_pb2.AdminRequest(stop_profile=pb.control_pb2.StopProfileCommand()) + sub_tag = _PROFILE_SUB_TAG_STOP + else: + raise TypeError(f"Unsupported profile control request: {type(request).__name__}") + + env = { + "admin_req_hex": admin_req.SerializeToString().hex(), + "ack_endpoint": ack_endpoint, + "ack_hmac_hex": ack_hmac_hex, + "ack_is_tuple": ack_is_tuple, + } + return sub_tag, json.dumps(env, separators=(",", ":")).encode("utf-8") + + +def decode_profile_control_payload(sub_tag: int, payload: bytes) -> object: + """Decode ChannelTag.CONTROL_REQUEST profile payload back into native Start/StopProfileRequest.""" + from tensorrt_llm.executor.request import StartProfileRequest, StopProfileRequest + + env = json.loads(payload.decode("utf-8")) + admin_req = pb.control_pb2.AdminRequest() + admin_req.ParseFromString(bytes.fromhex(env["admin_req_hex"])) + ack_addr: str | tuple[str, bytes | None] | None = None + if env.get("ack_endpoint") is not None: + if env.get("ack_is_tuple", True) or env.get("ack_hmac_hex") is not None: + ack_key = bytes.fromhex(env["ack_hmac_hex"]) if env.get("ack_hmac_hex") else None + ack_addr = (str(env["ack_endpoint"]), ack_key) + else: + ack_addr = str(env["ack_endpoint"]) + + cmd_kind = admin_req.WhichOneof("command") + if cmd_kind == "start_profile" or sub_tag == _PROFILE_SUB_TAG_START: + sp = admin_req.start_profile + return StartProfileRequest( + output_dir=sp.output_dir if sp.HasField("output_dir") else None, + num_steps=int(sp.num_steps) if sp.HasField("num_steps") else None, + start_step=int(sp.start_step), + activities=list(sp.activities) if sp.activities else None, + ack_addr=ack_addr, + ) + if cmd_kind == "stop_profile" or sub_tag == _PROFILE_SUB_TAG_STOP: + return StopProfileRequest(ack_addr=ack_addr) + raise StrictProtoWireError(f"Unsupported CONTROL_REQUEST admin command: {cmd_kind!r}") + + +# ============================================================================ +# Hooks invoked by worker.py and base_worker.py +# ============================================================================ + + +def worker_decode_raw_frame( + raw_bytes: bytes, + hmac_key: bytes, + worker: object = None, + *, + strict: bool | None = None, +) -> list[object]: + """Decode one verified raw serve_engine.v1 ZMQ frame on rank0 into native request objects. + + Returns a list of GenerationRequest / CancellingRequest / StartProfileRequest / + StopProfileRequest / None (shutdown sentinel). + """ + from tensorrt_llm.executor.request import CancellingRequest + + tag, sub_tag, payload = unpack_raw_frame(raw_bytes, hmac_key) + if tag == ChannelTag.CONTROL_REQUEST: + _bump_stat("control_frames_recv") + return [decode_profile_control_payload(sub_tag, payload)] + _bump_stat("proto_frames_recv") + if tag == ChannelTag.SHUTDOWN_SENTINEL: + return [None] + if tag != ChannelTag.CLIENT_MESSAGE: + raise StrictProtoWireError(f"Worker expected CLIENT_MESSAGE frame, got {tag!r}") + + cmsg = pb.session_pb2.ClientMessage() + cmsg.ParseFromString(payload) + kind = cmsg.WhichOneof("payload") + if kind == "submit_batch": + return [ + _decode_and_reconstruct_or_error(req, worker, strict=strict) + for req in cmsg.submit_batch.requests + ] + if kind == "cancel_batch": + cb = decode_cancel_batch(cmsg.cancel_batch) + return [CancellingRequest(h) for h, _reason in cb.cancels] + return [] + + +def _decode_and_reconstruct_or_error( + req_proto: ProtoMessage, worker: object, *, strict: bool | None = None +) -> object: + """Decode and rebuild one request, or return an ErrorResponse that fails only that request. + + The frame itself is already authenticated and parsed, so a per-request decode or + reconstruction failure (for example a missing SHM segment, invalid handoff, or a value + rejected by SamplingParams / LoRARequest) answers only that client with an error instead + of stopping the rank-0 worker. + """ + from google.protobuf.message import DecodeError + + from tensorrt_llm.executor.utils import ErrorResponse, RequestError + + handle = int(getattr(req_proto, "handle", 0)) + try: + dreq = decode_request_proto(req_proto, unlink_shm=True) + return _reconstruct_generation_request(dreq, worker=worker) + except ( + RequestError, + StrictProtoWireError, + DecodeError, + AttributeError, + ValueError, + TypeError, + KeyError, + IndexError, + OSError, + RuntimeError, + ) as exc: + # Clean up any SHM segments referenced by this request that were not yet unlinked before + # decode failed (already-unlinked segments raise FileNotFoundError and are ignored). + unlink_untracked_shm(shm_locations_in(req_proto)) + logger.error("Failed to decode/rebuild serve_engine.v1 request %s: %s", handle, exc) + return ErrorResponse(handle, f"Invalid request: {exc}", handle) + + +def _unsupported_response_reason(worker: object, response: object) -> Optional[str]: + """Why a result that would be published has no serve_engine.v1 field, or None. + + Responses that are never published as results are skipped: errors, responses of refused + clients (dropped), and every response while the worker has a background error (replaced by + an error response). + """ + if not hasattr(response, "has_error") or response.has_error(): + return None + if getattr(response, "client_id", None) in worker._refused_client_ids: + return None + if worker._has_background_error(): + return None + return unsupported_result_reason(getattr(response, "result", None)) + + +def _refuse_unsupported_response(worker: object, response: object, reason: str) -> object: + """Fail only the request whose result strict mode cannot carry, and stop generating it.""" + helpers = _get_publish_helpers() + + msg = ( + f"Strict serve_engine ZMQ mode cannot publish the response for request " + f"{response.client_id}: {reason}" + ) + logger.error(msg) + if not response.result.is_final: + worker._refused_client_ids.add(response.client_id) + worker.abort_request(response.client_id) + with _GLOBAL_LOCK: + _CLIENT_FIRST_GEN_TOKEN.pop(response.client_id, None) + helpers.release_undelivered_response(response) + return helpers.error_response_cls(response.client_id, msg, response.request_id) + + +def worker_publish_responses( + worker: object, + responses: Sequence[object], + *, + mode: str, + enable_postproc: bool = False, +) -> bool: + """Publish one batch of rank-0 responses as columnar ServerMessage frames, one per lane. + + Returns False, before touching any state, when the batch must take the pickle path instead: + ``mode`` is ``off``; ``auto`` with postprocess workers; ``auto`` with a response whose + disaggregated-serving state has no serve_engine.v1 field; or a queue without an HMAC key in + ``auto``. In ``strict`` mode a response with such state fails only its own request (an error + response, and the request is aborted), and a queue without an HMAC key raises. + """ + global _WORKER_ITER_COUNTER + if mode == "off": + return False + strict = mode == "strict" + + if enable_postproc and not strict: + _bump_stat("pickle_fallbacks") + return False + + if not strict: + for rsp in responses: + if _unsupported_response_reason(worker, rsp) is not None: + _bump_stat("pickle_fallbacks") + return False + + helpers = _get_publish_helpers() + release_undelivered_response = helpers.release_undelivered_response + _drop_refused_response = helpers.drop_refused_response + _maybe_wrap_response = helpers.maybe_wrap_response + ErrorResponse = helpers.error_response_cls + frontend_lane_index = helpers.frontend_lane_index + + lanes = worker.frontend_result_queues + num_lanes = len(lanes) if lanes is not None else 0 + if not strict and responses: + # Check queue HMAC availability once per touched lane before mutating worker state + # (_maybe_wrap_response / _pop_result) so an auto-mode pickle fallback sees untouched + # responses and worker._results. + if lanes is not None: + checked_lanes: set[int] = set() + for r in responses: + fid = frontend_lane_index(getattr(r, "client_id", 0), num_lanes) + if fid not in checked_lanes: + checked_lanes.add(fid) + q_obj = lanes[fid] + zmq_q = getattr(q_obj, "queue", q_obj) + if not getattr(zmq_q, "hmac_key", None): + _bump_stat("pickle_fallbacks") + return False + else: + q_obj = worker.result_queue + zmq_q = getattr(q_obj, "queue", q_obj) + if not getattr(zmq_q, "hmac_key", None): + _bump_stat("pickle_fallbacks") + return False + + by_lane: dict[int, list[object]] = {} + done_cids_by_lane: dict[int, list[int]] = {} + prompt_token_ids_by_client: dict[int, Sequence[int]] = {} + first_gen_token_by_client: dict[int, int] = {} + worker_results = getattr(worker, "_results", None) + for rsp in responses: + if isinstance(rsp, ErrorResponse): + wrapped = rsp + elif _drop_refused_response(worker, rsp): + dropped_cid = getattr(rsp, "client_id", None) + if dropped_cid is not None: + with _GLOBAL_LOCK: + _CLIENT_FIRST_GEN_TOKEN.pop(dropped_cid, None) + continue + elif strict and (reason := _unsupported_response_reason(worker, rsp)) is not None: + wrapped = _refuse_unsupported_response(worker, rsp, reason) + elif worker._has_background_error(): + release_undelivered_response(rsp) + wrapped = worker._create_error_response(rsp) + elif rsp.has_error(): + wrapped = ErrorResponse(rsp.client_id, rsp.error_msg, rsp.request_id) + else: + wrapped = _maybe_wrap_response(worker, rsp) + + cid = getattr(wrapped, "client_id", 0) + wrapper_lp = getattr(wrapped, "logprobs", None) if hasattr(wrapped, "_response") else None + has_wrapper_prompt_lp = ( + getattr(wrapper_lp, "prompt", None) is not None if wrapper_lp is not None else False + ) + inner_rsp = getattr(wrapped, "_response", wrapped) + inner_res = getattr(inner_rsp, "result", None) + + if has_wrapper_prompt_lp: + if worker_results is not None and cid not in prompt_token_ids_by_client: + gen_res = worker_results.get(cid) + gen_req = ( + getattr(gen_res, "_generation_request", None) if gen_res is not None else None + ) + p_ids = getattr(gen_req, "prompt_token_ids", None) if gen_req is not None else None + if p_ids is not None: + prompt_token_ids_by_client[cid] = p_ids + # Record the first generated token per client so streaming chunk 2+ keeps aligning + # cached prompt_logprobs[-1] against chunk 1's first token rather than the current step's. + with _GLOBAL_LOCK: + cached_tok = _CLIENT_FIRST_GEN_TOKEN.get(cid) + if cached_tok is None and inner_res is not None: + if hasattr(inner_res, "_result") and isinstance( + getattr(inner_res, "_result", None), bytes + ): + inner_res.deserialize() + out_toks = getattr(inner_res, "output_token_ids", None) + if out_toks and out_toks[0]: + cached_tok = int(out_toks[0][0]) + with _GLOBAL_LOCK: + _CLIENT_FIRST_GEN_TOKEN[cid] = cached_tok + if cached_tok is not None: + first_gen_token_by_client[cid] = cached_tok + + fid = frontend_lane_index(cid, num_lanes) if lanes is not None else 0 + lane_list = by_lane.get(fid) + if lane_list is None: + by_lane[fid] = [wrapped] + else: + lane_list.append(wrapped) + + # Defer dropping the worker's record until the lane's frame has been encoded and sent. + is_req_done = ( + getattr(inner_res, "is_request_done", getattr(inner_res, "is_final", False)) + if inner_res is not None + else False + ) + is_done = isinstance(wrapped, ErrorResponse) or ( + hasattr(wrapped, "has_error") and (wrapped.has_error() or bool(is_req_done)) + ) + if is_done: + done_cids_by_lane.setdefault(fid, []).append(cid) + + with _GLOBAL_LOCK: + _WORKER_ITER_COUNTER += 1 + iter_num = _WORKER_ITER_COUNTER + lane_seqs: dict[int, int] = {} + for fid in by_lane: + seq = _WORKER_FRAME_SEQ.get(fid, 0) + 1 + _WORKER_FRAME_SEQ[fid] = seq + lane_seqs[fid] = seq + + for fid, lane_rsps in by_lane.items(): + seq = lane_seqs[fid] + sent = 0 + written_shm: list[ProtoMessage] = [] + try: + with capture_untracked_shm() as captured_shm: + smsg_bytes = encode_step_responses_bytes( + lane_rsps, + frame_seq=seq, + iter_first=iter_num, + iter_last=iter_num, + emit_time_ns=time.monotonic_ns(), + prompt_token_ids_by_client=prompt_token_ids_by_client or None, + first_gen_token_by_client=first_gen_token_by_client or None, + ) + written_shm = list(captured_shm) + target_q = lanes[fid] if lanes is not None else worker.result_queue + sent = send_raw_proto(target_q, ChannelTag.SERVER_MESSAGE, fid, smsg_bytes, strict=True) + finally: + if sent == 0 and written_shm: + unlink_untracked_shm(written_shm) + for cid in done_cids_by_lane.get(fid, ()): + worker._pop_result(cid) + with _GLOBAL_LOCK: + _CLIENT_FIRST_GEN_TOKEN.pop(cid, None) + return True diff --git a/tensorrt_llm/grpc/openengine/proto/manifest.json b/tensorrt_llm/grpc/openengine/proto/manifest.json index 759e9941eb61..31a6361079df 100644 --- a/tensorrt_llm/grpc/openengine/proto/manifest.json +++ b/tensorrt_llm/grpc/openengine/proto/manifest.json @@ -14,7 +14,7 @@ "grpc_gencode": "1.67.1" }, "runtime_floors": { - "protobuf": "6.30.2", + "protobuf": "6.33.6", "grpcio": "1.73.1" }, "source": { diff --git a/tensorrt_llm/llmapi/engine_client/proxy.py b/tensorrt_llm/llmapi/engine_client/proxy.py index d39de8b29365..12ade1af6f36 100644 --- a/tensorrt_llm/llmapi/engine_client/proxy.py +++ b/tensorrt_llm/llmapi/engine_client/proxy.py @@ -42,7 +42,7 @@ from ..._torch.pyexecutor.llm_request import release_undelivered_response from ..._utils import customized_gc_thresholds, mpi_rank, nvtx_range_debug from ...executor.executor import GenerationExecutor -from ...executor.ipc import FusedIpcQueue, IpcQueue +from ...executor.ipc import FusedIpcQueue, IpcQueue, RawServeEngineFrame from ...executor.postproc_worker import PostprocWorker from ...executor.prompt_tail import PromptTailPolicy from ...executor.request import (CancellingRequest, GenerationRequest, @@ -63,6 +63,7 @@ from ...executor.worker import GenerationExecutorWorker, worker_main from ...executor.worker_process_monitor import (WorkerProcessIdentity, WorkerProcessMonitor) +from ...executor.zmq_wire.transport import get_zmq_wire_mode from ..llm_args import TorchLlmArgs from ..mpi_session import (MpiCommSession, MpiPoolSession, MpiSession, RemoteMpiCommSessionClient, @@ -91,6 +92,10 @@ class _RequestSender: request queue's socket, which is not thread-safe, and it also sends the worker's shutdown sentinel. + With TLLM_SERVE_ENGINE_ZMQ=auto|strict, ``send`` also takes a signed + serve_engine.v1 frame (RawServeEngineFrame), which the thread sends on its + own, in order with the pickled payloads around it. + Trade-off: the sender thread must take the GIL before it can send. While the submitting thread keeps running Python, for example a busy trtllm-serve event loop, a lone request can wait up to the interpreter's @@ -99,9 +104,13 @@ class _RequestSender: MAX_BATCH_SIZE = 1024 - def __init__(self, request_queue: IpcQueue, error_queue: Queue): + def __init__(self, + request_queue: IpcQueue, + error_queue: Queue, + serve_engine_wire_mode: str = "off"): self._request_queue = request_queue self._error_queue = error_queue + self._serve_engine_wire_mode = serve_engine_wire_mode self._pending = collections.deque() self._cond = threading.Condition() self._closed = False @@ -113,8 +122,8 @@ def __init__(self, request_queue: IpcQueue, error_queue: Queue): # interpreter teardown, when module globals may already be None. self._is_finalizing = sys.is_finalizing - def send(self, payload: bytes) -> None: - """Queue a pickled request for the worker. + def send(self, payload: Union[bytes, RawServeEngineFrame]) -> None: + """Queue a pickled request or a serve_engine.v1 frame for the worker. Payloads sent after ``close`` are dropped: the proxy is shutting down. """ @@ -171,30 +180,74 @@ def _run(self) -> None: self._stopping = True send_sentinel = self._send_sentinel break - batch = [ - self._pending.popleft() - for _ in range(min(len(self._pending), self.MAX_BATCH_SIZE)) - ] + raw_frame = None + batch = [] + if isinstance(self._pending[0], RawServeEngineFrame): + raw_frame = self._pending.popleft() + else: + while (self._pending and len(batch) < self.MAX_BATCH_SIZE + and not isinstance(self._pending[0], + RawServeEngineFrame)): + batch.append(self._pending.popleft()) try: - self._request_queue.put(batch) + if raw_frame is not None: + self._request_queue.send_raw(raw_frame.data) + else: + self._request_queue.put(batch) except Exception as e: - # The payloads are already pickled, so this is a transport + # The payloads are already serialized, so this is a transport # error, which the proxy treats as fatal. self._error_queue.put_nowait(e) if send_sentinel: # A bare None, not a batch: the worker stops at a top-level None. try: - self._request_queue.put_noblock(None, retry=4) + _send_shutdown_sentinel(self._request_queue, + self._serve_engine_wire_mode) except Exception as e: self._error_queue.put_nowait(e) -def _create_request_sender(request_queue: IpcQueue, - error_queue: Queue) -> Optional[_RequestSender]: +def _send_shutdown_sentinel(request_queue: IpcQueue, + serve_engine_wire_mode: str) -> None: + """Tell the rank-0 worker to stop reading requests.""" + if serve_engine_wire_mode == "off": + request_queue.put_noblock(None, retry=4) + return + from ...executor.zmq_wire.worker_bridge import ( + dump_wire_stats_if_configured, send_shutdown_sentinel) + try: + send_shutdown_sentinel(request_queue, + strict=(serve_engine_wire_mode == "strict")) + finally: + dump_wire_stats_if_configured() + + +def _create_request_sender( + request_queue: IpcQueue, + error_queue: Queue, + serve_engine_wire_mode: str = "off") -> Optional[_RequestSender]: """Return a batching request sender if TRTLLM_PROXY_BATCH_REQUESTS=1.""" if os.getenv("TRTLLM_PROXY_BATCH_REQUESTS", "0") != "1": return None - return _RequestSender(request_queue, error_queue) + return _RequestSender(request_queue, error_queue, serve_engine_wire_mode) + + +def _serve_engine_postproc_config( + config: PostprocWorkerConfig, + serve_engine_wire_mode: str) -> PostprocWorkerConfig: + """Reject postprocess workers in strict serve_engine.v1 mode. + + Postprocess workers send pickled results to the proxy, which strict mode + rejects. Callers such as OpenAIServer read the postprocess workers' output + whenever ``num_postprocess_workers`` is set, so the combination fails here + instead of silently running without them. + """ + if serve_engine_wire_mode == "strict" and config.num_postprocess_workers > 0: + raise ValueError( + "TLLM_SERVE_ENGINE_ZMQ=strict does not support postprocess workers " + f"(num_postprocess_workers={config.num_postprocess_workers}); set " + "num_postprocess_workers=0 or use TLLM_SERVE_ENGINE_ZMQ=auto") + return config class GenerationExecutorProxy(GenerationExecutor): @@ -208,6 +261,8 @@ class GenerationExecutorProxy(GenerationExecutor): _WORKER_SHUTDOWN_TIMEOUT_S = 180.0 # Set from gen_prompt_tail_tokens; None sends full prompts. _prompt_tail: Optional[PromptTailPolicy] = None + # TLLM_SERVE_ENGINE_ZMQ mode, read once in __init__. + _serve_engine_wire_mode: str = "off" def __init__( self, @@ -219,10 +274,18 @@ def __init__( postproc_worker_config: Optional[PostprocWorkerConfig] = None, is_llm_executor: Optional[bool] = None, ) -> None: + # Set first: __del__ reads it even when __init__ raises early. + self.workers_started = False proxy_start = time.perf_counter() logger.info(f"[startup][pid={os.getpid()}] executor_proxy: start") postproc_worker_config = postproc_worker_config or PostprocWorkerConfig( ) + self._serve_engine_wire_mode = get_zmq_wire_mode() + if self._serve_engine_wire_mode != "off": + from .zmq_wire import reset_proxy_wire_state + reset_proxy_wire_state(0) + postproc_worker_config = _serve_engine_postproc_config( + postproc_worker_config, self._serve_engine_wire_mode) super().__init__( num_postprocess_workers=postproc_worker_config. num_postprocess_workers, @@ -231,7 +294,6 @@ def __init__( is_llm_executor=is_llm_executor, ) - self.workers_started = False self.worker_cls = worker_cls mpi_process_pre_spawned: bool = get_spawn_proxy_process_env() @@ -581,6 +643,11 @@ def _error_monitor_loop(self) -> None: # fine. Wakes immediately if _shutdown_event is set. self._shutdown_event.wait(timeout=5.0) + def _serve_engine_queue_kwargs(self) -> dict[str, bool]: + return dict( + serve_engine_wire_enabled=self._serve_engine_wire_mode != "off", + serve_engine_wire_strict=self._serve_engine_wire_mode == "strict") + def _setup_queues(self) -> WorkerCommIpcAddrs: frontend_result_addrs = None if self._num_frontends > 1: @@ -596,20 +663,26 @@ def _setup_queues(self) -> WorkerCommIpcAddrs: self.request_queue = IpcQueue(request_addr, is_server=False, socket_type=zmq.PUSH, - name="proxy_request_queue") + name="proxy_request_queue", + **self._serve_engine_queue_kwargs()) self._request_sender = _create_request_sender( - self.request_queue, self._error_queue) - self.result_queue = FusedIpcQueue(frontend_result_addrs[0], - is_server=True, - fuse_message=False, - socket_type=zmq.PULL, - name="proxy_result_queue") + self.request_queue, self._error_queue, + self._serve_engine_wire_mode) + self.result_queue = FusedIpcQueue( + frontend_result_addrs[0], + is_server=True, + fuse_message=False, + socket_type=zmq.PULL, + name="proxy_result_queue", + **self._serve_engine_queue_kwargs()) else: request_addr = None self.request_queue = IpcQueue(is_server=True, - name="proxy_request_queue") + name="proxy_request_queue", + **self._serve_engine_queue_kwargs()) self._request_sender = _create_request_sender( - self.request_queue, self._error_queue) + self.request_queue, self._error_queue, + self._serve_engine_wire_mode) # TODO[chunweiy]: Unify IpcQueue and FusedIpcQueue # Use PULL mode when enable_postprocess_parallel as there are # multiple senders from multiple processes. @@ -618,7 +691,8 @@ def _setup_queues(self) -> WorkerCommIpcAddrs: fuse_message=False, socket_type=zmq.PULL if self.enable_postprocess_parallel else zmq.PAIR, - name="proxy_result_queue") + name="proxy_result_queue", + **self._serve_engine_queue_kwargs()) self.worker_init_status_queue = IpcQueue( is_server=True, socket_type=zmq.ROUTER, @@ -861,6 +935,15 @@ def dispatch_result_task(self) -> bool: # benefit from zmq.asyncio.Context if (res := self.result_queue.get()) is None: return False # shutdown the thread + if isinstance(res, RawServeEngineFrame): + from .zmq_wire import proxy_decode_raw_frame + res = proxy_decode_raw_frame(res.data, + self.result_queue.queue.hmac_key, + frontend_id=getattr( + self, "_frontend_id", 0), + results_map=self._results) + if res is None: + return False # shutdown sentinel async_queues = [] event_loop = None @@ -1197,7 +1280,23 @@ def _send_request(self, request) -> None: it is put on ``request_queue`` directly. Either way the worker receives the request as it is now, and a request that cannot be pickled raises here. + + With TLLM_SERVE_ENGINE_ZMQ=auto|strict the request is sent as a + serve_engine.v1 frame instead when it can be encoded. Requests stay + pickled while postprocess workers run: the frame does not carry the + PostprocParams those workers read. """ + postproc_cfg = getattr(self, "postproc_config", None) + postproc_enabled = bool( + postproc_cfg.enabled) if postproc_cfg is not None else False + if self._serve_engine_wire_mode != "off" and not postproc_enabled: + from .zmq_wire import proxy_send_request + if proxy_send_request(self.request_queue, + request, + mode=self._serve_engine_wire_mode, + frontend_id=getattr(self, "_frontend_id", 0), + request_sender=self._request_sender): + return if self._request_sender is None: self.request_queue.put(request) else: @@ -1214,7 +1313,8 @@ def _close_request_sender(self, send_sentinel: bool = False) -> None: send_sentinel = self._request_sender.close( timeout=5.0, send_sentinel=send_sentinel) if send_sentinel: - self.request_queue.put_noblock(None, retry=4) + _send_shutdown_sentinel(self.request_queue, + self._serve_engine_wire_mode) def _get_next_client_id(self) -> int: client_id = super()._get_next_client_id() @@ -1328,6 +1428,9 @@ def shutdown(self): # owning ``_profile_control_executor`` was just drained above. if self.profile_ack_queue is not None: self.profile_ack_queue.close() + if self._serve_engine_wire_mode != "off": + from .zmq_wire import reset_proxy_wire_state + reset_proxy_wire_state(getattr(self, "_frontend_id", 0)) self.workers_started = False if self._owns_mpi_session: @@ -1382,8 +1485,15 @@ def submit(self, request: GenerationRequest) -> GenerationResult: if tail: request._prompt_tail_tokens = tail - with nvtx_range_debug("request_queue.put"): - self._send_request(request) + sent = False + try: + with nvtx_range_debug("request_queue.put"): + self._send_request(request) + sent = True + finally: + # A request that never reached the worker gets no response. + if not sent: + self._results.pop(request.id, None) self._handle_background_error() @@ -1671,6 +1781,8 @@ def __init__( postproc_worker_config: Optional[PostprocWorkerConfig] = None, is_llm_executor: Optional[bool] = None, ) -> None: + # Set first: __del__ reads it even when __init__ raises early. + self.workers_started = False num_lanes = len(attach_info["result_addrs"]) if not 0 < frontend_id < num_lanes: raise ValueError( @@ -1678,6 +1790,12 @@ def __init__( f"use ids 1..{num_lanes - 1} (id 0 is the launcher)") postproc_worker_config = postproc_worker_config or PostprocWorkerConfig( ) + self._serve_engine_wire_mode = get_zmq_wire_mode() + if self._serve_engine_wire_mode != "off": + from .zmq_wire import reset_proxy_wire_state + reset_proxy_wire_state(frontend_id) + postproc_worker_config = _serve_engine_postproc_config( + postproc_worker_config, self._serve_engine_wire_mode) # Deliberately skip GenerationExecutorProxy.__init__: it creates an # MPI session, launches workers, and registers the pre_shutdown # atexit hook that emits the engine shutdown sentinel. @@ -1708,7 +1826,6 @@ def __init__( f"(frontend {frontend_id})") self._results: Dict[int, GenerationResult] = {} self.garbage_collection_gen0_threshold = None - self.workers_started = False self.dispatch_result_thread: Optional[ManagedThread] = None # Must be None: OpenAIServer reads the resource_governor_queue # property at init; the governor lives with the launcher only. @@ -1719,15 +1836,17 @@ def __init__( (attach_info["request_addr"], hmac_key), is_server=False, socket_type=zmq.PUSH, - name=f"frontend_{frontend_id}_request_queue") - self._request_sender = _create_request_sender(self.request_queue, - self._error_queue) + name=f"frontend_{frontend_id}_request_queue", + **self._serve_engine_queue_kwargs()) + self._request_sender = _create_request_sender( + self.request_queue, self._error_queue, self._serve_engine_wire_mode) self.result_queue = FusedIpcQueue( (attach_info["result_addrs"][frontend_id], hmac_key), is_server=True, fuse_message=False, socket_type=zmq.PULL, - name=f"frontend_{frontend_id}_result_queue") + name=f"frontend_{frontend_id}_result_queue", + **self._serve_engine_queue_kwargs()) # Stats / KV events / disagg params share the rank0 worker's stats # RPC server with the launcher (ROUTER socket, multi-client). @@ -1777,6 +1896,9 @@ def shutdown(self): self.rpc_client.close() self.rpc_client = None self._worker_process_monitor.close() + if self._serve_engine_wire_mode != "off": + from .zmq_wire import reset_proxy_wire_state + reset_proxy_wire_state(self._frontend_id) # The dispatch thread blocks on result_queue.get(); it is a daemon # ManagedThread that exits with the process or on the worker's # per-lane None sentinel at engine teardown. Closing its socket from diff --git a/tensorrt_llm/llmapi/engine_client/zmq_wire.py b/tensorrt_llm/llmapi/engine_client/zmq_wire.py new file mode 100644 index 000000000000..9c5c3092e8b4 --- /dev/null +++ b/tensorrt_llm/llmapi/engine_client/zmq_wire.py @@ -0,0 +1,509 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The executor proxy's side of trtllm.engine.v1 over the executor's ZeroMQ queues. + +Controlled by ``TLLM_SERVE_ENGINE_ZMQ=auto|strict|off`` (default ``auto``): + - ``proxy_send_request`` encodes a GenerationRequest / CancellingRequest / + Start- or StopProfileRequest into a signed ClientMessage frame instead of pickling it. + - ``proxy_decode_raw_frame`` decodes a ServerMessage frame from the rank-0 worker into the + responses ``GenerationResult`` consumes. + +Disaggregated-serving requests are carried; a request whose disaggregated-serving state has no +serve_engine.v1 field takes the pickle path in ``auto`` mode and raises DisaggNotSupportedError +in ``strict`` mode. +""" + +from __future__ import annotations + +import datetime +import struct +import threading +from typing import Mapping, Optional, Sequence + +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc +from tensorrt_llm.executor.logprobs import LogProbsResult +from tensorrt_llm.executor.request import ( + CancellingRequest, + GenerationRequest, + StartProfileRequest, + StopProfileRequest, +) +from tensorrt_llm.executor.utils import ErrorResponse, ResponseWrapper +from tensorrt_llm.executor.zmq_wire.codec import ( + ZmqStepResponse, + decode_step_server_message_bytes, + encode_cancel_batch, + encode_generation_requests, + shm_locations_in, + unlink_untracked_shm, +) +from tensorrt_llm.executor.zmq_wire.disagg_codec import ( + DisaggNotSupportedError, + unsupported_request_reason, +) +from tensorrt_llm.executor.zmq_wire.transport import ( + ChannelTag, + StrictProtoWireError, + unpack_raw_frame, +) +from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + _bump_stat, + encode_profile_control_payload, + send_raw_proto, +) + +# Highest frame_seq each frontend lane has consumed; reported back in every ClientMessage. +_PROXY_SEQ_LOCK = threading.Lock() +_PROXY_CONSUMED_SEQ: dict[int, int] = {} + + +def reset_proxy_wire_state(frontend_id: int | None = None) -> None: + """Reset per-session proxy consumed frame sequence tracking on proxy init/shutdown.""" + with _PROXY_SEQ_LOCK: + if frontend_id is None: + _PROXY_CONSUMED_SEQ.clear() + else: + _PROXY_CONSUMED_SEQ.pop(frontend_id, None) + + +def proxy_send_request( + request_queue: object, + request: object, + *, + mode: str, + frontend_id: int = 0, + request_sender: object = None, +) -> bool: + """Send ``request`` as a serve_engine.v1 frame. + + Returns True if the frame was sent and False if the caller must pickle the request instead, + which happens only in ``auto`` mode; in ``strict`` mode such a request raises + StrictProtoWireError. + """ + if mode == "off": + return False + strict = mode == "strict" + + if isinstance(request, GenerationRequest): + reason = unsupported_request_reason(request) + if reason is not None: + if strict: + raise DisaggNotSupportedError( + f"Strict serve_engine ZMQ mode cannot send request {request.id}: {reason}" + ) + _bump_stat("pickle_fallbacks") + return False + + with _PROXY_SEQ_LOCK: + consumed_seq = _PROXY_CONSUMED_SEQ.get(frontend_id, 0) + try: + if isinstance(request, GenerationRequest): + cmsg = encode_generation_requests( + [request], consumed_frame_seq=consumed_seq, strict=strict + ) + sent = 0 + try: + sent = send_raw_proto( + request_queue, + ChannelTag.CLIENT_MESSAGE, + frontend_id, + cmsg, + strict=strict, + request_sender=request_sender, + ) + finally: + # The worker unlinks the SHM segments of a frame it reads; a frame that was not + # sent leaves them to us. A frame dropped by a closed request sender, or one the + # worker never reads because it exits first, still leaves them in /dev/shm. + if sent == 0: + unlink_untracked_shm(shm_locations_in(cmsg)) + if sent == 0: + _bump_stat("pickle_fallbacks") + return False + return True + if isinstance(request, CancellingRequest): + cmsg = encode_cancel_batch( + [int(request.id)], + reason=pb.common_pb2.CANCEL_REASON_CLIENT_DISCONNECTED, + consumed_frame_seq=consumed_seq, + ) + sent = send_raw_proto( + request_queue, + ChannelTag.CLIENT_MESSAGE, + frontend_id, + cmsg, + strict=strict, + request_sender=request_sender, + ) + if sent == 0: + _bump_stat("pickle_fallbacks") + return False + return True + if isinstance(request, (StartProfileRequest, StopProfileRequest)): + sub_tag, ctrl_payload = encode_profile_control_payload(request) + sent = send_raw_proto( + request_queue, + ChannelTag.CONTROL_REQUEST, + sub_tag, + ctrl_payload, + strict=strict, + request_sender=request_sender, + ) + if sent == 0: + _bump_stat("pickle_fallbacks") + return False + return True + if strict: + raise StrictProtoWireError( + f"Strict serve_engine ZMQ mode does not allow legacy pickled request {type(request).__name__}" + ) + _bump_stat("pickle_fallbacks") + return False + except StrictProtoWireError: + # Includes UnsupportedCallableError (a Python logits processor) and + # DisaggNotSupportedError: fields the contract cannot carry. + if strict: + raise + _bump_stat("pickle_fallbacks") + return False + except (AttributeError, KeyError, OverflowError, TypeError, ValueError, struct.error) as exc: + if strict: + raise StrictProtoWireError( + f"Failed to encode {type(request).__name__} over strict serve_engine ZMQ wire: {exc}" + ) from exc + _bump_stat("pickle_fallbacks") + return False + + +def proxy_decode_raw_frame( + raw_bytes: bytes, + hmac_key: bytes, + *, + frontend_id: int = 0, + results_map: Mapping[int, object] | None = None, +) -> Optional[Sequence[ZmqStepResponse | ErrorResponse | ResponseWrapper]]: + """Decode one verified raw serve_engine.v1 ServerMessage ZMQ frame on the proxy. + + Returns a sequence of ZmqStepResponse / ErrorResponse / ResponseWrapper, or None on + SHUTDOWN_SENTINEL. + """ + tag, _sub_tag, payload = unpack_raw_frame(raw_bytes, hmac_key) + _bump_stat("proto_frames_recv") + if tag == ChannelTag.SHUTDOWN_SENTINEL: + return None + if tag != ChannelTag.SERVER_MESSAGE: + raise StrictProtoWireError(f"Proxy expected SERVER_MESSAGE frame, got {tag!r}") + + fseq, step_rsps, pre_finalized = decode_step_server_message_bytes( + payload, + results_map=results_map, + unlink_shm=True, + ) + if fseq is None: + return [] + with _PROXY_SEQ_LOCK: + _PROXY_CONSUMED_SEQ[frontend_id] = fseq + if pre_finalized: + return step_rsps + + # Coalesce multi-beam rows belonging to the same request into one multi-beam + # ZmqStepResponse ONLY when beam search is active for that request. Non-beam + # n > 1 / best_of > 1 rows carry independent sequences indexed by sequence_index + # and MUST remain separate ZmqStepResponse objects so GenerationResult._handle_sequence + # updates each sequence independently and never smears is_final across sequences. + def _is_beam_row(cid: int, res_obj: object) -> bool: + if results_map is not None: + gen_res = results_map.get(cid) + sp = getattr(gen_res, "sampling_params", None) + if sp is not None: + return bool(getattr(sp, "use_beam_search", False)) + # Fallback when results_map is not supplied (unit tests / offline decode): + # beam rows carry replace_from != NO_REPLACE_FROM. + return ( + res_obj is not None + and getattr(res_obj, "replace_from", wc.NO_REPLACE_FROM) != wc.NO_REPLACE_FROM + ) + + grouped: list[ZmqStepResponse] = [] + beam_group_by_key: dict[int, ZmqStepResponse] = {} + for sr in step_rsps: + if sr.has_error(): + grouped.append(sr) + continue + res = sr.result + key = sr.client_id + prev = beam_group_by_key.get(key) + if ( + prev is not None + and prev.result is not None + and res is not None + and res.sequence_index != prev.result.sequence_index + and (_is_beam_row(key, res) or _is_beam_row(key, prev.result)) + ): + prev_res = prev.result + prev_beams = len(prev_res.output_token_ids) + add_beams = len(res.output_token_ids) + prev_res.output_token_ids.extend(res.output_token_ids) + prev_res.finish_reasons.extend(res.finish_reasons) + if res.cum_log_probs is not None: + if prev_res.cum_log_probs is None: + prev_res.cum_log_probs = [None] * prev_beams + prev_res.cum_log_probs.extend(res.cum_log_probs) + elif prev_res.cum_log_probs is not None: + prev_res.cum_log_probs.extend([None] * add_beams) + if res.log_probs is not None: + if prev_res.log_probs is None: + prev_res.log_probs = [None] * prev_beams + prev_res.log_probs.extend(res.log_probs) + elif prev_res.log_probs is not None: + prev_res.log_probs.extend([None] * add_beams) + prev_res.is_request_done = prev_res.is_request_done or res.is_request_done + prev_res.is_final = bool(prev_res.is_request_done) + continue + if _is_beam_row(key, res): + beam_group_by_key[key] = sr + grouped.append(sr) + + out: list[ZmqStepResponse | ErrorResponse | ResponseWrapper] = [] + for sr in grouped: + if sr.has_error(): + out.append(ErrorResponse(sr.client_id, sr.error_msg, sr.request_id)) + continue + res = sr.result + lp_res = None + perf_dict = None + if res is not None: + sp = None + if results_map is not None: + gen_res = results_map.get(sr.client_id) + sp = getattr(gen_res, "sampling_params", None) + # GenerationResult._handle_response sets self._done = response_result.is_final and + # proxy.py pops self._results[cid] on res.result.is_final. Always reflect + # whole-request completion (ROW_FLAG_REQUEST_DONE) in res.is_final so an + # early-finishing sequence or beam does not prematurely finalize the request. + res.is_final = bool(res.is_request_done) + if ( + sp is not None + and getattr(sp, "logprobs_simple_format", False) + and res.log_probs is not None + ): + res.log_probs = [ + None + if seq_lps is None + else _collapse_logprobs_to_simple( + seq_lps, + seq_toks[-len(seq_lps) :] + if seq_lps and len(seq_lps) < len(seq_toks) + else seq_toks, + ) + for seq_lps, seq_toks in zip(res.log_probs, res.output_token_ids) + ] + if isinstance(res.prompt_logprobs, dict) and "entries" in res.prompt_logprobs: + prompt_entries = res.prompt_logprobs["entries"] + if sp is not None and getattr(sp, "prompt_logprobs_simple_format", False): + prompt_entries = _collapse_logprobs_to_simple( + prompt_entries, res.prompt_logprobs.get("ids") + ) + lp_res = LogProbsResult(prompt=prompt_entries) + base_s = 0.0 + if isinstance(res.request_perf_metrics, dict): + timing_dict = res.request_perf_metrics + base_s = float(timing_dict.get("host_accept_ns", 0)) * 1e-9 + # A synthetic timing anchor carrying only host_accept_ns (no timing fields) + # may be emitted solely for time_breakdown_metrics; avoid synthesizing a + # bogus RequestPerfMetrics when no actual timing fields are present. + has_perf = bool(getattr(sp, "return_perf_metrics", False)) or any( + timing_dict.get(k) + for k in ( + "first_scheduled_us", + "first_token_us", + "last_token_us", + "kv_cache_hit_rate", + "first_iter", + "last_iter", + "kv_blocks", + "kv_transfer_start_us", + "kv_transfer_end_us", + "kv_transfer_bytes", + ) + ) + if has_perf: + perf_dict = _timing_dict_to_event_metrics(timing_dict) + res.request_perf_metrics = _build_native_perf_metrics(timing_dict) + elif res.time_breakdown_metrics is not None or ( + sp is not None and not getattr(sp, "return_perf_metrics", False) + ): + res.request_perf_metrics = None + else: + perf_dict = _timing_dict_to_event_metrics(timing_dict) + res.request_perf_metrics = _build_native_perf_metrics(timing_dict) + if isinstance(res.time_breakdown_metrics, dict): + res.time_breakdown_metrics = _build_native_time_breakdown( + res.time_breakdown_metrics, base_s=base_s + ) + if lp_res is not None or perf_dict: + out.append(ResponseWrapper(sr, lp_res, perf_dict)) + else: + out.append(sr) + return out + + +def _collapse_logprobs_to_simple( + entries: Sequence[object], target_ids: Sequence[int] | None = None +) -> list[float]: + """Collapse per-token {token_id: Logprob} dicts into flat list[float] for *_simple_format.""" + out: list[float] = [] + for idx, entry in enumerate(entries): + if isinstance(entry, (int, float)): + out.append(float(entry)) + elif isinstance(entry, dict) and entry: + lp_obj = None + if target_ids is not None and idx < len(target_ids): + lp_obj = entry.get(int(target_ids[idx])) + if lp_obj is None: + lp_obj = next(iter(entry.values())) + out.append(float(getattr(lp_obj, "logprob", lp_obj))) + else: + out.append(float("nan")) + return out + + +def _build_native_time_breakdown( + tb: Mapping[str, object], *, base_s: float = 0.0 +) -> dict[str, object]: + """Convert decoded TimeBreakdown dict into native LlmResult.time_breakdown_metrics keys.""" + if "step_metrics" in tb or "ctx_chunk_metrics" in tb: + return dict(tb) + + def _to_native_step(st: Mapping[str, object]) -> dict[str, object]: + fwd_start_us = int(st.get("forward_start_us", 0)) + fwd_end_us = int(st.get("forward_end_us", 0)) + smp_start_us = int(st.get("sample_start_us", 0)) + smp_end_us = int(st.get("sample_end_us", 0)) + # Intermediate chunked-prefill chunks skip the sampler and record sample_*_time = None, + # which proto encodes as 0 while forward_end_us > 0; avoid fabricating base_s for them. + sampler_skipped = smp_start_us == 0 and smp_end_us == 0 and fwd_end_us > 0 + d: dict[str, object] = { + "forward_start_time": base_s + float(fwd_start_us) * 1e-6, + "forward_end_time": base_s + float(fwd_end_us) * 1e-6, + "sample_start_time": None if sampler_skipped else base_s + float(smp_start_us) * 1e-6, + "sample_end_time": None if sampler_skipped else base_s + float(smp_end_us) * 1e-6, + "token_time": base_s + float(st.get("token_us", 0)) * 1e-6, + "gpu_forward_time": float(st.get("gpu_forward_ms", 0.0)), + "gpu_sample_time": float(st.get("gpu_sample_ms", 0.0)), + } + if "iter" in st: + d["iter"] = int(st["iter"]) + return d + + out: dict[str, object] = {} + steps = tb.get("steps") + if steps: + out["step_metrics"] = [_to_native_step(s) for s in steps] + chunks = tb.get("ctx_chunks") + if chunks: + out["ctx_chunk_metrics"] = [_to_native_step(s) for s in chunks] + if "ctx_gpu_forward_ms" in tb: + out["ctx_gpu_forward_time"] = float(tb["ctx_gpu_forward_ms"]) + if "ctx_gpu_sample_ms" in tb: + out["ctx_gpu_sample_time"] = float(tb["ctx_gpu_sample_ms"]) + return out + + +def _milestone_seconds(base_s: float, delta_us: int, *, reached: bool) -> float: + """Reconstruct an absolute timestamp in seconds, returning 0.0 when unreached.""" + if not reached: + return 0.0 + return base_s + float(delta_us) * 1e-6 + + +def _timing_dict_to_event_metrics(timing: Mapping[str, object]) -> dict[object, float]: + """Convert decoded RequestTiming dict into native RequestEventTiming -> float seconds dict.""" + from tensorrt_llm.metrics.enums import RequestEventTiming + + base_s = float(timing.get("host_accept_ns", 0)) * 1e-9 + sched_us = int(timing.get("first_scheduled_us", 0) or 0) + ft_us = int(timing.get("first_token_us", 0) or 0) + lt_us = int(timing.get("last_token_us", 0) or 0) + first_iter = int(timing.get("first_iter", 0) or 0) + last_iter = int(timing.get("last_iter", 0) or 0) + # proto3 uint64 cannot distinguish delta==0 (immediate scheduling) from unset/unreached. + # Treat a zero delta as reached when a later milestone or iteration confirms execution. + lt_reached = lt_us > 0 + ft_reached = ft_us > 0 or lt_reached + sched_reached = sched_us > 0 or ft_reached or first_iter > 0 or last_iter > 0 + out: dict[object, float] = { + RequestEventTiming.ARRIVAL_TIME: base_s, + RequestEventTiming.FIRST_SCHEDULED_TIME: _milestone_seconds( + base_s, sched_us, reached=sched_reached + ), + RequestEventTiming.FIRST_TOKEN_TIME: _milestone_seconds(base_s, ft_us, reached=ft_reached), + RequestEventTiming.LAST_TOKEN_TIME: _milestone_seconds(base_s, lt_us, reached=lt_reached), + } + if "kv_transfer_start_us" in timing: + out[RequestEventTiming.KV_CACHE_TRANSFER_START] = ( + base_s + float(timing["kv_transfer_start_us"]) * 1e-6 + ) + if "kv_transfer_end_us" in timing: + out[RequestEventTiming.KV_CACHE_TRANSFER_END] = ( + base_s + float(timing["kv_transfer_end_us"]) * 1e-6 + ) + if "kv_transfer_bytes" in timing: + out[RequestEventTiming.KV_CACHE_SIZE] = float(timing["kv_transfer_bytes"]) + return out + + +def _build_native_perf_metrics(timing: Mapping[str, object]) -> object: + """Convert decoded RequestTiming dict into bindings.executor.RequestPerfMetrics if available.""" + from tensorrt_llm.bindings import executor as tllm + + rpm = tllm.RequestPerfMetrics() + base_s = float(timing.get("host_accept_ns", 0)) * 1e-9 + sched_us = int(timing.get("first_scheduled_us", 0) or 0) + ft_us = int(timing.get("first_token_us", 0) or 0) + lt_us = int(timing.get("last_token_us", 0) or 0) + first_iter = int(timing.get("first_iter", 0) or 0) + last_iter = int(timing.get("last_iter", 0) or 0) + lt_reached = lt_us > 0 + ft_reached = ft_us > 0 or lt_reached + sched_reached = sched_us > 0 or ft_reached or first_iter > 0 or last_iter > 0 + rpm.timing_metrics.arrival_time = datetime.timedelta(seconds=base_s) + rpm.timing_metrics.first_scheduled_time = datetime.timedelta( + seconds=_milestone_seconds(base_s, sched_us, reached=sched_reached) + ) + rpm.timing_metrics.first_token_time = datetime.timedelta( + seconds=_milestone_seconds(base_s, ft_us, reached=ft_reached) + ) + rpm.timing_metrics.last_token_time = datetime.timedelta( + seconds=_milestone_seconds(base_s, lt_us, reached=lt_reached) + ) + if "kv_transfer_start_us" in timing: + rpm.timing_metrics.kv_cache_transfer_start = datetime.timedelta( + seconds=base_s + float(timing["kv_transfer_start_us"]) * 1e-6 + ) + if "kv_transfer_end_us" in timing: + rpm.timing_metrics.kv_cache_transfer_end = datetime.timedelta( + seconds=base_s + float(timing["kv_transfer_end_us"]) * 1e-6 + ) + if "kv_transfer_bytes" in timing: + rpm.timing_metrics.kv_cache_size = int(timing["kv_transfer_bytes"]) + rpm.first_iter = int(timing.get("first_iter", 0)) + rpm.last_iter = int(timing.get("last_iter", 0)) + rpm.iter = int(timing.get("last_iter", 0)) + kvb = timing.get("kv_blocks") + if kvb: + reused = int(kvb.get("reused", 0)) + missed = int(kvb.get("missed", 0)) + rpm.kv_cache_metrics.num_total_allocated_blocks = int(kvb.get("allocated", 0)) + rpm.kv_cache_metrics.num_new_allocated_blocks = int(kvb.get("new_blocks", 0)) + rpm.kv_cache_metrics.num_reused_blocks = reused + rpm.kv_cache_metrics.num_missed_blocks = missed + hit_rate = timing.get("kv_cache_hit_rate") + if hit_rate is not None and float(hit_rate) != 0.0: + rpm.kv_cache_metrics.kv_cache_hit_rate = float(hit_rate) + elif reused + missed > 0: + rpm.kv_cache_metrics.kv_cache_hit_rate = float(reused) / float(reused + missed) + elif timing.get("kv_cache_hit_rate"): + rpm.kv_cache_metrics.kv_cache_hit_rate = float(timing["kv_cache_hit_rate"]) + return rpm diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index bf92c53348de..cc95da70a831 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -377,6 +377,9 @@ l0_cpu: - unittest/_torch/weight_sharing - unittest/api_stability - unittest/bindings + - unittest/contracts/test_engine_v1_contract.py + - unittest/executor/test_zmq_wire.py + - unittest/executor/test_zmq_wire_disagg.py - unittest/disaggregated - unittest/docs/test_llmapi_reference_docs.py - unittest/dynamo @@ -403,6 +406,7 @@ l0_cpu: - unittest/executor/test_stop_word_side_output_trim.py - unittest/executor/test_stop_word_streaming_text.py - unittest/executor/test_ray_stub.py + - unittest/executor/test_engine_wire_cpp.py - unittest/executor/test_layering.py - unittest/executor/test_generation_request_array_prompt.py - unittest/executor/test_postproc_worker_request_end.py diff --git a/tests/unittest/contracts/test_engine_v1_contract.py b/tests/unittest/contracts/test_engine_v1_contract.py new file mode 100644 index 000000000000..51891b607ff2 --- /dev/null +++ b/tests/unittest/contracts/test_engine_v1_contract.py @@ -0,0 +1,465 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""CPU unit tests for the frozen trtllm.engine.v1 (v1.1) contract and columnar wire_codec.""" + +from __future__ import annotations + +import hashlib +import json +import math +from pathlib import Path + +import pytest + +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc + +pytestmark = pytest.mark.cpu_only + +_REPO_ROOT = Path(__file__).resolve().parents[3] +_CONTRACT_DIR = _REPO_ROOT / "tensorrt_llm" / "contracts" / "engine" / "v1" +_PROTO_ROOT = _REPO_ROOT / "contracts" +_EXPECTED_PROTOS = ( + "capabilities", + "common", + "control", + "disagg", + "output", + "request", + "session", + "stats", +) + + +def test_manifest_and_proto_tree_digest_match() -> None: + manifest = json.loads((_CONTRACT_DIR / "manifest.json").read_text(encoding="utf-8")) + assert manifest["contract"] == "trtllm.engine.v1" + assert manifest["protocol_version"] == {"major": 1, "minor": 1} + assert pb.PROTOCOL_MAJOR == 1 + assert pb.PROTOCOL_MINOR == 1 + + per_file: dict[str, str] = {} + h = hashlib.sha256() + for name in sorted(_EXPECTED_PROTOS): + rel = f"engine/v1/{name}.proto" + digest = hashlib.sha256((_PROTO_ROOT / rel).read_bytes()).hexdigest() + per_file[rel] = digest + h.update(f"{rel}\0{digest}\n".encode("utf-8")) + + computed_digest = f"sha256-tree-v1:{h.hexdigest()}" + assert manifest["files"] == per_file + assert manifest["tree_digest"] == computed_digest + assert pb.TREE_DIGEST == computed_digest + + +def test_v1_1_additions_and_reserved_fields() -> None: + # Request field 52 (thinking_budget) was moved to client layer and reserved. + req_desc = pb.request_pb2.Request.DESCRIPTOR + assert 52 not in req_desc.fields_by_number + assert "thinking_budget" not in req_desc.fields_by_name + + # v1.1 P-2: sampled_at_unix_nanos on LoadInfo (15) and DpRankLoad (8). + assert "sampled_at_unix_nanos" in pb.control_pb2.LoadInfo.DESCRIPTOR.fields_by_name + assert pb.control_pb2.LoadInfo.DESCRIPTOR.fields_by_name["sampled_at_unix_nanos"].number == 15 + assert "sampled_at_unix_nanos" in pb.control_pb2.DpRankLoad.DESCRIPTOR.fields_by_name + assert pb.control_pb2.DpRankLoad.DESCRIPTOR.fields_by_name["sampled_at_unix_nanos"].number == 8 + + # v1.1 P-3: MultimodalCapabilities.image_routing_version (10); + # io_option_keys / processor_option_keys live solely in Capabilities.ext.namespaces. + mm_cap = pb.capabilities_pb2.MultimodalCapabilities.DESCRIPTOR.fields_by_name + assert "image_routing_version" in mm_cap + assert mm_cap["image_routing_version"].number == 10 + assert "io_option_keys" not in mm_cap + assert "processor_option_keys" not in mm_cap + + # RequestTiming omits redundant queue_us (first_scheduled_us is the single queueing metric). + rt_fields = pb.output_pb2.RequestTiming.DESCRIPTOR.fields_by_name + assert "first_scheduled_us" in rt_fields + assert "queue_us" not in rt_fields + + # OutputTensorKind omits unused OUTPUT_TENSOR_KIND_FIRST_GEN_LOGITS. + otk_values = pb.output_pb2.OutputTensorKind.DESCRIPTOR.values_by_name + assert "OUTPUT_TENSOR_KIND_FIRST_GEN_LOGITS" not in otk_values + + # KvHints / KvHintAction use extra_fields (not unknown_fields) to avoid protobuf >=4.22 C++ clash. + for msg_cls in (pb.request_pb2.KvHints, pb.request_pb2.KvHintAction): + fnames = msg_cls.DESCRIPTOR.fields_by_name + assert "extra_fields" in fnames + assert "unknown_fields" not in fnames + + # AdminCapabilities / AdminRequest / AdminResponse carry memory_report (field 7 / 9 / 3). + assert "memory_report" in pb.capabilities_pb2.AdminCapabilities.DESCRIPTOR.fields_by_name + assert ( + pb.capabilities_pb2.AdminCapabilities.DESCRIPTOR.fields_by_name["memory_report"].number == 7 + ) + assert "get_memory_report" in pb.control_pb2.AdminRequest.DESCRIPTOR.fields_by_name + assert pb.control_pb2.AdminRequest.DESCRIPTOR.fields_by_name["get_memory_report"].number == 9 + assert "memory_report" in pb.control_pb2.AdminResponse.DESCRIPTOR.fields_by_name + assert pb.control_pb2.AdminResponse.DESCRIPTOR.fields_by_name["memory_report"].number == 3 + mr_fields = pb.control_pb2.MemoryReportInfo.DESCRIPTOR.fields_by_name + assert "reports_json" in mr_fields and "blob" in mr_fields + + # v1.1 P-4: KvEventsCapability.sources (3). + kv_cap = pb.capabilities_pb2.KvEventsCapability.DESCRIPTOR.fields_by_name + assert "sources" in kv_cap + assert kv_cap["sources"].number == 3 + + # Preprocessed ModelInput scalar branches (bool, i64, f64, string) and matching capability enum. + mi_fields = pb.request_pb2.ModelInput.DESCRIPTOR.fields_by_name + for fname, fnum in ( + ("bool_value", 5), + ("i64_value", 6), + ("f64_value", 7), + ("string_value", 8), + ): + assert fname in mi_fields + assert mi_fields[fname].number == fnum + mi_enum = pb.capabilities_pb2.ModelInputValueKind.DESCRIPTOR.values_by_name + for ename, enum_val in ( + ("MODEL_INPUT_VALUE_KIND_BOOL", 4), + ("MODEL_INPUT_VALUE_KIND_I64", 5), + ("MODEL_INPUT_VALUE_KIND_F64", 6), + ("MODEL_INPUT_VALUE_KIND_STRING", 7), + ): + assert ename in mi_enum + assert mi_enum[ename].number == enum_val + + # Chunked-context prefill stats on PromptInfo (9) and FinalInfo (10). + cc_fields = pb.output_pb2.ContextChunkStats.DESCRIPTOR.fields_by_name + assert cc_fields["computed_tokens"].number == 1 + assert cc_fields["first_begin"].number == 2 + assert cc_fields["num_chunks"].number == 3 + pi_fields = pb.output_pb2.PromptInfo.DESCRIPTOR.fields_by_name + assert "ctx_chunks" in pi_fields and pi_fields["ctx_chunks"].number == 9 + fi_fields = pb.output_pb2.FinalInfo.DESCRIPTOR.fields_by_name + assert "ctx_chunks" in fi_fields and fi_fields["ctx_chunks"].number == 10 + + +def test_columnar_frame_encode_decode_roundtrip() -> None: + extra0 = pb.output_pb2.RowExtra( + prompt_info=pb.output_pb2.PromptInfo( + engine_request_id=1001, + prompt_len=16, + max_tokens=32, + ) + ) + rows = [ + wc.FrameRow( + handle=101, + seq=0, + tokens=[10, 11], + finish=pb.common_pb2.FINISH_REASON_NOT_FINISHED, + row_flags=wc.ROW_FLAG_FIRST_ROW | wc.ROW_FLAG_HAS_EXTRA, + stop_index=wc.NO_STOP_INDEX, + replace_from=wc.NO_REPLACE_FROM, + cum_logprob=-1.25, + decoding_iter=1, + cached_tokens=8, + lp_sampled=[-0.5, -0.75], + lp_rank=[1, 2], + lp_topk=[[(10, -0.5), (12, -1.2)], [(11, -0.75)]], + extra=extra0, + ), + wc.FrameRow( + handle=102, + seq=1, + tokens=[42], + finish=pb.common_pb2.FINISH_REASON_END_ID, + row_flags=wc.ROW_FLAG_SEQ_FINAL | wc.ROW_FLAG_REQUEST_DONE, + stop_index=0, + replace_from=0, + cum_logprob=None, + decoding_iter=4, + cached_tokens=0, + lp_sampled=[-0.1], + lp_rank=[1], + lp_topk=[[(42, -0.1)]], + extra=None, + ), + ] + + frame = wc.encode_frame(rows, frame_seq=7, iter_first=10, iter_last=11, emit_time_ns=123456) + raw = frame.SerializeToString() + + parsed = pb.output_pb2.Frame() + parsed.ParseFromString(raw) + decoded = wc.decode_frame(parsed) + + assert len(decoded) == 2 + r0, r1 = decoded + assert r0.handle == 101 + assert r0.seq == 0 + assert r0.tokens == [10, 11] + assert r0.finish == pb.common_pb2.FINISH_REASON_NOT_FINISHED + assert r0.row_flags == (wc.ROW_FLAG_FIRST_ROW | wc.ROW_FLAG_HAS_EXTRA) + assert math.isclose(r0.cum_logprob, -1.25, rel_tol=1e-6) + assert r0.decoding_iter == 1 + assert r0.cached_tokens == 8 + assert r0.lp_rank == [1, 2] + assert r0.lp_topk[0][0][0] == 10 + assert r0.extra is not None + assert r0.extra.prompt_info.prompt_len == 16 + + assert r1.handle == 102 + assert r1.seq == 1 + assert r1.tokens == [42] + assert r1.finish == pb.common_pb2.FINISH_REASON_END_ID + assert r1.stop_index == 0 + assert r1.replace_from == 0 + assert r1.cum_logprob is None + assert r1.extra is None + + +def test_columnar_frame_rejects_corrupt_columns() -> None: + frame = wc.encode_frame( + [wc.FrameRow(handle=1, tokens=[5], finish=0, row_flags=0)], + frame_seq=1, + iter_first=1, + ) + bad_handle = pb.output_pb2.Frame() + bad_handle.CopyFrom(frame) + bad_handle.handle = b"\x01\x02" + with pytest.raises(ValueError, match="handle"): + wc.decode_frame(bad_handle) + + +def test_signed_handoff_unsigned_and_hmac_roundtrip() -> None: + ho = pb.disagg_pb2.KvHandoff( + disagg_request_id=99, + ctx_instance_id="ctx-0", + ctx_endpoint="127.0.0.1:9000", + transfer_backend="nixl", + schedule_style=pb.common_pb2.SCHEDULE_STYLE_CONTEXT_FIRST, + first_gen_tokens=[7], + ) + unsigned = wc.sign_handoff(ho, key=None) + assert unsigned.mac == b"" + unpacked = wc.verify_and_unpack_handoff(unsigned, require_signature=False) + assert unpacked.disagg_request_id == 99 + assert list(unpacked.first_gen_tokens) == [7] + + key = b"secret-test-key" + signed = wc.sign_handoff(ho, key=key, key_id="k1") + assert len(signed.mac) == 32 + unpacked_signed = wc.verify_and_unpack_handoff(signed, keys={"k1": key}, require_signature=True) + assert unpacked_signed.ctx_endpoint == "127.0.0.1:9000" + + +def _load_contract_generator() -> object: + import importlib.util + + script = _REPO_ROOT / "scripts" / "generate_contract_protos.py" + spec = importlib.util.spec_from_file_location("generate_contract_protos", script) + assert spec is not None and spec.loader is not None + gen = importlib.util.module_from_spec(spec) + spec.loader.exec_module(gen) + return gen + + +def test_generated_bindings_not_checked_in_and_manifest_check(tmp_path: Path) -> None: + import subprocess + + gen = _load_contract_generator() + + # Verify the installed bindings have the expected proto package. + assert pb.request_pb2.Request.DESCRIPTOR.full_name == "trtllm.engine.v1.Request" + + # When running inside a git checkout, verify _generated/ is never checked in. + if (_REPO_ROOT / ".git").exists(): + tracked = subprocess.run( + [ + "git", + "-C", + str(_REPO_ROOT), + "ls-files", + "tensorrt_llm/contracts/engine/v1/_generated", + ], + capture_output=True, + text=True, + check=True, + ) + assert tracked.stdout.strip() == "", f"_generated/ must not be tracked: {tracked.stdout}" + + # Verify default manifest check succeeds without requiring a protoc binary. + assert gen.main(["--check"]) == 0 + # Passing an explicit missing --out-dir must fail rather than silently returning 0. + assert gen.main(["--check", "--out-dir", str(tmp_path / "missing")]) == 1 + + # Generator refuses to overwrite a directory without its ownership marker. + unowned = tmp_path / "unowned" + unowned.mkdir() + (unowned / "keep.txt").write_text("keep\n", encoding="utf-8") + dummy_artifacts = { + "__init__.py": b"", + ".contracts-generated": b"Owned\n", + } + with pytest.raises(RuntimeError, match="missing .contracts-generated"): + gen.write_artifacts(unowned, dummy_artifacts) + assert (unowned / "keep.txt").read_text(encoding="utf-8") == "keep\n" + + # Replacing a symlinked output directory unlinks the symlink without modifying its target. + target = tmp_path / "cmake_generated_py" + target.mkdir() + (target / "sentinel.txt").write_text("cmake-owned\n", encoding="utf-8") + link = tmp_path / "linked_generated" + link.symlink_to(target, target_is_directory=True) + gen.write_artifacts(link, dummy_artifacts) + assert not link.is_symlink() and link.is_dir() + assert (link / ".contracts-generated").is_file() + assert (target / "sentinel.txt").read_text(encoding="utf-8") == "cmake-owned\n" + + +def test_generator_roundtrip_and_import_isolation(tmp_path: Path) -> None: + import subprocess + import sys + + gen = _load_contract_generator() + try: + gen._resolve_protoc_cmd(None, include_grpc=False) + except RuntimeError as exc: + pytest.skip(f"No compatible protoc compiler available in test environment: {exc}") + + # Generate into an isolated package tree and actually import the generated modules + # in a clean subprocess (separate descriptor pool from the already-imported wheel). + pkg_root = tmp_path / "iso_pkg" + out_dir = pkg_root / "iso_gen" + pkg_root.mkdir() + artifacts = gen.generate_to_dir( + _PROTO_ROOT, + out_dir, + bindings_pkg="iso_gen", + ) + expected_names = { + "__init__.py", + ".contracts-generated", + *(f"{name}_pb2.py" for name in _EXPECTED_PROTOS), + *(f"{name}_pb2.pyi" for name in _EXPECTED_PROTOS), + } + assert set(artifacts.keys()) == expected_names + assert gen.main(["--check", "--out-dir", str(out_dir)]) == 0 + + probe = subprocess.run( + [ + sys.executable, + "-c", + ( + "import sys; sys.path.insert(0, sys.argv[1]); " + "from iso_gen import request_pb2, output_pb2, disagg_pb2; " + "assert request_pb2.Request.DESCRIPTOR.full_name == 'trtllm.engine.v1.Request'; " + "assert output_pb2.Frame.DESCRIPTOR.full_name == 'trtllm.engine.v1.Frame'; " + "assert disagg_pb2.KvHandoff.DESCRIPTOR.full_name == 'trtllm.engine.v1.KvHandoff'" + ), + str(pkg_root), + ], + capture_output=True, + text=True, + check=False, + ) + assert probe.returncode == 0, f"Fresh import of generated bindings failed:\n{probe.stderr}" + + +class _FakeCudaStorage: + def __init__(self, ref_counter_handle: bytes) -> None: + self._ref_counter_handle = ref_counter_handle + + def _share_cuda_( + self, + ) -> tuple[int, bytes, int, int, bytes, int, bytes, bool]: + return (0, b"\x11" * 64, 16, 0, self._ref_counter_handle, 0, b"", False) + + +class _FakeCudaTensor: + is_cuda: bool = True + dtype: str = "torch.float32" + shape: tuple[int, ...] = (4,) + + def __init__(self, ref_counter_handle: bytes) -> None: + self._storage = _FakeCudaStorage(ref_counter_handle) + + def detach(self) -> _FakeCudaTensor: + return self + + def contiguous(self) -> _FakeCudaTensor: + return self + + def untyped_storage(self) -> _FakeCudaStorage: + return self._storage + + def storage_offset(self) -> int: + return 0 + + def element_size(self) -> int: + return 4 + + def numel(self) -> int: + return 4 + + +def test_make_cuda_ipc_ref_skips_caching_allocator_refcounter() -> None: + # Non-empty ref_counter_handle (info[4]) cannot be carried in CudaIpcLocation; + # make_cuda_ipc_ref must return None so callers fall back to SHM/INLINE/BLOB_FETCH. + fake_with_refcnt = _FakeCudaTensor(ref_counter_handle=b"\x22" * 64) + assert wc.make_cuda_ipc_ref(fake_with_refcnt) is None + + # Positive control: empty ref_counter_handle builds a TensorRef with cuda_ipc set. + fake_without_refcnt = _FakeCudaTensor(ref_counter_handle=b"") + res = wc.make_cuda_ipc_ref(fake_without_refcnt) + assert res is not None + ref, keepalive = res + assert keepalive is fake_without_refcnt + assert ref.WhichOneof("location") == "cuda_ipc" + assert ref.cuda_ipc.device == 0 + assert ref.cuda_ipc.mem_handle == b"\x11" * 64 + assert ref.cuda_ipc.size == 16 + + +def test_open_cuda_ipc_ref_raises_not_implemented(monkeypatch: pytest.MonkeyPatch) -> None: + import sys + import types + + def _unexpected_new_shared_cuda(*_args: object, **_kwargs: object) -> object: + raise AssertionError("_new_shared_cuda must not be called without refcounter metadata") + + class _FakeTorchModule(types.ModuleType): + cuda: types.SimpleNamespace + UntypedStorage: types.SimpleNamespace + + def __init__(self) -> None: + super().__init__("torch") + self.cuda = types.SimpleNamespace(device_count=lambda: 1) + self.UntypedStorage = types.SimpleNamespace( + _new_shared_cuda=_unexpected_new_shared_cuda + ) + + monkeypatch.setitem(sys.modules, "torch", _FakeTorchModule()) + + valid_ref = pb.common_pb2.TensorRef( + dtype=pb.common_pb2.DTYPE_F32, + shape=[4], + cuda_ipc=pb.common_pb2.CudaIpcLocation( + device=0, + mem_handle=b"\x33" * 64, + offset=0, + size=16, + event_handle=b"", + ), + device=0, + ) + with pytest.raises(NotImplementedError, match="refcounter"): + wc.open_cuda_ipc_ref(valid_ref) + + # Validation still rejects malformed handles with ValueError before NotImplementedError. + bad_ref = pb.common_pb2.TensorRef( + dtype=pb.common_pb2.DTYPE_F32, + shape=[4], + cuda_ipc=pb.common_pb2.CudaIpcLocation( + device=0, + mem_handle=b"short", + offset=0, + size=16, + event_handle=b"", + ), + device=0, + ) + with pytest.raises(ValueError, match="mem_handle"): + wc.open_cuda_ipc_ref(bad_ref) diff --git a/tests/unittest/executor/test_engine_wire_cpp.py b/tests/unittest/executor/test_engine_wire_cpp.py new file mode 100644 index 000000000000..9c05ef5f1e44 --- /dev/null +++ b/tests/unittest/executor/test_engine_wire_cpp.py @@ -0,0 +1,1041 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The native trtllm.engine.v1 wire codec against the pure-Python one. + +Both backends get the same inputs: encoders must produce identical bytes, decoders +identical rows, and malformed input must be rejected by both. +""" + +from __future__ import annotations + +import math +import random +import struct +from types import ModuleType +from typing import Callable, TypeVar + +import pytest +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.message import Message as ProtoMessage + +from tensorrt_llm.contracts.engine.v1 import _native +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc + +pytestmark = pytest.mark.cpu_only + +_MsgT = TypeVar("_MsgT", bound=ProtoMessage) + + +def _require_native() -> ModuleType: + native = _native.native_module() + if native is not None: + return native + try: + import tensorrt_llm.bindings # noqa: F401 + except ImportError: + pytest.skip("neither the bindings module nor engine_wire_standalone imports") + pytest.fail("tensorrt_llm.bindings imports but has no internal.engine_wire") + + +@pytest.fixture(scope="module") +def native() -> ModuleType: + return _require_native() + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +_NAN_KEY = "nan" + + +def _norm_float(v: float | None) -> str | bytes | None: + if v is None: + return None + return _NAN_KEY if math.isnan(v) else struct.pack(" tuple[object, ...]: + return ( + row.handle, + list(row.tokens), + row.finish, + row.row_flags, + row.seq, + row.stop_index, + row.replace_from, + _norm_float(row.cum_logprob), + row.decoding_iter, + row.cached_tokens, + None if row.lp_sampled is None else [_norm_float(v) for v in row.lp_sampled], + None if row.lp_rank is None else list(row.lp_rank), + None + if row.lp_topk is None + else [[(cid, _norm_float(lp)) for cid, lp in cands] for cands in row.lp_topk], + None if row.extra is None else row.extra.SerializeToString(), + ) + + +def _frame_key(decoded: wc.DecodedFrame) -> tuple[object, ...]: + return ( + decoded.frame_seq, + decoded.iter_first, + decoded.iter_last, + decoded.emit_time_ns, + [_row_key(r) for r in decoded.rows], + [m.SerializeToString() for m in decoded.acks], + [m.SerializeToString() for m in decoded.iteration_stats], + [m.SerializeToString() for m in decoded.lora_set_changed], + ) + + +def _f32(rng: random.Random) -> float: + return struct.unpack(" bool: + is_repeated = getattr(field, "is_repeated", None) + if is_repeated is not None: + return bool(is_repeated) + return field.label == FieldDescriptor.LABEL_REPEATED + + +def _random_message(message: _MsgT, rng: random.Random, depth: int = 0) -> _MsgT: + """Fill a protobuf message with random values for every kind of field it has.""" + for field in message.DESCRIPTOR.fields: + if rng.random() < 0.4: + continue + if field.type == FieldDescriptor.TYPE_MESSAGE: + if field.message_type.GetOptions().map_entry or depth >= 2: + continue + if _is_repeated(field): + for _ in range(rng.randint(0, 2)): + _random_message(getattr(message, field.name).add(), rng, depth + 1) + else: + _random_message(getattr(message, field.name), rng, depth + 1) + getattr(message, field.name).SetInParent() + continue + values = [_random_scalar(field, rng) for _ in range(rng.randint(0, 3))] + if _is_repeated(field): + getattr(message, field.name).extend(values) + elif values: + setattr(message, field.name, values[0]) + return message + + +def _random_scalar(field: FieldDescriptor, rng: random.Random) -> int | float | bool | str | bytes: + t = field.type + if t == FieldDescriptor.TYPE_ENUM: + return rng.choice(field.enum_type.values).number + if t == FieldDescriptor.TYPE_BOOL: + return rng.random() < 0.5 + if t == FieldDescriptor.TYPE_STRING: + return rng.choice(["", "a", "λ-text", "x" * 40]) + if t == FieldDescriptor.TYPE_BYTES: + return bytes(rng.randrange(256) for _ in range(rng.randint(0, 12))) + if t in (FieldDescriptor.TYPE_FLOAT,): + return _f32(rng) + if t in (FieldDescriptor.TYPE_DOUBLE,): + return rng.uniform(-1e6, 1e6) + if t in ( + FieldDescriptor.TYPE_UINT32, + FieldDescriptor.TYPE_FIXED32, + ): + return rng.choice([0, 1, rng.randrange(2**32)]) + if t in (FieldDescriptor.TYPE_UINT64, FieldDescriptor.TYPE_FIXED64): + return rng.choice([0, 1, rng.randrange(2**64)]) + if t in ( + FieldDescriptor.TYPE_INT32, + FieldDescriptor.TYPE_SINT32, + FieldDescriptor.TYPE_SFIXED32, + ): + return rng.randrange(-(2**31), 2**31) + return rng.randrange(-(2**63), 2**63) + + +def _random_rows(rng: random.Random, n: int) -> list[wc.FrameRow]: + use_lp = rng.random() < 0.6 + use_topk = rng.random() < 0.5 + rows = [] + for _ in range(n): + nt = rng.choice([0, 1, 1, 2, 4, 7]) + tokens = [ + rng.randrange(-(2**31), 2**31) if rng.random() < 0.05 else rng.randrange(200000) + for _ in range(nt) + ] + lp_sampled = None + lp_rank = None + lp_topk = None + if use_lp and rng.random() < 0.7: + lp_sampled = [float("nan") if rng.random() < 0.1 else _f32(rng) for _ in range(nt)] + if rng.random() < 0.7: + lp_rank = [rng.randrange(1, 50) for _ in range(nt)] + if use_topk and rng.random() < 0.7: + lp_topk = [ + [(rng.randrange(200000), _f32(rng)) for _ in range(rng.choice([0, 1, 5]))] + for _ in range(nt) + ] + extra = None + if rng.random() < 0.2: + extra = _random_message(pb.output_pb2.RowExtra(), rng) + rows.append( + wc.FrameRow( + handle=rng.choice([0, 1, rng.randrange(2**64), 2**64 - 1]), + tokens=tokens, + finish=rng.randrange(256) if rng.random() < 0.3 else 0, + row_flags=rng.randrange(16), + seq=rng.choice([0, 0, 1, 2**32 - 1]), + stop_index=rng.choice([wc.NO_STOP_INDEX, wc.NO_STOP_INDEX, 0, 3, -(2**31)]), + replace_from=rng.choice([wc.NO_REPLACE_FROM, wc.NO_REPLACE_FROM, 0, 5]), + cum_logprob=rng.choice([None, None, -1.25, float("nan"), rng.uniform(-100, 0)]), + decoding_iter=rng.choice([0, 0, 1, 2**32 - 1]), + cached_tokens=rng.choice([0, 0, 16]), + lp_sampled=lp_sampled, + lp_rank=lp_rank, + lp_topk=lp_topk, + extra=extra, + ) + ) + return rows + + +def _random_header(rng: random.Random) -> dict: + return dict( + frame_seq=rng.randrange(1, 2**40), + iter_first=rng.choice([0, 7]), + iter_last=rng.choice([0, 9]), + emit_time_ns=rng.choice([0, rng.randrange(2**63)]), + acks=[ + _random_message(pb.common_pb2.SubmitAck(), rng) for _ in range(rng.choice([0, 0, 2])) + ], + iteration_stats=[ + _random_message(pb.stats_pb2.IterationStats(), rng) for _ in range(rng.choice([0, 1])) + ], + lora_set_changed=[ + _random_message(pb.common_pb2.LoraSetChanged(), rng) for _ in range(rng.choice([0, 1])) + ], + ) + + +def _decode_both(data: bytes) -> list[tuple[str, object]]: + """(python_result, cpp_result); each is ("ok", key) or ("error", exception type).""" + out: list[tuple[str, object]] = [] + for backend in ("python", "cpp"): + try: + out.append(("ok", _frame_key(wc.decode_frame_bytes(data, backend=backend)))) + except ValueError as exc: + out.append(("error", type(exc))) + return out + + +# --------------------------------------------------------------------------- +# Frame encode / decode equivalence +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("seed", range(40)) +def test_random_frames_encode_identically_and_decode_equal(native: ModuleType, seed: int) -> None: + rng = random.Random(seed) + n = rng.choice([0, 1, 2, 3, 8, 33, 128]) + rows = _random_rows(rng, n) + header = _random_header(rng) + for server_message in (False, True): + py = wc.encode_frame_bytes(rows, server_message=server_message, backend="python", **header) + cpp = wc.encode_frame_bytes(rows, server_message=server_message, backend="cpp", **header) + assert py == cpp + data = wc.encode_frame_bytes(rows, backend="python", **header) + py_decoded, cpp_decoded = _decode_both(data) + assert py_decoded[0] == "ok" + assert py_decoded == cpp_decoded + + py_frame = wc.encode_frame(rows, backend="python", **header) + cpp_frame = wc.encode_frame(rows, backend="cpp", **header) + assert py_frame == cpp_frame + assert [_row_key(r) for r in wc.decode_frame(py_frame, backend="python")] == [ + _row_key(r) for r in wc.decode_frame(py_frame, backend="cpp") + ] + + kind_py, payload_py = wc.parse_server_message( + wc.encode_frame_bytes(rows, server_message=True, backend="python", **header), + backend="python", + ) + kind_cpp, payload_cpp = wc.parse_server_message( + wc.encode_frame_bytes(rows, server_message=True, backend="cpp", **header), backend="cpp" + ) + assert kind_py == kind_cpp == "frame" + assert _frame_key(payload_py) == _frame_key(payload_cpp) + + +def test_edge_rows(native: ModuleType) -> None: + rows = [ + # HAS_EXTRA set without an extra is cleared; other flags are kept. + wc.FrameRow( + handle=2**64 - 1, tokens=[], row_flags=wc.ROW_FLAG_HAS_EXTRA | wc.ROW_FLAG_SEQ_FINAL + ), + # An explicit NaN cum_logprob still emits the column and decodes as None. + wc.FrameRow( + handle=1, tokens=[1, 2], cum_logprob=float("nan"), lp_sampled=[float("nan")] * 2 + ), + # Logprob lists on an empty row. + wc.FrameRow(handle=2, tokens=[], lp_sampled=[], lp_rank=[], lp_topk=[]), + wc.FrameRow( + handle=3, + tokens=[-(2**31), 2**31 - 1], + seq=2**32 - 1, + stop_index=-(2**31), + replace_from=0xFFFFFFFE, + decoding_iter=2**32 - 1, + cached_tokens=2**32 - 1, + finish=255, + row_flags=0xFFFF & ~wc.ROW_FLAG_HAS_EXTRA, + lp_topk=[[], [(7, -0.5)]], + extra=pb.output_pb2.RowExtra(), + ), + ] + header = dict(frame_seq=1, acks=[pb.common_pb2.SubmitAck()]) + py = wc.encode_frame_bytes(rows, backend="python", **header) + assert py == wc.encode_frame_bytes(rows, backend="cpp", **header) + py_decoded, cpp_decoded = _decode_both(py) + assert py_decoded[0] == "ok" and py_decoded == cpp_decoded + + # Only logprob lists with no tokens: no logprob column is written. + rows = [wc.FrameRow(handle=1, tokens=[], lp_sampled=[], lp_topk=[])] + assert wc.encode_frame_bytes(rows, frame_seq=1, backend="python") == wc.encode_frame_bytes( + rows, frame_seq=1, backend="cpp" + ) + # An empty frame carries only its header and piggybacked messages. + empty = wc.encode_frame_bytes( + [], frame_seq=5, iter_first=3, backend="cpp", acks=[pb.common_pb2.SubmitAck()] + ) + assert empty == wc.encode_frame_bytes( + [], frame_seq=5, iter_first=3, backend="python", acks=[pb.common_pb2.SubmitAck()] + ) + assert wc.decode_frame_bytes(empty, backend="cpp").rows == [] + + +def test_native_accepts_serialized_messages(native: ModuleType) -> None: + extra = pb.output_pb2.RowExtra(error=pb.common_pb2.ErrorInfo(message="boom")) + rows = [wc.FrameRow(handle=1, tokens=[3], extra=extra)] + ack = pb.common_pb2.SubmitAck() + expected = native.encode_frame(rows, frame_seq=1, acks=[ack]) + rows_bytes = [wc.FrameRow(handle=1, tokens=[3], extra=extra.SerializeToString())] + assert native.encode_frame(rows_bytes, frame_seq=1, acks=[ack.SerializeToString()]) == expected + with pytest.raises(ValueError): + native.encode_frame([wc.FrameRow(handle=1, tokens=[3], extra=b"\xff\xff")], frame_seq=1) + + +@pytest.mark.parametrize( + "row, error", + [ + (wc.FrameRow(handle=-1, tokens=[]), OverflowError), + (wc.FrameRow(handle=2**64, tokens=[]), OverflowError), + (wc.FrameRow(handle=1, tokens=[2**31]), OverflowError), + (wc.FrameRow(handle=1, tokens=[1.5]), TypeError), + (wc.FrameRow(handle=1, tokens=[], seq=-1), OverflowError), + (wc.FrameRow(handle=1, tokens=[], finish=256), OverflowError), + (wc.FrameRow(handle=1, tokens=[], row_flags=1 << 16), OverflowError), + (wc.FrameRow(handle=1, tokens=[1], lp_sampled=[0.0, 0.0]), ValueError), + (wc.FrameRow(handle=1, tokens=[1], lp_rank=[]), ValueError), + (wc.FrameRow(handle=1, tokens=[1], lp_topk=[[(1, 0.0)], []]), ValueError), + (wc.FrameRow(handle=1, tokens=[1], lp_topk=[[(1, 0.0, 2)]]), ValueError), + (wc.FrameRow(handle=1, tokens=[], extra=pb.common_pb2.SubmitAck()), TypeError), + ], +) +def test_invalid_rows_raise_on_both( + native: ModuleType, row: wc.FrameRow, error: type[Exception] +) -> None: + for backend in ("python", "cpp"): + with pytest.raises(error): + wc.encode_frame_bytes([row], frame_seq=1, backend=backend) + + +def _corrupt_frames() -> dict[str, bytes]: + rows = [ + wc.FrameRow( + handle=1, tokens=[1, 2], lp_sampled=[-0.1, -0.2], lp_topk=[[(1, -0.1)], [(2, -0.2)]] + ), + wc.FrameRow(handle=2, tokens=[3], extra=pb.output_pb2.RowExtra()), + ] + base = wc.encode_frame(rows, frame_seq=1, backend="python") + + def mutate(fn: Callable[[ProtoMessage], object]) -> bytes: + frame = pb.output_pb2.Frame() + frame.CopyFrom(base) + fn(frame) + return frame.SerializeToString() + + def u32(*values: int) -> bytes: + return struct.pack(f"<{len(values)}I", *values) + + cases = { + "handle_short": lambda f: setattr(f, "handle", f.handle[:-1]), + "seq_wrong_len": lambda f: setattr(f, "seq", u32(1)), + "offsets_missing": lambda f: setattr(f, "token_offsets", b""), + "offsets_first_nonzero": lambda f: setattr(f, "token_offsets", u32(1, 2, 3)), + "offsets_not_monotonic": lambda f: setattr(f, "token_offsets", u32(0, 3, 2)), + "tokens_short": lambda f: setattr(f, "tokens", f.tokens[:-1]), + "tokens_without_offsets": lambda f: ( + setattr(f, "token_offsets", u32(0, 0, 0)), + setattr(f, "lp_sampled", b""), + setattr(f, "lp_topk_offsets", b""), + ), + "finish_missing": lambda f: setattr(f, "finish", b""), + "row_flags_odd": lambda f: setattr(f, "row_flags", b"\x00"), + "stop_index_short": lambda f: setattr(f, "stop_index", b"\x00\x00"), + "cum_logprob_short": lambda f: setattr(f, "cum_logprob", b"\x00" * 8), + "extra_index_absent": lambda f: f.ClearField("extra_index"), + "extra_index_out_of_range": lambda f: setattr(f, "extra_index", u32(wc.NO_EXTRA_INDEX, 5)), + "lp_sampled_short": lambda f: setattr(f, "lp_sampled", f.lp_sampled[:-4]), + "lp_rank_short": lambda f: setattr(f, "lp_rank", u32(1)), + "lp_topk_offsets_first_nonzero": lambda f: setattr(f, "lp_topk_offsets", u32(1, 1, 2, 2)), + "lp_topk_offsets_not_monotonic": lambda f: setattr(f, "lp_topk_offsets", u32(0, 2, 1, 2)), + "lp_topk_ids_short": lambda f: setattr(f, "lp_topk_ids", f.lp_topk_ids[:-4]), + "lp_topk_logprobs_long": lambda f: setattr( + f, "lp_topk_logprobs", f.lp_topk_logprobs + b"\x00" * 4 + ), + "huge_n_rows": lambda f: setattr(f, "n_rows", 2**32 - 1), + } + out = {name: mutate(fn) for name, fn in cases.items()} + raw = base.SerializeToString() + out["garbage"] = b"\xff\xff\xff\xff" + out["truncated_varint"] = raw[:1] + b"\x80" + for cut in (1, 3, len(raw) // 2, len(raw) - 1): + out[f"truncated_{cut}"] = raw[:cut] + return out + + +@pytest.mark.parametrize("name, data", sorted(_corrupt_frames().items())) +def test_malformed_frames_rejected_by_both(native: ModuleType, name: str, data: bytes) -> None: + py_result, cpp_result = _decode_both(data) + assert py_result == cpp_result, name + if not name.startswith("truncated_"): + assert py_result[0] == "error", name + + +def test_random_truncations_and_bitflips_agree(native: ModuleType) -> None: + rng = random.Random(1234) + rows = _random_rows(rng, 16) + data = wc.encode_frame_bytes(rows, frame_seq=3, backend="python") + for _ in range(300): + mutated = bytearray(data) + if rng.random() < 0.5: + mutated = mutated[: rng.randrange(len(mutated))] + else: + pos = rng.randrange(len(mutated)) + mutated[pos] ^= 1 << rng.randrange(8) + py_result, cpp_result = _decode_both(bytes(mutated)) + assert py_result[0] == cpp_result[0] + if py_result[0] == "ok": + assert py_result == cpp_result + + +# --------------------------------------------------------------------------- +# ClientMessage / ServerMessage envelopes +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("seed", range(10)) +def test_submit_batch_roundtrip(native: ModuleType, seed: int) -> None: + rng = random.Random(seed) + requests = [ + _random_message(pb.request_pb2.Request(), rng) for _ in range(rng.choice([0, 1, 4, 16])) + ] + seq = rng.choice([0, 1, 2**64 - 1]) + py = wc.encode_submit_batch(requests, consumed_frame_seq=seq, backend="python") + cpp = wc.encode_submit_batch(requests, consumed_frame_seq=seq, backend="cpp") + assert py == cpp + assert ( + native.encode_submit_batch( + [r.SerializeToString() for r in requests], consumed_frame_seq=seq + ) + == py + ) + views = [wc.parse_client_message(py, backend=b) for b in ("python", "cpp")] + assert views[0] == views[1] + assert views[0].kind == "submit_batch" and views[0].requests == requests + + +def test_client_message_kinds(native: ModuleType) -> None: + cancels = [(1, 1), (2**64 - 1, 2)] + messages = [ + wc.encode_cancel_batch( + cancels, cancel_all=True, cancel_all_reason=3, consumed_frame_seq=9, backend="python" + ), + wc.encode_cancel_batch([], backend="python"), + pb.session_pb2.ClientMessage( + progress=pb.session_pb2.Progress(consumed_frame_seq=4) + ).SerializeToString(), + pb.session_pb2.ClientMessage( + open=pb.session_pb2.SessionOpen(frontend_label="fe") + ).SerializeToString(), + b"", + ] + assert messages[0] == wc.encode_cancel_batch( + cancels, cancel_all=True, cancel_all_reason=3, consumed_frame_seq=9, backend="cpp" + ) + for data in messages: + assert wc.parse_client_message(data, backend="python") == wc.parse_client_message( + data, backend="cpp" + ) + view = wc.parse_client_message(messages[0], backend="cpp") + assert view.kind == "cancel_batch" and view.cancels == cancels and view.cancel_all + + +@pytest.mark.parametrize("data", [b"\xff", b"\x12\x05\x0a", b"\x12\x02\x0a\x05"]) +def test_malformed_client_message_rejected_by_both(native: ModuleType, data: bytes) -> None: + for backend in ("python", "cpp"): + with pytest.raises(ValueError): + wc.parse_client_message(data, backend=backend) + + +def test_server_message_kinds(native: ModuleType) -> None: + rng = random.Random(7) + messages = [ + pb.session_pb2.ServerMessage(submit_ack=_random_message(pb.common_pb2.SubmitAck(), rng)), + pb.session_pb2.ServerMessage(notice=pb.session_pb2.SessionNotice(message="draining")), + pb.session_pb2.ServerMessage( + iteration_stats=_random_message(pb.stats_pb2.IterationStats(), rng) + ), + pb.session_pb2.ServerMessage(lora_set_changed=pb.common_pb2.LoraSetChanged()), + pb.session_pb2.ServerMessage(accepted=pb.session_pb2.SessionAccepted(session_id=3)), + pb.session_pb2.ServerMessage(), + ] + for message in messages: + data = message.SerializeToString() + assert wc.parse_server_message(data, backend="python") == wc.parse_server_message( + data, backend="cpp" + ) + for backend in ("python", "cpp"): + with pytest.raises(ValueError): + wc.parse_server_message(b"\x12\x05\x0a", backend=backend) + + +# --------------------------------------------------------------------------- +# Backend selection +# --------------------------------------------------------------------------- + + +def test_backend_selection(monkeypatch: pytest.MonkeyPatch, native: ModuleType) -> None: + monkeypatch.setenv(_native.BACKEND_ENV, "python") + assert _native.resolve() is None + monkeypatch.setenv(_native.BACKEND_ENV, "cpp") + assert _native.resolve() is native + monkeypatch.setenv(_native.BACKEND_ENV, "auto") + assert _native.resolve() is native + assert _native.resolve(auto_native=False) is None + assert _native.resolve("cpp", auto_native=False) is native + monkeypatch.setenv(_native.BACKEND_ENV, "rust") + with pytest.raises(ValueError): + _native.resolve() + monkeypatch.setattr(_native, "_native_module", None) + assert _native.resolve("auto") is None + with pytest.raises(ImportError): + _native.resolve("cpp") + + +def test_writable_buffer_inputs_decoded_safely(native: ModuleType) -> None: + """Writable buffer exporters (bytearray, memoryview) work and copy before releasing GIL.""" + rng = random.Random(99) + rows = _random_rows(rng, 4) + raw_frame = wc.encode_frame_bytes(rows, frame_seq=11, backend="python") + ba_frame = bytearray(raw_frame) + mv_frame = memoryview(ba_frame) + assert _frame_key(wc.decode_frame_bytes(ba_frame, backend="cpp")) == _frame_key( + wc.decode_frame_bytes(raw_frame, backend="python") + ) + assert _frame_key(wc.decode_frame_bytes(mv_frame, backend="cpp")) == _frame_key( + wc.decode_frame_bytes(raw_frame, backend="python") + ) + + raw_smsg = pb.session_pb2.ServerMessage( + notice=pb.session_pb2.SessionNotice(message="buf") + ).SerializeToString() + assert wc.parse_server_message(bytearray(raw_smsg), backend="cpp") == wc.parse_server_message( + raw_smsg, backend="python" + ) + + raw_cmsg = wc.encode_cancel_batch([(1, 1)], backend="python") + assert wc.parse_client_message(bytearray(raw_cmsg), backend="cpp") == wc.parse_client_message( + raw_cmsg, backend="python" + ) + + +def _pack_cpp_result_bytes( + *, + is_final: bool = False, + output_token_ids: list[list[int]] = ([10, 11],), + finish_reasons: list[int] = (0,), + has_ctx: bool = False, + decoding_iter: int = 3, + avg_decoded: float = 1.0, + sequence_index: int = 0, + is_sequence_final: bool = False, + has_perf: bool = False, +) -> bytes: + """Serialize a C++ tensorrt_llm::executor::Result matching Serialization::serialize(Result).""" + parts: list[bytes] = [struct.pack(" None: + """Native encode_step_fast and decode_step_server_message_fast match Python byte-for-byte.""" + import types + + from tensorrt_llm.executor.zmq_wire.codec import ( + ZmqFinishReason, + ZmqLogprob, + ZmqStepResponse, + ZmqStepResult, + decode_step_server_message_bytes, + encode_step_responses_bytes, + ) + + # 1. Plain ZmqStepResponse batch (no logprobs, simple float logprobs, dict top-k logprobs, beam). + rsps = [ + ZmqStepResponse( + client_id=101, + request_id=101, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + sequence_index=0, + output_token_ids=[[42, 43]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + decoding_iter=5, + cached_tokens=16, + ), + ), + ZmqStepResponse( + client_id=102, + request_id=102, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + sequence_index=1, + output_token_ids=[[7]], + cum_log_probs=[-0.5], + log_probs=[[[-0.5][0]]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + decoding_iter=2, + ), + ), + ZmqStepResponse( + client_id=103, + request_id=103, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + sequence_index=0, + output_token_ids=[[50], [60]], + cum_log_probs=[-1.0, -1.5], + log_probs=[ + [{50: ZmqLogprob(logprob=-0.4, rank=1), 51: ZmqLogprob(logprob=-0.8, rank=2)}], + [ + { + 61: ZmqLogprob(logprob=-0.3, rank=1), + 62: ZmqLogprob(logprob=-0.7, rank=2), + 60: ZmqLogprob(logprob=-2.1, rank=9), + } + ], + ], + finish_reasons=[ZmqFinishReason.NOT_FINISHED, ZmqFinishReason.NOT_FINISHED], + replace_from=0, + decoding_iter=4, + ), + ), + ] + + py_bytes = encode_step_responses_bytes( + rsps, frame_seq=7, iter_first=9, iter_last=9, emit_time_ns=123456, backend="python" + ) + cpp_bytes = encode_step_responses_bytes( + rsps, frame_seq=7, iter_first=9, iter_last=9, emit_time_ns=123456, backend="cpp" + ) + assert cpp_bytes == py_bytes + + results_map = { + 103: types.SimpleNamespace( + sampling_params=types.SimpleNamespace( + use_beam_search=True, logprobs_simple_format=False + ) + ), + } + fseq_cpp, dec_cpp, pre_fin = decode_step_server_message_bytes( + cpp_bytes, results_map=results_map, backend="cpp" + ) + assert pre_fin is True + assert fseq_cpp == 7 + assert len(dec_cpp) == 3 # beam rows for client 103 coalesced into 1 response + assert dec_cpp[0].client_id == 101 + assert dec_cpp[0].result.output_token_ids == [[42, 43]] + assert dec_cpp[0].result.cached_tokens == 16 + assert dec_cpp[0].result.decoding_iter == 5 + assert dec_cpp[0].result.context_phase_params is None + assert dec_cpp[1].client_id == 102 + assert dec_cpp[1].result.sequence_index == 1 + assert math.isclose(dec_cpp[1].result.cum_log_probs[0], -0.5, rel_tol=1e-6) + assert math.isclose(dec_cpp[1].result.log_probs[0][0], -0.5, rel_tol=1e-6) + assert dec_cpp[2].client_id == 103 + assert dec_cpp[2].result.output_token_ids == [[50], [60]] + assert dec_cpp[2].result.log_probs[1][0][60].rank == 9 + assert math.isclose(dec_cpp[2].result.log_probs[1][0][60].logprob, -2.1, rel_tol=1e-5) + + # simple_format collapses dict logprobs to flat floats inside C++ decoder. + results_map_simple = { + 103: types.SimpleNamespace( + sampling_params=types.SimpleNamespace(use_beam_search=True, logprobs_simple_format=True) + ), + } + _, dec_simple, pre_fin_simple = decode_step_server_message_bytes( + cpp_bytes, results_map=results_map_simple, backend="cpp" + ) + assert pre_fin_simple is True + assert math.isclose(dec_simple[2].result.log_probs[0][0], -0.4, rel_tol=1e-5) + assert math.isclose(dec_simple[2].result.log_probs[1][0], -2.1, rel_tol=1e-5) + + # 2. Serialized C++ LlmResult._result bytes fast path matches Python encoder after deserialize. + raw_res_bytes = _pack_cpp_result_bytes( + output_token_ids=[[100, 101]], + finish_reasons=[0], + decoding_iter=6, + sequence_index=2, + ) + lp_storage = types.SimpleNamespace( + log_probs=[ + [ + {100: ZmqLogprob(logprob=-0.2, rank=1)}, + {101: ZmqLogprob(logprob=-0.3, rank=1), 102: ZmqLogprob(logprob=-0.9, rank=2)}, + ] + ], + cum_log_probs=[-0.5], + ) + py_res = types.SimpleNamespace(_log_probs=lp_storage) + fake_llm_res = types.SimpleNamespace( + _result=raw_res_bytes, + _py_result=py_res, + is_final=False, + cached_tokens=8, + ) + fake_llm_rsp = types.SimpleNamespace( + client_id=201, + request_id=201, + result=fake_llm_res, + error_msg=None, + has_error=lambda: False, + ) + cpp_from_raw = encode_step_responses_bytes( + [fake_llm_rsp], frame_seq=12, iter_first=3, iter_last=3, emit_time_ns=999, backend="cpp" + ) + equiv_rsp = ZmqStepResponse( + client_id=201, + request_id=201, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + sequence_index=2, + output_token_ids=[[100, 101]], + cum_log_probs=[-0.5], + log_probs=lp_storage.log_probs, + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + decoding_iter=6, + cached_tokens=8, + ), + ) + py_equiv = encode_step_responses_bytes( + [equiv_rsp], frame_seq=12, iter_first=3, iter_last=3, emit_time_ns=999, backend="python" + ) + assert cpp_from_raw == py_equiv + + # 3. Any cold/final response causes encode_step_fast and decode_step_server_message_fast + # to cleanly return None and fall back to the full Python path. + final_rsp = ZmqStepResponse( + client_id=301, + request_id=301, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[9]], + finish_reasons=[ZmqFinishReason.END_ID], + ), + ) + assert ( + native.encode_step_fast([final_rsp], frame_seq=1, iter_first=1, iter_last=1, emit_time_ns=1) + is None + ) + final_bytes = encode_step_responses_bytes( + [final_rsp], frame_seq=1, iter_first=1, iter_last=1, emit_time_ns=1, backend="cpp" + ) + fseq_f, dec_f, pre_fin_f = decode_step_server_message_bytes(final_bytes, backend="cpp") + assert fseq_f == 1 and pre_fin_f is False and len(dec_f) == 1 + assert dec_f[0].result.is_final is True and dec_f[0].result.is_request_done is True + + # 4. Real PyResult empty additional output dicts must NOT disable encode_step_fast, + # whereas non-empty additional outputs or routed_experts MUST trigger fallback (return None). + empty_add_py_res = types.SimpleNamespace( + _log_probs=lp_storage, + _additional_context_outputs={"hidden": []}, + _additional_generation_outputs={"hidden": []}, + ) + empty_add_llm_res = types.SimpleNamespace( + _result=raw_res_bytes, + _py_result=empty_add_py_res, + is_final=False, + cached_tokens=8, + routed_experts=None, + ) + empty_add_rsp = types.SimpleNamespace( + client_id=202, + request_id=202, + result=empty_add_llm_res, + error_msg=None, + has_error=lambda: False, + ) + assert ( + native.encode_step_fast( + [empty_add_rsp], frame_seq=13, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is not None + ) + + non_empty_py_res = types.SimpleNamespace( + _log_probs=lp_storage, + _additional_context_outputs={}, + _additional_generation_outputs={"hidden": [1]}, + ) + non_empty_llm_res = types.SimpleNamespace( + _result=raw_res_bytes, + _py_result=non_empty_py_res, + is_final=False, + cached_tokens=8, + ) + non_empty_rsp = types.SimpleNamespace( + client_id=203, + request_id=203, + result=non_empty_llm_res, + error_msg=None, + has_error=lambda: False, + ) + assert ( + native.encode_step_fast( + [non_empty_rsp], frame_seq=14, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is None + ) + + routed_llm_res = types.SimpleNamespace( + _result=raw_res_bytes, + _py_result=empty_add_py_res, + is_final=False, + cached_tokens=8, + routed_experts=[1, 2], + ) + routed_rsp = types.SimpleNamespace( + client_id=204, + request_id=204, + result=routed_llm_res, + error_msg=None, + has_error=lambda: False, + ) + assert ( + native.encode_step_fast( + [routed_rsp], frame_seq=15, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is None + ) + + # 5. Slotted serialized LlmResult (no __dict__) with spec_dec_totals / row_flags bails cleanly. + class _SlottedRes: + __slots__ = ("_result", "_py_result", "is_final", "cached_tokens", "spec_dec_totals") + + def __init__(self, raw: bytes) -> None: + self._result = raw + self._py_result = None + self.is_final = False + self.cached_tokens = 0 + self.spec_dec_totals = (3, 4) + + slotted_rsp = types.SimpleNamespace( + client_id=205, + request_id=205, + result=_SlottedRes(raw_res_bytes), + error_msg=None, + has_error=lambda: False, + ) + assert ( + native.encode_step_fast( + [slotted_rsp], frame_seq=16, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is None + ) + + # 6. decode_step_server_message_fast rejects types with tp_new == nullptr and bails to Python + # when beam rows have mismatched optional columns or duplicate seqs. + with pytest.raises(TypeError): + native.decode_step_server_message_fast( + cpp_bytes, + response_type=types.FunctionType, + result_type=ZmqStepResult, + finish_reasons=(ZmqFinishReason.NOT_FINISHED,), + logprob_type=ZmqLogprob, + ) + + mismatched_beam_rows = [ + wc.FrameRow(handle=901, seq=0, tokens=[10], replace_from=0, lp_sampled=None), + wc.FrameRow(handle=901, seq=1, tokens=[20], replace_from=0, lp_sampled=[-0.5]), + ] + mismatched_frame = pb.session_pb2.ServerMessage( + frame=wc.encode_frame(mismatched_beam_rows, frame_seq=20, backend="python") + ).SerializeToString() + assert ( + native.decode_step_server_message_fast( + mismatched_frame, + response_type=ZmqStepResponse, + result_type=ZmqStepResult, + finish_reasons=(ZmqFinishReason.NOT_FINISHED,), + logprob_type=ZmqLogprob, + results_map={ + 901: types.SimpleNamespace( + sampling_params=types.SimpleNamespace( + use_beam_search=True, logprobs_simple_format=False + ) + ) + }, + ) + is None + ) + + dup_beam_rows = [ + wc.FrameRow(handle=902, seq=0, tokens=[10], replace_from=0), + wc.FrameRow(handle=902, seq=0, tokens=[11], replace_from=0), + ] + dup_frame = pb.session_pb2.ServerMessage( + frame=wc.encode_frame(dup_beam_rows, frame_seq=21, backend="python") + ).SerializeToString() + assert ( + native.decode_step_server_message_fast( + dup_frame, + response_type=ZmqStepResponse, + result_type=ZmqStepResult, + finish_reasons=(ZmqFinishReason.NOT_FINISHED,), + logprob_type=ZmqLogprob, + ) + is None + ) + + # 7. Non-dict Mapping results_map (e.g. MappingProxyType) bails out of the C++ fast path + # so callers fall back to Python, which still coalesces beams and collapses simple_format. + from tensorrt_llm.executor.zmq_wire.transport import ChannelTag, pack_raw_frame + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + + proxy_results_map = types.MappingProxyType(results_map) + assert ( + native.decode_step_server_message_fast( + cpp_bytes, + proxy_results_map, + response_type=ZmqStepResponse, + result_type=ZmqStepResult, + finish_reasons=(ZmqFinishReason.NOT_FINISHED,), + logprob_type=ZmqLogprob, + ) + is None + ) + + fseq_proxy, dec_proxy, pre_fin_proxy = decode_step_server_message_bytes( + cpp_bytes, results_map=proxy_results_map, backend="cpp" + ) + assert fseq_proxy == 7 + assert pre_fin_proxy is False + assert len(dec_proxy) == 4 # uncoalesced rows handed to Python post-processing + + hmac_key = b"test-hmac-key" + signed_frame = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, cpp_bytes, hmac_key) + proxy_decoded = proxy_decode_raw_frame(signed_frame, hmac_key, results_map=proxy_results_map) + assert proxy_decoded is not None + assert len(proxy_decoded) == 3 # beam rows for client 103 coalesced identically to dict + assert proxy_decoded[2].client_id == 103 + assert proxy_decoded[2].result.output_token_ids == [[50], [60]] + assert proxy_decoded[2].result.log_probs[1][0][60].rank == 9 + assert math.isclose(proxy_decoded[2].result.log_probs[1][0][60].logprob, -2.1, rel_tol=1e-5) + + proxy_results_map_simple = types.MappingProxyType(results_map_simple) + assert ( + native.decode_step_server_message_fast( + cpp_bytes, + proxy_results_map_simple, + response_type=ZmqStepResponse, + result_type=ZmqStepResult, + finish_reasons=(ZmqFinishReason.NOT_FINISHED,), + logprob_type=ZmqLogprob, + ) + is None + ) + fseq_proxy_simple, _, pre_fin_proxy_simple = decode_step_server_message_bytes( + cpp_bytes, results_map=proxy_results_map_simple, backend="cpp" + ) + assert fseq_proxy_simple == 7 + assert pre_fin_proxy_simple is False + proxy_decoded_simple = proxy_decode_raw_frame( + signed_frame, hmac_key, results_map=proxy_results_map_simple + ) + assert proxy_decoded_simple is not None + assert len(proxy_decoded_simple) == 3 + assert math.isclose(proxy_decoded_simple[2].result.log_probs[0][0], -0.4, rel_tol=1e-5) + assert math.isclose(proxy_decoded_simple[2].result.log_probs[1][0], -2.1, rel_tol=1e-5) + + # 8. Empty-string error_msg="" matches Response.has_error() (error_msg is not None) and bails + # out of encode_step_fast for both instance-dict and slotted responses. + empty_err_rsp = types.SimpleNamespace( + client_id=206, + request_id=206, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[1]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + ), + error_msg="", + has_error=lambda: True, + ) + assert ( + native.encode_step_fast( + [empty_err_rsp], frame_seq=22, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is None + ) + + slotted_empty_err_rsp = ZmqStepResponse( + client_id=207, + request_id=207, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[2]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + ), + error_msg="", + ) + assert ( + native.encode_step_fast( + [slotted_empty_err_rsp], frame_seq=23, iter_first=3, iter_last=3, emit_time_ns=999 + ) + is None + ) diff --git a/tests/unittest/executor/test_multi_frontend_routing.py b/tests/unittest/executor/test_multi_frontend_routing.py index d97a099c6a6b..23756da19e1a 100644 --- a/tests/unittest/executor/test_multi_frontend_routing.py +++ b/tests/unittest/executor/test_multi_frontend_routing.py @@ -217,7 +217,12 @@ def _stop_dispatch_thread(proxy, result_addrs, hmac_key): proxy.dispatch_result_thread.join(timeout=10) assert not proxy.dispatch_result_thread.is_alive() - def test_submit_namespaces_and_shutdown_never_sends_sentinel(self): + def test_submit_namespaces_and_shutdown_never_sends_sentinel( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + # The fake worker speaks pickle; keep the proxy on the pickle path too. + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "off") + from tensorrt_llm.executor.request import CancellingRequest, GenerationRequest from tensorrt_llm.sampling_params import SamplingParams @@ -247,7 +252,12 @@ def test_submit_namespaces_and_shutdown_never_sends_sentinel(self): ) self._stop_dispatch_thread(proxy, result_addrs, hmac_key) - def test_check_health_and_submit_reflect_fatal_error(self): + def test_check_health_and_submit_reflect_fatal_error( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + # The fake worker speaks pickle; keep the proxy on the pickle path too. + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "off") + from tensorrt_llm.executor.request import GenerationRequest from tensorrt_llm.executor.utils import EngineDeadError from tensorrt_llm.sampling_params import SamplingParams @@ -267,7 +277,10 @@ def test_check_health_and_submit_reflect_fatal_error(self): with pytest.raises(EngineDeadError): proxy.submit(GenerationRequest([1], SamplingParams())) - def test_dispatch_routes_own_lane_responses(self): + def test_dispatch_routes_own_lane_responses(self, monkeypatch: pytest.MonkeyPatch) -> None: + # The fake worker speaks pickle; keep the proxy on the pickle path too. + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "off") + import zmq from tensorrt_llm.executor.ipc import FusedIpcQueue diff --git a/tests/unittest/executor/test_zmq_wire.py b/tests/unittest/executor/test_zmq_wire.py new file mode 100644 index 000000000000..e1b8537d7813 --- /dev/null +++ b/tests/unittest/executor/test_zmq_wire.py @@ -0,0 +1,2738 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Comprehensive CPU unit tests for trtllm.engine.v1 (v1.1) over ZeroMQ. + +Covers: + - Transport layer: binary HMAC frame format (magic=0x53), constant-time verification, + tamper/wrong-key/truncation rejection, strict zero-pickle mode (StrictProtoWireError), + TLLM_SERVE_ENGINE_ZMQ env modes (0/off/auto/strict), InMemoryZmqQueue + optional real pyzmq. + - Feature families end-to-end (encode -> HMAC frame -> decode -> consume): + 1. prompt_tokens, encoder_input_tokens, multimodal (MEDIA + PREPROCESSED + CAP-20 + io_options/processor_options + INLINE / SHM / BLOB_FETCH large tensors + item_metadata) + 2. SamplingParams all 22 optional/repeated/enum fields (incl. sparse logit_bias & dense bias) + 3. StopParams all 7 fields (max_tokens, min_tokens, end_id, pad_id, ignore_eos, stop & bad) + 4. OutputOptions (logprobs, logprob_rank, prompt_logprobs inline/SHM/Blob/sharded, + context/generation logits, encoder_output, routed_experts, additional_context/generation, + metrics, return_expanded_prompt) + 5. n / best_of / beam search (num_sequences, beam_width, num_return_beams, beam_width_array, + length_penalty, early_stopping, diversity_rate, replace_from) + 6. GuidedDecoding all 6 kinds (json_schema, json_object, regex, ebnf_grammar, + structural_tag, choice), LoRA (LoraRef), named logits_processors, + and UnsupportedCallableError on arbitrary Python callable in strict mode + 7. SchedulingParams 6 fields + queue_age_us + TraceContext + 8. KvParams (cache_salt, KvRetention incl. TokenRangeRetention, KvHints incl. KvHintAction) + 9. Disaggregated serving: see test_zmq_wire_disagg.py + 10. CancelBatch (explicit handles/reasons + all_flag + consumed_frame_seq) + 11. Columnar output Frame + duck-typed ZmqStepResponse compatibility with GenerationResult + 12. Strict zero-pickle invariant assertion: pickle_fallbacks == 0 across all strict flows. + - Executor integration: ZeroMqQueue raw-frame lane (HMAC before return, strict rejection + before pickle.loads), proxy / worker bridges, _incoming_requests, the batching sender. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import math +import os +import pickle # Only used in negative tests to synthesize a foreign 0x80 pickle frame +import struct +import types +from typing import Optional + +import pytest + +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc +from tensorrt_llm.executor.utils import FRONTEND_ID_SHIFT +from tensorrt_llm.executor.zmq_wire import ( + FRAME_MAGIC, + ChannelTag, + FrameAuthError, + FrameFormatError, + InMemoryZmqQueue, + LocalBlobStore, + RawTensor, + StrictProtoWireError, + UnsupportedCallableError, + ZmqFinishReason, + ZmqLogprob, + ZmqRawSocketWrapper, + ZmqStepResponse, + ZmqStepResult, + decode_cancel_batch, + decode_prompt_logprobs, + decode_step_frame, + decode_submit_batch, + encode_cancel_batch, + encode_generation_requests, + encode_prompt_logprobs, + encode_step_responses, + get_zmq_wire_mode, + is_raw_proto_frame, + materialize_embedding_bias, + pack_raw_frame, + unpack_raw_frame, +) + +pytestmark = pytest.mark.cpu_only + +try: + import zmq as _pyzmq + + HAS_PYZMQ = True +except ImportError: + _pyzmq = None + HAS_PYZMQ = False + + +# ============================================================================ +# Helper mock types matching GenerationRequest / SamplingParams / etc. +# ============================================================================ + + +def _make_f32_tensor( + shape: tuple[int, ...], vals: list[float], device: Optional[int] = None +) -> RawTensor: + return RawTensor( + dtype=pb.common_pb2.DTYPE_F32, + shape=shape, + data=struct.pack(f"<{len(vals)}f", *vals), + device=device, + ) + + +def _make_i16_tensor(shape: tuple[int, ...], vals: list[int]) -> RawTensor: + return RawTensor( + dtype=pb.common_pb2.DTYPE_I16, + shape=shape, + data=struct.pack(f"<{len(vals)}h", *vals), + ) + + +def _make_i64_tensor(shape: tuple[int, ...], vals: list[int]) -> RawTensor: + return RawTensor( + dtype=pb.common_pb2.DTYPE_I64, + shape=shape, + data=struct.pack(f"<{len(vals)}q", *vals), + ) + + +@dataclasses.dataclass +class _MockSamplingParams: + end_id: Optional[int] = 2 + pad_id: Optional[int] = 0 + max_tokens: Optional[int] = 64 + min_tokens: Optional[int] = None + ignore_eos: bool = False + stop_token_ids: Optional[list[int]] = None + _stop_word_ids: Optional[list[list[int]]] = None + bad_token_ids: Optional[list[int]] = None + _bad_word_ids: Optional[list[list[int]]] = None + n: int = 1 + best_of: Optional[int] = None + use_beam_search: bool = False + num_return_beams: Optional[int] = None + beam_width_array: Optional[list[int]] = None + temperature: Optional[float] = None + top_k: Optional[int] = None + top_p: Optional[float] = None + top_p_decay: Optional[float] = None + top_p_min: Optional[float] = None + top_p_reset_ids: Optional[int] = None + min_p: Optional[float] = None + seed: Optional[int] = None + repetition_penalty: Optional[float] = None + presence_penalty: Optional[float] = None + frequency_penalty: Optional[float] = None + prompt_ignore_length: Optional[int] = None + no_repeat_ngram_size: Optional[int] = None + length_penalty: Optional[float] = None + early_stopping: Optional[int] = None + beam_search_diversity_rate: Optional[float] = None + embedding_bias: object = None + logit_bias: object = None + logprobs_mode: str = "raw" + logprobs: Optional[int] = None + logprob_rank: Optional[bool] = None + prompt_logprobs: Optional[int] = None + return_context_logits: bool = False + return_generation_logits: bool = False + return_encoder_output: bool = False + return_routed_experts: bool = False + additional_context_outputs: Optional[list[str]] = None + additional_generation_outputs: Optional[list[str]] = None + additional_model_outputs: Optional[list[str]] = None + return_perf_metrics: bool = False + return_time_breakdown: bool = False + return_decoding_stats: bool = False + return_expanded_prompt: bool = False + guided_decoding: object = None + logits_processor: object = None + logits_processors: Optional[list[object]] = None + apply_batched_logits_processor: bool = False + thinking_budget: object = None + _decoder_output_token_prefix: tuple[int, ...] = () + + +@dataclasses.dataclass +class _MockGenerationRequest: + prompt_token_ids: list[int] + sampling_params: _MockSamplingParams + id: int = 1 + request_id: str = "req-1" + encoder_input_token_ids: Optional[list[int]] = None + streaming: bool = False + priority: float = 0.5 + queue_age_us: Optional[int] = None + lora_request: object = None + scheduling_params: object = None + conversation_params: object = None + cache_salt: Optional[str] = None + kv_cache_retention_config: object = None + kv_hints: object = None + trace_headers: Optional[dict[str, str]] = None + disaggregated_params: object = None + multimodal_params: object = None + thinking_budget: object = None + logits_processors: Optional[list[object]] = None + + +class ThinkingBudgetLogitsProcessor: + """Matches real ThinkingBudgetLogitsProcessor attribute contract.""" + + def __init__(self, budget: int, start_ids: list[int], end_ids: list[int]) -> None: + self.thinking_token_budget = budget + self.reasoning_start_token_ids = start_ids + self.reasoning_end_token_ids = end_ids + + def __call__(self, *args: object, **kwargs: object) -> None: + pass + + +# ============================================================================ +# 1. Transport Layer: Binary HMAC Framing, Tamper Rejection, Strict Mode +# ============================================================================ + + +def test_env_mode_resolution(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("TLLM_SERVE_ENGINE_ZMQ", raising=False) + assert get_zmq_wire_mode() == "auto" + for val, expected in [ + ("0", "off"), + ("off", "off"), + ("auto", "auto"), + ("1", "auto"), + ("strict", "strict"), + ("STRICT", "strict"), + ]: + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", val) + assert get_zmq_wire_mode() == expected + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "bogus") + with pytest.raises(ValueError, match="TLLM_SERVE_ENGINE_ZMQ"): + get_zmq_wire_mode() + + +def test_raw_hmac_frame_pack_unpack_and_tamper_rejection() -> None: + key = os.urandom(32) + payload = b"\x0a\x05hello\x10\x2a" + raw = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 42, payload, key) + + assert raw[0] == FRAME_MAGIC == 0x53 + assert raw[1] == int(ChannelTag.CLIENT_MESSAGE) + assert is_raw_proto_frame(raw) is True + assert is_raw_proto_frame(pickle.dumps({"a": 1})) is False + + tag, sub_tag, out_payload = unpack_raw_frame(raw, key) + assert tag == ChannelTag.CLIENT_MESSAGE + assert sub_tag == 42 + assert out_payload == payload + + # Wrong HMAC key rejected + with pytest.raises(FrameAuthError): + unpack_raw_frame(raw, b"wrong" * 7) + + # Bit-flip in payload rejected + tampered_payload = bytearray(raw) + tampered_payload[7] ^= 0x01 + with pytest.raises(FrameAuthError): + unpack_raw_frame(bytes(tampered_payload), key) + + # Bit-flip in header sub_tag rejected + tampered_hdr = bytearray(raw) + tampered_hdr[2] ^= 0x80 + with pytest.raises(FrameAuthError): + unpack_raw_frame(bytes(tampered_hdr), key) + + # Bit-flip in MAC rejected + tampered_mac = bytearray(raw) + tampered_mac[-1] ^= 0xFF + with pytest.raises(FrameAuthError): + unpack_raw_frame(bytes(tampered_mac), key) + + # Truncated frame rejected + with pytest.raises(FrameFormatError): + unpack_raw_frame(raw[:20], key) + + # Wrong magic rejected + bad_magic = bytes([0x80]) + raw[1:] + with pytest.raises(FrameFormatError): + unpack_raw_frame(bad_magic, key) + + +def test_strict_mode_rejects_pickle_frames_and_tracks_counters() -> None: + key = os.urandom(32) + q_cli, q_srv = InMemoryZmqQueue.make_pair() + w_cli = ZmqRawSocketWrapper(q_cli, key, mode="strict") + w_srv = ZmqRawSocketWrapper(q_srv, key, mode="strict") + + # Send a foreign pickle payload (starts with 0x80) directly + foreign_pickle = pickle.dumps({"evil": "payload"}) + w_cli.send_raw_bytes(foreign_pickle) + + with pytest.raises(StrictProtoWireError): + w_srv.recv_frame(timeout=1.0) + assert w_srv.pickle_fallbacks == 0 + + # Strict send_with_fallback also raises + with pytest.raises(StrictProtoWireError): + w_cli.send_with_fallback({"legacy": 1}, reason="test") + assert w_cli.pickle_fallbacks == 0 + + # In auto mode, fallback increments pickle_fallbacks and uses configured parser + w_srv_auto = ZmqRawSocketWrapper( + q_srv, key, mode="auto", pickle_recv_fallback=lambda raw: {"fallback_len": len(raw)} + ) + w_cli.send_raw_bytes(foreign_pickle) + kind, obj = w_srv_auto.recv_frame(timeout=1.0) + assert kind == "pickle" + assert obj == {"fallback_len": len(foreign_pickle)} + assert w_srv_auto.pickle_fallbacks == 1 + + +# ============================================================================ +# 2. All 14 Table 3-1 Feature Families End-to-End over Strict ZMQ Session +# ============================================================================ + + +def test_all_sampling_22_fields_and_stop_7_fields_and_output_options_roundtrip() -> None: + # Sparse embedding_bias tuple -> proto repeated LogitBias + sparse_bias = ((1, 1.5), (3, -2.25)) + sp = _MockSamplingParams( + end_id=2, + pad_id=0, + max_tokens=128, + min_tokens=4, + ignore_eos=False, + stop_token_ids=[99], + _stop_word_ids=[[50, 51]], + bad_token_ids=[77], + _bad_word_ids=[[88, 89]], + n=2, + best_of=4, + use_beam_search=True, + num_return_beams=2, + beam_width_array=[2, 4], + temperature=0.75, + top_k=40, + top_p=0.92, + top_p_decay=0.99, + top_p_min=0.05, + top_p_reset_ids=13, + min_p=0.02, + seed=123456789, + repetition_penalty=1.15, + presence_penalty=0.3, + frequency_penalty=0.4, + prompt_ignore_length=8, + no_repeat_ngram_size=3, + length_penalty=1.2, + early_stopping=1, + beam_search_diversity_rate=0.5, + embedding_bias=sparse_bias, + logprobs_mode="processed", + logprobs=5, + logprob_rank=True, + prompt_logprobs=3, + return_context_logits=True, + return_generation_logits=True, + return_encoder_output=True, + return_routed_experts=True, + additional_context_outputs=["hidden_ctx"], + additional_generation_outputs=["hidden_gen"], + return_perf_metrics=True, + return_time_breakdown=True, + return_decoding_stats=True, + return_expanded_prompt=True, + ) + req = _MockGenerationRequest( + id=101, + request_id="req-full-sampling", + prompt_token_ids=[1, 10, 20, 30], + encoder_input_token_ids=[5, 6, 7], + sampling_params=sp, + streaming=True, + priority=0.85, + queue_age_us=4200, + lora_request={"adapter_id": 7, "name": "sql-lora", "path": "/models/sql", "format": "nemo"}, + scheduling_params=types.SimpleNamespace( + attention_dp_rank=3, + attention_dp_relax=False, + agent_hierarchy=[("root", 1), ("tool", 42)], + subagent_affinity_id="aff-xyz", + ), + conversation_params=types.SimpleNamespace(conversation_id="conv-999"), + cache_salt="tenant-alpha", + kv_cache_retention_config=types.SimpleNamespace( + token_range_retention_configs=[ + types.SimpleNamespace(token_start=0, token_end=16, priority=90, duration_ms=5000), + types.SimpleNamespace( + token_start=16, token_end=None, priority=50, duration_ms=None + ), + ], + decode_retention_priority=70, + decode_duration_ms=3000, + transfer_mode=1, # GDS + directory="/nvme/kv", + ), + kv_hints={ + "protocol_version": "0.1", + "message_id": "msg-01", + "extra_env_tag": "keep-me", + "actions": [ + { + "action_id": "act-1", + "action_type": "kv.prefetch", + "action_version": "1", + "payload": {"blocks": [1, 2, 3]}, + "custom_flag": True, + } + ], + }, + trace_headers={ + "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + "tracestate": "nv=1", + }, + thinking_budget={"budget": 256, "start_tokens": [1001], "end_tokens": [1002, 1003]}, + logits_processors=["custom_proc_a", "custom_proc_b"], + ) + + cmsg = encode_generation_requests([req], strict=True) + decoded_list = decode_submit_batch( + pb.session_pb2.ClientMessage.FromString(cmsg.SerializeToString()) + ) + assert len(decoded_list) == 1 + d = decoded_list[0] + + # Verify prompt & encoder tokens + assert d.handle == 101 + assert d.request_id == "req-full-sampling" + assert d.prompt_tokens == [1, 10, 20, 30] + assert d.encoder_input_tokens == [5, 6, 7] + assert d.streaming is True + assert d.queue_age_us == 4200 + + # Verify all 22 SamplingParams fields + s = d.sampling + assert s["num_sequences"] == 1 + assert s["beam_width"] == 4 + assert s["num_return_beams"] == 2 + assert s["beam_width_array"] == [2, 4] + assert math.isclose(s["temperature"], 0.75, rel_tol=1e-6) + assert s["top_k"] == 40 + assert math.isclose(s["top_p"], 0.92, rel_tol=1e-6) + assert math.isclose(s["top_p_decay"], 0.99, rel_tol=1e-6) + assert math.isclose(s["top_p_min"], 0.05, rel_tol=1e-6) + assert s["top_p_reset_ids"] == 13 + assert math.isclose(s["min_p"], 0.02, rel_tol=1e-6) + assert s["seed"] == 123456789 + assert math.isclose(s["repetition_penalty"], 1.15, rel_tol=1e-6) + assert math.isclose(s["presence_penalty"], 0.3, rel_tol=1e-6) + assert math.isclose(s["frequency_penalty"], 0.4, rel_tol=1e-6) + assert s["prompt_ignore_length"] == 8 + assert s["no_repeat_ngram_size"] == 3 + assert math.isclose(s["length_penalty"], 1.2, rel_tol=1e-6) + assert s["early_stopping"] == 1 + assert math.isclose(s["beam_search_diversity_rate"], 0.5, rel_tol=1e-6) + assert s["logit_bias"] == [(1, 1.5), (3, -2.25)] + assert s["logprobs_mode"] == "processed" + + # Verify all 7 StopParams fields + st = d.stop + assert st["max_tokens"] == 128 + assert st["min_tokens"] == 4 + assert st["end_id"] == 2 + assert st["pad_id"] == 0 + assert st["ignore_eos"] is False + assert st["sequences"] == [[99], [50, 51]] + assert st["bad_sequences"] == [[77], [88, 89]] + + # Verify OutputOptions + o = d.output + assert o["logprobs"] == 5 + assert o["logprob_rank"] is True + assert o["prompt_logprobs"] == 3 + assert o["tensors"] == { + "context_logits": True, + "generation_logits": True, + "encoder_output": True, + "routed_experts": True, + "additional_context": ["hidden_ctx"], + "additional_generation": ["hidden_gen"], + } + assert o["metrics"] == {"perf": True, "time_breakdown": True, "decoding_stats": True} + assert o["return_expanded_prompt"] is True + + # Verify LoRA and named logits processors + assert d.lora == {"adapter_id": 7, "name": "sql-lora", "path": "/models/sql", "format": "nemo"} + assert not hasattr(d, "thinking_budget") + assert d.logits_processors == ["custom_proc_a", "custom_proc_b"] + + # Verify SchedulingParams + TraceContext + assert math.isclose(d.sched["priority"], 0.85, rel_tol=1e-6) + assert d.sched["attention_dp_rank"] == 3 + assert d.sched["attention_dp_relax"] is False + assert d.sched["agent_hierarchy"] == [("root", 1), ("tool", 42)] + assert d.sched["subagent_affinity_id"] == "aff-xyz" + assert d.sched["conversation_id"] == "conv-999" + assert d.trace == { + "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + "tracestate": "nv=1", + } + + # Verify KvParams (salt + retention + hints) + assert d.kv["cache_salt"] == "tenant-alpha" + assert len(d.kv["retention"]["ranges"]) == 2 + assert d.kv["retention"]["ranges"][0] == { + "token_start": 0, + "token_end": 16, + "priority": 90, + "duration_ms": 5000, + } + assert d.kv["retention"]["decode_priority"] == 70 + assert d.kv["retention"]["transfer_mode"] == 1 + assert d.kv["retention"]["directory"] == "/nvme/kv" + assert d.kv["hints"]["protocol_version"] == "0.1" + assert d.kv["hints"]["extra_fields"] == {"extra_env_tag": "keep-me"} + assert d.kv["hints"]["actions"][0]["payload"] == {"blocks": [1, 2, 3]} + assert d.kv["hints"]["actions"][0]["extra_fields"] == {"custom_flag": True} + + +def test_guided_decoding_all_6_kinds_and_callable_rejection() -> None: + guided_cases = [ + ( + {"json_schema": {"type": "object", "properties": {"a": {"type": "integer"}}}}, + "json_schema", + ), + ({"json_object": True}, "json_object"), + ({"regex": r"[A-Z]{3}-\d{4}"}, "regex"), + ({"ebnf_grammar": 'root ::= "yes" | "no"'}, "ebnf_grammar"), + ({"structural_tag": '{"type":"triggered_tags"}'}, "structural_tag"), + ({"choice": ["alpha", "beta", "gamma"]}, "choice"), + ] + reqs = [ + _MockGenerationRequest( + id=i + 1, + prompt_token_ids=[1, 2, 3], + sampling_params=_MockSamplingParams(guided_decoding=gd), + ) + for i, (gd, _k) in enumerate(guided_cases) + ] + cmsg = encode_generation_requests(reqs, strict=True) + decoded = decode_submit_batch(cmsg) + assert len(decoded) == 6 + for idx, (_gd, expected_kind) in enumerate(guided_cases): + assert decoded[idx].guided["kind"] == expected_kind + assert decoded[5].guided["choices"] == ["alpha", "beta", "gamma"] + + # Request.thinking_budget was removed from v1.1 wire contract; callable ThinkingBudgetLogitsProcessor + # is rejected in strict proto mode just like any other arbitrary Python callable. + tb_proc = ThinkingBudgetLogitsProcessor(64, [151667], [151668]) + tb_req = _MockGenerationRequest( + id=99, + prompt_token_ids=[1, 2], + sampling_params=_MockSamplingParams(logits_processor=tb_proc), + ) + with pytest.raises(UnsupportedCallableError): + encode_generation_requests([tb_req], strict=True) + + # Arbitrary Python callable logits_processor MUST raise UnsupportedCallableError in strict mode + bad_req = _MockGenerationRequest( + id=100, + prompt_token_ids=[1, 2], + sampling_params=_MockSamplingParams( + logits_processor=lambda rid, logits, tids, sp, cid: None + ), + ) + with pytest.raises(UnsupportedCallableError): + encode_generation_requests([bad_req], strict=True) + + +def test_multimodal_media_and_preprocessed_inline_shm_blob() -> None: + blobs = LocalBlobStore() + + # 1. MEDIA mode with URL, inline bytes, BlobLocation, and CAP-20 io_options/processor_options + media_blob = blobs.put_blob(b"FAKE-VIDEO-BYTES-1234567890", session_id=1, handle=201) + req_media = _MockGenerationRequest( + id=201, + prompt_token_ids=[1, 32000, 32001, 5], + sampling_params=_MockSamplingParams(return_expanded_prompt=True), + multimodal_params={ + "media": [ + { + "modality": "image", + "url": "https://example.invalid/cat.png", + "mime_type": "image/png", + "uuid": "u-img-1", + "placeholder_index": 0, + }, + { + "modality": "audio", + "data": b"\x00\x01\x02\x03", + "mime_type": "audio/wav", + "placeholder_index": 1, + }, + { + "modality": "video", + "blob": media_blob, + "mime_type": "video/mp4", + "placeholder_index": 2, + }, + ], + "io_options": {"video.num_frames": 8, "image.do_resize": True}, + "processor_options": {"max_pixels": 1003520, "fps": 2.5}, + }, + ) + cmsg_m = encode_generation_requests([req_media], blob_store=blobs, session_id=1, strict=True) + dec_m = decode_submit_batch(cmsg_m, blob_store=blobs, session_id=1)[0] + assert dec_m.mm["mode"] == "media" + assert len(dec_m.mm["media"]) == 3 + assert dec_m.mm["media"][0]["url"] == "https://example.invalid/cat.png" + assert dec_m.mm["media"][0]["uuid"] == "u-img-1" + assert dec_m.mm["media"][1]["data"] == b"\x00\x01\x02\x03" + assert dec_m.mm["media"][2]["data"] == b"FAKE-VIDEO-BYTES-1234567890" + assert dec_m.mm["io_options"] == {"video.num_frames": 8, "image.do_resize": True} + assert dec_m.mm["processor_options"] == {"max_pixels": 1003520, "fps": 2.5} + + # 2. PREPROCESSED mode across INLINE, SHM, and BLOB_FETCH deliveries + pixel_tensor = _make_f32_tensor((2, 4), [float(i) for i in range(8)]) + emb_tensor = _make_f32_tensor((4, 3), [float(i) * 0.5 for i in range(12)]) + mm_input = types.SimpleNamespace( + multimodal_hashes=[[1, 2, 3, 4, 5, 6, 7, 8]], + multimodal_positions=[4], + multimodal_lengths=[16], + multimodal_uuids=["img-uuid-0"], + multimodal_item_run_cu_offsets=[0, 2], + multimodal_run_positions=[4, 12], + multimodal_run_lengths=[8, 8], + ) + item_meta = types.SimpleNamespace( + item_refs=[("image", 0)], + encoder_token_lengths=[16], + output_embedding_lengths=[16], + input_partitions={ + "image": { + "pixel_values": types.SimpleNamespace(item_axis=0, item_lengths=(2,)), + } + }, + ) + req_pre = _MockGenerationRequest( + id=202, + prompt_token_ids=[1, 2, 3, 4] + [999] * 16, + sampling_params=_MockSamplingParams(), + multimodal_params={ + "multimodal_input": mm_input, + "multimodal_data": { + "image": {"pixel_values": pixel_tensor, "grid_thw": [1, 2, 2]}, + "multimodal_encoder_item_metadata": item_meta, + }, + "embeddings": [(0, emb_tensor)], + }, + ) + + for delivery_mode in ( + pb.common_pb2.TENSOR_DELIVERY_INLINE, + pb.common_pb2.TENSOR_DELIVERY_SHM, + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, + ): + cmsg_p = encode_generation_requests( + [req_pre], + blob_store=blobs, + session_id=1, + delivery_pref=(delivery_mode,), + max_inline_bytes=1024 if delivery_mode == pb.common_pb2.TENSOR_DELIVERY_INLINE else 0, + strict=True, + ) + # Verify actual wire location kind matches requested delivery + mi0 = cmsg_p.submit_batch.requests[0].mm.model_inputs[0] + if mi0.path == "image.pixel_values": + loc = mi0.tensor.WhichOneof("location") + expected_loc = { + pb.common_pb2.TENSOR_DELIVERY_INLINE: "inline_bytes", + pb.common_pb2.TENSOR_DELIVERY_SHM: "shm", + pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH: "blob", + }[delivery_mode] + assert loc == expected_loc + + dec_p = decode_submit_batch( + cmsg_p, + blob_store=blobs, + session_id=1, + unlink_shm=(delivery_mode == pb.common_pb2.TENSOR_DELIVERY_SHM), + )[0] + assert dec_p.mm["mode"] == "preprocessed" + assert dec_p.mm["items"][0]["hash_i32"] == [1, 2, 3, 4, 5, 6, 7, 8] + assert dec_p.mm["items"][0]["run_positions"] == [4, 12] + assert dec_p.mm["model_inputs"]["image.grid_thw"] == [1, 2, 2] + assert dec_p.mm["model_inputs"]["image.pixel_values"].reshape(-1).tolist() == [ + float(i) for i in range(8) + ] + assert dec_p.mm["embeddings"][0]["tensor"].reshape(-1).tolist() == [ + float(i) * 0.5 for i in range(12) + ] + assert dec_p.mm["item_metadata"]["item_refs"] == [("image", 0)] + assert dec_p.mm["item_metadata"]["partitions"][0]["item_lengths"] == [2] + + +def test_step_frame_beam_replace_stop_index_logprobs_prompt_logprobs_perf_spec_tensors() -> None: + blobs = LocalBlobStore() + + # PromptLogprobs: inline + SHM + BLOB_FETCH + sharded has_more + plp_entries = [ + {10: ZmqLogprob(-0.1, 1), 11: ZmqLogprob(-1.2, 2)}, + {20: ZmqLogprob(-0.3, 1), 21: ZmqLogprob(-2.0, 2)}, + {30: ZmqLogprob(-0.5, 3), 31: ZmqLogprob(-0.2, 1)}, + ] + plp_ids = [10, 20, 30] + for mode_deliv, max_inl in [ + (pb.common_pb2.TENSOR_DELIVERY_INLINE, 0), + (pb.common_pb2.TENSOR_DELIVERY_SHM, 1), + (pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH, 1), + ]: + enc_plp = encode_prompt_logprobs( + plp_entries, + plp_ids, + start=2, + has_more=True, + max_inline_bytes=max_inl, + delivery_pref=(mode_deliv,), + blob_store=blobs, + session_id=1, + handle=401, + ) + dec_plp = decode_prompt_logprobs( + enc_plp, + blob_store=blobs, + session_id=1, + unlink_shm=(mode_deliv == pb.common_pb2.TENSOR_DELIVERY_SHM), + ) + assert dec_plp["start"] == 2 + assert dec_plp["count"] == 3 + assert dec_plp["has_more"] is True + assert dec_plp["ids"] == [10, 20, 30] + assert dec_plp["entries"][2][30].rank == 3 + assert math.isclose(dec_plp["entries"][0][10].logprob, -0.1, rel_tol=1e-5) + + # Full step response with beam replace_from, stop_index, logprobs, streaming OutputTensor, + # routed_experts, context_logits, encoder_output, perf timing, time_breakdown, spec stats + ctx_logits = _make_f32_tensor((3, 4), [float(i) for i in range(12)]) + gen_logits_seg = _make_f32_tensor((2, 4), [float(i) * 0.25 for i in range(8)]) + enc_out = _make_f32_tensor((2, 2), [1.0, 2.0, 3.0, 4.0]) + routed_exp = _make_i16_tensor((2, 2), [0, 3, -1, 1]) + + rsp = ZmqStepResponse( + client_id=401, + request_id=7777, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + sequence_index=1, + output_token_ids=[[100, 101]], + cum_log_probs=[-0.75], + log_probs=[ + [ + {100: ZmqLogprob(-0.25, 1), 200: ZmqLogprob(-1.1, 2)}, + {101: ZmqLogprob(-0.5, 2), 201: ZmqLogprob(-0.4, 1)}, + ] + ], + finish_reasons=[ZmqFinishReason.STOP_WORDS], + stop_index=1, + replace_from=0, + row_flags=wc.ROW_FLAG_FIRST_ROW | wc.ROW_FLAG_SEQ_FINAL | wc.ROW_FLAG_REQUEST_DONE, + prompt_len=3, + effective_max_tokens=16, + max_tokens_clamped=True, + expanded_prompt_tokens=[1, 2, 3, 4], + prompt_logprobs={"entries": plp_entries, "ids": plp_ids, "start": 0}, + context_logits=ctx_logits, + encoder_output=enc_out, + routed_experts=routed_exp, + additional_context_outputs={"ctx_feat": _make_f32_tensor((2,), [9.0, 8.0])}, + streaming_tensor_ranges=[ + (pb.output_pb2.OUTPUT_TENSOR_KIND_GENERATION_LOGITS, "", (0, 2), gen_logits_seg) + ], + cached_tokens=2, + decoding_iter=5, + avg_decoded_tokens_per_iter=1.8, + per_pos_drafted=[5, 4], + per_pos_accepted=[4, 2], + spec_dec_totals=(6, 9), + request_perf_metrics={ + "host_accept_ns": 1000, + "first_scheduled_us": 60, + "first_token_us": 200, + "last_token_us": 950, + "kv_transfer_start_us": 70, + "kv_transfer_end_us": 120, + "kv_transfer_bytes": 4096, + "kv_blocks": {"allocated": 8, "new_blocks": 6, "reused": 2, "missed": 6}, + "kv_cache_hit_rate": 0.25, + "first_iter": 10, + "last_iter": 15, + }, + time_breakdown_metrics={ + "steps": [ + { + "iter": 11, + "forward_start_us": 100, + "forward_end_us": 150, + "sample_start_us": 150, + "sample_end_us": 160, + "gpu_forward_ms": 0.45, + "gpu_sample_ms": 0.05, + "token_us": 165, + } + ], + "ctx_chunks": [], + "ctx_gpu_forward_ms": 1.2, + "ctx_gpu_sample_ms": 0.1, + }, + ), + ) + + err_rsp = ZmqStepResponse( + client_id=402, + request_id=7778, + error_msg="grammar compile failed", + error_info={ + "code": int(pb.common_pb2.ERROR_CODE_INVALID_ARGUMENT), + "field": "guided.ebnf_grammar", + }, + ) + + srv_msg = encode_step_responses( + [rsp, err_rsp], + frame_seq=7, + iter_first=10, + iter_last=15, + tensor_delivery=(pb.common_pb2.TENSOR_DELIVERY_BLOB_FETCH,), + max_inline_bytes=0, + blob_store=blobs, + session_id=1, + ) + out_list = decode_step_frame(srv_msg, blob_store=blobs, session_id=1) + assert len(out_list) == 2 + + # Verify normal row + o0 = out_list[0] + assert o0.client_id == 401 and o0.request_id == 7777 and not o0.has_error() + r0 = o0.result + assert r0.is_final is True and r0.is_request_done is True + assert r0.sequence_index == 1 + assert r0.output_token_ids == [[100, 101]] + assert r0.stop_index == 1 + assert r0.replace_from == 0 + assert r0.cum_log_probs == pytest.approx([-0.75]) + assert r0.log_probs[0][0][100].logprob == pytest.approx(-0.25) + assert r0.log_probs[0][1][101].rank == 2 + assert r0.cached_tokens == 2 + assert r0.decoding_iter == 5 + assert r0.avg_decoded_tokens_per_iter == pytest.approx(1.8) + assert r0.per_pos_drafted == [5, 4] + assert r0.per_pos_accepted == [4, 2] + assert r0.spec_dec_totals == (6, 9) + assert r0.request_perf_metrics["kv_transfer_bytes"] == 4096 + assert r0.request_perf_metrics["kv_blocks"]["reused"] == 2 + assert r0.time_breakdown_metrics["ctx_gpu_forward_ms"] == pytest.approx(1.2) + assert r0.time_breakdown_metrics["steps"][0]["iter"] == 11 + assert r0.context_logits.reshape(-1).tolist() == [float(i) for i in range(12)] + assert r0.generation_logits.reshape(-1).tolist() == pytest.approx( + [float(i) * 0.25 for i in range(8)] + ) + assert r0.encoder_output.reshape(-1).tolist() == [1.0, 2.0, 3.0, 4.0] + assert r0.routed_experts.reshape(-1).tolist() == [0, 3, -1, 1] + assert r0.additional_context_outputs["ctx_feat"].reshape(-1).tolist() == [9.0, 8.0] + assert r0.expanded_prompt_tokens == [1, 2, 3, 4] + assert r0.max_tokens_clamped is True + assert r0.streaming_tensor_ranges[0][2] == (0, 2) + + # Verify error row + o1 = out_list[1] + assert o1.client_id == 402 and o1.has_error() + assert o1.error_msg == "grammar compile failed" + assert o1.error_info["code"] == int(pb.common_pb2.ERROR_CODE_INVALID_ARGUMENT) + assert o1.error_info["field"] == "guided.ebnf_grammar" + + +# ============================================================================ +# 3. CancelBatch, Multi-Frontend Routing, Backlog Merge & Backpressure +# ============================================================================ + + +def test_cancel_batch_round_trip() -> None: + h0 = (0 << FRONTEND_ID_SHIFT) | 11 + cb = decode_cancel_batch( + encode_cancel_batch( + [h0], reason=pb.common_pb2.CANCEL_REASON_STOP_STRING, consumed_frame_seq=1 + ) + ) + assert cb.cancels == [(h0, int(pb.common_pb2.CANCEL_REASON_STOP_STRING))] + assert cb.consumed_frame_seq == 1 + assert cb.all is False + + # Also test cancel_batch(all_flag=True) roundtrip + cb_all = decode_cancel_batch( + encode_cancel_batch( + all_flag=True, all_reason=pb.common_pb2.CANCEL_REASON_SHUTDOWN, consumed_frame_seq=9 + ) + ) + assert cb_all.all is True + assert cb_all.all_reason == int(pb.common_pb2.CANCEL_REASON_SHUTDOWN) + assert cb_all.consumed_frame_seq == 9 + + +# ============================================================================ +# 4. ControlService (all 13 RPCs + 8 Admin subcommands) & BlobService (3 RPCs) +# ============================================================================ + + +def test_materialize_embedding_bias() -> None: + # Sparse logit_bias -> dense embedding_bias materialization roundtrip + bias_tensor = materialize_embedding_bias([(1, 1.5), (3, -2.25)], vocab_size=5) + assert bias_tensor.shape == (5,) + assert bias_tensor.reshape(-1).tolist() == pytest.approx([0.0, 1.5, 0.0, -2.25, 0.0]) + + +class _CapQueue: + """Records the frames sent on a queue.""" + + def __init__(self, hmac_key: bytes) -> None: + self.hmac_key = hmac_key + self.sent: list[bytes] = [] + + def send_raw(self, raw: bytes) -> None: + self.sent.append(raw) + + +def _fake_worker(**kwargs: object) -> types.SimpleNamespace: + popped: list[int] = [] + attrs: dict[str, object] = dict( + result_queue=None, + frontend_result_queues=None, + _refused_client_ids=set(), + _has_background_error=lambda: False, + _pop_result=popped.append, + popped=popped, + ) + attrs.update(kwargs) + return types.SimpleNamespace(**attrs) + + +def test_selfreview_zmq_security_and_correctness_regressions( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Regressions for K2, K7, K12, K13, K21, K26, K32.""" + import hmac + + from tensorrt_llm.executor import base_worker + from tensorrt_llm.executor.ipc import RawServeEngineFrame, ZeroMqQueue + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + worker_decode_raw_frame, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import ( + proxy_decode_raw_frame, + proxy_send_request, + ) + + # K13 & K32: ZeroMqQueue._parse_data verifies HMAC BEFORE returning raw 0x53 frame, + # ignores 0x53 when serve_engine_wire_enabled=False, and blocks pickle when strict=True. + def _make_dummy_q(*, enabled: bool, strict: bool, hmac_key: bytes | None) -> ZeroMqQueue: + q = ZeroMqQueue.__new__(ZeroMqQueue) + q.socket = None + q.context = None + q.use_hmac_encryption = hmac_key is not None + q.hmac_key = hmac_key + q._serve_engine_wire_enabled = enabled + q._serve_engine_wire_strict = strict + return q + + key = b"k" * 32 + payload = bytes([FRAME_MAGIC, int(ChannelTag.CLIENT_MESSAGE)]) + b"\x00" * 16 + good_sig = hmac.new(key, payload, hashlib.sha256).digest() + forged_sig = b"\x00" * 32 + + # Non-opt-in queue with HMAC MUST reject forged 0x53 frame + q_plain = _make_dummy_q(enabled=False, strict=False, hmac_key=key) + with pytest.raises(RuntimeError, match="HMAC"): + q_plain._parse_data(payload + forged_sig) + + # Opt-in queue with HMAC MUST reject forged 0x53 frame and accept valid 0x53 frame + q_opt = _make_dummy_q(enabled=True, strict=True, hmac_key=key) + with pytest.raises(RuntimeError, match="HMAC"): + q_opt._parse_data(payload + forged_sig) + assert q_opt._parse_data(payload + good_sig) == RawServeEngineFrame(payload + good_sig) + + # K32: strict queue MUST reject pickled payload BEFORE pickle.loads! + pickled_body = pickle.dumps({"evil": True}) + pickled_sig = hmac.new(key, pickled_body, hashlib.sha256).digest() + with pytest.raises(StrictProtoWireError): + q_opt._parse_data(pickled_body + pickled_sig) + + # K12 & K26: LocalBlobStore removes session_id=0 wildcard, randomizes blob_id, rejects negative bounds + lbs = LocalBlobStore() + loc_a = lbs.put_blob(b"alpha-data", session_id=10) + loc_b = lbs.put_blob(b"beta-data", session_id=20) + assert loc_a.blob_id != 1 or loc_b.blob_id != 2 + with pytest.raises(PermissionError): + lbs.get_blob(loc_a.blob_id, session_id=0) + with pytest.raises(PermissionError): + lbs.get_blob(loc_a.blob_id, session_id=20) + with pytest.raises(ValueError): + lbs.get_blob(loc_a.blob_id, session_id=10, offset=-1) + with pytest.raises(ValueError): + lbs.get_blob(loc_a.blob_id, session_id=10, length=-1) + assert lbs.release(session_id=0, blob_ids=[loc_a.blob_id]) == 0 + assert lbs.get_blob(loc_a.blob_id, session_id=10)[0] == b"alpha-data" + + # K2: Non-beam n > 1 responses stay separate in proxy_decode_raw_frame and is_final only on request_done + n2_frame = encode_step_responses( + [ + ZmqStepResponse( + client_id=50, + request_id=50, + result=ZmqStepResult( + sequence_index=0, + output_token_ids=[[100]], + is_final=True, + is_request_done=False, + finish_reasons=[ZmqFinishReason.END_ID], + row_flags=wc.ROW_FLAG_SEQ_FINAL, + ), + ), + ZmqStepResponse( + client_id=50, + request_id=50, + result=ZmqStepResult( + sequence_index=1, + output_token_ids=[[200]], + is_final=False, + is_request_done=False, + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + row_flags=0, + ), + ), + ], + frame_seq=1, + ) + raw_n2 = pack_raw_frame( + ChannelTag.SERVER_MESSAGE, 0, n2_frame.SerializeToString(), hmac_key=key + ) + non_beam_results = { + 50: types.SimpleNamespace(sampling_params=_MockSamplingParams(use_beam_search=False)) + } + decoded_n2 = proxy_decode_raw_frame(raw_n2, hmac_key=key, results_map=non_beam_results) + assert len(decoded_n2) == 2 + assert [r.result.sequence_index for r in decoded_n2] == [0, 1] + assert decoded_n2[0].result.is_final is False + assert decoded_n2[1].result.is_final is False + + # K7: StartProfileRequest / StopProfileRequest round-trip in strict mode + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "strict") + + from tensorrt_llm.executor.request import StartProfileRequest, StopProfileRequest + + start_req = StartProfileRequest( + output_dir="/tmp/prof", + start_step=1, + num_steps=3, + activities=["cpu"], + ack_addr=("inproc://ack-start", b"\xab" * 16), + ) + stop_req = StopProfileRequest(ack_addr=("inproc://ack-stop", None)) + + cap_q = _CapQueue(key) + assert proxy_send_request(cap_q, start_req, mode="strict") is True + assert proxy_send_request(cap_q, stop_req, mode="strict") is True + assert len(cap_q.sent) == 2 + dec_start = worker_decode_raw_frame(cap_q.sent[0], hmac_key=key) + dec_stop = worker_decode_raw_frame(cap_q.sent[1], hmac_key=key) + assert len(dec_start) == 1 and type(dec_start[0]).__name__ == "StartProfileRequest" + assert dec_start[0].ack_addr == ("inproc://ack-start", b"\xab" * 16) + assert len(dec_stop) == 1 and type(dec_stop[0]).__name__ == "StopProfileRequest" + assert dec_stop[0].ack_addr == ("inproc://ack-stop", None) + + # K21: Multi-frontend worker_publish_responses clamps out-of-range frontend_id without IndexError + lane0 = _CapQueue(key) + lane1 = _CapQueue(key) + fake_worker = _fake_worker(frontend_result_queues=[lane0, lane1]) + monkeypatch.setattr(base_worker, "_maybe_wrap_response", lambda _worker, r: r) + out_of_range_cid = (99 << FRONTEND_ID_SHIFT) | 7 + published = worker_publish_responses( + fake_worker, + [ + ZmqStepResponse( + client_id=out_of_range_cid, + request_id=7, + result=ZmqStepResult(output_token_ids=[[42]], is_final=True, is_request_done=True), + ) + ], + mode="strict", + ) + assert published is True + assert len(lane0.sent) + len(lane1.sent) == 1 + + +def test_encode_step_responses_deserializes_lazy_llm_result() -> None: + """Regression for Z5: LlmResult._result bytes must be deserialized before reading finish_reasons.""" + + class _InnerResult: + def __init__(self) -> None: + self.output_token_ids = [[42, 43]] + self.finish_reasons = [ZmqFinishReason.END_ID] + self.sequence_index = 0 + self.decoding_iter = 2 + self.avg_decoded_tokens_per_iter = 1.0 + self.context_phase_params = None + self.request_perf_metrics = None + + class _LazyLlmResult: + def __init__(self) -> None: + self._result: bytes | _InnerResult = b"serialized-cpp-result" + self.is_final = True + self.cached_tokens = 0 + self.cum_log_probs = None + self.log_probs = None + self.per_pos_drafted = None + self.per_pos_accepted = None + self.spec_dec_totals = None + self.ctx_usage = None + self.remote_tail_start = None + self.time_breakdown_metrics = None + self.context_logits = None + self.generation_logits = None + self.encoder_output = None + self.additional_context_outputs = None + self.additional_generation_outputs = None + + def deserialize(self) -> None: + self._result = _InnerResult() + + def __getattr__(self, item: str) -> object: + return getattr(self._result, item) + + @dataclasses.dataclass + class _LazyRsp: + client_id: int = 901 + request_id: int = 901 + error_msg: Optional[str] = None + result: _LazyLlmResult = dataclasses.field(default_factory=_LazyLlmResult) + + def has_error(self) -> bool: + return self.error_msg is not None + + smsg = encode_step_responses([_LazyRsp()], frame_seq=1, iter_first=1, iter_last=1) + decoded = decode_step_frame(smsg) + assert len(decoded) == 1 + assert decoded[0].result is not None + assert decoded[0].result.is_final is True + assert decoded[0].result.output_token_ids == [[42, 43]] + assert decoded[0].result.finish_reasons[0].name == ZmqFinishReason.END_ID.name + + +# ============================================================================ +# 5. Real pyzmq end-to-end tests (skipped only if pyzmq absent) +# ============================================================================ + + +# ============================================================================ +# 6. Executor integration +# ============================================================================ + + +def test_ipc_frame_constants_match_transport() -> None: + from tensorrt_llm.executor import ipc + from tensorrt_llm.executor.zmq_wire import transport + + assert ipc.SERVE_ENGINE_FRAME_MAGIC == transport.FRAME_MAGIC + assert ipc.SERVE_ENGINE_MIN_FRAME_SIZE == transport.MIN_FRAME_SIZE + assert ipc.SERVE_ENGINE_CHANNEL_TAGS == frozenset(int(t) for t in ChannelTag) + + +def _real_generation_request(*, client_id: int = 21) -> object: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + req = GenerationRequest( + [5, 6, 7], + sampling_params=SamplingParams(max_tokens=8, temperature=0.5), + ) + req.set_id(client_id) + return req + + +def test_proxy_send_request_round_trip() -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + worker_decode_raw_frame, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_send_request + + key = os.urandom(32) + reset_global_wire_stats() + + q = _CapQueue(key) + assert proxy_send_request(q, _real_generation_request(), mode="off") is False + assert q.sent == [] + + assert proxy_send_request(q, _real_generation_request(), mode="auto") is True + assert len(q.sent) == 1 and is_raw_proto_frame(q.sent[0]) + (decoded,) = worker_decode_raw_frame(q.sent[0], key) + assert isinstance(decoded, GenerationRequest) + assert decoded.id == 21 + assert list(decoded.prompt_token_ids) == [5, 6, 7] + assert decoded.sampling_params.max_tokens == 8 + assert decoded.sampling_params.temperature == pytest.approx(0.5) + assert decoded.disaggregated_params is None + + assert get_global_wire_stats()["pickle_fallbacks"] == 0 + + # The batching sender owns the socket: the frame goes through its send(). + sender = types.SimpleNamespace(items=[]) + sender.send = sender.items.append + assert proxy_send_request(q, _real_generation_request(), mode="strict", request_sender=sender) + assert len(q.sent) == 1 and len(sender.items) == 1 + reset_global_wire_stats() + + +def test_incoming_requests_raw_frames_and_strict_rejection() -> None: + from tensorrt_llm.executor.ipc import RawServeEngineFrame + from tensorrt_llm.executor.request import CancellingRequest + from tensorrt_llm.executor.worker import _incoming_requests + + key = os.urandom(32) + + class _ListQueue: + hmac_key = key + + def __init__(self, messages: list[object]) -> None: + self._messages = list(messages) + + def get(self) -> object: + return self._messages.pop(0) + + cancel = encode_cancel_batch([33], reason=pb.common_pb2.CANCEL_REASON_CLIENT_DISCONNECTED) + cancel_frame = RawServeEngineFrame( + pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cancel.SerializeToString(), key) + ) + sentinel_frame = RawServeEngineFrame(pack_raw_frame(ChannelTag.SHUTDOWN_SENTINEL, 0, b"", key)) + + items = list( + _incoming_requests( + _ListQueue(["a", cancel_frame, sentinel_frame, "after sentinel"]), + serve_engine_wire_mode="auto", + ) + ) + assert items[0] == "a" + assert isinstance(items[1], CancellingRequest) and items[1].id == 33 + assert len(items) == 2 + + with pytest.raises(StrictProtoWireError): + list( + _incoming_requests( + _ListQueue([[pickle.dumps("x")], None]), serve_engine_wire_mode="strict" + ) + ) + + +def test_request_sender_keeps_raw_frames_in_order() -> None: + import queue as _queue + + from tensorrt_llm.executor.ipc import RawServeEngineFrame + from tensorrt_llm.llmapi.engine_client.proxy import _RequestSender + + class _RecordingQueue: + def __init__(self) -> None: + self.events: list[tuple[str, object]] = [] + + def put(self, batch: list[bytes]) -> None: + self.events.append(("put", list(batch))) + + def send_raw(self, data: bytes) -> None: + self.events.append(("raw", data)) + + def put_noblock(self, obj: object, retry: int = 1) -> None: + self.events.append(("put_noblock", obj)) + + rq = _RecordingQueue() + sender = _RequestSender(rq, _queue.Queue(), serve_engine_wire_mode="off") + sender.send(b"p1") + sender.send(RawServeEngineFrame(b"r1")) + sender.send(b"p2") + sender.send(b"p3") + assert sender.close(timeout=5.0, send_sentinel=True) is False + flat = [] + for kind, val in rq.events: + if kind == "put": + flat.extend(("p", v) for v in val) + else: + flat.append((kind, val)) + assert flat == [("p", b"p1"), ("raw", b"r1"), ("p", b"p2"), ("p", b"p3"), ("put_noblock", None)] + + +@pytest.mark.parametrize("mode", ["auto", "strict"]) +def test_executor_queues_round_trip_over_real_sockets( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + """A request and its response cross real ZeroMqQueue / FusedIpcQueue sockets as frames.""" + from tensorrt_llm.executor import base_worker + from tensorrt_llm.executor.ipc import FusedIpcQueue, IpcQueue, RawServeEngineFrame + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.worker import _incoming_requests + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + reset_global_wire_stats, + send_shutdown_sentinel, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import ( + proxy_decode_raw_frame, + proxy_send_request, + ) + + flags = dict(serve_engine_wire_enabled=True, serve_engine_wire_strict=mode == "strict") + reset_global_wire_stats() + proxy_req = IpcQueue(is_server=True, name="t_proxy_request_queue", **flags) + worker_req = IpcQueue( + proxy_req.address, is_server=False, name="t_worker_request_queue", **flags + ) + proxy_res = FusedIpcQueue( + is_server=True, fuse_message=False, name="t_proxy_result_queue", **flags + ) + worker_res = FusedIpcQueue( + proxy_res.address, is_server=False, fuse_message=False, name="t_worker_result_queue" + ) + try: + # A bound PAIR socket blocks on send until its peer connects, so connect both + # clients before anything is sent. + worker_req.setup_lazily() + worker_res.queue.setup_lazily() + assert proxy_send_request(proxy_req, _real_generation_request(client_id=77), mode=mode) + send_shutdown_sentinel(proxy_req) + received = list(_incoming_requests(worker_req, serve_engine_wire_mode=mode)) + assert len(received) == 1 and isinstance(received[0], GenerationRequest) + assert received[0].id == 77 and list(received[0].prompt_token_ids) == [5, 6, 7] + + monkeypatch.setattr(base_worker, "_maybe_wrap_response", lambda _worker, r: r) + worker = _fake_worker(result_queue=worker_res) + rsp = ZmqStepResponse( + client_id=77, + request_id=77, + result=ZmqStepResult( + output_token_ids=[[8, 9]], + finish_reasons=[ZmqFinishReason.LENGTH], + is_final=True, + is_request_done=True, + ), + ) + assert worker_publish_responses(worker, [rsp], mode=mode) is True + assert worker.popped == [77] + send_shutdown_sentinel(worker_res) + + frame = proxy_res.get() + assert isinstance(frame, RawServeEngineFrame) + decoded = proxy_decode_raw_frame(frame.data, proxy_res.queue.hmac_key) + assert len(decoded) == 1 + assert decoded[0].client_id == 77 + assert decoded[0].result.output_token_ids == [[8, 9]] + assert decoded[0].result.is_final is True + sentinel = proxy_res.get() + assert proxy_decode_raw_frame(sentinel.data, proxy_res.queue.hmac_key) is None + + if mode == "strict": + # A pickled message on a strict queue is rejected before pickle.loads. + worker_res.put(["pickled"]) + with pytest.raises(StrictProtoWireError): + proxy_res.get() + finally: + for q in (worker_req, proxy_req, worker_res, proxy_res): + q.close() + reset_global_wire_stats() + + +class _WordTokenizer: + """Tokenizes the stop / bad words of the tests below.""" + + WORDS = {"\n\nUser:": [11, 12, 13], "!": [7], "bad words": [21, 22]} + + def encode(self, text: str, add_special_tokens: bool = False) -> list[int]: + return list(self.WORDS[text]) + + +def _send_real_request(req: object, mode: str = "auto") -> object: + """Send ``req`` like the proxy and rebuild it like rank 0; None if it took the pickle path.""" + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_decode_raw_frame + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_send_request + + key = os.urandom(32) + q = _CapQueue(key) + if not proxy_send_request(q, req, mode=mode): + assert q.sent == [] + return None + (decoded,) = worker_decode_raw_frame(q.sent[0], key) + return decoded + + +def test_multi_token_stop_and_bad_words_rebuild_like_the_pickle_path() -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + sp = SamplingParams(max_tokens=8, stop=["\n\nUser:", "!"], stop_token_ids=[5], bad="bad words") + sp._setup_word_ids(_WordTokenizer()) + req = GenerationRequest([1, 2, 3], sampling_params=sp).set_id(41) + decoded = _send_real_request(req) + assert isinstance(decoded, GenerationRequest) + rebuilt = decoded.sampling_params + assert sorted(rebuilt._get_stop_words()) == sorted(sp._get_stop_words()) + assert sorted(rebuilt._get_bad_words()) == sorted(sp._get_bad_words()) + + +def test_worker_fails_only_the_request_it_cannot_rebuild(monkeypatch: pytest.MonkeyPatch) -> None: + from tensorrt_llm.executor.ipc import RawServeEngineFrame + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.worker import _incoming_requests + from tensorrt_llm.executor.zmq_wire import worker_bridge + + key = os.urandom(32) + reqs = [_real_generation_request(client_id=cid) for cid in (51, 52)] + cmsg = encode_generation_requests(reqs, strict=True) + frame = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg.SerializeToString(), key) + + rebuild = worker_bridge._reconstruct_generation_request + + def _reject_51(dreq: object, worker: object = None) -> object: + if getattr(dreq, "handle", None) == 51: + raise ValueError("lora_ckpt_source must be 'hf' or 'nemo'") + return rebuild(dreq, worker=worker) + + monkeypatch.setattr(worker_bridge, "_reconstruct_generation_request", _reject_51) + + class _ListQueue: + hmac_key = key + + def __init__(self, items: list[object]) -> None: + self.items = list(items) + + def get(self) -> object: + return self.items.pop(0) + + items = list( + _incoming_requests( + _ListQueue([RawServeEngineFrame(frame), None]), serve_engine_wire_mode="strict" + ) + ) + assert isinstance(items[0], ErrorResponse) and items[0].client_id == 51 + assert "lora_ckpt_source" in str(items[0].error_msg) + assert isinstance(items[1], GenerationRequest) and items[1].id == 52 + + +def test_auto_pickles_a_python_logits_processor_and_strict_rejects_it() -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + ) + from tensorrt_llm.sampling_params import SamplingParams + + reset_global_wire_stats() + sp = SamplingParams( + max_tokens=8, logits_processor=ThinkingBudgetLogitsProcessor(64, [151667], [151668]) + ) + req = GenerationRequest([1, 2, 3], sampling_params=sp).set_id(61) + assert _send_real_request(req, mode="auto") is None + assert get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(UnsupportedCallableError): + _send_real_request(req, mode="strict") + reset_global_wire_stats() + + +def test_strict_rejects_postprocess_workers() -> None: + from tensorrt_llm.executor.utils import PostprocWorkerConfig + from tensorrt_llm.llmapi.engine_client.proxy import _serve_engine_postproc_config + + config = PostprocWorkerConfig(num_postprocess_workers=2) + assert _serve_engine_postproc_config(config, "auto") is config + assert ( + _serve_engine_postproc_config(PostprocWorkerConfig(), "strict").num_postprocess_workers == 0 + ) + with pytest.raises(ValueError, match="num_postprocess_workers"): + _serve_engine_postproc_config(config, "strict") + + +def test_await_response_helper_ignores_the_env_without_ipc_queues( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from tensorrt_llm.executor.base_worker import AwaitResponseHelper + + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "strict") + helper = AwaitResponseHelper(types.SimpleNamespace(enable_postprocess_parallel=False)) + # RPC / Ray workers never get the ZeroMQ IPC result queues, so the wire stays off. + assert helper.serve_engine_wire_mode == "off" + + +def _uncarried_cases() -> list[tuple[str, dict[str, object], dict[str, object]]]: + return [ + ("exclude_input_from_output", dict(exclude_input_from_output=False), {}), + ("watermarking", dict(watermarking=False), {}), + ("prompt_adapter_request", {}, dict(prompt_adapter_request=types.SimpleNamespace(id=1))), + ] + + +@pytest.mark.parametrize("case", _uncarried_cases(), ids=lambda c: c[0]) +def test_fields_without_a_contract_field_take_the_pickle_path( + case: tuple[str, dict[str, object], dict[str, object]], +) -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + ) + from tensorrt_llm.sampling_params import SamplingParams + + name, sp_kwargs, req_kwargs = case + reset_global_wire_stats() + sp = SamplingParams(max_tokens=8, **sp_kwargs) + req = GenerationRequest([1, 2, 3], sampling_params=sp, **req_kwargs).set_id(71) + assert _send_real_request(req, mode="auto") is None + assert get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(StrictProtoWireError, match=name): + _send_real_request(req, mode="strict") + reset_global_wire_stats() + + +@pytest.mark.parametrize( + "sp_kwargs", + [ + dict(logprobs=1, logprobs_mode="processed"), + dict(additional_model_outputs=["hidden_states", "router_logits"]), + dict(exclude_input_from_output=True, watermarking=None), + ], + ids=["logprobs_mode", "additional_model_outputs", "defaults"], +) +def test_carried_output_fields_round_trip(sp_kwargs: dict[str, object]) -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + sp = SamplingParams(max_tokens=8, **sp_kwargs) + req = GenerationRequest([1, 2, 3], sampling_params=sp).set_id(81) + decoded = _send_real_request(req, mode="strict") + for name, value in sp_kwargs.items(): + assert getattr(decoded.sampling_params, name) == value, name + + +@pytest.mark.parametrize( + "mm_data", + [ + {"image": {"pixel_values": [1, 2], "aspect_ratio": None}}, + {"image": {"extra": {}}}, + {"image": {"a.b": [1, 2]}}, + ], + ids=["none", "empty_mapping", "dotted_key"], +) +def test_multimodal_data_without_a_lossless_form_raises(mm_data: dict[str, object]) -> None: + req = _MockGenerationRequest( + id=91, + prompt_token_ids=[1, 2, 3], + sampling_params=_MockSamplingParams(), + multimodal_params={"multimodal_data": mm_data}, + ) + with pytest.raises(TypeError): + encode_generation_requests([req], strict=False) + + +def test_multimodal_scalar_model_inputs_roundtrip() -> None: + mm_data = { + "image": { + "mm_bidirectional_blocks": True, + "use_hd": False, + "num_frames": 8, + "fps": 2.5, + "layout": "nhwc", + "flags": [True, False], + "tags": ["a", "b"], + } + } + req = _MockGenerationRequest( + id=90, + prompt_token_ids=[1, 2, 3], + sampling_params=_MockSamplingParams(), + multimodal_params={"multimodal_data": mm_data}, + ) + cmsg = encode_generation_requests([req], strict=True) + dec = decode_submit_batch(cmsg)[0] + mi = dec.mm["model_inputs"] + assert mi["image.mm_bidirectional_blocks"] is True + assert mi["image.use_hd"] is False + assert mi["image.num_frames"] == 8 and type(mi["image.num_frames"]) is int + assert mi["image.fps"] == pytest.approx(2.5) and type(mi["image.fps"]) is float + assert mi["image.layout"] == "nhwc" + assert mi["image.flags.__list__.0"] is True + assert mi["image.flags.__list__.1"] is False + assert mi["image.tags.__list__.0"] == "a" + assert mi["image.tags.__list__.1"] == "b" + + +def test_failed_encode_unlinks_the_shm_it_wrote() -> None: + pid_prefix = f"trtllm_se_{os.getpid()}_" + root = wc._shm_root_dir() + + def _segments() -> set[str]: + return {p.name for p in root.iterdir() if p.name.startswith(pid_prefix)} + + before = _segments() + req = _MockGenerationRequest( + id=92, + prompt_token_ids=[1, 2, 3], + sampling_params=_MockSamplingParams(), + multimodal_params={ + "multimodal_data": { + "image": { + "pixel_values": _make_f32_tensor((2, 4), [float(i) for i in range(8)]), + "bad_none": None, + } + } + }, + ) + with pytest.raises(TypeError): + encode_generation_requests( + [req], + strict=False, + delivery_pref=(pb.common_pb2.TENSOR_DELIVERY_SHM,), + max_inline_bytes=0, + ) + assert _segments() == before + + +@pytest.mark.skipif(not HAS_PYZMQ, reason="pyzmq not installed") +def test_shutdown_sentinel_does_not_block_without_a_peer() -> None: + import threading + + from tensorrt_llm.executor.ipc import IpcQueue + from tensorrt_llm.executor.zmq_wire.worker_bridge import send_shutdown_sentinel + + assert _pyzmq is not None + q = IpcQueue( + is_server=True, + socket_type=_pyzmq.PAIR, + name="t_sentinel_no_peer", + serve_engine_wire_enabled=True, + ) + try: + t = threading.Thread(target=send_shutdown_sentinel, args=(q,), daemon=True) + t.start() + t.join(timeout=10.0) + assert not t.is_alive() + finally: + q.close() + + +def test_embedding_bias_sparse_and_dense_validation() -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + ) + from tensorrt_llm.sampling_params import SamplingParams + + # Sparse negative/OOB indices round-trip as sparse tuple (not materialized on bridge), + # letting PyExecutor._validate_embedding_bias reject them with the native error. + sp_sparse = SamplingParams(max_tokens=4, embedding_bias=((42, -0.5), (-1, -2.5), (999999, 1.0))) + req_sparse = GenerationRequest([1, 2, 3], sampling_params=sp_sparse).set_id(201) + rebuilt = _send_real_request(req_sparse, mode="strict") + assert isinstance(rebuilt.sampling_params.embedding_bias, tuple) + assert rebuilt.sampling_params.embedding_bias == ((42, -0.5), (-1, -2.5), (999999, 1.0)) + + # Dense embedding_bias falls back to pickle in auto mode and raises StrictProtoWireError + # in strict mode so C++ length/shape checks are never silently bypassed (C4 Option 1). + reset_global_wire_stats() + sp_dense = SamplingParams(max_tokens=4, embedding_bias=[1.0] * 5) + req_dense = GenerationRequest([1, 2, 3], sampling_params=sp_dense).set_id(202) + assert _send_real_request(req_dense, mode="auto") is None + assert get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(StrictProtoWireError, match="embedding_bias"): + _send_real_request(req_dense, mode="strict") + reset_global_wire_stats() + + # Helper-level _extract_logit_bias still sparsifies valid 1D dense lists and rejects non-1D. + from tensorrt_llm.executor.zmq_wire.codec import _extract_logit_bias + + extracted = _extract_logit_bias(_MockSamplingParams(embedding_bias=[0.0, 1.5, 0.0, -2.25])) + assert [(e.token_id, e.bias) for e in extracted] == [(1, 1.5), (3, -2.25)] + with pytest.raises(ValueError, match="1D"): + _extract_logit_bias(_MockSamplingParams(embedding_bias=[[1.0, 2.0], [3.0, 4.0]])) + + +def test_streaming_generation_logits_and_additional_outputs_roundtrip() -> None: + logits = _make_f32_tensor((1, 2, 4), [float(i) * 0.1 for i in range(8)]) + hidden = _make_f32_tensor((2, 3), [float(i) for i in range(6)]) + rsp = ZmqStepResponse( + client_id=301, + request_id=301, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[11, 12]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + generation_logits=logits, + additional_generation_outputs={"hidden_states": hidden}, + ), + ) + smsg = encode_step_responses([rsp], frame_seq=1) + decoded = decode_step_frame(smsg) + assert len(decoded) == 1 + r = decoded[0].result + assert r.is_final is False + assert r.generation_logits is not None + assert tuple(r.generation_logits.shape) == (1, 2, 4) + assert r.generation_logits.reshape(-1).tolist() == pytest.approx( + [float(i) * 0.1 for i in range(8)] + ) + assert r.additional_generation_outputs is not None + assert tuple(r.additional_generation_outputs["hidden_states"].shape) == (2, 3) + + +def test_native_time_breakdown_and_perf_metrics_roundtrip() -> None: + import datetime + + from tensorrt_llm.llmapi.engine_client.zmq_wire import ( + _build_native_perf_metrics, + _build_native_time_breakdown, + proxy_decode_raw_frame, + ) + + arr_s = 1000.0 + fake_perf = types.SimpleNamespace( + timing_metrics=types.SimpleNamespace( + arrival_time=datetime.timedelta(seconds=arr_s), + first_scheduled_time=datetime.timedelta(seconds=arr_s + 0.01), + first_token_time=datetime.timedelta(seconds=arr_s + 0.05), + last_token_time=datetime.timedelta(seconds=arr_s + 0.25), + ), + kv_cache_metrics=types.SimpleNamespace( + num_total_allocated_blocks=10, + num_new_allocated_blocks=4, + num_reused_blocks=6, + num_missed_blocks=4, + kv_cache_hit_rate=0.0, + ), + first_iter=3, + last_iter=9, + iter=9, + ) + native_tb = { + "step_metrics": [ + { + "iter": 4, + "forward_start_time": arr_s + 0.02, + "forward_end_time": arr_s + 0.03, + "sample_start_time": arr_s + 0.03, + "sample_end_time": arr_s + 0.035, + "token_time": arr_s + 0.04, + "gpu_forward_time": 1.25, + "gpu_sample_time": 0.15, + } + ], + "ctx_chunk_metrics": [ + { + "forward_start_time": arr_s + 0.01, + "forward_end_time": arr_s + 0.018, + "sample_start_time": arr_s + 0.018, + "sample_end_time": arr_s + 0.019, + "token_time": arr_s + 0.02, + "gpu_forward_time": 2.5, + "gpu_sample_time": 0.2, + } + ], + "ctx_gpu_forward_time": 2.5, + "ctx_gpu_sample_time": 0.2, + } + rsp = ZmqStepResponse( + client_id=302, + request_id=302, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[55]], + finish_reasons=[ZmqFinishReason.END_ID], + request_perf_metrics=fake_perf, + time_breakdown_metrics=native_tb, + ), + ) + key = os.urandom(32) + smsg = encode_step_responses([rsp], frame_seq=2) + raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg.SerializeToString(), key) + out = proxy_decode_raw_frame(raw, key) + assert len(out) == 1 + res = out[0]._response.result + tb_out = res.time_breakdown_metrics + assert len(tb_out["step_metrics"]) == 1 + assert tb_out["step_metrics"][0]["iter"] == 4 + assert tb_out["step_metrics"][0]["gpu_forward_time"] == pytest.approx(1.25) + assert tb_out["step_metrics"][0]["forward_end_time"] - tb_out["step_metrics"][0][ + "forward_start_time" + ] == pytest.approx(0.01, abs=1e-4) + assert len(tb_out["ctx_chunk_metrics"]) == 1 + assert tb_out["ctx_gpu_forward_time"] == pytest.approx(2.5) + assert tb_out["ctx_gpu_sample_time"] == pytest.approx(0.2) + rpm = res.request_perf_metrics + assert rpm.iter == 9 + assert rpm.last_iter == 9 + assert rpm.kv_cache_metrics.kv_cache_hit_rate == pytest.approx(0.6) + + # Also verify standalone helper preserves proto->native key conversion. + converted = _build_native_time_breakdown( + {"steps": [{"forward_start_us": 1000, "forward_end_us": 2000}], "ctx_chunks": []}, + base_s=10.0, + ) + assert converted["step_metrics"][0]["forward_start_time"] == pytest.approx(10.001) + assert ( + _build_native_perf_metrics({"last_iter": 7, "kv_blocks": {"reused": 3, "missed": 1}}).iter + == 7 + ) + + +def test_prompt_and_gen_logprobs_out_of_topk_rank_and_native_type() -> None: + from tensorrt_llm.executor.logprobs import Logprob + from tensorrt_llm.executor.result import LogProbsResult, ResponseWrapper + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + # Target token 999 is outside top-2 (ranks 1..2 are 10, 20; target has full-vocab rank 3343). + prompt_entries = [ + {10: Logprob(-0.1, 1), 20: Logprob(-0.4, 2), 999: Logprob(-9.5, 3343)}, + {30: Logprob(-0.2, 1), 40: Logprob(-0.5, 2)}, + ] + gen_entries = [[{50: Logprob(-0.05, 1), 60: Logprob(-0.8, 2), 777: Logprob(-7.2, 1500)}]] + base_rsp = ZmqStepResponse( + client_id=303, + request_id=303, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[777]], + log_probs=gen_entries, + finish_reasons=[ZmqFinishReason.END_ID], + row_flags=wc.ROW_FLAG_FIRST_ROW | wc.ROW_FLAG_SEQ_FINAL | wc.ROW_FLAG_REQUEST_DONE, + ), + ) + wrapped = ResponseWrapper(base_rsp, LogProbsResult(prompt=prompt_entries), None) + # Prompt tokens [1, 999] -> offset-1 targets [999, 777] (matches base_worker.py:1961). + smsg = encode_step_responses( + [wrapped], + frame_seq=3, + prompt_token_ids_by_client={303: [1, 999]}, + ) + dec = decode_step_frame(smsg)[0] + p0 = dec.result.prompt_logprobs["entries"][0] + assert set(p0.keys()) == {10, 20, 999} + assert isinstance(p0[999], Logprob) + assert p0[10].rank == 1 and p0[20].rank == 2 and p0[999].rank == 3343 + assert p0[999].logprob == pytest.approx(-9.5) + # Entries[1] did not contain 777; resolved fallback must NOT fabricate a phantom 777 key. + p1 = dec.result.prompt_logprobs["entries"][1] + assert set(p1.keys()) == {30, 40} + assert p1[30].rank == 1 and p1[40].rank == 2 + g0 = dec.result.log_probs[0][0] + assert set(g0.keys()) == {50, 60, 777} + assert isinstance(g0[777], Logprob) + assert g0[50].rank == 1 and g0[60].rank == 2 and g0[777].rank == 1500 + + # Regression for C1/C2: streaming chunk 2+ cached prompt_logprobs, rank == k+1, and tied top-k ranks. + stream_plp_entries = [ + {10: Logprob(-0.1, 1), 20: Logprob(-0.4, 2), 99: Logprob(-0.9, 3)}, # rank == k+1 + {10: Logprob(-1.0, 1), 20: Logprob(-1.0, 2), 88: Logprob(-1.0, 1)}, # tied out-of-top-k + { + 10: Logprob(-0.5, 1), + 20: Logprob(-0.5, 1), + 100: Logprob(-2.0, 3), + }, # tied top-k, first_gen=100 + ] + chunk2_rsp = ResponseWrapper( + ZmqStepResponse( + client_id=306, + request_id=306, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[10]], # chunk 2 token happens to be in top-2 of entry[-1] + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + ), + ), + LogProbsResult(prompt=stream_plp_entries), + None, + ) + smsg_chunk2 = encode_step_responses( + [chunk2_rsp], + frame_seq=5, + prompt_token_ids_by_client={306: [1, 99, 88]}, + first_gen_token_by_client={306: 100}, + ) + dec_chunk2 = decode_step_frame(smsg_chunk2)[0].result.prompt_logprobs["entries"] + assert set(dec_chunk2[0].keys()) == {10, 20, 99} and dec_chunk2[0][99].rank == 3 + assert set(dec_chunk2[1].keys()) == {10, 20, 88} + assert ( + dec_chunk2[1][10].rank == 1 and dec_chunk2[1][20].rank == 2 and dec_chunk2[1][88].rank == 1 + ) + assert set(dec_chunk2[2].keys()) == {10, 20, 100} and dec_chunk2[2][100].rank == 3 + + # Client-side simple_format collapsing for both logprobs and prompt_logprobs. + simple_rsp = ZmqStepResponse( + client_id=304, + request_id=304, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[777]], + log_probs=[[{777: Logprob(-7.2, 1500)}]], + finish_reasons=[ZmqFinishReason.END_ID], + row_flags=wc.ROW_FLAG_FIRST_ROW | wc.ROW_FLAG_SEQ_FINAL | wc.ROW_FLAG_REQUEST_DONE, + ), + ) + simple_wrapped = ResponseWrapper( + simple_rsp, + LogProbsResult(prompt=[{999: Logprob(-9.5, 3343)}, {777: Logprob(-0.3, 1)}]), + None, + ) + key = os.urandom(32) + smsg_simple = encode_step_responses( + [simple_wrapped], + frame_seq=4, + prompt_token_ids_by_client={304: [1, 999]}, + ) + raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg_simple.SerializeToString(), key) + results_map = { + 304: types.SimpleNamespace( + sampling_params=SamplingParams( + max_tokens=4, + logprobs=0, + logprobs_simple_format=True, + prompt_logprobs=0, + prompt_logprobs_simple_format=True, + ) + ) + } + decoded_simple = proxy_decode_raw_frame(raw, key, results_map=results_map) + assert decoded_simple[0]._response.result.log_probs == [[pytest.approx(-7.2)]] + assert decoded_simple[0].logprobs.prompt == [pytest.approx(-9.5), pytest.approx(-0.3)] + + +def test_apply_batched_logits_processor_roundtrip() -> None: + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + sp = SamplingParams(max_tokens=4, apply_batched_logits_processor=True) + req = GenerationRequest([1, 2, 3], sampling_params=sp).set_id(305) + rebuilt = _send_real_request(req, mode="strict") + assert rebuilt.sampling_params.apply_batched_logits_processor is True + + +def test_r3_selfreview_regressions() -> None: + """Regressions for R3 self-review Important fixes (C3, C7, C10, C11, C12, C14).""" + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_publish_responses + from tensorrt_llm.llmapi.engine_client.zmq_wire import _build_native_time_breakdown + from tensorrt_llm.sampling_params import SamplingParams + + # C3: sparse embedding_bias with bias == 0.0 must be preserved (so invalid indices still validate). + sp_zero = SamplingParams(max_tokens=4, embedding_bias=((-1, 0.0), (42, 0.0))) + rebuilt = _send_real_request( + GenerationRequest([1, 2], sampling_params=sp_zero).set_id(310), mode="strict" + ) + assert rebuilt.sampling_params.embedding_bias == ((-1, 0.0), (42, 0.0)) + + # C4 (ragged list sub-item): _extract_logit_bias must raise ValueError on ragged lists, not TypeError. + from tensorrt_llm.executor.zmq_wire.codec import _extract_logit_bias + + with pytest.raises(ValueError, match="1D"): + _extract_logit_bias(_MockSamplingParams(embedding_bias=[1.0, [2.0]])) + + # C7: pre-built TimeBreakdown proto with perf=None must not raise AttributeError. + tb_proto = pb.output_pb2.TimeBreakdown(ctx_gpu_forward_ms=1.5) + rsp_proto = ZmqStepResponse( + client_id=312, + request_id=312, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[10]], + finish_reasons=[ZmqFinishReason.END_ID], + time_breakdown_metrics=tb_proto, + ), + ) + dec_proto = decode_step_frame(encode_step_responses([rsp_proto], frame_seq=6))[0] + assert dec_proto.result.time_breakdown_metrics["ctx_gpu_forward_ms"] == pytest.approx(1.5) + + # C11: skipped sampler in intermediate ctx_chunk restores sample_*_time as None, not base_s. + tb_chunk = _build_native_time_breakdown( + { + "steps": [], + "ctx_chunks": [ + { + "forward_start_us": 1000, + "forward_end_us": 2000, + "sample_start_us": 0, + "sample_end_us": 0, + "token_us": 2500, + } + ], + }, + base_s=100.0, + ) + assert tb_chunk["ctx_chunk_metrics"][0]["sample_start_time"] is None + assert tb_chunk["ctx_chunk_metrics"][0]["sample_end_time"] is None + + # C14: worker_publish_responses must NOT pop worker._results before checking queue hmac_key in auto mode. + popped: list[int] = [] + no_hmac_q = types.SimpleNamespace(hmac_key=None) + fake_w = types.SimpleNamespace( + frontend_result_queues=None, + result_queue=no_hmac_q, + _refused_client_ids=set(), + _has_background_error=lambda: False, + _pop_result=popped.append, + _results={ + 313: types.SimpleNamespace( + _generation_request=types.SimpleNamespace(prompt_token_ids=[1, 2]) + ) + }, + ) + rsp_no_hmac = ZmqStepResponse( + client_id=313, + request_id=313, + result=ZmqStepResult(is_final=True, is_request_done=True, output_token_ids=[[5]]), + ) + assert worker_publish_responses(fake_w, [rsp_no_hmac], mode="auto") is False + assert popped == [] + + +def test_worker_decode_isolates_per_request_decode_failure() -> None: + """A missing SHM segment or invalid handoff in one request fails only that request.""" + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + key = os.urandom(32) + good_req = GenerationRequest([1, 2, 3], sampling_params=SamplingParams(max_tokens=4)).set_id( + 502 + ) + cmsg = encode_generation_requests([good_req]) + bad_req = pb.request_pb2.Request(handle=501, request_id="bad-shm", prompt_tokens=[1, 2]) + bad_req.mm.mode = pb.request_pb2.MULTIMODAL_MODE_PREPROCESSED + mi = bad_req.mm.model_inputs.add(path="image.pixel_values") + mi.tensor.dtype = pb.common_pb2.DTYPE_F32 + mi.tensor.shape.extend([2]) + mi.tensor.shm.name = "trtllm_se_nonexistent_segment_for_isolation_test" + mi.tensor.shm.offset = 0 + mi.tensor.shm.size = 8 + + # Put the broken request first and the valid request second in the same SubmitBatch. + valid_proto = pb.request_pb2.Request() + valid_proto.CopyFrom(cmsg.submit_batch.requests[0]) + del cmsg.submit_batch.requests[:] + cmsg.submit_batch.requests.extend([bad_req, valid_proto]) + + raw = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg.SerializeToString(), key) + rebuilt = worker_decode_raw_frame(raw, key) + assert len(rebuilt) == 2 + assert isinstance(rebuilt[0], ErrorResponse) + assert rebuilt[0].client_id == 501 + assert isinstance(rebuilt[1], GenerationRequest) + assert rebuilt[1].id == 502 + + +def test_beam_coalescing_uses_request_done_for_is_final() -> None: + """An early-finishing beam must not finalize a live beam-search request before is_request_done.""" + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + key = os.urandom(32) + # Beam 0 hits END_ID (ROW_FLAG_SEQ_FINAL set) while beam 1 is still NOT_FINISHED and + # the overall request is NOT done (is_final=False, is_request_done=False). + live_beam_rsp = ZmqStepResponse( + client_id=601, + request_id=601, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[11, 2], [22, 33]], + finish_reasons=[ZmqFinishReason.END_ID, ZmqFinishReason.NOT_FINISHED], + replace_from=0, + ), + ) + smsg = encode_step_responses([live_beam_rsp], frame_seq=1) + raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg.SerializeToString(), key) + results_map = { + 601: types.SimpleNamespace( + sampling_params=SamplingParams(max_tokens=8, use_beam_search=True, best_of=2) + ) + } + (decoded,) = proxy_decode_raw_frame(raw, key, results_map=results_map) + assert decoded.result.output_token_ids == [[11, 2], [22, 33]] + assert decoded.result.is_request_done is False + assert decoded.result.is_final is False + + # When the whole request completes (is_request_done=True), is_final becomes True. + done_beam_rsp = ZmqStepResponse( + client_id=601, + request_id=601, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[11, 2], [22, 33, 2]], + finish_reasons=[ZmqFinishReason.END_ID, ZmqFinishReason.END_ID], + replace_from=0, + ), + ) + smsg_done = encode_step_responses([done_beam_rsp], frame_seq=2) + raw_done = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg_done.SerializeToString(), key) + (decoded_done,) = proxy_decode_raw_frame(raw_done, key, results_map=results_map) + assert decoded_done.result.is_request_done is True + assert decoded_done.result.is_final is True + + +def test_kv_hints_extra_fields_roundtrip_into_snapshot() -> None: + """KvHints/KvHintAction extra_fields reconstruct flattened into KvHintsSnapshot wire_json.""" + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + orig = { + "protocol_version": "0.1", + "message_id": "msg-extra", + "env_ext": "keep-me", + "actions": [ + { + "action_id": "a1", + "action_type": "kv.fetch", + "action_version": "1", + "payload": {"k": 1}, + "act_ext": True, + } + ], + } + req = GenerationRequest( + [1, 2, 3], sampling_params=SamplingParams(max_tokens=4), kv_hints=orig + ).set_id(602) + assert req.kv_hints is not None + rebuilt = _send_real_request(req, mode="strict") + assert rebuilt.kv_hints is not None + env = rebuilt.kv_hints.envelope() + assert env.protocol_version == "0.1" + assert env.message_id == "msg-extra" + assert env.__pydantic_extra__ == {"env_ext": "keep-me"} + assert env.actions[0].__pydantic_extra__ == {"act_ext": True} + + +def test_kv_hints_malformed_extra_fields_cannot_clobber_or_crash_worker() -> None: + """Extra fields cannot overwrite canonical keys, and non-dict extra_fields isolate per request.""" + import json + + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + key = os.urandom(32) + # 1. Attempting to clobber actions/protocol_version/action_id via extra_fields is ignored; + # canonical typed fields always win and valid non-canonical extra keys survive. + clobber_req = pb.request_pb2.Request(handle=603, request_id="clobber", prompt_tokens=[1, 2]) + clobber_req.stop.max_tokens = 4 + clobber_req.kv.hints.protocol_version = "0.1" + clobber_req.kv.hints.message_id = "msg-safe" + clobber_req.kv.hints.extra_fields = json.dumps( + {"actions": "not-a-list", "protocol_version": "9.9", "safe_ext": 42} + ).encode("utf-8") + act = clobber_req.kv.hints.actions.add( + action_id="a1", action_type="kv.fetch", action_version="1" + ) + act.payload = b'{"k": 1}' + act.extra_fields = json.dumps({"action_id": "hijacked", "act_safe": "ok"}).encode("utf-8") + + # 2. Non-dict extra_fields (JSON array) must fail only that request as ErrorResponse. + bad_req = pb.request_pb2.Request(handle=604, request_id="bad-extra", prompt_tokens=[1, 2]) + bad_req.stop.max_tokens = 4 + bad_req.kv.hints.protocol_version = "0.1" + bad_req.kv.hints.message_id = "msg-bad" + bad_req.kv.hints.extra_fields = b"[1, 2, 3]" + + good_req = GenerationRequest([1, 2, 3], sampling_params=SamplingParams(max_tokens=4)).set_id( + 605 + ) + cmsg = encode_generation_requests([good_req]) + valid_proto = pb.request_pb2.Request() + valid_proto.CopyFrom(cmsg.submit_batch.requests[0]) + del cmsg.submit_batch.requests[:] + cmsg.submit_batch.requests.extend([clobber_req, bad_req, valid_proto]) + + raw = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg.SerializeToString(), key) + rebuilt = worker_decode_raw_frame(raw, key) + assert len(rebuilt) == 3 + + assert isinstance(rebuilt[0], GenerationRequest) and rebuilt[0].id == 603 + env = rebuilt[0].kv_hints.envelope() + assert env.protocol_version == "0.1" + assert env.__pydantic_extra__ == {"safe_ext": 42} + assert env.actions[0].action_id == "a1" + assert env.actions[0].__pydantic_extra__ == {"act_safe": "ok"} + + assert isinstance(rebuilt[1], ErrorResponse) and rebuilt[1].client_id == 604 + assert isinstance(rebuilt[2], GenerationRequest) and rebuilt[2].id == 605 + + +def test_worker_decode_failure_unlinks_remaining_shm_segments() -> None: + """When one SHM tensor fails to decode, all remaining SHM segments in that request are unlinked.""" + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_decode_raw_frame + + key = os.urandom(32) + live_loc = wc.write_shm_bytes(b"\x00" * 16) + live_path = wc._shm_path_for_name(live_loc.name) + assert live_path.exists() + + bad_req = pb.request_pb2.Request(handle=606, request_id="multi-shm", prompt_tokens=[1, 2]) + bad_req.mm.mode = pb.request_pb2.MULTIMODAL_MODE_PREPROCESSED + mi_missing = bad_req.mm.model_inputs.add(path="image.first_missing") + mi_missing.tensor.dtype = pb.common_pb2.DTYPE_F32 + mi_missing.tensor.shape.extend([2]) + mi_missing.tensor.shm.name = "trtllm_se_nonexistent_first_segment_for_cleanup_test" + mi_missing.tensor.shm.offset = 0 + mi_missing.tensor.shm.size = 8 + + mi_live = bad_req.mm.model_inputs.add(path="image.second_live") + mi_live.tensor.dtype = pb.common_pb2.DTYPE_F32 + mi_live.tensor.shape.extend([4]) + mi_live.tensor.shm.CopyFrom(live_loc) + + cmsg = pb.session_pb2.ClientMessage(submit_batch=pb.session_pb2.SubmitBatch(requests=[bad_req])) + raw = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg.SerializeToString(), key) + try: + (out,) = worker_decode_raw_frame(raw, key) + assert isinstance(out, ErrorResponse) and out.client_id == 606 + assert not live_path.exists() + finally: + if live_path.exists(): + live_path.unlink() + + +def test_r1_review_regressions(monkeypatch: pytest.MonkeyPatch) -> None: + """Regressions for strict queue guards, KvCacheTransferMode enum, SHM cleanup, timing, and state reset.""" + import datetime + + from tensorrt_llm.bindings import executor as tllm + from tensorrt_llm.executor.ipc import ZeroMqQueue + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + reset_worker_wire_state, + worker_decode_raw_frame, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import ( + _build_native_perf_metrics, + _timing_dict_to_event_metrics, + proxy_decode_raw_frame, + proxy_send_request, + reset_proxy_wire_state, + ) + from tensorrt_llm.metrics.enums import RequestEventTiming + from tensorrt_llm.sampling_params import SamplingParams + + # 1. ZeroMqQueue must reject use_hmac_encryption=False in __init__, and a bypassed + # unencrypted strict instance must still reject _recv_data() with StrictProtoWireError. + with pytest.raises(RuntimeError): + ZeroMqQueue( + address=None, + is_server=True, + use_hmac_encryption=False, + serve_engine_wire_enabled=True, + serve_engine_wire_strict=True, + ) + bypassed_q = object.__new__(ZeroMqQueue) + bypassed_q.socket = None + bypassed_q.context = None + bypassed_q.socket_type = 0 + bypassed_q.use_hmac_encryption = False + bypassed_q._serve_engine_wire_strict = True + with pytest.raises(StrictProtoWireError): + bypassed_q._recv_data() + + # 2. Real nanobind KvCacheTransferMode enum encodes cleanly in strict mode. + ret_cfg = tllm.KvCacheRetentionConfig( + token_range_retention_configs=[], + decode_retention_priority=50, + transfer_mode=tllm.KvCacheTransferMode.DRAM, + ) + req_kv = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams(max_tokens=4), + kv_cache_retention_config=ret_cfg, + ).set_id(701) + rebuilt_kv = _send_real_request(req_kv, mode="strict") + assert rebuilt_kv.kv_cache_retention_config is not None + assert rebuilt_kv.kv_cache_retention_config.transfer_mode == tllm.KvCacheTransferMode.DRAM + + # 3. explicit strict=True overrides env var in worker_decode_raw_frame. + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "auto") + key = os.urandom(32) + bad_kv_req = pb.request_pb2.Request(handle=702, request_id="bad-kv", prompt_tokens=[1, 2]) + bad_kv_req.stop.max_tokens = 4 + bad_kv_req.kv.hints.protocol_version = "0.1" + bad_kv_req.kv.hints.message_id = "m" + bad_kv_req.kv.hints.extra_fields = b"[1, 2]" + cmsg_kv = pb.session_pb2.ClientMessage( + submit_batch=pb.session_pb2.SubmitBatch(requests=[bad_kv_req]) + ) + raw_kv = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg_kv.SerializeToString(), key) + (out_strict,) = worker_decode_raw_frame(raw_kv, key, strict=True) + assert isinstance(out_strict, ErrorResponse) and out_strict.client_id == 702 + + # 4. logprobs=0 + logprobs_simple_format=True roundtrips to worker SamplingParams. + req_simple = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams(max_tokens=4, logprobs=0, logprobs_simple_format=True), + ).set_id(703) + rebuilt_simple = _send_real_request(req_simple, mode="strict") + assert rebuilt_simple.sampling_params.logprobs == 0 + assert rebuilt_simple.sampling_params.logprobs_simple_format is True + + # 5. Unreached timing milestones stay 0 / timedelta(0) instead of fabricating arrival_time, + # and host_accept_ns-only timing does not fabricate RequestPerfMetrics when disabled. + unreached = { + "host_accept_ns": 100_000_000_000, + "first_scheduled_us": 0, + "first_token_us": 0, + "last_token_us": 0, + } + ev = _timing_dict_to_event_metrics(unreached) + assert ev[RequestEventTiming.ARRIVAL_TIME] == pytest.approx(100.0) + assert ev[RequestEventTiming.FIRST_SCHEDULED_TIME] == 0.0 + assert ev[RequestEventTiming.FIRST_TOKEN_TIME] == 0.0 + assert ev[RequestEventTiming.LAST_TOKEN_TIME] == 0.0 + rpm = _build_native_perf_metrics(unreached) + assert rpm.timing_metrics.arrival_time == datetime.timedelta(seconds=100.0) + assert rpm.timing_metrics.first_scheduled_time == datetime.timedelta(0) + assert rpm.timing_metrics.first_token_time == datetime.timedelta(0) + assert rpm.timing_metrics.last_token_time == datetime.timedelta(0) + + anchor_only_rsp = ZmqStepResponse( + client_id=704, + request_id=704, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[5]], + finish_reasons=[ZmqFinishReason.END_ID], + request_perf_metrics=unreached, + ), + ) + anchor_smsg = encode_step_responses([anchor_only_rsp], frame_seq=1) + anchor_raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, anchor_smsg.SerializeToString(), key) + (decoded_anchor,) = proxy_decode_raw_frame( + anchor_raw, + key, + results_map={ + 704: types.SimpleNamespace( + sampling_params=SamplingParams(max_tokens=4, return_perf_metrics=False) + ) + }, + ) + assert isinstance(decoded_anchor, ZmqStepResponse) + assert decoded_anchor.result.request_perf_metrics is None + + # 6. Response SHM segment is unlinked if encoding fails on a subsequent row in the same frame. + import pathlib + + from google.protobuf.message import Message as ProtoMessage + + from tensorrt_llm.executor.zmq_wire.codec import encode_step_responses_bytes + + created_shm: list[pathlib.Path] = [] + orig_write = wc.write_shm_bytes + + def _recording_write(data: bytes) -> ProtoMessage: + loc = orig_write(data) + created_shm.append(wc._shm_path_for_name(loc.name)) + return loc + + monkeypatch.setattr(wc, "write_shm_bytes", _recording_write) + big_logits = RawTensor( + dtype=pb.common_pb2.DTYPE_F32, + shape=(1, 4096), + data=b"\x00" * (4096 * 4), + ) + row_ok = ZmqStepResponse( + client_id=705, + request_id=705, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[1]], + finish_reasons=[ZmqFinishReason.END_ID], + generation_logits=big_logits, + ), + ) + row_bad = ZmqStepResponse( + client_id=706, + request_id=706, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[1, 2, 3]], + log_probs=[[1.0]], # length mismatch (1 != 3 and not 3-1) -> ValueError + ), + ) + with pytest.raises(ValueError): + encode_step_responses_bytes([row_ok, row_bad], frame_seq=1, max_inline_bytes=0) + assert created_shm and all(not p.exists() for p in created_shm) + + # 7. reset_proxy_wire_state / reset_worker_wire_state clear session seq counters cleanly. + reset_proxy_wire_state(0) + reset_worker_wire_state() + cap_q = _CapQueue(key) + assert proxy_send_request( + cap_q, + GenerationRequest([1, 2], sampling_params=SamplingParams(max_tokens=2)).set_id(707), + mode="strict", + frontend_id=0, + ) + _, _, payload = unpack_raw_frame(cap_q.sent[-1], key) + cmsg_check = pb.session_pb2.ClientMessage() + cmsg_check.ParseFromString(payload) + assert cmsg_check.submit_batch.consumed_frame_seq == 0 + + # 8. worker_publish_responses defers _pop_result until send succeeds. + popped_ids: list[int] = [] + + class _FailingQueue: + hmac_key = key + + def send_raw(self, _data: bytes) -> None: + raise RuntimeError("send failed") + + failing_w = types.SimpleNamespace( + frontend_result_queues=None, + result_queue=_FailingQueue(), + _refused_client_ids=set(), + _has_background_error=lambda: False, + _pop_result=popped_ids.append, + _results={}, + ) + with pytest.raises(RuntimeError, match="send failed"): + worker_publish_responses( + failing_w, + [ + ZmqStepResponse( + client_id=708, + request_id=708, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[5]], + finish_reasons=[ZmqFinishReason.END_ID], + ), + ) + ], + mode="strict", + ) + assert popped_ids == [] + + +def test_r2_review_regressions(monkeypatch: pytest.MonkeyPatch) -> None: + """Regressions for R2 review fixes (#1, #2, #7, #8, #10, #11, #13, #14).""" + import inspect + import queue as _queue + + from tensorrt_llm.executor import base_worker + from tensorrt_llm.executor import worker as worker_mod + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.executor.result import GenerationResult + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + worker_decode_raw_frame, + worker_publish_responses, + ) + from tensorrt_llm.inputs.multimodal import MultimodalInput, MultimodalParams + from tensorrt_llm.llmapi.engine_client.zmq_wire import ( + proxy_decode_raw_frame, + proxy_send_request, + ) + from tensorrt_llm.sampling_params import SamplingParams + + key = os.urandom(32) + + # R2 #1: worker_publish_responses re-checks _has_background_error() per response so a + # single queued background error does not raise queue.Empty on the 2nd response. + err_q: _queue.Queue[Exception] = _queue.Queue() + err_q.put(RuntimeError("bg failure")) + cap_bg = _CapQueue(key) + monkeypatch.setattr(base_worker, "_maybe_wrap_response", lambda _worker, r: r) + + def _create_err(rsp: ZmqStepResponse) -> ErrorResponse: + bck_err = err_q.get_nowait() + return ErrorResponse(rsp.client_id, str(bck_err), rsp.request_id) + + bg_worker = _fake_worker( + result_queue=cap_bg, + _has_background_error=lambda: not err_q.empty(), + _create_error_response=_create_err, + ) + rsp_bg_1 = ZmqStepResponse( + client_id=801, + request_id=801, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[11]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + ), + ) + rsp_bg_2 = ZmqStepResponse( + client_id=802, + request_id=802, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[22]], + finish_reasons=[ZmqFinishReason.END_ID], + ), + ) + assert worker_publish_responses(bg_worker, [rsp_bg_1, rsp_bg_2], mode="strict") is True + assert len(cap_bg.sent) == 1 + decoded_bg = proxy_decode_raw_frame(cap_bg.sent[0], key) + assert decoded_bg is not None and len(decoded_bg) == 2 + assert isinstance(decoded_bg[0], ErrorResponse) and decoded_bg[0].client_id == 801 + assert isinstance(decoded_bg[1], ZmqStepResponse) and decoded_bg[1].client_id == 802 + + # R2 #2: worker_main calls worker.start() before queueing an ErrorResponse from wire decode, + # ensuring the response thread drains it even when it is the very first request. + worker_main_src = inspect.getsource(worker_mod.worker_main) + err_branch_idx = worker_main_src.index("elif isinstance(req, ErrorResponse):") + gen_branch_idx = worker_main_src.index("elif isinstance(req, GenerationRequest):") + err_branch_src = worker_main_src[err_branch_idx:gen_branch_idx] + assert "worker.start()" in err_branch_src + assert err_branch_src.index("worker.start()") < err_branch_src.index("temp_error_responses.put") + + # R2 #7: beam_width_array=[1, 2] with best_of=1 roundtrips use_beam_search=True, while + # use_beam_search=True with best_of=1 and no beam_width_array falls back in auto and fails + # in strict mode. + req_bwa = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams( + max_tokens=4, use_beam_search=True, best_of=1, beam_width_array=[1, 2] + ), + ).set_id(803) + rebuilt_bwa = _send_real_request(req_bwa, mode="strict") + assert isinstance(rebuilt_bwa, GenerationRequest) + assert rebuilt_bwa.sampling_params.use_beam_search is True + assert rebuilt_bwa.sampling_params.beam_width_array == [1, 2] + + reset_global_wire_stats() + req_beam1 = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams(max_tokens=4, use_beam_search=True, best_of=1), + ).set_id(804) + assert _send_real_request(req_beam1, mode="auto") is None + assert get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(StrictProtoWireError, match="use_beam_search"): + _send_real_request(req_beam1, mode="strict") + reset_global_wire_stats() + + # R2 #8: malformed KvHintsSnapshot fails as ErrorResponse even in auto mode (not dropped). + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "auto") + bad_hints_req = pb.request_pb2.Request( + handle=805, request_id="bad-kv-hints-auto", prompt_tokens=[1, 2] + ) + bad_hints_req.stop.max_tokens = 4 + bad_hints_req.kv.hints.protocol_version = "0.1" + bad_hints_req.kv.hints.message_id = "m-auto" + bad_hints_req.kv.hints.extra_fields = b"[1, 2]" + cmsg_hints = pb.session_pb2.ClientMessage( + submit_batch=pb.session_pb2.SubmitBatch(requests=[bad_hints_req]) + ) + raw_hints = pack_raw_frame(ChannelTag.CLIENT_MESSAGE, 0, cmsg_hints.SerializeToString(), key) + (out_auto_hints,) = worker_decode_raw_frame(raw_hints, key, strict=False) + assert isinstance(out_auto_hints, ErrorResponse) and out_auto_hints.client_id == 805 + + # R2 #10: multi-beam frame where beam 0 has cum_log_probs=None/log_probs=None and beam 1 + # has values keeps cum_log_probs and log_probs 1-to-1 aligned with output_token_ids (idx 0 + # == None), and logprobs_simple_format=True preserves None entries without crashing. + beam_frame = encode_step_responses( + [ + ZmqStepResponse( + client_id=806, + request_id=806, + result=ZmqStepResult( + sequence_index=0, + output_token_ids=[[10]], + cum_log_probs=None, + log_probs=None, + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + replace_from=0, + is_final=False, + is_request_done=False, + ), + ), + ZmqStepResponse( + client_id=806, + request_id=806, + result=ZmqStepResult( + sequence_index=1, + output_token_ids=[[20]], + cum_log_probs=[-0.5], + log_probs=[[{20: ZmqLogprob(logprob=-0.5, rank=1)}]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + replace_from=0, + is_final=False, + is_request_done=False, + ), + ), + ], + frame_seq=1, + ) + raw_beam = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, beam_frame.SerializeToString(), key) + beam_results_map = { + 806: types.SimpleNamespace( + sampling_params=types.SimpleNamespace( + use_beam_search=True, + logprobs_simple_format=True, + ) + ) + } + (decoded_beam,) = proxy_decode_raw_frame(raw_beam, key, results_map=beam_results_map) + assert isinstance(decoded_beam, ZmqStepResponse) + assert decoded_beam.result is not None + assert decoded_beam.result.output_token_ids == [[10], [20]] + assert decoded_beam.result.cum_log_probs is not None + assert len(decoded_beam.result.cum_log_probs) == 2 + assert decoded_beam.result.cum_log_probs[0] is None + assert decoded_beam.result.cum_log_probs[1] == pytest.approx(-0.5) + assert decoded_beam.result.log_probs is not None + assert len(decoded_beam.result.log_probs) == 2 + assert decoded_beam.result.log_probs[0] is None + assert decoded_beam.result.log_probs[1] == [pytest.approx(-0.5)] + + # R2 #11: ZmqStepResult carries ctx_computed_tokens / ctx_first_begin / ctx_num_chunks + # through encode/decode when protobuf defines ContextChunkStats, and GenerationResult + # preserves them across intermediate streaming steps. + if hasattr(pb.output_pb2, "ContextChunkStats"): + step1_ctx = ZmqStepResponse( + client_id=807, + request_id=807, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[41]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + row_flags=wc.ROW_FLAG_FIRST_ROW, + ctx_computed_tokens=128, + ctx_first_begin=0, + ctx_num_chunks=2, + ), + ) + step2_mid = ZmqStepResponse( + client_id=807, + request_id=807, + result=ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[42]], + finish_reasons=[ZmqFinishReason.NOT_FINISHED], + ), + ) + step3_final = ZmqStepResponse( + client_id=807, + request_id=807, + result=ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[43]], + finish_reasons=[ZmqFinishReason.END_ID], + ctx_computed_tokens=128, + ctx_first_begin=0, + ctx_num_chunks=2, + ), + ) + dec_step1 = decode_step_frame(encode_step_responses([step1_ctx], frame_seq=1))[0] + assert dec_step1.result is not None + assert dec_step1.result.ctx_computed_tokens == 128 + assert dec_step1.result.ctx_first_begin == 0 + assert dec_step1.result.ctx_num_chunks == 2 + + dec_step2 = decode_step_frame(encode_step_responses([step2_mid], frame_seq=2))[0] + dec_step3 = decode_step_frame(encode_step_responses([step3_final], frame_seq=3))[0] + assert dec_step3.result is not None + assert dec_step3.result.ctx_computed_tokens == 128 + assert dec_step3.result.ctx_first_begin == 0 + assert dec_step3.result.ctx_num_chunks == 2 + + gen_req_ctx = GenerationRequest( + [1, 2, 3], sampling_params=SamplingParams(max_tokens=4), streaming=True + ).set_id(807) + gen_res_ctx = GenerationResult(gen_req_ctx) + gen_res_ctx._handle_response(dec_step1) + assert gen_res_ctx.ctx_computed_tokens == 128 + assert gen_res_ctx.ctx_first_begin == 0 + assert gen_res_ctx.ctx_num_chunks == 2 + gen_res_ctx._handle_response(dec_step2) + assert gen_res_ctx.ctx_computed_tokens == 128 + assert gen_res_ctx.ctx_first_begin == 0 + assert gen_res_ctx.ctx_num_chunks == 2 + gen_res_ctx._handle_response(dec_step3) + assert gen_res_ctx.ctx_computed_tokens == 128 + assert gen_res_ctx.ctx_first_begin == 0 + assert gen_res_ctx.ctx_num_chunks == 2 + + # R2 #13: struct.error during multimodal hash packing falls back to pickle in auto mode + # and raises StrictProtoWireError in strict mode. + reset_global_wire_stats() + bad_mm_input = MultimodalInput.from_components( + [[1 << 40]], # overflows 32-bit signed int in struct.pack('<1i', ...) + [0], + [4], + ) + req_bad_hash = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams(max_tokens=4), + multimodal_params=MultimodalParams(multimodal_input=bad_mm_input), + ).set_id(808) + cap_struct = _CapQueue(key) + assert proxy_send_request(cap_struct, req_bad_hash, mode="auto") is False + assert cap_struct.sent == [] + assert get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(StrictProtoWireError): + proxy_send_request(cap_struct, req_bad_hash, mode="strict") + reset_global_wire_stats() + + # R2 #14: request with scheduling_params=None roundtrips with rebuilt.scheduling_params is None. + req_no_sched = GenerationRequest( + [1, 2, 3], + sampling_params=SamplingParams(max_tokens=4), + scheduling_params=None, + ).set_id(809) + rebuilt_no_sched = _send_real_request(req_no_sched, mode="strict") + assert isinstance(rebuilt_no_sched, GenerationRequest) + assert rebuilt_no_sched.scheduling_params is None diff --git a/tests/unittest/executor/test_zmq_wire_disagg.py b/tests/unittest/executor/test_zmq_wire_disagg.py new file mode 100644 index 000000000000..42576baa3694 --- /dev/null +++ b/tests/unittest/executor/test_zmq_wire_disagg.py @@ -0,0 +1,1203 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""CPU unit tests for disaggregated serving over the trtllm.engine.v1 ZeroMQ wire. + +Covers Request.phase / Request.disagg (context_only, generation_only, context-first and +generation-first schedule styles), the unsigned KvHandoff (integrity scheme NONE), the +FINISH_REASON_CONTEXT_DONE row with RowExtra.handoff, prefill usage, and the executor +integration: auto mode carries disaggregated requests and results instead of pickling them, and +only state with no serve_engine.v1 field falls back. +""" + +from __future__ import annotations + +import dataclasses +import enum +import os +import struct +import types +from typing import Optional + +import pytest + +from tensorrt_llm.contracts.engine.v1 import bindings as pb +from tensorrt_llm.contracts.engine.v1 import wire_codec as wc +from tensorrt_llm.executor.zmq_wire import ( + RawTensor, + ZmqLogprob, + ZmqStepResponse, + ZmqStepResult, + decode_step_frame, + decode_submit_batch, + encode_generation_requests, + encode_step_responses, +) +from tensorrt_llm.executor.zmq_wire.disagg_codec import ( + NATIVE_SCHEDULE_STYLE_TO_PROTO, + DisaggNotSupportedError, + ZmqContextPhaseParams, + schedule_style_from_proto, + schedule_style_to_proto, + unsupported_request_reason, + unsupported_result_reason, +) + +pytestmark = pytest.mark.cpu_only + + +class _ScheduleStyle(enum.IntEnum): + """Mirrors tensorrt_llm.disaggregated_params.DisaggScheduleStyle.""" + + CONTEXT_FIRST = 0 + GENERATION_FIRST = 1 + + +@dataclasses.dataclass +class _MockSamplingParams: + end_id: Optional[int] = 2 + pad_id: Optional[int] = 0 + max_tokens: Optional[int] = 64 + min_tokens: Optional[int] = None + ignore_eos: bool = False + stop_token_ids: Optional[list[int]] = None + _stop_word_ids: Optional[list[list[int]]] = None + bad_token_ids: Optional[list[int]] = None + _bad_word_ids: Optional[list[list[int]]] = None + n: int = 1 + best_of: Optional[int] = None + use_beam_search: bool = False + num_return_beams: Optional[int] = None + beam_width_array: Optional[list[int]] = None + temperature: Optional[float] = None + top_k: Optional[int] = None + top_p: Optional[float] = None + top_p_decay: Optional[float] = None + top_p_min: Optional[float] = None + top_p_reset_ids: Optional[int] = None + min_p: Optional[float] = None + seed: Optional[int] = None + repetition_penalty: Optional[float] = None + presence_penalty: Optional[float] = None + frequency_penalty: Optional[float] = None + prompt_ignore_length: Optional[int] = None + no_repeat_ngram_size: Optional[int] = None + length_penalty: Optional[float] = None + early_stopping: Optional[int] = None + beam_search_diversity_rate: Optional[float] = None + embedding_bias: object = None + logit_bias: object = None + logprobs_mode: str = "raw" + logprobs: Optional[int] = None + logprob_rank: Optional[bool] = None + prompt_logprobs: Optional[int] = None + return_context_logits: bool = False + return_generation_logits: bool = False + return_encoder_output: bool = False + return_routed_experts: bool = False + additional_context_outputs: Optional[list[str]] = None + additional_generation_outputs: Optional[list[str]] = None + additional_model_outputs: Optional[list[str]] = None + return_perf_metrics: bool = False + return_time_breakdown: bool = False + return_decoding_stats: bool = False + return_expanded_prompt: bool = False + guided_decoding: object = None + logits_processor: object = None + logits_processors: Optional[list[object]] = None + apply_batched_logits_processor: bool = False + thinking_budget: object = None + _decoder_output_token_prefix: tuple[int, ...] = () + + +@dataclasses.dataclass +class _MockGenerationRequest: + prompt_token_ids: list[int] + sampling_params: _MockSamplingParams + id: int = 1 + request_id: str = "req-1" + encoder_input_token_ids: Optional[list[int]] = None + streaming: bool = False + priority: float = 0.5 + queue_age_us: Optional[int] = None + lora_request: object = None + scheduling_params: object = None + conversation_params: object = None + cache_salt: Optional[str] = None + kv_cache_retention_config: object = None + kv_hints: object = None + trace_headers: Optional[dict[str, str]] = None + disaggregated_params: object = None + multimodal_params: object = None + thinking_budget: object = None + logits_processors: Optional[list[object]] = None + _prompt_tail_tokens: int = 0 + + +def _request( + prompt_token_ids: list[int], disaggregated_params: object = None, id: int = 1 +) -> _MockGenerationRequest: + return _MockGenerationRequest( + prompt_token_ids=prompt_token_ids, + sampling_params=_MockSamplingParams(max_tokens=16), + id=id, + disaggregated_params=disaggregated_params, + ) + + +def _f32(shape: tuple[int, ...], vals: list[float]) -> RawTensor: + return RawTensor( + dtype=pb.common_pb2.DTYPE_F32, shape=shape, data=struct.pack(f"<{len(vals)}f", *vals) + ) + + +def _i64(shape: tuple[int, ...], vals: list[int]) -> RawTensor: + return RawTensor( + dtype=pb.common_pb2.DTYPE_I64, shape=shape, data=struct.pack(f"<{len(vals)}q", *vals) + ) + + +def _flat(t: object) -> list[int | float | bool]: + return t.reshape(-1).tolist() + + +def _decode_one(req: object) -> object: + return decode_submit_batch(encode_generation_requests([req]), prefer_torch=False)[0] + + +# ============================================================================ +# Enum mapping +# ============================================================================ + + +def test_schedule_style_mapping_is_explicit() -> None: + assert NATIVE_SCHEDULE_STYLE_TO_PROTO == { + 0: pb.common_pb2.SCHEDULE_STYLE_CONTEXT_FIRST, + 1: pb.common_pb2.SCHEDULE_STYLE_GENERATION_FIRST, + } + assert pb.common_pb2.SCHEDULE_STYLE_CONTEXT_FIRST == 1 + assert pb.common_pb2.SCHEDULE_STYLE_GENERATION_FIRST == 2 + for native in _ScheduleStyle: + proto = schedule_style_to_proto(native) + assert proto == int(native) + 1 + assert schedule_style_from_proto(proto) == int(native) + assert schedule_style_to_proto(native.name.lower()) == proto + assert schedule_style_to_proto(None) == pb.common_pb2.SCHEDULE_STYLE_UNSPECIFIED + assert schedule_style_from_proto(pb.common_pb2.SCHEDULE_STYLE_UNSPECIFIED) is None + with pytest.raises(ValueError): + schedule_style_to_proto(2) + with pytest.raises(ValueError): + schedule_style_to_proto("round_robin") + with pytest.raises(ValueError): + schedule_style_from_proto(9) + + +# ============================================================================ +# Requests +# ============================================================================ + + +@pytest.mark.parametrize("style", list(_ScheduleStyle)) +def test_context_only_request_roundtrip(style: _ScheduleStyle) -> None: + req = _request( + [1, 11, 22, 33], + types.SimpleNamespace( + request_type="context_only", disagg_request_id=1 << 42, schedule_style=style + ), + id=301, + ) + pb_req = encode_generation_requests([req]).submit_batch.requests[0] + assert pb_req.phase == pb.common_pb2.PHASE_CONTEXT_ONLY + assert pb_req.disagg.request_id == 1 << 42 + assert pb_req.disagg.schedule_style == int(style) + 1 + assert not pb_req.disagg.HasField("handoff") + assert not pb_req.HasField("queue_age_us") + + dec = _decode_one(req) + assert dec.disagg == { + "request_type": "context_only", + "disagg_request_id": 1 << 42, + "schedule_style": int(style), + "ctx_usage": None, + } + + +def test_aggregated_request_without_params_carries_no_disagg() -> None: + req = _request([1, 2, 3]) + pb_req = encode_generation_requests([req]).submit_batch.requests[0] + assert pb_req.phase == pb.common_pb2.PHASE_AGGREGATED + assert not pb_req.HasField("disagg") + assert _decode_one(req).disagg is None + # context_and_generation with nothing else set is the same as no parameters. + req.disaggregated_params = types.SimpleNamespace(request_type="context_and_generation") + assert not encode_generation_requests([req]).submit_batch.requests[0].HasField("disagg") + + +@pytest.mark.parametrize("ctx_dp_rank", [0, None]) +@pytest.mark.parametrize("style", list(_ScheduleStyle)) +def test_generation_only_request_handoff_roundtrip( + ctx_dp_rank: Optional[int], style: _ScheduleStyle +) -> None: + dp = types.SimpleNamespace( + request_type="generation_only", + disagg_request_id=(1 << 42) + 5, + ctx_request_id=9001, + ctx_dp_rank=ctx_dp_rank, + ctx_info_endpoint="tcp://10.0.0.1:19000", + schedule_style=style, + opaque_state=b"nixl-state-blob", + first_gen_tokens=[44], + first_gen_log_probs=[{44: ZmqLogprob(-0.25, 1), 45: ZmqLogprob(-1.5, 2)}], + first_gen_logits=[_f32((1, 4), [0.1, 0.2, 0.3, 0.4])], + draft_tokens=[45, 46], + remote_tail_start=3, + multimodal_positions=[1], + multimodal_lengths=[2], + ctx_usage={"prompt_tokens": 4, "prompt_tokens_details": {"cached_tokens": 2}}, + orig_elapsed_s=0.015, + ) + req = _request([1, 11, 22, 33], dp, id=302) + pb_req = encode_generation_requests([req]).submit_batch.requests[0] + assert pb_req.phase == pb.common_pb2.PHASE_GENERATION_ONLY + assert pb_req.queue_age_us == 15000 + signed = pb_req.disagg.handoff + # Integrity scheme NONE: the handoff is not signed. + assert signed.mac == b"" and signed.key_id == "" + handoff = pb.disagg_pb2.KvHandoff.FromString(signed.handoff_bytes) + assert handoff.HasField("ctx_dp_rank") == (ctx_dp_rank is not None) + assert handoff.schedule_style == int(style) + 1 + + d = _decode_one(req).disagg + assert d["request_type"] == "generation_only" + assert d["disagg_request_id"] == (1 << 42) + 5 + assert d["ctx_request_id"] == 9001 + assert d["ctx_dp_rank"] == ctx_dp_rank + assert d["ctx_info_endpoint"] == "tcp://10.0.0.1:19000" + assert d["schedule_style"] == int(style) + assert d["opaque_state"] == b"nixl-state-blob" + assert d["first_gen_tokens"] == [44] + assert d["draft_tokens"] == [45, 46] + assert d["remote_tail_start"] == 3 + assert d["multimodal_positions"] == [1] and d["multimodal_lengths"] == [2] + assert d["ctx_usage"]["prompt_tokens"] == 4 + assert d["ctx_usage"]["prompt_tokens_details"]["cached_tokens"] == 2 + assert d["orig_elapsed_s"] == pytest.approx(0.015) + (lp,) = d["first_gen_log_probs"] + assert list(lp) == [44, 45] + assert lp[44].logprob == pytest.approx(-0.25) and lp[44].rank == 1 + assert lp[45].logprob == pytest.approx(-1.5) and lp[45].rank == 2 + assert _flat(d["first_gen_logits"][0]) == pytest.approx([0.1, 0.2, 0.3, 0.4]) + + +def test_generation_first_request_without_context_response() -> None: + dp = types.SimpleNamespace( + request_type="generation_only", + disagg_request_id=77, + ctx_request_id=77, + schedule_style=_ScheduleStyle.GENERATION_FIRST, + ) + d = _decode_one(_request([5, 6], dp, id=303)).disagg + assert d["disagg_request_id"] == 77 and d["ctx_request_id"] == 77 + assert d["schedule_style"] == int(_ScheduleStyle.GENERATION_FIRST) + for name in ("first_gen_tokens", "opaque_state", "ctx_dp_rank", "remote_tail_start"): + assert d[name] is None + + +def test_simple_format_first_gen_logprobs_roundtrip() -> None: + dp = types.SimpleNamespace( + request_type="generation_only", + disagg_request_id=1, + first_gen_tokens=[44], + first_gen_log_probs=[-0.5], + ) + d = _decode_one(_request([5], dp)).disagg + assert d["first_gen_log_probs"] == [pytest.approx(-0.5)] + + +def test_generation_only_rejects_signed_or_missing_handoff() -> None: + handoff = pb.disagg_pb2.KvHandoff(disagg_request_id=1) + signed = wc.sign_handoff(handoff, key=b"K" * 32, key_id="k1") + req = pb.request_pb2.Request( + handle=1, + phase=pb.common_pb2.PHASE_GENERATION_ONLY, + disagg=pb.request_pb2.DisaggParams(handoff=signed), + ) + with pytest.raises(DisaggNotSupportedError): + decode_submit_batch(pb.session_pb2.SubmitBatch(requests=[req])) + bare = pb.request_pb2.Request(handle=2, phase=pb.common_pb2.PHASE_GENERATION_ONLY) + with pytest.raises(ValueError): + decode_submit_batch(pb.session_pb2.SubmitBatch(requests=[bare])) + unknown = pb.request_pb2.Request(handle=3, phase=7) + with pytest.raises(ValueError): + decode_submit_batch(pb.session_pb2.SubmitBatch(requests=[unknown])) + + +# ============================================================================ +# Results +# ============================================================================ + + +def _context_result(**overrides: object) -> ZmqStepResult: + fields: dict[str, object] = dict( + is_final=True, + is_request_done=True, + output_token_ids=[[44]], + log_probs=[[{44: ZmqLogprob(-0.25, 1), 45: ZmqLogprob(-1.5, 2)}]], + finish_reasons=[0], + row_flags=wc.ROW_FLAG_FIRST_ROW, + prompt_len=4, + ctx_usage={"prompt_tokens": 4, "prompt_tokens_details": {"cached_tokens": 2}}, + context_phase_params=ZmqContextPhaseParams( + first_gen_tokens=[44], + req_id=1 << 42, + opaque_state=b"nixl-state-blob", + draft_tokens=[45, 46], + ctx_dp_rank=0, + disagg_info_endpoint="tcp://10.0.0.1:19000", + ), + remote_tail_start=3, + mrope_position_ids=_i64((3, 2), [0, 1, 0, 1, 0, 1]), + mrope_position_deltas=_i64((1, 1), [-2]), + ) + fields.update(overrides) + return ZmqStepResult(**fields) + + +def test_context_done_row_carries_unsigned_handoff() -> None: + rsp = ZmqStepResponse(client_id=301, request_id=9001, result=_context_result()) + smsg = encode_step_responses([rsp], frame_seq=1, iter_first=10, iter_last=10) + (row,) = wc.decode_frame(smsg.frame) + assert row.finish == pb.common_pb2.FINISH_REASON_CONTEXT_DONE + assert list(row.tokens) == [] + assert row.extra is not None + assert row.extra.handoff.mac == b"" and row.extra.handoff.key_id == "" + assert row.extra.final_info.usage.completion_tokens == 0 + assert row.extra.final_info.prefill_usage.prompt_tokens == 4 + assert row.extra.final_info.prefill_usage.cached_tokens == 2 + + (out,) = decode_step_frame(smsg, prefer_torch=False) + r = out.result + assert r.is_final and r.finish_reasons[0].name == "NOT_FINISHED" + # The first generated token comes back as the output token, as on the pickle path. + assert r.output_token_ids == [[44]] + cpp = r.context_phase_params + assert cpp.req_id == 1 << 42 + assert cpp.first_gen_tokens == [44] + assert cpp.draft_tokens == [45, 46] + assert cpp.ctx_dp_rank == 0 + assert cpp.disagg_info_endpoint == "tcp://10.0.0.1:19000" + assert cpp.opaque_state == b"nixl-state-blob" + assert r.remote_tail_start == 3 + assert r.ctx_usage["prompt_tokens"] == 4 + assert r.ctx_usage["prompt_tokens_details"]["cached_tokens"] == 2 + # Without first_gen_log_probs on the result the row's first logprob entry is carried. + (lp,) = r.first_gen_log_probs + assert lp[44].logprob == pytest.approx(-0.25) and lp[44].rank == 1 + assert _flat(r.mrope_position_ids) == [0, 1, 0, 1, 0, 1] + assert _flat(r.mrope_position_deltas) == [-2] + assert isinstance(r.signed_handoff, pb.disagg_pb2.SignedHandoff) + + # A decoded result re-encodes to the same handoff bytes. + again = encode_step_responses( + [ZmqStepResponse(client_id=301, request_id=9001, result=r)], frame_seq=2 + ) + (row2,) = wc.decode_frame(again.frame) + assert row2.extra is not None + assert row2.extra.handoff == row.extra.handoff + + +def test_context_done_ctx_dp_rank_none_and_explicit_logits() -> None: + cpp = ZmqContextPhaseParams(first_gen_tokens=[7], req_id=5, ctx_dp_rank=None) + res = _context_result( + context_phase_params=cpp, + log_probs=None, + first_gen_log_probs=[-0.75], + first_gen_logits=[_f32((1, 2), [1.0, 2.0])], + remote_tail_start=None, + mrope_position_ids=None, + mrope_position_deltas=None, + ctx_usage=None, + ) + smsg = encode_step_responses([ZmqStepResponse(1, 1, result=res)], frame_seq=1) + (row,) = wc.decode_frame(smsg.frame) + assert row.extra is not None + handoff = pb.disagg_pb2.KvHandoff.FromString(row.extra.handoff.handoff_bytes) + assert not handoff.HasField("ctx_dp_rank") + assert not handoff.HasField("remote_tail_start") + assert not handoff.HasField("multimodal") + assert not row.extra.final_info.HasField("prefill_usage") + (out,) = decode_step_frame(smsg, prefer_torch=False) + r = out.result + assert r.context_phase_params.ctx_dp_rank is None + assert r.remote_tail_start is None + assert r.first_gen_log_probs == [pytest.approx(-0.75)] + assert _flat(r.first_gen_logits[0]) == pytest.approx([1.0, 2.0]) + assert r.ctx_usage is None + + +def test_context_phase_finished_by_end_id_keeps_tokens() -> None: + res = _context_result(finish_reasons=[1]) + smsg = encode_step_responses([ZmqStepResponse(1, 1, result=res)], frame_seq=1) + (row,) = wc.decode_frame(smsg.frame) + assert row.finish == pb.common_pb2.FINISH_REASON_END_ID + assert list(row.tokens) == [44] + assert row.extra is not None + assert row.extra.HasField("handoff") + (out,) = decode_step_frame(smsg, prefer_torch=False) + assert out.result.output_token_ids == [[44]] + + +def test_prefill_usage_on_generation_side_rows() -> None: + usage = {"prompt_tokens": 9, "prompt_tokens_details": {"cached_tokens": 4}} + first = ZmqStepResult( + is_final=False, + output_token_ids=[[5]], + row_flags=wc.ROW_FLAG_FIRST_ROW, + prompt_len=9, + ctx_usage=usage, + ) + last = ZmqStepResult( + is_final=True, output_token_ids=[[6]], finish_reasons=[1], prompt_len=9, ctx_usage=usage + ) + smsg = encode_step_responses( + [ZmqStepResponse(1, 1, result=first), ZmqStepResponse(2, 2, result=last)], frame_seq=1 + ) + rows = wc.decode_frame(smsg.frame) + assert rows[0].extra is not None and rows[1].extra is not None + assert rows[0].extra.prompt_info.prefill_usage.cached_tokens == 4 + assert not rows[0].extra.HasField("final_info") + assert rows[1].extra.final_info.prefill_usage.prompt_tokens == 9 + assert not rows[1].extra.HasField("handoff") + outs = decode_step_frame(smsg, prefer_torch=False) + for out in outs: + assert out.result.ctx_usage["prompt_tokens"] == 9 + assert out.result.ctx_usage["prompt_tokens_details"]["cached_tokens"] == 4 + assert out.result.context_phase_params is None + + +# ============================================================================ +# State with no serve_engine.v1 field +# ============================================================================ + + +def test_unsupported_disagg_state_is_reported() -> None: + plain = _request([1, 2]) + assert unsupported_request_reason(plain) is None + ctx = _request([1, 2], types.SimpleNamespace(request_type="context_only")) + assert unsupported_request_reason(ctx) is None + + tail = _request([1, 2, 3]) + tail._prompt_tail_tokens = 2 + handles = _request( + [1, 2], + types.SimpleNamespace(request_type="context_only", mrope_position_ids_handle={"h": 1}), + ) + unknown = _request([1], types.SimpleNamespace(request_type="encode_only")) + for req in (tail, handles, unknown): + assert unsupported_request_reason(req) is not None + with pytest.raises(DisaggNotSupportedError): + encode_generation_requests([req]) + + assert unsupported_result_reason(ZmqStepResult()) is None + assert unsupported_result_reason(ZmqStepResult(mm_embedding_handles=[])) is None + assert unsupported_result_reason(_context_result()) is None + res = ZmqStepResult(output_token_ids=[[5]], mm_embedding_handles=[{"handle": 1}]) + assert unsupported_result_reason(res) is not None + with pytest.raises(DisaggNotSupportedError): + encode_step_responses([ZmqStepResponse(1, 1, result=res)], frame_seq=1) + + +# ============================================================================ +# Executor integration +# ============================================================================ + + +class _CapQueue: + """Records the frames sent on a queue.""" + + def __init__(self, hmac_key: bytes) -> None: + self.hmac_key = hmac_key + self.sent: list[bytes] = [] + + def send_raw(self, raw: bytes) -> None: + self.sent.append(raw) + + +@dataclasses.dataclass +class _EngineResponse: + client_id: int + request_id: int + result: object + error_msg: Optional[str] = None + + def has_error(self) -> bool: + return self.error_msg is not None + + +def _fake_worker(**kwargs: object) -> types.SimpleNamespace: + popped: list[int] = [] + attrs: dict[str, object] = dict( + result_queue=None, + frontend_result_queues=None, + _refused_client_ids=set(), + _results={}, + _has_background_error=lambda: False, + _pop_result=popped.append, + popped=popped, + ) + attrs.update(kwargs) + return types.SimpleNamespace(**attrs) + + +def _native_request(client_id: int, **disagg: object) -> object: + from tensorrt_llm.disaggregated_params import DisaggregatedParams + from tensorrt_llm.executor.request import GenerationRequest + from tensorrt_llm.sampling_params import SamplingParams + + req = GenerationRequest( + [5, 6, 7, 8], + sampling_params=SamplingParams(max_tokens=8), + disaggregated_params=DisaggregatedParams(**disagg), + ) + req.set_id(client_id) + return req + + +def _send_and_decode(req: object, mode: str) -> object: + from tensorrt_llm.executor.zmq_wire.worker_bridge import worker_decode_raw_frame + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_send_request + + key = os.urandom(32) + q = _CapQueue(key) + assert proxy_send_request(q, req, mode=mode) is True + (decoded,) = worker_decode_raw_frame(q.sent[0], key) + return decoded + + +@pytest.mark.parametrize("mode", ["auto", "strict"]) +def test_proxy_carries_disaggregated_requests(mode: str) -> None: + from tensorrt_llm.disaggregated_params import DisaggScheduleStyle + from tensorrt_llm.executor.logprobs import Logprob + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + ) + + reset_global_wire_stats() + ctx = _send_and_decode( + _native_request( + 31, + request_type="context_only", + disagg_request_id=1 << 40, + schedule_style=DisaggScheduleStyle.GENERATION_FIRST, + ), + mode, + ) + dp = ctx.disaggregated_params + assert dp.request_type == "context_only" + assert dp.disagg_request_id == 1 << 40 + assert dp.schedule_style is DisaggScheduleStyle.GENERATION_FIRST + + gen = _send_and_decode( + _native_request( + 32, + request_type="generation_only", + disagg_request_id=1 << 40, + ctx_request_id=777, + ctx_dp_rank=0, + ctx_info_endpoint="tcp://10.0.0.1:19000", + schedule_style=DisaggScheduleStyle.CONTEXT_FIRST, + opaque_state=b"state", + first_gen_tokens=[44], + first_gen_log_probs=[{44: Logprob(-0.25, 1)}], + draft_tokens=[45], + ctx_usage={"prompt_tokens": 4, "prompt_tokens_details": {"cached_tokens": 1}}, + orig_elapsed_s=0.25, + ), + mode, + ) + dp = gen.disaggregated_params + assert dp.request_type == "generation_only" + assert dp.schedule_style is DisaggScheduleStyle.CONTEXT_FIRST + assert (dp.disagg_request_id, dp.ctx_request_id, dp.ctx_dp_rank) == (1 << 40, 777, 0) + assert dp.ctx_info_endpoint == "tcp://10.0.0.1:19000" + assert dp.opaque_state == b"state" + assert dp.first_gen_tokens == [44] and dp.draft_tokens == [45] + assert dp.ctx_usage["prompt_tokens_details"]["cached_tokens"] == 1 + assert dp.orig_elapsed_s == pytest.approx(0.25) + (lp,) = dp.first_gen_log_probs + assert isinstance(lp[44], Logprob) and lp[44].logprob == pytest.approx(-0.25) + cpp = dp.get_context_phase_params() + assert cpp.req_id == 1 << 40 and list(cpp.first_gen_tokens) == [44] + assert get_global_wire_stats()["pickle_fallbacks"] == 0 + reset_global_wire_stats() + + +def test_proxy_falls_back_only_for_state_without_a_field() -> None: + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_send_request + + reset_global_wire_stats() + q = _CapQueue(os.urandom(32)) + req = _native_request( + 33, request_type="generation_only", mrope_position_ids_handle={"handle": 1} + ) + assert proxy_send_request(q, req, mode="auto") is False + assert q.sent == [] and get_global_wire_stats()["pickle_fallbacks"] == 1 + with pytest.raises(DisaggNotSupportedError): + proxy_send_request(q, req, mode="strict") + assert q.sent == [] + reset_global_wire_stats() + + +def test_worker_publishes_context_done_and_frontend_adopts_handoff() -> None: + from tensorrt_llm.disaggregated_params import DisaggregatedParams + from tensorrt_llm.executor.result import GenerationResultBase + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + get_global_wire_stats, + reset_global_wire_stats, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + key = os.urandom(32) + reset_global_wire_stats() + lane = _CapQueue(key) + worker = _fake_worker(result_queue=lane) + ctx_result = _context_result(log_probs=None) + assert worker_publish_responses(worker, [_EngineResponse(41, 41, ctx_result)], mode="auto") + assert len(lane.sent) == 1 and worker.popped == [41] + assert get_global_wire_stats()["pickle_fallbacks"] == 0 + + (rsp,) = proxy_decode_raw_frame(lane.sent[0], key) + gen_result = GenerationResultBase(41, SamplingParams(max_tokens=1)) + gen_result._disaggregated_params = DisaggregatedParams( + request_type="context_only", disagg_request_id=1 << 42 + ) + gen_result._handle_response(rsp) + dp = gen_result.disaggregated_params + assert dp is not None + assert dp.request_type == "context_only" + assert dp.ctx_request_id == 1 << 42 + assert dp.opaque_state == b"nixl-state-blob" + assert dp.ctx_info_endpoint == "tcp://10.0.0.1:19000" + assert dp.ctx_dp_rank == 0 + assert dp.remote_tail_start == 3 + assert dp.ctx_usage is not None + assert dp.ctx_usage["prompt_tokens"] == 4 + assert gen_result._outputs[0].token_ids == [44] + reset_global_wire_stats() + + +def test_worker_falls_back_only_for_results_without_a_field() -> None: + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + reset_global_wire_stats, + worker_publish_responses, + ) + + key = os.urandom(32) + reset_global_wire_stats() + lane = _CapQueue(key) + worker = _fake_worker(result_queue=lane) + batch = [ + _EngineResponse(1, 1, _context_result()), + _EngineResponse( + 2, 2, ZmqStepResult(output_token_ids=[[3]], mm_embedding_handles=[{"h": 1}]) + ), + ] + # auto: the whole batch takes the pickle path before any state changes. + assert worker_publish_responses(worker, batch, mode="auto") is False + assert lane.sent == [] and worker.popped == [] + reset_global_wire_stats() + + +def test_strict_worker_fails_only_the_request_whose_result_has_no_field() -> None: + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + reset_global_wire_stats, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + + key = os.urandom(32) + reset_global_wire_stats() + lane = _CapQueue(key) + aborted: list[int] = [] + worker = _fake_worker(result_queue=lane, abort_request=aborted.append) + batch = [ + _EngineResponse(1, 1, _context_result()), + _EngineResponse( + 2, 2, ZmqStepResult(output_token_ids=[[3]], mm_embedding_handles=[{"h": 1}]) + ), + ] + # strict: the batch is still published, request 2 gets an error and is aborted. + assert worker_publish_responses(worker, batch, mode="strict") is True + assert aborted == [2] and 2 in worker._refused_client_ids and 2 in worker.popped + (frame,) = lane.sent + decoded = proxy_decode_raw_frame(frame, key) + errors = [r for r in decoded if isinstance(r, ErrorResponse)] + assert [e.client_id for e in errors] == [2] + assert "mm_embedding_handles" in str(errors[0].error_msg) + assert any(getattr(r, "client_id", None) == 1 for r in decoded if r not in errors) + reset_global_wire_stats() + + +@pytest.mark.parametrize("mode", ["auto", "strict"]) +def test_worker_skips_the_field_check_for_responses_it_will_not_publish(mode: str) -> None: + from tensorrt_llm.executor.utils import ErrorResponse + from tensorrt_llm.executor.zmq_wire.worker_bridge import ( + reset_global_wire_stats, + worker_publish_responses, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + + key = os.urandom(32) + reset_global_wire_stats() + lane = _CapQueue(key) + aborted: list[int] = [] + worker = _fake_worker( + result_queue=lane, + abort_request=aborted.append, + _refused_client_ids={3}, + _has_background_error=lambda: True, + _create_error_response=lambda rsp: ErrorResponse( + rsp.client_id, "background error", rsp.request_id + ), + ) + mm_result = ZmqStepResult(output_token_ids=[[3]], mm_embedding_handles=[{"h": 1}]) + batch = [_EngineResponse(2, 2, mm_result), _EngineResponse(3, 3, mm_result)] + # Request 3 is dropped and request 2 is replaced by the background error, so neither result + # is published and neither falls back or is refused for its uncarried field. + assert worker_publish_responses(worker, batch, mode=mode) is True + assert aborted == [] + (frame,) = lane.sent + decoded = proxy_decode_raw_frame(frame, key) + assert [(r.client_id, r.error_msg) for r in decoded] == [(2, "background error")] + reset_global_wire_stats() + + +def test_multi_beam_context_done_distributes_first_gen_tokens_per_beam() -> None: + """Multi-beam CONTEXT_DONE distributes first_gen_tokens[i] to beam i instead of [[t0, t1], []].""" + from tensorrt_llm.executor.zmq_wire import ChannelTag, pack_raw_frame + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + cpp = ZmqContextPhaseParams( + first_gen_tokens=[11, 22], + req_id=12345, + opaque_state=b"nixl-beam", + ctx_dp_rank=0, + disagg_info_endpoint="tcp://10.0.0.1:19000", + ) + res = _context_result( + context_phase_params=cpp, + output_token_ids=[[11], [22]], + finish_reasons=[0, 0], + log_probs=None, + first_gen_log_probs=[-0.2, -0.5], + replace_from=0, + ) + smsg = encode_step_responses([ZmqStepResponse(701, 701, result=res)], frame_seq=1) + decoded_rows = decode_step_frame(smsg, prefer_torch=False) + assert len(decoded_rows) == 2 + assert decoded_rows[0].result.output_token_ids == [[11]] + assert decoded_rows[1].result.output_token_ids == [[22]] + + key = os.urandom(32) + raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg.SerializeToString(), key) + results_map = { + 701: types.SimpleNamespace( + sampling_params=SamplingParams(max_tokens=4, use_beam_search=True, best_of=2) + ) + } + (coalesced,) = proxy_decode_raw_frame(raw, key, results_map=results_map) + assert coalesced.result.output_token_ids == [[11], [22]] + assert coalesced.result.context_phase_params.first_gen_tokens == [11, 22] + assert coalesced.result.is_final is True + + +def test_first_token_logprobs_sentinel_and_out_of_topk_ranks() -> None: + """Empty first_gen_tokens must not misidentify token 0 as chosen; out-of-top-k ranks stay intact.""" + from tensorrt_llm.executor.logprobs import Logprob + from tensorrt_llm.executor.zmq_wire.disagg_codec import ( + decode_first_token_logprobs, + encode_first_token_logprobs, + ) + + # Empty first_gen_tokens with token 0 present at rank 10 must pick rank-1 token 42, not token 0. + encoded = encode_first_token_logprobs( + [{0: Logprob(-5.0, rank=10), 42: Logprob(-0.1, rank=1)}], + [], + ) + assert len(encoded) == 1 + assert encoded[0].token_id == 42 and encoded[0].rank == 1 + + # Out-of-top-k sampled token 999 preserves top-k ranks 1..2 and its own rank 15 without shifting. + encoded2 = encode_first_token_logprobs( + [{999: Logprob(-8.5, rank=15), 10: Logprob(-0.2, rank=1), 20: Logprob(-0.5, rank=2)}], + [999], + ) + (decoded2,) = decode_first_token_logprobs(encoded2) + assert set(decoded2.keys()) == {10, 20, 999} + assert decoded2[10].rank == 1 and decoded2[20].rank == 2 and decoded2[999].rank == 15 + assert decoded2[999].logprob == pytest.approx(-8.5) + + # k=0 with explicit rank > 0 decodes to a dict preserving token_id and rank. + encoded_k0 = encode_first_token_logprobs([{77: Logprob(-3.0, rank=12)}], [77]) + (decoded_k0,) = decode_first_token_logprobs(encoded_k0) + assert isinstance(decoded_k0, dict) and decoded_k0[77].rank == 12 + assert decoded_k0[77].logprob == pytest.approx(-3.0) + + +def test_context_done_distributes_when_beam_width_exceeds_num_return_beams_and_ignores_non_ctx_rows() -> ( + None +): + """Distribute first_gen_tokens when beam_width > num_return_beams and ignore non-CONTEXT_DONE rows.""" + from tensorrt_llm.executor.zmq_wire import ChannelTag, pack_raw_frame + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + # Case 1: beam_width=4, num_return_beams=2 -> 2 CONTEXT_DONE rows, 4 first_gen_tokens. + cpp = ZmqContextPhaseParams( + first_gen_tokens=[11, 22, 33, 44], + req_id=54321, + opaque_state=b"nixl-beam4", + ctx_dp_rank=0, + disagg_info_endpoint="tcp://10.0.0.1:19000", + ) + res = _context_result( + context_phase_params=cpp, + output_token_ids=[[11], [22]], + finish_reasons=[0, 0], + log_probs=None, + first_gen_log_probs=[-0.1, -0.2], + replace_from=0, + ) + smsg = encode_step_responses([ZmqStepResponse(702, 702, result=res)], frame_seq=2) + decoded_rows = decode_step_frame(smsg, prefer_torch=False) + assert len(decoded_rows) == 2 + assert decoded_rows[0].result.output_token_ids == [[11]] + assert decoded_rows[1].result.output_token_ids == [[22]] + + key = os.urandom(32) + raw = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg.SerializeToString(), key) + results_map = { + 702: types.SimpleNamespace( + sampling_params=SamplingParams(max_tokens=4, use_beam_search=True, best_of=4, n=2) + ) + } + (coalesced,) = proxy_decode_raw_frame(raw, key, results_map=results_map) + assert coalesced.result.output_token_ids == [[11], [22]] + + # Case 2: beam_width=4, num_return_beams=1 -> 1 CONTEXT_DONE row, 4 first_gen_tokens. + res_single = _context_result( + context_phase_params=cpp, + output_token_ids=[[11]], + finish_reasons=[0], + log_probs=None, + first_gen_log_probs=[-0.1], + replace_from=0, + ) + smsg_single = encode_step_responses([ZmqStepResponse(703, 703, result=res_single)], frame_seq=3) + (dec_single,) = decode_step_frame(smsg_single, prefer_torch=False) + assert dec_single.result.output_token_ids == [[11]] + + # Case 3: A non-CONTEXT_DONE empty-token row sharing the same handle in the same frame must not + # be swept into the CONTEXT_DONE distribution group or have its tokens overwritten. + ctx_rows = list(wc.decode_frame(smsg.frame)) + extra_empty_row = wc.FrameRow( + handle=702, + tokens=[], + finish=pb.common_pb2.FINISH_REASON_NOT_FINISHED, + row_flags=0, + seq=2, + replace_from=wc.NO_REPLACE_FROM, + cum_logprob=None, + extra=None, + ) + mixed_frame = wc.encode_frame( + ctx_rows + [extra_empty_row], frame_seq=4, iter_first=1, iter_last=1 + ) + mixed_smsg = pb.session_pb2.ServerMessage(frame=mixed_frame) + mixed_decoded = decode_step_frame(mixed_smsg, prefer_torch=False) + assert len(mixed_decoded) == 3 + assert mixed_decoded[0].result.output_token_ids == [[11]] + assert mixed_decoded[1].result.output_token_ids == [[22]] + assert mixed_decoded[2].result.output_token_ids == [[]] + + +def test_disagg_generation_only_omitted_first_token_and_cumulative_logprobs() -> None: + """len(lp) == len(tokens) - 1 omits token 0 cleanly; len(lp) > len(tokens) truncates to tokens.""" + from tensorrt_llm.disaggregated_params import DisaggregatedParams + from tensorrt_llm.executor.logprobs import Logprob + from tensorrt_llm.executor.result import GenerationResultBase + from tensorrt_llm.sampling_params import SamplingParams + + # Case 1: generation_only without first_gen_log_probs -> 3 tokens, 2 dict logprobs. + res_omit = ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[10, 20, 30]], + log_probs=[ + [ + {20: Logprob(-0.2, rank=1), 21: Logprob(-1.1, rank=2)}, + {30: Logprob(-0.4, rank=1), 31: Logprob(-2.0, rank=2)}, + ] + ], + finish_reasons=[1], + ) + smsg_omit = encode_step_responses([ZmqStepResponse(801, 801, result=res_omit)], frame_seq=1) + (dec_omit,) = decode_step_frame(smsg_omit, prefer_torch=False) + assert dec_omit.result.output_token_ids == [[10, 20, 30]] + assert dec_omit.result.log_probs is not None + assert len(dec_omit.result.log_probs[0]) == 2 + assert dec_omit.result.log_probs[0][0][20].logprob == pytest.approx(-0.2) + assert dec_omit.result.log_probs[0][1][30].logprob == pytest.approx(-0.4) + + gen_res = GenerationResultBase(801, SamplingParams(max_tokens=4, logprobs=2)) + gen_res._disaggregated_params = DisaggregatedParams(request_type="generation_only") + gen_res._handle_response(dec_omit) + assert gen_res._outputs[0].token_ids == [10, 20, 30] + assert len(gen_res._outputs[0].logprobs) == 2 + + # Case 2: generation_only with 1 token and 0 logprobs -> decodes without error. + res_single_empty = ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[10]], + log_probs=[[]], + finish_reasons=[1], + ) + smsg_se = encode_step_responses( + [ZmqStepResponse(802, 802, result=res_single_empty)], frame_seq=2 + ) + (dec_se,) = decode_step_frame(smsg_se, prefer_torch=False) + assert dec_se.result.output_token_ids == [[10]] + assert dec_se.result.log_probs in (None, [[]]) + + # Case 3: cumulative LogProbStorage with len(lp) > len(tokens) truncates cleanly to len(tokens). + res_over = ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[10, 20]], + log_probs=[[-0.1, -0.2, -0.3, -0.4]], + finish_reasons=[0], + ) + smsg_over = encode_step_responses([ZmqStepResponse(803, 803, result=res_over)], frame_seq=3) + (dec_over,) = decode_step_frame(smsg_over, prefer_torch=False) + assert dec_over.result.log_probs is not None + assert dec_over.result.log_probs[0] == pytest.approx([-0.1, -0.2]) + + # Case 4: len(lp) < len(tokens) - 1 still raises ValueError. + res_short = ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[10, 20, 30]], + log_probs=[[-0.1]], + finish_reasons=[0], + ) + with pytest.raises(ValueError): + encode_step_responses([ZmqStepResponse(804, 804, result=res_short)], frame_seq=4) + + +def test_context_done_populates_log_probs_and_preserves_empty_and_none_rank() -> None: + """CONTEXT_DONE populates res.log_probs (single & multi-beam), preserves {} and rank=None.""" + from tensorrt_llm.disaggregated_params import DisaggregatedParams + from tensorrt_llm.executor.logprobs import Logprob + from tensorrt_llm.executor.result import GenerationResultBase + from tensorrt_llm.executor.zmq_wire import ChannelTag, pack_raw_frame + from tensorrt_llm.executor.zmq_wire.disagg_codec import ( + decode_first_token_logprobs, + encode_first_token_logprobs, + ) + from tensorrt_llm.llmapi.engine_client.zmq_wire import proxy_decode_raw_frame + from tensorrt_llm.sampling_params import SamplingParams + + # Empty dict {} roundtrips as {} (not scalar NaN float). + enc_empty = encode_first_token_logprobs([{}], [44]) + (dec_empty,) = decode_first_token_logprobs(enc_empty) + assert isinstance(dec_empty, dict) and dec_empty == {} + + # 1-entry dict with rank=None roundtrips as dict with rank=None (not scalar float or rank=1). + enc_none_rk = encode_first_token_logprobs([{44: Logprob(-0.7, rank=None)}], [44]) + (dec_none_rk,) = decode_first_token_logprobs(enc_none_rk) + assert isinstance(dec_none_rk, dict) + assert set(dec_none_rk.keys()) == {44} + assert dec_none_rk[44].logprob == pytest.approx(-0.7) + assert dec_none_rk[44].rank is None + + # Multi-entry dict where sampled token has rank=None does not promote rank=None to position. + enc_multi_none = encode_first_token_logprobs( + [{44: Logprob(-0.7, rank=None), 45: Logprob(-1.2, rank=None)}], [44] + ) + (dec_multi_none,) = decode_first_token_logprobs(enc_multi_none) + assert isinstance(dec_multi_none, dict) + assert dec_multi_none[44].rank is None + assert dec_multi_none[44].logprob == pytest.approx(-0.7) + assert dec_multi_none[45].logprob == pytest.approx(-1.2) + + # Single-beam CONTEXT_DONE populates res.log_probs and GenerationResult.outputs[0].logprobs. + ctx_rsp = ZmqStepResponse(client_id=810, request_id=810, result=_context_result()) + smsg_ctx = encode_step_responses([ctx_rsp], frame_seq=1) + (dec_ctx,) = decode_step_frame(smsg_ctx, prefer_torch=False) + assert dec_ctx.result.log_probs is not None + assert len(dec_ctx.result.log_probs) == 1 and len(dec_ctx.result.log_probs[0]) == 1 + assert dec_ctx.result.log_probs[0][0][44].logprob == pytest.approx(-0.25) + + gen_res = GenerationResultBase(810, SamplingParams(max_tokens=1, logprobs=2)) + gen_res._disaggregated_params = DisaggregatedParams( + request_type="context_only", disagg_request_id=1 << 42 + ) + gen_res._handle_response(dec_ctx) + assert gen_res._outputs[0].token_ids == [44] + assert len(gen_res._outputs[0].logprobs) == 1 + assert gen_res._outputs[0].logprobs[0][44].logprob == pytest.approx(-0.25) + + # Multi-beam CONTEXT_DONE distributes first_gen_log_probs across beam rows so coalescing matches. + cpp = ZmqContextPhaseParams( + first_gen_tokens=[11, 22], + req_id=22222, + opaque_state=b"nixl-beam-lp", + ctx_dp_rank=0, + disagg_info_endpoint="tcp://10.0.0.1:19000", + ) + res_mb = _context_result( + context_phase_params=cpp, + output_token_ids=[[11], [22]], + finish_reasons=[0, 0], + log_probs=[ + [{11: ZmqLogprob(-0.2, 1)}], + [{22: ZmqLogprob(-0.6, 1)}], + ], + replace_from=0, + ) + smsg_mb = encode_step_responses([ZmqStepResponse(811, 811, result=res_mb)], frame_seq=2) + dec_mb_rows = decode_step_frame(smsg_mb, prefer_torch=False) + assert len(dec_mb_rows) == 2 + assert dec_mb_rows[0].result.log_probs is not None + assert dec_mb_rows[1].result.log_probs is not None + assert dec_mb_rows[0].result.log_probs[0][0][11].logprob == pytest.approx(-0.2) + assert dec_mb_rows[1].result.log_probs[0][0][22].logprob == pytest.approx(-0.6) + + key = os.urandom(32) + raw_mb = pack_raw_frame(ChannelTag.SERVER_MESSAGE, 0, smsg_mb.SerializeToString(), key) + results_map = { + 811: types.SimpleNamespace( + sampling_params=SamplingParams( + max_tokens=4, use_beam_search=True, best_of=2, logprobs=1 + ) + ) + } + (coalesced_mb,) = proxy_decode_raw_frame(raw_mb, key, results_map=results_map) + assert coalesced_mb.result.output_token_ids == [[11], [22]] + assert coalesced_mb.result.log_probs is not None + assert len(coalesced_mb.result.log_probs) == 2 + assert coalesced_mb.result.log_probs[0][0][11].logprob == pytest.approx(-0.2) + assert coalesced_mb.result.log_probs[1][0][22].logprob == pytest.approx(-0.6) + + +def test_ctx_chunk_stats_and_request_edge_cases() -> None: + """Verify R2 #7 (use_beam_search w/ best_of<=1), R2 #11 (ctx_chunks), R2 #14 (dp_relax).""" + from tensorrt_llm.executor.result import GenerationResultBase + from tensorrt_llm.executor.zmq_wire.codec import uncarried_field_reason + from tensorrt_llm.sampling_params import SamplingParams + + # R2 #7: use_beam_search=True with best_of<=1 and no beam_width_array is uncarried. + req_beam1 = _MockGenerationRequest( + prompt_token_ids=[1, 2], + sampling_params=_MockSamplingParams(use_beam_search=True, n=1, best_of=1), + id=901, + ) + reason = uncarried_field_reason(req_beam1) + assert reason is not None and "use_beam_search" in reason + # With beam_width_array or best_of > 1 it remains carryable. + req_bwa = _MockGenerationRequest( + prompt_token_ids=[1, 2], + sampling_params=_MockSamplingParams( + use_beam_search=True, n=1, best_of=1, beam_width_array=[2, 4] + ), + id=902, + ) + assert uncarried_field_reason(req_bwa) is None + + # R2 #14: unset attention_dp_relax decodes to None (not True). + req_dp = _MockGenerationRequest( + prompt_token_ids=[1, 2], + sampling_params=_MockSamplingParams(max_tokens=4), + scheduling_params=types.SimpleNamespace(attention_dp_rank=1, attention_dp_relax=None), + id=903, + ) + dec_dp = _decode_one(req_dp) + assert dec_dp.sched is not None + assert dec_dp.sched["attention_dp_rank"] == 1 + assert dec_dp.sched["attention_dp_relax"] is None + + # R2 #11: ctx_chunks survives PromptInfo/FinalInfo roundtrip and is not clobbered by decode steps. + step1 = ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[10]], + row_flags=wc.ROW_FLAG_FIRST_ROW, + ctx_computed_tokens=128, + ctx_first_begin=0, + ctx_num_chunks=2, + ) + step2 = ZmqStepResult( + is_final=False, + is_request_done=False, + output_token_ids=[[20]], + ) + step3 = ZmqStepResult( + is_final=True, + is_request_done=True, + output_token_ids=[[30]], + finish_reasons=[1], + ctx_computed_tokens=128, + ctx_first_begin=0, + ctx_num_chunks=2, + ) + smsg1 = encode_step_responses([ZmqStepResponse(904, 904, result=step1)], frame_seq=1) + smsg2 = encode_step_responses([ZmqStepResponse(904, 904, result=step2)], frame_seq=2) + smsg3 = encode_step_responses([ZmqStepResponse(904, 904, result=step3)], frame_seq=3) + (dec1,) = decode_step_frame(smsg1, prefer_torch=False) + (dec2,) = decode_step_frame(smsg2, prefer_torch=False) + (dec3,) = decode_step_frame(smsg3, prefer_torch=False) + assert ( + dec1.result.ctx_computed_tokens, + dec1.result.ctx_first_begin, + dec1.result.ctx_num_chunks, + ) == (128, 0, 2) + assert ( + dec2.result.ctx_computed_tokens, + dec2.result.ctx_first_begin, + dec2.result.ctx_num_chunks, + ) == (0, -1, 0) + assert ( + dec3.result.ctx_computed_tokens, + dec3.result.ctx_first_begin, + dec3.result.ctx_num_chunks, + ) == (128, 0, 2) + + gen_res = GenerationResultBase(904, SamplingParams(max_tokens=4)) + gen_res._handle_response(dec1) + assert (gen_res.ctx_computed_tokens, gen_res.ctx_first_begin, gen_res.ctx_num_chunks) == ( + 128, + 0, + 2, + ) + # Intermediate streaming step with default ctx_* does NOT clobber recorded metadata. + gen_res._handle_response(dec2) + assert (gen_res.ctx_computed_tokens, gen_res.ctx_first_begin, gen_res.ctx_num_chunks) == ( + 128, + 0, + 2, + ) + gen_res._handle_response(dec3) + assert (gen_res.ctx_computed_tokens, gen_res.ctx_first_begin, gen_res.ctx_num_chunks) == ( + 128, + 0, + 2, + ) diff --git a/tests/unittest/llmapi/test_llm_pytorch.py b/tests/unittest/llmapi/test_llm_pytorch.py index 70d2b3434234..88a2e58e9dde 100644 --- a/tests/unittest/llmapi/test_llm_pytorch.py +++ b/tests/unittest/llmapi/test_llm_pytorch.py @@ -428,3 +428,117 @@ def test_min_tokens_with_ignore_eos(): assert all(t == _LAST_VOCAB_TOKEN_ID for t in token_ids), ( f"Expected all tokens to be {_LAST_VOCAB_TOKEN_ID}, got {token_ids}. " f"logits[..., -1] may be incorrectly suppressing the last vocab token.") + + +@force_ampere +def test_serve_engine_zmq_strict_zero_fallback(monkeypatch: pytest.MonkeyPatch, + tmp_path: pathlib.Path) -> None: + """Verify the proxy<->rank0 serve_engine.v1 wire runs end-to-end in strict mode with 0 fallbacks.""" + import json + + from tensorrt_llm.executor.zmq_wire.worker_bridge import \ + reset_global_wire_stats + + stats_path = tmp_path / "zmq_wire_stats.jsonl" + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ", "strict") + monkeypatch.setenv("TLLM_SERVE_ENGINE_ZMQ_STATS_PATH", str(stats_path)) + reset_global_wire_stats() + try: + with LLM( + model=llama_model_path, + kv_cache_config=global_kvcache_config, + ) as llm: + # Non-streaming + prompt/gen logprobs + perf metrics + sparse embedding_bias + out = llm.generate( + "Hello, my name is", + sampling_params=SamplingParams( + max_tokens=8, + temperature=0.0, + logprobs=2, + prompt_logprobs=2, + return_perf_metrics=True, + embedding_bias=((42, -0.5), ), + ), + ) + assert len(out.outputs[0].token_ids) > 0 + assert out.outputs[0].logprobs is not None + assert out.outputs[0].prompt_logprobs is not None + assert out.outputs[0].request_perf_metrics is not None + assert out.outputs[0].request_perf_metrics.iter > 0 + + # Streaming + generation_logits + simple_format logprobs. + # GenerationResult.__next__ mutates and yields `self` in place, so inspect each + # chunk inside the loop rather than calling list(...). + non_final_chunks_with_logits = 0 + total_chunks = 0 + simple_out = None + for chunk in llm.generate_async( + "The capital of France is", + sampling_params=SamplingParams( + max_tokens=4, + temperature=0.0, + logprobs=0, + logprobs_simple_format=True, + prompt_logprobs=0, + prompt_logprobs_simple_format=True, + return_generation_logits=True, + ), + streaming=True, + ): + total_chunks += 1 + assert chunk.outputs[0].generation_logits is not None + if not chunk.finished: + non_final_chunks_with_logits += 1 + simple_out = chunk + assert total_chunks >= 2 and non_final_chunks_with_logits >= 1 + assert simple_out is not None + assert len(simple_out.outputs[0].token_ids) > 0 + assert simple_out.outputs[0].logprobs + assert len(simple_out.outputs[0].logprobs) == len( + simple_out.outputs[0].token_ids) + assert all( + isinstance(x, float) for x in simple_out.outputs[0].logprobs) + assert simple_out.outputs[0].prompt_logprobs + assert len(simple_out.outputs[0].prompt_logprobs) == len( + simple_out.prompt_token_ids) + assert all( + isinstance(x, float) + for x in simple_out.outputs[0].prompt_logprobs) + + # Streaming + dict-format prompt_logprobs across multiple chunks must keep + # aligning the cached final prompt entry with the first generated token. + dict_stream_last = None + first_gen_tok = None + for chunk in llm.generate_async( + "Once upon a time in a distant galaxy", + sampling_params=SamplingParams( + max_tokens=4, + temperature=0.0, + prompt_logprobs=2, + ), + streaming=True, + ): + if first_gen_tok is None and chunk.outputs[0].token_ids: + first_gen_tok = chunk.outputs[0].token_ids[0] + dict_stream_last = chunk + assert dict_stream_last is not None and first_gen_tok is not None + plp_dict = dict_stream_last.outputs[0].prompt_logprobs + assert plp_dict and len(plp_dict) == len( + dict_stream_last.prompt_token_ids) + assert first_gen_tok in plp_dict[-1] + assert len(plp_dict[-1]) <= 3 + + # Proxy dumps stats on shutdown sentinel; assert proto frames flowed with zero pickle fallbacks. + assert stats_path.is_file( + ), "TLLM_SERVE_ENGINE_ZMQ_STATS_PATH was not written" + records = [ + json.loads(line) + for line in stats_path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assert records, "No wire stats records emitted" + assert sum(int(r.get("proto_frames_sent", 0)) for r in records) > 0 + assert sum(int(r.get("proto_frames_recv", 0)) for r in records) > 0 + assert sum(int(r.get("pickle_fallbacks", 0)) for r in records) == 0 + finally: + reset_global_wire_stats() diff --git a/tests/unittest/scripts/test_serve_schema_packaging.py b/tests/unittest/scripts/test_serve_schema_packaging.py index 64da93a792f0..2f6efe0dcbcb 100644 --- a/tests/unittest/scripts/test_serve_schema_packaging.py +++ b/tests/unittest/scripts/test_serve_schema_packaging.py @@ -51,6 +51,15 @@ def test_wheel_contains_serving_schemas(tmp_path: Path, missing_schema: bool) -> "tensorrt_llm/__init__.py", "tensorrt_llm/bindings/__init__.py", "tensorrt_llm/grpc/openengine/_generated/openengine_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/__init__.py", + "tensorrt_llm/contracts/engine/v1/_generated/capabilities_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/common_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/control_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/disagg_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/output_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/request_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/session_pb2.py", + "tensorrt_llm/contracts/engine/v1/_generated/stats_pb2.py", "3rdparty/fmha_sm100/__init__.py", "ATTRIBUTIONS.md", ):