main
py 97 lines 2.96 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """This file demonstrates preempt requests when using the `LLMEngine`
4 for processing prompts with various sampling parameters.
5 """
6
7 import argparse
8
9 from vllm import EngineArgs, LLMEngine, RequestOutput, SamplingParams
10 from vllm.utils.argparse_utils import FlexibleArgumentParser
11
12
13 def create_test_prompts() -> list[tuple[str, SamplingParams]]:
14 """Create a list of test prompts with their sampling parameters."""
15 return [
16 (
17 "A robot may not injure a human being " * 50,
18 SamplingParams(
19 temperature=0.0, logprobs=1, prompt_logprobs=1, max_tokens=16
20 ),
21 ),
22 (
23 "A robot may not injure a human being " * 50,
24 SamplingParams(
25 temperature=0.0, logprobs=1, prompt_logprobs=1, max_tokens=16
26 ),
27 ),
28 (
29 "To be or not to be,",
30 SamplingParams(
31 temperature=0.8, top_k=5, presence_penalty=0.2, max_tokens=128
32 ),
33 ),
34 (
35 "What is the meaning of life?",
36 SamplingParams(
37 n=2, temperature=0.8, top_p=0.95, frequency_penalty=0.1, max_tokens=128
38 ),
39 ),
40 ]
41
42
43 def process_requests(engine: LLMEngine, test_prompts: list[tuple[str, SamplingParams]]):
44 """Continuously process a list of prompts and handle the outputs."""
45 request_id = 0
46
47 print("-" * 50)
48 step_id = 0
49 while test_prompts or engine.has_unfinished_requests():
50 print("-" * 50)
51 import os
52
53 print(f"Step {step_id} (pid={os.getpid()})")
54
55 if test_prompts:
56 prompt, sampling_params = test_prompts.pop(0)
57 engine.add_request(str(request_id), prompt, sampling_params)
58 request_id += 1
59
60 if step_id == 10:
61 print(f"Resetting prefix cache at {step_id}")
62 engine.reset_prefix_cache(reset_running_requests=True)
63
64 request_outputs: list[RequestOutput] = engine.step()
65
66 for request_output in request_outputs:
67 if request_output.finished:
68 print("-" * 50)
69 print(request_output)
70 print("-" * 50)
71 step_id += 1
72
73
74 def initialize_engine(args: argparse.Namespace) -> LLMEngine:
75 """Initialize the LLMEngine from the command line arguments."""
76 engine_args = EngineArgs.from_cli_args(args)
77 return LLMEngine.from_engine_args(engine_args)
78
79
80 def parse_args():
81 parser = FlexibleArgumentParser(
82 description="Demo on using the LLMEngine class directly"
83 )
84 parser = EngineArgs.add_cli_args(parser)
85 return parser.parse_args()
86
87
88 def main(args: argparse.Namespace):
89 """Main function that sets up and runs the prompt processing."""
90 engine = initialize_engine(args)
91 test_prompts = create_test_prompts()
92 process_requests(engine, test_prompts)
93
94
95 if __name__ == "__main__":
96 args = parse_args()
97 main(args)