使用IPEX-LLM在Intel CPU和GPU上实现高效低延迟文本生成

247 阅读2分钟

引言

随着大规模语言模型(LLMs)的普及,如何在本地硬件上高效地运行这些模型变得越来越重要。IPEX-LLM作为一个PyTorch库,旨在通过Intel CPU和GPU,如iGPU和Arc系列等,实现LLMs的低延迟推理。在本文中,我们将探讨如何使用LangChain与IPEX-LLM结合,进行文本生成。

主要内容

1. 环境设置

在开始之前,需要确认你的环境中已安装LangChain和IPEX-LLM。可以通过以下命令更新LangChain并安装IPEX-LLM:

%pip install -qU langchain langchain-community
%pip install --pre --upgrade ipex-llm[all]

2. 基础用法

我们将使用LangChain中的LLMChainIpexLLM来构建文本生成应用。

2.1 导入必要库

import warnings
from langchain.chains import LLMChain
from langchain_community.llms import IpexLLM
from langchain_core.prompts import PromptTemplate

# 忽略不相关的警告
warnings.filterwarnings("ignore", category=UserWarning, message=".*padding_mask.*")

2.2 设置提示模板

template = "USER: {question}\nASSISTANT:"
prompt = PromptTemplate(template=template, input_variables=["question"])

2.3 加载模型

llm = IpexLLM.from_model_id(
    model_id="lmsys/vicuna-7b-v1.5",
    model_kwargs={"temperature": 0, "max_length": 64, "trust_remote_code": True},
)

3. 模型链的使用

通过将模型加载到LLMChain,可以直接进行推理:

llm_chain = prompt | llm
question = "What is AI?"
output = llm_chain.invoke(question)
print(output)

4. 保存和加载低位模型

低位模型具有更低的存储要求和更快的加载速度,适合在资源受限的环境中使用。

保存低位模型

saved_lowbit_model_path = "./vicuna-7b-1.5-low-bit"
llm.model.save_low_bit(saved_lowbit_model_path)
del llm

加载低位模型

注意:低位模型保存路径不包括分词器。确保将分词器文件手动复制到目标路径。

llm_lowbit = IpexLLM.from_model_id_low_bit(
    model_id=saved_lowbit_model_path,
    tokenizer_id="lmsys/vicuna-7b-v1.5",
    model_kwargs={"temperature": 0, "max_length": 64, "trust_remote_code": True},
)

llm_chain = prompt | llm_lowbit
output = llm_chain.invoke(question)
print(output)

常见问题和解决方案

  1. 模型加载失败:确认你的网络环境能够访问相关API。在某些地区,由于网络限制,建议使用API代理服务来提高访问稳定性。

  2. 内存不足:确保你的设备有足够的内存来处理所选模型,或者尝试使用更小的低位模型。

总结和进一步学习资源

IPEX-LLM在Intel硬件上提供了高效运行LLMs的能力。在进一步学习中,你可以参阅以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---