news 2026/9/25 3:49:22

PaddleNLP 在昆仑 XPU 上跑通 Llama2-7B:环境搭建、自定义算子编译与高性能推理实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PaddleNLP 在昆仑 XPU 上跑通 Llama2-7B:环境搭建、自定义算子编译与高性能推理实战
  • 人工智能
  • 大模型
  • 预训练
  • 微调
  • LoRA
  • RLHF
  • 强化学习
  • 分布式训练

【免费下载链接】PaddleNLP

Easy-to-use and powerful LLM and SLM library with awesome model zoo.

项目地址:https://gitcode.com/gh_mirrors/pa/PaddleNLP
点击查看免费下载

PaddleNLP 在昆仑 XPU 上对 Llama2-7B 模型进行了深度适配与优化。本文以 llm/devices/xpu/llama/README.md 为主线,完整还原从硬件校验、镜像容器准备、飞桨 XPU 安装、自定义算子编译到高性能推理的全流程,并结合仓库源码(csrc/xpu/src、llm/predict/predictor.py、csrc/xpu/test)补充底层实现细节与参数说明。读完本文,你将能够在一台昆仑 R480(R300)XPU 机器上独立复现 Llama2-7B 的端到端推理,并理解 PaddleNLP 在 XPU 上的算子适配机制。

一、适用场景与硬件要求

XPU 是昆仑芯片的计算单元,PaddleNLP 针对 Llama2-7B 在其上做了算子级适配。要复现本指南,首先需要一台搭载昆仑 XPU 的机器,官方验证过的硬件与驱动组合如下:

芯片类型卡型号驱动版本
昆仑 R480R3004.31.0

依赖环境说明

  • 机器:昆仑 R480 32G 显存版本,batch size 为 1 时推理大约需要 17.5G 显存;
  • 镜像:registry.baidubce.com/device/paddle-xpu:ubuntu20-x86_64-gcc84-py310(仅作为开发环境,镜像内不包含预编译的飞桨安装包);
  • GCC 路径:/usr/bin/gcc(版本 8.4);
  • Python 版本:3.10;
  • 文中示例基于 8 卡机器。

校验机器是否为昆仑 XPU

在系统环境下执行以下命令,如果出现1d22开头的 PCI 设备,说明该机器具备昆仑芯片:

lspci | grep 1d22 #例如:$ lspci | grep 1d22 , 输出如下 53:00.0 Communication controller: Device 1d22:3684 56:00.0 Communication controller: Device 1d22:3684 6d:00.0 Communication controller: Device 1d22:3684 70:00.0 Communication controller: Device 1d22:3684 b9:00.0 Communication controller: Device 1d22:3684 bc:00.0 Communication controller: Device 1d22:3684 d2:00.0 Communication controller: Device 1d22:3684 d5:00.0 Communication controller: Device 1d22:3684

PCI vendor ID1d22即昆仑芯片的标识,3684为具体设备型号。输出中每一条记录对应一张可见的 XPU 卡,示例输出即 8 张卡全部被系统识别。

二、环境准备:从拉取镜像到编译自定义算子(约 5~15 分钟)

1. 拉取开发镜像

# 注意此镜像仅为开发环境,镜像中不包含预编译的飞桨安装包 docker pull registry.baidubce.com/device/paddle-xpu:ubuntu20-x86_64-gcc84-py310

2. 启动容器

使用--device参数将 XPU 设备透传给容器,--net host便于多卡通信,-v $(pwd):/work将当前目录挂载进容器:

docker run -it --privileged=true --net host --device=/dev/xpu0:/dev/xpu0 --device=/dev/xpu1:/dev/xpu1 --device=/dev/xpu2:/dev/xpu2 --device=/dev/xpu3:/dev/xpu3 --device=/dev/xpu4:/dev/xpu4 --device=/dev/xpu5:/dev/xpu5 --device=/dev/xpu6:/dev/xpu6 --device=/dev/xpu7:/dev/xpu7 --device=/dev/xpuctrl:/dev/xpuctrl --name paddle-xpu-dev -v $(pwd):/work -w=/work -v xxx registry.baidubce.com/device/paddle-xpu:ubuntu20-x86_64-gcc84-py310 /bin/bash

其中/dev/xpu0~/dev/xpu7是 8 张计算卡,/dev/xpuctrl是芯片控制设备,二者缺一不可。容器命名paddle-xpu-dev方便后续docker exec复用。

3. 安装 paddlepaddle-xpu

paddlepaddle(飞桨)提供运算基础能力,需安装带 XPU 支持的最新 dev 版本:

# paddlepaddle『飞桨』深度学习框架,提供运算基础能力 wget https://paddle-whl.bj.bcebos.com/nightly/xpu/paddlepaddle-xpu/paddlepaddle_xpu-3.0.0.dev20240612-cp310-cp310-linux_x86_64.whl python -m pip install paddlepaddle_xpu-3.0.0.dev20240612-cp310-cp310-linux_x86_64.whl

注意 whl 文件名中的cp310-cp310表示该安装包仅适配 Python 3.10,与依赖环境中指定的 Python 版本一致。若需获取更新的 nightly 版本,可在飞桨官方 nightly 包仓库的 xpu/paddlepaddle-xpu 目录下按日期选取。

4. 克隆 PaddleNLP 并安装依赖

PaddleNLP 是基于飞桨的自然语言处理与大语言模型开发库,仓库中存放了包括 Llama2-7B 在内的各类大模型实现。由于本指南对应的适配代码基于特定提交,需要切换到指定 commit:

# Clone PaddleNLP git clone https://github.com/PaddlePaddle/PaddleNLP cd PaddleNLP # 切换到对应指定依赖的提交 git checkout 0844a5b730c636ad77975fd30a485ad5dc217eac # 安装依赖 pip install -r requirements.txt python -m pip install -e .

python -m pip install -e .以可编辑模式安装当前仓库,便于直接跟踪paddlenlp源码中的模型与推理实现。

5. 下载并编译 XPU 自定义算子

PaddleNLP 在 XPU 上的高性能推理依赖一批自定义算子,源码位于仓库的csrc/xpu/src目录。进入该目录,下载昆仑的 XDNN、XRE、XTDK 三套 SDK,设置路径后一键编译:

# 下载XPU自定义算子 cd csrc/xpu/src # 设置 XDNN, XRE and XTDK 的路径后一键执行。 wget https://baidu-kunlun-product.su.bcebos.com/KL-SDK/klsdk-dev/release_paddle/20240429/xdnn-ubuntu_x86_64.tar.gz wget https://baidu-kunlun-product.su.bcebos.com/KL-SDK/klsdk-dev/release_paddle/20240429/xre-ubuntu_x86_64.tar.gz wget https://klx-sdk-release-public.su.bcebos.com/xtdk_llvm15/release_paddle/2.7.98.2/xtdk-llvm15-ubuntu1604_x86_64.tar.gz # 解压到当前目录 tar -xf xdnn-ubuntu_x86_64.tar.gz tar -xf xre-ubuntu_x86_64.tar.gz tar -xf xtdk-llvm15-ubuntu1604_x86_64.tar.gz # 设置环境变量 export PWD=$(pwd) export XDNN_PATH=${PWD}/xdnn-ubuntu_x86_64/ export XRE_PATH=${PWD}/xre-ubuntu_x86_64/ export CLANG_PATH=${PWD}/xtdk-llvm15-ubuntu1604_x86_64/ #XPU设备安装自定义算子 bash ./cmake_build.sh cd -
编译脚本做了什么

从源码看,csrc/xpu/src/cmake_build.sh 的编译链路分为两步:

  1. 进入plugin子目录执行./cmake_build.sh,通过 csrc/xpu/src/plugin/cmake_build.sh 调用 CMake 以-DBUILD_STANDALONE=ON模式构建 XPU 插件库,产出静态库plugin/build/libxpuplugin.a;
  2. 卸载旧版paddlenlp_ops后执行python setup.py install。

csrc/xpu/src/setup.py 定义了名为paddlenlp_ops的 Python 扩展包,源码列表包含update_inputs_v2.cc、set_preids_token_penalty_multi_scores.cc、set_stop_value_multi_ends_v2.cc、get_token_penalty_multi_scores_v2.cc、get_padding_offset_v2.cc、rebuild_padding_v2.cc、save_with_output.cc、save_with_output_msg.cc、get_output.cc、get_position_ids.cc、step.cc、fused_rotary_position_encoding.cc、block_attn.cc等 20 余个算子,并通过环境变量XRE_PATH、XFT_PATH、BKCL_PATH、XFA_PATH、XBLAS_PATH链接 XPU 运行时、Flash Attention、BLAS 等底层库(未设置时回退到飞桨安装包自带的include/xpu、libs路径)。编译参数中显式带上-DPADDLE_WITH_XPU与-D_GLIBCXX_USE_CXX11_ABI=1,以匹配飞桨 XPU 构建的 ABI 约定。

plugin 目录本身支持两种集成方式(见 csrc/xpu/src/plugin/README.md):一是如上所示独立编译;二是将plugin拷贝到飞桨源码的paddle/phi/xpu下,并在飞桨 CMake 配置中追加-DWITH_XPU_PLUGIN=ON一并编译。

三、数据准备(约 2~5 分钟)

仓库提供了可直接用于精调验证的测试数据集:

# 进入llm目录 cd llm # 下载数据集 wget https://baidu-kunlun-customer.su.bcebos.com/paddle-llm/infernce.tar.gz # 解压 tar -zxvf infernce.tar.gz

解压后得到llm/inference目录,即推理命令中--model_name_or_path ./inference指向的模型与分词器目录。

四、高性能推理(约 10~15 分钟)

1. 指定可见的 XPU 卡号

#可以通过设置 FLAGS_selected_xpus 指定容器可见的昆仑芯片卡号 export FLAGS_selected_xpus=0 #设置环境变量 export PYTHONPATH=$PYTHONPATH:../../../PaddleNLP/

FLAGS_selected_xpus是飞桨 XPU 的设备选择环境变量。这一点在 llm/predict/predictor.py 的静态推理实现中可以得到印证:构造 predictor 时,代码通过os.environ.get("FLAGS_selected_{}s".format(predictor_args.device), 0)读取对应设备环境变量并调用config.enable_custom_device指定设备 ID。

2. 高性能推理命令

python predictor.py --model_name_or_path ./inference --dtype float16 --src_length 2048 --max_length 2048 --mode "static" --batch_size 1 --inference_model --block_attn --device xpu

该命令在llm目录下执行,各参数含义如下(参数定义均来自 llm/predict/predictor.py 的PredictorArgument):

参数说明本示例取值
--model_name_or_path模型权重与分词器所在目录./inference
--dtype模型精度,XPU 场景使用半精度 float16float16
--src_length输入文本最大长度2048
--max_length解码最大长度2048
--mode推理模式,dynamic或static"static"
--batch_size推理 batch 大小1
--inference_model使用 InferenceModel(静态图推理模型)进行生成开启
--block_attn是否使用 block attention(分块注意力)开启
--device运行设备xpu

其中--block_attn是 XPU 高性能推理的关键开关。llm/predict/predictor.py 中block_attn: bool = field(default=False, metadata={"help": "whether use block attention"}),同时静态推理路径对 XPU 有明确约束:使用 XPU 导出静态模型时必须以--block_attn标志导出,推理时也必须带上--block_attn(见 llm/predict/predictor.py 的校验逻辑)。分块注意力通过按块管理 KV Cache、配合block_tables等结构减少访存与搬运开销,是长序列生成场景下 XPU 上的核心优化手段。

除上述参数外,PredictorArgument还支持采样类生成参数,包括--decode_strategy(sampling/greedy_search/beam_search,默认sampling)、--top_k、--top_p、--temperature、--repetition_penalty,以及 LoRA 推理相关的--lora_path、--tare_path等,可按需扩展。

3. 预期运行结果

执行成功后,日志会依次输出 preprocess、分词器加载、推理耗时与生成文本。参考输出如下:

[[2024-08-22 13:23:34,969] [ INFO] - preprocess spend 0.012732744216918945 [2024-08-22 13:23:34,994] [ INFO] - We are using <class 'paddlenlp.transformers.llama.tokenizer.LlamaTokenizer'> to load './inference'. [2024-08-22 13:23:35,014] [ INFO] - Start read result message [2024-08-22 13:23:35,014] [ INFO] - Current path is /home/workspace/wangy_test/PaddleNLP/llm [2024-08-22 13:23:53,313] [ INFO] - running spend 18.322898864746094 [2024-08-22 13:23:53,326] [ INFO] - Finish read result message [2024-08-22 13:23:53,327] [ INFO] - End predict ***********Source********** 解释一下“温故而知新” ***********Target********** ***********Output********** "温故而知新" (wēn gǔ èr zhī xīn) is a Chinese idiom that means "to understand the old in order to appreciate the new." The word "温故" (wēn gǔ) means "old" or "ancient," while "知新" (zhī xīn) means "to know or understand something new." The idiom as a whole suggests that in order to fully appreciate something new, one must first have a deep understanding of the past or the traditional ways of doing things. In other words, "温故而知新" means that one should have a foundation of knowledge and understanding before being open to new ideas or experiences. This can help prevent one from being too quick to dismiss the old in favor of the new, and instead allow for a more nuanced and informed appreciation of both. For example, if someone is learning a new language, they may find it helpful to study the grammar and syntax of the language's ancestor languages in order to better understand the nuances of the new language. Similarly, if someone is learning a new skill or craft, they may find it helpful to study the traditional techniques and methods of the craft in order to better understand the new approaches and technologies that are being introduced. Overall, "温故而知新" is a reminder to approach new things with a sense of respect and appreciation for the past, and to be open to learning and growing in a way that is informed by a deep understanding of both the old and the new. [2024-08-22 13:23:53,328] [ INFO] - Start predict [2024-08-22 13:23:53,335] [ INFO] - preprocess spend 0.007447242736816406 [2024-08-22 13:23:53,357] [ INFO] - We are using <class 'paddlenlp.transformers.llama.tokenizer.LlamaTokenizer'> to load './inference'. [2024-08-22 13:23:53,386] [ INFO] - Start read result message [2024-08-22 13:23:53,386] [ INFO] - Current path is /home/workspace/wangy_test/PaddleNLP/llm [2024-08-22 13:23:57,859] [ INFO] - running spend 4.506801605224609 [2024-08-22 13:23:57,863] [ INFO] - Finish read result message [2024-08-22 13:23:57,864] [ INFO] - End predict ***********Source********** 你好,请问你是谁? ***********Target********** ***********Output********** Hello! I'm just an AI assistant, I don't have a personal identity or ego, but I'm here to help you with any questions or tasks you may have. I'm a machine learning model trained to provide helpful and informative responses, and I'm here to assist you in a safe and respectful manner. Is there anything else I can help you with?

两次推理的running spend分别为 18.3 秒与 4.5 秒量级(该耗时包含完整 2048 token 长度设置下的处理与解码开销,实测会随输入长度与机器负载变化,仅供参考)。日志中We are using <class 'paddlenlp.transformers.llama.tokenizer.LlamaTokenizer'>表明分词器加载自paddlenlp.transformers.llama模块,与仓库中 paddlenlp/transformers/llama 目录的实现对应。

五、XPU 适配的源码佐证与进一步验证

自定义算子的测试用例

编译安装paddlenlp_ops后,仓库在 csrc/xpu/test/python 提供了多个算子级验证脚本,例如test_blha_get_max_len.py、test_update_inputs_v2.py、test_get_padding_offset_v2.py、test_rebuild_padding_v2.py、test_set_stop_value_multi_ends_v2.py、test_get_position_ids.py等。以 csrc/xpu/test/python/test_blha_get_max_len.py 为例,测试通过paddle.XPUPlace(0)显式将张量放置到 0 号 XPU 设备,并调用paddle.incubate.nn.functional.blha_get_max_len验证 block attention 场景下的序列长度计算——这正是--block_attn推理链路中 KV Cache 组织与 batch 调度的基础算子之一。

推理入口的 XPU 分支

从 llm/predict/predictor.py 的实现可以确认两点:

  • 设备选择统一走自定义设备分支:predictor_args.device in paddle.device.get_all_custom_device_type()时调用config.enable_custom_device(predictor_args.device, device_id),device_id 取自FLAGS_selected_{device}s环境变量;
  • XPU 静态推理强制要求--block_attn:device == "xpu"且未启用 block attention 时会抛出明确报错,引导开发者以--block_attn同时完成导出与推理。

因此在实际复现时,务必保证导出静态模型与执行推理两处都携带--block_attn,否则会触发该校验逻辑。

注意事项小结

  • 镜像只提供开发环境,飞桨 XPU 安装包需按第 2.3 节手动安装,且包名严格绑定 Python 3.10;
  • 自定义算子编译前需完整解压 XDNN、XRE、XTDK 并正确导出XDNN_PATH/XRE_PATH/CLANG_PATH(setup.py还会按需读取XFT_PATH、BKCL_PATH、XFA_PATH、XBLAS_PATH);
  • 单卡推理约需 17.5G 显存(bs=1),建议在 32G 版本的昆仑 R480 上运行;
  • 推理前在llm目录下执行命令,且保证PYTHONPATH能指向 PaddleNLP 仓库根目录,以便正确加载paddlenlp与已编译的paddlenlp_ops扩展。
  • 人工智能
  • 大模型
  • 预训练
  • 微调
  • LoRA
  • RLHF
  • 强化学习
  • 分布式训练

【免费下载链接】PaddleNLP

Easy-to-use and powerful LLM and SLM library with awesome model zoo.

项目地址:https://gitcode.com/gh_mirrors/pa/PaddleNLP
点击查看免费下载

相关推荐

上一篇:CANN/GE图引擎AddInput接口
下一篇:终极前端性能清单:如何在性能优化与基础设施成本间找到完美平衡点

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/25 3:40:48

ESP32驱动墨水屏实战:GxEPD2库入门与避坑指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/25 3:38:59

SpringBoot+Vue二手交易系统:从业务建模到部署上线全解析

最近我把一套基于 SpringBoot Vue 的二手物品交易管理系统重新翻了出来&#xff0c;项目代号 bootpf&#xff0c;代码包名统一叫 com.bootpf。这套系统从用户注册、商品发布、浏览搜索、购物车、下订单&#xff0c;到后台的商品审核、用户管理和数据统计&#xff0c;基本把二手…

作者头像 李华