---
title: Python代码段多副本配置步骤
description: "1. 安装pyinstaller打包库。"
url: https://www.hikunpeng.com/document/detail/zh/kunpenghpcs/KunpengDeveloper/usermanual/topic_0000002566415851.html
sourcePath: /source/zh/kunpenghpcs/KunpengDeveloper/usermanual/topic_0000002566415851.html
indexId: 68ff48dcb80ea5bfa0bc8ad99df0ec7d0335b5aa5cfae608956a0c0baebd8b1e78
---
# Python代码段多副本配置步骤

1. 安装pyinstaller打包库。

```
yum install pyinstaller
```


2. 安装其他Python依赖库。

```
pip install pyyaml
pip install typing_extensions
pip install pympler
pip install ninja
yum install patchelf
```


3. 进入需要打包的Python应用根目录，建立文件夹lib_py，并将该应用所依赖的所有.so文件和数据文件放置在lib_py目录下。
4. 执行打包脚本py_install.sh。

```
#!/bin/bash
set -e
pyinstaller \
--name=app_name \                              # Application name
--onefile \
--add-binary="lib_py/*.so:lib_py" \       # Binary files required
--add-data=" lib_py:lib_py " \              # Data files required
--hidden-import=app_name \                   # If the entry file of the Python application imports this application, this line is required; otherwise, please ignore it.
--hidden-import=torch \
app_entry.py                                    # Entry python file
echo "onefile build complete! Binary: dist/app_name"
```


5. 建立rankfile。

```
#示例
rank 0=localhost slot=0-35
rank 1=localhost slot=38-73
rank 2=localhost slot=76-111
rank 3=localhost slot=114-149
rank 4=localhost slot=152-187
rank 5=localhost slot=190-225
rank 6=localhost slot=228-263
rank 7=localhost slot=266-301
```


6. mpirun多副本运行（以8进程36线程应用为例），建立脚本run.sh并执行。

```
#!/bin/bash
export OMP_NUM_THREADS=36
export OMP_PROC_BIND=close
mpirun \
-np 8 \
-rf rankfile \
-x OMP_NUM_THREADS \
bash -c '
exec ./dist/app_name … '# Provide the necessary runtime parameters at …
```


  补充：若运行时因内存消耗异常增长导致失败，请将步骤4中的--onefile修改为--onedir，并将运行脚本最后一行修改为：

```
exec ./dist/app_name/app_name … '# Provide the necessary runtime parameters at …
```


  (该方式存在性能衰减的风险，请根据实际情况按需使用)。
