1use 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::{
12 self, EmbedBackend, Finish, InferBackend, Input, Output, Request, TranscribeBackend, TranscribeRequest, Transcript, Usage,
13};
14use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError};
15use weirdnet_agent::{CancelToken, Modalities, ModelBackend};
16
17use crate::error::{bad_request, engine_error, unavailable};
18use crate::sse::{Chunk, ToolCalls};
19use crate::supervisor::{ModelState, Supervisor};
20
21#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
23pub struct Speed {
24 pub decode_tps: Option<f32>,
26 pub prefill_tps: Option<f32>,
28 pub ttft_ms: Option<u64>,
30}
31
32impl Speed {
33 fn ewma(old: Option<f32>, new: f32) -> Option<f32> {
34 Some(match old {
35 Some(o) => o * 0.8 + new * 0.2,
36 None => new,
37 })
38 }
39
40 fn record(&mut self, ttft: Option<f64>, total: f64, prompt: u64, completion: u64) {
41 if let Some(t) = ttft {
42 self.ttft_ms = Some((t * 1000.0) as u64);
43 if t > 0.0 && prompt > 0 {
44 self.prefill_tps = Self::ewma(self.prefill_tps, prompt as f32 / t as f32);
45 }
46 let decode = total - t;
47 if decode > 0.0 && completion > 1 {
48 self.decode_tps = Self::ewma(self.decode_tps, (completion - 1) as f32 / decode as f32);
49 }
50 }
51 }
52}
53
54pub struct ModelHost {
61 supervisor: Supervisor,
62 auth: Arc<dyn Authorize>,
63 default_model: Option<String>,
64 load_on_demand: bool,
65 draining: AtomicBool,
66 speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
67}
68
69impl ModelHost {
70 pub fn new(supervisor: Supervisor, auth: Arc<dyn Authorize>) -> Self {
71 Self { supervisor, auth, default_model: None, load_on_demand: false, draining: AtomicBool::new(false), speed: Default::default() }
72 }
73
74 pub fn with_default(mut self, model: impl Into<String>) -> Self {
76 self.default_model = Some(model.into());
77 self
78 }
79
80 pub fn with_load_on_demand(mut self, on: bool) -> Self {
82 self.load_on_demand = on;
83 self
84 }
85
86 pub fn supervisor(&self) -> &Supervisor {
87 &self.supervisor
88 }
89
90 pub fn set_draining(&self, on: bool) {
92 self.draining.store(on, Ordering::SeqCst);
93 }
94
95 pub fn draining(&self) -> bool {
96 self.draining.load(Ordering::SeqCst)
97 }
98
99 pub fn speed(&self, model: &str) -> Speed {
101 self.speed.lock().unwrap_or_else(|e| e.into_inner()).get(model).copied().unwrap_or_default()
102 }
103
104 fn pick(&self, model: Option<&str>, wait: bool, needed: Modalities) -> Result<(String, bool), RemoteError> {
105 if self.draining() {
106 return Err(unavailable("this node is draining"));
107 }
108 if let Some(r) = self.supervisor.reservation() {
109 return Err(unavailable(format!("this node is reserved by {}", r.holder)));
110 }
111 let id = model.map(str::to_string).or_else(|| self.default_model.clone()).ok_or_else(|| bad_request("no model named and no default"))?;
112 if let Some(what) = self.supervisor.capabilities(&id).and_then(|c| c.lacking(needed)) {
113 return Err(RemoteError::Unsupported { message: format!("model `{id}` does not take {what} on this node") });
114 }
115 match self.supervisor.state(&id) {
116 None => Err(crate::error::unknown_model(&id)),
117 Some(ModelState::Ready) => Ok((id, false)),
118 Some(_) if wait || self.load_on_demand => Ok((id, true)),
119 Some(state) => Err(unavailable(format!("{id} is not loaded ({state:?})"))),
120 }
121 }
122
123 fn pick_transcriber(&self, model: Option<&str>) -> Result<(String, bool), RemoteError> {
127 let transcribes = |id: &str| self.supervisor.capabilities(id).is_some_and(|c| c.transcribe);
128 let id = match model {
129 Some(id) => {
130 if self.supervisor.state(id).is_none() {
131 return Err(crate::error::unknown_model(id));
132 }
133 if !transcribes(id) {
134 return Err(RemoteError::Unsupported { message: format!("model `{id}` does not transcribe on this node") });
135 }
136 id.to_string()
137 }
138 None => {
139 let ids: Vec<String> = self.supervisor.launches().into_iter().map(|l| l.id).filter(|id| transcribes(id)).collect();
140 let ready = ids.iter().find(|id| self.supervisor.state(id) == Some(ModelState::Ready));
141 match ready.or(ids.first().filter(|_| self.load_on_demand)) {
142 Some(id) => id.clone(),
143 None if ids.is_empty() => return Err(unavailable("no transcription model on this node")),
144 None => return Err(unavailable(format!("no transcription model is loaded on this node ({})", ids.join(", ")))),
145 }
146 }
147 };
148 self.pick(Some(&id), false, Modalities::TEXT)
149 }
150
151 fn backend(&self, id: String, load: bool) -> EngineModel {
152 EngineModel { supervisor: self.supervisor.clone(), id, load, speed: self.speed.clone() }
153 }
154}
155
156impl InferHost for ModelHost {
157 fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
158 self.auth.authorize(caller)
159 }
160
161 fn open(&self, _caller: &Caller, _model: Option<&str>) -> Result<Arc<dyn ModelBackend>, RemoteError> {
163 Err(RemoteError::Unsupported { message: "model nodes serve /weirdnet-agent/infer/2".into() })
164 }
165
166 fn open_request(&self, _caller: &Caller, request: &Request) -> Result<Arc<dyn InferBackend>, RemoteError> {
167 let needed = request.needs();
168 if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
169 return Err(bad_request(message));
170 }
171 let (id, load) = self.pick(request.model.as_deref(), request.wait_for_model, needed)?;
172 Ok(Arc::new(self.backend(id, load)))
173 }
174
175 fn open_embed(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn EmbedBackend>, RemoteError> {
176 let (id, load) = self.pick(model, false, Modalities::TEXT)?;
177 Ok(Arc::new(self.backend(id, load)))
178 }
179
180 fn open_transcribe(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn TranscribeBackend>, RemoteError> {
186 let (id, load) = self.pick_transcriber(model)?;
187 Ok(Arc::new(self.backend(id, load)))
188 }
189}
190
191pub struct EngineModel {
193 supervisor: Supervisor,
194 id: String,
195 load: bool,
196 speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
197}
198
199impl EngineModel {
200 async fn ready(&self) -> Result<(), RemoteError> {
201 if self.load { self.supervisor.load(&self.id).await } else { Ok(()) }
202 }
203}
204
205#[async_trait]
206impl InferBackend for EngineModel {
207 fn name(&self) -> String {
208 self.id.clone()
209 }
210
211 fn resumes(&self) -> bool {
214 true
215 }
216
217 async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
218 self.ready().await?;
219 let started = Instant::now();
220 let mut stream = match &request.input {
221 Input::Prompt(prompt) => {
222 let mut prompt = prompt.clone();
223 if let Some(p) = &request.assistant_prefix {
224 prompt.push_str(&p.text);
225 }
226 self.supervisor.complete_scaled(&self.id, &prompt, &request.sampling, request.seed, request.adapter_scale).await?
227 }
228 _ => self.supervisor.chat(&self.id, request).await?,
229 };
230 let mut calls = ToolCalls::default();
231 let mut first: Option<f64> = None;
232 loop {
233 let next = tokio::select! {
234 _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
235 n = stream.next() => n,
236 };
237 let chunk = match next {
238 Some(c) => c?,
239 None => return Err(engine_error("engine stream ended early")),
240 };
241 if first.is_none() && matches!(chunk, Chunk::Text(_) | Chunk::Reasoning(_) | Chunk::ToolCall { .. }) {
242 first = Some(started.elapsed().as_secs_f64());
243 }
244 match chunk {
245 Chunk::Text(t) => out.text(t),
246 Chunk::Reasoning(t) => out.reasoning(t),
247 Chunk::ToolCall { index, id, name, arguments } => calls.push(index, id, name, &arguments),
248 Chunk::Done { finish_reason, usage } => {
249 let had_calls = !calls.is_empty();
250 for call in calls.finish() {
251 out.tool_call(call);
252 }
253 let reason = finish_reason.unwrap_or_else(|| if had_calls { "tool_calls".into() } else { "stop".into() });
254 let mut finish = Finish::new(reason);
255 if let Some(u) = usage {
256 out.usage(u);
257 finish = finish.with_usage(u);
258 let total = started.elapsed().as_secs_f64();
259 self.speed.lock().unwrap_or_else(|e| e.into_inner()).entry(self.id.clone()).or_default().record(
260 first,
261 total,
262 u.prompt_tokens,
263 u.completion_tokens,
264 );
265 }
266 return Ok(finish);
267 }
268 }
269 }
270 }
271}
272
273#[async_trait]
274impl EmbedBackend for EngineModel {
275 fn name(&self) -> String {
276 self.id.clone()
277 }
278
279 async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError> {
280 Ok(self.embed_counted(input, cancel).await?.0)
281 }
282
283 async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
285 self.ready().await?;
286 let inputs = [input.to_string()];
287 let call = self.supervisor.embed(&self.id, &inputs);
288 let (mut vectors, tokens) = tokio::select! {
289 _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
290 r = call => r?,
291 };
292 Ok((vectors.pop().ok_or_else(|| engine_error("no embedding"))?, Some(tokens)))
293 }
294}
295
296#[async_trait]
297impl TranscribeBackend for EngineModel {
298 fn name(&self) -> String {
299 self.id.clone()
300 }
301
302 async fn transcribe(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcript, RemoteError> {
303 Ok(self.transcribe_counted(request, cancel).await?.0)
304 }
305
306 async fn transcribe_counted(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<(Transcript, Option<Usage>), RemoteError> {
308 self.ready().await?;
309 tokio::select! {
310 _ = cancel.cancelled() => Err(RemoteError::Cancelled),
311 r = self.supervisor.transcribe(&self.id, request) => r,
312 }
313 }
314}
315
316pub const RAW_INFER_PROTOCOL: &str = "/weirdnet-backends/infer/1";
320
321pub struct RawInferDialer {
326 inner: Arc<dyn Dialer>,
327 legacy: Mutex<std::collections::HashSet<String>>,
328}
329
330impl RawInferDialer {
331 pub fn new(inner: Arc<dyn Dialer>) -> Self {
332 Self { inner, legacy: Mutex::new(Default::default()) }
333 }
334
335 pub fn is_legacy(&self, node: &str) -> bool {
337 self.legacy.lock().unwrap_or_else(|e| e.into_inner()).contains(node)
338 }
339}
340
341#[async_trait]
342impl Dialer for RawInferDialer {
343 async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
344 if protocol != v2::PROTOCOL {
345 return self.inner.open(node, protocol).await;
346 }
347 if !self.is_legacy(node) {
348 match self.inner.open(node, RAW_INFER_PROTOCOL).await {
349 Err(RemoteError::Unsupported { .. }) => {}
350 other => return other,
351 }
352 }
353 let ch = self.inner.open(node, v2::PROTOCOL).await?;
354 self.legacy.lock().unwrap_or_else(|e| e.into_inner()).insert(node.to_string());
355 Ok(ch)
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 #[test]
364 fn speed_is_smoothed() {
365 let mut s = Speed::default();
366 s.record(Some(0.5), 1.5, 100, 11);
367 assert_eq!((s.ttft_ms, s.prefill_tps, s.decode_tps), (Some(500), Some(200.0), Some(10.0)));
368 s.record(Some(0.5), 0.5, 100, 11);
369 assert_eq!(s.decode_tps, Some(10.0), "no decode time: unchanged");
370 }
371}