358 lines
14 KiB
Rust
358 lines
14 KiB
Rust
//! Several supervised workers behind the one generation channel (experimental).
|
|
//!
|
|
//! The control plane normally feeds one worker, which runs one generation at a time. With a pool, a dispatcher sits
|
|
//! between the API's channel and one channel per worker and hands each request to an idle, ready worker; requests
|
|
//! wait in arrival order while every worker is busy. Among the idle workers it picks the one whose last prompt shares
|
|
//! the longest prefix with the new prompt, so the turns of one conversation keep finding their cached prefix in the
|
|
//! same worker (a worker reuses only its own cache), and two conversations spread over two workers. Ties go to the
|
|
//! worker listed first. A worker counts as busy from dispatch until its result channel closes, which the dispatcher
|
|
//! learns by relaying that channel; a client that goes away still closes the worker's side, as without a pool.
|
|
|
|
use crate::worker::{GenerationCommand, GenerationResult, WorkerState, WorkerStatus};
|
|
use std::{collections::VecDeque, sync::Arc, time::Duration};
|
|
use tokio::sync::{RwLock, mpsc, oneshot};
|
|
|
|
/// Capacity of the relayed streaming channel between a worker and the original requester.
|
|
const RELAY_CAPACITY: usize = 64;
|
|
/// How often waiting requests are checked against workers that become ready.
|
|
const RECHECK: Duration = Duration::from_millis(200);
|
|
|
|
pub struct Member {
|
|
pub requests: mpsc::Sender<GenerationCommand>,
|
|
pub status: Arc<RwLock<WorkerStatus>>,
|
|
}
|
|
|
|
struct Slot {
|
|
member: Member,
|
|
busy: bool,
|
|
/// Prompt of the last request this worker took (its cache starts with it).
|
|
last_prompt: Vec<u32>,
|
|
}
|
|
|
|
/// The index of the idle, ready worker to take `prompt`; `None` while none is free. `Err(())` when no worker can
|
|
/// ever take it (all have stopped or failed for good).
|
|
async fn choose(slots: &[Slot], prompt: &[u32]) -> Result<Option<usize>, ()> {
|
|
let mut best: Option<(usize, usize)> = None;
|
|
let mut alive = false;
|
|
for (index, slot) in slots.iter().enumerate() {
|
|
let state = slot.member.status.read().await.state;
|
|
if !matches!(state, WorkerState::Failed | WorkerState::Stopping)
|
|
&& !slot.member.requests.is_closed()
|
|
{
|
|
alive = true;
|
|
}
|
|
if slot.busy || state != WorkerState::Ready {
|
|
continue;
|
|
}
|
|
let shared = slot
|
|
.last_prompt
|
|
.iter()
|
|
.zip(prompt)
|
|
.take_while(|(a, b)| a == b)
|
|
.count();
|
|
if best.is_none_or(|(_, longest)| shared > longest) {
|
|
best = Some((index, shared));
|
|
}
|
|
}
|
|
match best {
|
|
Some((index, _)) => Ok(Some(index)),
|
|
None if alive => Ok(None),
|
|
None => Err(()),
|
|
}
|
|
}
|
|
|
|
/// Forward the one buffered result of the worker to `original`, unless the caller gave up; then report `index`.
|
|
async fn relay_buffered(
|
|
mut original: oneshot::Sender<Result<Vec<crate::wire::Event>, String>>,
|
|
mut receiver: oneshot::Receiver<Result<Vec<crate::wire::Event>, String>>,
|
|
index: usize,
|
|
done: mpsc::UnboundedSender<usize>,
|
|
) {
|
|
let result = tokio::select! {
|
|
result = &mut receiver => result.ok(),
|
|
_ = original.closed() => None,
|
|
};
|
|
drop(receiver);
|
|
if let Some(result) = result {
|
|
let _ = original.send(result);
|
|
}
|
|
let _ = done.send(index);
|
|
}
|
|
|
|
/// Forward the streamed events of the worker to `original` until either side closes; then report `index`.
|
|
async fn relay_streaming(
|
|
original: mpsc::Sender<Result<crate::wire::Event, String>>,
|
|
mut receiver: mpsc::Receiver<Result<crate::wire::Event, String>>,
|
|
index: usize,
|
|
done: mpsc::UnboundedSender<usize>,
|
|
) {
|
|
loop {
|
|
let next = tokio::select! {
|
|
event = receiver.recv() => event,
|
|
_ = original.closed() => None,
|
|
};
|
|
let Some(event) = next else { break };
|
|
if original.send(event).await.is_err() {
|
|
break;
|
|
}
|
|
}
|
|
drop(receiver);
|
|
let _ = done.send(index);
|
|
}
|
|
|
|
/// Give `command` a fresh result channel and forward what the worker sends to the original one; report `index` on
|
|
/// `done` once the worker's side closes (finished, failed or abandoned).
|
|
fn relay(command: &mut GenerationCommand, index: usize, done: mpsc::UnboundedSender<usize>) {
|
|
match std::mem::replace(&mut command.result, GenerationResult::Finished) {
|
|
GenerationResult::Buffered(original) => {
|
|
let (sender, receiver) = oneshot::channel();
|
|
command.result = GenerationResult::Buffered(sender);
|
|
tokio::spawn(relay_buffered(original, receiver, index, done));
|
|
}
|
|
GenerationResult::Streaming(original) => {
|
|
let (sender, receiver) = mpsc::channel(RELAY_CAPACITY);
|
|
command.result = GenerationResult::Streaming(sender);
|
|
tokio::spawn(relay_streaming(original, receiver, index, done));
|
|
}
|
|
GenerationResult::Finished => {
|
|
let _ = done.send(index);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Route commands from `incoming` to `members` until `incoming` closes and nothing is in flight.
|
|
pub async fn dispatch(mut incoming: mpsc::Receiver<GenerationCommand>, members: Vec<Member>) {
|
|
let (done_sender, mut done) = mpsc::unbounded_channel();
|
|
let mut slots: Vec<Slot> = members
|
|
.into_iter()
|
|
.map(|member| Slot {
|
|
member,
|
|
busy: false,
|
|
last_prompt: Vec::new(),
|
|
})
|
|
.collect();
|
|
let mut pending: VecDeque<GenerationCommand> = VecDeque::new();
|
|
let mut incoming_open = true;
|
|
let mut recheck = tokio::time::interval(RECHECK);
|
|
loop {
|
|
assign_pending(&mut pending, &mut slots, &done_sender).await;
|
|
if drained(incoming_open, &pending, &slots) {
|
|
return;
|
|
}
|
|
tokio::select! {
|
|
command = incoming.recv(), if incoming_open => match command {
|
|
Some(command) => pending.push_back(command),
|
|
None => incoming_open = false,
|
|
},
|
|
Some(index) = done.recv() => slots[index].busy = false,
|
|
_ = recheck.tick(), if !pending.is_empty() => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Nothing more can arrive, wait or be in flight.
|
|
fn drained(incoming_open: bool, pending: &VecDeque<GenerationCommand>, slots: &[Slot]) -> bool {
|
|
!incoming_open && pending.is_empty() && slots.iter().all(|slot| !slot.busy)
|
|
}
|
|
|
|
/// Hand waiting commands, oldest first, to the workers that can take them now.
|
|
async fn assign_pending(
|
|
pending: &mut VecDeque<GenerationCommand>,
|
|
slots: &mut [Slot],
|
|
done_sender: &mpsc::UnboundedSender<usize>,
|
|
) {
|
|
while let Some(front) = pending.front() {
|
|
let index = match choose(slots, &front.request.token_ids).await {
|
|
Ok(Some(index)) => index,
|
|
Ok(None) => break,
|
|
Err(()) => {
|
|
// no worker will come back: dropping the commands closes their result channels
|
|
pending.clear();
|
|
break;
|
|
}
|
|
};
|
|
let command = pending.pop_front().expect("checked above");
|
|
send_to_slot(&mut slots[index], index, command, done_sender).await;
|
|
}
|
|
}
|
|
|
|
/// Mark `slot` busy with `command`, relay its result, and send it to the worker.
|
|
async fn send_to_slot(
|
|
slot: &mut Slot,
|
|
index: usize,
|
|
mut command: GenerationCommand,
|
|
done_sender: &mpsc::UnboundedSender<usize>,
|
|
) {
|
|
slot.last_prompt.clone_from(&command.request.token_ids);
|
|
slot.busy = true;
|
|
relay(&mut command, index, done_sender.clone());
|
|
if let Err(mpsc::error::SendError(command)) = slot.member.requests.send(command).await {
|
|
// the worker's task has ended; its relay reports it idle when the command is dropped here
|
|
drop(command);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::wire::{Event, Generate};
|
|
|
|
fn command(
|
|
prompt: &[u32],
|
|
) -> (
|
|
GenerationCommand,
|
|
oneshot::Receiver<Result<Vec<Event>, String>>,
|
|
) {
|
|
let (result, received) = oneshot::channel();
|
|
(
|
|
GenerationCommand {
|
|
queue: None,
|
|
activity: None,
|
|
request: Generate {
|
|
token_ids: prompt.to_vec(),
|
|
max_new: 1,
|
|
..Default::default()
|
|
},
|
|
result: GenerationResult::Buffered(result),
|
|
},
|
|
received,
|
|
)
|
|
}
|
|
|
|
async fn ready_member() -> (Member, mpsc::Receiver<GenerationCommand>) {
|
|
let (requests, received) = mpsc::channel(1);
|
|
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
|
status.write().await.state = WorkerState::Ready;
|
|
(Member { requests, status }, received)
|
|
}
|
|
|
|
fn answer(command: GenerationCommand, text: &str) {
|
|
let GenerationResult::Buffered(sender) = command.result else {
|
|
panic!("buffered expected")
|
|
};
|
|
sender
|
|
.send(Ok(vec![Event::Error(text.to_owned())]))
|
|
.unwrap();
|
|
}
|
|
|
|
/// Two conversations start at once: one lands on each worker, and the results reach their requesters.
|
|
async fn first_turns(
|
|
sender: &mpsc::Sender<GenerationCommand>,
|
|
first_queue: &mut mpsc::Receiver<GenerationCommand>,
|
|
second_queue: &mut mpsc::Receiver<GenerationCommand>,
|
|
) {
|
|
let (a1, a1_result) = command(&[1, 2, 3]);
|
|
let (b1, b1_result) = command(&[7, 8, 9]);
|
|
sender.send(a1).await.unwrap();
|
|
sender.send(b1).await.unwrap();
|
|
let got_a = first_queue.recv().await.unwrap();
|
|
let got_b = second_queue.recv().await.unwrap();
|
|
assert_eq!(got_a.request.token_ids, [1, 2, 3]);
|
|
assert_eq!(got_b.request.token_ids, [7, 8, 9]);
|
|
answer(got_b, "b1");
|
|
answer(got_a, "a1");
|
|
assert_eq!(
|
|
a1_result.await.unwrap().unwrap(),
|
|
[Event::Error("a1".into())]
|
|
);
|
|
assert_eq!(
|
|
b1_result.await.unwrap().unwrap(),
|
|
[Event::Error("b1".into())]
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn two_conversations_spread_and_keep_their_worker_and_results_reach_the_requester() {
|
|
let (first, mut first_queue) = ready_member().await;
|
|
let (second, mut second_queue) = ready_member().await;
|
|
let (sender, incoming) = mpsc::channel(16);
|
|
let dispatcher = tokio::spawn(dispatch(incoming, vec![first, second]));
|
|
|
|
first_turns(&sender, &mut first_queue, &mut second_queue).await;
|
|
|
|
// the next turns extend their prompts and go back to the worker that holds their prefix, whatever the order
|
|
let (b2, _b2_result) = command(&[7, 8, 9, 10]);
|
|
let (a2, _a2_result) = command(&[1, 2, 3, 4]);
|
|
sender.send(b2).await.unwrap();
|
|
sender.send(a2).await.unwrap();
|
|
assert_eq!(
|
|
second_queue.recv().await.unwrap().request.token_ids,
|
|
[7, 8, 9, 10]
|
|
);
|
|
assert_eq!(
|
|
first_queue.recv().await.unwrap().request.token_ids,
|
|
[1, 2, 3, 4]
|
|
);
|
|
drop(sender);
|
|
dispatcher.abort();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn requests_wait_while_every_worker_is_busy_and_skip_one_that_is_not_ready() {
|
|
let (first, mut first_queue) = ready_member().await;
|
|
let (second, mut second_queue) = ready_member().await;
|
|
second.status.write().await.state = WorkerState::Starting;
|
|
let second_status = second.status.clone();
|
|
let (sender, incoming) = mpsc::channel(16);
|
|
let dispatcher = tokio::spawn(dispatch(incoming, vec![first, second]));
|
|
let (one, _one_result) = command(&[1]);
|
|
let (two, _two_result) = command(&[2]);
|
|
sender.send(one).await.unwrap();
|
|
sender.send(two).await.unwrap();
|
|
let taken = first_queue.recv().await.unwrap();
|
|
// the second request waits: the first worker is busy, the second is still starting
|
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
|
assert!(second_queue.try_recv().is_err());
|
|
second_status.write().await.state = WorkerState::Ready;
|
|
assert_eq!(second_queue.recv().await.unwrap().request.token_ids, [2]);
|
|
drop(taken);
|
|
drop(sender);
|
|
dispatcher.abort();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_requester_that_leaves_frees_the_worker_and_closes_its_side() {
|
|
let (only, mut queue) = ready_member().await;
|
|
let (sender, incoming) = mpsc::channel(16);
|
|
let dispatcher = tokio::spawn(dispatch(incoming, vec![only]));
|
|
let (first, first_result) = command(&[1]);
|
|
sender.send(first).await.unwrap();
|
|
let taken = queue.recv().await.unwrap();
|
|
drop(first_result);
|
|
let GenerationResult::Buffered(worker_side) = &taken.result else {
|
|
panic!("buffered expected")
|
|
};
|
|
tokio::time::timeout(Duration::from_secs(1), async {
|
|
while !worker_side.is_closed() {
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.expect("the worker's result channel closes");
|
|
let (second, _second_result) = command(&[2]);
|
|
sender.send(second).await.unwrap();
|
|
assert_eq!(queue.recv().await.unwrap().request.token_ids, [2]);
|
|
drop(sender);
|
|
dispatcher.abort();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn requests_fail_when_no_worker_can_come_back() {
|
|
let (only, queue) = ready_member().await;
|
|
only.status.write().await.state = WorkerState::Failed;
|
|
drop(queue);
|
|
let (sender, incoming) = mpsc::channel(16);
|
|
let dispatcher = tokio::spawn(dispatch(incoming, vec![only]));
|
|
let (one, one_result) = command(&[1]);
|
|
sender.send(one).await.unwrap();
|
|
assert!(
|
|
tokio::time::timeout(Duration::from_secs(2), one_result)
|
|
.await
|
|
.expect("answered")
|
|
.is_err()
|
|
);
|
|
drop(sender);
|
|
dispatcher.await.unwrap();
|
|
}
|
|
}
|