Skip to main content

weirdnet_backends/
host.rs

1//! The model node's inference side: a `weirdnet-agent` [`InferHost`] over the [`Supervisor`],
2//! serving raw infer/2 (assembled messages in, tokens out; cancel aborts the engine request).
3
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::Instant;
7
8use async_trait::async_trait;
9use futures::StreamExt;
10use weirdnet_agent::remote::infer::InferHost;
11use weirdnet_agent::remote::infer::v2::{self, EmbedBackend, Finish, InferBackend, Input, Output, Request};
12use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError};
13use weirdnet_agent::{CancelToken, Modalities, ModelBackend};
14
15use crate::error::{bad_request, engine_error, unavailable};
16use crate::sse::{Chunk, ToolCalls};
17use crate::supervisor::{ModelState, Supervisor};
18
19/// Measured speed, for the capability record.
20#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
21pub struct Speed {
22    /// Exponentially weighted decode tokens per second.
23    pub decode_tps: Option<f32>,
24    /// Exponentially weighted prefill tokens per second (prompt tokens over time to first token).
25    pub prefill_tps: Option<f32>,
26    /// The last time to first token.
27    pub ttft_ms: Option<u64>,
28}
29
30impl Speed {
31    fn ewma(old: Option<f32>, new: f32) -> Option<f32> {
32        Some(match old {
33            Some(o) => o * 0.8 + new * 0.2,
34            None => new,
35        })
36    }
37
38    fn record(&mut self, ttft: Option<f64>, total: f64, prompt: u64, completion: u64) {
39        if let Some(t) = ttft {
40            self.ttft_ms = Some((t * 1000.0) as u64);
41            if t > 0.0 && prompt > 0 {
42                self.prefill_tps = Self::ewma(self.prefill_tps, prompt as f32 / t as f32);
43            }
44            let decode = total - t;
45            if decode > 0.0 && completion > 1 {
46                self.decode_tps = Self::ewma(self.decode_tps, (completion - 1) as f32 / decode as f32);
47            }
48        }
49    }
50}
51
52/// Serves the supervisor's models over infer/2. Requests name a model by its launch id (or get
53/// the default). A request with image or audio parts is refused (`Unsupported`, so a pool tries
54/// elsewhere) unless the model takes them ([`ModelLaunch::capabilities`](crate::ModelLaunch::capabilities));
55/// remote image URLs are a `BadRequest`. A model that is not ready is refused as unavailable unless the request has
56/// `wait_for_model` or the host loads on demand. While draining, new requests are refused.
57pub struct ModelHost {
58    supervisor: Supervisor,
59    auth: Arc<dyn Authorize>,
60    default_model: Option<String>,
61    load_on_demand: bool,
62    draining: AtomicBool,
63    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
64}
65
66impl ModelHost {
67    pub fn new(supervisor: Supervisor, auth: Arc<dyn Authorize>) -> Self {
68        Self { supervisor, auth, default_model: None, load_on_demand: false, draining: AtomicBool::new(false), speed: Default::default() }
69    }
70
71    /// The model for requests that name none.
72    pub fn with_default(mut self, model: impl Into<String>) -> Self {
73        self.default_model = Some(model.into());
74        self
75    }
76
77    /// Load a model that is not ready instead of refusing (a single box with no coordinator).
78    pub fn with_load_on_demand(mut self, on: bool) -> Self {
79        self.load_on_demand = on;
80        self
81    }
82
83    pub fn supervisor(&self) -> &Supervisor {
84        &self.supervisor
85    }
86
87    /// Stop (or resume) taking new requests; requests under way finish.
88    pub fn set_draining(&self, on: bool) {
89        self.draining.store(on, Ordering::SeqCst);
90    }
91
92    pub fn draining(&self) -> bool {
93        self.draining.load(Ordering::SeqCst)
94    }
95
96    /// Measured speed per model.
97    pub fn speed(&self, model: &str) -> Speed {
98        self.speed.lock().unwrap_or_else(|e| e.into_inner()).get(model).copied().unwrap_or_default()
99    }
100
101    fn pick(&self, model: Option<&str>, wait: bool, needed: Modalities) -> Result<(String, bool), RemoteError> {
102        if self.draining() {
103            return Err(unavailable("this node is draining"));
104        }
105        let id = model.map(str::to_string).or_else(|| self.default_model.clone()).ok_or_else(|| bad_request("no model named and no default"))?;
106        if let Some(what) = self.supervisor.capabilities(&id).and_then(|c| c.lacking(needed)) {
107            return Err(RemoteError::Unsupported { message: format!("model `{id}` does not take {what} on this node") });
108        }
109        match self.supervisor.state(&id) {
110            None => Err(crate::error::unknown_model(&id)),
111            Some(ModelState::Ready) => Ok((id, false)),
112            Some(_) if wait || self.load_on_demand => Ok((id, true)),
113            Some(state) => Err(unavailable(format!("{id} is not loaded ({state:?})"))),
114        }
115    }
116
117    fn backend(&self, id: String, load: bool) -> EngineModel {
118        EngineModel { supervisor: self.supervisor.clone(), id, load, speed: self.speed.clone() }
119    }
120}
121
122impl InferHost for ModelHost {
123    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
124        self.auth.authorize(caller)
125    }
126
127    /// Model nodes serve infer/2 only.
128    fn open(&self, _caller: &Caller, _model: Option<&str>) -> Result<Arc<dyn ModelBackend>, RemoteError> {
129        Err(RemoteError::Unsupported { message: "model nodes serve /weirdnet-agent/infer/2".into() })
130    }
131
132    fn open_request(&self, _caller: &Caller, request: &Request) -> Result<Arc<dyn InferBackend>, RemoteError> {
133        let needed = request.needs();
134        if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
135            return Err(bad_request(message));
136        }
137        let (id, load) = self.pick(request.model.as_deref(), request.wait_for_model, needed)?;
138        Ok(Arc::new(self.backend(id, load)))
139    }
140
141    fn open_embed(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn EmbedBackend>, RemoteError> {
142        let (id, load) = self.pick(model, false, Modalities::TEXT)?;
143        Ok(Arc::new(self.backend(id, load)))
144    }
145}
146
147/// One supervised model as an infer/2 backend.
148pub struct EngineModel {
149    supervisor: Supervisor,
150    id: String,
151    load: bool,
152    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
153}
154
155impl EngineModel {
156    async fn ready(&self) -> Result<(), RemoteError> {
157        if self.load { self.supervisor.load(&self.id).await } else { Ok(()) }
158    }
159}
160
161#[async_trait]
162impl InferBackend for EngineModel {
163    fn name(&self) -> String {
164        self.id.clone()
165    }
166
167    /// Both engines continue an assistant prefix (chat) or the prompt plus the prefix (a raw
168    /// prompt, through `/v1/completions`).
169    fn resumes(&self) -> bool {
170        true
171    }
172
173    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
174        self.ready().await?;
175        let started = Instant::now();
176        let mut stream = match &request.input {
177            Input::Prompt(prompt) => {
178                let mut prompt = prompt.clone();
179                if let Some(p) = &request.assistant_prefix {
180                    prompt.push_str(&p.text);
181                }
182                self.supervisor.complete(&self.id, &prompt, &request.sampling, request.seed).await?
183            }
184            _ => self.supervisor.chat(&self.id, request).await?,
185        };
186        let mut calls = ToolCalls::default();
187        let mut first: Option<f64> = None;
188        loop {
189            let next = tokio::select! {
190                _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
191                n = stream.next() => n,
192            };
193            let chunk = match next {
194                Some(c) => c?,
195                None => return Err(engine_error("engine stream ended early")),
196            };
197            if first.is_none() && matches!(chunk, Chunk::Text(_) | Chunk::Reasoning(_) | Chunk::ToolCall { .. }) {
198                first = Some(started.elapsed().as_secs_f64());
199            }
200            match chunk {
201                Chunk::Text(t) => out.text(t),
202                Chunk::Reasoning(t) => out.reasoning(t),
203                Chunk::ToolCall { index, id, name, arguments } => calls.push(index, id, name, &arguments),
204                Chunk::Done { finish_reason, usage } => {
205                    let had_calls = !calls.is_empty();
206                    for call in calls.finish() {
207                        out.tool_call(call);
208                    }
209                    let reason = finish_reason.unwrap_or_else(|| if had_calls { "tool_calls".into() } else { "stop".into() });
210                    let mut finish = Finish::new(reason);
211                    if let Some(u) = usage {
212                        out.usage(u);
213                        finish = finish.with_usage(u);
214                        let total = started.elapsed().as_secs_f64();
215                        self.speed.lock().unwrap_or_else(|e| e.into_inner()).entry(self.id.clone()).or_default().record(
216                            first,
217                            total,
218                            u.prompt_tokens,
219                            u.completion_tokens,
220                        );
221                    }
222                    return Ok(finish);
223                }
224            }
225        }
226    }
227}
228
229#[async_trait]
230impl EmbedBackend for EngineModel {
231    fn name(&self) -> String {
232        self.id.clone()
233    }
234
235    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError> {
236        Ok(self.embed_counted(input, cancel).await?.0)
237    }
238
239    /// The vector and the engine's `usage.prompt_tokens`.
240    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
241        self.ready().await?;
242        let inputs = [input.to_string()];
243        let call = self.supervisor.embed(&self.id, &inputs);
244        let (mut vectors, tokens) = tokio::select! {
245            _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
246            r = call => r?,
247        };
248        Ok((vectors.pop().ok_or_else(|| engine_error("no embedding"))?, Some(tokens)))
249    }
250}
251
252/// The protocol id model nodes serve raw infer on: the `/weirdnet-agent/infer/2` framing under
253/// its own id, so one node can be an inference node (which serves infer/2 to apps) and a model
254/// node at once. `NodeServer` (`node` feature) always serves it; [`RawInferDialer`] prefers it.
255pub const RAW_INFER_PROTOCOL: &str = "/weirdnet-backends/infer/1";
256
257/// A [`Dialer`] for inference nodes talking to model nodes: opening
258/// `/weirdnet-agent/infer/2` tries [`RAW_INFER_PROTOCOL`] first and falls back to infer/2 on
259/// nodes that don't accept it (backends 0.1.0). Nodes that fell back are remembered. Other
260/// protocols pass through. Wrap the dialer given to the `Pool` of model nodes.
261pub struct RawInferDialer {
262    inner: Arc<dyn Dialer>,
263    legacy: Mutex<std::collections::HashSet<String>>,
264}
265
266impl RawInferDialer {
267    pub fn new(inner: Arc<dyn Dialer>) -> Self {
268        Self { inner, legacy: Mutex::new(Default::default()) }
269    }
270
271    /// Whether `node` answered only on infer/2.
272    pub fn is_legacy(&self, node: &str) -> bool {
273        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).contains(node)
274    }
275}
276
277#[async_trait]
278impl Dialer for RawInferDialer {
279    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
280        if protocol != v2::PROTOCOL {
281            return self.inner.open(node, protocol).await;
282        }
283        if !self.is_legacy(node) {
284            match self.inner.open(node, RAW_INFER_PROTOCOL).await {
285                Err(RemoteError::Unsupported { .. }) => {}
286                other => return other,
287            }
288        }
289        let ch = self.inner.open(node, v2::PROTOCOL).await?;
290        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).insert(node.to_string());
291        Ok(ch)
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn speed_is_smoothed() {
301        let mut s = Speed::default();
302        s.record(Some(0.5), 1.5, 100, 11);
303        assert_eq!((s.ttft_ms, s.prefill_tps, s.decode_tps), (Some(500), Some(200.0), Some(10.0)));
304        s.record(Some(0.5), 0.5, 100, 11);
305        assert_eq!(s.decode_tps, Some(10.0), "no decode time: unchanged");
306    }
307}