【vLLM 学习】Llm Engine Example

vLLM 是一款专为大语言模型推理加速而设计的框架,实现了 KV 缓存内存几乎零浪费,解决了内存管理瓶颈问题。

更多 vLLM 中文文档及教程可访问 →https://vllm.hyper.ai/

*在线运行 vLLM 入门教程:零基础分步指南

源码 examples/offline_inference/llm_engine_example.py

# SPDX-License-Identifier: Apache-2.0

import argparse

from vllm import EngineArgs, LLMEngine, RequestOutput, SamplingParams
from vllm.utils import FlexibleArgumentParser


def create_test_prompts() -> list[tuple[str, SamplingParams]]:
    """Create a list of test prompts with their sampling parameters."""
    return [
        ("A robot may not injure a human being",
         SamplingParams(temperature=0.0, logprobs=1, prompt_logprobs=1)),
        ("To be or not to be,",
         SamplingParams(temperature=0.8, top_k=5, presence_penalty=0.2)),
        ("What is the meaning of life?",
         SamplingParams(n=2,
                        temperature=0.8,
                        top_p=0.95,
                        frequency_penalty=0.1)),
    ]


def process_requests(engine: LLMEngine,
                     test_prompts: list[tuple[str, SamplingParams]]):
    """Continuously process a list of prompts and handle the outputs."""
    "持续处理提示列表并处理输出"
    request_id = 0

    while test_prompts or engine.has_unfinished_requests():
        if test_prompts:
            prompt, sampling_params = test_prompts.pop(0)
            engine.add_request(str(request_id), prompt, sampling_params)
            request_id += 1

        request_outputs: list[RequestOutput] = engine.step()

        for request_output in request_outputs:
            if request_output.finished:
                print(request_output)


def initialize_engine(args: argparse.Namespace) -> LLMEngine:
    """Initialize the LLMEngine from the command line arguments."""
    engine_args = EngineArgs.from_cli_args(args)
    return LLMEngine.from_engine_args(engine_args)


def main(args: argparse.Namespace):
    """Main function that sets up and runs the prompt processing."""
    engine = initialize_engine(args)
    test_prompts = create_test_prompts()
    process_requests(engine, test_prompts)


if __name__ == '__main__':
    parser = FlexibleArgumentParser(
        description='Demo on using the LLMEngine class directly')
    parser = EngineArgs.add_cli_args(parser)
    args = parser.parse_args()
    main(args)
### vllm 库中 LLM 函数的使用说明 vllm 是一个用于加速大型语言模型推理和服务部署的高效库。关于 `LLM` 函数的具体实现细节未直接提及于提供的参考资料内,不过可以根据一般性的大型语言模型框架以及相似功能模块的设计来推测其工作原理。 #### 初始化与配置 通常情况下,初始化一个 LLM 实例涉及指定预训练模型路径或名称以及其他必要的超参数设置。这一步骤确保了后续调用过程中具备足够的上下文信息来进行有效的预测和生成任务[^2]。 ```python from vllm import LLM model_path = "path/to/model" llm_instance = LLM(model_name_or_path=model_path) ``` #### 推理接口 对于给定的一段文本输入,可以通过调用特定的方法完成前向传播计算得到输出结果。考虑到不同应用场景下的需求差异较大,API 设计上往往会提供灵活多样的选项供开发者选择最适合自己业务逻辑的方式进行交互[^1]。 ```python input_text = "Once upon a time..." output = llm_instance.generate(input_text) print(output) ``` #### 批量处理能力 为了支持高效的批量请求处理机制,部分高级特性允许一次性提交多个样本至后台线程池并发执行,从而极大提升了吞吐率并降低了延迟时间。这种设计特别适用于在线服务场景下大规模用户的实时响应要求[^5]。 ```python batch_inputs = ["First sentence.", "Second one."] outputs = llm_instance.batch_generate(batch_inputs) for output in outputs: print(output) ``` #### 自定义回调函数 有时用户希望能够捕获更多内部状态变化的信息或者对某些事件做出即时反应,则可通过注册自定义回调函数的方式来达成目的。这种方式增强了 API 的可扩展性和灵活性,使得第三方集成变得更加容易[^3]。 ```python def custom_callback(response): # Handle response here. pass llm_instance.set_custom_callback(custom_callback) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值