Repository: vllm-project/vllm
Pull request: [BugFix] Fix `min_tokens` when `eos_token_id` is None
Fixes #4365

Also fix re-use of index variable `i` within inner loop.

Problem statement:
[Bug]:  When I specify `max-tokens` and `min-tokens` at the same time, the service reports an error in `_apply_min_tokens_penalty`
### Your current environment

```text
Collecting environment information...
PyTorch version: 2.2.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.28.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-4.18.0-240.el8.x86_64-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.3.107
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA L20
GPU 1: NVIDIA L20
GPU 2: NVIDIA L20
GPU 3: NVIDIA L20
GPU 4: NVIDIA L20
GPU 5: NVIDIA L20
GPU 6: NVIDIA L20
GPU 7: NVIDIA L20

Nvidia driver version: 550.54.15
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.0.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Address sizes:                   52 bits physical, 57 bits virtual
Byte Order:                      Little Endian
CPU(s):                          128
On-line CPU(s) list:             0-127
Vendor ID:                       GenuineIntel
BIOS Vendor ID:                  Intel(R) Corporation
Model name:                      Intel(R) Xeon(R) Gold 6430
BIOS Model name:                 Intel(R) Xeon(R) Gold 6430
CPU family:                      6
Model:                           143
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
Stepping:                        8
Frequency boost:                 enabled
CPU max MHz:                     2101.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4200.00
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid cldemote movdiri movdir64b md_clear pconfig flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       3 MiB (64 instances)
L1i cache:                       2 MiB (64 instances)
L2 cache:                        128 MiB (64 instances)
L3 cache:                        120 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-31,64-95
NUMA node1 CPU(s):               32-63,96-127
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:        Vulnerable, IBPB: disabled, STIBP: disabled
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.4
[pip3] nvidia-nccl-cu12==2.19.3
[pip3] onnx==1.15.0rc2
[pip3] onnx-graphsurgeon==0.3.27
[pip3] onnxruntime==1.16.3
[pip3] optree==0.10.0
[pip3] pytorch-quantization==2.1.2
[pip3] torch==2.2.1
[pip3] torchvision==0.17.1
[pip3] triton==2.2.0+e28a256
[conda] _anaconda_depends         2023.09             py311_mkl_1
[conda] blas                      1.0                         mkl
[conda] mkl                       2023.1.0         h213fc3f_46343
[conda] mkl-service               2.4.0           py311h5eee18b_1
[conda] mkl_fft                   1.3.8           py311h5eee18b_0
[conda] mkl_random                1.2.4           py311hdb19cb5_0
[conda] numpy                     1.24.3          py311h08b1b3b_1
[conda] numpy-base                1.24.3          py311hf175353_1
[conda] numpydoc                  1.5.0           py311h06a4308_0  ROCM Version: Could not collect
Neuron SDK Version: N/A
vLLM Version: 0.4.1
vLLM Build Flags:
CUDA Archs: 5.2 6.0 6.1 7.0 7.2 7.5 8.0 8.6 8.7 9.0+PTX; ROCm: Disabled; Neuron: Disabled
GPU Topology:
GPU0	GPU1	GPU2	GPU3	GPU4	GPU5	GPU6	GPU7	CPU Affinity	NUMA Affinity	GPU NUMA ID
GPU0	 X 	PIX	PIX	PIX	SYS	SYS	SYS	SYS	0-31,64-95	0		N/A
GPU1	PIX	 X 	PIX	PIX	SYS	SYS	SYS	SYS	0-31,64-95	0		N/A
GPU2	PIX	PIX	 X 	PIX	SYS	SYS	SYS	SYS	0-31,64-95	0		N/A
GPU3	PIX	PIX	PIX	 X 	SYS	SYS	SYS	SYS	0-31,64-95	0		N/A
GPU4	SYS	SYS	SYS	SYS	 X 	PIX	PIX	PIX	32-63,96-127	1		N/A
GPU5	SYS	SYS	SYS	SYS	PIX	 X 	PIX	PIX	32-63,96-127	1		N/A
GPU6	SYS	SYS	SYS	SYS	PIX	PIX	 X 	PIX	32-63,96-127	1		N/A
GPU7	SYS	SYS	SYS	SYS	PIX	PIX	PIX	 X 	32-63,96-127	1		N/A

Legend:

  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks```
```

### 🐛 Describe the bug

```bash
ERROR 04-25 20:24:29 worker_base.py:157] Error executing method execute_model. This might cause deadlock in distributed execution.
ERROR 04-25 20:24:29 worker_base.py:157] Traceback (most recent call last):
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 149, in execute_method
ERROR 04-25 20:24:29 worker_base.py:157]     return executor(*args, **kwargs)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
ERROR 04-25 20:24:29 worker_base.py:157]     return func(*args, **kwargs)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/worker.py", line 249, in execute_model
ERROR 04-25 20:24:29 worker_base.py:157]     output = self.model_runner.execute_model(seq_group_metadata_list,
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
ERROR 04-25 20:24:29 worker_base.py:157]     return func(*args, **kwargs)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 858, in execute_model
ERROR 04-25 20:24:29 worker_base.py:157]     output = self.model.sample(
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/models/qwen.py", line 252, in sample
ERROR 04-25 20:24:29 worker_base.py:157]     next_tokens = self.sampler(logits, sampling_metadata)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
ERROR 04-25 20:24:29 worker_base.py:157]     return self._call_impl(*args, **kwargs)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
ERROR 04-25 20:24:29 worker_base.py:157]     return forward_call(*args, **kwargs)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 56, in forward
ERROR 04-25 20:24:29 worker_base.py:157]     logits = _apply_min_tokens_penalty(logits, sampling_metadata)
ERROR 04-25 20:24:29 worker_base.py:157]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 188, in _apply_min_tokens_penalty
ERROR 04-25 20:24:29 worker_base.py:157]     logits[tuple(zip(*logits_to_penalize))] = -float("inf")
ERROR 04-25 20:24:29 worker_base.py:157] RuntimeError: Could not infer dtype of NoneType
ERROR 04-25 20:24:29 async_llm_engine.py:43] Engine background task failed
```
after that, the metrics log always show me: `Running: 1 reqs`
```bash 
3%, CPU KV cache usage: 0.0%
INFO 04-25 20:28:30 metrics.py:229] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 1 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 1.3%, CPU KV cache usage: 0.0%
INFO 04-25 20:28:40 metrics.py:229] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 1 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 1.3%, CPU KV cache usage: 0.0%
```

Hints from issue discussion:
@youkaichao can you take a look? many thanks~
@DefTruth could you provide the exact request parameters you're using to trigger this?
@njhill 
- launch server   
```bash 
python3 -m vllm.entrypoints.openai.api_server \
    --model Qwen/Qwen-72B-Chat \
    --tensor-parallel-size 8 \
    --max-model-len 8192 \
    --trust-remote-code \
    --disable-custom-all-reduce \
    --enable-prefix-caching \
    --tokenizer-mode slow \
    --enforce-eager \
    --gpu-memory-utilization 0.9 \
    --port 8861
```
- curl completion api with `min_tokens` > 0 
```bash 
curl http://localhost:8861/v1/completions \
     -H "Content-Type: application/json" \
     -d '{
            "model": "Qwen/Qwen-72B-Chat",
             "prompt": "你是谁？",
             "max_tokens": 256,
             "min_tokens": 128,
             "temperature": 0.0,
             "stream":true
          }'
```
Then will hit  this crash issue. more log:  
```bash
ERROR 04-26 10:18:02 worker_base.py:147] Error executing method execute_model. This might cause deadlock in distributed execution.
ERROR 04-26 10:18:02 worker_base.py:147] Traceback (most recent call last):
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 139, in execute_method
ERROR 04-26 10:18:02 worker_base.py:147]     return executor(*args, **kwargs)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
ERROR 04-26 10:18:02 worker_base.py:147]     return func(*args, **kwargs)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/worker.py", line 249, in execute_model
ERROR 04-26 10:18:02 worker_base.py:147]     output = self.model_runner.execute_model(seq_group_metadata_list,
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
ERROR 04-26 10:18:02 worker_base.py:147]     return func(*args, **kwargs)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 858, in execute_model
ERROR 04-26 10:18:02 worker_base.py:147]     output = self.model.sample(
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/models/qwen.py", line 252, in sample
ERROR 04-26 10:18:02 worker_base.py:147]     next_tokens = self.sampler(logits, sampling_metadata)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
ERROR 04-26 10:18:02 worker_base.py:147]     return self._call_impl(*args, **kwargs)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
ERROR 04-26 10:18:02 worker_base.py:147]     return forward_call(*args, **kwargs)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 56, in forward
ERROR 04-26 10:18:02 worker_base.py:147]     logits = _apply_min_tokens_penalty(logits, sampling_metadata)
ERROR 04-26 10:18:02 worker_base.py:147]   File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/vllm/model_executor/layers/sampler.py", line 188, in _apply_min_tokens_penalty
ERROR 04-26 10:18:02 worker_base.py:147]     logits[tuple(zip(*logits_to_penalize))] = -float("inf")
ERROR 04-26 10:18:02 worker_base.py:147] RuntimeError: Could not infer dtype of NoneType
vllm.engine.async_llm_engine.AsyncEngineDeadError: Task finished unexpectedly. This should never happen! Please open an issue on Github. See stack trace above for the actual cause.
INFO 04-26 10:18:02 async_llm_engine.py:154] Aborted request cmpl-9b46820086b64d739819b02e9e7457c4-0.
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 265, in __call__
    await wrap(partial(self.listen_for_disconnect, receive))
  File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 261, in wrap
    await func()
  File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 238, in listen_for_disconnect
    message = await receive()
  File "/root/anaconda3/envs/vllm/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 568, in receive
    await self.message_event.wait()
  File "/root/anaconda3/envs/vllm/lib/python3.10/asyncio/locks.py", line 214, in wait
    await fut
```
After this error, the server no longer works properly. All new requests trigger the same error.
vLLM commit id (I use the latest commit): 
```bash
cf29b7e (origin/main, origin/HEAD, main) [ROCm][Hardware][AMD][Doc] Documentation update for ROCm (#4376)
```
@njhill I have submit a PR to fix this error https://github.com/vllm-project/vllm/pull/4386 , can you take a look?

Commit message: [BugFix] Fix min_tokens when eos_token_id is None

Co-authored-by: DefTruth <31974251+deftruth@users.noreply.github.com>

Patch to review:
diff --git a/vllm/model_executor/layers/sampler.py b/vllm/model_executor/layers/sampler.py
index c4b11cb33a67..5d36d6b52f3d 100644
--- a/vllm/model_executor/layers/sampler.py
+++ b/vllm/model_executor/layers/sampler.py
@@ -163,19 +163,22 @@ def _apply_min_tokens_penalty(
             start_idx += sampling_metadata.prompt_lens[i] - 1
 
         min_tokens = sampling_params.min_tokens
-        if min_tokens > 0:
+        eos_token_id = sampling_params.eos_token_id
+        stop_token_ids = sampling_params.stop_token_ids
+        if min_tokens > 0 and (eos_token_id is not None or stop_token_ids):
             seqs_to_penalize = []
-            for i, seq_id in enumerate(seq_ids):
+            for j, seq_id in enumerate(seq_ids):
                 seq_data = sampling_metadata.seq_data[seq_id]
                 if len(seq_data.output_token_ids) < min_tokens:
-                    seqs_to_penalize.append(i)
+                    seqs_to_penalize.append(j)
 
             if seqs_to_penalize:
                 # convert to the index into logits
-                seqs_to_penalize = [start_idx + i for i in seqs_to_penalize]
-                # use set() to remove any duplicates
-                token_ids_to_penalize = set(sampling_params.stop_token_ids +
-                                            [sampling_params.eos_token_id])
+                seqs_to_penalize = [start_idx + j for j in seqs_to_penalize]
+                if eos_token_id is None or eos_token_id in stop_token_ids:
+                    token_ids_to_penalize = stop_token_ids
+                else:
+                    token_ids_to_penalize = stop_token_ids + [eos_token_id]
                 # itertools.product pairs each seq index with every token id
                 logits_to_penalize.extend(
                     itertools.product(seqs_to_penalize, token_ids_to_penalize))


Code review comments:
diff_hunk: @@ -163,19 +163,22 @@ def _apply_min_tokens_penalty(
             start_idx += sampling_metadata.prompt_lens[i] - 1
 
         min_tokens = sampling_params.min_tokens
-        if min_tokens > 0:
+        eos_token_id = sampling_params.eos_token_id
+        stop_token_ids = sampling_params.stop_token_ids
+        if min_tokens > 0 and (eos_token_id is not None or stop_token_ids):
             seqs_to_penalize = []
-            for i, seq_id in enumerate(seq_ids):
+            for j, seq_id in enumerate(seq_ids):
                 seq_data = sampling_metadata.seq_data[seq_id]
                 if len(seq_data.output_token_ids) < min_tokens:
-                    seqs_to_penalize.append(i)
+                    seqs_to_penalize.append(j)
 
             if seqs_to_penalize:
                 # convert to the index into logits
-                seqs_to_penalize = [start_idx + i for i in seqs_to_penalize]
-                # use set() to remove any duplicates
-                token_ids_to_penalize = set(sampling_params.stop_token_ids +
-                                            [sampling_params.eos_token_id])
+                seqs_to_penalize = [start_idx + j for j in seqs_to_penalize]
+                if eos_token_id is None or eos_token_id in stop_token_ids:
+                    token_ids_to_penalize = stop_token_ids
+                else:
+                    token_ids_to_penalize = stop_token_ids + [eos_token_id]
path: vllm/model_executor/layers/sampler.py
text: @user1:
I think it may be better to convert `token_ids_to_penalize` to `set()` object, in order to remove any duplicates

@user1:
stop_token_ids may have duplicates itself, for examples: if pass stop_token_ids=[2, 2, 111] to sampling_param by user.

@user1:
@author @user2-mo 

@author:
@user1 it would probably be better to de-dup the stop_token_ids up-front when the sampling params are received, so that we're not creating a set here on every iteration. Let me make an update for that.

@user1:
> @user1 it would probably be better to de-dup the stop_token_ids up-front when the sampling params are received, so that we're not creating a set here on every iteration. Let me make an update for that.

sounds better ~ 

@author:
@user1 OK I've pushed a commit for that. Thanks, I think this looks much better!