Repository: vllm-project/vllm
Pull request: [Bugfix] Fix logits processor when prompt_logprobs is not None
This is a resubmission of #3023.

This handles `prompt_logprobs` by skipping rows in logits added for the prompt tokens (prompt logprobs are not processed)

Comparing to the previous one, this pr resolves the [comment](https://github.com/vllm-project/vllm/pull/3023#issuecomment-2040557561) of @tjohnson31415.

Related issue: #2141 
Related PR: #2800
FIX #2800

---

<details>
<!-- inside this <details> section, markdown rendering does not work, so we use raw html here. -->
<summary><b> PR Checklist (Click to Expand) </b></summary>

<p>Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.</p>

<h3>PR Title and Classification</h3>
<p>Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:</p>
<ul>
    <li><code>[Bugfix]</code> for bug fixes.</li>
    <li><code>[CI/Build]</code> for build or continuous integration improvements.</li>
    <li><code>[Doc]</code> for documentation fixes and improvements.</li>
    <li><code>[Model]</code> for adding a new model or improving an existing model. Model name should appear in the title.</li>
    <li><code>[Frontend]</code> For changes on the vLLM frontend (e.g., OpenAI API server, <code>LLM</code> class, etc.) </li>
    <li><code>[Kernel]</code> for changes affecting CUDA kernels or other compute kernels.</li>
    <li><code>[Core]</code> for changes in the core vLLM logic (e.g., <code>LLMEngine</code>, <code>AsyncLLMEngine</code>, <code>Scheduler</code>, etc.)</li>
    <li><code>[Hardware][Vendor]</code> for hardware-specific changes. Vendor name should appear in the prefix (e.g., <code>[Hardware][AMD]</code>).</li>
    <li><code>[Misc]</code> for PRs that do not fit the above categories. Please use this sparingly.</li>
</ul>
<p><strong>Note:</strong> If the PR spans more than one category, please include all relevant prefixes.</p>

<h3>Code Quality</h3>

<p>The PR need to meet the following code quality standards:</p>

<ul>
    <li>We adhere to <a href="https://google.github.io/styleguide/pyguide.html">Google Python style guide</a> and <a href="https://google.github.io/styleguide/cppguide.html">Google C++ style guide</a>.</li>
    <li>Pass all linter checks. Please use <a href="https://github.com/vllm-project/vllm/blob/main/format.sh"><code>format.sh</code></a> to format your code.</li>
    <li>The code need to be well-documented to ensure future contributors can easily understand the code.</li>
    <li>Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.</li>
    <li>Please add documentation to <code>docs/source/</code> if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.</li>
</ul>

<h3>Notes for Large Changes</h3>
<p>Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with <code>rfc-required</code> and might not go through the PR.</p>

<h3>What to Expect for the Reviews</h3>

<p>The goal of the vLLM team is to be a <i>transparent reviewing machine</i>. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process: </p>

<ul>
    <li> After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.</li>
    <li> After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.</li>
    <li> After the review, the reviewer will put an <code> action-required</code> label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.</li>
    <li> Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.
 </li>
</ul>

<h3>Thank You</h3>

<p> Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone! </p>


</details>




Problem statement:
[bug] AssertionError with prompt_logprobs and logits_processors both set
version 0.3.0
with prompt_logprobs and logits_processors both set
```
def proc(token_ids, logits_row):
    return logits_row
sampling_params = SamplingParams(temperature=0.8, top_p=0.95, prompt_logprobs=100, logits_processors=[proc])
```
got error
```
  File "/opt/conda/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 74, in forward
    logits = _apply_logits_processors(logits, sampling_metadata)
  File "/opt/conda/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 162, in _apply_logits_processors
    assert logits_row_idx == logits.shape[0]
AssertionError
```

Hints from issue discussion:
In fact, I want a way to get logits (tensor, instead of those dicts of floats or so) of all tokens (including prompts) to calculate ppl outside vllm, tried these params and got the error
Same issue. I think the author @noamgat @hongxiayang @simon-mo might know the answer.

API added here: #1469 
I believe this issue is related to `prompt_logprobs`. A quick solution would be to set `prompt_logprobs` to None (if it applies in your case).

Commit message: Add pytest

Patch to review:
diff --git a/tests/samplers/test_logits_processor.py b/tests/samplers/test_logits_processor.py
new file mode 100644
index 000000000000..4f8afd93c3f1
--- /dev/null
+++ b/tests/samplers/test_logits_processor.py
@@ -0,0 +1,49 @@
+import pytest
+import torch
+
+from vllm import SamplingParams
+
+MODELS = ["facebook/opt-125m"]
+
+
+@pytest.mark.parametrize("model", MODELS)
+@pytest.mark.parametrize("dtype", ["half"])
+def test_logits_processor_force_generate(
+    vllm_runner,
+    example_prompts,
+    model: str,
+    dtype: str,
+) -> None:
+    vllm_model = vllm_runner(model, dtype=dtype)
+    tokenizer = vllm_model.model.get_tokenizer()
+    repeat_times = 2
+    enforced_answers = " vLLM"
+    vllm_token_ids = tokenizer.encode(enforced_answers,
+                                      add_special_tokens=False)
+    max_tokens = len(vllm_token_ids) * repeat_times
+
+    def pick_vllm(token_ids, logits):
+        token_id = vllm_token_ids[len(token_ids) % len(vllm_token_ids)]
+        logits[token_id] = torch.finfo(logits.dtype).max
+        return logits
+
+    params_with_logprobs = SamplingParams(
+        logits_processors=[pick_vllm],
+        prompt_logprobs=3,
+        max_tokens=max_tokens,
+    )
+
+    # test prompt_logprobs is not None
+    vllm_model.model._add_request(prompt=example_prompts[0],
+                                  sampling_params=params_with_logprobs,
+                                  prompt_token_ids=None)
+
+    # test grouped requests
+    vllm_model.model._add_request(
+        prompt=example_prompts[1],
+        sampling_params=SamplingParams(max_tokens=max_tokens),
+        prompt_token_ids=None)
+
+    outputs = vllm_model.model._run_engine(False)
+
+    assert outputs[0].outputs[0].text == enforced_answers * repeat_times
diff --git a/vllm/model_executor/layers/logits_processor.py b/vllm/model_executor/layers/logits_processor.py
index 28e8f6bb7e63..62d5c5867431 100644
--- a/vllm/model_executor/layers/logits_processor.py
+++ b/vllm/model_executor/layers/logits_processor.py
@@ -86,11 +86,17 @@ def _apply_logits_processors(
 ) -> torch.Tensor:
     logits_row_idx = 0
     found_logits_processors = False
-    for seq_ids, sampling_params in sampling_metadata.seq_groups:
+    for i, seq_group in enumerate(sampling_metadata.seq_groups):
+        seq_ids, sampling_params = seq_group
         logits_processors = sampling_params.logits_processors
         if logits_processors:
             found_logits_processors = True
             for seq_id in seq_ids:
+                # handle prompt_logprobs by skipping rows in logits added for
+                # the prompt tokens (prompt logprobs are not processed)
+                if (i < sampling_metadata.num_prompts
+                        and sampling_params.prompt_logprobs is not None):
+                    logits_row_idx += sampling_metadata.prompt_lens[i] - 1
                 logits_row = logits[logits_row_idx]
                 token_ids = sampling_metadata.seq_data[seq_id].output_token_ids
                 for logits_processor in logits_processors:
@@ -100,5 +106,6 @@ def _apply_logits_processors(
         else:
             logits_row_idx += len(seq_ids)
     if found_logits_processors:
+        # verifies that no rows in logits were missed unexpectedly
         assert logits_row_idx == logits.shape[0]
     return logits


Code review comments:
diff_hunk: @@ -86,11 +86,17 @@ def _apply_logits_processors(
 ) -> torch.Tensor:
     logits_row_idx = 0
     found_logits_processors = False
-    for seq_ids, sampling_params in sampling_metadata.seq_groups:
+    for i, seq_group in enumerate(sampling_metadata.seq_groups):
+        seq_ids, sampling_params = seq_group
         logits_processors = sampling_params.logits_processors
         if logits_processors:
             found_logits_processors = True
             for seq_id in seq_ids:
+                # handle prompt_logprobs by skipping rows in logits added for
+                # the prompt tokens (prompt logprobs are not processed)
+                if (i < sampling_metadata.num_prompts
+                        and sampling_params.prompt_logprobs is not None):
+                    logits_row_idx += sampling_metadata.prompt_lens[i] - 1
path: vllm/model_executor/layers/logits_processor.py
text: @user2:
Actually @author I think this should be moved higher, prior to the `if logits_processors:` line.

In the prompt case, `len(seq_ids)` should always be 1 (you could also add an assert like @user1 did [here](https://github.com/vllm-project/vllm/pull/3876/files#diff-a49206d5c29b28f53c18c4c18265a89eb06f11102b2f4d6ee95123ea788a602eR122)).

diff_hunk: @@ -0,0 +1,49 @@
+import pytest
+import torch
+
+from vllm import SamplingParams
+
+MODELS = ["facebook/opt-125m"]
+
+
+@pytest.mark.parametrize("model", MODELS)
+@pytest.mark.parametrize("dtype", ["half"])
+def test_logits_processor_force_generate(
+    vllm_runner,
+    example_prompts,
+    model: str,
+    dtype: str,
+) -> None:
+    vllm_model = vllm_runner(model, dtype=dtype)
+    tokenizer = vllm_model.model.get_tokenizer()
+    repeat_times = 2
+    enforced_answers = " vLLM"
+    vllm_token_ids = tokenizer.encode(enforced_answers,
+                                      add_special_tokens=False)
+    max_tokens = len(vllm_token_ids) * repeat_times
+
+    def pick_vllm(token_ids, logits):
+        token_id = vllm_token_ids[len(token_ids) % len(vllm_token_ids)]
+        logits[token_id] = torch.finfo(logits.dtype).max
+        return logits
+
+    params_with_logprobs = SamplingParams(
+        logits_processors=[pick_vllm],
+        prompt_logprobs=3,
+        max_tokens=max_tokens,
+    )
+
+    # test prompt_logprobs is not None
+    vllm_model.model._add_request(prompt=example_prompts[0],
+                                  sampling_params=params_with_logprobs,
+                                  prompt_token_ids=None)
+
path: tests/samplers/test_logits_processor.py
text: @user1:
@author thank you for adding the test! Perhaps add one more request here which requests `prompt_logprobs` but _doesn't_ have any `logits_processors` (that should fail I think without the latest requested change).

@author:
It fails indeed