STRA-338 size: engine runner::run and generate within the limits (command_loop, Delivery)
This commit is contained in:
@@ -119,8 +119,12 @@ mod run_parts;
|
||||
use run_parts::drop_model_page_cache;
|
||||
#[allow(unused_imports)]
|
||||
use run_parts::{
|
||||
GenerateEnv, abandon_stack, close_context, close_stack, emit_cache_line, open_run_stack, serve_generate, sweep_idle,
|
||||
GenerateEnv, abandon_stack, close_context, close_stack, open_run_stack, publish_open, serve_generate, sweep_idle,
|
||||
};
|
||||
#[path = "runner/command_loop.rs"]
|
||||
mod command_loop;
|
||||
#[allow(unused_imports)]
|
||||
use command_loop::{LoopCtx, announce, command_loop};
|
||||
#[path = "runner/reconfigure_parts.rs"]
|
||||
mod reconfigure_parts;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! The command loop of the Original owner, moved out of `run` by STRA-338 (size): receive, sweep the idle sessions,
|
||||
//! and answer each command in the order `run` did.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// What the loop reads and does not change: the channel, the flags, the model handle and the clock.
|
||||
pub(super) struct LoopCtx<'r, 'a, 'ctx> {
|
||||
pub(super) rx: &'r Receiver<Command>,
|
||||
pub(super) shared: &'r Shared,
|
||||
pub(super) reopen: ReopenEnv<'a, 'ctx, 'r>,
|
||||
pub(super) loaded: &'r LoadedModel,
|
||||
pub(super) tokenizer: &'r Tokenizer,
|
||||
pub(super) eos: u32,
|
||||
pub(super) clock: &'r SystemClock,
|
||||
}
|
||||
|
||||
/// The state is ready: refuse a cancelled load, publish readiness and answer the load. `false`: nobody was listening.
|
||||
pub(super) fn announce(
|
||||
shared: &Shared,
|
||||
reply: &Reply<LoadedModel>,
|
||||
loaded: &LoadedModel,
|
||||
stack: &mut Option<OriginalServeStack<'_, '_>>,
|
||||
) -> Result<bool, BackendError> {
|
||||
if shared.shutdown.load(Ordering::Acquire) {
|
||||
abandon_stack(stack);
|
||||
return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled")));
|
||||
}
|
||||
shared.ready.store(true, Ordering::Release);
|
||||
crate::load_clock::lap("ready_published");
|
||||
if reply.send(Ok(loaded.clone())).is_err() {
|
||||
shared.ready.store(false, Ordering::Release);
|
||||
abandon_stack(stack);
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Serve commands until unload or shutdown; the unload's reply target is handed back to answer after the close.
|
||||
pub(super) fn command_loop<'a, 'ctx>(
|
||||
ctx: &LoopCtx<'_, 'a, 'ctx>,
|
||||
live: &mut Live<'_, 'a, 'ctx>,
|
||||
) -> Result<Option<Reply<()>>, BackendError> {
|
||||
let mut sweep = IdleSweep::new(Duration::from_secs(15), ctx.clock);
|
||||
while !ctx.shared.shutdown.load(Ordering::Acquire) {
|
||||
match ctx.rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => sweep_idle(live.stack, &mut sweep, ctx.clock, ctx.shared),
|
||||
Err(_) => break,
|
||||
Ok(command) => {
|
||||
if let Some(reply) = handle_command(ctx, live, command)? {
|
||||
return Ok(Some(reply));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn handle_command<'a, 'ctx>(
|
||||
ctx: &LoopCtx<'_, 'a, 'ctx>,
|
||||
live: &mut Live<'_, 'a, 'ctx>,
|
||||
command: Command,
|
||||
) -> Result<Option<Reply<()>>, BackendError> {
|
||||
match command {
|
||||
Command::Load(_, _, reply) => {
|
||||
let _ = reply.send(Err(exhausted("unload the existing model before another load")));
|
||||
}
|
||||
Command::Reconfigure(text, reply) => {
|
||||
let _ = reply.send(reconfigure(&ctx.reopen, live, &text));
|
||||
}
|
||||
Command::Unload(candidate, reply) => {
|
||||
if &candidate == ctx.loaded {
|
||||
return Ok(Some(reply));
|
||||
}
|
||||
let _ = reply.send(Err(invalid("unknown loaded model handle")));
|
||||
}
|
||||
Command::Generate(candidate, request, cancel, reply) => {
|
||||
let env = GenerateEnv {
|
||||
shared: ctx.shared,
|
||||
tokenizer: ctx.tokenizer,
|
||||
eos: ctx.eos,
|
||||
loaded: ctx.loaded,
|
||||
clock: ctx.clock,
|
||||
spec_min_p: live.options.spec_min_p,
|
||||
context_tokens: *live.context_tokens,
|
||||
};
|
||||
serve_generate(&env, live.stack, (candidate, request, cancel, reply))?;
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
@@ -18,7 +18,24 @@ struct Delivery<'x, F: Fn() -> bool, C: Clock> {
|
||||
generated_ids: Vec<i32>,
|
||||
}
|
||||
|
||||
impl<F: Fn() -> bool, C: Clock> Delivery<'_, F, C> {
|
||||
impl<'x, F: Fn() -> bool, C: Clock> Delivery<'x, F, C> {
|
||||
fn new(io: &RequestIo<'x, C>, cancelled: &'x F) -> Self {
|
||||
let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(io.eos);
|
||||
let (tokenizer, sink, clock) = (io.tokenizer, io.sink, io.clock);
|
||||
let utf8 = Utf8Pending::default();
|
||||
Self {
|
||||
tokenizer,
|
||||
sink,
|
||||
cancelled,
|
||||
clock,
|
||||
stop_tokens,
|
||||
utf8,
|
||||
count: 0,
|
||||
captured: None,
|
||||
generated_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The authoritative EOS (<|im_end|> or <|endoftext|>) counts as an output token and carries no text.
|
||||
fn deliver_one(&mut self, token: i32) -> Result<(), GenerationFailure> {
|
||||
self.count += 1;
|
||||
@@ -101,22 +118,10 @@ fn generate_with<C: Clock>(
|
||||
request: &GenerationRequest,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
let (sink, cancel, shared, clock) = (io.sink, io.cancel, io.shared, io.clock);
|
||||
let (env, channel) = (io, (sink, cancel));
|
||||
let serve_request = serve_request_for(request, prompt, env.eos, env.spec_min_p)?;
|
||||
let serve_request = serve_request_for(request, prompt, io.eos, io.spec_min_p)?;
|
||||
let cancelled = || cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed();
|
||||
let start = clock.now();
|
||||
let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(env.eos);
|
||||
let mut delivery = Delivery {
|
||||
tokenizer: env.tokenizer,
|
||||
sink,
|
||||
cancelled: &cancelled,
|
||||
clock,
|
||||
stop_tokens,
|
||||
utf8: Utf8Pending::default(),
|
||||
count: 0,
|
||||
captured: None,
|
||||
generated_ids: Vec::new(),
|
||||
};
|
||||
let mut delivery = Delivery::new(io, &cancelled);
|
||||
leleka_memory::telemetry::request_started_at(prompt.len() as u64, start);
|
||||
let mut timed_out = false;
|
||||
let mut probe = || {
|
||||
@@ -125,7 +130,21 @@ fn generate_with<C: Clock>(
|
||||
};
|
||||
let result = stack.serve(&serve_request, &mut |tokens: &[i32]| delivery.deliver(tokens), &mut probe);
|
||||
let outcome = served_outcome(delivery.captured.take(), timed_out, result)?;
|
||||
finish_request(stack, (env, channel), (prompt, request), (delivery, outcome))
|
||||
finish_request(stack, (io, (sink, cancel)), (prompt, request), (delivery, outcome))
|
||||
}
|
||||
|
||||
/// `LELEKA_CAPTURE_DIR`: the request is written out for the offline replay.
|
||||
fn capture_if_configured(
|
||||
stack: &impl ServeDevice,
|
||||
ids: (&[u32], &[i32]),
|
||||
request: &GenerationRequest,
|
||||
outcome: ServeOutcome,
|
||||
) {
|
||||
if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() {
|
||||
let (prompt, generated) = ids;
|
||||
let reused = stack.reused_tokens() as u64;
|
||||
capture_request(std::path::Path::new(directory), prompt, generated, request, outcome.rounds as u64, reused);
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream's last text, the usage, the telemetry and the operator lines of a request that was served.
|
||||
@@ -136,18 +155,16 @@ fn finish_request<F: Fn() -> bool, C: Clock>(
|
||||
served: (Delivery<'_, F, C>, ServeOutcome),
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
let ((env, (sink, _)), (prompt, request), (mut delivery, outcome)) = (io, asked, served);
|
||||
if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() {
|
||||
let reused = stack.reused_tokens() as u64;
|
||||
let ids = &delivery.generated_ids;
|
||||
capture_request(std::path::Path::new(directory), prompt, ids, request, outcome.rounds as u64, reused);
|
||||
}
|
||||
capture_if_configured(stack, (prompt, &delivery.generated_ids), request, outcome);
|
||||
let reason = match outcome.stop {
|
||||
ServeStop::Eos => FinishReason::Stop,
|
||||
ServeStop::Length | ServeStop::Context => FinishReason::Length,
|
||||
};
|
||||
let cancelled = delivery.cancelled;
|
||||
if matches!(reason, FinishReason::Length) {
|
||||
delivery.utf8.finish_length(|text| emit_event(sink, cancelled, env.clock, GenerationEvent::TextDelta { text }))?;
|
||||
delivery
|
||||
.utf8
|
||||
.finish_length(|text| emit_event(sink, cancelled, env.clock, GenerationEvent::TextDelta { text }))?;
|
||||
} else {
|
||||
delivery.utf8.finish()?;
|
||||
}
|
||||
@@ -167,13 +184,9 @@ fn served_outcome(
|
||||
timed_out: bool,
|
||||
result: Result<ServeOutcome, ServeError>,
|
||||
) -> Result<ServeOutcome, GenerationFailure> {
|
||||
if let Some(failure) = captured {
|
||||
if captured.is_some() || timed_out {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(failure);
|
||||
}
|
||||
if timed_out {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
return Err(captured.unwrap_or_else(|| unavailable("generation deadline exceeded").into()));
|
||||
}
|
||||
let error = match result {
|
||||
Ok(outcome) => return Ok(outcome),
|
||||
|
||||
@@ -6,93 +6,28 @@ use super::*;
|
||||
/// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply
|
||||
/// target, as `serve_load` does after its loop.
|
||||
pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> {
|
||||
let Run {
|
||||
context_tokens,
|
||||
rx,
|
||||
shared,
|
||||
binding,
|
||||
context,
|
||||
tokenizer,
|
||||
eos,
|
||||
loaded,
|
||||
reply,
|
||||
options,
|
||||
model_files,
|
||||
clock,
|
||||
gpu_ordinal,
|
||||
} = args;
|
||||
#[rustfmt::skip]
|
||||
let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files,
|
||||
clock, gpu_ordinal } = args;
|
||||
// the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy
|
||||
let mut options = options.clone();
|
||||
let mut context_tokens = context_tokens;
|
||||
options.validate()?;
|
||||
let (stack, mut workers) = open_run_stack(&binding, &context, &options, context_tokens, &loaded, &model_files)?;
|
||||
emit_cache_line(&stack);
|
||||
publish_prefix_summary(&stack, shared);
|
||||
crate::load_clock::lap("serve_stack_open_total");
|
||||
#[cfg(target_os = "linux")]
|
||||
drop_model_page_cache(&options, &model_files);
|
||||
leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None));
|
||||
// operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request
|
||||
leleka_memory::telemetry::set_context_max(u64::from(context_tokens));
|
||||
publish_open(&stack, shared, (&options, &model_files), (context_tokens, workers));
|
||||
let _telemetry = leleka_memory::telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1));
|
||||
let mut stack = Some(stack);
|
||||
if shared.shutdown.load(Ordering::Acquire) {
|
||||
abandon_stack(&mut stack);
|
||||
return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled")));
|
||||
}
|
||||
shared.ready.store(true, Ordering::Release);
|
||||
crate::load_clock::lap("ready_published");
|
||||
if reply.send(Ok(loaded.clone())).is_err() {
|
||||
shared.ready.store(false, Ordering::Release);
|
||||
abandon_stack(&mut stack);
|
||||
if !announce(shared, reply, &loaded, &mut stack)? {
|
||||
drop(stack);
|
||||
let _ = Rc::try_unwrap(context).map(|c| c.close());
|
||||
return Ok(());
|
||||
}
|
||||
let mut unload_reply = None;
|
||||
let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock);
|
||||
let reopen = ReopenEnv { binding: &binding, context: &context, shared, clock: &clock };
|
||||
while !shared.shutdown.load(Ordering::Acquire) {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
sweep_idle(&mut stack, &mut sweep, &clock, shared);
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
Ok(Command::Load(_, _, reply)) => {
|
||||
let _ = reply.send(Err(exhausted("unload the existing model before another load")));
|
||||
}
|
||||
Ok(Command::Reconfigure(text, reply)) => {
|
||||
let mut live = Live {
|
||||
options: &mut options,
|
||||
context_tokens: &mut context_tokens,
|
||||
workers: &mut workers,
|
||||
stack: &mut stack,
|
||||
};
|
||||
let _ = reply.send(reconfigure(&reopen, &mut live, &text));
|
||||
}
|
||||
Ok(Command::Unload(candidate, reply)) => {
|
||||
if candidate != loaded {
|
||||
let _ = reply.send(Err(invalid("unknown loaded model handle")));
|
||||
} else {
|
||||
unload_reply = Some(reply);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Command::Generate(candidate, request, cancel, reply)) => {
|
||||
let env = GenerateEnv {
|
||||
shared,
|
||||
tokenizer: &tokenizer,
|
||||
eos,
|
||||
loaded: &loaded,
|
||||
clock: &clock,
|
||||
spec_min_p: options.spec_min_p,
|
||||
context_tokens,
|
||||
};
|
||||
serve_generate(&env, &mut stack, (candidate, request, cancel, reply))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[rustfmt::skip]
|
||||
let ctx = LoopCtx { rx, shared, loaded: &loaded, tokenizer: &tokenizer, eos, clock: &clock,
|
||||
reopen: ReopenEnv { binding: &binding, context: &context, shared, clock: &clock } };
|
||||
let mut live =
|
||||
Live { options: &mut options, context_tokens: &mut context_tokens, workers: &mut workers, stack: &mut stack };
|
||||
let unload_reply = command_loop(&ctx, &mut live)?;
|
||||
shared.ready.store(false, Ordering::Release);
|
||||
let stack_closed = close_stack(stack.take());
|
||||
// the stack's borrow of the context ends with it
|
||||
|
||||
@@ -238,3 +238,25 @@ pub(super) fn close_context(context: Rc<Context<'_>>) -> Result<Result<(), Backe
|
||||
.close()
|
||||
.map_err(|_| unavailable("native context cleanup failed")))
|
||||
}
|
||||
|
||||
/// The report of a stack that opened: the cache line, the prefix summary, the page cache given back and the settings
|
||||
/// and context ceiling the telemetry carries.
|
||||
pub(super) fn publish_open(
|
||||
stack: &Stack<'_, '_>,
|
||||
shared: &Shared,
|
||||
state: (&OriginalServeOptions, &[PathBuf]),
|
||||
sizes: (u32, i32),
|
||||
) {
|
||||
let (options, model_files) = state;
|
||||
let (context_tokens, workers) = sizes;
|
||||
emit_cache_line(stack);
|
||||
publish_prefix_summary(stack, shared);
|
||||
crate::load_clock::lap("serve_stack_open_total");
|
||||
#[cfg(target_os = "linux")]
|
||||
drop_model_page_cache(options, model_files);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let _ = model_files;
|
||||
leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(options, context_tokens, workers, None));
|
||||
// operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request
|
||||
leleka_memory::telemetry::set_context_max(u64::from(context_tokens));
|
||||
}
|
||||
|
||||
@@ -163,9 +163,8 @@ impl DirectTier {
|
||||
};
|
||||
let open_span = super::super::original_serve_profile::span("cpu.open");
|
||||
let use_pass = open.use_pass;
|
||||
let opened = self.open_group(binding, rows.layer as u32, &ids, |pool, opened| {
|
||||
open.note_opened(pool, opened, use_pass)
|
||||
})?;
|
||||
let opened =
|
||||
self.open_group(binding, rows.layer as u32, &ids, |pool, opened| open.note_opened(pool, opened, use_pass))?;
|
||||
drop(open_span);
|
||||
self.start_lookahead_once(binding, &opened);
|
||||
Ok((opened, open))
|
||||
|
||||
Reference in New Issue
Block a user