> For the complete documentation index, see [llms.txt](https://1684.gitbook.io/bmnnsdk2-1684-2-0-1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://1684.gitbook.io/bmnnsdk2-1684-2-0-1/fp32-bmodel-zhuan-hua-patha.md).

# FP32 Bmodel转化

​BM1684平台同时兼容支持fp32模型，用户可以简化流程之间验证模型的可用性。基于BMNNSDK2提供的BMNet工具链可以很方便的转换。当前BMNet 已支持绝大部分开源的 Caffe,TensorFlow,MXNet 和 PyTorch 网络层，更多的网络层正在不断开发中,用户可使用这些网络层进行网络编译,生成 bmodel 文件。

## 1. caffe模型转换fp32 bmodel

BMNETC是针对caffe的模型编译器，可将某网络的caffemodel和prototxt编译 成BMRuntime所需要的文件。而且在编译的同时，支持每一层的NPU模型计算结 果都会和CPU的计算结果进行对比，保证正确性。 Caffe模型转换的主要操作工具介绍如下：&#x20;

Command name: bmnetc - BMNet compiler command for Caffe model

```
    /path/to/bmnetc [--model=<path>] \
                [--weight=<path>] \
                [--shapes=<string>] \
                [--net_name=<name>] \
                [--opt=<value>] \
                [--dyn=<bool>] \
                [--outdir=<path>] \
                [--target=<name>] \
                [--cmp=<bool>] \
                [--mode=<string>] \
                [--enable_profile=<bool>]
                [--show_args]
                [--check_model]
```

| args            | type   | Description                                                                                                                                     |
| --------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| model           | String | Necessary. Caffe prototxt path                                                                                                                  |
| weight          | string | Necessary. Caffemodel(weight) path                                                                                                              |
| shapes          | string | Optional. Shapes of all inputs, default use the shape in prototxt, format \[x,x,x,x],\[x,x]…, these correspond to inputs one by one in sequence |
| net\_name       | string | Optional. Name of the network, default use the name in prototxt                                                                                 |
| opt             | int    | Optional. Optimization level. Option: 0, 1, 2, default 2.                                                                                       |
| dyn             | bool   | Optional. Use dynamic compilation, default false.                                                                                               |
| outdir          | string | Necessary. Output directory                                                                                                                     |
| target          | string | Necessary. Option: BM1682, BM1684; default: BM1682                                                                                              |
| cmp             | bool   | Optional.Check result during compilation. Default: true                                                                                         |
| mode            | string | Optional. Set bmnetc mode. Option: compile, GenUmodel. Default: compile.                                                                        |
| enable\_profile | bool   | Optional. Enable profile log. Default: false                                                                                                    |
| show\_args      |        | Optional. Display arguments passed to bmnetc compiler.                                                                                          |
| check\_model    |        | Optional. Check unsupported layer types from input model.                                                                                       |

以sdk中的SSD模型编译float32 bmodel为例：

脚本中的主要内容如下：

```
bmnetc --model=${model_dir}/ssd300_deploy.prototxt \
       --weight=${model_dir}/ssd300.caffemodel \
       --shapes=[1,3,300,300] \
       --outdir=./out/ssd300 \
       --target=BM1684
```

执行完脚本后正常的输出结果如下：

```
I0923 11:25:19.796756    91 bmcompiler_bmodel.cpp:123] [BMCompiler:I] save_tensor inout name [mbox_priorbox]
I0923 11:25:19.796763    91 bmcompiler_bmodel.cpp:123] [BMCompiler:I] save_tensor inout name [detection_out]
BMLIB Send Quit Message
FW INFO: finish api, nd 0, api_id -1, result = success
FW INFO: terminate nodechip_idx 0
```

编译生成的模型存放在如下目录：

```
out/
├── fp32_ssd300.bmodel     //f32_1b.bmodel 和 f32_4b.bmodel 进行combine后的bmodel
├── ssd300
│   ├── compilation.bmodel
│   ├── compiler_profile_0.dat
│   ├── f32_1b.bmodel
│   ├── input_ref_data.dat
│   └── output_ref_data.dat
└── ssd300_4batch
    ├── compilation.bmodel
    ├── compiler_profile_0.dat
    ├── f32_4b.bmodel
    ├── input_ref_data.dat
    └── output_ref_data.dat
```

至此生成bmodel. 执行如下命令，检测模型的精度回归：

```
# cd  /workspace/scripts/
# source envsetup_cmodel.sh
# bmrt_test --context_dir=./out/ssd300/
```

正常结束后提示如下：

```
I0923 11:34:56.020706   126 bmrt_test.cpp:573] [BMRT_TEST:I] net[ssd300-caffe] stage[0], launch total time is 213432770 us (npu 0 us, cpu 213432770 us)
I0923 11:34:56.020737   126 bmrt_test.cpp:609] [BMRT_TEST:I] +++ The network[ssd300-caffe] stage[0] cmp success +++
I0923 11:34:56.020751   126 bmrt_test.cpp:620] [BMRT_TEST:I] load input time(s): 0.000872
I0923 11:34:56.020778   126 bmrt_test.cpp:621] [BMRT_TEST:I] calculate  time(s): 213.433
I0923 11:34:56.020787   126 bmrt_test.cpp:622] [BMRT_TEST:I] get output time(s): 5e-06
I0923 11:34:56.020794   126 bmrt_test.cpp:623] [BMRT_TEST:I] compare    time(s): 7.6e-05
BMLIB Send Quit Message
FW INFO: finish api, nd 0, api_id -1, result = success
FW INFO: terminate nodechip_idx 0
```

有“+++ The network\[ssd300-caffe] stage\[0] cmp success +++”的提示，则模型编译流程正确，与原生模型的精度一致。

此外，BMNETC还有python版本支持，简单使用配置如下：

```
import bmnetc

compile fp32 model

bmnetc.compile(
  model = "/path/to/prototxt",    ## Necessary
  weight = "/path/to/caffemodel", ## Necessary
  outdir = "xxx",                 ## Necessary
  target = "BM1682",              ## Necessary
  shapes = [[x,x,x,x], [x,x,x]],  ## optional, if not set, default use shape in prototxt
  net_name = "name",              ## optional, if not set, default use the network name in prototxt
  opt = 2,                        ## optional, if not set, default equal to 2
  dyn = False,                    ## optional, if not set, default equal to False
  cmp = True,                     ## optional, if not set, default equal to True
  enable_profile = False          ## optional, if not set, default equal to False
)
```

bmnetc成功后，将在指定的文件夹中生成一个compilation.bmodel的文件，该文件则是转换成功的bmodel，用户可以重命名。 若用户在bmnetc时使用了cmp=true模式，则会在指定的文件夹中生成一个input\_ref\_data.dat和一个output\_ref\_data.dat， 分别是Caffe产生的网络输入参考数据和网络输出参考数据，可用于bmrt\_test验证生成的bmodel在芯片运行时结果是否正确。

## 2. TensorFlow模型编译

fp32 bmodel BMNETT是针对tensorflow的模型编译器，在该device下创建graph，可以被编译成BMRuntime所需的文件。而且在编译graph的同时，可选择将每一个操作的NPU模型计算结果和CPU的计算结果进行对比，保证正确性。

* 通过BMNETT工具可以把TF一般模型进行编译成bmodel，同样支持shell cmd模式以及python模式：

```
  　　python3 -m bmnett [--model=<path>] \
    　　                  [--input_names=<string>] \
    　　                  [--shapes=<string>] \
    　　                  [--output_names=<string>] \
    　　                  [--net_name=<name>] \
    　　                  [--opt=<value>] \
    　　                  [--dyn=<bool>] \
    　　                  [--outdir=<path>] \
    　　                  [--target=<name>] \
    　　                  [--cmp=<bool>] \
    　　                  [--mode=<string>] \
    　　                  [--enable_profile=<bool>]
```

| args            | type   | Description                                                                                                                                     |
| --------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| model           | String | Necessary. Caffe prototxt path                                                                                                                  |
| input\_names    | string | Necessary. Set name of all network inputs one by one in sequence. Format “name1,name2,name3”                                                    |
| shapes          | string | Optional. Shapes of all inputs, default use the shape in prototxt, format \[x,x,x,x],\[x,x]…, these correspond to inputs one by one in sequence |
| output\_names   | string | Necessary. Set name of all network outputs one by one in sequence. Format “name1,name2,name2”                                                   |
| net\_name       | string | Optional. Name of the network, default use the name in prototxt                                                                                 |
| opt             | int    | Optional. Optimization level. Option: 0, 1, 2, default 2.                                                                                       |
| dyn             | bool   | Optional. Use dynamic compilation, default false.                                                                                               |
| outdir          | string | Necessary. Output directory                                                                                                                     |
| target          | string | Necessary. Option: BM1684, BM1684; default: BM1684                                                                                              |
| cmp             | bool   | Optional.Check result during compilation. Default: true                                                                                         |
| mode            | string | Optional. Set bmnetc mode. Option: compile, GenUmodel. Default: compile.                                                                        |
| enable\_profile | bool   | Optional. Enable profile log. Default: false                                                                                                    |

* Python模式下简单配置命令如下：

```
import bmnett
## compile fp32 model
bmnett.compile(
    model = "/path/to/model(.pb,.h5)", ## Necessary
    outdir = "xxx",                    ## Necessary
    target = "BM1684"                  ## Necessary
    shapes = [[x,x,x,x], [x,x,x]],     ## Necessary
    net_name = "name",                 ## Necessary
    input_names=["name1", "name2"],    ## Necessary, when .h5 use None
    output_names=["out_name1", "out_name2"], ## Necessary, when .h5 use None
    opt = 2,                           ## optional, if not set, default equal to 1
    dyn = False,                       ## optional, if not set, default equal to False
    cmp = True,                        ## optional, if not set, default equal to True
    enable_profile = True              ## optional, if not set, default equal to False
)
```

bmnett成功后，将在指定的文件夹中生成一个compilation.bmodel的文件，该文件则是转换成功的bmodel，用户可以重命名。&#x20;

若用户在bmnett时使用了cmp=true模式，则会在指定的文件夹中生成一个input\_ref\_data.dat和一个output\_ref\_data.dat， 分别是Tensorflow产生的网络输入参考数据和网络输出参考数据，可用于bmrt\_test验证生成的bmodel在芯片运行时结果是否正确。&#x20;

对于复杂的tensorflow模型，例如fastrcnn等，目前版本的bmnett暂时不支持，后续会有bmnett\_plus版本更新，效率会提升更好。

* bmnett 安装

```
 cd /workspace/bmnet/bmnett/
 pip install bmnett-2.1.0-py2.py3-none-any.whl
```

## 3. PyTorch模型编译

fp32 bmodel BMNETP是针对pytorch的模型编译器，可以把pytorch的model直接编译成BMRuntime所需的执行指令。支持python代码或已经保存的trace文件。在编译model的同时，可选择将每一个操作的NPU模型计算结果和CPU的计算结果进行对比，保证正确性。

* 通过bmnetp工具可以pytorch模型转换为Bmodel来运行，使用命令如下：

  ```
    python3 -m bmnetp [--model=<path>] \
    　　              [--shapes=<string>] \
    　　              [--net_name=<name>] \
    　　              [--opt=<value>] \
    　　              [--dyn=<bool>] \
    　　              [--outdir=<path>] \
    　　              [--target=<name>] \
    　　              [--cmp=<bool>] \
                      [--enable_profile=<bool>]
  ```
* 参数介绍：

  | args            | type   | Description                                                                                                                                      |
  | --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
  | model           | String | Necessary. Traced PyTorch model (.pt) path                                                                                                       |
  | shapes          | string | Necessary. Shapes of all inputs, default use the shape in prototxt, format \[x,x,x,x],\[x,x]…, these correspond to inputs one by one in sequence |
  | net\_name       | string | Optional. Name of the network, default use the name in prototxt                                                                                  |
  | opt             | int    | Optional. Optimization level. Option: 0, 1, 2, default 1.                                                                                        |
  | dyn             | bool   | Optional. Use dynamic compilation, default false.                                                                                                |
  | outdir          | string | Necessary. Output directory                                                                                                                      |
  | target          | string | Necessary. Option: BM1682, BM1684; default: BM1682                                                                                               |
  | cmp             | bool   | Optional.Check result during compilation. Default: true                                                                                          |
  | mode            | string | Optional. Set bmnetc mode. Option: compile, GenUmodel. Default: compile.                                                                         |
  | enable\_profile | bool   | Optional. Enable profile log. Default: false                                                                                                     |
* Python模式下工具支持配置格式如下：

```
  import bmnetp
  ## compile fp32 model
  bmnetp.compile(
  　　  model = "/path/to/.pth",        ## Necessary
  　　  outdir = "xxx",                 ## Necessary
  　　  target = "BM1682"               ## Necessary
  　　  shapes = [[x,x,x,x], [x,x,x]],  ## Necessary
  　　  net_name = "name",              ## Necessary
  　　  opt = 2,                        ## optional, if not set, default equal to 1
  　　  dyn = False,                    ## optional, if not set, default equal to False
  　　  cmp = True,                     ## optional, if not set, default equal to True
  　　  enable_profile = True           ## optional, if not set, default equal to False
  )
```

bmnetp成功后，将在指定的文件夹中生成一个compilation.bmodel的文件，该文件则是转换成功的bmodel，用户可以重命名。 若用户在bmnetp时使用了cmp=true模式，则会在指定的文件夹中生成一个input\_ref\_data.dat和一个output\_ref\_data.dat， 分别是Pytorch产生的网络输入参考数据和网络输出参考数据，可用于bmrt\_test验证生成的bmodel在芯片运行时结果是否正确。

* Bmnetp安装：

```
  # cd /workspace/bmnet/bmnetp/
  # pip install bmnetp-x.x.x-py2.py3-none-any.whl
```

## 4. MxNet模型编译

fp32 bmodel BMNETM是针对mxnet的模型编译器，可以将mxnet格式的模型结构文件和参数文件（比如：lenet-symbol.json和lenet-0100.params）在经过图编译优化后，转换成BMRuntime所需的文件。可选择将每一个操作的NPU模型计算结果和原始模型在mxnet框架上的计算结果进行对比，保证模型转换的正确性。

* BMNETM命令可以把mxnet模型转换为bmodel，命令介绍如下：

  ```
    python3 -m bmnetm [--model=<path>] \
    　　              [--weight=<path>] \
    　　              [--shapes=<string>] \
    　　              [--input_names=<string>] \
    　　              [--net_name=<name>] \
    　　              [--opt=<value>] \
    　　              [--dyn=<bool>] \
    　　              [--outdir=<path>] \
    　　              [--target=<name>] \
    　　              [--cmp=<bool>] \
    　　              [--enable_profile=<bool>]
  ```
* 参数介绍如下：

  | args            | type   | Description                                                                                                                                      |
  | --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
  | model           | String | Necessary. MxNet symbol .json path                                                                                                               |
  | weight          | string | Necessary. MxNet weight .params path                                                                                                             |
  | shapes          | string | Necessary. Shapes of all inputs, default use the shape in prototxt, format \[x,x,x,x],\[x,x]…, these correspond to inputs one by one in sequence |
  | input\_names    | string | Optional. Set input name according to .json. They correspond to shapes one by one. Default: “data”. Format “name1,name2,…”.                      |
  | net\_name       | string | Optional. Name of the network, default use the name in prototxt                                                                                  |
  | opt             | int    | Optional. Optimization level. Option: 0, 1, 2, default 1.                                                                                        |
  | dyn             | bool   | Optional. Use dynamic compilation, default false.                                                                                                |
  | outdir          | string | Necessary. Output directory                                                                                                                      |
  | target          | string | Necessary. Option: BM1682, BM1684; default: BM1682                                                                                               |
  | cmp             | bool   | Optional.Check result during compilation. Default: true                                                                                          |
  | mode            | string | Optional. Set bmnetc mode. Option: compile, GenUmodel. Default: compile.                                                                         |
  | enable\_profile | bool   | Optional. Enable profile log. Default: false                                                                                                     |
* Python模式下配置接口参数如下：

```
  import bmnetm
  ## compile fp32 model
  bmnetm.compile(
  　　  model = "/path/to/.json",       ## Necessary
  　　  weight = "/path/to/.params",    ## Necessary
  　　  outdir = "xxx",                 ## Necessary
  　　  target = "BM1682",              ## Necessary
  　　  shapes = [[x,x,x,x], [x,x,x]],  ## Necessary
  　　  net_name = "name",              ## Necessary
  　　  input_names=["name1","name2"]   ## optional, if not set, default is "data"
  　　  opt = 2,                        ## optional, if not set, default equal to 1
  　　  dyn = False,                    ## optional, if not set, default equal to False
  　　  cmp = True,                     ## optional, if not set, default equal to True
  　　  enable_profile = True           ## optional, if not set, default equal to False
  )
```

bmnetm成功后，将在指定的文件夹中生成一个compilation.bmodel的文件，该文件则是转换成功的bmodel，用户可以重命名。 若用户在bmnetm时使用了cmp=true模式，则会在指定的文件夹中生成一个input\_ref\_data.dat和一个output\_ref\_data.dat， 分别是Mxnet产生的网络输入参考数据和网络输出参考数据，可用于bmrt\_test验证生成的bmodel在芯片运行时结果是否正确。

* bmnetm安装：

```
  # cd /workspace/bmnet/bmnetm/
  # pip install bmnetm-x.x.x-py2.py3-none-any.whl
```
