Skip to content
4 changes: 2 additions & 2 deletions docs/serving/online_serving/derenderer.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ The server keeps no state between calls. Everything the next call needs is in `s
- **Send `prompt_token_ids` on the first chunk, even without a parser.** It seeds detokenization so the first token's leading space matches the coupled endpoint (see [Request format](#request-format)). Later chunks already carry that context in `stream_state`.
- **Don't forward `[DONE]`.** It marks the end of the generate stream and isn't a chunk.

Streaming derender resolves `logprobs` on the plain detokenization path, including `token_id:N` placeholders, same as the non-streaming endpoints (see [Streaming state and logprobs](#streaming-state-and-logprobs)). The parser path doesn't resolve them yet and drops them.
`/inference/v1/generate` returns `GenerateLogProbs` with integer `token_id`s (the generate server has no tokenizer), and derender turns those into `ChatCompletionLogProbs` / `CompletionLogProbs`, filling `token` and `bytes` from the tokenizer with the usual U+FFFD byte-fallback correction. Streaming derender does the same per chunk on the plain detokenization path (see [Streaming state and logprobs](#streaming-state-and-logprobs)). The parser path doesn't resolve them yet and drops them.

## Streaming cost

Expand All @@ -129,7 +129,7 @@ Streaming derender is stateless on the server side: all mutable state lives in t
- `logprob_context_token_ids`: the trailing sampled token IDs (at most 4) from previous chunks, used to seed byte-fallback (U+FFFD) correction so multi-byte characters whose tokens split across chunk boundaries still resolve to real strings
- `logprob_text_offset`: the cumulative emitted text length, so `text_offset` in completion streaming logprobs stays absolute across chunks instead of restarting at 0

When a streamed `GenerateTokensStreamChoice` carries `logprobs`, the `token_id:N` placeholders are resolved per chunk and the resolved logprobs are attached to the corresponding streamed choice. For chat it is as `ChatCompletionLogProbs` and for completions it is converted to the flat `CompletionLogProbs` lists. Chunks without `logprobs` produce choices with `logprobs: null`.
When a streamed `GenerateTokensStreamChoice` carries `logprobs`, the integer `token_id`s are decoded per chunk and the resolved logprobs are attached to the corresponding streamed choice. For chat it is as `ChatCompletionLogProbs` and for completions it is converted to the flat `CompletionLogProbs` lists. Chunks without `logprobs` produce choices with `logprobs: null`.

## Example

Expand Down
53 changes: 53 additions & 0 deletions docs/serving/online_serving/renderer.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,59 @@ for the existing authentication boundaries.

For the post processing counterpart that turns generated token IDs back into OpenAI compatible responses, see the [Derenderer APIs](derenderer.md).

## Generate Output Logprobs

`/inference/v1/generate` is a token in / token out API, so its output logprobs
identify tokens by integer ID rather than by the OpenAI string token. With
`sampling_params.logprobs` set and `output_mode: "tokens"` (the default), each
choice carries a `GenerateLogProbs`; `output_mode: "text"` returns decoded
`ChatCompletionLogProbs` instead (see [token in, token out](token_in_token_out.md)):

```json
{
"logprobs": {
"content": [
{
"token_id": 262,
"logprob": -0.10,
"rank": 1,
"top_logprobs": [
{"token_id": 262, "logprob": -0.10, "rank": 1},
{"token_id": 257, "logprob": -1.20, "rank": 2}
]
}
]
}
}
```

- `content` has one entry per generated token, in generation order.
- `top_logprobs` is a list, not a dict: JSON turns dict keys into strings and
the ordering would be implicit. It follows the engine's order: the sampled
token first, then the remaining candidates in rank order. With non-greedy
sampling the sampled token can sit outside the top k (for example ranks
`[5, 1, 2]` at `logprobs=2`); it then takes one of the `logprobs` slots and
the rank-k candidate is left out, as on the OpenAI endpoints.
- `rank` is the token's rank in the vocabulary distribution (1 = most likely)
on every entry, the sampled one included; a top-k candidate's rank is its
top-k position. The list is not sorted by it, so sort by `rank` if you need
rank order.
- There is no `token` or `bytes` field. The generate server has no tokenizer;
[derender](derenderer.md) fills those in when it converts the response to the
OpenAI shapes.
- `prompt_logprobs` on the same response is unchanged
(`list[dict[int, Logprob] | None]`).

!!! warning "Changed in this release"
Output logprobs used to be `ChatCompletionLogProbs` with every token written
as a `"token_id:N"` placeholder string, and `bytes` set to the UTF-8 bytes of
that placeholder by the Rust frontend but left unset by the Python one.
Clients that read only `content[i].logprob` are unaffected. Clients that
parsed the placeholder should read `content[i].token_id` instead.
`return_tokens_as_token_ids` on `/v1/chat/completions` and `/v1/completions`
is unchanged: it is a user-facing OpenAI option and still uses the
`token_id:N` format.

## Multimodal Render Features

Multimodal render responses include a `features` object with per-modality
Expand Down
2 changes: 1 addition & 1 deletion docs/serving/online_serving/token_in_token_out.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ print(response["choices"][0]["token_ids"])

### Logprobs

With `output_mode: "tokens"`, logprob entries carry `token_id:N` placeholders. With `output_mode: "text"`, they carry the decoded token strings and their UTF-8 `bytes` for the sampled token and every entry in `top_logprobs`. A server started with `--return-tokens-as-token-ids` always returns the placeholders, as `/v1/completions` does.
With `output_mode: "tokens"`, logprobs are `GenerateLogProbs` with an integer `token_id` and `rank` per entry and no `token` or `bytes` (see [Generate Output Logprobs](renderer.md#generate-output-logprobs)). With `output_mode: "text"`, they are `ChatCompletionLogProbs` carrying the decoded token strings and their UTF-8 `bytes` for the sampled token and every entry in `top_logprobs`; a server started with `--return-tokens-as-token-ids` returns `token_id:N` placeholders there instead, as `/v1/completions` does.

### Errors

Expand Down
113 changes: 87 additions & 26 deletions rust/src/server/src/routes/inference/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,17 @@ use vllm_llm::{

use self::convert::{ResponseOptions, prepare_generate_request};
use self::types::{
GenerateLogprob, GenerateResponse, GenerateResponseChoice, GenerateResponseStreamChoice,
GenerateStreamResponse, MultiModalPlaceholders, PerRequestMetrics, PlaceholderRangeInfo,
SpeculativeDecodingMetrics, StreamingSpeculativeDecodingMetrics,
GenerateLogProb, GenerateLogProbs, GenerateLogProbsContent, GenerateLogprob, GenerateResponse,
GenerateResponseChoice, GenerateResponseStreamChoice, GenerateStreamResponse,
MultiModalPlaceholders, PerRequestMetrics, PlaceholderRangeInfo, SpeculativeDecodingMetrics,
StreamingSpeculativeDecodingMetrics,
};
pub(crate) use self::types::{GenerateRequest, GenerateSamplingParams};
pub(crate) use self::validate::validate_request_compat;
use crate::config::ApiServerOptions;
use crate::error::{ApiError, bail_server_error, server_error, text_submit_error};
use crate::routes::openai::utils::logprobs::clamp_logprob;
use crate::routes::openai::utils::types::{ChatLogProbs, ChatLogProbsContent, TopLogProb, Usage};
use crate::routes::openai::utils::types::Usage;
use crate::routes::openai::utils::validated_json::ValidatedJson;
use crate::state::AppState;
use crate::utils::{resolve_request_context, sse_response};
Expand Down Expand Up @@ -157,7 +158,7 @@ async fn generate_chunk_stream(
ResponseOptions {
include_usage,
include_continuous_usage,
include_logprobs,
logprobs: output_logprobs,
// Ignored: raw generate streaming has no prompt-logprobs wire shape.
include_prompt_logprobs: _,
return_token_ids,
Expand Down Expand Up @@ -212,13 +213,15 @@ async fn generate_chunk_stream(
continue;
}

let logprobs = if include_logprobs && !token_ids.is_empty() {
let logprobs = if let Some(requested) = output_logprobs
&& !token_ids.is_empty()
{
let logprobs = output.logprobs.as_ref().ok_or_else(|| {
server_error!(
"raw generate stream requested logprobs but generation returned none"
)
})?;
Some(raw_logprobs_to_openai_chat(logprobs)?)
Some(raw_logprobs_to_generate(logprobs, requested)?)
} else {
None
};
Expand Down Expand Up @@ -282,19 +285,19 @@ fn collect_generate(
include_usage: _,
// Ignored: continuous usage is a streaming-only option.
include_continuous_usage: _,
include_logprobs,
logprobs: output_logprobs,
include_prompt_logprobs,
return_token_ids,
}: ResponseOptions,
mm_placeholders: Option<MultiModalPlaceholders>,
) -> Result<GenerateResponse, ApiError> {
let logprobs = if include_logprobs {
let logprobs = if let Some(requested) = output_logprobs {
let logprobs = collected.logprobs.as_ref().ok_or_else(|| {
ApiError::server_error(
"raw generate response requested logprobs but generation returned none".to_string(),
)
})?;
Some(raw_logprobs_to_openai_chat(logprobs)?)
Some(raw_logprobs_to_generate(logprobs, requested)?)
} else {
None
};
Expand Down Expand Up @@ -371,14 +374,17 @@ fn extract_mm_placeholders(features: Option<&[MmFeatureSpec]>) -> Option<MultiMo
Some(placeholders)
}

fn raw_logprobs_to_openai_chat(logprobs: &Logprobs) -> Result<ChatLogProbs, ApiError> {
fn raw_logprobs_to_generate(
logprobs: &Logprobs,
requested: i32,
) -> Result<GenerateLogProbs, ApiError> {
let content = logprobs
.positions
.iter()
.map(position_to_chat_logprobs_content)
.map(|position| position_to_generate_logprobs_content(position, requested))
.collect::<Result<Vec<_>, _>>()?;

Ok(ChatLogProbs {
Ok(GenerateLogProbs {
content: Some(content),
})
}
Expand All @@ -396,30 +402,36 @@ fn raw_prompt_logprobs_to_maps(
.collect()
}

fn position_to_chat_logprobs_content(
/// `top_logprobs` matches the Python generate server: the engine's entries (the
/// sampled token first, then ranks 1..k) with repeated token ids dropped, cut to
/// `max(requested, 1)` entries, or all of them for `-1`.
fn position_to_generate_logprobs_content(
position: &PositionLogprobs,
) -> Result<ChatLogProbsContent, ApiError> {
requested: i32,
) -> Result<GenerateLogProbsContent, ApiError> {
let chosen = position.entries.first().ok_or_else(|| {
ApiError::server_error(
"raw generate logprobs position unexpectedly had no token candidates".to_string(),
)
})?;
let token = format_token_id(chosen.token_id);

Ok(ChatLogProbsContent {
token: token.clone(),
Ok(GenerateLogProbsContent {
token_id: chosen.token_id,
logprob: clamp_logprob(chosen.logprob),
bytes: Some(token.as_bytes().to_vec()),
rank: Some(chosen.rank),
Comment thread
DarkLight1337 marked this conversation as resolved.
Resolved
top_logprobs: position
.entries
.iter()
.map(|entry| {
let token = format_token_id(entry.token_id);
TopLogProb {
token: token.clone(),
logprob: clamp_logprob(entry.logprob),
bytes: Some(token.into_bytes()),
}
.enumerate()
.filter(|(i, entry)| {
!position.entries[..*i].iter().any(|earlier| earlier.token_id == entry.token_id)
})
.map(|(_, entry)| entry)
.take(usize::try_from(requested).map_or(usize::MAX, |n| n.max(1)))
Comment thread
DarkLight1337 marked this conversation as resolved.
Resolved
.map(|entry| GenerateLogProb {
token_id: entry.token_id,
logprob: clamp_logprob(entry.logprob),
rank: Some(entry.rank),
})
.collect(),
})
Expand Down Expand Up @@ -523,6 +535,55 @@ mod tests {

use super::*;

fn position(entries: &[(u32, f32, u32)]) -> PositionLogprobs {
PositionLogprobs {
entries: entries
.iter()
.map(|&(token_id, logprob, rank)| {
vllm_engine_core_client::protocol::logprobs::TokenLogprob {
token_id,
logprob,
rank,
}
})
.collect(),
}
}

fn top(position: &PositionLogprobs, requested: i32) -> Vec<(u32, Option<u32>)> {
position_to_generate_logprobs_content(position, requested)
.unwrap()
.top_logprobs
.iter()
.map(|entry| (entry.token_id, entry.rank))
.collect()
}

#[test]
fn generate_top_logprobs_drop_the_repeated_sampled_token() {
// Sampled token 7 is also top-1: the engine row is [7, 7, 8].
let pos = position(&[(7, -0.1, 1), (7, -0.1, 1), (8, -2.0, 2)]);
assert_eq!(top(&pos, 2), vec![(7, Some(1)), (8, Some(2))]);
}

#[test]
fn generate_top_logprobs_keep_sampled_first_when_outside_top_k() {
// Sampled token 50 has vocab rank 5; it takes a slot and rank 2 drops
// out, as on the Python generate server and the OpenAI endpoints.
let pos = position(&[(50, -3.0, 5), (10, -0.2, 1), (20, -1.0, 2)]);
assert_eq!(top(&pos, 2), vec![(50, Some(5)), (10, Some(1))]);
}

#[test]
fn generate_top_logprobs_respect_zero_and_all() {
let pos = position(&[(7, -0.1, 1), (7, -0.1, 1), (8, -2.0, 2), (9, -3.0, 3)]);
assert_eq!(top(&pos, 0), vec![(7, Some(1))]);
assert_eq!(
top(&pos, -1),
vec![(7, Some(1)), (8, Some(2)), (9, Some(3))]
);
}

#[tokio::test]
async fn generate_chunk_stream_captures_late_prompt_info() {
let stream = stream::iter(vec![
Expand Down
10 changes: 6 additions & 4 deletions rust/src/server/src/routes/inference/generate/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ pub(super) struct ResponseOptions {
pub include_usage: bool,
/// Whether the caller asked for usage on every streamed chunk.
pub include_continuous_usage: bool,
/// Whether the caller requested output logprobs on generate choices.
pub include_logprobs: bool,
/// Requested output logprobs (`sampling_params.logprobs`): `None` omits
/// them, `Some(n)` returns `max(n, 1)` candidates per position, `Some(-1)`
/// all of them.
pub logprobs: Option<i32>,
/// Whether the caller requested top-level prompt logprobs.
pub include_prompt_logprobs: bool,
/// Whether the caller requested final prompt token metadata.
Expand Down Expand Up @@ -56,7 +58,7 @@ pub(super) fn prepare_generate_request(
.as_ref()
.and_then(|options| options.continuous_usage_stats)
.unwrap_or(false);
let include_logprobs = request.sampling_params.inner.logprobs.is_some();
let logprobs = request.sampling_params.inner.logprobs;
let include_prompt_logprobs = request.sampling_params.inner.prompt_logprobs.is_some();
let return_token_ids = request.return_token_ids.unwrap_or(false);
let mut sampling_params = request.sampling_params.inner;
Expand Down Expand Up @@ -96,7 +98,7 @@ pub(super) fn prepare_generate_request(
options: ResponseOptions {
include_usage,
include_continuous_usage,
include_logprobs,
logprobs,
include_prompt_logprobs,
return_token_ids,
},
Expand Down
32 changes: 29 additions & 3 deletions rust/src/server/src/routes/inference/generate/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use validator::Validate;
use vllm_engine_core_client::protocol::output::RequestSpecDecodeMetrics;
use vllm_text::SamplingParams;

use crate::routes::openai::utils::types::{ChatLogProbs, Normalizable, StreamOptions, Usage};
use crate::routes::openai::utils::types::{Normalizable, StreamOptions, Usage};

/// Sampling parameters for the token-in/token-out generate API.
///
Expand Down Expand Up @@ -61,7 +61,7 @@ impl Normalizable for GenerateRequest {}
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateResponseChoice {
pub index: u32,
pub logprobs: Option<ChatLogProbs>,
pub logprobs: Option<GenerateLogProbs>,
pub finish_reason: Option<String>,
pub token_ids: Vec<u32>,
pub sampling_mask: Option<Vec<Vec<u32>>>,
Expand All @@ -72,7 +72,7 @@ pub(super) struct GenerateResponseChoice {
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateResponseStreamChoice {
pub index: u32,
pub logprobs: Option<ChatLogProbs>,
pub logprobs: Option<GenerateLogProbs>,
pub finish_reason: Option<String>,
pub token_ids: Vec<u32>,
pub sampling_mask: Option<Vec<Vec<u32>>>,
Expand Down Expand Up @@ -197,6 +197,32 @@ pub(super) struct PlaceholderRangeInfo {
pub length: usize,
}

/// Mirrors the Python vLLM `GenerateLogProbs` class: output logprobs for one
/// choice, carrying integer token ids rather than the OpenAI string token.
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateLogProbs {
pub content: Option<Vec<GenerateLogProbsContent>>,
}

/// Mirrors the Python vLLM `GenerateLogProbsContent` class: the sampled token
/// at one position plus its top-k candidates, in the engine's order: the
/// sampled token first, then the remaining candidates in rank order.
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateLogProbsContent {
pub token_id: u32,
pub logprob: f32,
pub rank: Option<u32>,
pub top_logprobs: Vec<GenerateLogProb>,
}

/// Mirrors the Python vLLM `GenerateLogProb` class: one candidate token.
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateLogProb {
pub token_id: u32,
pub logprob: f32,
pub rank: Option<u32>,
}

/// Mirrors the Python vLLM `Logprob` class used in prompt-logprobs payloads.
#[derive(Debug, Clone, Serialize)]
pub(super) struct GenerateLogprob {
Expand Down
Loading
Loading