Repository: vllm-project/vllm

Issue:
[Bug]: Offline Inference with the OpenAI Batch file format yields unnecessary `asyncio.exceptions.CancelledError`
### Your current environment

```text
Collecting environment information...
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.29.3
Libc version: glibc-2.31

Python version: 3.10.14 (main, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-60-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100-SXM4-80GB
Nvidia driver version: 525.105.17
cuDNN version: Could not collect
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
Byte Order:                      Little Endian
Address sizes:                   43 bits physical, 48 bits virtual
CPU(s):                          128
On-line CPU(s) list:             0-127
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7513 32-Core Processor
Stepping:                        1
Frequency boost:                 enabled
CPU MHz:                         3098.695
CPU max MHz:                     3681.6399
CPU min MHz:                     1500.0000
BogoMIPS:                        5189.82
Virtualization:                  AMD-V
L1d cache:                       2 MiB
L1i cache:                       2 MiB
L2 cache:                        32 MiB
L3 cache:                        256 MiB
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 Mmio stale data:   Not affected
Vulnerability Retbleed:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm sme sev sev_es

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] nvidia-nccl-cu12==2.20.5
[pip3] torch==2.3.0
[pip3] triton==2.3.0
[conda] cudatoolkit               11.8.0               h6a678d5_0  
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] nvidia-nccl-cu12          2.20.5                   pypi_0    pypi
[conda] torch                     2.3.0                    pypi_0    pypi
[conda] triton                    2.3.0                    pypi_0    pypiROCM Version: Could not collect
Neuron SDK Version: N/A
vLLM Version: 0.4.3
vLLM Build Flags:
CUDA Archs: Not Set; ROCm: Disabled; Neuron: Disabled
GPU Topology:
GPU0	NIC0	CPU Affinity	NUMA Affinity
GPU0	 X 	PXB	0-31,64-95	0
NIC0	PXB	 X 		

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

NIC Legend:

  NIC0: mlx5_bond_0
```


### 🐛 Describe the bug

The offline Inference with the OpenAI Batch file format yields an unnecessary `asyncio.exceptions.CancelledError` even though it fulfills the requests appropriately.

After following the steps for the usual install I run:

```
wget https://raw.githubusercontent.com/vllm-project/vllm/main/examples/openai_example_batch.jsonl
python -m vllm.entrypoints.openai.run_batch -i openai_example_batch.jsonl -o results.jsonl --model meta-llama/Meta-Llama-3-8B-Instruct
```

which yields the following output:

```
/root/.conda/envs/venv/lib/python3.10/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(
INFO 06-01 11:35:00 llm_engine.py:161] Initializing an LLM engine (v0.4.3) with config: model='meta-llama/Meta-Llama-3-8B-Instruct', speculative_config=None, tokenizer='meta-llama/Meta-Llama-3-8B-Instruct', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, rope_scaling=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=8192, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=False, kv_cache_dtype=auto, quantization_param_path=None, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='outlines'), seed=0, served_model_name=meta-llama/Meta-Llama-3-8B-Instruct)
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
WARNING 06-01 11:35:01 logger.py:146] VLLM_TRACE_FUNCTION is enabled. It will record every function executed by Python. This will slow down the code. It is suggested to be used for debugging hang or crashes only.
INFO 06-01 11:35:01 logger.py:150] Trace frame log is saved to /tmp/vllm/vllm-instance-1f1fb60e04e448b989f2d3eeef714ac3/VLLM_TRACE_FUNCTION_for_process_3702_thread_140538783966400_at_2024-06-01_11:35:01.276871.log
DEBUG 06-01 11:35:01 parallel_state.py:87] world_size=1 rank=0 local_rank=0 distributed_init_method=tcp://172.17.0.12:48437 backend=nccl
INFO 06-01 11:35:02 weight_utils.py:207] Using model weights format ['*.safetensors']
INFO 06-01 11:35:07 model_runner.py:146] Loading model weights took 14.9595 GB
INFO 06-01 11:35:08 gpu_executor.py:83] # GPU blocks: 27973, # CPU blocks: 2048
INFO 06-01 11:35:09 model_runner.py:854] Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI.
INFO 06-01 11:35:09 model_runner.py:858] CUDA graphs can take additional 1~3 GiB memory per GPU. If you are running out of memory, consider decreasing `gpu_memory_utilization` or enforcing eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.
INFO 06-01 11:35:25 model_runner.py:924] Graph capturing finished in 15 secs.
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
INFO 06-01 11:35:27 serving_chat.py:84] Using default chat template:
INFO 06-01 11:35:27 serving_chat.py:84] {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '
' + message['role'] + '

INFO 06-01 11:35:27 serving_chat.py:84] 
INFO 06-01 11:35:27 serving_chat.py:84] '+ message['content'] | trim + '
' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '
assistant

INFO 06-01 11:35:27 serving_chat.py:84] 
INFO 06-01 11:35:27 serving_chat.py:84] ' }}{% endif %}
INFO 06-01 11:35:27 async_llm_engine.py:553] Received request cmpl-9ac7822d394c4eb590bfd6af6c3ae539: prompt: '

system
\n\nYou are a helpful assistant.

user
\n\nHello world!

assistant
\n\n', params: SamplingParams(n=1, best_of=1, presence_penalty=0.0, frequency_penalty=0.0, repetition_penalty=1.0, temperature=0.7, top_p=1.0, top_k=-1, min_p=0.0, seed=None, use_beam_search=False, length_penalty=1.0, early_stopping=False, stop=[], stop_token_ids=[], include_stop_str_in_output=False, ignore_eos=False, max_tokens=1000, min_tokens=0, logprobs=None, prompt_logprobs=None, skip_special_tokens=True, spaces_between_special_tokens=True, truncate_prompt_tokens=None), prompt_token_ids: [128000, 128006, 9125, 128007, 271, 2675, 527, 264, 11190, 18328, 13, 128009, 128006, 882, 128007, 271, 9906, 1917, 0, 128009, 128006, 78191, 128007, 271], lora_request: None.
INFO 06-01 11:35:27 async_llm_engine.py:553] Received request cmpl-5216cb94e03e4263bd89d265f4ab8c56: prompt: '

system
\n\nYou are an unhelpful assistant.

user
\n\nHello world!

assistant
\n\n', params: SamplingParams(n=1, best_of=1, presence_penalty=0.0, frequency_penalty=0.0, repetition_penalty=1.0, temperature=0.7, top_p=1.0, top_k=-1, min_p=0.0, seed=None, use_beam_search=False, length_penalty=1.0, early_stopping=False, stop=[], stop_token_ids=[], include_stop_str_in_output=False, ignore_eos=False, max_tokens=1000, min_tokens=0, logprobs=None, prompt_logprobs=None, skip_special_tokens=True, spaces_between_special_tokens=True, truncate_prompt_tokens=None), prompt_token_ids: [128000, 128006, 9125, 128007, 271, 2675, 527, 459, 653, 8823, 1285, 18328, 13, 128009, 128006, 882, 128007, 271, 9906, 1917, 0, 128009, 128006, 78191, 128007, 271], lora_request: None.
DEBUG 06-01 11:35:27 async_llm_engine.py:514] Waiting for new requests...
DEBUG 06-01 11:35:27 async_llm_engine.py:516] Got new requests!
INFO 06-01 11:35:27 async_llm_engine.py:124] Finished request cmpl-5216cb94e03e4263bd89d265f4ab8c56.
INFO 06-01 11:35:28 async_llm_engine.py:124] Finished request cmpl-9ac7822d394c4eb590bfd6af6c3ae539.
Exception in callback _raise_exception_on_finish(error_callback=<bound method...7fd04ff2d600>>)(<Task cancell...ngine.py:510>>) at /root/.conda/envs/venv/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py:32
handle: <Handle _raise_exception_on_finish(error_callback=<bound method...7fd04ff2d600>>)(<Task cancell...ngine.py:510>>) at /root/.conda/envs/venv/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py:32>
Traceback (most recent call last):
  File "/root/.conda/envs/venv/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py", line 528, in run_engine_loop
    await asyncio.sleep(0)
  File "/root/.conda/envs/venv/lib/python3.10/asyncio/tasks.py", line 596, in sleep
    await __sleep0()
  File "/root/.conda/envs/venv/lib/python3.10/asyncio/tasks.py", line 590, in __sleep0
    yield
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.conda/envs/venv/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/root/.conda/envs/venv/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py", line 40, in _raise_exception_on_finish
    task.result()
asyncio.exceptions.CancelledError
```

The input file, `openai_example_batch.jsonl`, contains two requests: 
```
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "meta-llama/Meta-Llama-3-8B-Instruct", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "meta-llama/Meta-Llama-3-8B-Instruct", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
```

And the output file, `results.jsonl`, contains two responses:
```
{"id":"vllm-3db6165852554c9ca09676d5079efba5","custom_id":"request-1","response":{"id":"cmpl-9ac7822d394c4eb590bfd6af6c3ae539","object":"chat.completion","created":1717266927,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"message":{"role":"assistant","content":"Hello! It's great to meet you! I'm here to help with any questions or tasks you may have. What's on your mind today?"},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":24,"total_tokens":55,"completion_tokens":31}},"error":null}
{"id":"vllm-601cfbcc98d34ddf8e1a6b50581d636e","custom_id":"request-2","response":{"id":"cmpl-5216cb94e03e4263bd89d265f4ab8c56","object":"chat.completion","created":1717266927,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"message":{"role":"assistant","content":"*silence*"},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":26,"total_tokens":31,"completion_tokens":5}},"error":null}
```

So everything appears to be working, but I'm just not sure why an error is being thrown. (I also doubled the size of the input file and still found four responses in the results.)


Discussion:
@wuisawesome can you help take a look? 
Likely related, since it only happened when I sent multiple concurrent requests:

* https://github.com/vllm-project/vllm/issues/2621#issuecomment-2143889481

As detailed in that linked comment, the solution I stumbled upon was to reduce `--gpu-memory-utilization` from `0.99` to `0.96`. Hopefully this provides some clues as to the root cause.
Yeah I've noticed this too and can look into it. I think this is a logging issue when cleaning up the program so it shouldn't be causing a correctness issue. Still worth fixing though I think.

Resolving patch:
diff --git a/vllm/engine/async_llm_engine.py b/vllm/engine/async_llm_engine.py
--- a/vllm/engine/async_llm_engine.py
+++ b/vllm/engine/async_llm_engine.py
@@ -29,23 +29,32 @@ class AsyncEngineDeadError(RuntimeError):
     pass
 
 
-def _raise_exception_on_finish(
-        task: asyncio.Task, error_callback: Callable[[Exception],
-                                                     None]) -> None:
-    msg = ("Task finished unexpectedly. This should never happen! "
-           "Please open an issue on Github.")
+def _log_task_completion(task: asyncio.Task,
+                         error_callback: Callable[[Exception], None]) -> None:
+    """This function is only intended for the `engine.run_engine_loop()` task.
+
+    In particular, that task runs a `while True` loop that can only exit if
+    there is an exception.
+    """
 
     exception = None
     try:
-        task.result()
-        # NOTE: This will be thrown if task exits normally (which it should not)
-        raise AsyncEngineDeadError(msg)
+        return_value = task.result()
+        raise AssertionError(
+            f"The engine background task should never finish without an "
+            f"exception. {return_value}")
+    except asyncio.exceptions.CancelledError:
+        # We assume that if the task is cancelled, we are gracefully shutting
+        # down. This should only happen on program exit.
+        logger.info("Engine is gracefully shutting down.")
     except Exception as e:
         exception = e
         logger.error("Engine background task failed", exc_info=e)
         error_callback(exception)
         raise AsyncEngineDeadError(
-            msg + " See stack trace above for the actual cause.") from e
+            "Task finished unexpectedly. This should never happen! "
+            "Please open an issue on Github. See stack trace above for the"
+            "actual cause.") from e
 
 
 class AsyncStream:
@@ -438,8 +447,7 @@ def start_background_loop(self) -> None:
         self._background_loop_unshielded = asyncio.get_event_loop(
         ).create_task(self.run_engine_loop())
         self._background_loop_unshielded.add_done_callback(
-            partial(_raise_exception_on_finish,
-                    error_callback=self._error_callback))
+            partial(_log_task_completion, error_callback=self._error_callback))
         self.background_loop = asyncio.shield(self._background_loop_unshielded)
 
     def _init_engine(self, *args,


Test patch: