Repository navigation
Description
System Info
- TensorRT-LLM 1.4.0rc3, PyTorch backend (
TorchSampler). The code path below is the same on main (c2ea6bc). - x86_64, NVIDIA L40S 48 GB, CUDA 13.0, Python 3.12, torch 2.14.0, transformers 5.5.4
Who can help?
Not sure whom to tag; CODEOWNERS lists NVIDIA/trt-llm-runtime-devs for sampling_params.py. logprobs_mode was added in #9675.
Information
- The official example scripts
- My own modified scripts
Tasks
- An officially supported task in the
examplesfolder (such as GLUE/SQuAD, ...) - My own task or dataset (give details below)
Reproduction
Greedy decoding of one token with logprobs=5 (default logprobs_mode="raw"), with and without a penalty. The penalties count prompt tokens, so they already change the logits of the first generated token. The script prints the raw logprobs of the three most likely tokens next to log_softmax of the generation logits the same request returns.
"""Raw logprobs of the first generated token under different sampling parameters.
LogprobMode.RAW is documented as "the log probabilities calculated directly from the model output logits", so the
raw logprobs of step 0 should not depend on the penalties. Also compares them with log_softmax of the generation
logits the same request returns.
"""
import torch
from tensorrt_llm import LLM, SamplingParams
from tensorrt_llm.llmapi import KvCacheConfig
PROMPT = "The cat sat on the mat. The cat sat on the"
CONFIGS = {
"no penalty": {},
"repetition_penalty=1.3": {"repetition_penalty": 1.3},
"presence_penalty=1.0": {"presence_penalty": 1.0},
"frequency_penalty=1.0": {"frequency_penalty": 1.0},
}
def main() -> None:
# host_cache_size=0 only works around NVIDIA/TensorRT-LLM#20967 on this host.
llm = LLM("Qwen/Qwen2.5-0.5B-Instruct", kv_cache_config=KvCacheConfig(free_gpu_memory_fraction=0.5, host_cache_size=0))
tokenizer = llm.tokenizer
watch = None
for name, kwargs in CONFIGS.items():
params = SamplingParams(max_tokens=1, temperature=0.0, logprobs=5, return_generation_logits=True, **kwargs)
out = llm.generate([PROMPT], params, use_tqdm=False)[0].outputs[0]
step0 = out.logprobs[0]
if watch is None:
watch = sorted(step0, key=lambda t: step0[t].rank)[:3]
ref = torch.log_softmax(out.generation_logits[0].float(), dim=-1)
cells = []
for t in watch:
got = f"{step0[t].logprob:.3f}" if t in step0 else "not in top-5"
cells.append(f"{tokenizer.decode([t])!r}: raw {got} / log_softmax(generation_logits) {ref[t].item():.3f}")
print(f"{name:24s} sampled {tokenizer.decode(out.token_ids)!r:8s} | " + " | ".join(cells), flush=True)
llm.shutdown()
if __name__ == "__main__":
main()no penalty sampled ' mat' | ' mat': raw -0.460 / log_softmax(generation_logits) -0.460 | ' bed': raw -3.773 / log_softmax(generation_logits) -3.772 | ' floor': raw -3.773 / log_softmax(generation_logits) -3.772
repetition_penalty=1.3 sampled ' floor' | ' mat': raw -3.394 / log_softmax(generation_logits) -0.468 | ' bed': raw -2.784 / log_softmax(generation_logits) -3.781 | ' floor': raw -2.721 / log_softmax(generation_logits) -3.718
presence_penalty=1.0 sampled ' mat' | ' mat': raw -0.945 / log_softmax(generation_logits) -0.468 | ' bed': raw -3.258 / log_softmax(generation_logits) -3.781 | ' floor': raw -3.195 / log_softmax(generation_logits) -3.718
frequency_penalty=1.0 sampled ' mat' | ' mat': raw -0.938 / log_softmax(generation_logits) -0.468 | ' bed': raw -3.251 / log_softmax(generation_logits) -3.781 | ' floor': raw -3.188 / log_softmax(generation_logits) -3.718
Expected behavior
LogprobMode.RAW is documented as "the log probabilities calculated directly from the model output logits", and the note added in #12514 describes the PyTorch backend's default as computing "log probs from the raw model logits without temperature scaling". So the raw logprobs of the first token should be the same in all four rows, and equal to log_softmax(generation_logits), as they are in the first row. vLLM defines its default raw_logprobs mode the same way: "the values before applying any logit processors".
actual behavior
The raw logprobs include the penalty. ' mat' is -0.460 without a penalty, -3.394 with repetition_penalty=1.3, and -0.945 / -0.938 with presence_penalty=1.0 / frequency_penalty=1.0, while log_softmax(generation_logits) stays at -0.468 in every penalized run. Temperature is correctly left out of raw logprobs; the penalties are not.
I first saw this in a comparison against a Hugging Face fp32 reference on the same token ids (Qwen2.5-0.5B-Instruct and Llama-3.2-1B-Instruct, 8 prompts, 24 tokens each): with repetition_penalty=1.3 the raw logprob was off by more than 0.25 for 85 of 188 and 69 of 187 generated tokens (up to 7.6), while the greedy, temperature, top-k and top-p runs matched within bf16 noise apart from a few tokens at the top-k/top-p cutoff.
additional notes
In TorchSampler._process_requests (tensorrt_llm/_torch/pyexecutor/sampler/sampler.py), apply_embedding_bias, PenaltyHandler.apply ("Apply repetition/presence/frequency penalties in place") and the token-ban handler (bad words, min_length, no_repeat_ngram_size) modify logits_cuda in place before sampling. _process_logprobs then computes the raw logprobs from that same tensor (selected_raw_logprobs(logits_cuda, ...)), while temperature and top-k/top-p are applied only on the processed path. So the embedding bias and token bans most likely reach raw logprobs the same way; I only measured the three penalties.
If raw is meant to exclude these, one option is to read the raw logprobs from the logits before the in-place steps, only for requests that ask for raw logprobs and use a penalty, bias or ban. I can send a PR for that, or for a docstring change if the current behavior is intended.
Activity
[NVIDIA#22299][fix] Keep only the raw-logprob rows that logit rewrite…
[NVIDIA#22299][fix] Skip multi-beam requests when copying raw-logprob…
[#22299][fix] Read raw logprobs from the logits before penalties and …