| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | from vllm import LLM, EngineArgs |
| 5 | from vllm.utils.argparse_utils import FlexibleArgumentParser |
| 6 | |
| 7 | |
| 8 | def create_parser(): |
| 9 | parser = FlexibleArgumentParser() |
| 10 | # Add engine args |
| 11 | EngineArgs.add_cli_args(parser) |
| 12 | parser.set_defaults(model="meta-llama/Llama-3.2-1B-Instruct") |
| 13 | # Add sampling params |
| 14 | sampling_group = parser.add_argument_group("Sampling parameters") |
| 15 | sampling_group.add_argument("--max-tokens", type=int) |
| 16 | sampling_group.add_argument("--temperature", type=float) |
| 17 | sampling_group.add_argument("--top-p", type=float) |
| 18 | sampling_group.add_argument("--top-k", type=int) |
| 19 | |
| 20 | return parser |
| 21 | |
| 22 | |
| 23 | def main(args: dict): |
| 24 | # Pop arguments not used by LLM |
| 25 | max_tokens = args.pop("max_tokens") |
| 26 | temperature = args.pop("temperature") |
| 27 | top_p = args.pop("top_p") |
| 28 | top_k = args.pop("top_k") |
| 29 | |
| 30 | # Create an LLM |
| 31 | llm = LLM(**args) |
| 32 | |
| 33 | # Create a sampling params object |
| 34 | sampling_params = llm.get_default_sampling_params() |
| 35 | if max_tokens is not None: |
| 36 | sampling_params.max_tokens = max_tokens |
| 37 | if temperature is not None: |
| 38 | sampling_params.temperature = temperature |
| 39 | if top_p is not None: |
| 40 | sampling_params.top_p = top_p |
| 41 | if top_k is not None: |
| 42 | sampling_params.top_k = top_k |
| 43 | |
| 44 | # Generate texts from the prompts. The output is a list of RequestOutput |
| 45 | # objects that contain the prompt, generated text, and other information. |
| 46 | prompts = [ |
| 47 | "Hello, my name is", |
| 48 | "The president of the United States is", |
| 49 | "The capital of France is", |
| 50 | "The future of AI is", |
| 51 | ] |
| 52 | outputs = llm.generate(prompts, sampling_params) |
| 53 | # Print the outputs. |
| 54 | print("-" * 50) |
| 55 | for output in outputs: |
| 56 | prompt = output.prompt |
| 57 | generated_text = output.outputs[0].text |
| 58 | print(f"Prompt: {prompt!r}\nGenerated text: {generated_text!r}") |
| 59 | print("-" * 50) |
| 60 | |
| 61 | |
| 62 | if __name__ == "__main__": |
| 63 | parser = create_parser() |
| 64 | args: dict = vars(parser.parse_args()) |
| 65 | main(args) |