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, 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 (chat) or the prompt plus the prefix (a raw
159    /// prompt, through `/v1/completions`).
160    fn resumes(&self) -> bool {
161        true
162    }
163
164    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
165        self.ready().await?;
166        let started = Instant::now();
167        let mut stream = match &request.input {
168            Input::Prompt(prompt) => {
169                let mut prompt = prompt.clone();
170                if let Some(p) = &request.assistant_prefix {
171                    prompt.push_str(&p.text);
172                }
173                self.supervisor.complete(&self.id, &prompt, &request.sampling, request.seed).await?
174            }
175            _ => self.supervisor.chat(&self.id, request).await?,
176        };
177        let mut calls = ToolCalls::default();
178        let mut first: Option<f64> = None;
179        loop {
180            let next = tokio::select! {
181                _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
182                n = stream.next() => n,
183            };
184            let chunk = match next {
185                Some(c) => c?,
186                None => return Err(engine_error("engine stream ended early")),
187            };
188            if first.is_none() && matches!(chunk, Chunk::Text(_) | Chunk::Reasoning(_) | Chunk::ToolCall { .. }) {
189                first = Some(started.elapsed().as_secs_f64());
190            }
191            match chunk {
192                Chunk::Text(t) => out.text(t),
193                Chunk::Reasoning(t) => out.reasoning(t),
194                Chunk::ToolCall { index, id, name, arguments } => calls.push(index, id, name, &arguments),
195                Chunk::Done { finish_reason, usage } => {
196                    let had_calls = !calls.is_empty();
197                    for call in calls.finish() {
198                        out.tool_call(call);
199                    }
200                    let reason = finish_reason.unwrap_or_else(|| if had_calls { "tool_calls".into() } else { "stop".into() });
201                    let mut finish = Finish::new(reason);
202                    if let Some(u) = usage {
203                        out.usage(u);
204                        finish = finish.with_usage(u);
205                        let total = started.elapsed().as_secs_f64();
206                        self.speed.lock().unwrap_or_else(|e| e.into_inner()).entry(self.id.clone()).or_default().record(
207                            first,
208                            total,
209                            u.prompt_tokens,
210                            u.completion_tokens,
211                        );
212                    }
213                    return Ok(finish);
214                }
215            }
216        }
217    }
218}
219
220#[async_trait]
221impl EmbedBackend for EngineModel {
222    fn name(&self) -> String {
223        self.id.clone()
224    }
225
226    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError> {
227        Ok(self.embed_counted(input, cancel).await?.0)
228    }
229
230    /// The vector and the engine's `usage.prompt_tokens`.
231    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
232        self.ready().await?;
233        let inputs = [input.to_string()];
234        let call = self.supervisor.embed(&self.id, &inputs);
235        let (mut vectors, tokens) = tokio::select! {
236            _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
237            r = call => r?,
238        };
239        Ok((vectors.pop().ok_or_else(|| engine_error("no embedding"))?, Some(tokens)))
240    }
241}
242
243/// The protocol id model nodes serve raw infer on: the `/weirdnet-agent/infer/2` framing under
244/// its own id, so one node can be an inference node (which serves infer/2 to apps) and a model
245/// node at once. `NodeServer` (`node` feature) always serves it; [`RawInferDialer`] prefers it.
246pub const RAW_INFER_PROTOCOL: &str = "/weirdnet-backends/infer/1";
247
248/// A [`Dialer`] for inference nodes talking to model nodes: opening
249/// `/weirdnet-agent/infer/2` tries [`RAW_INFER_PROTOCOL`] first and falls back to infer/2 on
250/// nodes that don't accept it (backends 0.1.0). Nodes that fell back are remembered. Other
251/// protocols pass through. Wrap the dialer given to the `Pool` of model nodes.
252pub struct RawInferDialer {
253    inner: Arc<dyn Dialer>,
254    legacy: Mutex<std::collections::HashSet<String>>,
255}
256
257impl RawInferDialer {
258    pub fn new(inner: Arc<dyn Dialer>) -> Self {
259        Self { inner, legacy: Mutex::new(Default::default()) }
260    }
261
262    /// Whether `node` answered only on infer/2.
263    pub fn is_legacy(&self, node: &str) -> bool {
264        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).contains(node)
265    }
266}
267
268#[async_trait]
269impl Dialer for RawInferDialer {
270    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
271        if protocol != v2::PROTOCOL {
272            return self.inner.open(node, protocol).await;
273        }
274        if !self.is_legacy(node) {
275            match self.inner.open(node, RAW_INFER_PROTOCOL).await {
276                Err(RemoteError::Unsupported { .. }) => {}
277                other => return other,
278            }
279        }
280        let ch = self.inner.open(node, v2::PROTOCOL).await?;
281        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).insert(node.to_string());
282        Ok(ch)
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn speed_is_smoothed() {
292        let mut s = Speed::default();
293        s.record(Some(0.5), 1.5, 100, 11);
294        assert_eq!((s.ttft_ms, s.prefill_tps, s.decode_tps), (Some(500), Some(200.0), Some(10.0)));
295        s.record(Some(0.5), 0.5, 100, 11);
296        assert_eq!(s.decode_tps, Some(10.0), "no decode time: unchanged");
297    }
298}