Skip to main content

ts_wire/
multimodal.rs

1// Copyright (c) 2026 LightSeek Foundation
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Multimodal payloads (`multimodal/inputs.py`, `multimodal/shm_transport.py`),
22//! and the EPD encode request that carries an item to an encode node
23//! (`epd/encode_worker.py`).
24
25use crate::{
26    codec::{Dict, StrOrList, Wire},
27    error::{Error, Result},
28    msgpack::{Decoder, Encoder},
29    tensor::Tensor,
30    value::Value,
31};
32
33/// The media kind of an item. Encoded as the Python enum's value.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Modality {
36    /// Images.
37    Image = 1,
38    /// Video.
39    Video = 2,
40    /// Audio.
41    Audio = 3,
42}
43
44impl Wire for Modality {
45    fn encode(&self, encoder: &mut Encoder) {
46        encoder.uint(*self as u64);
47    }
48
49    fn decode(decoder: &mut Decoder<'_>) -> Result<Self> {
50        match decoder.integer()?.narrow::<i64>("Modality")? {
51            1 => Ok(Modality::Image),
52            2 => Ok(Modality::Video),
53            3 => Ok(Modality::Audio),
54            other => Err(Error::Invalid(format!("unknown modality {other}"))),
55        }
56    }
57}
58
59wire_struct! {
60    /// A CPU tensor published in a POSIX shared-memory segment on the same
61    /// host. A map-layout struct.
62    #[derive(Debug, Clone, PartialEq, Eq)]
63    pub struct ShmTensorHandle: map {
64        /// Segment name.
65        pub shm_name: String,
66        /// Tensor dimensions.
67        pub shape: Vec<i64>,
68        /// torch dtype name.
69        pub dtype: String,
70    }
71}
72
73wire_struct! {
74    /// One image, video or audio item of a request.
75    #[derive(Debug, Clone, PartialEq)]
76    pub struct MultimodalDataItem: array {
77        /// Media kind.
78        pub modality: Modality,
79        /// Content id used for prefix matching; up to 64 bits.
80        pub hash: Option<u64> = None,
81        /// The placeholder token id substituted into the prompt.
82        pub pad_value: Option<i64> = None,
83        /// `(start, end)` token ranges of the item in the prompt.
84        pub offsets: Option<Vec<(i64, i64)>> = None,
85        /// Inline feature tensor. Exactly one of `feature` and `feature_shm`
86        /// is set in flight.
87        pub feature: Option<Tensor> = None,
88        /// Feature tensor in shared memory.
89        pub feature_shm: Option<ShmTensorHandle> = None,
90        /// Model-specific tensors, such as image grid sizes.
91        pub model_specific_data: Dict<String, Tensor> = Dict::default(),
92        /// Engine-local encoder output; always `None` on the wire.
93        pub encoded: Option<Tensor> = None,
94        /// Engine-local deepstack encoder output; always `None` on the wire.
95        pub encoded_deepstack: Option<Tensor> = None,
96        /// EPD: the encode worker's rendezvous for this item's embedding.
97        pub encode_handshake: Option<Dict<Value, Value>> = None,
98    }
99}
100
101wire_struct! {
102    /// The multimodal part of a request.
103    #[derive(Debug, Clone, PartialEq)]
104    pub struct MultimodalInputs: array {
105        /// The media items, in prompt order.
106        pub mm_items: Vec<MultimodalDataItem>,
107        /// Image placeholder token id.
108        pub im_token_id: Option<i64> = None,
109        /// Video placeholder token id.
110        pub video_token_id: Option<i64> = None,
111        /// M-RoPE position ids.
112        pub mrope_positions: Option<Tensor> = None,
113        /// M-RoPE position delta.
114        pub mrope_position_delta: Option<Tensor> = None,
115        /// M-RoPE position delta as a scalar.
116        pub mrope_position_delta_scalar: Option<i64> = None,
117        /// Retired slot kept for arity; always `None`.
118        pub mrope_position_delta_repeated_cache: Option<Tensor> = None,
119    }
120}
121
122wire_struct! {
123    /// EPD: one item for an encode node to embed and ship to the prefill
124    /// ranks that wait for it under `bootstrap_room`. The first two fields
125    /// come from the Python `BaseReq` base class.
126    #[derive(Debug, Clone, PartialEq)]
127    pub struct EncodeRequest: array("EncodeRequest") {
128        /// Request id; unused, `request_id` names the request.
129        pub rid: Option<StrOrList> = None,
130        /// In-process HTTP worker address; unused across processes.
131        pub http_worker_ipc: Option<String> = None,
132        /// The gateway's id of the request.
133        pub request_id: String,
134        /// The encode node's bootstrap server, as the gateway gave it.
135        pub bootstrap_host: String,
136        /// Its port.
137        pub bootstrap_port: i64,
138        /// The room the prefill ranks receive the embedding under.
139        pub bootstrap_room: u64,
140        /// The items to embed; the gateway sends one per request.
141        pub items: Vec<MultimodalDataItem>,
142    }
143}