Oversize files before/after: tokenizer 1 -> 0 (lib.rs 840 into construction, encoding, decoding, bpe_merge, vocabulary), gateway-text 1 -> 0, runtime-client 1 -> 0, cpu-worker 1 -> 0, experimental-ref 1 -> 0 (test files split by topic), gateway-domain 1 -> 0: render_request_with (385 lines, complexity 93) became an entry function plus one function per system message and one method per input item kind; messages, check order and rendered text unchanged (gateway-domain 17 tests and strata-control responses 72 tests pass). Census prod/test (fn>30 / cx>10 / nesting>4 / wide lines): gateway-domain 16/3, 13/0, 6/0, 53/1 -> 16/3, 12/0, 5/0, 45/1; runtime-client test 9 -> 6 long functions; experimental-ref test wide lines 58 -> 37; tokenizer, gateway-text and cpu-worker unchanged. Test ids and outcomes unchanged.
289 lines
7.9 KiB
Rust
289 lines
7.9 KiB
Rust
//! The request loop against a mock decoder: protocol lines, stop tokens, prefix reuse, STOP and QUIT.
|
|
|
|
use leleka_cpu_worker::serve::{Decoder, serve};
|
|
use std::io::{self, BufReader, Read, Write};
|
|
use std::sync::mpsc::{self, Receiver, Sender};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
|
|
const VOCAB: usize = 10;
|
|
|
|
/// A decoder whose next token is always `last + 1` (mod 10); it keeps the fed tokens like the real one.
|
|
struct Mock {
|
|
cache: Vec<u32>,
|
|
logits: Vec<f32>,
|
|
context: usize,
|
|
step_delay: Duration,
|
|
fail_at: Option<usize>,
|
|
}
|
|
|
|
impl Mock {
|
|
fn new() -> Self {
|
|
Self {
|
|
cache: Vec::new(),
|
|
logits: vec![0.0; VOCAB],
|
|
context: 64,
|
|
step_delay: Duration::ZERO,
|
|
fail_at: None,
|
|
}
|
|
}
|
|
|
|
fn set_logits(&mut self, last: u32) {
|
|
self.logits = vec![0.0; VOCAB];
|
|
self.logits[(last as usize + 1) % VOCAB] = 5.0;
|
|
}
|
|
}
|
|
|
|
impl Decoder for Mock {
|
|
fn max_context(&self) -> usize {
|
|
self.context
|
|
}
|
|
|
|
fn prefill(
|
|
&mut self,
|
|
prompt: &[u32],
|
|
progress: &mut dyn FnMut(usize, usize) -> bool,
|
|
) -> Result<Option<usize>, String> {
|
|
let common = self
|
|
.cache
|
|
.iter()
|
|
.zip(prompt)
|
|
.take_while(|(a, b)| a == b)
|
|
.count()
|
|
.min(prompt.len() - 1);
|
|
self.cache.truncate(common);
|
|
let mut done = common;
|
|
while done < prompt.len() {
|
|
let end = (done + 2).min(prompt.len());
|
|
self.cache.extend_from_slice(&prompt[done..end]);
|
|
done = end;
|
|
if !progress(done, prompt.len()) {
|
|
return Ok(None);
|
|
}
|
|
}
|
|
self.set_logits(*prompt.last().unwrap());
|
|
Ok(Some(common))
|
|
}
|
|
|
|
fn logits(&self) -> &[f32] {
|
|
&self.logits
|
|
}
|
|
|
|
fn advance(&mut self, token: u32) -> Result<(), String> {
|
|
std::thread::sleep(self.step_delay);
|
|
if self.fail_at == Some(self.cache.len()) {
|
|
return Err("engine exploded".into());
|
|
}
|
|
self.cache.push(token);
|
|
self.set_logits(token);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// A reader fed from a channel, so a test can type lines while the server runs.
|
|
struct ChannelReader {
|
|
rx: Receiver<Vec<u8>>,
|
|
pending: Vec<u8>,
|
|
}
|
|
|
|
impl Read for ChannelReader {
|
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
if self.pending.is_empty() {
|
|
match self.rx.recv() {
|
|
Ok(bytes) => self.pending = bytes,
|
|
Err(_) => return Ok(0), // sender dropped: end of input
|
|
}
|
|
}
|
|
let n = buf.len().min(self.pending.len());
|
|
buf[..n].copy_from_slice(&self.pending[..n]);
|
|
self.pending.drain(..n);
|
|
Ok(n)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct SharedOut(Arc<Mutex<Vec<u8>>>);
|
|
|
|
impl Write for SharedOut {
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
self.0.lock().unwrap().extend_from_slice(buf);
|
|
Ok(buf.len())
|
|
}
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl SharedOut {
|
|
fn lines(&self) -> Vec<String> {
|
|
String::from_utf8(self.0.lock().unwrap().clone())
|
|
.unwrap()
|
|
.lines()
|
|
.map(str::to_owned)
|
|
.collect()
|
|
}
|
|
|
|
fn wait_for(&self, what: &str, test: impl Fn(&[String]) -> bool) {
|
|
let deadline = Instant::now() + Duration::from_secs(10);
|
|
while Instant::now() < deadline {
|
|
if test(&self.lines()) {
|
|
return;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
panic!("timed out waiting for {what}; output so far: {:?}", self.lines());
|
|
}
|
|
}
|
|
|
|
struct Session {
|
|
out: SharedOut,
|
|
tx: Option<Sender<Vec<u8>>>,
|
|
handle: Option<std::thread::JoinHandle<io::Result<()>>>,
|
|
}
|
|
|
|
impl Session {
|
|
fn start<D: Decoder + Send + 'static>(mut decoder: D) -> Self {
|
|
let (tx, rx) = mpsc::channel();
|
|
let out = SharedOut::default();
|
|
let (writer, stops) = (out.clone(), [9u32]);
|
|
let handle = std::thread::spawn(move || {
|
|
let input = BufReader::new(ChannelReader {
|
|
rx,
|
|
pending: Vec::new(),
|
|
});
|
|
serve(&mut decoder, input, writer, &stops, 1)
|
|
});
|
|
Self {
|
|
out,
|
|
tx: Some(tx),
|
|
handle: Some(handle),
|
|
}
|
|
}
|
|
|
|
fn send(&self, line: &str) {
|
|
self.tx
|
|
.as_ref()
|
|
.unwrap()
|
|
.send(format!("{line}\n").into_bytes())
|
|
.unwrap();
|
|
}
|
|
|
|
fn finish(mut self) -> Vec<String> {
|
|
drop(self.tx.take()); // end of input
|
|
self.handle.take().unwrap().join().unwrap().unwrap();
|
|
self.out.lines()
|
|
}
|
|
|
|
fn done_count(&self) -> usize {
|
|
self.out.lines().iter().filter(|l| l.starts_with("DONE ")).count()
|
|
}
|
|
}
|
|
|
|
fn tokens(lines: &[String]) -> Vec<u32> {
|
|
lines
|
|
.iter()
|
|
.filter_map(|l| l.strip_prefix("T "))
|
|
.map(|t| t.parse().unwrap())
|
|
.collect()
|
|
}
|
|
|
|
fn s_done(lines: &[String]) -> usize {
|
|
lines.iter().filter(|l| l.starts_with("DONE ")).count()
|
|
}
|
|
|
|
/// A decoder whose next token is a hash of the last four fed tokens (so repeated three-token contexts can still
|
|
/// continue differently), with batch decoding and truncation for speculative decoding.
|
|
struct Hashing {
|
|
cache: Vec<u32>,
|
|
logits: Vec<f32>,
|
|
speculate: bool,
|
|
batches: Arc<Mutex<(usize, usize)>>, // (advance_many calls, truncate calls)
|
|
}
|
|
|
|
impl Hashing {
|
|
fn new(speculate: bool, batches: Arc<Mutex<(usize, usize)>>) -> Self {
|
|
Self {
|
|
cache: Vec::new(),
|
|
logits: vec![0.0; VOCAB],
|
|
speculate,
|
|
batches,
|
|
}
|
|
}
|
|
|
|
fn logits_of(cache: &[u32]) -> Vec<f32> {
|
|
let at = |back: usize| cache.len().checked_sub(back).map_or(0, |i| cache[i]);
|
|
let next = (at(1) + 2 * at(2) + 3 * at(3) + 5 * at(4)) % 9; // never the stop token 9
|
|
// temperature 0.8 samples below; the shape keeps the choice deterministic per context
|
|
let mut logits = vec![-50.0; VOCAB];
|
|
logits[next as usize] = 3.0;
|
|
logits[((next + 4) % 9) as usize] = 2.0;
|
|
logits
|
|
}
|
|
}
|
|
|
|
impl Decoder for Hashing {
|
|
fn max_context(&self) -> usize {
|
|
4096
|
|
}
|
|
|
|
fn prefill(
|
|
&mut self,
|
|
prompt: &[u32],
|
|
progress: &mut dyn FnMut(usize, usize) -> bool,
|
|
) -> Result<Option<usize>, String> {
|
|
self.cache = prompt.to_vec();
|
|
self.logits = Self::logits_of(&self.cache);
|
|
progress(prompt.len(), prompt.len());
|
|
Ok(Some(0))
|
|
}
|
|
|
|
fn logits(&self) -> &[f32] {
|
|
&self.logits
|
|
}
|
|
|
|
fn advance(&mut self, token: u32) -> Result<(), String> {
|
|
self.cache.push(token);
|
|
self.logits = Self::logits_of(&self.cache);
|
|
Ok(())
|
|
}
|
|
|
|
fn speculating(&self) -> bool {
|
|
self.speculate
|
|
}
|
|
|
|
fn cached_len(&self) -> usize {
|
|
self.cache.len()
|
|
}
|
|
|
|
fn advance_many(&mut self, tokens: &[u32]) -> Result<Vec<Vec<f32>>, String> {
|
|
self.batches.lock().unwrap().0 += 1;
|
|
let mut all = Vec::new();
|
|
for token in tokens {
|
|
self.cache.push(*token);
|
|
all.push(Self::logits_of(&self.cache));
|
|
}
|
|
self.logits = all.last().unwrap().clone();
|
|
Ok(all)
|
|
}
|
|
|
|
fn truncate(&mut self, len: usize) {
|
|
self.batches.lock().unwrap().1 += 1;
|
|
self.cache.truncate(len);
|
|
}
|
|
}
|
|
|
|
fn run_hashing(speculate: bool, request: &str) -> (Vec<u32>, (usize, usize)) {
|
|
let counters = Arc::new(Mutex::new((0, 0)));
|
|
let s = Session::start(Hashing::new(speculate, counters.clone()));
|
|
s.send(request);
|
|
s.out.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
|
|
let lines = s.finish();
|
|
let counts = *counters.lock().unwrap();
|
|
(tokens(&lines), counts)
|
|
}
|
|
|
|
#[path = "serve_loop/failure_shutdown_and_speculation.rs"]
|
|
mod failure_shutdown_and_speculation;
|
|
#[path = "serve_loop/generation_and_cancellation.rs"]
|
|
mod generation_and_cancellation;
|