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::{EmbedBackend, Finish, InferBackend, Output, Request};
12use weirdnet_agent::remote::{Authorize, Caller, RemoteError};
13use weirdnet_agent::{CancelToken, 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 model that is not ready is refused as unavailable unless the request has
54/// `wait_for_model` or the host loads on demand. While draining, new requests are refused.
55pub struct ModelHost {
56    supervisor: Supervisor,
57    auth: Arc<dyn Authorize>,
58    default_model: Option<String>,
59    load_on_demand: bool,
60    draining: AtomicBool,
61    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
62}
63
64impl ModelHost {
65    pub fn new(supervisor: Supervisor, auth: Arc<dyn Authorize>) -> Self {
66        Self { supervisor, auth, default_model: None, load_on_demand: false, draining: AtomicBool::new(false), speed: Default::default() }
67    }
68
69    /// The model for requests that name none.
70    pub fn with_default(mut self, model: impl Into<String>) -> Self {
71        self.default_model = Some(model.into());
72        self
73    }
74
75    /// Load a model that is not ready instead of refusing (a single box with no coordinator).
76    pub fn with_load_on_demand(mut self, on: bool) -> Self {
77        self.load_on_demand = on;
78        self
79    }
80
81    pub fn supervisor(&self) -> &Supervisor {
82        &self.supervisor
83    }
84
85    /// Stop (or resume) taking new requests; requests under way finish.
86    pub fn set_draining(&self, on: bool) {
87        self.draining.store(on, Ordering::SeqCst);
88    }
89
90    pub fn draining(&self) -> bool {
91        self.draining.load(Ordering::SeqCst)
92    }
93
94    /// Measured speed per model.
95    pub fn speed(&self, model: &str) -> Speed {
96        self.speed.lock().unwrap_or_else(|e| e.into_inner()).get(model).copied().unwrap_or_default()
97    }
98
99    fn pick(&self, model: Option<&str>, wait: bool) -> Result<(String, bool), RemoteError> {
100        if self.draining() {
101            return Err(unavailable("this node is draining"));
102        }
103        let id = model.map(str::to_string).or_else(|| self.default_model.clone()).ok_or_else(|| bad_request("no model named and no default"))?;
104        match self.supervisor.state(&id) {
105            None => Err(crate::error::unknown_model(&id)),
106            Some(ModelState::Ready) => Ok((id, false)),
107            Some(_) if wait || self.load_on_demand => Ok((id, true)),
108            Some(state) => Err(unavailable(format!("{id} is not loaded ({state:?})"))),
109        }
110    }
111
112    fn backend(&self, id: String, load: bool) -> EngineModel {
113        EngineModel { supervisor: self.supervisor.clone(), id, load, speed: self.speed.clone() }
114    }
115}
116
117impl InferHost for ModelHost {
118    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
119        self.auth.authorize(caller)
120    }
121
122    /// Model nodes serve infer/2 only.
123    fn open(&self, _caller: &Caller, _model: Option<&str>) -> Result<Arc<dyn ModelBackend>, RemoteError> {
124        Err(RemoteError::Unsupported { message: "model nodes serve /weirdnet-agent/infer/2".into() })
125    }
126
127    fn open_request(&self, _caller: &Caller, request: &Request) -> Result<Arc<dyn InferBackend>, RemoteError> {
128        let (id, load) = self.pick(request.model.as_deref(), request.wait_for_model)?;
129        Ok(Arc::new(self.backend(id, load)))
130    }
131
132    fn open_embed(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn EmbedBackend>, RemoteError> {
133        let (id, load) = self.pick(model, false)?;
134        Ok(Arc::new(self.backend(id, load)))
135    }
136}
137
138/// One supervised model as an infer/2 backend.
139pub struct EngineModel {
140    supervisor: Supervisor,
141    id: String,
142    load: bool,
143    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
144}
145
146impl EngineModel {
147    async fn ready(&self) -> Result<(), RemoteError> {
148        if self.load { self.supervisor.load(&self.id).await } else { Ok(()) }
149    }
150}
151
152#[async_trait]
153impl InferBackend for EngineModel {
154    fn name(&self) -> String {
155        self.id.clone()
156    }
157
158    /// Both engines continue an assistant prefix.
159    fn resumes(&self) -> bool {
160        true
161    }
162
163    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
164        self.ready().await?;
165        let started = Instant::now();
166        let mut stream = self.supervisor.chat(&self.id, request).await?;
167        let mut calls = ToolCalls::default();
168        let mut first: Option<f64> = None;
169        loop {
170            let next = tokio::select! {
171                _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
172                n = stream.next() => n,
173            };
174            let chunk = match next {
175                Some(c) => c?,
176                None => return Err(engine_error("engine stream ended early")),
177            };
178            if first.is_none() && matches!(chunk, Chunk::Text(_) | Chunk::Reasoning(_) | Chunk::ToolCall { .. }) {
179                first = Some(started.elapsed().as_secs_f64());
180            }
181            match chunk {
182                Chunk::Text(t) => out.text(t),
183                Chunk::Reasoning(t) => out.reasoning(t),
184                Chunk::ToolCall { index, id, name, arguments } => calls.push(index, id, name, &arguments),
185                Chunk::Done { finish_reason, usage } => {
186                    let had_calls = !calls.is_empty();
187                    for call in calls.finish() {
188                        out.tool_call(call);
189                    }
190                    let reason = finish_reason.unwrap_or_else(|| if had_calls { "tool_calls".into() } else { "stop".into() });
191                    let mut finish = Finish::new(reason);
192                    if let Some(u) = usage {
193                        out.usage(u);
194                        finish = finish.with_usage(u);
195                        let total = started.elapsed().as_secs_f64();
196                        self.speed.lock().unwrap_or_else(|e| e.into_inner()).entry(self.id.clone()).or_default().record(
197                            first,
198                            total,
199                            u.prompt_tokens,
200                            u.completion_tokens,
201                        );
202                    }
203                    return Ok(finish);
204                }
205            }
206        }
207    }
208}
209
210#[async_trait]
211impl EmbedBackend for EngineModel {
212    fn name(&self) -> String {
213        self.id.clone()
214    }
215
216    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError> {
217        self.ready().await?;
218        let inputs = [input.to_string()];
219        let call = self.supervisor.embed(&self.id, &inputs);
220        let (mut vectors, _) = tokio::select! {
221            _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
222            r = call => r?,
223        };
224        vectors.pop().ok_or_else(|| engine_error("no embedding"))
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn speed_is_smoothed() {
234        let mut s = Speed::default();
235        s.record(Some(0.5), 1.5, 100, 11);
236        assert_eq!((s.ttft_ms, s.prefill_tps, s.decode_tps), (Some(500), Some(200.0), Some(10.0)));
237        s.record(Some(0.5), 0.5, 100, 11);
238        assert_eq!(s.decode_tps, Some(10.0), "no decode time: unchanged");
239    }
240}