advanced_usage.rst 23.3 KB
Newer Older
L
liyin 已提交
1 2
Advanced usage for Bazel users
================================
L
Liangliang He 已提交
3

L
liutuo 已提交
4 5 6
This part contains the full usage of MACE.

Overview
L
liutuo 已提交
7
---------
L
liutuo 已提交
8 9

As mentioned in the previous part, a model deployment file defines a case of model deployment.
L
Liangliang He 已提交
10 11
The building process includes parsing model deployment file, converting models,
building MACE core library and packing generated model libraries.
L
liutuo 已提交
12 13

Deployment file
L
Liangliang He 已提交
14
---------------
L
liutuo 已提交
15 16 17 18 19 20 21 22 23 24


One deployment file will generate one library normally, but if more than one ABIs are specified,
one library will be generated for each ABI.
A deployment file can also contain multiple models. For example, an AI camera application may
contain face recognition, object recognition, and voice recognition models, all of which can be defined
in one deployment file.

* **Example**

25
    Here is an example deployment file with two models.
L
liutuo 已提交
26

27
    .. literalinclude:: models/demo_models.yml
L
liutuo 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
        :language: yaml


* **Configurations**


.. list-table::
    :header-rows: 1

    * - Options
      - Usage
    * - library_name
      - Library name.
    * - target_abis
      - The target ABI(s) to build, could be 'host', 'armeabi-v7a' or 'arm64-v8a'.
L
liuqi 已提交
43
        If more than one ABIs will be used, separate them by commas.
L
liutuo 已提交
44 45
    * - target_socs
      - [optional] Build for specific SoCs.
46 47 48 49
    * - model_graph_format
      - model graph format, could be 'file' or 'code'. 'file' for converting model graph to ProtoBuf file(.pb) and 'code' for converting model graph to c++ code.
    * - model_data_format
      - model data format, could be 'file' or 'code'. 'file' for converting model weight to data file(.data) and 'code' for converting model weight to c++ code.
L
liutuo 已提交
50
    * - model_name
L
liuqi 已提交
51
      - model name should be unique if there are more than one models.
L
liutuo 已提交
52 53 54 55
        **LIMIT: if build_type is code, model_name will be used in c++ code so that model_name must comply with c++ name specification.**
    * - platform
      - The source framework, tensorflow or caffe.
    * - model_file_path
L
liuqi 已提交
56
      - The path of your model file which can be local path or remote URL.
L
liutuo 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    * - model_sha256_checksum
      - The SHA256 checksum of the model file.
    * - weight_file_path
      - [optional] The path of Caffe model weights file.
    * - weight_sha256_checksum
      - [optional] The SHA256 checksum of Caffe model weights file.
    * - subgraphs
      - subgraphs key. **DO NOT EDIT**
    * - input_tensors
      - The input tensor name(s) (tensorflow) or top name(s) of inputs' layer (caffe).
        If there are more than one tensors, use one line for a tensor.
    * - output_tensors
      - The output tensor name(s) (tensorflow) or top name(s) of outputs' layer (caffe).
        If there are more than one tensors, use one line for a tensor.
    * - input_shapes
72
      - The shapes of the input tensors, default is NHWC order.
L
liutuo 已提交
73
    * - output_shapes
74
      - The shapes of the output tensors, default is NHWC order.
L
liutuo 已提交
75 76 77 78
    * - input_ranges
      - The numerical range of the input tensors' data, default [-1, 1]. It is only for test.
    * - validation_inputs_data
      - [optional] Specify Numpy validation inputs. When not provided, [-1, 1] random values will be used.
79 80
    * - accuracy_validation_script
      - [optional] Specify the accuracy validation script as a plugin to test accuracy, see `doc <#validate-accuracy-of-mace-model>`__.
81 82
    * - validation_threshold
      - [optional] Specify the similarity threshold for validation. A dict with key in 'CPU', 'GPU' and/or 'HEXAGON' and value <= 1.0.
L
liutuo 已提交
83 84
    * - backend
      - The onnx backend framework for validation, could be [tensorflow, caffe2, pytorch], default is tensorflow.
L
liutuo 已提交
85
    * - runtime
L
Fix doc  
liyin 已提交
86
      - The running device, one of [cpu, gpu, dsp, cpu+gpu]. cpu+gpu contains CPU and GPU model definition so you can run the model on both CPU and GPU.
L
liutuo 已提交
87 88
    * - data_type
      - [optional] The data type used for specified runtime. [fp16_fp32, fp32_fp32] for GPU, default is fp16_fp32, [fp32] for CPU and [uint8] for DSP.
Y
yejianwu 已提交
89 90
    * - input_data_types
      - [optional] The input data type for specific op(eg. gather), which can be [int32, float32], default to float32.
91
    * - input_data_formats
Y
yejianwu 已提交
92
      - [optional] The format of the input tensors, one of [NONE, NHWC, NCHW]. If there is no format of the input, please use NONE. If only one single format is specified, all inputs will use that format, default is NHWC order.
93
    * - output_data_formats
Y
yejianwu 已提交
94
      - [optional] The format of the output tensors, one of [NONE, NHWC, NCHW]. If there is no format of the output, please use NONE. If only one single format is specified, all inputs will use that format, default is NHWC order.
L
liutuo 已提交
95 96
    * - limit_opencl_kernel_time
      - [optional] Whether splitting the OpenCL kernel within 1 ms to keep UI responsiveness, default is 0.
97 98
    * - opencl_queue_window_size
      - [optional] Limit the max commands in OpenCL command queue to keep UI responsiveness, default is 0.
L
liutuo 已提交
99 100 101
    * - obfuscate
      - [optional] Whether to obfuscate the model operator name, default to 0.
    * - winograd
102
      - [optional] Which type winograd to use, could be [0, 2, 4]. 0 for disable winograd, 2 and 4 for enable winograd, 4 may be faster than 2 but may take more memory.
L
liutuo 已提交
103 104 105 106 107 108


.. note::

    Some command tools:

109
    .. code-block:: bash
L
liutuo 已提交
110

L
liuqi 已提交
111 112
        # Get device's soc info.
        adb shell getprop | grep platform
L
liutuo 已提交
113 114

        # command for generating sha256_sum
L
liutuo 已提交
115
        sha256sum /path/to/your/file
L
liutuo 已提交
116 117


L
liuqi 已提交
118

L
Liangliang He 已提交
119 120
Advanced usage
--------------
L
liutuo 已提交
121

L
liuqi 已提交
122
There are three common advanced use cases:
123
  - run your model on the embedded device(ARM LINUX)
L
Liangliang He 已提交
124 125
  - converting model to C++ code.
  - tuning GPU kernels for a specific SoC.
L
liutuo 已提交
126

127 128
Run you model on the embedded device(ARM Linux)
-----------------------------------------------
L
liuqi 已提交
129

130
The way to run your model on the ARM Linux is nearly same as with android, except you need specify a device config file.
L
liuqi 已提交
131

132
.. code-block:: bash
L
liuqi 已提交
133

134
    python tools/converter.py run --config=/path/to/your/model_deployment_file.yml --device_yml=/path/to/devices.yml
L
liuqi 已提交
135

136
There are two steps to do before run:
L
liuqi 已提交
137

138
1. configure login without password
L
liuqi 已提交
139

140
    MACE use ssh to connect embedded device, you should copy your public key to embedded device with the blow command.
L
liuqi 已提交
141

142
    .. code-block:: bash
L
liuqi 已提交
143

144
      cat ~/.ssh/id_rsa.pub | ssh -q {user}@{ip} "cat >> ~/.ssh/authorized_keys"
L
liuqi 已提交
145

146
2. write your own device yaml configuration file.
L
liuqi 已提交
147

148
    * **Example**
L
liuqi 已提交
149

150
        Here is an device yaml config demo.
L
liuqi 已提交
151

152 153
        .. literalinclude:: devices/demo_device_nanopi.yml
            :language: yaml
L
liuqi 已提交
154

155 156
    * **Configuration**
        The detailed explanation is listed in the blow table.
L
liuqi 已提交
157

158 159
        .. list-table::
            :header-rows: 1
L
liuqi 已提交
160

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
            * - Options
              - Usage
            * - target_abis
              - Device supported abis, you can get it via ``dpkg --print-architecture`` and
                ``dpkg --print-foreign-architectures`` command, if more than one abi is supported,
                separate them by commas.
            * - target_socs
              - device soc, you can get it from device manual, we haven't found a way to get it in shell.
            * - models
              - device models full name, you can get via get ``lshw`` command (third party package, install it via your package manager).
                see it's product value.
            * - address
              - Since we use ssh to connect device, ip address is required.
            * - username
              - login username, required.
L
liuqi 已提交
176 177


178
Convert model(s) to C++ code
179
----------------------------
L
liutuo 已提交
180

181
    * **1. Change the model deployment file(.yml)**
L
liutuo 已提交
182

L
Liangliang He 已提交
183
        If you want to protect your model, you can convert model to C++ code. there are also two cases:
L
liutuo 已提交
184

L
liuqi 已提交
185
        * convert model graph to code and model weight to file with below model configuration.
L
liutuo 已提交
186

187
        .. code-block:: sh
L
liutuo 已提交
188

L
liuqi 已提交
189 190
            model_graph_format: code
            model_data_format: file
L
liutuo 已提交
191

L
liuqi 已提交
192
        * convert both model graph and model weight to code with below model configuration.
L
liutuo 已提交
193

194
        .. code-block:: sh
L
liutuo 已提交
195

L
liuqi 已提交
196 197
            model_graph_format: code
            model_data_format: code
L
liutuo 已提交
198

L
liuqi 已提交
199
        .. note::
L
liutuo 已提交
200

201
             Another model protection method is using ``obfuscate`` to obfuscate names of model's operators.
L
liutuo 已提交
202

L
liuqi 已提交
203
    * **2. Convert model(s) to code**
L
liutuo 已提交
204

205
        .. code-block:: sh
L
liutuo 已提交
206

L
liuqi 已提交
207
            python tools/converter.py convert --config=/path/to/model_deployment_file.yml
L
liutuo 已提交
208

L
Liangliang He 已提交
209 210
        The command will generate **${library_name}.a** in **build/${library_name}/model** directory and
        ** *.h ** in **build/${library_name}/include** like the following dir-tree.
L
liutuo 已提交
211

212
        .. code-block:: none
L
liutuo 已提交
213

214 215 216
             # model_graph_format: code
             # model_data_format: file

L
Liangliang He 已提交
217
             build
218 219 220 221 222 223 224 225
               ├── include
               │   └── mace
               │       └── public
               │           ├── mace_engine_factory.h
               │           └── mobilenet_v1.h
               └── model
                   ├── mobilenet-v1.a
                   └── mobilenet_v1.data
L
liutuo 已提交
226

L
liuqi 已提交
227 228 229
             # model_graph_format: code
             # model_data_format: code

L
Liangliang He 已提交
230
             build
L
liuqi 已提交
231 232 233 234 235 236 237
               ├── include
               │   └── mace
               │       └── public
               │           ├── mace_engine_factory.h
               │           └── mobilenet_v1.h
               └── model
                   └── mobilenet-v1.a
L
liutuo 已提交
238

L
liuqi 已提交
239 240
    * **3. Deployment**
        * Link `libmace.a` and `${library_name}.a` to your target.
L
liyin 已提交
241
        * Refer to \ ``mace/tools/mace_run.cc``\ for full usage. The following list the key steps.
L
liutuo 已提交
242

243
        .. code-block:: cpp
L
liutuo 已提交
244

L
liuqi 已提交
245 246 247 248 249
            // Include the headers
            #include "mace/public/mace.h"
            // If the model_graph_format is code
            #include "mace/public/${model_name}.h"
            #include "mace/public/mace_engine_factory.h"
L
liutuo 已提交
250

L
liuqi 已提交
251
            // ... Same with the code in basic usage
L
liutuo 已提交
252

L
liuqi 已提交
253 254 255 256 257 258
            // 4. Create MaceEngine instance
            std::shared_ptr<mace::MaceEngine> engine;
            MaceStatus create_engine_status;
            // Create Engine from compiled code
            create_engine_status =
                CreateMaceEngineFromCode(model_name.c_str(),
李寅 已提交
259 260
                                         model_data_ptr, // nullptr if model_data_format is code
                                         model_data_size, // 0 if model_data_format is code
L
liuqi 已提交
261 262 263 264 265
                                         input_names,
                                         output_names,
                                         device_type,
                                         &engine);
            if (create_engine_status != MaceStatus::MACE_SUCCESS) {
L
liuqi 已提交
266
              // Report error or fallback
L
liuqi 已提交
267
            }
L
liutuo 已提交
268

L
liuqi 已提交
269
            // ... Same with the code in basic usage
L
liutuo 已提交
270 271


272
Transform models after conversion
273
---------------------------------
L
liutuo 已提交
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    If ``model_graph_format`` or ``model_data_format`` is specified as `file`, the model or weight file will
    be generated as a `.pb` or `.data` file after model conversion. After that, more transformations can be
    applied to the generated files, such as compression or encryption. To achieve that, the model loading is
    split to two stages: 1) load the file from file system to memory buffer; 2) create the MACE engine from the
    model buffer. So between the two stages, transformations can be inserted to decompress or decrypt the model
    buffer. The transformations are user defined. The following lists the key steps when both ``model_graph_format``
    and ``model_data_format`` are set as `file`.

    .. code-block:: cpp

        // Load model graph from file system
        std::unique_ptr<mace::port::ReadOnlyMemoryRegion> model_graph_data =
            make_unique<mace::port::ReadOnlyBufferMemoryRegion>();
        if (FLAGS_model_file != "") {
          auto fs = GetFileSystem();
          status = fs->NewReadOnlyMemoryRegionFromFile(FLAGS_model_file.c_str(),
              &model_graph_data);
          if (status != MaceStatus::MACE_SUCCESS) {
            // Report error or fallback
          }
        }
        // Load model data from file system
        std::unique_ptr<mace::port::ReadOnlyMemoryRegion> model_weights_data =
            make_unique<mace::port::ReadOnlyBufferMemoryRegion>();
        if (FLAGS_model_data_file != "") {
          auto fs = GetFileSystem();
          status = fs->NewReadOnlyMemoryRegionFromFile(FLAGS_model_data_file.c_str(),
              &model_weights_data);
          if (status != MaceStatus::MACE_SUCCESS) {
            // Report error or fallback
          }
        }
        if (model_graph_data == nullptr || model_weights_data == nullptr) {
          // Report error or fallback
        }

B
Bin Li 已提交
311 312
        std::vector<unsigned char> transformed_model_graph_data;
        std::vector<unsigned char> transformed_model_weights_data;
313 314
        // Add transformations here.
        ...
B
Bin Li 已提交
315 316 317
        // Release original model data after transformations
        model_graph_data.reset();
        model_weights_data.reset();
318 319 320 321 322

        // Create the MACE engine from the model buffer
        std::shared_ptr<mace::MaceEngine> engine;
        MaceStatus create_engine_status;
        create_engine_status =
B
Bin Li 已提交
323 324 325 326
            CreateMaceEngineFromProto(transformed_model_graph_data.data(),
                                      transformed_model_graph_data.size(),
                                      transformed_model_weights_data.data(),
                                      transformed_model_weights_data.size(),
327 328 329 330 331 332 333 334 335 336 337 338
                                      input_names,
                                      output_names,
                                      config,
                                      &engine);
        if (create_engine_status != MaceStatus::MACE_SUCCESS) {
          // Report error or fallback
        }


Tuning for specific SoC's GPU
-----------------------------

339
    If you want to use the GPU of a specific device, you can just specify the ``target_socs`` in your YAML file and
L
Liangliang He 已提交
340
    then tune the MACE lib for it (OpenCL kernels), which may get 1~10% performance improvement.
L
liutuo 已提交
341

342
    * **1. Change the model deployment file(.yml)**
L
liutuo 已提交
343

344
        Specify ``target_socs`` in your model deployment file(.yml):
L
liutuo 已提交
345

346
        .. code-block:: sh
L
liuqi 已提交
347 348 349 350 351 352 353 354 355

            target_socs: [sdm845]

        .. note::

            Get device's soc info: `adb shell getprop | grep platform`

    * **2. Convert model(s)**

356
        .. code-block:: sh
L
liuqi 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369

            python tools/converter.py convert --config=/path/to/model_deployment_file.yml

    * **3. Tuning**

        The tools/converter.py will enable automatic tuning for GPU kernels. This usually takes some
        time to finish depending on the complexity of your model.

        .. note::

             You should plug in device(s) with the specific SoC(s).


370
        .. code-block:: sh
L
liuqi 已提交
371 372 373

            python tools/converter.py run --config=/path/to/model_deployment_file.yml --validate

L
Liangliang He 已提交
374
        The command will generate two files in `build/${library_name}/opencl`, like the following dir-tree.
L
liuqi 已提交
375

376
        .. code-block:: none
L
liuqi 已提交
377

L
Liangliang He 已提交
378
              build
L
liuqi 已提交
379 380 381 382 383 384 385
              └── mobilenet-v2
                  ├── model
                  │   ├── mobilenet_v2.data
                  │   └── mobilenet_v2.pb
                  └── opencl
                      └── arm64-v8a
                         ├── moblinet-v2_compiled_opencl_kernel.MiNote3.sdm660.bin
386 387 388
                         ├── moblinet-v2_compiled_opencl_kernel.MiNote3.sdm660.bin.cc
                         ├── moblinet-v2_tuned_opencl_parameter.MiNote3.sdm660.bin
                         └── moblinet-v2_tuned_opencl_parameter.MiNote3.sdm660.bin.cc
L
liuqi 已提交
389 390 391 392 393


        * **mobilenet-v2-gpu_compiled_opencl_kernel.MI6.msm8998.bin** stands for the OpenCL binaries
          used for your models, which could accelerate the initialization stage.
          Details please refer to `OpenCL Specification <https://www.khronos.org/registry/OpenCL/sdk/1.0/docs/man/xhtml/clCreateProgramWithBinary.html>`__.
394
        * **mobilenet-v2-gpu_compiled_opencl_kernel.MI6.msm8998.bin.cc** contains C++ source code which defines OpenCL binary data as const array.
L
liuqi 已提交
395
        * **mobilenet-v2-tuned_opencl_parameter.MI6.msm8998.bin** stands for the tuned OpenCL parameters
L
Liangliang He 已提交
396
          for the SoC.
397
        * **mobilenet-v2-tuned_opencl_parameter.MI6.msm8998.bin.cc** contains C++ source code which defines OpenCL binary data as const array.
L
liuqi 已提交
398 399

    * **4. Deployment**
L
liuqi 已提交
400 401
        * Change the names of files generated above for not collision and push them to **your own device's directory**.
        * Use like the previous procedure, below lists the key steps differently.
L
liuqi 已提交
402

403
        .. code-block:: cpp
L
liuqi 已提交
404 405 406

            // Include the headers
            #include "mace/public/mace.h"
L
liuqi 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
            // 0. Declare the device type (must be same with ``runtime`` in configuration file)
            DeviceType device_type = DeviceType::GPU;

            // 1. configuration
            MaceStatus status;
            MaceEngineConfig config(device_type);
            std::shared_ptr<GPUContext> gpu_context;

            const std::string storage_path ="path/to/storage";
            gpu_context = GPUContextBuilder()
                .SetStoragePath(storage_path)
                .SetOpenCLBinaryPaths(path/to/opencl_binary_paths)
                .SetOpenCLParameterPath(path/to/opencl_parameter_file)
                .Finalize();
            config.SetGPUContext(gpu_context);
            config.SetGPUHints(
                static_cast<GPUPerfHint>(GPUPerfHint::PERF_NORMAL),
                static_cast<GPUPriorityHint>(GPUPriorityHint::PRIORITY_LOW));
L
liuqi 已提交
425 426 427 428

            // ... Same with the code in basic usage.


429 430 431 432 433 434 435 436 437 438 439 440 441
Validate accuracy of MACE model
-------------------------------

MACE supports **python validation script** as a plugin to test the accuracy, the plugin script could be used for below two purpose.

1. Test the **accuracy(like Top-1)** of MACE model(specifically quantization model) converted from other framework(like tensorflow)
2. Show some real output if you want to see it.

The script define some interfaces like `preprocess` and `postprocess` to deal with input/outut and calculate the accuracy,
you could refer to the `sample code <https://github.com/XiaoMi/mace/tree/master/tools/accuracy_validator.py>`__ for detail.
the sample code show how to calculate the Top-1 accuracy with imagenet validation dataset.


L
liuqi 已提交
442
Useful Commands
L
Liangliang He 已提交
443
---------------
L
liuqi 已提交
444 445
* **run the model**

446
.. code-block:: sh
L
liuqi 已提交
447 448 449 450 451 452 453 454

    # Test model run time
    python tools/converter.py run --config=/path/to/model_deployment_file.yml --round=100

    # Validate the correctness by comparing the results against the
    # original model and framework, measured with cosine distance for similarity.
    python tools/converter.py run --config=/path/to/model_deployment_file.yml --validate

455
    # Check the memory usage of the model(**Just keep only one model in deployment file**)
L
liuqi 已提交
456 457 458 459 460 461 462 463
    python tools/converter.py run --config=/path/to/model_deployment_file.yml --round=10000 &
    sleep 5
    adb shell dumpsys meminfo | grep mace_run
    kill %1


.. warning::

464
    ``run`` rely on ``convert`` command, you should ``convert`` before ``run``.
L
liuqi 已提交
465

466
* **benchmark and profile model**
L
liuqi 已提交
467

468 469
the detailed information is in :doc:`benchmark`.

470
.. code-block:: sh
L
liuqi 已提交
471 472

    # Benchmark model, get detailed statistics of each Op.
L
liyin 已提交
473
    python tools/converter.py run --config=/path/to/model_deployment_file.yml --benchmark
L
liuqi 已提交
474 475 476


.. warning::
L
liutuo 已提交
477

L
liuqi 已提交
478
    ``benchmark`` rely on ``convert`` command, you should ``benchmark`` after ``convert``.
L
liutuo 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492

**Common arguments**

    .. list-table::
        :header-rows: 1

        * - option
          - type
          - default
          - commands
          - explanation
        * - --omp_num_threads
          - int
          - -1
L
liyin 已提交
493
          - ``run``
L
liutuo 已提交
494 495 496 497
          - number of threads
        * - --cpu_affinity_policy
          - int
          - 1
L
liyin 已提交
498
          - ``run``
L
liutuo 已提交
499 500 501 502
          - 0:AFFINITY_NONE/1:AFFINITY_BIG_ONLY/2:AFFINITY_LITTLE_ONLY
        * - --gpu_perf_hint
          - int
          - 3
L
liyin 已提交
503
          - ``run``
L
liutuo 已提交
504 505 506 507 508 509 510 511 512
          - 0:DEFAULT/1:LOW/2:NORMAL/3:HIGH
        * - --gpu_priority_hint
          - int
          - 3
          - ``run``/``benchmark``
          - 0:DEFAULT/1:LOW/2:NORMAL/3:HIGH

Use ``-h`` to get detailed help.

513
.. code-block:: sh
L
liutuo 已提交
514 515 516 517

    python tools/converter.py -h
    python tools/converter.py build -h
    python tools/converter.py run -h
Y
yejianwu 已提交
518 519 520

Reduce Library Size
-------------------
521 522
* Build for your own usage purpose.
    * **dynamic library**
Y
yejianwu 已提交
523

524 525
        - If the models don't need to run on device ``dsp``, change the build option ``--define hexagon=true``
          to ``false``. And the library will be decreased about ``100KB``.
Y
yejianwu 已提交
526

527 528
        - Futher more, if only ``cpu`` device needed, change ``--define opencl=true`` to ``false``. This way
          will reduce half of library size to about ``700KB`` for ``armeabi-v7a`` and ``1000KB`` for ``arm64-v8a``
Y
yejianwu 已提交
529

530 531 532
        - About ``300KB`` can be reduced when add ``--config symbol_hidden`` building option. It will change
          the visibility of inner apis in libmace.so and lead to linking error when load model(s) in ``code``
          but no effection for ``file`` mode.
Y
yejianwu 已提交
533

534
    * **static library**
535

536 537 538
        - The methods in dynamic library can be useful for static library too. In additional, the static
          library may also contain model graph and model datas if the configs ``model_graph_format`` and
          ``model_data_format`` in deployment file are set to ``code``.
Y
yejianwu 已提交
539

540
        - It is recommended to use ``version script`` and ``strip`` feature when linking mace static library. The effect is remarkable.
Y
yejianwu 已提交
541

542
* Remove the unused ops.
L
liuqi 已提交
543

544 545 546
Remove the registration of the ops unused for your models in the ``mace/ops/ops_register.cc``,
which will reduce the library size significantly. the final binary just link the registered ops' code.

547
.. code-block:: cpp
548

549
    #include "mace/ops/ops_register.h"
550

551 552 553
    namespace mace {
    namespace ops {
    // Just leave the ops used in your models
554

555
    ...
556

557
    }  // namespace ops
558 559


560 561
    OpRegistry::OpRegistry() : OpRegistryBase() {
    // Just leave the ops used in your models
562

563
      ...
564

565
      ops::RegisterMyCustomOp(this);
566

567 568 569 570 571
      ...

    }

    }  // namespace mace
B
Bin Li 已提交
572 573 574 575 576 577 578 579

Reduce Model Size
-------------------
Model file size can be a bottleneck for the deployment of neural networks on mobile devices,
so MACE provides several ways to reduce the model size with no or little performance or accuracy degradation.

**1. Save model weights in half-precision floating point format**

B
Bin Li 已提交
580
The data type of a regular model is float (32bit). To reduce the model weights size,
B
Bin Li 已提交
581
half (16bit) can be used to reduce it by half with negligible accuracy degradation.
B
Bin Li 已提交
582 583
Therefore, the default storage type for a regular model in MACE is half. However,
if the model is very sensitive to accuracy, storage type can be changed to float.
B
Bin Li 已提交
584

B
Bin Li 已提交
585
In the deployment file, ``data_type`` is ``fp16_fp32`` by default and can be changed to ``fp32_fp32``.
B
Bin Li 已提交
586

B
Bin Li 已提交
587 588 589
For CPU, ``fp16_fp32`` means that the weights are saved in half and actual inference is in float.

For GPU, ``fp16_fp32`` means that the ops in GPU take half as inputs and outputs while kernel execution in float.
B
Bin Li 已提交
590 591 592 593 594 595 596 597

**2. Save model weights in quantized fixed point format**

Weights of convolutional (excluding depthwise) and fully connected layers take up a major part of model size.
These weights can be quantized to 8bit to reduce the size to a quarter, whereas the accuracy usually decreases only by 1%-3%.
For example, the top-1 accuracy of MobileNetV1 after quantization of weights is 68.2% on the ImageNet validation set.
``quantize_large_weights`` can be specified as 1 in the deployment file to save these weights in 8bit and actual inference in float.
It can be used for both CPU and GPU.