Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,36 @@ requires the serving key: both report aggregate state without request content.
`GET /metrics` returns Prometheus text exposition format 0.0.4 by default.
Counter and gauge names start with `flare_`, such as
`flare_generated_tokens_total`, `flare_active_requests`, and
`flare_free_kv_pages`. The only histograms describe host prefix-store lookups:
`flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, and
`flare_host_cache_estimated_prefill_ns`. Beyond the JSON fields below, the
`flare_free_kv_pages`. Beyond the JSON fields below, the
text includes speculative and proposal counters by batch, width, or depth, graph
launches by kind, embedding row-cache counters, HTTP admission gauges, and
uptime. `flare_history_drafts_enabled` reports whether shared decoded history
augments learned proposals in the serving process.

Histograms appear in the Prometheus format only. Host prefix-store histograms
report lookup cost and retirement: `flare_host_cache_missing_tokens`,
`flare_host_cache_estimated_transfer_ns`,
`flare_host_cache_estimated_prefill_ns`, and
`flare_host_cache_retirement_seconds`. Request histograms observe the served
response. `flare_request_e2e_seconds` counts each successful generation from
admission to the completed response, and
`flare_time_to_first_response_seconds` counts each response that offers answer
or reasoning text, from admission to that text, once the client reads it. The
runtime records one observation per completed generation in
`flare_request_queue_seconds` from model-scheduler arrival to the first model
step that includes the request, `flare_request_prefill_seconds` from that step to
the request's first committed generated token, `flare_request_decode_seconds`
from the first to the last committed generated token,
`flare_time_per_output_token_seconds` as decode time divided by generated tokens
after the first, and `flare_request_prompt_tokens` for prompt tokens including
tokens reused from the prefix cache. Cancelled and failed requests enter only
`flare_requests_cancelled_total` and `flare_requests_failed_total`.

On Linux the text also carries `process_cpu_seconds_total`,
`process_resident_memory_bytes`, `process_virtual_memory_bytes`,
`process_start_time_seconds`, `process_open_fds`, and `process_max_fds` for the
serving process. Other platforms omit them.

The route returns one JSON object instead when the query contains `format=json`,
or when the `Accept` header gives `application/json` a higher quality than
`text/plain`; at equal quality the earlier media range wins. `format=prometheus`
Expand Down Expand Up @@ -879,6 +901,26 @@ before the final usage chunk arrives. Each emitted chunk carries cumulative
native token counts; text chunks can combine multiple tokens, so counting
chunks does not measure generated tokens. The final usage chunk is also emitted.

Final output from Chat Completions, Completions, Messages, and Responses also
carries a llama.cpp-compatible `timings` object. `prompt_ms` spans from the first
model step that included the request to the earliest committed generated token,
and `prompt_n` counts the prompt tokens that step had to prefill, which is
`cache_n` fewer than the prompt total. `predicted_ms` spans the earliest to the
latest committed generated token, and `predicted_n` is the generated-token count
usage reports. `predicted_per_token_ms` and `predicted_per_second` divide that
span by the token intervals after each choice's first token, so one choice
reports its decode rate over its remaining tokens. `draft_n` and
`draft_n_accepted` count speculative drafts offered for verification and accepted;
both keys appear only when drafts were offered. `prompt_per_token_ms`,
`prompt_per_second`, `predicted_per_token_ms`, and `predicted_per_second` report
zero rather than an undefined value when their interval or token count is zero.

Streams carry `timings` on the usage chunk when `stream_options.include_usage` is
set, otherwise on the chunk that completes the last choice. Messages reports it on
the `message_delta` event, and Responses reports it beside `response` on
`response.completed` or `response.incomplete`. The `[DONE]` sentinel, cancelled
requests, and failed requests carry no `timings`.

## Raw completions

`prompt` accepts a string, an array of strings, a token-ID array, or an array of
Expand Down
2 changes: 2 additions & 0 deletions helios/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,7 @@ async fn metrics(State(state): State<Arc<HttpState>>, uri: Uri, headers: HeaderM
use std::fmt::Write;
let _ = writeln!(text, "# HELP flare_first_response_median_seconds Server-side HTTP admission to first offered answer or reasoning text.\n# TYPE flare_first_response_median_seconds gauge\nflare_first_response_median_seconds {median}");
}
state.first_response.render_histogram(&mut text);
for (name, kind, help, value) in input_metrics {
metrics::metric(&mut text, name, kind, help, value);
}
Expand Down Expand Up @@ -705,6 +706,7 @@ async fn metrics(State(state): State<Arc<HttpState>>, uri: Uri, headers: HeaderM
] {
metrics::metric(&mut text, name, "gauge", help, value as u64);
}
metrics::process::render(&mut text);
(
[
(header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8"),
Expand Down
13 changes: 12 additions & 1 deletion helios/src/server/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,9 +519,12 @@ pub(super) async fn generate(
reused_prompt_tokens,
termination,
stop_sequence,
times,
drafts,
..
} => {
reused_total += reused_prompt_tokens;
encoder.record_timing(index, times, drafts);
let result = decoders[index]
.finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination })
.and_then(|events| encoder.apply(index, events))
Expand Down Expand Up @@ -579,6 +582,9 @@ pub(super) async fn generate(
}
}
let mut response = encoder.response();
if let Some(timings) = encoder.timings_value() {
response["timings"] = timings;
}
if protocol == Protocol::Chat {
if let Some(ids) = prompt_ids {
response["prompt_token_ids"] = json!(ids);
Expand All @@ -600,6 +606,7 @@ pub(super) async fn generate(
if streaming {
let request_id = id.clone();
let log_to_stderr = state.log_to_stderr;
let metrics = state.model.metrics_handle();
let events = delivery.filter_map(move |event| {
let event = match event {
Delivery::Frame(frame) => {
Expand All @@ -610,7 +617,10 @@ pub(super) async fn generate(
if log_to_stderr { log_failure(&request_id, "stream", &error); }
Some(Ok::<_, Infallible>(frame.sse()))
}
Delivery::Complete(_) => None,
Delivery::Complete(_) => {
if !count { metrics.request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); }
None
}
};
std::future::ready(event)
});
Expand All @@ -625,6 +635,7 @@ pub(super) async fn generate(
while let Some(event) = delivery.next().await {
match event {
Delivery::Complete(body) => {
if !count { state.model.metrics().request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); }
let visible = super::latency::response_text(&body);
let response = with_request_id(Json(body).into_response(), &id);
if !visible { return response; }
Expand Down
35 changes: 27 additions & 8 deletions helios/src/server/latency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ struct Samples {
dropped_at: Option<Instant>,
}
#[derive(Default)]
pub(super) struct FirstResponseSamples(Mutex<Samples>);
pub(super) struct FirstResponseSamples {
window: Mutex<Samples>,
histogram: super::metrics::Histogram<21>,
}
impl Samples {
fn expire(&mut self, now: Instant) {
while self
Expand Down Expand Up @@ -67,7 +70,7 @@ impl FirstResponseSamples {
}
pub(super) fn snapshot(&self) -> FirstResponseSnapshot {
let (mut seconds, truncated) = {
let mut samples = self.0.lock().unwrap_or_else(|e| e.into_inner());
let mut samples = self.window.lock().unwrap_or_else(|e| e.into_inner());
samples.expire(Instant::now());
(
samples
Expand Down Expand Up @@ -104,13 +107,29 @@ pub(super) struct FirstResponse {
impl FirstResponse {
pub(super) fn output(&mut self) {
if !self.recorded {
let mut samples = self.samples.0.lock().unwrap_or_else(|e| e.into_inner());
samples.record(self.started, Instant::now());
let now = Instant::now();
let mut samples = self.samples.window.lock().unwrap_or_else(|e| e.into_inner());
samples.record(self.started, now);
self.samples.histogram.observe(
&super::metrics::REQUEST_SECONDS,
now.saturating_duration_since(self.started).as_nanos() as u64,
);
self.recorded = true;
}
}
}

impl FirstResponseSamples {
pub(super) fn render_histogram(&self, text: &mut String) {
self.histogram.render(
text,
"time_to_first_response_seconds",
"Server-side HTTP admission to the first offered answer or reasoning text.",
&super::metrics::REQUEST_SECONDS,
);
}
}

/// Only answer/reasoning text is eligible. Roles, keepalives, token observations,
/// usage, signatures and tool-only content do not represent visible text here.
pub(super) fn stream_text(value: &serde_json::Value) -> bool {
Expand Down Expand Up @@ -176,13 +195,13 @@ mod tests {
assert_eq!(empty.samples, 0);
let now = Instant::now();
{
let mut values = samples.0.lock().unwrap();
let mut values = samples.window.lock().unwrap();
for seconds in [4, 1, 2, 3] {
values.values.push_back((now, Duration::from_secs(seconds)));
}
}
assert_eq!(samples.snapshot().median_seconds, Some(2.5));
samples.0.lock().unwrap().expire(now + WINDOW);
samples.window.lock().unwrap().expire(now + WINDOW);
assert_eq!(samples.snapshot().median_seconds, None);
}

Expand All @@ -191,7 +210,7 @@ mod tests {
let samples = FirstResponseSamples::default();
let now = Instant::now();
{
let mut values = samples.0.lock().unwrap();
let mut values = samples.window.lock().unwrap();
for _ in 0..=CAPACITY {
values.record(now, now);
}
Expand All @@ -200,7 +219,7 @@ mod tests {
assert_eq!(snapshot.samples, CAPACITY as u64);
assert_eq!(snapshot.window_seconds, 60);
assert!(snapshot.truncated);
samples.0.lock().unwrap().expire(now + WINDOW);
samples.window.lock().unwrap().expire(now + WINDOW);
let expired = samples.snapshot();
assert_eq!(expired.samples, 0);
assert!(!expired.truncated);
Expand Down
Loading