头图

LangChain 是提供构建复杂操作链的工具,而 vLLM 专注于高效的模型推理,两者结合应用可以简化并加速智能 LLM 应用程序的开发。
在本教程中,我们将介绍如何将 LangChain 与 vLLM 结合使用:从设置到分布式推理和量化的所有内容。

教程链接:https://go.openbayes.com/O3E61

使用云平台:OpenBayes
http://openbayes.com/console/signup?r=sony_0m6v

登录 http://OpenBayes.com,在「公共教程」页面,选择「将 LangChain 与 vLLM 结合使用教程」教程。

图片

页面跳转后,点击右上角「克隆」,将该教程克隆至自己的容器中。

图片

选择「NVIDIA GeForce RTX 4090」以及「vLLM」镜像,OpenBayes 平台上线了新的计费方式,大家可以按照需求选择「按量付费」或「包日/周/月」,点击「继续执行」。可以使用文章开头的邀请链接,获得 RTX 4090 使用时长!

图片

图片

稍等片刻,待系统分配好资源,当状态变为「运行中」后,点击「打开工作空间」。

图片

图片

进入到工作空间后,点击左侧目录栏中的 README.ipynb,可以看到详细的操作步骤。

图片

1、安装和设置 vLLM。本教程已经安装 vLLM.0.6.4,只需将 langchain 相关包安装完毕。

!pip install -U langchain langchain_community -q

图片

图片

2、配置 vLLM 与 LangChain 配合使用。
下面的示例演示了如何使用 vLLM 库初始化模型并将其与 LangChain 集成。

import gc 
import ctypes 
import torch defclean_memory(deep=False): 
    gc.collect()     if deep: 
        ctypes.CDLL("libc.so.6").malloc_trim(0) 
    torch.cuda.empty_cache()
from langchain_community.llms import VLLM
  # Initializing the vLLM model
 llm = VLLM(
     model="/input0/Qwen2.5-1.5B-Instruct",
     trust_remote_code=True,  # mandatory for Hugging Face models
     max_new_tokens=128,
     top_k=10,
     top_p=0.95,
     temperature=0.8,
 )
  # Running a simple query
print(llm.invoke("What are the most popular Halloween Costumes?"))
Loading safetensors checkpoint shards:   0% Completed | 0/1 [00:00

图片

3、使用 LangChain 和 vLLM 创建链。

from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
# Defining a prompt template for our LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)
# Creating an LLMChain with vLLM
llm_chain = LLMChain(prompt=prompt, llm=llm)
# Testing the LLMChain
question = "Who was the US president in the year the first Pokemon game was released?"
print(llm_chain.invoke(question))

图片

4、利用多 GPU 推理进行扩展。

del llm
clean_memory(deep=True)
from langchain_community.llms import VLLM
  # Running inference on multiple GPUs llm = VLLM(
     model="/input0/Qwen2.5-1.5B-Instruct",
     tensor_parallel_size=1,  # using 1 GPUs
     trust_remote_code=True,
 )
  print(llm.invoke("What is the future of AI?"))
Loading safetensors checkpoint shards:   0% Completed | 0/1 [00:00

图片

5、利用量化提高效率。

del llm
clean_memory(deep=True)
llm_q = VLLM(
     model="/input0/Qwen2.5-3B-Instruct-AWQ",
     trust_remote_code=True,
     max_new_tokens=512,
     vllm_kwargs={"quantization": "awq"},
 )
 # Running a simple query
 print(llm_q.invoke("What are the most popular Halloween Costumes?"))
Loading safetensors checkpoint shards:   0% Completed | 0/1 [00:00

图片

最后,通过利用分布式 GPU 支持、先进的量化技术和保持 API 兼容性,您可以创建不仅提供卓越性能而且还能灵活满足不同业务需求的系统。
当您继续使用 LangChain 和 vLLM 进行大型语言模型研究时,请务必记住,持续优化和监控是实现最佳效率的关键。
例如,vLLM 的 CUDA 优化内核和连续批处理策略可以显著减少响应时间。
然而,在生产系统中,特别是面向用户的系统(如聊天机器人)中,监控实时推理延迟至关重要。


小白狮ww
1 声望0 粉丝