Skip to main content

weirdnet_model/
worker.rs

1//! Inference on a worker thread: callers submit a request and read streamed text, and can cancel.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::mpsc::{self, Sender};
6
7use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
8
9use crate::prompt::ChatMessage;
10use crate::{Error, Result};
11
12/// One generation request.
13#[derive(Debug, Clone, PartialEq)]
14pub struct GenerateRequest {
15    pub messages: Vec<ChatMessage>,
16    /// Longest reply in tokens; the engine's default when `None`.
17    pub max_tokens: Option<u32>,
18    /// 0 or less is greedy; the engine's default when `None`.
19    pub temperature: Option<f32>,
20}
21
22impl GenerateRequest {
23    pub fn new(messages: Vec<ChatMessage>) -> Self {
24        Self { messages, max_tokens: None, temperature: None }
25    }
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum StopCause {
30    End,
31    MaxTokens,
32    Cancelled,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Stats {
37    pub prompt_tokens: u64,
38    pub generated_tokens: u64,
39    pub stop: StopCause,
40}
41
42/// A loaded model. `on_text` gets each piece of text as it is sampled and returns `false` to stop.
43pub trait Engine: Send + 'static {
44    fn generate(&mut self, req: &GenerateRequest, on_text: &mut dyn FnMut(&str) -> bool) -> Result<Stats>;
45}
46
47/// What a generation streams back.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Chunk {
50    Text(String),
51    /// The last chunk of a successful or cancelled generation.
52    Done(Stats),
53    /// The last chunk of a failed one (the model could not load, or sampling failed).
54    Failed(String),
55}
56
57/// A running generation.
58pub struct Generation {
59    rx: UnboundedReceiver<Chunk>,
60    cancel: Arc<AtomicBool>,
61}
62
63/// Stops a generation from another thread or task.
64#[derive(Debug, Clone)]
65pub struct Canceller(Arc<AtomicBool>);
66
67impl Canceller {
68    pub fn cancel(&self) {
69        self.0.store(true, Ordering::SeqCst);
70    }
71}
72
73impl Generation {
74    pub fn cancel(&self) {
75        self.cancel.store(true, Ordering::SeqCst);
76    }
77
78    pub fn canceller(&self) -> Canceller {
79        Canceller(self.cancel.clone())
80    }
81
82    /// The next chunk; `None` once the generation has ended.
83    pub async fn recv(&mut self) -> Option<Chunk> {
84        self.rx.recv().await
85    }
86
87    /// Like [`recv`](Self::recv), blocking the thread (not for async code).
88    pub fn blocking_recv(&mut self) -> Option<Chunk> {
89        self.rx.blocking_recv()
90    }
91
92    /// Waits for the whole reply: its text and how it ended.
93    pub fn collect_blocking(mut self) -> Result<(String, Stats)> {
94        let mut text = String::new();
95        while let Some(chunk) = self.blocking_recv() {
96            match chunk {
97                Chunk::Text(t) => text.push_str(&t),
98                Chunk::Done(stats) => return Ok((text, stats)),
99                Chunk::Failed(e) => return Err(Error::Model(e)),
100            }
101        }
102        Err(Error::Model("the worker stopped".into()))
103    }
104}
105
106impl Drop for Generation {
107    fn drop(&mut self) {
108        self.cancel.store(true, Ordering::SeqCst);
109    }
110}
111
112struct Job {
113    req: GenerateRequest,
114    tx: UnboundedSender<Chunk>,
115    cancel: Arc<AtomicBool>,
116}
117
118/// An engine on its own thread. The engine is loaded on the first request (and again after a
119/// failed load), so creating a worker is cheap. Requests run one at a time, in order.
120pub struct Worker {
121    jobs: Sender<Job>,
122}
123
124impl Worker {
125    pub fn spawn(mut load: impl FnMut() -> Result<Box<dyn Engine>> + Send + 'static) -> Self {
126        let (jobs, rx) = mpsc::channel::<Job>();
127        std::thread::Builder::new()
128            .name("weirdnet-model".into())
129            .spawn(move || {
130                let mut engine: Option<Box<dyn Engine>> = None;
131                while let Ok(job) = rx.recv() {
132                    if job.cancel.load(Ordering::SeqCst) {
133                        let stats = Stats { prompt_tokens: 0, generated_tokens: 0, stop: StopCause::Cancelled };
134                        let _ = job.tx.send(Chunk::Done(stats));
135                        continue;
136                    }
137                    if engine.is_none() {
138                        match load() {
139                            Ok(e) => engine = Some(e),
140                            Err(e) => {
141                                let _ = job.tx.send(Chunk::Failed(e.to_string()));
142                                continue;
143                            }
144                        }
145                    }
146                    let Some(e) = engine.as_mut() else { continue };
147                    let (tx, cancel) = (job.tx.clone(), job.cancel.clone());
148                    let result = e.generate(&job.req, &mut |piece| !cancel.load(Ordering::SeqCst) && tx.send(Chunk::Text(piece.to_string())).is_ok());
149                    let _ = job.tx.send(match result {
150                        Ok(mut stats) => {
151                            if job.cancel.load(Ordering::SeqCst) {
152                                stats.stop = StopCause::Cancelled;
153                            }
154                            Chunk::Done(stats)
155                        }
156                        Err(e) => Chunk::Failed(e.to_string()),
157                    });
158                }
159            })
160            .expect("spawn the model worker");
161        Self { jobs }
162    }
163
164    /// Queues a request and returns its stream.
165    pub fn generate(&self, req: GenerateRequest) -> Generation {
166        let (tx, rx) = unbounded_channel();
167        let cancel = Arc::new(AtomicBool::new(false));
168        if self.jobs.send(Job { req, tx: tx.clone(), cancel: cancel.clone() }).is_err() {
169            let _ = tx.send(Chunk::Failed("the worker stopped".into()));
170        }
171        Generation { rx, cancel }
172    }
173}
174
175#[cfg(test)]
176pub(crate) mod tests {
177    use std::sync::atomic::AtomicUsize;
178
179    use super::*;
180    use crate::prompt::ChatRole;
181
182    /// Says each word of the last user message back, one piece per word.
183    pub struct Echo {
184        pub delay_ms: u64,
185    }
186
187    impl Engine for Echo {
188        fn generate(&mut self, req: &GenerateRequest, on_text: &mut dyn FnMut(&str) -> bool) -> Result<Stats> {
189            let last = req.messages.iter().rev().find(|m| m.role == ChatRole::User).map(|m| m.content.clone()).unwrap_or_default();
190            let mut n = 0;
191            for w in last.split_whitespace() {
192                std::thread::sleep(std::time::Duration::from_millis(self.delay_ms));
193                if !on_text(&format!("{w} ")) {
194                    return Ok(Stats { prompt_tokens: 1, generated_tokens: n, stop: StopCause::Cancelled });
195                }
196                n += 1;
197            }
198            Ok(Stats { prompt_tokens: 1, generated_tokens: n, stop: StopCause::End })
199        }
200    }
201
202    fn req(text: &str) -> GenerateRequest {
203        GenerateRequest::new(vec![ChatMessage::new(ChatRole::User, text)])
204    }
205
206    #[test]
207    fn text_streams_in_order_and_ends_with_stats() {
208        let w = Worker::spawn(|| Ok(Box::new(Echo { delay_ms: 0 })));
209        let mut g = w.generate(req("one two three"));
210        let mut pieces = Vec::new();
211        let stats = loop {
212            match g.blocking_recv().unwrap() {
213                Chunk::Text(t) => pieces.push(t),
214                Chunk::Done(s) => break s,
215                Chunk::Failed(e) => panic!("{e}"),
216            }
217        };
218        assert_eq!(pieces, ["one ", "two ", "three "]);
219        assert_eq!((stats.generated_tokens, stats.stop), (3, StopCause::End));
220    }
221
222    #[test]
223    fn cancelling_stops_a_slow_reply() {
224        let w = Worker::spawn(|| Ok(Box::new(Echo { delay_ms: 20 })));
225        let mut g = w.generate(req(&"w ".repeat(500)));
226        assert!(matches!(g.blocking_recv(), Some(Chunk::Text(_))));
227        g.canceller().cancel();
228        let mut last = None;
229        while let Some(c) = g.blocking_recv() {
230            last = Some(c);
231        }
232        assert!(matches!(last, Some(Chunk::Done(Stats { stop: StopCause::Cancelled, generated_tokens, .. })) if generated_tokens < 500));
233    }
234
235    #[test]
236    fn a_failed_load_is_reported_and_retried_on_the_next_request() {
237        let tries = Arc::new(AtomicUsize::new(0));
238        let t = tries.clone();
239        let w = Worker::spawn(move || {
240            if t.fetch_add(1, Ordering::SeqCst) == 0 { Err(Error::Model("no file".into())) } else { Ok(Box::new(Echo { delay_ms: 0 })) }
241        });
242        let err = w.generate(req("a")).collect_blocking().unwrap_err();
243        assert!(err.to_string().contains("no file"), "{err}");
244        let (text, _) = w.generate(req("b")).collect_blocking().unwrap();
245        assert_eq!(text, "b ");
246        assert_eq!(tries.load(Ordering::SeqCst), 2);
247    }
248
249    #[test]
250    fn requests_run_one_at_a_time_in_order_and_a_dropped_stream_cancels() {
251        let w = Worker::spawn(|| Ok(Box::new(Echo { delay_ms: 5 })));
252        let first = w.generate(req("a b"));
253        let second = w.generate(req("c d"));
254        assert_eq!(first.collect_blocking().unwrap().0, "a b ");
255        assert_eq!(second.collect_blocking().unwrap().0, "c d ");
256        let dropped = w.generate(req(&"x ".repeat(1000)));
257        drop(dropped);
258        assert_eq!(w.generate(req("after")).collect_blocking().unwrap().0, "after ");
259    }
260
261    #[tokio::test]
262    async fn async_callers_can_await_chunks() {
263        let w = Worker::spawn(|| Ok(Box::new(Echo { delay_ms: 0 })));
264        let mut g = w.generate(req("hi there"));
265        let mut text = String::new();
266        while let Some(c) = g.recv().await {
267            if let Chunk::Text(t) = c {
268                text.push_str(&t);
269            }
270        }
271        assert_eq!(text, "hi there ");
272    }
273}