Merge branch 'claude/cp-latency' into claude/port-gpu-bringup
This commit is contained in:
Generated
+1
@@ -1146,6 +1146,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"fancy-regex",
|
||||
"regex-syntax",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,944 @@
|
||||
//! Host-side latency replay (`docs/cp-latency.md`): Codex-shaped Responses requests with a growing history sent over real
|
||||
//! loopback HTTP to the real router, the real worker adapter and the real tokenizer, in front of an *instant* engine that
|
||||
//! returns a canned reply the moment it has the prompt. Everything this prints is therefore the cost of the control plane
|
||||
//! outside the engine, per stage; it says nothing about the engine.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run --release -p strata-control --example cp_replay -- TOKENIZER_DIR SESSION.json \
|
||||
//! [--sizes 20000,60000,120000,180000] [--turns 24] [--out results.json] [--json-response] [--verify]
|
||||
//! ```
|
||||
//!
|
||||
//! SESSION.json comes from `scripts/cp/synth_session.py` (a captured Codex session inverted into Responses items).
|
||||
//! For every size the history is cut at the round whose rendered prompt is closest to the size, then `--turns` consecutive
|
||||
//! rounds are replayed on one keep-alive connection: turn 0 is cold (nothing cached), turns 1.. are the steady state of a real
|
||||
//! session (each request is the previous history plus a few new items). Per request it reports, in milliseconds:
|
||||
//!
|
||||
//! * `pre_engine`: client finished sending -> the engine received the prompt (body read, parse, validation, template,
|
||||
//! tokenization, queue, prompt text for the engine);
|
||||
//! * `first_event`: engine's first text delta -> that delta's SSE event reached the client;
|
||||
//! * `tail`: engine's terminal event -> `response.completed` reached the client;
|
||||
//! * the stage table (`STRATA_STAGE_TRACE` spans, summed per request).
|
||||
//!
|
||||
//! `--verify` checks, for every request, that the prompt the engine received is byte-identical to the one produced by the
|
||||
//! reference path (`STRATA_REFERENCE_PROMPT=1` semantics are implemented in the library; here the harness compares the prompt
|
||||
//! text against `reference_prompt.json` when given and always records an FNV hash of every prompt and its token ids in the
|
||||
//! results so two runs of different builds can be diffed).
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::Write as _,
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use leleka_backend_api::{
|
||||
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
|
||||
GenerationRequest, GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig,
|
||||
SupportedModelTuple, Usage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{
|
||||
app::{AppState, router},
|
||||
backend_worker::{BackendWorkerConfig, run_backend_worker},
|
||||
stage_trace,
|
||||
tokenizer::Tokenizer,
|
||||
worker::{WorkerState, WorkerStatus},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
sync::{RwLock, mpsc, watch},
|
||||
};
|
||||
|
||||
/// Nanoseconds since the process epoch, shared by the engine thread and the client.
|
||||
pub fn now_ns() -> u64 {
|
||||
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
|
||||
EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct EngineMarks {
|
||||
pub received: AtomicU64,
|
||||
pub first_delta: AtomicU64,
|
||||
pub terminal: AtomicU64,
|
||||
pub prompt_bytes: AtomicU64,
|
||||
pub prompt_hash: AtomicU64,
|
||||
/// The last prompt text, kept only when `--verify` asks for it.
|
||||
pub last_prompt: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
static KEEP_PROMPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// How long the instant engine waits after taking the prompt before its first token (a real engine needs far longer; the
|
||||
/// wait lets the response's opening events leave first, as they do in production).
|
||||
static ENGINE_DELAY_MS: AtomicU64 = AtomicU64::new(20);
|
||||
/// Pause between two text deltas (a real engine delivers a few tokens per round, tens of ms apart; with no pause the host
|
||||
/// pipeline would be measured while it drains a backlog).
|
||||
static DELTA_GAP_US: AtomicU64 = AtomicU64::new(1000);
|
||||
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
let mut hash = 0xcbf29ce484222325u64;
|
||||
for &byte in bytes {
|
||||
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
fn reply_text() -> String {
|
||||
let reasoning = "The task needs a look at the current state of the repository before anything is changed. I will list the \
|
||||
files, check the git status and then open the module that the failing test exercises. The previous command output shows that the \
|
||||
test suite is red because the handler returns a 500 instead of a 404 for a missing customer, so the fix is probably in the \
|
||||
router or in the error mapping. Let me inspect both with one command and then decide on the patch. ";
|
||||
let mut text = reasoning.repeat(3);
|
||||
text.push_str(
|
||||
"\n</think>\n\n<tool_call>\n<function=exec_command>\n<parameter=cmd>\nls -la && git status --short && sed -n '1,120p' router.py\n</parameter>\n</function>\n</tool_call>",
|
||||
);
|
||||
text
|
||||
}
|
||||
|
||||
/// An engine with no latency: it records when it got the prompt and answers at once.
|
||||
pub struct InstantBackend {
|
||||
descriptor: leleka_backend_api::ModelDescriptor,
|
||||
marks: Arc<EngineMarks>,
|
||||
ready: bool,
|
||||
reply: Vec<String>,
|
||||
}
|
||||
|
||||
impl InstantBackend {
|
||||
pub fn new(marks: Arc<EngineMarks>) -> Self {
|
||||
let text = reply_text();
|
||||
let mut pieces = Vec::new();
|
||||
let mut current = String::new();
|
||||
for ch in text.chars() {
|
||||
current.push(ch);
|
||||
if current.len() >= 24 {
|
||||
pieces.push(std::mem::take(&mut current));
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
pieces.push(current);
|
||||
}
|
||||
Self {
|
||||
descriptor: leleka_backend_api::scripted::ScriptedEngine::fixture_descriptor(),
|
||||
marks,
|
||||
ready: false,
|
||||
reply: pieces,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for InstantBackend {
|
||||
fn identity(&self) -> BackendIdentity {
|
||||
BackendIdentity {
|
||||
name: "instant".into(),
|
||||
implementation_version: "bench".into(),
|
||||
api_version: leleka_backend_api::BACKEND_API_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> BackendCapabilities {
|
||||
BackendCapabilities {
|
||||
supported_models: if self.ready {
|
||||
vec![SupportedModelTuple {
|
||||
family: self.descriptor.family.clone(),
|
||||
architecture: self.descriptor.architecture.clone(),
|
||||
weight_format: self.descriptor.weight_format.clone(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
max_concurrent_generations: 1,
|
||||
supports_cancellation: true,
|
||||
supports_tool_call_streaming: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn load(
|
||||
&mut self,
|
||||
model: leleka_backend_api::ModelDescriptor,
|
||||
config: RuntimeConfig,
|
||||
) -> Result<LoadedModel, BackendError> {
|
||||
self.ready = true;
|
||||
Ok(LoadedModel {
|
||||
handle: "instant-handle".into(),
|
||||
descriptor: model,
|
||||
load_config_version: config.load_config_version,
|
||||
effective_mode: config.inference_mode,
|
||||
mode_identity_digest: format!("sha256:{}", "d".repeat(64)),
|
||||
})
|
||||
}
|
||||
|
||||
fn start_generation(
|
||||
&mut self,
|
||||
_model: &LoadedModel,
|
||||
request: GenerationRequest,
|
||||
) -> Result<GenerationStream, BackendError> {
|
||||
self.marks.received.store(now_ns(), Ordering::SeqCst);
|
||||
self.marks
|
||||
.prompt_bytes
|
||||
.store(request.prompt.len() as u64, Ordering::SeqCst);
|
||||
self.marks
|
||||
.prompt_hash
|
||||
.store(fnv(request.prompt.as_bytes()), Ordering::SeqCst);
|
||||
if KEEP_PROMPT.load(Ordering::Relaxed) {
|
||||
*self.marks.last_prompt.lock().unwrap() = Some(request.prompt.clone());
|
||||
}
|
||||
let (sink, stream) = GenerationSink::channel();
|
||||
let reply = self.reply.clone();
|
||||
let marks = Arc::clone(&self.marks);
|
||||
let input = (request.prompt.len() / 4) as u64;
|
||||
let delay = ENGINE_DELAY_MS.load(Ordering::Relaxed);
|
||||
let gap = DELTA_GAP_US.load(Ordering::Relaxed);
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(delay));
|
||||
for (at, piece) in reply.into_iter().enumerate() {
|
||||
if at == 0 {
|
||||
marks.first_delta.store(now_ns(), Ordering::SeqCst);
|
||||
} else if gap > 0 {
|
||||
std::thread::sleep(Duration::from_micros(gap));
|
||||
}
|
||||
if sink
|
||||
.emit(GenerationEvent::TextDelta { text: piece })
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
marks.terminal.store(now_ns(), Ordering::SeqCst);
|
||||
let _ = sink.complete(
|
||||
FinishReason::Stop,
|
||||
Usage {
|
||||
input_tokens: input,
|
||||
output_tokens: 420,
|
||||
reused_input_tokens: input * 97 / 100,
|
||||
},
|
||||
);
|
||||
});
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _request_id: &str) -> Result<(), BackendError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unload(&mut self, _model: LoadedModel) -> Result<(), BackendError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Stack {
|
||||
addr: std::net::SocketAddr,
|
||||
marks: Arc<EngineMarks>,
|
||||
stop: watch::Sender<bool>,
|
||||
worker: tokio::task::JoinHandle<()>,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
async fn start_stack<F>(tokenizer_dir: &Path, make: &F) -> Stack
|
||||
where
|
||||
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
|
||||
{
|
||||
let tokenizer = Arc::new(Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets"));
|
||||
let marks = Arc::new(EngineMarks::default());
|
||||
let backend = make(marks.clone()).await;
|
||||
let config = BackendWorkerConfig {
|
||||
tokenizer: tokenizer.clone(),
|
||||
model: leleka_backend_api::scripted::ScriptedEngine::fixture_descriptor(),
|
||||
runtime: RuntimeConfig {
|
||||
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
|
||||
inference_mode: InferenceMode::Native,
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: false,
|
||||
},
|
||||
max_context: 262_144,
|
||||
max_output_tokens: 32768,
|
||||
health_interval: Duration::from_secs(3600),
|
||||
generation_timeout: None,
|
||||
stall_timeout: None,
|
||||
attach_retry: Duration::from_millis(20),
|
||||
cancel_drain_timeout: Duration::from_secs(5),
|
||||
prefix_view: None,
|
||||
memory_view: None,
|
||||
};
|
||||
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
||||
let (stop, stop_rx) = watch::channel(false);
|
||||
let (requests, requests_rx) = mpsc::channel(8);
|
||||
let (control, control_rx) = mpsc::channel(8);
|
||||
let worker = tokio::spawn(run_backend_worker(
|
||||
backend,
|
||||
config,
|
||||
status.clone(),
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
));
|
||||
let state = AppState {
|
||||
model: Some("fixture".into()),
|
||||
worker: status.clone(),
|
||||
tokenizer: Some(tokenizer),
|
||||
generation: Some(requests),
|
||||
control: Some(control),
|
||||
..Default::default()
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let app = router(state);
|
||||
let server = tokio::spawn(async move {
|
||||
use axum::serve::ListenerExt as _;
|
||||
let listener = listener.tap_io(|tcp| {
|
||||
let _ = tcp.set_nodelay(true);
|
||||
});
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while status.read().await.state != WorkerState::Ready {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("worker ready");
|
||||
Stack {
|
||||
addr,
|
||||
marks,
|
||||
stop,
|
||||
worker,
|
||||
server,
|
||||
}
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
async fn stop(self) {
|
||||
let _ = self.stop.send(true);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), self.worker).await;
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
|
||||
struct Reply {
|
||||
status: u16,
|
||||
body_len: usize,
|
||||
t_sent: u64,
|
||||
t_first_byte: u64,
|
||||
t_created: u64,
|
||||
t_first_delta: u64,
|
||||
t_completed: u64,
|
||||
saw_function_call: bool,
|
||||
saw_completed: bool,
|
||||
sent_unix_ms: u128,
|
||||
done_unix_ms: u128,
|
||||
/// `input_tokens` / `cached_tokens` of the terminal event's usage, when present.
|
||||
usage: (u64, u64),
|
||||
terminal: String,
|
||||
}
|
||||
|
||||
/// `Authorization` value for `--live` runs (the key is read from a file and never printed).
|
||||
static AUTH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
static MODEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
static MAX_OUTPUT: AtomicU64 = AtomicU64::new(0);
|
||||
/// `--store`: send `store: true` (Codex sends false; the Responses API default is true).
|
||||
static STORE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
fn unix_ms() -> u128 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis())
|
||||
}
|
||||
|
||||
fn number_after(text: &[u8], key: &[u8]) -> u64 {
|
||||
find(text, 0, key)
|
||||
.map(|at| {
|
||||
text[at + key.len()..]
|
||||
.iter()
|
||||
.take_while(|b| b.is_ascii_digit())
|
||||
.fold(0u64, |n, b| n * 10 + u64::from(b - b'0'))
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn find(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
|
||||
let start = from.saturating_sub(needle.len());
|
||||
haystack[start.min(haystack.len())..]
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.map(|p| p + start)
|
||||
}
|
||||
|
||||
/// One request on an open keep-alive connection; timestamps are taken as the bytes arrive.
|
||||
async fn request(conn: &mut TcpStream, path: &str, body: &[u8], stream: bool) -> Reply {
|
||||
let auth = AUTH
|
||||
.get()
|
||||
.map(|value| format!("Authorization: Bearer {value}\r\n"))
|
||||
.unwrap_or_default();
|
||||
let head = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccept: {}\r\n{auth}\r\n",
|
||||
body.len(),
|
||||
if stream {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
}
|
||||
);
|
||||
conn.write_all(head.as_bytes()).await.unwrap();
|
||||
conn.write_all(body).await.unwrap();
|
||||
conn.flush().await.unwrap();
|
||||
let t_sent = now_ns();
|
||||
let sent_unix_ms = unix_ms();
|
||||
let mut t_created = 0;
|
||||
let mut data: Vec<u8> = Vec::with_capacity(64 * 1024);
|
||||
let mut buf = vec![0u8; 256 * 1024];
|
||||
let mut t_first_byte = 0;
|
||||
let mut t_first_delta = 0;
|
||||
let mut t_completed = 0;
|
||||
let mut header_end = None;
|
||||
let mut chunked = false;
|
||||
let mut content_length = None;
|
||||
let mut status = 0;
|
||||
let mut scanned = 0usize;
|
||||
loop {
|
||||
let n = conn.read(&mut buf).await.unwrap();
|
||||
assert!(n > 0, "connection closed mid-response");
|
||||
if t_first_byte == 0 {
|
||||
t_first_byte = now_ns();
|
||||
}
|
||||
let before = data.len();
|
||||
data.extend_from_slice(&buf[..n]);
|
||||
if header_end.is_none() {
|
||||
if let Some(end) = find(&data, 0, b"\r\n\r\n") {
|
||||
header_end = Some(end + 4);
|
||||
let head = String::from_utf8_lossy(&data[..end]).to_ascii_lowercase();
|
||||
status = head
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
chunked = head.contains("transfer-encoding: chunked");
|
||||
content_length = head
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("content-length: "))
|
||||
.and_then(|v| v.trim().parse::<usize>().ok());
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let start = header_end.unwrap();
|
||||
if t_first_delta == 0 {
|
||||
let from = scanned.max(start).min(before.max(start));
|
||||
if find(&data, from, b"response.reasoning_text.delta").is_some()
|
||||
|| find(&data, from, b"response.output_text.delta").is_some()
|
||||
|| find(&data, from, b"response.function_call_arguments.delta").is_some()
|
||||
{
|
||||
t_first_delta = now_ns();
|
||||
}
|
||||
}
|
||||
if t_created == 0 && find(&data, scanned.max(start), b"response.created").is_some() {
|
||||
t_created = now_ns();
|
||||
}
|
||||
if t_completed == 0
|
||||
&& (find(&data, scanned.max(start), b"response.completed").is_some()
|
||||
|| find(&data, scanned.max(start), b"response.incomplete").is_some()
|
||||
|| find(&data, scanned.max(start), b"response.failed").is_some())
|
||||
{
|
||||
t_completed = now_ns();
|
||||
}
|
||||
scanned = data.len();
|
||||
let finished = if chunked {
|
||||
data.ends_with(b"0\r\n\r\n")
|
||||
} else if let Some(length) = content_length {
|
||||
data.len() - start >= length
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if finished {
|
||||
let now = now_ns();
|
||||
if t_completed == 0 {
|
||||
t_completed = now;
|
||||
}
|
||||
if t_first_delta == 0 {
|
||||
t_first_delta = t_completed;
|
||||
}
|
||||
let text = &data[start..];
|
||||
let terminal = [
|
||||
"response.completed",
|
||||
"response.incomplete",
|
||||
"response.failed",
|
||||
]
|
||||
.into_iter()
|
||||
.find(|name| find(text, 0, name.as_bytes()).is_some())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let tail = &text[text.len().saturating_sub(4096)..];
|
||||
return Reply {
|
||||
status,
|
||||
body_len: text.len(),
|
||||
t_sent,
|
||||
t_first_byte,
|
||||
t_created,
|
||||
t_first_delta,
|
||||
t_completed,
|
||||
saw_function_call: find(text, 0, b"\"type\":\"function_call\"").is_some(),
|
||||
saw_completed: terminal == "response.completed"
|
||||
|| find(text, 0, b"\"status\":\"completed\"").is_some(),
|
||||
sent_unix_ms,
|
||||
done_unix_ms: unix_ms(),
|
||||
usage: (
|
||||
number_after(tail, b"\"input_tokens\":"),
|
||||
number_after(tail, b"\"cached_tokens\":"),
|
||||
),
|
||||
terminal,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percentile(values: &[f64], q: f64) -> f64 {
|
||||
if values.is_empty() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let rank = (q * (sorted.len() - 1) as f64).round() as usize;
|
||||
sorted[rank]
|
||||
}
|
||||
|
||||
struct Session {
|
||||
instructions: String,
|
||||
tools: Vec<Value>,
|
||||
items: Vec<Value>,
|
||||
rounds: Vec<usize>,
|
||||
capture_items: usize,
|
||||
capture_ids: Vec<u32>,
|
||||
}
|
||||
|
||||
fn load_session(path: &str) -> Session {
|
||||
let doc: Value = serde_json::from_slice(&std::fs::read(path).expect("session file")).unwrap();
|
||||
Session {
|
||||
instructions: doc["instructions"].as_str().unwrap().to_owned(),
|
||||
tools: doc["tools"].as_array().unwrap().clone(),
|
||||
items: doc["items"].as_array().unwrap().clone(),
|
||||
rounds: doc["rounds"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap() as usize)
|
||||
.collect(),
|
||||
capture_items: doc["capture_items"].as_u64().unwrap_or(0) as usize,
|
||||
capture_ids: doc["capture_prompt_ids"]
|
||||
.as_array()
|
||||
.map(|ids| ids.iter().map(|v| v.as_u64().unwrap() as u32).collect())
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The request Codex would send at round `round` (history = the items before it).
|
||||
fn body_at(session: &Session, round: usize, stream: bool) -> Vec<u8> {
|
||||
let end = session.rounds[round];
|
||||
let mut body = json!({
|
||||
"model": MODEL.get().map_or("fixture", String::as_str),
|
||||
"instructions": session.instructions,
|
||||
"input": &session.items[..end],
|
||||
"tools": session.tools,
|
||||
"tool_choice": "auto",
|
||||
"parallel_tool_calls": true,
|
||||
"reasoning": {"effort": "medium", "summary": "auto"},
|
||||
"store": STORE.load(Ordering::Relaxed),
|
||||
"stream": stream,
|
||||
"include": ["reasoning.encrypted_content"],
|
||||
"prompt_cache_key": "019a0000-0000-7000-8000-00000000e2e0",
|
||||
"text": {"verbosity": "low"},
|
||||
});
|
||||
let limit = MAX_OUTPUT.load(Ordering::Relaxed);
|
||||
if limit > 0 {
|
||||
body["max_output_tokens"] = json!(limit);
|
||||
}
|
||||
serde_json::to_vec(&body).unwrap()
|
||||
}
|
||||
|
||||
async fn token_count(conn: &mut TcpStream, session: &Session, round: usize) -> usize {
|
||||
let mut body: Value = serde_json::from_slice(&body_at(session, round, false)).unwrap();
|
||||
for key in ["stream", "store", "prompt_cache_key", "include"] {
|
||||
body.as_object_mut().unwrap().remove(key);
|
||||
}
|
||||
let bytes = serde_json::to_vec(&body).unwrap();
|
||||
// reuse the sender, response is small JSON
|
||||
let reply = request_raw(conn, "/v1/responses/input_tokens", &bytes).await;
|
||||
let value: Value =
|
||||
serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
|
||||
value["input_tokens"].as_u64().unwrap() as usize
|
||||
}
|
||||
|
||||
async fn request_raw(conn: &mut TcpStream, path: &str, body: &[u8]) -> String {
|
||||
let auth = AUTH
|
||||
.get()
|
||||
.map(|value| format!("Authorization: Bearer {value}\r\n"))
|
||||
.unwrap_or_default();
|
||||
let head = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{auth}\r\n",
|
||||
body.len()
|
||||
);
|
||||
conn.write_all(head.as_bytes()).await.unwrap();
|
||||
conn.write_all(body).await.unwrap();
|
||||
let mut data = Vec::new();
|
||||
let mut buf = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = conn.read(&mut buf).await.unwrap();
|
||||
assert!(n > 0);
|
||||
data.extend_from_slice(&buf[..n]);
|
||||
if let Some(end) = find(&data, 0, b"\r\n\r\n") {
|
||||
let head = String::from_utf8_lossy(&data[..end]).to_ascii_lowercase();
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("content-length: "))
|
||||
.and_then(|v| v.trim().parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
if data.len() >= end + 4 + length {
|
||||
return String::from_utf8_lossy(&data[end + 4..end + 4 + length]).into_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `--live URL[,URL2]`: the same requests against servers that are already running (a real engine behind them), alternating between
|
||||
/// the URLs turn by turn so that both see the same conversation and the engine the same sequence of prompts. One JSON line per turn on
|
||||
/// stdout (`LIVE {...}`); the join with the servers' `STRATA_STAGE_TRACE=log` lines is done by scripts/cp/live_report.py.
|
||||
///
|
||||
/// `--key-file F --model M --size N | --first-round R --turns T --max-output-tokens K --names a,b`
|
||||
async fn live(targets: &str, session: Session, args: &[String]) {
|
||||
let key = std::fs::read_to_string(arg(args, "--key-file").expect("--key-file"))
|
||||
.expect("key file")
|
||||
.trim()
|
||||
.to_owned();
|
||||
AUTH.set(key).ok();
|
||||
MODEL
|
||||
.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into()))
|
||||
.ok();
|
||||
MAX_OUTPUT.store(
|
||||
arg(args, "--max-output-tokens")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(48),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
let urls: Vec<String> = targets.split(',').map(str::to_owned).collect();
|
||||
let names: Vec<String> = arg(args, "--names")
|
||||
.map(|v| v.split(',').map(str::to_owned).collect())
|
||||
.unwrap_or_else(|| (0..urls.len()).map(|i| format!("arm{i}")).collect());
|
||||
let turns: usize = arg(args, "--turns")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(24);
|
||||
let mut conns = Vec::new();
|
||||
for url in &urls {
|
||||
let address = url.trim_start_matches("http://").trim_end_matches('/');
|
||||
let conn = TcpStream::connect(address).await.expect("connect");
|
||||
conn.set_nodelay(true).unwrap();
|
||||
conns.push(conn);
|
||||
}
|
||||
let first = match arg(args, "--first-round").and_then(|v| v.parse::<usize>().ok()) {
|
||||
Some(round) => round,
|
||||
None => {
|
||||
let size: usize = arg(args, "--size")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(60000);
|
||||
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
|
||||
while low < high {
|
||||
let mid = (low + high) / 2;
|
||||
if token_count(&mut conns[0], &session, mid).await < size {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
low
|
||||
}
|
||||
};
|
||||
let first = first.min(session.rounds.len().saturating_sub(turns));
|
||||
eprintln!("live: {turns} turns from round {first}, arms {names:?}");
|
||||
for turn in 0..turns {
|
||||
let round = first + turn;
|
||||
if round >= session.rounds.len() {
|
||||
break;
|
||||
}
|
||||
let arm = turn % urls.len();
|
||||
let body = body_at(&session, round, true);
|
||||
let reply = request(&mut conns[arm], "/v1/responses", &body, true).await;
|
||||
let ms = |a: u64, b: u64| b.saturating_sub(a) as f64 / 1e6;
|
||||
println!(
|
||||
"LIVE {}",
|
||||
json!({
|
||||
"turn": turn, "round": round, "arm": names[arm], "status": reply.status, "terminal": reply.terminal,
|
||||
"body_bytes": body.len(), "sent_unix_ms": reply.sent_unix_ms as u64, "done_unix_ms": reply.done_unix_ms as u64,
|
||||
"first_byte_ms": ms(reply.t_sent, reply.t_first_byte), "created_ms": ms(reply.t_sent, reply.t_created),
|
||||
"ttft_ms": ms(reply.t_sent, reply.t_first_delta), "total_ms": ms(reply.t_sent, reply.t_completed),
|
||||
"input_tokens": reply.usage.0, "cached_tokens": reply.usage.1,
|
||||
})
|
||||
);
|
||||
std::io::stdout().flush().ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Equivalence on real data. For every round of the session (`--verify-step n` takes every n-th) the prompt the engine received is
|
||||
/// tokenized by the production path and by the original implementation (`encode_reference`) and must give the same ids, the ids
|
||||
/// must decode back to the text, `/v1/responses/input_tokens` must count them, and the round whose history is exactly what the
|
||||
/// captured Codex request held must reproduce the captured prompt ids (the ids the real engine prefilled). Prints one
|
||||
/// `PROMPT round fnv ids_fnv` line per round so two builds can be diffed.
|
||||
async fn verify<F>(tokenizer_dir: &Path, session: &Session, make: &F, args: &[String])
|
||||
where
|
||||
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
|
||||
{
|
||||
KEEP_PROMPT.store(true, Ordering::Relaxed);
|
||||
let reference = Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets");
|
||||
let step: usize = arg(args, "--verify-step")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(1);
|
||||
let stack = start_stack(tokenizer_dir, make).await;
|
||||
let mut conn = TcpStream::connect(stack.addr).await.unwrap();
|
||||
conn.set_nodelay(true).unwrap();
|
||||
let mut checked = 0;
|
||||
let mut captured = false;
|
||||
for round in 0..session.rounds.len() {
|
||||
if round % step != 0 && session.rounds[round] != session.capture_items {
|
||||
continue;
|
||||
}
|
||||
let counted = token_count(&mut conn, session, round).await;
|
||||
let body = body_at(session, round, false);
|
||||
let reply = request(&mut conn, "/v1/responses", &body, false).await;
|
||||
assert_eq!(reply.status, 200, "round {round}");
|
||||
let prompt = stack
|
||||
.marks
|
||||
.last_prompt
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("prompt");
|
||||
let fast = reference.encode(&prompt, true).unwrap();
|
||||
let slow = reference.encode_reference(&prompt, true).unwrap();
|
||||
assert_eq!(
|
||||
fast, slow,
|
||||
"round {round}: fast path ids differ from the reference"
|
||||
);
|
||||
assert_eq!(
|
||||
fast.len(),
|
||||
counted,
|
||||
"round {round}: input_tokens differs from the ids"
|
||||
);
|
||||
assert!(
|
||||
reference.decodes_to(&fast, prompt.as_bytes()),
|
||||
"round {round}: ids do not decode to the prompt"
|
||||
);
|
||||
let mut hash = 0xcbf29ce484222325u64;
|
||||
for id in &fast {
|
||||
hash = (hash ^ u64::from(*id)).wrapping_mul(0x100000001b3);
|
||||
}
|
||||
println!(
|
||||
"PROMPT round={round} tokens={} prompt_fnv={:016x} ids_fnv={hash:016x}",
|
||||
fast.len(),
|
||||
fnv(prompt.as_bytes())
|
||||
);
|
||||
if session.rounds[round] == session.capture_items && !session.capture_ids.is_empty() {
|
||||
if fast != session.capture_ids {
|
||||
let at = fast
|
||||
.iter()
|
||||
.zip(&session.capture_ids)
|
||||
.position(|(a, b)| a != b)
|
||||
.unwrap_or(fast.len().min(session.capture_ids.len()));
|
||||
let window = |ids: &[u32]| {
|
||||
let (from, to) = (at.saturating_sub(12), (at + 12).min(ids.len()));
|
||||
reference.decode(&ids[from..to]).unwrap_or_default()
|
||||
};
|
||||
panic!(
|
||||
"round {round}: differs from the captured engine prompt at token {at} (mine {} tokens, capture {}):
|
||||
mine: {:?}
|
||||
capture: {:?}",
|
||||
fast.len(),
|
||||
session.capture_ids.len(),
|
||||
window(&fast),
|
||||
window(&session.capture_ids)
|
||||
);
|
||||
}
|
||||
captured = true;
|
||||
println!(
|
||||
"CAPTURE round={round} tokens={} identical to the captured prompt ids",
|
||||
fast.len()
|
||||
);
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
stack.stop().await;
|
||||
println!("VERIFY ok rounds={checked} capture_checked={captured}");
|
||||
}
|
||||
|
||||
fn arg(args: &[String], name: &str) -> Option<String> {
|
||||
args.iter()
|
||||
.position(|a| a == name)
|
||||
.and_then(|i| args.get(i + 1).cloned())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
run(std::env::args().collect(), async |marks| {
|
||||
Box::new(InstantBackend::new(marks)) as Box<dyn Backend>
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The replay with the engine `make` builds: the instant engine in process, or (desktop-core's `cp_replay_grpc`) the same engine
|
||||
/// behind the real gRPC runtime server and `GrpcBackend`.
|
||||
pub async fn run<F>(args: Vec<String>, make: F)
|
||||
where
|
||||
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
|
||||
{
|
||||
if args.len() < 3 {
|
||||
eprintln!(
|
||||
"usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]"
|
||||
);
|
||||
std::process::exit(2);
|
||||
}
|
||||
stage_trace::enable();
|
||||
let tokenizer_dir = Path::new(&args[1]).to_owned();
|
||||
let session = load_session(&args[2]);
|
||||
let sizes: Vec<usize> = arg(&args, "--sizes")
|
||||
.unwrap_or_else(|| "20000,60000,120000,180000".into())
|
||||
.split(',')
|
||||
.map(|s| s.parse().unwrap())
|
||||
.collect();
|
||||
let turns: usize = arg(&args, "--turns")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(24);
|
||||
let stream = !args.iter().any(|a| a == "--json-response");
|
||||
let label = arg(&args, "--label").unwrap_or_else(|| "run".into());
|
||||
if args.iter().any(|a| a == "--store") {
|
||||
STORE.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(delay) = arg(&args, "--engine-delay-ms").and_then(|v| v.parse().ok()) {
|
||||
ENGINE_DELAY_MS.store(delay, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(gap) = arg(&args, "--delta-gap-us").and_then(|v| v.parse().ok()) {
|
||||
DELTA_GAP_US.store(gap, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(targets) = arg(&args, "--live") {
|
||||
live(&targets, session, &args).await;
|
||||
return;
|
||||
}
|
||||
if args.iter().any(|a| a == "--verify") {
|
||||
verify(&tokenizer_dir, &session, &make, &args).await;
|
||||
return;
|
||||
}
|
||||
let mut results = Vec::new();
|
||||
for &size in &sizes {
|
||||
let stack = start_stack(&tokenizer_dir, &make).await;
|
||||
let mut conn = TcpStream::connect(stack.addr).await.unwrap();
|
||||
conn.set_nodelay(true).unwrap();
|
||||
// pick the round whose prompt is closest to `size` tokens (counted by the server itself)
|
||||
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
|
||||
while low < high {
|
||||
let mid = (low + high) / 2;
|
||||
if token_count(&mut conn, &session, mid).await < size {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
let first = low.min(session.rounds.len().saturating_sub(turns));
|
||||
let _ = stage_trace::drain();
|
||||
// a new stack (cold caches) for the measured sequence
|
||||
stack.stop().await;
|
||||
let stack = start_stack(&tokenizer_dir, &make).await;
|
||||
let mut conn = TcpStream::connect(stack.addr).await.unwrap();
|
||||
conn.set_nodelay(true).unwrap();
|
||||
let mut rows: Vec<Value> = Vec::new();
|
||||
for turn in 0..turns {
|
||||
let round = first + turn;
|
||||
if round >= session.rounds.len() {
|
||||
break;
|
||||
}
|
||||
let body = body_at(&session, round, stream);
|
||||
let reply = request(&mut conn, "/v1/responses", &body, stream).await;
|
||||
let marks = &stack.marks;
|
||||
let received = marks.received.load(Ordering::SeqCst);
|
||||
let first_delta = marks.first_delta.load(Ordering::SeqCst);
|
||||
let terminal = marks.terminal.load(Ordering::SeqCst);
|
||||
assert_eq!(reply.status, 200, "turn {turn}");
|
||||
assert!(
|
||||
reply.saw_completed && reply.saw_function_call,
|
||||
"turn {turn}: incomplete reply"
|
||||
);
|
||||
let stages = stage_trace::drain();
|
||||
let ms = |ns: u64| ns as f64 / 1e6;
|
||||
let mut stage_json = serde_json::Map::new();
|
||||
for (name, (total, count)) in &stages {
|
||||
stage_json.insert((*name).into(), json!({"ms": total, "n": count}));
|
||||
}
|
||||
rows.push(json!({
|
||||
"turn": turn,
|
||||
"round": round,
|
||||
"body_bytes": body.len(),
|
||||
"prompt_bytes": marks.prompt_bytes.load(Ordering::SeqCst),
|
||||
"prompt_fnv": format!("{:016x}", marks.prompt_hash.load(Ordering::SeqCst)),
|
||||
"pre_engine_ms": ms(received.saturating_sub(reply.t_sent)),
|
||||
"first_event_ms": ms(reply.t_first_delta.saturating_sub(first_delta)),
|
||||
"tail_ms": ms(reply.t_completed.saturating_sub(terminal)),
|
||||
"wall_ms": ms(reply.t_completed.saturating_sub(reply.t_sent)),
|
||||
"first_byte_ms": ms(reply.t_first_byte.saturating_sub(reply.t_sent)),
|
||||
"response_bytes": reply.body_len,
|
||||
"stages": stage_json,
|
||||
}));
|
||||
}
|
||||
stack.stop().await;
|
||||
// summaries
|
||||
let warm: Vec<&Value> = rows.iter().skip(1).collect();
|
||||
let col = |key: &str, set: &[&Value]| -> Vec<f64> {
|
||||
set.iter().map(|r| r[key].as_f64().unwrap()).collect()
|
||||
};
|
||||
let mut stage_names: BTreeMap<String, Vec<f64>> = BTreeMap::new();
|
||||
for row in &warm {
|
||||
for (name, value) in row["stages"].as_object().unwrap() {
|
||||
stage_names
|
||||
.entry(name.clone())
|
||||
.or_default()
|
||||
.push(value["ms"].as_f64().unwrap());
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"== {label} size~{size} tokens (rounds {first}..{}) body {:.0} KB prompt {:.0} KB, {} warm turns",
|
||||
first + rows.len() - 1,
|
||||
rows[0]["body_bytes"].as_f64().unwrap() / 1024.0,
|
||||
rows[0]["prompt_bytes"].as_f64().unwrap() / 1024.0,
|
||||
warm.len()
|
||||
);
|
||||
println!(
|
||||
"{:<22} {:>9} {:>9} {:>9}",
|
||||
"metric (ms)", "cold", "p50", "p95"
|
||||
);
|
||||
for key in ["pre_engine_ms", "first_event_ms", "tail_ms", "wall_ms"] {
|
||||
println!(
|
||||
"{:<22} {:>9.2} {:>9.2} {:>9.2}",
|
||||
key,
|
||||
rows[0][key].as_f64().unwrap(),
|
||||
percentile(&col(key, &warm), 0.5),
|
||||
percentile(&col(key, &warm), 0.95)
|
||||
);
|
||||
}
|
||||
for (name, values) in &stage_names {
|
||||
println!(
|
||||
" stage {:<18} {:>9.2} {:>9.2} {:>9.2}",
|
||||
name,
|
||||
rows[0]["stages"]
|
||||
.get(name)
|
||||
.map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
|
||||
percentile(values, 0.5),
|
||||
percentile(values, 0.95)
|
||||
);
|
||||
}
|
||||
std::io::stdout().flush().ok();
|
||||
results.push(json!({"size": size, "first_round": first, "rows": rows}));
|
||||
}
|
||||
if let Some(out) = arg(&args, "--out") {
|
||||
let doc = json!({"label": label, "results": results});
|
||||
let guard = Mutex::new(());
|
||||
let _g = guard.lock().unwrap();
|
||||
std::fs::write(out, serde_json::to_vec_pretty(&doc).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/v1/models/{id}", get(crate::models_api::retrieve))
|
||||
.route(
|
||||
"/v1/responses",
|
||||
post(responses::create).layer(middleware::from_fn_with_state(
|
||||
post(responses::create_route).layer(middleware::from_fn_with_state(
|
||||
state.lifecycle.clone(),
|
||||
crate::lifecycle::admit,
|
||||
)),
|
||||
|
||||
@@ -186,11 +186,22 @@ async fn prepare(
|
||||
}
|
||||
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
|
||||
.map_err(|error| format!("sampling: {error}"))?;
|
||||
let tokenizer = Arc::clone(&config.tokenizer);
|
||||
let ids = request.token_ids.clone();
|
||||
let prompt = tokio::task::spawn_blocking(move || prompt_text(&tokenizer, &ids))
|
||||
.await
|
||||
.map_err(|error| error.to_string())??;
|
||||
let prompt_span = crate::stage_trace::span("worker_prompt_text");
|
||||
let prompt = match &request.prompt_text {
|
||||
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still decode to it
|
||||
// (a table walk over the ids, well under a millisecond for a whole conversation).
|
||||
Some(text) if config.tokenizer.decodes_to(&request.token_ids, text.as_bytes()) => {
|
||||
text.to_string()
|
||||
}
|
||||
_ => {
|
||||
let tokenizer = Arc::clone(&config.tokenizer);
|
||||
let ids = request.token_ids.clone();
|
||||
tokio::task::spawn_blocking(move || prompt_text(&tokenizer, &ids))
|
||||
.await
|
||||
.map_err(|error| error.to_string())??
|
||||
}
|
||||
};
|
||||
drop(prompt_span);
|
||||
Ok(api::GenerationRequest {
|
||||
request_id: request_id(),
|
||||
prompt,
|
||||
@@ -396,20 +407,21 @@ async fn serve_one(
|
||||
let id = request.request_id.clone();
|
||||
let counted_input = u64::try_from(command.request.token_ids.len()).unwrap_or(u64::MAX);
|
||||
status.write().await.metrics.start();
|
||||
crate::elog!(
|
||||
"generation start: t_unix_ms={} prompt_tokens={} max_new={}",
|
||||
crate::worker::unix_ms(),
|
||||
counted_input,
|
||||
request.max_output_tokens
|
||||
);
|
||||
// The line is written once the engine has the request (its time is taken now), so a slow log sink cannot delay the start.
|
||||
let start_ms = crate::worker::unix_ms();
|
||||
let max_new = request.max_output_tokens;
|
||||
let started = Instant::now();
|
||||
let start = {
|
||||
let _span = crate::stage_trace::span("engine_start");
|
||||
let model = loaded.clone();
|
||||
on_engine(engine, move |backend| {
|
||||
backend.start_generation(&model, request)
|
||||
})
|
||||
.await
|
||||
};
|
||||
crate::elog!(
|
||||
"generation start: t_unix_ms={start_ms} prompt_tokens={counted_input} max_new={max_new}"
|
||||
);
|
||||
let stream = match start {
|
||||
Ok(Ok(stream)) => stream,
|
||||
Ok(Err(error)) => {
|
||||
@@ -532,7 +544,10 @@ async fn serve_one(
|
||||
first_delta.get_or_insert_with(Instant::now);
|
||||
let piece = stops.push(&text);
|
||||
if !piece.emit.is_empty() {
|
||||
match text_tokens(&config.tokenizer, &piece.emit) {
|
||||
let retokenize = crate::stage_trace::time("delta_retokenize", || {
|
||||
text_tokens(&config.tokenizer, &piece.emit)
|
||||
});
|
||||
match retokenize {
|
||||
Ok(ids) => {
|
||||
for id in ids {
|
||||
delivered += 1;
|
||||
|
||||
@@ -87,6 +87,8 @@ pub mod sampling;
|
||||
|
||||
pub mod server_api;
|
||||
|
||||
pub mod stage_trace;
|
||||
|
||||
pub mod settings;
|
||||
|
||||
pub mod mcp;
|
||||
|
||||
@@ -1032,6 +1032,11 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
|
||||
let state_vision = state.vision.clone();
|
||||
let lifecycle = state.lifecycle.clone();
|
||||
let shutdown_grace = config.shutdown_grace;
|
||||
// TCP_NODELAY: SSE events and small responses must not wait for the peer's delayed ACK (Nagle's algorithm).
|
||||
use axum::serve::ListenerExt as _;
|
||||
let listener = listener.tap_io(|tcp| {
|
||||
let _ = tcp.set_nodelay(true);
|
||||
});
|
||||
let result = axum::serve(listener, app::router(state))
|
||||
.with_graceful_shutdown(async move {
|
||||
shutdown_signal().await;
|
||||
|
||||
@@ -569,6 +569,97 @@ pub fn render_with_tools(
|
||||
render_with_images(messages, effort, tools).map(|(prompt, _)| prompt)
|
||||
}
|
||||
|
||||
/// `STRATA_REFERENCE_RENDER=1` sends every prompt through the Jinja template (no native fast path).
|
||||
fn reference_render() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("STRATA_REFERENCE_RENDER").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// The prompt of a text-only conversation without running the Jinja template over the history.
|
||||
///
|
||||
/// For the pinned template a message after the leading system/developer ones renders to text that depends on that message
|
||||
/// alone, because `preserve_thinking` is never set (an assistant turn always keeps its `<think>` block):
|
||||
///
|
||||
/// ```text
|
||||
/// user: <|im_start|>user\n{content|trim}<|im_end|>\n
|
||||
/// assistant: <|im_start|>assistant\n<think>\n{reasoning|trim}\n</think>\n\n{content|trim}<|im_end|>\n
|
||||
/// ```
|
||||
///
|
||||
/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the leading
|
||||
/// system messages, the tools and the effort, so the template renders just that part, with the history left out. The
|
||||
/// generation prompt is the template's own closing lines. The result is the template's output byte for byte
|
||||
/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template.
|
||||
fn render_native(messages: &[Message<'_>], effort: Effort, tools: &[Json]) -> Result<String, String> {
|
||||
let leading = messages
|
||||
.iter()
|
||||
.take_while(|message| matches!(message.role, Role::System | Role::Developer))
|
||||
.count();
|
||||
let object = |message: &Message<'_>| {
|
||||
let mut fields = vec![
|
||||
("role".to_owned(), Json::str(message.role.name())),
|
||||
("content".to_owned(), Json::str(message.content)),
|
||||
];
|
||||
if let Some(reasoning) = message.reasoning {
|
||||
fields.push(("reasoning_content".to_owned(), Json::str(reasoning)));
|
||||
}
|
||||
Json::Object(fields)
|
||||
};
|
||||
// The template refuses an empty message list, so a conversation without system messages gets a placeholder user turn whose
|
||||
// exact output is cut off again.
|
||||
const PLACEHOLDER: &str = "<|im_start|>user\n<|im_end|>\n";
|
||||
let head: Vec<Json> = if leading == 0 {
|
||||
vec![Json::object([("role", Json::str("user")), ("content", Json::str(""))])]
|
||||
} else {
|
||||
messages[..leading].iter().map(object).collect()
|
||||
};
|
||||
let mut prompt = pinned().render(&ChatInput {
|
||||
messages: &head,
|
||||
tools: (!tools.is_empty()).then_some(tools),
|
||||
add_generation_prompt: false,
|
||||
kwargs: effort.kwargs(),
|
||||
})?;
|
||||
if leading == 0 {
|
||||
prompt = prompt
|
||||
.strip_suffix(PLACEHOLDER)
|
||||
.ok_or("the chat template changed its output for an empty user turn")?
|
||||
.to_owned();
|
||||
}
|
||||
let rest = &messages[leading..];
|
||||
prompt.reserve(
|
||||
rest.iter()
|
||||
.map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64)
|
||||
.sum::<usize>()
|
||||
+ 64,
|
||||
);
|
||||
for message in rest {
|
||||
let content = message.content.trim_matches(py_space);
|
||||
match message.role {
|
||||
Role::User => {
|
||||
prompt.push_str("<|im_start|>user\n");
|
||||
prompt.push_str(content);
|
||||
prompt.push_str("<|im_end|>\n");
|
||||
}
|
||||
Role::Assistant => {
|
||||
prompt.push_str("<|im_start|>assistant\n<think>\n");
|
||||
prompt.push_str(message.reasoning.unwrap_or("").trim_matches(py_space));
|
||||
prompt.push_str("\n</think>\n\n");
|
||||
prompt.push_str(content);
|
||||
prompt.push_str("<|im_end|>\n");
|
||||
}
|
||||
Role::System | Role::Developer => {
|
||||
return Err("System message must be at the beginning.".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
prompt.push_str("<|im_start|>assistant\n");
|
||||
prompt.push_str(if matches!(effort, Effort::None) {
|
||||
"<think>\n\n</think>\n\n"
|
||||
} else {
|
||||
"<think>\n"
|
||||
});
|
||||
Ok(prompt)
|
||||
}
|
||||
|
||||
/// [`render_with_tools`] and the sources of the pictures the prompt contains, in prompt order (`images_of`).
|
||||
pub fn render_with_images(
|
||||
messages: &[Message<'_>],
|
||||
@@ -595,6 +686,19 @@ pub fn render_with_images(
|
||||
{
|
||||
return Err("generation needs a final user message".into());
|
||||
}
|
||||
if !reference_render() && messages.iter().all(|message| message.parts.is_none()) {
|
||||
let tools = tools.iter().map(chat_tool).collect::<Result<Vec<_>, _>>()?;
|
||||
return render_native(messages, effort, &tools).map(|prompt| (prompt, Vec::new()));
|
||||
}
|
||||
render_via_template(messages, effort, tools)
|
||||
}
|
||||
|
||||
/// The whole conversation through the Jinja template (the reference the native renderer is tested against).
|
||||
fn render_via_template(
|
||||
messages: &[Message<'_>],
|
||||
effort: Effort,
|
||||
tools: &[Plain],
|
||||
) -> Result<(String, Vec<String>), String> {
|
||||
let chat: Vec<Json> = messages
|
||||
.iter()
|
||||
.map(|message| {
|
||||
@@ -744,6 +848,66 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Random text-only conversations (white space of every kind at the edges of contents, empty contents and reasoning,
|
||||
/// template-looking text, special-token text, non-ASCII), all efforts, with and without system messages and tools:
|
||||
/// the native renderer and the template produce the same bytes (or the same error).
|
||||
#[test]
|
||||
fn native_render_equals_the_template() {
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % n as u64) as usize
|
||||
}
|
||||
}
|
||||
const ATOMS: &[&str] = &[
|
||||
"", " ", " ", "\n", "\n\n", "\t", "\r\n", "\u{a0}", "\u{2003}", "\u{1c}", "\u{85}", "\u{200b}", "word", "a b",
|
||||
"{{ x }}", "{% if %}", "{# c #}", "<|im_start|>", "<|im_end|>", "<think>", "</think>", "<tool_call>", "<tool_response>",
|
||||
"\u{fc}\u{4e2d}\u{6587}\u{1f600}", "\"quoted\"", "back\\slash", "0", "-1.5e10", "null", "[1, 2]", "{\"a\": 1}",
|
||||
];
|
||||
let tools_pool = [
|
||||
json!({"type":"function","name":"exec","description":"Run a command","parameters":{"type":"object","properties":{"cmd":{"type":"string"},"n":{"type":"number"}},"required":["cmd"]}}),
|
||||
json!({"type":"function","name":"plan","parameters":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"step":{"type":"string"}}}}}},"strict":false}),
|
||||
json!({"type":"function","name":"bare"}),
|
||||
];
|
||||
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
|
||||
let text = |rng: &mut Rng| {
|
||||
(0..rng.below(5))
|
||||
.map(|_| ATOMS[rng.below(ATOMS.len())])
|
||||
.collect::<String>()
|
||||
};
|
||||
for case in 0..4000 {
|
||||
let mut storage: Vec<(Role, String, Option<String>)> = Vec::new();
|
||||
for _ in 0..rng.below(3) {
|
||||
let role = if rng.below(2) == 0 { Role::System } else { Role::Developer };
|
||||
storage.push((role, text(&mut rng), None));
|
||||
}
|
||||
for _ in 0..rng.below(5) {
|
||||
let role = if rng.below(2) == 0 { Role::User } else { Role::Assistant };
|
||||
let reasoning = (rng.below(2) == 0).then(|| text(&mut rng));
|
||||
storage.push((role, text(&mut rng), if role == Role::Assistant { reasoning } else { None }));
|
||||
}
|
||||
storage.push((Role::User, text(&mut rng), None));
|
||||
let messages: Vec<Message<'_>> = storage
|
||||
.iter()
|
||||
.map(|(role, content, reasoning)| Message {
|
||||
role: *role,
|
||||
content,
|
||||
reasoning: reasoning.as_deref(),
|
||||
parts: None,
|
||||
})
|
||||
.collect();
|
||||
let tools: Vec<Plain> = tools_pool.iter().take(rng.below(4)).cloned().collect();
|
||||
let effort = [Effort::None, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh][rng.below(5)];
|
||||
let reference = render_via_template(&messages, effort, &tools).map(|(prompt, _)| prompt);
|
||||
let chat_tools = tools.iter().map(chat_tool).collect::<Result<Vec<_>, _>>().unwrap();
|
||||
let native = render_native(&messages, effort, &chat_tools);
|
||||
assert_eq!(native, reference, "case {case}: {storage:?} {effort:?} tools {}", tools.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flattened_tool_continuation_matches_the_golden_bytes() {
|
||||
let case = golden()
|
||||
|
||||
@@ -811,9 +811,7 @@ impl CreateRequest {
|
||||
));
|
||||
}
|
||||
if let Some(parameters) = tool.get("parameters")
|
||||
&& (parameters.get("type").and_then(Value::as_str) != Some("object")
|
||||
|| reject_remote_refs(parameters).is_err()
|
||||
|| jsonschema::validator_for(parameters).is_err())
|
||||
&& !tool_schema_accepted(parameters)
|
||||
{
|
||||
return Err((
|
||||
"tools",
|
||||
@@ -825,6 +823,21 @@ impl CreateRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Json<Value>` with the body read and parse timed as the stage `http_body_json`; same rejections.
|
||||
pub struct TracedJson(pub Json<Value>);
|
||||
|
||||
impl<S: Send + Sync> axum::extract::FromRequest<S> for TracedJson {
|
||||
type Rejection = JsonRejection;
|
||||
|
||||
async fn from_request(
|
||||
request: axum::extract::Request,
|
||||
state: &S,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let _span = crate::stage_trace::span("http_body_json");
|
||||
Json::<Value>::from_request(request, state).await.map(Self)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_request(
|
||||
state: &AppState,
|
||||
body: Result<Json<Value>, JsonRejection>,
|
||||
@@ -841,6 +854,7 @@ fn parse_request(
|
||||
)));
|
||||
}
|
||||
};
|
||||
let decode = crate::stage_trace::span("request_decode");
|
||||
let request: CreateRequest = match serde_json::from_value(body) {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
@@ -853,7 +867,9 @@ fn parse_request(
|
||||
)));
|
||||
}
|
||||
};
|
||||
if let Err((param, message)) = request.validate() {
|
||||
drop(decode);
|
||||
let validated = crate::stage_trace::time("request_validate", || request.validate());
|
||||
if let Err((param, message)) = validated {
|
||||
return Err(Box::new(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
@@ -882,6 +898,8 @@ fn parse_request(
|
||||
/// pictures, the embeddings file `GENI` takes.
|
||||
struct Prepared {
|
||||
token_ids: Vec<u32>,
|
||||
/// What `token_ids` is the encoding of (absent once pictures were expanded into the ids).
|
||||
prompt_text: Option<Arc<str>>,
|
||||
embeddings: Option<String>,
|
||||
keep: crate::vision::Keep,
|
||||
}
|
||||
@@ -974,6 +992,7 @@ async fn expand_images(
|
||||
let (path, keep) = vision.combine(&encoded).await.map_err(vision_error)?;
|
||||
Ok(Prepared {
|
||||
token_ids,
|
||||
prompt_text: None,
|
||||
embeddings: Some(path.to_string_lossy().into_owned()),
|
||||
keep,
|
||||
})
|
||||
@@ -1002,7 +1021,8 @@ async fn prepare_input_tokens(
|
||||
append_input(&mut transcript, &request.input);
|
||||
request.input = Value::Array(transcript);
|
||||
}
|
||||
let (prompt, images) = match render_request(request) {
|
||||
let rendered = crate::stage_trace::time("render", || render_request(request));
|
||||
let (prompt, images) = match rendered {
|
||||
Ok(rendered) => rendered,
|
||||
Err(message) => {
|
||||
return Err(Box::new(api_error(
|
||||
@@ -1015,14 +1035,16 @@ async fn prepare_input_tokens(
|
||||
}
|
||||
};
|
||||
let tokenizer_for_encode = tokenizer.clone();
|
||||
let token_ids = match tokio::task::spawn_blocking(move || {
|
||||
let tokenize_span = crate::stage_trace::span("tokenize");
|
||||
let (token_ids, prompt) = match tokio::task::spawn_blocking(move || {
|
||||
tokenizer_for_encode
|
||||
.encode(&prompt, true)
|
||||
.map(|ids| (ids, prompt))
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(ids)) => ids,
|
||||
Ok(Ok(encoded)) => encoded,
|
||||
Ok(Err(message)) => {
|
||||
return Err(Box::new(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
@@ -1042,9 +1064,11 @@ async fn prepare_input_tokens(
|
||||
)));
|
||||
}
|
||||
};
|
||||
drop(tokenize_span);
|
||||
if images.is_empty() || !encode_images {
|
||||
return Ok(Prepared {
|
||||
token_ids,
|
||||
prompt_text: Some(Arc::from(prompt)),
|
||||
embeddings: None,
|
||||
keep: Default::default(),
|
||||
});
|
||||
@@ -1121,6 +1145,14 @@ fn queue_error(error: crate::queue::Error) -> Response {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/v1/responses` route: [`create`] with the body read and parse timed.
|
||||
pub async fn create_route(
|
||||
state: State<AppState>,
|
||||
body: Result<TracedJson, JsonRejection>,
|
||||
) -> Response {
|
||||
create(state, body.map(|traced| traced.0)).await
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
body: Result<Json<Value>, JsonRejection>,
|
||||
@@ -1167,6 +1199,7 @@ pub async fn create(
|
||||
request.apply_defaults(&state.settings);
|
||||
let Prepared {
|
||||
token_ids,
|
||||
prompt_text,
|
||||
embeddings,
|
||||
keep,
|
||||
} = match prepare_input_tokens(&state, &mut request, tokenizer.clone(), true).await {
|
||||
@@ -1237,6 +1270,7 @@ pub async fn create(
|
||||
embeddings,
|
||||
keep,
|
||||
reasoning: reasoning_plan(&request, &state, tokenizer),
|
||||
prompt_text,
|
||||
};
|
||||
if text_level_engine {
|
||||
// What the text-level engine contract cannot carry is the client's error to hear about now, not a 502 after queueing.
|
||||
@@ -1271,7 +1305,8 @@ pub async fn create(
|
||||
}
|
||||
if request.stream {
|
||||
let (events, received) = mpsc::channel(16);
|
||||
if let Err(error) = crate::queue::enqueue(
|
||||
let enqueue_span = crate::stage_trace::span("enqueue");
|
||||
let enqueued = crate::queue::enqueue(
|
||||
generation,
|
||||
GenerationCommand {
|
||||
queue: None,
|
||||
@@ -1281,8 +1316,9 @@ pub async fn create(
|
||||
},
|
||||
state.queue_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
.await;
|
||||
drop(enqueue_span);
|
||||
if let Err(error) = enqueued {
|
||||
return queue_error(error);
|
||||
}
|
||||
return stream_live_text(
|
||||
@@ -2082,6 +2118,7 @@ fn render_request(request: &CreateRequest) -> Result<(String, Vec<String>), Stri
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let catalog = Catalog::new(&request.tools)?;
|
||||
let _template = crate::stage_trace::span("render_template");
|
||||
prompt::render_with_images(
|
||||
&messages,
|
||||
reasoning_effort(request).map_err(|(_, message)| message.to_owned())?,
|
||||
@@ -2370,12 +2407,15 @@ fn stream_live_buffered(
|
||||
let delta = reasoning_stream.finish();
|
||||
if !delta.is_empty() && !send_stream_event(&sender, &mut sequence, "response.reasoning_text.delta", json!({"response_id":id,"item_id":reasoning_id,"output_index":0,"content_index":0,"delta":delta})).await { return; }
|
||||
}
|
||||
let post_decode = crate::stage_trace::span("post_decode");
|
||||
let decoded = tokio::task::spawn_blocking(move || {
|
||||
decode_generation(&tokenizer, &tokens, thinking, done.finish)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|result| result);
|
||||
drop(post_decode);
|
||||
let post_assemble = crate::stage_trace::span("post_assemble");
|
||||
let assembled = decoded
|
||||
.and_then(|output| decoded_items(&request, output, &id))
|
||||
.and_then(|(items, reasoning_tokens)| {
|
||||
@@ -2397,8 +2437,10 @@ fn stream_live_buffered(
|
||||
done.finish == Finish::Length,
|
||||
)
|
||||
});
|
||||
drop(post_assemble);
|
||||
match assembled {
|
||||
Ok(trace) => {
|
||||
let _post_store = crate::stage_trace::span("post_store");
|
||||
if request.store != Some(false)
|
||||
&& let Some(history) = &history
|
||||
&& let Err(error) = store_response(
|
||||
@@ -3205,6 +3247,29 @@ fn validate_text_format(request: &CreateRequest, text: &str) -> Result<(), Strin
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a tool's `parameters` is a local, valid object schema. The answer depends on the schema alone, and a coding agent
|
||||
/// sends the same dozen tool schemas with every request (validated three times per request), so it is remembered by the
|
||||
/// schema's compact text instead of compiling a validator each time.
|
||||
fn tool_schema_accepted(parameters: &Value) -> bool {
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static MEMO: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
|
||||
let key = parameters.to_string();
|
||||
let memo = MEMO.get_or_init(Default::default);
|
||||
if let Some(known) = memo.lock().ok().and_then(|memo| memo.get(&key).copied()) {
|
||||
return known;
|
||||
}
|
||||
let accepted = parameters.get("type").and_then(Value::as_str) == Some("object")
|
||||
&& reject_remote_refs(parameters).is_ok()
|
||||
&& jsonschema::validator_for(parameters).is_ok();
|
||||
if let Ok(mut memo) = memo.lock() {
|
||||
if memo.len() >= 512 {
|
||||
memo.clear();
|
||||
}
|
||||
memo.insert(key, accepted);
|
||||
}
|
||||
accepted
|
||||
}
|
||||
|
||||
fn reject_remote_refs(value: &Value) -> Result<(), String> {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Env-gated per-stage timing of the host side of a request (`STRATA_STAGE_TRACE=1`).
|
||||
//!
|
||||
//! The control plane's cost outside the engine is a sum of small stages (body read and JSON parse, validation, chat
|
||||
//! template, tokenization, prompt text for the engine, event pump, response assembly). With the variable unset a span is
|
||||
//! one relaxed atomic load and no clock read; with `STRATA_STAGE_TRACE=1` every span adds its monotonic duration to a
|
||||
//! per-stage accumulator that [`drain`] hands out (the replay harness `examples/cp_replay.rs` reads it after each request),
|
||||
//! and with `STRATA_STAGE_TRACE=log` each span also writes one `stage <name> <ms> t_unix_ms=<end>` line to stderr. Spans never carry request
|
||||
//! content, only names and durations.
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Mutex, OnceLock,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const UNSET: u8 = 0;
|
||||
const OFF: u8 = 1;
|
||||
const ON: u8 = 2;
|
||||
const LOG: u8 = 3;
|
||||
|
||||
static MODE: AtomicU8 = AtomicU8::new(UNSET);
|
||||
|
||||
fn mode() -> u8 {
|
||||
match MODE.load(Ordering::Relaxed) {
|
||||
UNSET => {
|
||||
let value = match std::env::var("STRATA_STAGE_TRACE").as_deref() {
|
||||
Ok("1") => ON,
|
||||
Ok("log") => LOG,
|
||||
_ => OFF,
|
||||
};
|
||||
MODE.store(value, Ordering::Relaxed);
|
||||
value
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch tracing on from code (the replay harness); the environment variable does the same for a server.
|
||||
pub fn enable() {
|
||||
MODE.store(ON, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
mode() >= ON
|
||||
}
|
||||
|
||||
fn table() -> &'static Mutex<BTreeMap<&'static str, (f64, u32)>> {
|
||||
static TABLE: OnceLock<Mutex<BTreeMap<&'static str, (f64, u32)>>> = OnceLock::new();
|
||||
TABLE.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
/// Add `elapsed` to the stage `name`.
|
||||
pub fn record(name: &'static str, elapsed: Duration) {
|
||||
let current = mode();
|
||||
if current < ON {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut table) = table().lock() {
|
||||
let entry = table.entry(name).or_insert((0.0, 0));
|
||||
entry.0 += elapsed.as_secs_f64() * 1000.0;
|
||||
entry.1 += 1;
|
||||
}
|
||||
if current == LOG {
|
||||
let unix_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis());
|
||||
crate::elog!(
|
||||
"stage {name} {:.3} t_unix_ms={unix_ms}",
|
||||
elapsed.as_secs_f64() * 1000.0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything recorded since the last call: stage -> (total ms, spans).
|
||||
pub fn drain() -> BTreeMap<&'static str, (f64, u32)> {
|
||||
table()
|
||||
.lock()
|
||||
.map(|mut table| std::mem::take(&mut *table))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A running span; it records on drop.
|
||||
pub struct Span {
|
||||
started: Option<(&'static str, Instant)>,
|
||||
}
|
||||
|
||||
impl Drop for Span {
|
||||
fn drop(&mut self) {
|
||||
if let Some((name, started)) = self.started.take() {
|
||||
record(name, started.elapsed());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn span(name: &'static str) -> Span {
|
||||
Span {
|
||||
started: (mode() >= ON).then(|| (name, Instant::now())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `work` inside the span `name`.
|
||||
pub fn time<T>(name: &'static str, work: impl FnOnce() -> T) -> T {
|
||||
let _span = span(name);
|
||||
work()
|
||||
}
|
||||
@@ -61,6 +61,10 @@ pub struct Generate {
|
||||
pub keep: crate::vision::Keep,
|
||||
/// Reasoning-budget wrap-up, executed by the worker; never sent to the engine.
|
||||
pub reasoning: Option<ReasoningPlan>,
|
||||
/// The text `token_ids` was produced from (`encode(text, true)`), when the HTTP layer still has it. A text-level engine
|
||||
/// is sent this text after a cheap check that the ids decode to it, instead of decoding the ids and tokenizing the result
|
||||
/// again to prove they round-trip.
|
||||
pub prompt_text: Option<std::sync::Arc<str>>,
|
||||
}
|
||||
|
||||
impl Generate {
|
||||
@@ -322,6 +326,7 @@ mod tests {
|
||||
embeddings: case["embeddings"].as_str().map(str::to_owned),
|
||||
keep: Default::default(),
|
||||
reasoning: None,
|
||||
prompt_text: None,
|
||||
};
|
||||
assert_eq!(
|
||||
request.line().unwrap(),
|
||||
|
||||
+14
-12
@@ -915,18 +915,9 @@ pub(crate) async fn finish(
|
||||
disconnected: bool,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
) -> Result<(), String> {
|
||||
// One line per generation: the operator's only per-request record (no prompt or output text).
|
||||
crate::elog!(
|
||||
"generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}",
|
||||
unix_ms(),
|
||||
done.finish,
|
||||
done.prompt_tokens,
|
||||
done.reused.unwrap_or(0),
|
||||
done.generated,
|
||||
done.prompt_ms,
|
||||
done.decode_ms,
|
||||
disconnected
|
||||
);
|
||||
// One line per generation: the operator's only per-request record (no prompt or output text). The time is taken now; the
|
||||
// line is written after the client side has the terminal event, so a slow log sink never delays a response.
|
||||
let finished_ms = unix_ms();
|
||||
let event = Event::Done(done.clone());
|
||||
match command.result.take() {
|
||||
GenerationResult::Buffered(sender) => {
|
||||
@@ -938,6 +929,17 @@ pub(crate) async fn finish(
|
||||
}
|
||||
GenerationResult::Finished => {}
|
||||
}
|
||||
crate::elog!(
|
||||
"generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}",
|
||||
finished_ms,
|
||||
done.finish,
|
||||
done.prompt_tokens,
|
||||
done.reused.unwrap_or(0),
|
||||
done.generated,
|
||||
done.prompt_ms,
|
||||
done.decode_ms,
|
||||
disconnected
|
||||
);
|
||||
status.write().await.metrics.finish(&done, disconnected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1425,3 +1425,80 @@ async fn codex_tool_choice_and_parallel_calls_are_enforced_on_the_generated_call
|
||||
);
|
||||
stack.finish().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() {
|
||||
use strata_control::wire::Generate;
|
||||
use strata_control::worker::{GenerationCommand, GenerationResult};
|
||||
let stack = Stack::start("bw-known-text").await;
|
||||
let (requests, requests_rx) = mpsc::channel(1);
|
||||
let (_control, control_rx) = mpsc::channel(1);
|
||||
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
|
||||
handle.respond_with(|_| {
|
||||
Script::stop_with(
|
||||
&["ok"],
|
||||
Usage {
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
reused_input_tokens: 0,
|
||||
},
|
||||
)
|
||||
});
|
||||
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
||||
let (_stop, stop_rx) = watch::channel(false);
|
||||
let config = BackendWorkerConfig {
|
||||
tokenizer: stack.tokenizer.clone(),
|
||||
model: ScriptedEngine::fixture_descriptor(),
|
||||
runtime: runtime_config(),
|
||||
max_context: 262_144,
|
||||
max_output_tokens: 4096,
|
||||
health_interval: Duration::from_millis(20),
|
||||
generation_timeout: None,
|
||||
stall_timeout: None,
|
||||
attach_retry: Duration::from_millis(20),
|
||||
cancel_drain_timeout: Duration::from_secs(1),
|
||||
prefix_view: None,
|
||||
memory_view: None,
|
||||
};
|
||||
tokio::spawn(run_backend_worker(
|
||||
Box::new(engine),
|
||||
config,
|
||||
status.clone(),
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
));
|
||||
while status.read().await.state != WorkerState::Ready {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let mut ask = async |text: &str, claimed: Option<&str>| {
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel();
|
||||
requests
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: stack.tokenizer.encode(text, true).unwrap(),
|
||||
max_new: 8,
|
||||
prompt_text: claimed.map(Arc::from),
|
||||
..Default::default()
|
||||
},
|
||||
result: GenerationResult::Buffered(sender),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
receiver.await.unwrap().expect("served");
|
||||
};
|
||||
// the text the ids were produced from: the engine gets exactly that text
|
||||
ask("hello tool<|im_end|>\n", Some("hello tool<|im_end|>\n")).await;
|
||||
// a claim the ids do not decode to is not trusted: the engine gets the text of the ids
|
||||
ask("hello tool", Some("something else entirely")).await;
|
||||
// no claim: the ids are decoded and checked as before
|
||||
ask("tool hello", None).await;
|
||||
let prompts: Vec<String> = handle.requests().into_iter().map(|r| r.prompt).collect();
|
||||
assert_eq!(
|
||||
prompts,
|
||||
["hello tool<|im_end|>\n", "hello tool", "tool hello"]
|
||||
);
|
||||
stack.finish().await;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ rust-version.workspace = true
|
||||
[dependencies]
|
||||
aho-corasick = "1.1"
|
||||
fancy-regex = "0.19"
|
||||
regex-syntax = "0.8"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Reference vs fast path vs segment cache on a real prompt text.
|
||||
//!
|
||||
//! `cargo run --release -p leleka-tokenizer --example bench_fast -- TOKENIZER_DIR TEXT_FILE [REPEAT]`
|
||||
|
||||
use std::{env, fs, path::Path, process::ExitCode, time::Instant};
|
||||
|
||||
use leleka_tokenizer::Tokenizer;
|
||||
|
||||
fn best<T>(repeat: usize, mut work: impl FnMut() -> T) -> (f64, T) {
|
||||
let mut best = f64::MAX;
|
||||
let mut last = None;
|
||||
for _ in 0..repeat {
|
||||
let started = Instant::now();
|
||||
let value = work();
|
||||
best = best.min(started.elapsed().as_secs_f64() * 1e3);
|
||||
last = Some(value);
|
||||
}
|
||||
(best, last.unwrap())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() < 3 {
|
||||
eprintln!("usage: bench_fast TOKENIZER_DIR TEXT_FILE [REPEAT]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let started = Instant::now();
|
||||
let tokenizer = Tokenizer::from_assets(Path::new(&args[1])).expect("tokenizer assets");
|
||||
eprintln!(
|
||||
"load {:.0} ms, fast path {}",
|
||||
started.elapsed().as_secs_f64() * 1e3,
|
||||
tokenizer.has_fast_path()
|
||||
);
|
||||
let text = String::from_utf8_lossy(&fs::read(&args[2]).expect("text")).into_owned();
|
||||
let repeat: usize = args.get(3).and_then(|v| v.parse().ok()).unwrap_or(5);
|
||||
let (reference_ms, reference) =
|
||||
best(repeat, || tokenizer.encode_reference(&text, true).unwrap());
|
||||
tokenizer.set_segment_cache_bytes(0);
|
||||
let (fast_ms, fast) = best(repeat, || tokenizer.encode(&text, true).unwrap());
|
||||
assert_eq!(fast, reference);
|
||||
tokenizer.set_segment_cache_bytes(leleka_tokenizer::DEFAULT_SEGMENT_CACHE_BYTES);
|
||||
let started = Instant::now();
|
||||
let first = tokenizer.encode(&text, true).unwrap();
|
||||
let first_ms = started.elapsed().as_secs_f64() * 1e3;
|
||||
assert_eq!(first, reference);
|
||||
let (warm_ms, warm) = best(repeat, || tokenizer.encode(&text, true).unwrap());
|
||||
assert_eq!(warm, reference);
|
||||
// the next turn: the same history plus a new tail
|
||||
let tail = "<|im_start|>user\n<tool_response>\nsome new tool output that has not been seen before\n</tool_response><|im_end|>\n<|im_start|>assistant\n<think>\n";
|
||||
let next = format!("{text}{tail}");
|
||||
let (next_ms, _) = best(1, || tokenizer.encode(&next, true).unwrap());
|
||||
let (decode_ms, bytes) = best(repeat, || tokenizer.decode_bytes(&reference).unwrap());
|
||||
let (matches_ms, ok) = best(repeat, || tokenizer.decodes_to(&reference, text.as_bytes()));
|
||||
assert!(ok && bytes == text.as_bytes());
|
||||
let mtok = |ms: f64| reference.len() as f64 / ms / 1e3;
|
||||
println!(
|
||||
"{} bytes, {} tokens\n reference (regex + string BPE) {reference_ms:8.2} ms {:6.2} Mtok/s\n fast path, no cache {fast_ms:8.2} ms {:6.2} Mtok/s\n fast path, cache cold {first_ms:8.2} ms\n cache warm (same text) {warm_ms:8.2} ms\n cache warm + new tail {next_ms:8.2} ms\n decode_bytes {decode_ms:8.2} ms\n decodes_to {matches_ms:8.2} ms",
|
||||
text.len(),
|
||||
reference.len(),
|
||||
mtok(reference_ms),
|
||||
mtok(fast_ms),
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! A bounded cache of the token ids of text segments.
|
||||
//!
|
||||
//! A chat prompt is split at the special tokens (`<|im_start|>`, `<think>`, `<tool_call>`, ...) before byte-level BPE, so
|
||||
//! the ids of the text *between* two special tokens depend on that text alone. A coding agent sends its whole history
|
||||
//! again on every turn; all of the history except the last few segments is text this process tokenized on an earlier turn.
|
||||
//! Keyed by the exact segment text, the cache returns those ids without the pre-tokenizer or the merges, and a hit is
|
||||
//! verified byte for byte against the stored text, so a hash collision can only cost a miss, never a wrong id.
|
||||
//!
|
||||
//! The bound is a two-generation scheme: inserts go to the young generation; when it has taken half the budget it becomes
|
||||
//! the old generation and the previous old one is dropped. A hit in the old generation is promoted. That evicts what has
|
||||
//! not been used for a whole generation, in O(1), without an LRU list.
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
hash::Hasher,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
/// Segments shorter than this are tokenized every time: hashing and locking would cost about what the merges do.
|
||||
pub const MIN_SEGMENT_BYTES: usize = 96;
|
||||
|
||||
/// Default budget (text + ids of both generations), bytes.
|
||||
pub const DEFAULT_BUDGET: usize = 64 << 20;
|
||||
|
||||
struct Entry {
|
||||
text: Box<str>,
|
||||
ids: Arc<[u32]>,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn cost(&self) -> usize {
|
||||
self.text.len() + self.ids.len() * 4 + 64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Generations {
|
||||
young: HashMap<u64, Entry>,
|
||||
old: HashMap<u64, Entry>,
|
||||
young_bytes: usize,
|
||||
budget: usize,
|
||||
}
|
||||
|
||||
pub struct SegmentCache {
|
||||
inner: Mutex<Generations>,
|
||||
}
|
||||
|
||||
fn digest(text: &str) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
hasher.write(text.as_bytes());
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl SegmentCache {
|
||||
pub fn new(budget: usize) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(Generations {
|
||||
budget,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_budget(&self, budget: usize) {
|
||||
if let Ok(mut cache) = self.inner.lock() {
|
||||
cache.budget = budget;
|
||||
if budget == 0 {
|
||||
cache.young.clear();
|
||||
cache.old.clear();
|
||||
cache.young_bytes = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(hash, ids)` for a segment seen before; the hash is returned either way so the caller can insert without hashing again.
|
||||
pub fn lookup(&self, text: &str) -> (u64, Option<Arc<[u32]>>) {
|
||||
let key = digest(text);
|
||||
let Ok(mut cache) = self.inner.lock() else {
|
||||
return (key, None);
|
||||
};
|
||||
if let Some(entry) = cache.young.get(&key)
|
||||
&& &*entry.text == text
|
||||
{
|
||||
return (key, Some(Arc::clone(&entry.ids)));
|
||||
}
|
||||
if let Some(entry) = cache.old.get(&key)
|
||||
&& &*entry.text == text
|
||||
{
|
||||
let ids = Arc::clone(&entry.ids);
|
||||
if let Some(entry) = cache.old.remove(&key) {
|
||||
cache.young_bytes += entry.cost();
|
||||
cache.young.insert(key, entry);
|
||||
cache.rotate_if_full();
|
||||
}
|
||||
return (key, Some(ids));
|
||||
}
|
||||
(key, None)
|
||||
}
|
||||
|
||||
pub fn insert(&self, key: u64, text: &str, ids: &[u32]) {
|
||||
let Ok(mut cache) = self.inner.lock() else {
|
||||
return;
|
||||
};
|
||||
if cache.budget == 0 {
|
||||
return;
|
||||
}
|
||||
let entry = Entry {
|
||||
text: text.into(),
|
||||
ids: ids.into(),
|
||||
};
|
||||
if entry.cost() > cache.budget / 2 {
|
||||
return;
|
||||
}
|
||||
cache.young_bytes += entry.cost();
|
||||
cache.young.insert(key, entry);
|
||||
cache.rotate_if_full();
|
||||
}
|
||||
|
||||
/// (entries, approximate bytes) held now.
|
||||
pub fn stats(&self) -> (usize, usize) {
|
||||
self.inner
|
||||
.lock()
|
||||
.map(|cache| {
|
||||
let bytes =
|
||||
|map: &HashMap<u64, Entry>| map.values().map(Entry::cost).sum::<usize>();
|
||||
(
|
||||
cache.young.len() + cache.old.len(),
|
||||
bytes(&cache.young) + bytes(&cache.old),
|
||||
)
|
||||
})
|
||||
.unwrap_or((0, 0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Generations {
|
||||
fn rotate_if_full(&mut self) {
|
||||
if self.young_bytes > self.budget / 2 {
|
||||
self.old = std::mem::take(&mut self.young);
|
||||
self.young_bytes = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
//! The tokenizer's hot path: a hand-written scanner for the pinned `qwen35` pre-tokenizer pattern and a table-driven byte-level
|
||||
//! BPE over token ids.
|
||||
//!
|
||||
//! Neither changes what the tokenizer returns. The scanner is the pattern's seven alternatives written out with the
|
||||
//! backtracking they imply (see [`Classes::piece_end`]); its Unicode classes (`\p{L}`, `\p{M}`, `\p{N}`, `\s`) are read out
|
||||
//! of `regex-syntax`, the crate the regex engine resolves them with, so both agree by construction on every scalar value
|
||||
//! (`tests/fast_path.rs` checks all of them in many contexts, plus fuzzed text, against the regex). The BPE keeps the
|
||||
//! reference algorithm (repeatedly merge the lowest-ranked adjacent pair, leftmost on ties) but keeps symbols as vocabulary
|
||||
//! ids and ranks in an open-addressing table instead of re-building strings and hashing them for every comparison.
|
||||
//! A vocabulary for which the id-based merge could differ from the string-based one (a merge whose result is not a vocabulary
|
||||
//! token, a byte with no token) disables the fast path: [`Fast::build`] returns `None` and the string BPE stays in charge.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use regex_syntax::{
|
||||
ParserBuilder,
|
||||
hir::{Class, HirKind},
|
||||
};
|
||||
|
||||
const LETTER: u8 = 1;
|
||||
const MARK: u8 = 2;
|
||||
const NUMBER: u8 = 4;
|
||||
const SPACE: u8 = 8;
|
||||
const LETTER_OR_MARK: u8 = LETTER | MARK;
|
||||
|
||||
fn unicode_ranges(pattern: &str) -> Result<Vec<(u32, u32)>, String> {
|
||||
let hir = ParserBuilder::new()
|
||||
.build()
|
||||
.parse(pattern)
|
||||
.map_err(|e| e.to_string())?;
|
||||
match hir.kind() {
|
||||
HirKind::Class(Class::Unicode(class)) => Ok(class
|
||||
.iter()
|
||||
.map(|range| (range.start() as u32, range.end() as u32))
|
||||
.collect()),
|
||||
_ => Err(format!("{pattern} is not a Unicode class")),
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(ranges: &[(u32, u32)], code: u32) -> bool {
|
||||
let at = ranges.partition_point(|&(start, _)| start <= code);
|
||||
at > 0 && ranges[at - 1].1 >= code
|
||||
}
|
||||
|
||||
/// Unicode classes of the pre-tokenizer pattern, as flag bits per scalar value.
|
||||
pub struct Classes {
|
||||
ascii: [u8; 128],
|
||||
starts: Vec<u32>,
|
||||
flags: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Classes {
|
||||
pub fn new() -> Result<Self, String> {
|
||||
let sets = [
|
||||
(LETTER, unicode_ranges(r"\p{L}")?),
|
||||
(MARK, unicode_ranges(r"\p{M}")?),
|
||||
(NUMBER, unicode_ranges(r"\p{N}")?),
|
||||
(SPACE, unicode_ranges(r"\s")?),
|
||||
];
|
||||
let flags_of = |code: u32| {
|
||||
sets.iter()
|
||||
.filter(|(_, ranges)| contains(ranges, code))
|
||||
.fold(0u8, |bits, (flag, _)| bits | flag)
|
||||
};
|
||||
let mut ascii = [0u8; 128];
|
||||
for (code, slot) in ascii.iter_mut().enumerate() {
|
||||
*slot = flags_of(code as u32);
|
||||
}
|
||||
let mut bounds = vec![0u32];
|
||||
for (_, ranges) in &sets {
|
||||
for &(start, end) in ranges {
|
||||
bounds.push(start);
|
||||
bounds.push(end + 1);
|
||||
}
|
||||
}
|
||||
bounds.sort_unstable();
|
||||
bounds.dedup();
|
||||
bounds.retain(|&b| b <= 0x10FFFF);
|
||||
let flags = bounds.iter().map(|&start| flags_of(start)).collect();
|
||||
Ok(Self {
|
||||
ascii,
|
||||
starts: bounds,
|
||||
flags,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn flags_of(&self, c: char) -> u8 {
|
||||
let code = c as u32;
|
||||
if code < 128 {
|
||||
self.ascii[code as usize]
|
||||
} else {
|
||||
let at = self.starts.partition_point(|&start| start <= code);
|
||||
self.flags[at - 1]
|
||||
}
|
||||
}
|
||||
|
||||
/// The character at byte offset `i`: (class flags, char, byte length).
|
||||
#[inline]
|
||||
fn at(&self, text: &str, i: usize) -> Option<(u8, char, usize)> {
|
||||
let byte = *text.as_bytes().get(i)?;
|
||||
if byte < 128 {
|
||||
Some((self.ascii[byte as usize], byte as char, 1))
|
||||
} else {
|
||||
let c = text[i..].chars().next()?;
|
||||
Some((self.flags_of(c), c, c.len_utf8()))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn letters_end(&self, text: &str, mut i: usize) -> usize {
|
||||
while let Some((flags, _, len)) = self.at(text, i) {
|
||||
if flags & LETTER_OR_MARK == 0 {
|
||||
break;
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// End of the pre-token that starts at byte `i` (`i < text.len()`), for the pattern
|
||||
///
|
||||
/// ```text
|
||||
/// (?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])
|
||||
/// |[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+
|
||||
/// |\p{N}
|
||||
/// | ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*
|
||||
/// |\s*[\r\n]+
|
||||
/// |\s+(?!\S)
|
||||
/// |\s+
|
||||
/// ```
|
||||
///
|
||||
/// with leftmost-first alternation and backtracking quantifiers. Every scalar value falls in exactly one of letter/mark,
|
||||
/// number, symbol (none of the three and not white space) or white space, so some alternative always matches.
|
||||
pub fn piece_end(&self, text: &str, i: usize) -> usize {
|
||||
let bytes = text.as_bytes();
|
||||
let (flags, c, len) = self.at(text, i).expect("piece_end past the end");
|
||||
// 1: contractions
|
||||
if c == '\'' {
|
||||
let at = |k: usize| bytes.get(i + k).copied();
|
||||
match at(1) {
|
||||
Some(b's' | b'S' | b't' | b'T' | b'm' | b'M' | b'd' | b'D') => return i + 2,
|
||||
Some(b'r' | b'R' | b'v' | b'V') if matches!(at(2), Some(b'e' | b'E')) => {
|
||||
return i + 3;
|
||||
}
|
||||
Some(b'l' | b'L') if matches!(at(2), Some(b'l' | b'L')) => return i + 3,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// 2: [^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+ (a mark is both a possible prefix and a letter; either reading ends in the same place)
|
||||
if flags & LETTER_OR_MARK != 0 {
|
||||
return self.letters_end(text, i + len);
|
||||
}
|
||||
if c != '\r'
|
||||
&& c != '\n'
|
||||
&& flags & (LETTER | NUMBER) == 0
|
||||
&& let Some((next, _, _)) = self.at(text, i + len)
|
||||
&& next & LETTER_OR_MARK != 0
|
||||
{
|
||||
return self.letters_end(text, i + len);
|
||||
}
|
||||
// 3: \p{N}
|
||||
if flags & NUMBER != 0 {
|
||||
return i + len;
|
||||
}
|
||||
// 4: ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*
|
||||
let start = if c == ' ' { i + 1 } else { i };
|
||||
if let Some((first, _, _)) = self.at(text, start)
|
||||
&& first & (SPACE | LETTER | MARK | NUMBER) == 0
|
||||
{
|
||||
let mut end = start;
|
||||
while let Some((f, _, l)) = self.at(text, end) {
|
||||
if f & (SPACE | LETTER | MARK | NUMBER) != 0 {
|
||||
break;
|
||||
}
|
||||
end += l;
|
||||
}
|
||||
while matches!(bytes.get(end), Some(b'\r' | b'\n')) {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
// 5-7: white space. \s*[\r\n]+ ends at the last line break of the run; \s+(?!\S) gives the run back one character
|
||||
// unless the text ends; \s+ takes a lone character.
|
||||
debug_assert!(flags & SPACE != 0);
|
||||
let mut end = i;
|
||||
let mut last_break = 0;
|
||||
let mut last_len = 0;
|
||||
let mut count = 0;
|
||||
while let Some((f, ch, l)) = self.at(text, end) {
|
||||
if f & SPACE == 0 {
|
||||
break;
|
||||
}
|
||||
end += l;
|
||||
last_len = l;
|
||||
count += 1;
|
||||
if ch == '\r' || ch == '\n' {
|
||||
last_break = end;
|
||||
}
|
||||
}
|
||||
if last_break > 0 {
|
||||
return last_break;
|
||||
}
|
||||
if end == text.len() || count < 2 {
|
||||
return end;
|
||||
}
|
||||
end - last_len
|
||||
}
|
||||
}
|
||||
|
||||
const EMPTY: u64 = u64::MAX;
|
||||
|
||||
/// `(left id, right id) -> (rank, merged id)`, open addressing with a multiplicative hash.
|
||||
struct PairTable {
|
||||
keys: Vec<u64>,
|
||||
values: Vec<(u32, u32)>,
|
||||
shift: u32,
|
||||
}
|
||||
|
||||
impl PairTable {
|
||||
fn with_capacity(entries: usize) -> Self {
|
||||
let slots = (entries * 2).max(16).next_power_of_two();
|
||||
Self {
|
||||
keys: vec![EMPTY; slots],
|
||||
values: vec![(0, 0); slots],
|
||||
shift: 64 - slots.trailing_zeros(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn slot(&self, key: u64) -> usize {
|
||||
(key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> self.shift) as usize
|
||||
}
|
||||
|
||||
fn insert(&mut self, left: u32, right: u32, rank: u32, merged: u32) {
|
||||
let key = (u64::from(left) << 32) | u64::from(right);
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut at = self.slot(key);
|
||||
while self.keys[at] != EMPTY {
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
self.keys[at] = key;
|
||||
self.values[at] = (rank, merged);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get(&self, left: u32, right: u32) -> Option<(u32, u32)> {
|
||||
let key = (u64::from(left) << 32) | u64::from(right);
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut at = self.slot(key);
|
||||
loop {
|
||||
let stored = self.keys[at];
|
||||
if stored == key {
|
||||
return Some(self.values[at]);
|
||||
}
|
||||
if stored == EMPTY {
|
||||
return None;
|
||||
}
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NO_RANK: u32 = u32::MAX;
|
||||
|
||||
pub struct Fast {
|
||||
pub classes: Classes,
|
||||
pairs: PairTable,
|
||||
byte_ids: [u32; 256],
|
||||
}
|
||||
|
||||
impl Fast {
|
||||
/// `None` when the vocabulary is not one the id-based merge reproduces exactly (see the module notes).
|
||||
pub fn build(
|
||||
vocab: &HashMap<String, u32>,
|
||||
merges: &[(String, String)],
|
||||
byte_chars: &[char; 256],
|
||||
) -> Option<Self> {
|
||||
let mut byte_ids = [0u32; 256];
|
||||
for (byte, ch) in byte_chars.iter().enumerate() {
|
||||
byte_ids[byte] = *vocab.get(ch.to_string().as_str())?;
|
||||
}
|
||||
let mut pairs = PairTable::with_capacity(merges.len());
|
||||
let mut joined = String::new();
|
||||
for (rank, (left, right)) in merges.iter().enumerate() {
|
||||
joined.clear();
|
||||
joined.push_str(left);
|
||||
joined.push_str(right);
|
||||
let merged = *vocab.get(joined.as_str())?;
|
||||
pairs.insert(
|
||||
*vocab.get(left.as_str())?,
|
||||
*vocab.get(right.as_str())?,
|
||||
u32::try_from(rank).ok()?,
|
||||
merged,
|
||||
);
|
||||
}
|
||||
let classes = Classes::new().ok()?;
|
||||
Some(Self {
|
||||
classes,
|
||||
pairs,
|
||||
byte_ids,
|
||||
})
|
||||
}
|
||||
|
||||
/// Byte-level BPE of one pre-token.
|
||||
pub fn encode_piece(&self, piece: &[u8], out: &mut Vec<u32>, scratch: &mut Scratch) {
|
||||
if piece.len() == 1 {
|
||||
out.push(self.byte_ids[piece[0] as usize]);
|
||||
return;
|
||||
}
|
||||
let parts = &mut scratch.parts;
|
||||
let ranks = &mut scratch.ranks;
|
||||
parts.clear();
|
||||
parts.extend(piece.iter().map(|&byte| self.byte_ids[byte as usize]));
|
||||
if parts.len() > 48 {
|
||||
self.merge_long(parts);
|
||||
out.extend_from_slice(parts);
|
||||
return;
|
||||
}
|
||||
ranks.clear();
|
||||
for pair in parts.windows(2) {
|
||||
ranks.push(
|
||||
self.pairs
|
||||
.get(pair[0], pair[1])
|
||||
.map_or(NO_RANK, |(rank, _)| rank),
|
||||
);
|
||||
}
|
||||
loop {
|
||||
let mut best = NO_RANK;
|
||||
let mut at = 0;
|
||||
for (index, &rank) in ranks.iter().enumerate() {
|
||||
if rank < best {
|
||||
best = rank;
|
||||
at = index;
|
||||
}
|
||||
}
|
||||
if best == NO_RANK {
|
||||
break;
|
||||
}
|
||||
let (_, merged) = self
|
||||
.pairs
|
||||
.get(parts[at], parts[at + 1])
|
||||
.expect("ranked pair is in the table");
|
||||
parts[at] = merged;
|
||||
parts.remove(at + 1);
|
||||
ranks.remove(at);
|
||||
if at > 0 {
|
||||
ranks[at - 1] = self
|
||||
.pairs
|
||||
.get(parts[at - 1], parts[at])
|
||||
.map_or(NO_RANK, |(rank, _)| rank);
|
||||
}
|
||||
if at + 1 < parts.len() {
|
||||
ranks[at] = self
|
||||
.pairs
|
||||
.get(parts[at], parts[at + 1])
|
||||
.map_or(NO_RANK, |(rank, _)| rank);
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(parts);
|
||||
}
|
||||
|
||||
/// The linked-list and heap form for long pieces (the same merge order: lowest rank first, leftmost on ties).
|
||||
fn merge_long(&self, parts: &mut Vec<u32>) {
|
||||
use std::{cmp::Reverse, collections::BinaryHeap};
|
||||
let n = parts.len();
|
||||
let mut next: Vec<usize> = (1..=n).collect();
|
||||
let mut prev: Vec<isize> = (0..n as isize).map(|i| i - 1).collect();
|
||||
let mut alive = vec![true; n];
|
||||
let mut version = vec![0u32; n];
|
||||
let mut queue: BinaryHeap<Reverse<(u32, u32, u32, u32, u32)>> = BinaryHeap::new();
|
||||
let push = |queue: &mut BinaryHeap<Reverse<(u32, u32, u32, u32, u32)>>,
|
||||
parts: &[u32],
|
||||
next: &[usize],
|
||||
version: &[u32],
|
||||
left: usize| {
|
||||
let right = next[left];
|
||||
if right < n
|
||||
&& let Some((rank, _)) = self.pairs.get(parts[left], parts[right])
|
||||
{
|
||||
queue.push(Reverse((
|
||||
rank,
|
||||
left as u32,
|
||||
right as u32,
|
||||
version[left],
|
||||
version[right],
|
||||
)));
|
||||
}
|
||||
};
|
||||
for left in 0..n.saturating_sub(1) {
|
||||
push(&mut queue, parts, &next, &version, left);
|
||||
}
|
||||
while let Some(Reverse((_, left, right, left_version, right_version))) = queue.pop() {
|
||||
let (left, right) = (left as usize, right as usize);
|
||||
if !alive[left]
|
||||
|| !alive[right]
|
||||
|| next[left] != right
|
||||
|| version[left] != left_version
|
||||
|| version[right] != right_version
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (_, merged) = self
|
||||
.pairs
|
||||
.get(parts[left], parts[right])
|
||||
.expect("queued pair is in the table");
|
||||
parts[left] = merged;
|
||||
alive[right] = false;
|
||||
next[left] = next[right];
|
||||
version[left] += 1;
|
||||
if next[left] < n {
|
||||
prev[next[left]] = left as isize;
|
||||
}
|
||||
push(&mut queue, parts, &next, &version, left);
|
||||
if prev[left] >= 0 {
|
||||
push(&mut queue, parts, &next, &version, prev[left] as usize);
|
||||
}
|
||||
}
|
||||
let mut result = Vec::with_capacity(n);
|
||||
let mut current = 0usize;
|
||||
while current < n {
|
||||
result.push(parts[current]);
|
||||
current = next[current];
|
||||
}
|
||||
*parts = result;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable buffers of one encoding call.
|
||||
#[derive(Default)]
|
||||
pub struct Scratch {
|
||||
parts: Vec<u32>,
|
||||
ranks: Vec<u32>,
|
||||
}
|
||||
+212
-20
@@ -12,6 +12,11 @@ use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
|
||||
use fancy_regex::Regex;
|
||||
use serde::Deserialize;
|
||||
|
||||
mod cache;
|
||||
mod fast;
|
||||
|
||||
pub use cache::{DEFAULT_BUDGET as DEFAULT_SEGMENT_CACHE_BYTES, MIN_SEGMENT_BYTES};
|
||||
|
||||
/// Pre-tokenization expression pinned to the Qwen35 GGUF vocabulary oracle.
|
||||
pub const QWEN35_PATTERN: &str = concat!(
|
||||
r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])",
|
||||
@@ -40,6 +45,21 @@ pub fn pre_tokenize(text: &str) -> Result<Vec<&str>> {
|
||||
Ok(pieces)
|
||||
}
|
||||
|
||||
/// [`pre_tokenize`] by the hand-written scanner the tokenizer's fast path uses (same pieces; exposed for the differential tests).
|
||||
#[doc(hidden)]
|
||||
pub fn pre_tokenize_fast(text: &str) -> Vec<&str> {
|
||||
static CLASSES: std::sync::OnceLock<fast::Classes> = std::sync::OnceLock::new();
|
||||
let classes = CLASSES.get_or_init(|| fast::Classes::new().expect("unicode classes"));
|
||||
let mut pieces = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < text.len() {
|
||||
let end = classes.piece_end(text, at);
|
||||
pieces.push(&text[at..end]);
|
||||
at = end;
|
||||
}
|
||||
pieces
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
model: String,
|
||||
@@ -55,15 +75,78 @@ struct LiteralMatcher {
|
||||
ids: Vec<u32>,
|
||||
}
|
||||
|
||||
/// The bytes of every token, flat, for decoding without a hash lookup per character.
|
||||
struct DecodeTable {
|
||||
bytes: Vec<u8>,
|
||||
starts: Vec<u32>,
|
||||
/// Tokens with a character outside the byte alphabet (decoding them is an error, as it always was).
|
||||
outside: Vec<bool>,
|
||||
}
|
||||
|
||||
impl DecodeTable {
|
||||
fn new(tokens: &[String], char_bytes: &HashMap<char, u8>) -> Self {
|
||||
let mut bytes = Vec::new();
|
||||
let mut starts = Vec::with_capacity(tokens.len() + 1);
|
||||
let mut outside = Vec::with_capacity(tokens.len());
|
||||
for token in tokens {
|
||||
starts.push(bytes.len() as u32);
|
||||
let mark = bytes.len();
|
||||
let mut bad = false;
|
||||
for ch in token.chars() {
|
||||
match char_bytes.get(&ch) {
|
||||
Some(&byte) => bytes.push(byte),
|
||||
None => {
|
||||
bad = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if bad {
|
||||
bytes.truncate(mark);
|
||||
}
|
||||
outside.push(bad);
|
||||
}
|
||||
starts.push(bytes.len() as u32);
|
||||
Self {
|
||||
bytes,
|
||||
starts,
|
||||
outside,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
starts: vec![0],
|
||||
outside: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn token(&self, id: u32) -> Result<&[u8]> {
|
||||
let index = id as usize;
|
||||
if index >= self.outside.len() {
|
||||
return Err("token ID exceeds vocabulary".into());
|
||||
}
|
||||
if self.outside[index] {
|
||||
return Err("token is outside byte alphabet".into());
|
||||
}
|
||||
Ok(&self.bytes[self.starts[index] as usize..self.starts[index + 1] as usize])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Tokenizer {
|
||||
tokens: Vec<String>,
|
||||
vocab: HashMap<String, u32>,
|
||||
ranks: HashMap<String, usize>,
|
||||
pattern: Regex,
|
||||
always: Option<LiteralMatcher>,
|
||||
special: Option<LiteralMatcher>,
|
||||
byte_chars: [char; 256],
|
||||
char_bytes: HashMap<char, u8>,
|
||||
decode_table: DecodeTable,
|
||||
/// Table-driven pre-tokenizer and BPE; `None` for a vocabulary it cannot reproduce exactly.
|
||||
fast: Option<fast::Fast>,
|
||||
segments: cache::SegmentCache,
|
||||
}
|
||||
|
||||
impl Tokenizer {
|
||||
@@ -175,23 +258,127 @@ impl Tokenizer {
|
||||
let special = literal_matcher(&tokens, &types, true)?;
|
||||
let pattern = Regex::new(QWEN35_PATTERN)?;
|
||||
let (byte_chars, char_bytes) = byte_alphabet();
|
||||
let pairs: Vec<(String, String)> = merges
|
||||
.iter()
|
||||
.filter_map(|merge| merge.split_once(' '))
|
||||
.map(|(left, right)| (left.to_owned(), right.to_owned()))
|
||||
.collect();
|
||||
// Kill switches for an operator who suspects the fast path: `LELEKA_TOKENIZER_REFERENCE=1` runs the original
|
||||
// implementation only; `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` sizes the segment cache (0 turns it off).
|
||||
let reference_only =
|
||||
std::env::var_os("LELEKA_TOKENIZER_REFERENCE").is_some_and(|v| v == "1");
|
||||
let fast = if reference_only {
|
||||
None
|
||||
} else {
|
||||
fast::Fast::build(&vocab, &pairs, &byte_chars)
|
||||
};
|
||||
let cache_budget = std::env::var("LELEKA_TOKENIZER_SEGMENT_CACHE_MIB")
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.map_or(cache::DEFAULT_BUDGET, |mib| mib << 20);
|
||||
let decode_table = DecodeTable::new(&tokens, &char_bytes);
|
||||
Ok(Self {
|
||||
tokens,
|
||||
vocab,
|
||||
ranks,
|
||||
pattern,
|
||||
always,
|
||||
special,
|
||||
byte_chars,
|
||||
char_bytes,
|
||||
decode_table,
|
||||
fast,
|
||||
segments: cache::SegmentCache::new(cache_budget),
|
||||
})
|
||||
}
|
||||
|
||||
/// Bound the cache of segment encodings (bytes of text and ids; 0 turns it off). The default is
|
||||
/// [`DEFAULT_SEGMENT_CACHE_BYTES`].
|
||||
pub fn set_segment_cache_bytes(&self, budget: usize) {
|
||||
self.segments.set_budget(budget);
|
||||
}
|
||||
|
||||
/// (segments, approximate bytes) held by the segment cache.
|
||||
pub fn segment_cache_stats(&self) -> (usize, usize) {
|
||||
self.segments.stats()
|
||||
}
|
||||
|
||||
/// Whether the table-driven path is in use (it is for every real vocabulary).
|
||||
pub fn has_fast_path(&self) -> bool {
|
||||
self.fast.is_some()
|
||||
}
|
||||
|
||||
pub fn special_id(&self, token: &str) -> Option<u32> {
|
||||
self.vocab.get(token).copied()
|
||||
}
|
||||
|
||||
/// Token ids of `text`. Text between special tokens is looked up in the segment cache first; whatever the cache or the
|
||||
/// fast path does, the ids are the ones [`Tokenizer::encode_reference`] returns.
|
||||
pub fn encode(&self, text: &str, parse_special: bool) -> Result<Vec<u32>> {
|
||||
let mut ids = Vec::with_capacity(text.len() / 3 + 16);
|
||||
self.encode_into(text, parse_special, &mut ids)?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// [`Tokenizer::encode`] appending to `ids`.
|
||||
pub fn encode_into(&self, text: &str, parse_special: bool, ids: &mut Vec<u32>) -> Result<()> {
|
||||
let matcher = if parse_special {
|
||||
&self.special
|
||||
} else {
|
||||
&self.always
|
||||
};
|
||||
let mut scratch = fast::Scratch::default();
|
||||
let Some(matcher) = matcher else {
|
||||
return self.encode_segment(text, ids, &mut scratch);
|
||||
};
|
||||
let mut offset = 0;
|
||||
for found in matcher.search.find_iter(text) {
|
||||
self.encode_segment(&text[offset..found.start()], ids, &mut scratch)?;
|
||||
ids.push(matcher.ids[found.pattern().as_usize()]);
|
||||
offset = found.end();
|
||||
}
|
||||
self.encode_segment(&text[offset..], ids, &mut scratch)
|
||||
}
|
||||
|
||||
/// Text without special tokens: cache, then the fast path, then the string BPE.
|
||||
fn encode_segment(
|
||||
&self,
|
||||
text: &str,
|
||||
ids: &mut Vec<u32>,
|
||||
scratch: &mut fast::Scratch,
|
||||
) -> Result<()> {
|
||||
if text.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(fast) = &self.fast else {
|
||||
ids.extend(self.encode_plain(text)?);
|
||||
return Ok(());
|
||||
};
|
||||
let key = if text.len() >= cache::MIN_SEGMENT_BYTES {
|
||||
match self.segments.lookup(text) {
|
||||
(_, Some(hit)) => {
|
||||
ids.extend_from_slice(&hit);
|
||||
return Ok(());
|
||||
}
|
||||
(key, None) => Some(key),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mark = ids.len();
|
||||
let mut at = 0;
|
||||
while at < text.len() {
|
||||
let end = fast.classes.piece_end(text, at);
|
||||
fast.encode_piece(&text.as_bytes()[at..end], ids, scratch);
|
||||
at = end;
|
||||
}
|
||||
if let Some(key) = key {
|
||||
self.segments.insert(key, text, &ids[mark..]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The original implementation (regex pre-tokenizer, string BPE, no cache): the oracle the fast path is tested against.
|
||||
#[doc(hidden)]
|
||||
pub fn encode_reference(&self, text: &str, parse_special: bool) -> Result<Vec<u32>> {
|
||||
let matcher = if parse_special {
|
||||
&self.special
|
||||
} else {
|
||||
@@ -216,24 +403,28 @@ impl Tokenizer {
|
||||
}
|
||||
|
||||
pub fn decode_bytes(&self, ids: &[u32]) -> Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
let mut bytes = Vec::with_capacity(ids.len() * 4);
|
||||
for &id in ids {
|
||||
let token = self
|
||||
.tokens
|
||||
.get(id as usize)
|
||||
.ok_or("token ID exceeds vocabulary")?;
|
||||
for ch in token.chars() {
|
||||
bytes.push(
|
||||
*self
|
||||
.char_bytes
|
||||
.get(&ch)
|
||||
.ok_or("token is outside byte alphabet")?,
|
||||
);
|
||||
}
|
||||
bytes.extend_from_slice(self.decode_table.token(id)?);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Whether `ids` decode to exactly `text`, without building the decoded bytes. An id that cannot be decoded is `false`.
|
||||
pub fn decodes_to(&self, ids: &[u32], text: &[u8]) -> bool {
|
||||
let mut at = 0;
|
||||
for &id in ids {
|
||||
let Ok(token) = self.decode_table.token(id) else {
|
||||
return false;
|
||||
};
|
||||
if text.len() - at < token.len() || &text[at..at + token.len()] != token {
|
||||
return false;
|
||||
}
|
||||
at += token.len();
|
||||
}
|
||||
at == text.len()
|
||||
}
|
||||
|
||||
fn encode_plain(&self, text: &str) -> Result<Vec<u32>> {
|
||||
let mut ids = Vec::new();
|
||||
let mut offset = 0;
|
||||
@@ -458,16 +649,17 @@ mod tests {
|
||||
ranks.insert(pair_key("a", "b"), 1);
|
||||
ranks.insert(pair_key("b", "a"), 2);
|
||||
ranks.insert(pair_key("ab", "a"), 3);
|
||||
let (byte_chars, char_bytes) = byte_alphabet();
|
||||
let (byte_chars, _) = byte_alphabet();
|
||||
let tokenizer = Tokenizer {
|
||||
tokens: vec![],
|
||||
vocab: HashMap::new(),
|
||||
ranks,
|
||||
pattern: Regex::new(QWEN35_PATTERN).unwrap(),
|
||||
always: None,
|
||||
special: None,
|
||||
byte_chars,
|
||||
char_bytes,
|
||||
decode_table: DecodeTable::empty(),
|
||||
fast: None,
|
||||
segments: cache::SegmentCache::new(0),
|
||||
};
|
||||
for word in [
|
||||
"aba",
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
//! The fast path (hand-written pre-tokenizer, id-based BPE, segment cache, table decode) against the original
|
||||
//! implementation kept in the crate as `encode_reference` / `pre_tokenize`.
|
||||
//!
|
||||
//! * the scanner splits every Unicode scalar value, in many contexts, exactly like the regex engine;
|
||||
//! * fuzzed text (white space of every kind, line breaks, contractions, marks, scripts, digits, emoji) splits identically;
|
||||
//! * `encode` equals `encode_reference` with and without special parsing, on a cold cache, a warm cache and a cache that is
|
||||
//! too small to hold anything;
|
||||
//! * with real assets (`LELEKA_TOKENIZER_DIR`, `LELEKA_TOKENIZER_TEXTS`: a directory of UTF-8 files) the same holds on real prompts.
|
||||
use leleka_tokenizer::{Tokenizer, pre_tokenize, pre_tokenize_fast};
|
||||
use serde_json::Value;
|
||||
|
||||
fn golden() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/tokenizer_oracle.json")).unwrap()
|
||||
}
|
||||
|
||||
fn strings(value: &Value) -> Vec<String> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tokenizer() -> Tokenizer {
|
||||
let golden = golden();
|
||||
let types = golden["token_types"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap() as u32)
|
||||
.collect();
|
||||
Tokenizer::from_vocabulary(
|
||||
"gpt2",
|
||||
"qwen35",
|
||||
strings(&golden["tokens"]),
|
||||
strings(&golden["merges"]),
|
||||
Some(types),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
const ATOMS: &[&str] = &[
|
||||
"a",
|
||||
"b",
|
||||
"e",
|
||||
"l",
|
||||
"s",
|
||||
"t",
|
||||
"x",
|
||||
"Z",
|
||||
"ll",
|
||||
"re",
|
||||
"ve",
|
||||
"he",
|
||||
"xx",
|
||||
"the",
|
||||
"Hello",
|
||||
" ",
|
||||
" ",
|
||||
" ",
|
||||
"\t",
|
||||
"\n",
|
||||
"\r",
|
||||
"\r\n",
|
||||
"\n\n",
|
||||
" \n",
|
||||
"\n ",
|
||||
"\u{b}",
|
||||
"\u{c}",
|
||||
"\u{85}",
|
||||
"\u{a0}",
|
||||
"\u{1680}",
|
||||
"\u{2003}",
|
||||
"\u{2028}",
|
||||
"\u{2029}",
|
||||
"\u{202f}",
|
||||
"\u{3000}",
|
||||
"\u{1c}",
|
||||
"\u{1f}",
|
||||
"'",
|
||||
"'s",
|
||||
"'S",
|
||||
"'t",
|
||||
"'T",
|
||||
"'re",
|
||||
"'RE",
|
||||
"'ve",
|
||||
"'m",
|
||||
"'ll",
|
||||
"'LL",
|
||||
"'d",
|
||||
"'x",
|
||||
"''",
|
||||
"0",
|
||||
"7",
|
||||
"42",
|
||||
"\u{660}",
|
||||
"\u{2160}",
|
||||
"\u{b2}",
|
||||
"\u{bd}",
|
||||
"-",
|
||||
".",
|
||||
",",
|
||||
"!",
|
||||
"?",
|
||||
"_",
|
||||
"(",
|
||||
")",
|
||||
"{",
|
||||
"}",
|
||||
"[",
|
||||
"]",
|
||||
"\"",
|
||||
"\\",
|
||||
"/",
|
||||
"<",
|
||||
">",
|
||||
"=",
|
||||
"+",
|
||||
"*",
|
||||
"#",
|
||||
"$",
|
||||
"%",
|
||||
"&",
|
||||
"@",
|
||||
"~",
|
||||
"^",
|
||||
"|",
|
||||
"`",
|
||||
";",
|
||||
":",
|
||||
"e\u{301}",
|
||||
"\u{301}",
|
||||
"\u{20dd}",
|
||||
"\u{200d}",
|
||||
"\u{200b}",
|
||||
"\u{feff}",
|
||||
"\u{ad}",
|
||||
"\u{e9}",
|
||||
"\u{df}",
|
||||
"\u{3b1}",
|
||||
"\u{4e2d}",
|
||||
"\u{6587}",
|
||||
"\u{3042}",
|
||||
"\u{ac00}",
|
||||
"\u{627}",
|
||||
"\u{5d0}",
|
||||
"\u{905}",
|
||||
"\u{e01}",
|
||||
"\u{1f600}",
|
||||
"\u{1f1fa}\u{1f1f8}",
|
||||
"\u{10000}",
|
||||
"\u{e000}",
|
||||
"\u{10ffff}",
|
||||
"<|im_end|>",
|
||||
"<tool_response>",
|
||||
];
|
||||
|
||||
fn fuzz_text(rng: &mut Rng) -> String {
|
||||
let mut text = String::new();
|
||||
for _ in 0..rng.below(14) {
|
||||
text.push_str(ATOMS[rng.below(ATOMS.len())]);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn assert_same_split(text: &str) {
|
||||
let regex = pre_tokenize(text).unwrap();
|
||||
let fast = pre_tokenize_fast(text);
|
||||
assert_eq!(regex, fast, "text {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_splits_every_scalar_value_like_the_regex_in_many_contexts() {
|
||||
let contexts: &[(&str, &str)] = &[
|
||||
("", ""),
|
||||
("a", "b"),
|
||||
(" ", ""),
|
||||
("", " "),
|
||||
("\n", ""),
|
||||
("", "\n"),
|
||||
("1", ""),
|
||||
("'", ""),
|
||||
(" ", "x"),
|
||||
(" ", "x"),
|
||||
("x", " "),
|
||||
("\n ", "\n"),
|
||||
("e", "\u{301}"),
|
||||
];
|
||||
let mut buffer = String::new();
|
||||
for code in 0..=0x10FFFFu32 {
|
||||
let Some(c) = char::from_u32(code) else {
|
||||
continue;
|
||||
};
|
||||
for (before, after) in contexts {
|
||||
buffer.clear();
|
||||
buffer.push_str(before);
|
||||
buffer.push(c);
|
||||
buffer.push_str(after);
|
||||
assert_same_split(&buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_splits_fuzzed_text_like_the_regex() {
|
||||
let mut rng = Rng(0x9E3779B97F4A7C15);
|
||||
for _ in 0..400_000 {
|
||||
let text = fuzz_text(&mut rng);
|
||||
assert_same_split(&text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_handles_the_regex_corner_cases() {
|
||||
for text in [
|
||||
"",
|
||||
" ",
|
||||
" ",
|
||||
"\n",
|
||||
" \n",
|
||||
" \n x",
|
||||
"\n\n\n",
|
||||
"a b",
|
||||
"a \n b",
|
||||
"x \n\n y",
|
||||
"don't stop",
|
||||
"DON'T",
|
||||
"it'S fine 'RE 'vE 'Ll 'D 'M",
|
||||
"'",
|
||||
"''s",
|
||||
"'ss",
|
||||
"$100.50!",
|
||||
"-5",
|
||||
" 5",
|
||||
" 5",
|
||||
"\u{a0}word",
|
||||
"\t\tword",
|
||||
"word\t",
|
||||
"\u{301}\u{301}x",
|
||||
"e\u{301}\u{301} combining",
|
||||
"tail ",
|
||||
"tail\n ",
|
||||
"tail \r\n ",
|
||||
] {
|
||||
assert_same_split(text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_equals_the_reference_cold_warm_and_without_a_cache() {
|
||||
let tokenizer = tokenizer();
|
||||
assert!(tokenizer.has_fast_path());
|
||||
let mut rng = Rng(0x1234_5678_9ABC_DEF1);
|
||||
let golden = golden();
|
||||
let mut texts: Vec<String> = golden["cases"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|case| case["text"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
for _ in 0..3000 {
|
||||
// long enough that segments reach the cache threshold
|
||||
let mut text = String::new();
|
||||
for _ in 0..rng.below(60) {
|
||||
text.push_str(&fuzz_text(&mut rng));
|
||||
}
|
||||
texts.push(text);
|
||||
}
|
||||
for budget in [leleka_tokenizer::DEFAULT_SEGMENT_CACHE_BYTES, 4096, 0] {
|
||||
tokenizer.set_segment_cache_bytes(budget);
|
||||
for pass in 0..2 {
|
||||
for text in &texts {
|
||||
for special in [false, true] {
|
||||
assert_eq!(
|
||||
tokenizer.encode(text, special).unwrap(),
|
||||
tokenizer.encode_reference(text, special).unwrap(),
|
||||
"budget {budget} pass {pass} special {special} text {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_hit_needs_the_same_text() {
|
||||
let tokenizer = tokenizer();
|
||||
let long = "xx ".repeat(100);
|
||||
let other = "xx ".repeat(99) + "xy ";
|
||||
let first = tokenizer.encode(&long, false).unwrap();
|
||||
let again = tokenizer.encode(&long, false).unwrap();
|
||||
assert_eq!(first, again);
|
||||
assert_eq!(
|
||||
tokenizer.encode(&other, false).unwrap(),
|
||||
tokenizer.encode_reference(&other, false).unwrap()
|
||||
);
|
||||
assert_ne!(first, tokenizer.encode(&other, false).unwrap());
|
||||
let (segments, bytes) = tokenizer.segment_cache_stats();
|
||||
assert!(segments >= 2 && bytes > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_helpers_agree() {
|
||||
let tokenizer = tokenizer();
|
||||
let text = "Hello, world! \u{4e2d}\u{6587} \u{1f600}<|im_end|>";
|
||||
let ids = tokenizer.encode(text, true).unwrap();
|
||||
assert_eq!(tokenizer.decode_bytes(&ids).unwrap(), text.as_bytes());
|
||||
assert!(tokenizer.decodes_to(&ids, text.as_bytes()));
|
||||
assert!(!tokenizer.decodes_to(&ids, b"Hello"));
|
||||
assert!(!tokenizer.decodes_to(&ids[..ids.len() - 1], text.as_bytes()));
|
||||
assert!(!tokenizer.decodes_to(&[u32::MAX], b""));
|
||||
assert!(tokenizer.decode_bytes(&[u32::MAX]).is_err());
|
||||
}
|
||||
|
||||
/// Real vocabulary and real prompts: every file of `LELEKA_TOKENIZER_TEXTS` (and the whole directory joined) encodes to the
|
||||
/// reference ids, cold and warm, and each prefix cut at a message boundary encodes to a prefix of the full ids' tokens
|
||||
/// plus the tail (the cache never changes a boundary).
|
||||
#[test]
|
||||
fn real_assets_encode_like_the_reference() {
|
||||
let (Some(assets), Some(texts)) = (
|
||||
std::env::var_os("LELEKA_TOKENIZER_DIR"),
|
||||
std::env::var_os("LELEKA_TOKENIZER_TEXTS"),
|
||||
) else {
|
||||
eprintln!("LELEKA_TOKENIZER_DIR / LELEKA_TOKENIZER_TEXTS not set: skipped");
|
||||
return;
|
||||
};
|
||||
let tokenizer = Tokenizer::from_assets(std::path::Path::new(&assets)).unwrap();
|
||||
assert!(tokenizer.has_fast_path());
|
||||
let mut files: Vec<_> = std::fs::read_dir(texts)
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path())
|
||||
.filter(|path| path.is_file())
|
||||
.collect();
|
||||
files.sort();
|
||||
assert!(!files.is_empty());
|
||||
for path in files {
|
||||
let text = String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned();
|
||||
let reference = tokenizer.encode_reference(&text, true).unwrap();
|
||||
for pass in 0..2 {
|
||||
assert_eq!(
|
||||
tokenizer.encode(&text, true).unwrap(),
|
||||
reference,
|
||||
"{} pass {pass}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
assert!(tokenizer.decodes_to(&reference, text.as_bytes()));
|
||||
assert_eq!(
|
||||
tokenizer.encode(&text, false).unwrap(),
|
||||
tokenizer.encode_reference(&text, false).unwrap(),
|
||||
"{} plain",
|
||||
path.display()
|
||||
);
|
||||
// the pre-tokenizer on the real text, piece for piece
|
||||
assert_eq!(
|
||||
pre_tokenize(&text).unwrap(),
|
||||
pre_tokenize_fast(&text),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
eprintln!(
|
||||
"{}: {} bytes -> {} tokens ok",
|
||||
path.display(),
|
||||
text.len(),
|
||||
reference.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! `control-plane/examples/cp_replay.rs` with the real gRPC hop: the instant engine sits behind the real `RuntimeServer` and the
|
||||
//! control plane reaches it through `GrpcBackend` (snapshot RPC, a ~600 KB prompt string over HTTP/2, the event stream back), so
|
||||
//! the gap between the in-process and the gRPC run is the contract's transport and server-side handling, not the engine.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run --release -p strata-desktop-core --example cp_replay_grpc -- TOKENIZER_DIR SESSION.json [same options]
|
||||
//! ```
|
||||
#[path = "../../control-plane/examples/cp_replay.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod replay;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use leleka_backend_api as api;
|
||||
use leleka_runtime_client::{
|
||||
backend::GrpcBackend,
|
||||
client::RuntimeClient,
|
||||
convert::{config_to_proto, descriptor_to_proto},
|
||||
proto,
|
||||
};
|
||||
use replay::{EngineMarks, InstantBackend};
|
||||
use strata_desktop_core::runtime_rpc::RuntimeServer;
|
||||
|
||||
async fn grpc_backend(marks: Arc<EngineMarks>) -> Box<dyn api::Backend> {
|
||||
let token = format!(
|
||||
"fixture-runtime-credential-{:x}",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
);
|
||||
let server =
|
||||
RuntimeServer::new(Box::new(InstantBackend::new(marks)), token.clone()).expect("server");
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
let _ = server.serve(listener, std::future::pending::<()>()).await;
|
||||
});
|
||||
// what `leleka-cli load` does
|
||||
let mut client = RuntimeClient::connect(address, token.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let epoch = client.snapshot().await.unwrap().epoch;
|
||||
client
|
||||
.load(proto::LoadRequest {
|
||||
operation_id: uuid_like(),
|
||||
expected_epoch: epoch,
|
||||
model: Some(descriptor_to_proto(
|
||||
&api::scripted::ScriptedEngine::fixture_descriptor(),
|
||||
)),
|
||||
config: Some(config_to_proto(&api::RuntimeConfig {
|
||||
load_config_version: api::LOAD_CONFIG_VERSION,
|
||||
inference_mode: api::InferenceMode::Native,
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: false,
|
||||
})),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
while !client.snapshot().await.unwrap().model_ready {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
Box::new(GrpcBackend::new(
|
||||
tokio::runtime::Handle::current(),
|
||||
address,
|
||||
token,
|
||||
))
|
||||
}
|
||||
|
||||
fn uuid_like() -> String {
|
||||
let n = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
format!(
|
||||
"{:08x}-0000-4000-8000-{:012x}",
|
||||
(n >> 32) as u32,
|
||||
n & 0xffff_ffff_ffff
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
replay::run(std::env::args().collect(), grpc_backend).await;
|
||||
}
|
||||
@@ -212,8 +212,11 @@ impl RuntimeServer {
|
||||
.max_decoding_message_size(MESSAGE_LIMIT)
|
||||
.max_encoding_message_size(MESSAGE_LIMIT),
|
||||
)
|
||||
// `serve_with_incoming*` ignores the builder's `tcp_nodelay`, and Nagle's algorithm plus the client's delayed ACK
|
||||
// holds every small response frame (the accept of a generation, each text delta, the terminal) for up to ~40 ms
|
||||
// on loopback: the sockets are accepted here, so set TCP_NODELAY here.
|
||||
.serve_with_incoming_shutdown(
|
||||
tokio_stream::wrappers::TcpListenerStream::new(listener),
|
||||
tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true)),
|
||||
shutdown,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
# Host-side request latency: control plane, tokenizer, gRPC (`claude/cp-latency`)
|
||||
|
||||
Status: measured and fixed on the host side of a request (everything before the engine starts the prefill and after tokens
|
||||
leave it). The numbers below are a paired A/B of the code before and after, on the same workload, with an *instant* engine
|
||||
(it answers the moment it has the prompt), so they are the cost of the host path only and say nothing about the engine, the
|
||||
model or its quality. Token ids and prompt text are bit-identical to the old path on all the data checked (section 4). The
|
||||
real-engine run (section 6) is queued as job `9f1-cp-live-ab` and is not part of the numbers until it ran.
|
||||
|
||||
Branch `claude/cp-latency`, cut from `claude/port-gpu-bringup` at `cfe0a02`. The baseline for every "before" is `dbf487b`
|
||||
(the original request path plus the env-gated stage spans and the replay driver, nothing else); the "after" is the branch head.
|
||||
|
||||
## 1. What was measured and how
|
||||
|
||||
**Workload.** The engine side capture of two real Codex sessions (`capture/943b-codex-ttt`, `capture/945-codex-crm`: the
|
||||
rendered prompt token ids of every request) was inverted into the Responses requests Codex sends: `scripts/cp/synth_session.py`
|
||||
decodes the prompt with the pinned vocabulary and turns the system block into `instructions` and `tools`, the user turns into
|
||||
messages, the assistant turns into `reasoning` / `message` / `function_call` items and the `<tool_response>` turns into
|
||||
`function_call_output` items. The history of the CRM session (123,239 tokens) is extended with the second session (call ids and
|
||||
text tagged so no two items are identical) to reach 196k tokens. Check: rendering and tokenizing the synthesized request for the
|
||||
last captured round gives **exactly the 123,239 captured prompt ids** (and 82,315 for the other session), through the real HTTP
|
||||
layer. The captures and the synthesized sessions stay outside Git.
|
||||
|
||||
**Driver.** `control-plane/examples/cp_replay.rs`: real axum router, real `backend_worker`, real tokenizer, real loopback HTTP
|
||||
(keep-alive, SSE), request bodies exactly as Codex sends them (`reasoning.effort` medium, `store: false`, 12 tools, `stream`).
|
||||
For each history size (20k, 60k, 120k, 180k tokens, picked by the server's own `/v1/responses/input_tokens`) it replays 16
|
||||
consecutive rounds of the session on a fresh stack: turn 0 is **cold** (nothing cached), turns 1.. are the **steady state** of a
|
||||
real session (each request is the previous history plus a few new items). Two engines behind it:
|
||||
|
||||
* `proc`: an in-process engine implementing `leleka_backend_api::Backend` (answers at once with a 420-token reasoning + tool-call
|
||||
reply, 24-byte deltas 1 ms apart after a 20 ms wait, so the response's opening events have left before the first token);
|
||||
* `grpc`: the same engine behind the real `RuntimeServer` and the control plane's `GrpcBackend`
|
||||
(`desktop-core/examples/cp_replay_grpc.rs`): snapshot RPC, a 640 KB prompt string over HTTP/2 on loopback, the event stream back.
|
||||
|
||||
**Metrics** (ms per request, warm turns, p50 / p95): `pre_engine` = the client finished sending -> the engine has the prompt (body
|
||||
read, JSON parse, validation, chat template, tokenization, queue, prompt text for the engine, the engine call); `first_event` = the
|
||||
engine's first text delta -> its SSE event at the client; `tail` = the engine's terminal event -> `response.completed` at the client.
|
||||
The stage table comes from the spans (`STRATA_STAGE_TRACE=1`, off by default: one relaxed atomic load per span;
|
||||
`STRATA_STAGE_TRACE=log` writes `stage <name> <ms> t_unix_ms=<end>` lines to stderr, which `scripts/cp/live_report.py` joins with a
|
||||
client's timings).
|
||||
|
||||
**Noise.** The laptop (WSL2 Ubuntu 24.04, i9-11900H 8C/16T, rustc 1.99.0, other agents building and running jobs on it) is shared.
|
||||
Base and new runs alternate (`scripts/cp/run-ab.sh`), five repeats, and each cell is the *minimum over the repeats* of that
|
||||
repeat's p50 (resp. p95): the least disturbed estimate of each build. Raw per-turn rows are in the result JSONs the driver writes.
|
||||
|
||||
## 2. What was found and what changed (largest first)
|
||||
|
||||
At a 180k-token history, warm turn, `grpc` engine, per request, before -> after:
|
||||
|
||||
| # | finding | before -> after |
|
||||
| --- | --- | --- |
|
||||
| 1 | **The whole history was tokenized twice before the engine saw it.** The HTTP layer encoded the rendered prompt (`tokenize`), and the text-level worker then decoded those ids back to text and encoded that again to prove the round trip (`worker_prompt_text`), because the engine contract carries text. The tokenizer (regex pre-tokenizer + string BPE) ran at 1.0-1.3 Mtok/s. | `tokenize` 177 -> 1.0 ms, `worker_prompt_text` 187 -> 0.95 ms |
|
||||
| 2 | **A new tokenizer fast path with a segment cache** (`crates/tokenizer`): a hand-written scanner for the pinned pre-tokenizer pattern (Unicode classes read out of `regex-syntax`, the crate the regex engine uses), byte-level BPE over token ids with a rank table instead of re-built strings, and a bounded cache of the ids of text between special tokens, keyed by the exact text (a hit is verified byte for byte). Uncached 11.5 Mtok/s (9x); a repeated history costs a hash and a memcpy: 123k tokens in 0.24 ms against 100 ms. The agent resends its whole history every turn, so every turn after the first only tokenizes its new tail. The same crate runs in the engine process (`prepare_prompt` encodes the prompt string again, on every request, before the prefill), so that request-path copy of the cost goes away there too. | cold 123k tokens 100 -> 11 ms (the whole cold `pre_engine` at 180k: 340 -> 24 ms), warm 0.24 ms |
|
||||
| 3 | **The runtime gRPC server had Nagle on.** `serve_with_incoming_shutdown` ignores the builder's `tcp_nodelay` and `TcpListenerStream` does not set it, so every small response frame (the accept of a generation, the first delta, the terminal) waited for the client's delayed ACK. `TcpIncoming::with_nodelay(true)` in `desktop-core/src/runtime_rpc.rs`. | `engine_start` 42 -> 2.2, first token to the client 19.2 -> 0.4, completion 36.7 -> 1.4 |
|
||||
| 4 | **Chat template over the whole history**: three copies of every message (`Owned`, `Json`, minijinja `Value`) and the Jinja loop. For this template every message after the leading system messages renders to text that depends on that message alone (`preserve_thinking` is never set), so only the head (tools, reasoning instruction, merged system text) goes through Jinja and the messages are written directly (`prompt::render_native`; `STRATA_REFERENCE_RENDER=1` goes back to the template). | `render` 2.4 -> 0.98 |
|
||||
| 5 | Tool-schema validation compiled a JSON-schema validator per tool, three times per request (parse, initial envelope, final response). Memoized by the schema text. | `request_validate` 0.26 -> 0.07 |
|
||||
| 6 | The two per-generation log lines were written before the engine call / before the terminal event reached the client, under the stderr lock. Their timestamps are unchanged; the write now follows. | off the response path |
|
||||
| 7 | `TCP_NODELAY` on the HTTP listener (SSE events and small responses must not wait for an ACK). | not measurable on loopback; correct for a LAN |
|
||||
|
||||
Not changed, measured: body read + JSON parse 1.4 ms (a borrowed/typed parse would save about 1 ms and needs the validation error
|
||||
texts re-proved), the snapshot RPC before every generation 0.7 ms (it is a deliberate identity check), the 640 KB prompt over HTTP/2
|
||||
about 1.6 ms (frame size and window settings made no difference), `response.created` is sent after tokenization (Codex does not wait
|
||||
for it). Per streamed token the host spends about 12 us (decode, event JSON, SSE), 0.08 % of one core at 65 tok/s: flush batching per
|
||||
engine round would change the event contract for nothing.
|
||||
|
||||
## 3. Results
|
||||
|
||||
Headline, 180k-token history, warm turn (steady state of a session), p50 (p95), ms, minimum over 5 interleaved repeats:
|
||||
|
||||
| | before (`dbf487b`) | after |
|
||||
| --- | --- | --- |
|
||||
| `pre_engine`, engine behind the real gRPC hop | 376 (398) | **6.5 (6.8)** |
|
||||
| `pre_engine`, in-process engine | 347 (371) | 5.2 (5.6) |
|
||||
| `first_event` (engine's first delta -> client), gRPC | 19.2 (20.0) | 0.39 (0.47) |
|
||||
| `tail` (engine's terminal -> `response.completed`), gRPC | 36.7 (41.6) | 1.44 (1.53) |
|
||||
| `pre_engine`, first request of a session (cold), gRPC | 340 | 24 |
|
||||
|
||||
The same at the other sizes (`pre_engine`, gRPC, warm p50): 20k 90 -> 2.9, 60k 149 -> 3.8, 120k 270 -> 5.3. The cost used to grow
|
||||
with the history (about 2 ms per 1k tokens); it now grows by about 0.02 ms per 1k tokens. Per request that is roughly 370 ms
|
||||
before the engine plus about 55 ms of gRPC stalls around the first token and the completion, at 180k.
|
||||
|
||||
Full tables as printed by `scripts/cp/summarize.py` (p50 / p95 per cell; stage names as in section 1):
|
||||
|
||||
#### in-process instant engine
|
||||
|
||||
| metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| pre_engine_ms | 76.32 / 94.96 | 2.36 / 2.65 | 137.11 / 155.63 | 3.06 / 3.32 | 264.87 / 287.44 | 4.40 / 4.92 | 346.77 / 370.86 | 5.18 / 5.64 |
|
||||
| first_event_ms | 0.30 / 0.38 | 0.24 / 0.34 | 0.31 / 0.38 | 0.28 / 0.36 | 0.38 / 0.47 | 0.23 / 0.33 | 0.44 / 0.49 | 0.29 / 0.39 |
|
||||
| tail_ms | 1.32 / 1.37 | 1.08 / 1.17 | 1.44 / 1.51 | 1.10 / 1.24 | 1.53 / 1.65 | 1.24 / 1.35 | 1.60 / 1.75 | 1.31 / 1.37 |
|
||||
|
||||
| stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| http_body_json | 0.30 / 0.36 | 0.35 / 0.43 | 0.56 / 0.71 | 0.59 / 0.69 | 1.14 / 1.22 | 1.08 / 1.15 | 1.35 / 1.43 | 1.32 / 1.53 |
|
||||
| request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.06 | 0.09 / 0.11 | 0.09 / 0.10 | 0.12 / 0.15 | 0.12 / 0.15 |
|
||||
| request_validate | 0.22 / 0.24 | 0.07 / 0.08 | 0.23 / 0.24 | 0.07 / 0.07 | 0.24 / 0.27 | 0.06 / 0.07 | 0.25 / 0.28 | 0.07 / 0.07 |
|
||||
| render | 0.64 / 0.71 | 0.44 / 0.47 | 1.09 / 1.21 | 0.55 / 0.61 | 1.81 / 1.91 | 0.82 / 0.90 | 2.31 / 2.53 | 0.99 / 1.02 |
|
||||
| tokenize | 36.75 / 42.84 | 0.46 / 0.61 | 65.94 / 73.67 | 0.62 / 0.73 | 125.56 / 137.45 | 0.91 / 1.31 | 163.90 / 175.74 | 1.05 / 1.23 |
|
||||
| worker_prompt_text | 37.86 / 47.49 | 0.35 / 0.40 | 67.95 / 78.76 | 0.48 / 0.54 | 133.91 / 142.57 | 0.74 / 0.85 | 176.74 / 188.26 | 0.97 / 1.07 |
|
||||
| engine_start | 0.38 / 0.43 | 0.28 / 0.31 | 0.49 / 0.53 | 0.39 / 0.42 | 0.71 / 0.77 | 0.65 / 0.67 | 0.90 / 0.97 | 0.80 / 0.86 |
|
||||
| post_decode | 0.16 / 0.19 | 0.08 / 0.10 | 0.17 / 0.20 | 0.08 / 0.10 | 0.18 / 0.19 | 0.09 / 0.10 | 0.18 / 0.20 | 0.09 / 0.10 |
|
||||
| post_assemble | 0.67 / 0.72 | 0.53 / 0.57 | 0.70 / 0.74 | 0.54 / 0.59 | 0.70 / 0.76 | 0.55 / 0.60 | 0.70 / 0.75 | 0.56 / 0.63 |
|
||||
| post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 |
|
||||
| delta_retokenize | 1.92 / 2.29 | 0.50 / 0.59 | 2.00 / 2.25 | 0.44 / 0.55 | 2.11 / 2.29 | 0.47 / 0.54 | 1.97 / 2.33 | 0.49 / 0.61 |
|
||||
|
||||
cold first request (ms, min over repeats):
|
||||
base pre_engine cold: 20k=57.0, 60k=120.6, 120k=235.5, 180k=317.4
|
||||
new pre_engine cold: 20k=5.6, 60k=9.2, 120k=16.5, 180k=22.8
|
||||
|
||||
#### instant engine behind the real gRPC runtime server
|
||||
|
||||
| metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| pre_engine_ms | 89.96 / 100.84 | 2.93 / 3.38 | 148.72 / 166.45 | 3.81 / 4.16 | 269.81 / 296.34 | 5.34 / 6.01 | 376.19 / 398.10 | 6.50 / 6.84 |
|
||||
| first_event_ms | 19.30 / 20.18 | 0.36 / 0.44 | 18.73 / 19.91 | 0.32 / 0.40 | 18.92 / 20.25 | 0.34 / 0.41 | 19.18 / 20.01 | 0.39 / 0.47 |
|
||||
| tail_ms | 37.11 / 41.51 | 1.18 / 1.34 | 34.79 / 40.25 | 1.21 / 1.30 | 35.73 / 42.66 | 1.31 / 1.40 | 36.65 / 41.56 | 1.44 / 1.53 |
|
||||
|
||||
| stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| http_body_json | 0.31 / 0.38 | 0.32 / 0.43 | 0.58 / 0.71 | 0.58 / 0.66 | 1.07 / 1.23 | 1.00 / 1.17 | 1.39 / 1.67 | 1.35 / 1.52 |
|
||||
| request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.05 | 0.09 / 0.11 | 0.09 / 0.10 | 0.13 / 0.16 | 0.12 / 0.15 |
|
||||
| request_validate | 0.22 / 0.26 | 0.07 / 0.07 | 0.22 / 0.24 | 0.06 / 0.07 | 0.23 / 0.28 | 0.07 / 0.07 | 0.26 / 0.29 | 0.07 / 0.08 |
|
||||
| render | 0.68 / 0.78 | 0.42 / 0.47 | 1.06 / 1.16 | 0.56 / 0.64 | 1.85 / 1.99 | 0.84 / 0.88 | 2.37 / 2.50 | 0.98 / 1.04 |
|
||||
| tokenize | 40.90 / 45.94 | 0.46 / 0.65 | 70.57 / 79.79 | 0.63 / 0.76 | 127.94 / 148.69 | 0.90 / 1.29 | 176.81 / 202.94 | 1.03 / 1.32 |
|
||||
| worker_prompt_text | 43.00 / 50.17 | 0.34 / 0.43 | 75.03 / 84.18 | 0.47 / 0.53 | 135.32 / 149.33 | 0.76 / 0.84 | 186.68 / 203.86 | 0.95 / 1.06 |
|
||||
| engine_start | 1.74 / 40.88 | 1.08 / 1.22 | 39.36 / 41.22 | 1.34 / 1.57 | 40.51 / 42.04 | 1.77 / 1.95 | 41.66 / 42.40 | 2.15 / 2.47 |
|
||||
| post_decode | 0.16 / 0.19 | 0.08 / 0.09 | 0.17 / 0.21 | 0.08 / 0.09 | 0.15 / 0.18 | 0.08 / 0.10 | 0.16 / 0.20 | 0.09 / 0.11 |
|
||||
| post_assemble | 0.67 / 0.78 | 0.56 / 0.59 | 0.69 / 0.83 | 0.54 / 0.57 | 0.70 / 0.83 | 0.55 / 0.58 | 0.73 / 0.78 | 0.56 / 0.59 |
|
||||
| post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 |
|
||||
| delta_retokenize | 1.97 / 2.17 | 0.53 / 0.58 | 2.07 / 2.33 | 0.45 / 0.49 | 1.94 / 2.12 | 0.49 / 0.54 | 1.99 / 2.24 | 0.54 / 0.57 |
|
||||
|
||||
cold first request (ms, min over repeats):
|
||||
base pre_engine cold: 20k=61.6, 60k=127.0, 120k=253.7, 180k=340.2
|
||||
new pre_engine cold: 20k=6.5, 60k=10.1, 120k=17.6, 180k=23.9
|
||||
|
||||
|
||||
## 4. Equivalence
|
||||
|
||||
* `cp_replay --verify` replays **every round** of the synthesized sessions (135 rounds, 9k-196k tokens, and 52 rounds of the other
|
||||
session) through the real HTTP layer and checks: the ids of the production path equal `Tokenizer::encode_reference` (the original
|
||||
implementation) on the prompt the engine received; the ids decode back to that prompt; `/v1/responses/input_tokens` counts them;
|
||||
the round whose history is the captured request reproduces the **captured prompt ids** (123,239 and 82,315 tokens) exactly.
|
||||
The per-round `PROMPT round tokens prompt_fnv ids_fnv` lines of the baseline build, of the new build and of the new build with
|
||||
`STRATA_REFERENCE_RENDER=1` (Jinja for every prompt) are byte-identical (md5 of the 135 lines equal in all three).
|
||||
* `crates/tokenizer/tests/fast_path.rs`: the scanner splits every Unicode scalar value in 13 contexts and 400,000 fuzzed texts
|
||||
like the regex; `encode` equals `encode_reference` for ~3,000 fuzzed texts and the oracle cases on a cold cache, a warm cache and
|
||||
a cache too small to hold anything; real prompts (`LELEKA_TOKENIZER_DIR` / `LELEKA_TOKENIZER_TEXTS`) encode like the reference
|
||||
cold and warm; the existing Python-oracle test (`oracle_differential.rs`) still passes.
|
||||
* `prompt::native_render_equals_the_template`: 4,000 random conversations (whitespace of every kind at the edges, empty contents,
|
||||
template-looking and special-token text, with and without system messages and tools, every effort) render to the same bytes (or
|
||||
the same error) both ways; the ten golden chat cases pass.
|
||||
* `strata-control`: all 282 unit tests and every integration test, including the golden HTTP surface and the full-chain
|
||||
`backend_worker_http` suite (a new test covers the prompt-text pass-through: the text is sent only if the ids decode to it, else
|
||||
the old check runs); `strata-desktop-core` (the full chain with the real `RuntimeServer`), `leleka-runtime-client`,
|
||||
`leleka-backend-api`, `leleka-serving-policy`, and `leleka-runtime --lib` (510) pass.
|
||||
* Kill switches: `LELEKA_TOKENIZER_REFERENCE=1` (original tokenizer only), `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` (0 = no cache; default
|
||||
64, both engine and control plane), `STRATA_REFERENCE_RENDER=1`.
|
||||
|
||||
## 5. How to reproduce
|
||||
|
||||
```text
|
||||
python3 scripts/cp/synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ OUT.json [--extend CAPTURE2 LAST2]
|
||||
cargo run --release -p strata-control --example cp_replay -- TOKENIZER_DIR OUT.json [--sizes 20000,60000] [--turns 16] [--out r.json]
|
||||
cargo run --release -p strata-desktop-core --example cp_replay_grpc -- TOKENIZER_DIR OUT.json # real gRPC hop
|
||||
cp_replay TOKENIZER_DIR OUT.json --verify [--verify-step 1] # equivalence
|
||||
scripts/cp/run-ab.sh BASE_TREE NEW_TREE TOKENIZER_DIR OUT.json OUT_DIR 5 --turns 16; python3 scripts/cp/summarize.py OUT_DIR
|
||||
LELEKA_TOKENIZER_DIR=... LELEKA_TOKENIZER_TEXTS=... cargo test --release -p leleka-tokenizer
|
||||
```
|
||||
|
||||
## 6. Real engine
|
||||
|
||||
Job `scripts/e2e/codex/jobs/9f1-cp-live-ab.sh` (queue name `9f1-cp-live-ab`): one model load, the current `strata-next` on :8081 and the
|
||||
baseline `strata-next` on :8082 in front of the same engine (the new `leleka-inference`), one synthesized Codex session of about
|
||||
100k tokens, 20 consecutive requests (`max_output_tokens` 64) sent alternately through the two so the engine sees the same prompt
|
||||
sequence either way. `scripts/cp/live_report.py` joins the client's timings with both servers' stage logs and the engine's
|
||||
`generation done` lines: client time to first token = pre-engine host time + engine time + post time. Queued behind the other jobs of `holder2/jobs` (23 pending when submitted); the result is appended here when it ran.
|
||||
|
||||
## 7. What remains
|
||||
|
||||
* The engine contract carries the prompt as text, so the engine still tokenizes it (now a cache hit for a repeated history). Carrying
|
||||
the ids, or just the new tail plus a prefix digest, would remove the 640 KB string and the text/ids round trip; it is a contract change
|
||||
(proto, `RuntimeServer`, the engine), not made here. `runtime_rpc.rs` refuses a prompt above 1 MiB: at 3.76 bytes per token that is
|
||||
about 280k tokens, close to the 262k context for code-heavy text.
|
||||
* Body read and parse (1.4 ms at 180k), the snapshot RPC (0.7 ms), the prompt over HTTP/2 (1.6 ms) are the remaining 6.6 ms of
|
||||
`pre_engine`; the first two need semantics decisions (typed parse with identical errors; trusting the server-side epoch fence).
|
||||
* Clients that send `store: true` or `previous_response_id` (Codex sends neither) pay the history store before the terminal event:
|
||||
in memory it measured 1.2 ms at 180k (`post_store`, `cp_replay --store`); with persistence on it re-serializes and checksums *all*
|
||||
stored entries (up to 128 MiB) on every response, which was not measured; `previous_response_id` deep-copies the saved transcript.
|
||||
Not on the Codex path, not changed.
|
||||
* With `reasoning.effort` other than `none` the answer text (and tool calls) are withheld until the engine's terminal event (reasoning
|
||||
deltas stream live); the host cost of that is the 1.5 ms `tail`, the wait itself is the design.
|
||||
* The engine side of the prefix cache (block hash chain over 180k tokens, about 0.3 ms: one multiply-xor per token, sequential) and
|
||||
the cache resume grid belong to `claude/ttft`.
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs inside run-e2e.sh (as E2E_RUN_CMD, so inside a holder job, with the engine loaded and the current strata-next on :8081):
|
||||
# starts the BASELINE strata-next (commit dbf487b logic) on :8082 against the same engine and replays one synthesized Codex session
|
||||
# (scripts/cp/synth_session.py) alternately through the two, then joins the client's timings with the servers' stage logs.
|
||||
# Test tooling only; no credential is printed (keys are read from files).
|
||||
set -uo pipefail
|
||||
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
BINS=${CP_BINS:-$HOME/work/leleka-cp/bin}
|
||||
OUT=${E2E_OUT_DIR:?run through run-e2e.sh}
|
||||
STATE=$HOME/work/leleka-e2e/state
|
||||
SESSION=${CP_SESSION:-$HOME/work/leleka-cp/data/s945.json}
|
||||
TOK=$STATE/tokenizer-assets/tokenizer
|
||||
SIZE=${CP_SIZE:-100000}
|
||||
TURNS=${CP_TURNS:-20}
|
||||
MAXOUT=${CP_MAX_OUT:-64}
|
||||
sed 's/127.0.0.1:8081/127.0.0.1:8082/' "$STATE/strata.json" >"$STATE/strata-base.json"
|
||||
[ "$(grep -c 8082 "$STATE/strata-base.json")" = 1 ] || { echo "could not derive the baseline config"; exit 3; }
|
||||
STRATA_STAGE_TRACE=log "$BINS/strata-next-base" serve --config "$STATE/strata-base.json" >"$OUT/strata-base.log" 2>&1 &
|
||||
PID_BASE=$!
|
||||
if ! "$BINS/strata-next-base" wait-ready --url http://127.0.0.1:8082 --model qwen-iq3 --key-file "$STATE/api-key" --timeout-s 180 >"$OUT/wait-ready-base.log" 2>&1; then
|
||||
echo "baseline strata-next never became ready"; tail -20 "$OUT/wait-ready-base.log" "$OUT/strata-base.log"; kill -INT $PID_BASE 2>/dev/null; exit 6
|
||||
fi
|
||||
echo "both servers ready: $(date -u +%T)"
|
||||
sha256sum "$BINS"/strata-next-base "$BINS"/strata-next-new "$BINS"/leleka-inference "$BINS"/cp_replay | cut -c1-16,65-
|
||||
"$BINS/cp_replay" "$TOK" "$SESSION" --live http://127.0.0.1:8081,http://127.0.0.1:8082 --names new,base --key-file "$STATE/api-key" \
|
||||
--size "$SIZE" --turns "$TURNS" --max-output-tokens "$MAXOUT" >"$OUT/live.txt" 2>"$OUT/live.err"
|
||||
RC=$?
|
||||
cat "$OUT/live.err" | tail -5
|
||||
kill -INT $PID_BASE 2>/dev/null
|
||||
for _ in $(seq 1 20); do kill -0 $PID_BASE 2>/dev/null || break; sleep 1; done
|
||||
kill -KILL $PID_BASE 2>/dev/null
|
||||
python3 -I "$HERE/live_report.py" "$OUT/live.txt" new="$OUT/strata-next.log" base="$OUT/strata-base.log" | tee "$OUT/live-report.txt"
|
||||
echo "cp_replay exit status $RC"
|
||||
exit $RC
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline: join the client's per-turn timings of `cp_replay --live` with the servers' logs (experiments only).
|
||||
|
||||
live_report.py LIVE.txt ARM=SERVER_LOG [ARM=SERVER_LOG ...]
|
||||
|
||||
LIVE.txt holds `LIVE {json}` lines (one per request, with the client's unix-ms send/done times). Each SERVER_LOG is the stderr of a
|
||||
`strata-next serve` run with STRATA_STAGE_TRACE=log: `stage NAME MS t_unix_ms=END`, `generation start: t_unix_ms=T ...` and
|
||||
`generation done: ... prompt_ms=P ...` lines. A turn is joined with the lines of its arm's log that fall inside [send, done].
|
||||
|
||||
Per turn the client's time to the first token splits into
|
||||
pre = send -> `generation start` (everything the control plane does before it hands the prompt to the engine)
|
||||
engine= `generation start` -> first text delta as the worker saw it (`prompt_ms`: engine start call, prefill, first round)
|
||||
post = the rest (first delta at the worker -> first token event at the client)
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
PRE_STAGES = ["http_body_json", "request_decode", "request_validate", "render", "tokenize", "enqueue", "worker_prompt_text", "engine_start"]
|
||||
|
||||
|
||||
def load_log(path):
|
||||
stages, starts, dones = [], [], []
|
||||
for line in open(path, errors="replace"):
|
||||
m = re.match(r"stage (\S+) ([\d.]+) t_unix_ms=(\d+)", line)
|
||||
if m:
|
||||
stages.append((int(m.group(3)), m.group(1), float(m.group(2))))
|
||||
continue
|
||||
m = re.match(r"generation start: t_unix_ms=(\d+)", line)
|
||||
if m:
|
||||
starts.append(int(m.group(1)))
|
||||
continue
|
||||
m = re.match(r"generation done: t_unix_ms=(\d+).*prompt_tokens=(\d+) reused=(\d+).*prompt_ms=([\d.]+) decode_ms=([\d.]+)", line)
|
||||
if m:
|
||||
dones.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), float(m.group(4))))
|
||||
return stages, starts, dones
|
||||
|
||||
|
||||
def pct(values, q):
|
||||
v = sorted(values)
|
||||
return v[round(q * (len(v) - 1))] if v else float("nan")
|
||||
|
||||
|
||||
def main():
|
||||
live = [json.loads(l[5:]) for l in open(sys.argv[1]) if l.startswith("LIVE ")]
|
||||
logs = {}
|
||||
for spec in sys.argv[2:]:
|
||||
arm, path = spec.split("=", 1)
|
||||
logs[arm] = load_log(path)
|
||||
rows = []
|
||||
for turn in live:
|
||||
stages, starts, dones = logs[turn["arm"]]
|
||||
lo, hi = turn["sent_unix_ms"] - 5, turn["done_unix_ms"] + 50
|
||||
window = [(n, ms) for t, n, ms in stages if lo <= t <= hi]
|
||||
start = next((t for t in starts if lo <= t <= hi), None)
|
||||
done = next((d for d in dones if lo <= d[0] <= hi), None)
|
||||
stage_sum = {name: sum(ms for n, ms in window if n == name) for name in PRE_STAGES}
|
||||
pre = (start - turn["sent_unix_ms"]) if start else float("nan")
|
||||
engine = done[3] if done else float("nan")
|
||||
post = turn["ttft_ms"] - pre - engine
|
||||
rows.append({**turn, "pre": pre, "engine": engine, "post": post, "stages": stage_sum,
|
||||
"reused": done[2] if done else 0, "prompt_tokens": done[1] if done else 0})
|
||||
print("turn arm round prompt reused ttft_ms created pre_ms engine_ms post_ms total_ms terminal")
|
||||
for r in rows:
|
||||
print(f"{r['turn']:>4} {r['arm']:<5} {r['round']:>5} {r['prompt_tokens']:>7} {r['reused']:>7} {r['ttft_ms']:>8.1f} {r['created_ms']:>8.1f} {r['pre']:>7.1f} {r['engine']:>10.1f} {r['post']:>8.1f} {r['total_ms']:>9.1f} {r['terminal']}")
|
||||
print("\nper arm, turns after the first of each arm (median / p95), ms:")
|
||||
for arm in logs:
|
||||
mine = [r for r in rows if r["arm"] == arm][1:]
|
||||
if not mine:
|
||||
continue
|
||||
def cell(key):
|
||||
values = [r[key] for r in mine]
|
||||
return f"{statistics.median(values):8.1f} / {pct(values, 0.95):8.1f}"
|
||||
print(f" {arm:<6} n={len(mine):<3} ttft {cell('ttft_ms')} created {cell('created_ms')} pre {cell('pre')} engine {cell('engine')} post {cell('post')}")
|
||||
names = ", ".join(f"{k}={statistics.median(r['stages'][k] for r in mine):.2f}" for k in PRE_STAGES)
|
||||
print(f" median pre-engine stages: {names}")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Interleaved A/B of the host-side request path on the instant engine (docs/cp-latency.md), repeats alternating base and new so a shared
|
||||
# machine hurts both arms alike. Builds only; the model, the GPU and Python are not involved except for the summary table.
|
||||
#
|
||||
# run-ab.sh BASE_TREE NEW_TREE TOKENIZER_DIR SESSION.json OUT_DIR [REPS] [cp_replay args...]
|
||||
#
|
||||
# BASE_TREE / NEW_TREE: source trees (e.g. `git archive dbf487b` and a checkout of the new head), each already carrying
|
||||
# control-plane/examples/cp_replay.rs and desktop-core/examples/cp_replay_grpc.rs (the baseline needs `encode_reference` and
|
||||
# `decodes_to` shims on its Tokenizer for --verify only, not for timing). CARGO_TARGET_DIR_BASE / _NEW choose the target dirs.
|
||||
# Writes OUT_DIR/{base,new}-{proc,grpc}-N.{json,txt}; `python3 scripts/cp/summarize.py OUT_DIR` prints the tables.
|
||||
set -euo pipefail
|
||||
BASE=$1 NEW=$2 TOK=$3 SESSION=$4 OUT=$5; REPS=${6:-3}; shift 6 2>/dev/null || shift $#
|
||||
mkdir -p "$OUT"
|
||||
build() { # tree target
|
||||
( cd "$1" && CARGO_TARGET_DIR="$2" cargo build --locked --release -p strata-control --example cp_replay \
|
||||
&& CARGO_TARGET_DIR="$2" cargo build --locked --release -p strata-desktop-core --example cp_replay_grpc ) >&2
|
||||
}
|
||||
TB=${CARGO_TARGET_DIR_BASE:-$BASE/target-ab}
|
||||
TN=${CARGO_TARGET_DIR_NEW:-$NEW/target-ab}
|
||||
build "$BASE" "$TB"
|
||||
build "$NEW" "$TN"
|
||||
for r in $(seq 1 "$REPS"); do
|
||||
for cfg in base new; do
|
||||
T=$TN; [ $cfg = base ] && T=$TB
|
||||
for mode in proc grpc; do
|
||||
EX=cp_replay; [ $mode = grpc ] && EX=cp_replay_grpc
|
||||
"$T/release/examples/$EX" "$TOK" "$SESSION" --label "$cfg-$mode-$r" --out "$OUT/$cfg-$mode-$r.json" "$@" \
|
||||
>"$OUT/$cfg-$mode-$r.txt" 2>/dev/null
|
||||
echo "done $cfg-$mode-$r"
|
||||
done
|
||||
done
|
||||
done
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline: summarize cp_replay result files (experiments only).
|
||||
|
||||
summarize.py DIR -- reads DIR/{base,new}-{proc,grpc}-N.json and prints, per mode and history size, the warm-turn p50 and p95
|
||||
per metric and per stage (min over repeats of each repeat's percentile: the machine is shared).
|
||||
"""
|
||||
import glob, json, os, re, statistics, sys
|
||||
|
||||
def pct(values, q):
|
||||
v = sorted(values)
|
||||
return v[round(q * (len(v) - 1))] if v else float("nan")
|
||||
|
||||
def load(directory):
|
||||
runs = {}
|
||||
for path in sorted(glob.glob(os.path.join(directory, "*.json"))):
|
||||
m = re.match(r"(base|new)-(proc|grpc)-(\d+)\.json", os.path.basename(path))
|
||||
if not m:
|
||||
continue
|
||||
doc = json.load(open(path))
|
||||
runs.setdefault((m.group(2), m.group(1)), []).append(doc)
|
||||
return runs
|
||||
|
||||
def per_size(docs, metric, stage=None):
|
||||
"""size -> list over repeats of (cold, p50, p95)"""
|
||||
out = {}
|
||||
for doc in docs:
|
||||
for res in doc["results"]:
|
||||
rows = res["rows"]
|
||||
def val(r):
|
||||
if stage is None:
|
||||
return r[metric]
|
||||
return r["stages"].get(stage, {}).get("ms", 0.0)
|
||||
warm = [val(r) for r in rows[1:]]
|
||||
out.setdefault(res["size"], []).append((val(rows[0]), pct(warm, 0.5), pct(warm, 0.95)))
|
||||
return out
|
||||
|
||||
def best(entries, k):
|
||||
return min(e[k] for e in entries)
|
||||
|
||||
def main():
|
||||
runs = load(sys.argv[1])
|
||||
metrics = ["pre_engine_ms", "first_event_ms", "tail_ms"]
|
||||
stages = ["http_body_json", "request_decode", "request_validate", "render", "tokenize", "worker_prompt_text", "engine_start", "post_decode", "post_assemble", "post_store", "delta_retokenize"]
|
||||
for mode in ("proc", "grpc"):
|
||||
if (mode, "base") not in runs:
|
||||
continue
|
||||
print(f"\n### {'in-process instant engine' if mode == 'proc' else 'instant engine behind the real gRPC runtime server'}")
|
||||
sizes = sorted(per_size(runs[(mode, "new")], "pre_engine_ms"))
|
||||
for label, names, stage in (("metric", metrics, False), ("stage", stages, True)):
|
||||
print(f"\n| {label} (ms, warm turns) | " + " | ".join(f"{s//1000}k base p50 / p95 | {s//1000}k new p50 / p95" for s in sizes) + " |")
|
||||
print("|---|" + "---|---|" * len(sizes))
|
||||
for name in names:
|
||||
cells = []
|
||||
for s in sizes:
|
||||
for cfg in ("base", "new"):
|
||||
e = per_size(runs[(mode, cfg)], name if not stage else None, name if stage else None).get(s)
|
||||
cells.append(f"{best(e,1):.2f} / {best(e,2):.2f}" if e else "-")
|
||||
print(f"| {name} | " + " | ".join(cells) + " |")
|
||||
print("\ncold first request (ms, min over repeats):")
|
||||
for cfg in ("base", "new"):
|
||||
e = per_size(runs[(mode, cfg)], "pre_engine_ms")
|
||||
print(f" {cfg:5s} pre_engine cold: " + ", ".join(f"{s//1000}k={best(e[s],0):.1f}" for s in sorted(e)))
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tooling (experiments only; production stays Python-free): synthesize Codex-shaped Responses API request material
|
||||
from a captured session (the engine-side capture holds the rendered prompt token ids, not the HTTP bodies).
|
||||
|
||||
synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ_INDEX OUT.json [--extend CAPTURE2 LAST2]
|
||||
|
||||
The last request's prompt is decoded with the pinned vocabulary and the chat template is inverted: system block (tools, merged
|
||||
instructions), user messages, assistant turns (`<think>` reasoning, text, `<tool_call>` markup) and `<tool_response>` user turns become
|
||||
Responses `instructions`, `tools`, and `input` items (message / reasoning / function_call / function_call_output) exactly as Codex
|
||||
replays them. OUT.json holds the invariant part of a request and the item list with its round boundaries, plus the captured prompt
|
||||
ids of the last request so a harness can check that rendering + tokenizing the synthesized body reproduces the capture exactly.
|
||||
With --extend the items of a second capture (call ids and text tagged so no two items are byte-identical) are appended, to reach
|
||||
history sizes beyond the capture.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
|
||||
from tok_py import Vocab # noqa: E402
|
||||
|
||||
CALL_RE = re.compile(r"<tool_call>\n<function=([^>]+)>\n(.*?)</function>\n</tool_call>", re.S)
|
||||
PARAM_RE = re.compile(r"<parameter=([^>]+)>\n(.*?)\n</parameter>\n", re.S)
|
||||
RESP_RE = re.compile(r"<tool_response>\n(.*?)\n</tool_response>", re.S)
|
||||
|
||||
|
||||
def split_segments(text):
|
||||
segs = []
|
||||
pos = 0
|
||||
marker = "<|im_start|>"
|
||||
idx = [m.start() for m in re.finditer(re.escape(marker), text)]
|
||||
for a, b in zip(idx, idx[1:] + [len(text)]):
|
||||
seg = text[a + len(marker):b]
|
||||
segs.append(seg)
|
||||
return segs
|
||||
|
||||
|
||||
def parse_system(seg):
|
||||
# seg = "system\n...<|im_end|>\n"
|
||||
body = seg[len("system\n"):]
|
||||
assert body.endswith("<|im_end|>\n"), body[-40:]
|
||||
body = body[: -len("<|im_end|>\n")]
|
||||
tools_start = body.index("<tools>\n") + len("<tools>\n")
|
||||
tools_end = body.index("\n</tools>")
|
||||
tools = [json.loads(l) for l in body[tools_start:tools_end].split("\n")]
|
||||
rest = body[tools_end + len("\n</tools>"):]
|
||||
marker = "</IMPORTANT>"
|
||||
k = rest.index(marker) + len(marker)
|
||||
tail = rest[k:]
|
||||
assert tail.startswith("\n\n"), repr(tail[:30])
|
||||
instructions = tail[2:]
|
||||
flat = []
|
||||
for t in tools:
|
||||
f = t["function"]
|
||||
o = {"type": "function", "name": f["name"]}
|
||||
if "description" in f:
|
||||
o["description"] = f["description"]
|
||||
if "strict" in f:
|
||||
o["strict"] = f["strict"]
|
||||
if "parameters" in f:
|
||||
o["parameters"] = f["parameters"]
|
||||
flat.append(o)
|
||||
return instructions, flat
|
||||
|
||||
|
||||
def message(role, text):
|
||||
kind = "output_text" if role == "assistant" else "input_text"
|
||||
return {"type": "message", "role": role, "content": [{"type": kind, "text": text}]}
|
||||
|
||||
|
||||
def arg_value(raw, schema):
|
||||
prop = (schema or {}).get("properties", {})
|
||||
kind = None
|
||||
return raw, prop
|
||||
|
||||
|
||||
def parse_assistant(seg, tools, serial):
|
||||
body = seg[len("assistant\n"):]
|
||||
assert body.endswith("<|im_end|>\n"), repr(body[-30:])
|
||||
body = body[: -len("<|im_end|>\n")]
|
||||
assert body.startswith("<think>\n")
|
||||
close = body.index("\n</think>\n\n")
|
||||
reasoning = body[len("<think>\n"):close]
|
||||
content = body[close + len("\n</think>\n\n"):]
|
||||
items = []
|
||||
if reasoning:
|
||||
items.append({"type": "reasoning", "summary": [], "content": [{"type": "reasoning_text", "text": reasoning}]})
|
||||
first = content.find("<tool_call>\n")
|
||||
text = content if first < 0 else content[:first]
|
||||
text = text.strip()
|
||||
if text:
|
||||
items.append(message("assistant", text))
|
||||
calls = []
|
||||
for m in CALL_RE.finditer(content):
|
||||
name, params = m.group(1), m.group(2)
|
||||
schema = next((t.get("parameters") for t in tools if t["name"] == name), None) or {}
|
||||
props = schema.get("properties", {})
|
||||
args = {}
|
||||
for p in PARAM_RE.finditer(params):
|
||||
pname, raw = p.group(1), p.group(2)
|
||||
ptype = props.get(pname, {}).get("type")
|
||||
if ptype == "string" or ptype is None:
|
||||
args[pname] = raw
|
||||
else:
|
||||
try:
|
||||
args[pname] = json.loads(raw)
|
||||
except ValueError:
|
||||
args[pname] = raw
|
||||
serial[0] += 1
|
||||
call_id = f"call_{serial[0]:06d}"
|
||||
calls.append(call_id)
|
||||
items.append({"type": "function_call", "name": name, "call_id": call_id,
|
||||
"arguments": json.dumps(args, ensure_ascii=False, separators=(",", ":"))})
|
||||
return items, calls
|
||||
|
||||
|
||||
def parse_user(seg, pending_calls):
|
||||
body = seg[len("user\n"):]
|
||||
assert body.endswith("<|im_end|>\n")
|
||||
body = body[: -len("<|im_end|>\n")]
|
||||
if body.startswith("<tool_response>\n") and pending_calls:
|
||||
outs = [m.group(1) for m in RESP_RE.finditer(body)]
|
||||
assert len(outs) == len(pending_calls), (len(outs), len(pending_calls))
|
||||
return [{"type": "function_call_output", "call_id": c, "output": o} for c, o in zip(pending_calls, outs)], True
|
||||
return [message("user", body)], False
|
||||
|
||||
|
||||
def build(vocab, capture, last, serial):
|
||||
req = json.load(open(f"{capture}/req-{last:06d}.json"))
|
||||
ids = req["prompt_ids"]
|
||||
text = vocab.decode(ids)
|
||||
segs = split_segments(text)
|
||||
instructions, tools = parse_system(segs[0])
|
||||
items, rounds = [], []
|
||||
pending = []
|
||||
# the final segment is the generation prompt "assistant\n<think>\n"
|
||||
assert segs[-1] == "assistant\n<think>\n", repr(segs[-1])
|
||||
for seg in segs[1:-1]:
|
||||
if seg.startswith("assistant\n"):
|
||||
new, calls = parse_assistant(seg, tools, serial)
|
||||
items += new
|
||||
pending = calls
|
||||
else:
|
||||
new, was_output = parse_user(seg, pending)
|
||||
items += new
|
||||
pending = []
|
||||
# a request can be made after a user message or after tool outputs
|
||||
rounds.append(len(items))
|
||||
return instructions, tools, items, rounds, ids
|
||||
|
||||
|
||||
def retag(items, rounds, tag):
|
||||
out = []
|
||||
for it in items:
|
||||
it = json.loads(json.dumps(it))
|
||||
if it["type"] == "message":
|
||||
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
|
||||
elif it["type"] == "function_call_output":
|
||||
it["output"] = f"[{tag}] " + it["output"]
|
||||
elif it["type"] == "reasoning":
|
||||
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
|
||||
elif it["type"] == "function_call":
|
||||
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
|
||||
out.append(it)
|
||||
# call ids in outputs
|
||||
for it in out:
|
||||
if it["type"] == "function_call_output":
|
||||
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
argv = sys.argv[1:]
|
||||
tok_dir, capture, last, out = argv[0], argv[1], int(argv[2]), argv[3]
|
||||
extend = None
|
||||
if "--extend" in argv:
|
||||
k = argv.index("--extend")
|
||||
extend = (argv[k + 1], int(argv[k + 2]))
|
||||
vocab = Vocab(tok_dir)
|
||||
serial = [0]
|
||||
instructions, tools, items, rounds, ids = build(vocab, capture, last, serial)
|
||||
doc = {"instructions": instructions, "tools": tools, "items": items, "rounds": rounds,
|
||||
"capture_prompt_ids": ids, "capture_items": len(items)}
|
||||
if extend:
|
||||
i2, t2, items2, rounds2, _ = build(vocab, extend[0], extend[1], serial)
|
||||
# skip the leading environment/task user messages of the second session: keep from its first assistant turn
|
||||
first_assistant = next(n for n, it in enumerate(items2) if it["type"] in ("reasoning", "function_call") or (it["type"] == "message" and it["role"] == "assistant"))
|
||||
base = len(items)
|
||||
tail = retag(items2[first_assistant:], rounds2, "x")
|
||||
doc["items"] = items + tail
|
||||
doc["rounds"] = rounds + [base + (r - first_assistant) for r in rounds2 if r > first_assistant]
|
||||
json.dump(doc, open(out, "w", encoding="utf-8"), ensure_ascii=False)
|
||||
print(f"items={len(doc['items'])} rounds={len(doc['rounds'])} tools={len(tools)} instructions_bytes={len(instructions)} capture_tokens={len(ids)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Offline helper (experiments only): decode captured prompt ids to text with the pinned vocab.json (byte-level BPE alphabet)."""
|
||||
import json, os
|
||||
|
||||
def _byte_alphabet():
|
||||
bs = list(range(0x21, 0x7f)) + list(range(0xa1, 0xad)) + list(range(0xae, 0x100))
|
||||
cs = bs[:]
|
||||
n = 0
|
||||
for b in range(256):
|
||||
if b not in bs:
|
||||
bs.append(b); cs.append(256 + n); n += 1
|
||||
return {chr(c): b for b, c in zip(bs, cs)}
|
||||
|
||||
class Vocab:
|
||||
def __init__(self, directory):
|
||||
vocab = json.load(open(os.path.join(directory, "vocab.json"), encoding="utf-8"))
|
||||
self.tokens = [None] * len(vocab)
|
||||
for t, i in vocab.items():
|
||||
self.tokens[i] = t
|
||||
self.rev = _byte_alphabet()
|
||||
|
||||
def decode_bytes(self, ids):
|
||||
out = bytearray()
|
||||
for i in ids:
|
||||
for ch in self.tokens[i]:
|
||||
out.append(self.rev[ch])
|
||||
return bytes(out)
|
||||
|
||||
def decode(self, ids):
|
||||
return self.decode_bytes(ids).decode("utf-8")
|
||||
@@ -0,0 +1,26 @@
|
||||
set -uo pipefail
|
||||
# claude/cp-latency: the host side of one Codex session on the real engine. One model load; two API servers in front of the same engine
|
||||
# (the current strata-next on :8081 and the baseline dbf487b logic on :8082); one synthesized Codex session (capture 945, history ~100k tokens,
|
||||
# 20 consecutive requests, max_output_tokens 64) sent alternately through the two, so the engine sees the same prompt sequence either way.
|
||||
# Prints the per-request table and per-arm medians of: client TTFT, pre-engine time (send -> generation start), engine time, post time.
|
||||
# Needs (outside Git, copied by the operator): $CP/bin/{leleka-inference,strata-next-new,strata-next-base,cp_replay}, $CP/data/s945.json,
|
||||
# the e2e bins for leleka-daemon / leleka-cli, and the scripts of this branch under $CP/scripts/cp.
|
||||
CP=$HOME/work/leleka-cp
|
||||
E2E=$HOME/work/leleka-e2e/bin-sm120
|
||||
mkdir -p $CP/bin-e2e $CP/runs
|
||||
ln -sf $CP/bin/leleka-inference $CP/bin-e2e/leleka-inference
|
||||
ln -sf $CP/bin/strata-next-new $CP/bin-e2e/strata-next
|
||||
ln -sf $E2E/leleka-daemon $CP/bin-e2e/leleka-daemon
|
||||
ln -sf $E2E/leleka-cli $CP/bin-e2e/leleka-cli
|
||||
export E2E_BIN=$CP/bin-e2e
|
||||
export E2E_OUT=$CP/runs/9f1-cp-live-ab
|
||||
export CP_BINS=$CP/bin CP_SESSION=$CP/data/s945.json CP_SIZE=${CP_SIZE:-100000} CP_TURNS=${CP_TURNS:-20}
|
||||
export STRATA_STAGE_TRACE=log
|
||||
export LELEKA_BRINGUP_TRACE=1
|
||||
export E2E_SAMPLE_S=10
|
||||
export E2E_RUN_CMD="bash $CP/scripts/cp/live-ab.sh"
|
||||
rm -rf $E2E_OUT
|
||||
date -u +%FT%TZ
|
||||
bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh
|
||||
echo "run-e2e rc=$?"
|
||||
date -u +%FT%TZ
|
||||
Reference in New Issue
Block a user