main
py 62 lines 2.44 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 import pytest
5 import torch.cuda
6
7 from vllm import LLM, SamplingParams
8 from vllm.platforms import current_platform
9 from vllm.v1.engine import EngineCoreRequest
10 from vllm.v1.engine.core import EngineCore
11
12 MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
13
14
15 def test_preprocess_error_handling(monkeypatch: pytest.MonkeyPatch):
16 """Test that preprocessing errors are handled gracefully."""
17 if current_platform.is_rocm() or current_platform.is_xpu():
18 pytest.skip(
19 "Skipped on ROCm/XPU: this test only works with 'fork', "
20 "but ROCm/XPU uses 'spawn'."
21 )
22
23 assert not torch.cuda.is_initialized(), (
24 "fork needs to be used for the engine "
25 "core process and this isn't possible if cuda is already initialized"
26 )
27
28 # Store original method to call for non-failing requests
29 original_preprocess = EngineCore.preprocess_add_request
30
31 # Monkeypatch to make preprocess_add_request raise an exception
32 # only for requests with "FAIL" in the first token
33 def conditional_failing_preprocess(self, request: EngineCoreRequest):
34 # Fail if the first token id is 333
35 if request.prompt_token_ids and request.prompt_token_ids[0] == 333:
36 raise ValueError("Simulated preprocessing error!")
37 return original_preprocess(self, request)
38
39 monkeypatch.setattr(
40 EngineCore, "preprocess_add_request", conditional_failing_preprocess
41 )
42
43 llm = LLM(model=MODEL_NAME)
44
45 # Create a failing request by crafting a request with an invalid token
46 # We need to use a direct approach since LLM.generate tokenizes for us
47 from vllm.inputs import TokensPrompt
48
49 # This should raise an exception due to the preprocessing failure
50 # Special token id to trigger the failure
51 failing_prompt = TokensPrompt(prompt_token_ids=[333])
52 outputs = llm.generate(failing_prompt, SamplingParams(max_tokens=10)) # type: ignore
53 assert len(outputs) == 1
54 assert len(outputs[0].outputs[0].token_ids) == 0
55 assert outputs[0].finished
56 assert outputs[0].outputs[0].finish_reason == "error"
57
58 # Verify the engine is still functional with a normal request
59 outputs = llm.generate("Hello, my name is", SamplingParams(max_tokens=10))
60 assert len(outputs) == 1
61 assert len(outputs[0].outputs[0].token_ids) > 0
62 assert outputs[0].outputs[0].finish_reason in ("stop", "length")