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