basic_usage.rst 10.8 KB
Newer Older
L
Liangliang He 已提交
1
Basic usage
L
update  
liutuo 已提交
2
============
L
Liangliang He 已提交
3

L
liutuo 已提交
4 5

Build and run an example model
L
update  
liutuo 已提交
6
-------------------------------
L
liutuo 已提交
7

L
update  
liutuo 已提交
8
At first, make sure the environment has been set up correctly already (refer to :doc:`../installation/env_requirement`).
L
liutuo 已提交
9

L
liutuo 已提交
10
The followings are instructions about  how to quickly build and run a provided model in *MACE Model Zoo*.
L
liutuo 已提交
11

L
liutuo 已提交
12
Here we use the mobilenet-v2 model as an example.
L
liutuo 已提交
13

L
liutuo 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
**Commands**

    1. Pull *MACE* project.

    .. code:: sh

        git clone https://github.com/XiaoMi/mace.git
        git fetch --all --tags --prune

        # Checkout the latest tag (i.e. release version)
        tag_name=`git describe --abbrev=0 --tags`
        git checkout tags/${tag_name}

    .. note::

        It's highly recommanded to use a release version instead of master branch.


    2. Pull *MACE Model Zoo* project.

    .. code:: sh

        git clone https://github.com/XiaoMi/mace-models.git


L
liutuo 已提交
39
    3. Build a general MACE library.
L
liutuo 已提交
40 41

    .. code:: sh
L
liutuo 已提交
42

L
liutuo 已提交
43 44
        cd path/to/mace
        # Build library
L
liuqi 已提交
45 46
        # output lib path: builds/lib
        bash tools/build-standalone-lib.sh
L
liutuo 已提交
47 48


L
liutuo 已提交
49
    4. Convert the model to MACE format model.
L
liutuo 已提交
50

L
liutuo 已提交
51
    .. code:: sh
L
liutuo 已提交
52

L
liutuo 已提交
53 54
        cd path/to/mace
        # Build library
L
liuqi 已提交
55
        python tools/converter.py convert --config=/path/to/mace-models/mobilenet-v2/mobilenet-v2.yml
L
liutuo 已提交
56 57


L
liutuo 已提交
58
    5. Run the model.
L
liutuo 已提交
59

L
liuqi 已提交
60 61 62 63
    .. warning::

        If you want to run on device/phone, please plug in at least one device/phone.

L
liutuo 已提交
64 65
    .. code:: sh

66 67 68
        # Run example
        python tools/converter.py run --config=/path/to/mace-models/mobilenet-v2/mobilenet-v2.yml --example

L
liutuo 已提交
69
    	# Test model run time
L
liutuo 已提交
70
        python tools/converter.py run --config=/path/to/mace-models/mobilenet-v2/mobilenet-v2.yml --round=100
L
liutuo 已提交
71 72 73

    	# Validate the correctness by comparing the results against the
    	# original model and framework, measured with cosine distance for similarity.
L
liutuo 已提交
74
    	python tools/converter.py run --config=/path/to/mace-models/mobilenet-v2/mobilenet-v2.yml --validate
L
liutuo 已提交
75 76 77


Build your own model
L
update  
liutuo 已提交
78
---------------------
L
liutuo 已提交
79 80 81

This part will show you how to use your pre-trained model in MACE.

L
update  
liutuo 已提交
82
======================
L
liutuo 已提交
83
1. Prepare your model
L
update  
liutuo 已提交
84
======================
L
liutuo 已提交
85

86
Mace now supports models from TensorFlow and Caffe (more frameworks will be supported).
L
liutuo 已提交
87 88 89

-  TensorFlow

90
   Prepare your pre-trained TensorFlow model.pb file.
L
liutuo 已提交
91 92

   Use `Graph Transform Tool <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md>`__
L
liutuo 已提交
93
   to optimize your model for inference.
L
liutuo 已提交
94
   This tool will improve the efficiency of inference by making several optimizations like operators
L
liutuo 已提交
95
   folding, redundant node removal etc. We strongly recommend MACE users to use it before building.
L
liutuo 已提交
96

L
liutuo 已提交
97
   Usage for CPU/GPU,
L
liutuo 已提交
98 99 100 101 102

   .. code:: bash

       # CPU/GPU:
       ./transform_graph \
L
liutuo 已提交
103 104 105 106
           --in_graph=/path/to/your/tf_model.pb \
           --out_graph=/path/to/your/output/tf_model_opt.pb \
           --inputs='input node name' \
           --outputs='output node name' \
L
liutuo 已提交
107 108 109 110 111 112 113 114 115 116 117 118
           --transforms='strip_unused_nodes(type=float, shape="1,64,64,3")
               strip_unused_nodes(type=float, shape="1,64,64,3")
               remove_nodes(op=Identity, op=CheckNumerics)
               fold_constants(ignore_errors=true)
               flatten_atrous_conv
               fold_batch_norms
               fold_old_batch_norms
               strip_unused_nodes
               sort_by_execution_order'

-  Caffe

L
liutuo 已提交
119 120 121
   Caffe 1.0+ models are supported in MACE converter tool.

   If your model is from lower version Caffe, you need to upgrade it by using the Caffe built-in tool before converting.
L
liutuo 已提交
122 123 124 125 126 127 128 129 130

   .. code:: bash

       # Upgrade prototxt
       $CAFFE_ROOT/build/tools/upgrade_net_proto_text MODEL.prototxt MODEL.new.prototxt

       # Upgrade caffemodel
       $CAFFE_ROOT/build/tools/upgrade_net_proto_binary MODEL.caffemodel MODEL.new.caffemodel

L
liutuo 已提交
131

L
update  
liutuo 已提交
132
===========================================
L
liutuo 已提交
133
2. Create a deployment file for your model
L
update  
liutuo 已提交
134
===========================================
L
liutuo 已提交
135

L
liutuo 已提交
136 137 138 139 140
When converting a model or building a library, MACE needs to read a YAML file which is called model deployment file here.

A model deployment file contains all the information of your model(s) and building options. There are several example
deployment files in *MACE Model Zoo* project.

141
The following shows two basic usage of deployment files for TensorFlow and Caffe models.
L
liutuo 已提交
142
Modify one of them and use it for your own case.
L
liutuo 已提交
143

144
-  TensorFlow
L
liutuo 已提交
145 146 147 148 149 150 151 152 153

   .. literalinclude:: models/demo_app_models_tf.yml
      :language: yaml

-  Caffe

   .. literalinclude:: models/demo_app_models_caffe.yml
      :language: yaml

L
liutuo 已提交
154
More details about model deployment file are in :doc:`advanced_usage`.
L
liutuo 已提交
155

L
update  
liutuo 已提交
156
======================
L
liutuo 已提交
157
3. Convert your model
L
update  
liutuo 已提交
158
======================
L
liutuo 已提交
159

L
liutuo 已提交
160
When the deployment file is ready, you can use MACE converter tool to convert your model(s).
L
liutuo 已提交
161

L
liutuo 已提交
162
.. code:: bash
L
liutuo 已提交
163

L
liutuo 已提交
164
    python tools/converter.py convert --config=/path/to/your/model_deployment_file.yml
L
liutuo 已提交
165

L
liutuo 已提交
166
This command will download or load your pre-trained model and convert it to a MACE model proto file and weights data file.
L
liutuo 已提交
167 168 169 170
The generated model files will be stored in ``build/${library_name}/model`` folder.

.. warning::

L
liuqi 已提交
171 172
    Please set ``model_graph_format: file`` and ``model_data_format: file`` in your deployment file before converting.
    The usage of ``model_graph_format: code`` will be demonstrated in :doc:`advanced_usage`.
L
liutuo 已提交
173

L
update  
liutuo 已提交
174
=============================
L
liutuo 已提交
175
4. Build MACE into a library
L
update  
liutuo 已提交
176
=============================
L
liutuo 已提交
177 178

Use bazel to build MACE source code into a library.
L
liutuo 已提交
179 180 181 182 183

    .. code:: sh

        cd path/to/mace
        # Build library
L
liuqi 已提交
184 185
        # output lib path: builds/lib
        bash tools/build-standalone-lib.sh
L
liutuo 已提交
186

L
liuqi 已提交
187
The above command will generate dynamic library ``builds/lib/${ABI}/libmace.so`` and static library ``builds/lib/${ABI}/libmace.a``.
L
liutuo 已提交
188 189 190

    .. warning::

L
liuqi 已提交
191
        Please verify that the target_abis param in the above command and your deployment file are the same.
L
liutuo 已提交
192 193


L
update  
liutuo 已提交
194
==================
L
liutuo 已提交
195
5. Run your model
L
update  
liutuo 已提交
196
==================
L
liutuo 已提交
197

L
update  
liutuo 已提交
198 199
With the converted model, the static or shared library and header files, you can use the following commands
to run and validate your model.
L
liutuo 已提交
200

L
liuqi 已提交
201 202 203 204
    .. warning::

        If you want to run on device/phone, please plug in at least one device/phone.

L
liutuo 已提交
205 206 207
* **run**

    run the model.
L
liutuo 已提交
208 209 210 211

    .. code:: sh

    	# Test model run time
L
liutuo 已提交
212
        python tools/converter.py run --config=/path/to/your/model_deployment_file.yml --round=100
L
liutuo 已提交
213 214 215

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

L
liutuo 已提交
218
* **benchmark**
L
liutuo 已提交
219

L
liutuo 已提交
220
    benchmark and profile the model.
L
liutuo 已提交
221 222 223 224

    .. code:: sh

        # Benchmark model, get detailed statistics of each Op.
L
liutuo 已提交
225
        python tools/converter.py benchmark --config=/path/to/your/model_deployment_file.yml
L
liutuo 已提交
226 227


L
update  
liutuo 已提交
228
=======================================
L
liutuo 已提交
229
6. Deploy your model into applications
L
update  
liutuo 已提交
230
=======================================
L
liutuo 已提交
231

L
liutuo 已提交
232
In the converting and building steps, you've got the static/shared library, model files and
L
liuqi 已提交
233
header files.
L
liutuo 已提交
234

L
liutuo 已提交
235
``${library_name}`` is the name you defined in the first line of your deployment YAML file.
L
liutuo 已提交
236 237 238 239 240

-  The generated ``static`` library files are organized as follows,

.. code::

L
liuqi 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    builds
    ├── include
    │   └── mace
    │       └── public
    │           ├── mace.h
    │           └── mace_runtime.h
    ├── lib
    │   ├── arm64-v8a
    │   │   ├── libmace.a
    │   │   └── libmace.so
    │   ├── armeabi-v7a
    │   │   ├── libhexagon_controller.so
    │   │   ├── libmace.a
    │   │   └── libmace.so
    │   └── linux-x86-64
    │       ├── libmace.a
    │       └── libmace.so
    └── mobilenet-v1
        ├── model
        │   ├── mobilenet_v1.data
        │   └── mobilenet_v1.pb
        └── _tmp
            └── arm64-v8a
                └── mace_run_static
L
liutuo 已提交
265

L
liutuo 已提交
266

L
liutuo 已提交
267
Please refer to \ ``mace/examples/example.cc``\ for full usage. The following list the key steps.
L
liutuo 已提交
268 269 270 271 272 273 274 275 276 277 278 279

.. code:: cpp

    // Include the headers
    #include "mace/public/mace.h"
    #include "mace/public/mace_runtime.h"

    // 0. Set pre-compiled OpenCL binary program file paths when available
    if (device_type == DeviceType::GPU) {
      mace::SetOpenCLBinaryPaths(opencl_binary_paths);
    }

L
liutuo 已提交
280 281 282 283 284
    // 1. Set compiled OpenCL kernel cache, this is used to reduce the
    // initialization time since the compiling is too slow. It's suggested
    // to set this even when pre-compiled OpenCL program file is provided
    // because the OpenCL version upgrade may also leads to kernel
    // recompilations.
L
liutuo 已提交
285 286 287 288 289
    const std::string file_path ="path/to/opencl_cache_file";
    std::shared_ptr<KVStorageFactory> storage_factory(
        new FileStorageFactory(file_path));
    ConfigKVStorageFactory(storage_factory);

L
liutuo 已提交
290
    // 2. Declare the device type (must be same with ``runtime`` in configuration file)
L
liutuo 已提交
291 292 293 294 295 296 297 298 299
    DeviceType device_type = DeviceType::GPU;

    // 3. Define the input and output tensor names.
    std::vector<std::string> input_names = {...};
    std::vector<std::string> output_names = {...};

    // 4. Create MaceEngine instance
    std::shared_ptr<mace::MaceEngine> engine;
    MaceStatus create_engine_status;
L
liutuo 已提交
300 301

    // Create Engine from model file
L
liutuo 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    create_engine_status =
        CreateMaceEngineFromProto(model_pb_data,
                                  model_data_file.c_str(),
                                  input_names,
                                  output_names,
                                  device_type,
                                  &engine);
    if (create_engine_status != MaceStatus::MACE_SUCCESS) {
      // Report error
    }

    // 5. Create Input and Output tensor buffers
    std::map<std::string, mace::MaceTensor> inputs;
    std::map<std::string, mace::MaceTensor> outputs;
    for (size_t i = 0; i < input_count; ++i) {
      // Allocate input and output
      int64_t input_size =
          std::accumulate(input_shapes[i].begin(), input_shapes[i].end(), 1,
                          std::multiplies<int64_t>());
      auto buffer_in = std::shared_ptr<float>(new float[input_size],
                                              std::default_delete<float[]>());
      // Load input here
      // ...

      inputs[input_names[i]] = mace::MaceTensor(input_shapes[i], buffer_in);
    }

    for (size_t i = 0; i < output_count; ++i) {
      int64_t output_size =
          std::accumulate(output_shapes[i].begin(), output_shapes[i].end(), 1,
                          std::multiplies<int64_t>());
      auto buffer_out = std::shared_ptr<float>(new float[output_size],
                                               std::default_delete<float[]>());
      outputs[output_names[i]] = mace::MaceTensor(output_shapes[i], buffer_out);
    }

    // 6. Run the model
L
liutuo 已提交
339
    MaceStatus status = engine.Run(inputs, &outputs);
L
liutuo 已提交
340

L
liutuo 已提交
341
More details are in :doc:`advanced_usage`.